Application Android et IOS pour l'amicale des élèves https://play.google.com/store/apps/details?id=fr.amicaleinsat.application
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ProxiwashScreen.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. // @flow
  2. import * as React from 'react';
  3. import {Alert, View} from 'react-native';
  4. import i18n from "i18n-js";
  5. import WebSectionList from "../../components/Screens/WebSectionList";
  6. import * as Notifications from "../../utils/Notifications";
  7. import AsyncStorageManager from "../../managers/AsyncStorageManager";
  8. import {Avatar, Button, Card, Text, withTheme} from 'react-native-paper';
  9. import ProxiwashListItem from "../../components/Lists/Proxiwash/ProxiwashListItem";
  10. import ProxiwashConstants from "../../constants/ProxiwashConstants";
  11. import CustomModal from "../../components/Overrides/CustomModal";
  12. import AprilFoolsManager from "../../managers/AprilFoolsManager";
  13. import MaterialHeaderButtons, {Item} from "../../components/Overrides/CustomHeaderButton";
  14. import ProxiwashSectionHeader from "../../components/Lists/Proxiwash/ProxiwashSectionHeader";
  15. import type {CustomTheme} from "../../managers/ThemeManager";
  16. import {StackNavigationProp} from "@react-navigation/stack";
  17. import {getCleanedMachineWatched, getMachineEndDate, isMachineWatched} from "../../utils/Proxiwash";
  18. import {Modalize} from "react-native-modalize";
  19. import {MASCOT_STYLE} from "../../components/Mascot/Mascot";
  20. import MascotPopup from "../../components/Mascot/MascotPopup";
  21. const DATA_URL = "https://etud.insa-toulouse.fr/~amicale_app/v2/washinsa/washinsa_data.json";
  22. let modalStateStrings = {};
  23. const REFRESH_TIME = 1000 * 10; // Refresh every 10 seconds
  24. const LIST_ITEM_HEIGHT = 64;
  25. export type Machine = {
  26. number: string,
  27. state: string,
  28. startTime: string,
  29. endTime: string,
  30. donePercent: string,
  31. remainingTime: string,
  32. program: string,
  33. }
  34. type Props = {
  35. navigation: StackNavigationProp,
  36. theme: CustomTheme,
  37. }
  38. type State = {
  39. refreshing: boolean,
  40. modalCurrentDisplayItem: React.Node,
  41. machinesWatched: Array<Machine>,
  42. mascotDialogVisible: boolean,
  43. };
  44. /**
  45. * Class defining the app's proxiwash screen. This screen shows information about washing machines and
  46. * dryers, taken from a scrapper reading proxiwash website
  47. */
  48. class ProxiwashScreen extends React.Component<Props, State> {
  49. modalRef: null | Modalize;
  50. fetchedData: {
  51. dryers: Array<Machine>,
  52. washers: Array<Machine>,
  53. };
  54. state = {
  55. refreshing: false,
  56. modalCurrentDisplayItem: null,
  57. machinesWatched: AsyncStorageManager.getObject(AsyncStorageManager.PREFERENCES.proxiwashWatchedMachines.key),
  58. mascotDialogVisible: AsyncStorageManager.getBool(AsyncStorageManager.PREFERENCES.proxiwashShowBanner.key),
  59. };
  60. /**
  61. * Creates machine state parameters using current theme and translations
  62. */
  63. constructor(props) {
  64. super(props);
  65. modalStateStrings[ProxiwashConstants.machineStates.AVAILABLE] = i18n.t('screens.proxiwash.modal.ready');
  66. modalStateStrings[ProxiwashConstants.machineStates.RUNNING] = i18n.t('screens.proxiwash.modal.running');
  67. modalStateStrings[ProxiwashConstants.machineStates.RUNNING_NOT_STARTED] = i18n.t('screens.proxiwash.modal.runningNotStarted');
  68. modalStateStrings[ProxiwashConstants.machineStates.FINISHED] = i18n.t('screens.proxiwash.modal.finished');
  69. modalStateStrings[ProxiwashConstants.machineStates.UNAVAILABLE] = i18n.t('screens.proxiwash.modal.broken');
  70. modalStateStrings[ProxiwashConstants.machineStates.ERROR] = i18n.t('screens.proxiwash.modal.error');
  71. modalStateStrings[ProxiwashConstants.machineStates.UNKNOWN] = i18n.t('screens.proxiwash.modal.unknown');
  72. }
  73. /**
  74. * Callback used when closing the banner.
  75. * This hides the banner and saves to preferences to prevent it from reopening
  76. */
  77. onHideMascotDialog = () => {
  78. this.setState({mascotDialogVisible: false});
  79. AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.proxiwashShowBanner.key, false);
  80. };
  81. /**
  82. * Setup notification channel for android and add listeners to detect notifications fired
  83. */
  84. componentDidMount() {
  85. this.props.navigation.setOptions({
  86. headerRight: () =>
  87. <MaterialHeaderButtons>
  88. <Item title="information" iconName="information" onPress={this.onAboutPress}/>
  89. </MaterialHeaderButtons>,
  90. });
  91. }
  92. /**
  93. * Callback used when pressing the about button.
  94. * This will open the ProxiwashAboutScreen.
  95. */
  96. onAboutPress = () => this.props.navigation.navigate('proxiwash-about');
  97. /**
  98. * Extracts the key for the given item
  99. *
  100. * @param item The item to extract the key from
  101. * @return {*} The extracted key
  102. */
  103. getKeyExtractor = (item: Machine) => item.number;
  104. /**
  105. * Setups notifications for the machine with the given ID.
  106. * One notification will be sent at the end of the program.
  107. * Another will be send a few minutes before the end, based on the value of reminderNotifTime
  108. *
  109. * @param machine The machine to watch
  110. */
  111. setupNotifications(machine: Machine) {
  112. if (!isMachineWatched(machine, this.state.machinesWatched)) {
  113. Notifications.setupMachineNotification(machine.number, true, getMachineEndDate(machine))
  114. .then(() => {
  115. this.saveNotificationToState(machine);
  116. })
  117. .catch(() => {
  118. this.showNotificationsDisabledWarning();
  119. });
  120. } else {
  121. Notifications.setupMachineNotification(machine.number, false, null)
  122. .then(() => {
  123. this.removeNotificationFromState(machine);
  124. });
  125. }
  126. }
  127. /**
  128. * Shows a warning telling the user notifications are disabled for the app
  129. */
  130. showNotificationsDisabledWarning() {
  131. Alert.alert(
  132. i18n.t("screens.proxiwash.modal.notificationErrorTitle"),
  133. i18n.t("screens.proxiwash.modal.notificationErrorDescription"),
  134. );
  135. }
  136. /**
  137. * Adds the given notifications associated to a machine ID to the watchlist, and saves the array to the preferences
  138. *
  139. * @param machine
  140. */
  141. saveNotificationToState(machine: Machine) {
  142. let data = this.state.machinesWatched;
  143. data.push(machine);
  144. this.saveNewWatchedList(data);
  145. }
  146. /**
  147. * Removes the given index from the watchlist array and saves it to preferences
  148. *
  149. * @param machine
  150. */
  151. removeNotificationFromState(machine: Machine) {
  152. let data = this.state.machinesWatched;
  153. for (let i = 0; i < data.length; i++) {
  154. if (data[i].number === machine.number && data[i].endTime === machine.endTime) {
  155. data.splice(i, 1);
  156. break;
  157. }
  158. }
  159. this.saveNewWatchedList(data);
  160. }
  161. saveNewWatchedList(list: Array<Machine>) {
  162. this.setState({machinesWatched: list});
  163. AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.proxiwashWatchedMachines.key, list);
  164. }
  165. /**
  166. * Creates the dataset to be used by the flatlist
  167. *
  168. * @param fetchedData
  169. * @return {*}
  170. */
  171. createDataset = (fetchedData: Object) => {
  172. let data = fetchedData;
  173. if (AprilFoolsManager.getInstance().isAprilFoolsEnabled()) {
  174. data = JSON.parse(JSON.stringify(fetchedData)); // Deep copy
  175. AprilFoolsManager.getNewProxiwashDryerOrderedList(data.dryers);
  176. AprilFoolsManager.getNewProxiwashWasherOrderedList(data.washers);
  177. }
  178. this.fetchedData = data;
  179. this.state.machinesWatched =
  180. getCleanedMachineWatched(this.state.machinesWatched, [...data.dryers, ...data.washers]);
  181. return [
  182. {
  183. title: i18n.t('screens.proxiwash.dryers'),
  184. icon: 'tumble-dryer',
  185. data: data.dryers === undefined ? [] : data.dryers,
  186. keyExtractor: this.getKeyExtractor
  187. },
  188. {
  189. title: i18n.t('screens.proxiwash.washers'),
  190. icon: 'washing-machine',
  191. data: data.washers === undefined ? [] : data.washers,
  192. keyExtractor: this.getKeyExtractor
  193. },
  194. ];
  195. };
  196. /**
  197. * Shows a modal for the given item
  198. *
  199. * @param title The title to use
  200. * @param item The item to display information for in the modal
  201. * @param isDryer True if the given item is a dryer
  202. */
  203. showModal = (title: string, item: Object, isDryer: boolean) => {
  204. this.setState({
  205. modalCurrentDisplayItem: this.getModalContent(title, item, isDryer)
  206. });
  207. if (this.modalRef) {
  208. this.modalRef.open();
  209. }
  210. };
  211. /**
  212. * Callback used when the user clicks on enable notifications for a machine
  213. *
  214. * @param machine The machine to set notifications for
  215. */
  216. onSetupNotificationsPress(machine: Machine) {
  217. if (this.modalRef) {
  218. this.modalRef.close();
  219. }
  220. this.setupNotifications(machine);
  221. }
  222. /**
  223. * Generates the modal content.
  224. * This shows information for the given machine.
  225. *
  226. * @param title The title to use
  227. * @param item The item to display information for in the modal
  228. * @param isDryer True if the given item is a dryer
  229. * @return {*}
  230. */
  231. getModalContent(title: string, item: Machine, isDryer: boolean) {
  232. let button = {
  233. text: i18n.t("screens.proxiwash.modal.ok"),
  234. icon: '',
  235. onPress: undefined
  236. };
  237. let message = modalStateStrings[item.state];
  238. const onPress = this.onSetupNotificationsPress.bind(this, item);
  239. if (item.state === ProxiwashConstants.machineStates.RUNNING) {
  240. let remainingTime = parseInt(item.remainingTime)
  241. if (remainingTime < 0)
  242. remainingTime = 0;
  243. button =
  244. {
  245. text: isMachineWatched(item, this.state.machinesWatched) ?
  246. i18n.t("screens.proxiwash.modal.disableNotifications") :
  247. i18n.t("screens.proxiwash.modal.enableNotifications"),
  248. icon: '',
  249. onPress: onPress
  250. }
  251. ;
  252. message = i18n.t('screens.proxiwash.modal.running',
  253. {
  254. start: item.startTime,
  255. end: item.endTime,
  256. remaining: remainingTime,
  257. program: item.program
  258. });
  259. } else if (item.state === ProxiwashConstants.machineStates.AVAILABLE) {
  260. if (isDryer)
  261. message += '\n' + i18n.t('screens.proxiwash.dryersTariff');
  262. else
  263. message += '\n' + i18n.t('screens.proxiwash.washersTariff');
  264. }
  265. return (
  266. <View style={{
  267. flex: 1,
  268. padding: 20
  269. }}>
  270. <Card.Title
  271. title={title}
  272. left={() => <Avatar.Icon
  273. icon={isDryer ? 'tumble-dryer' : 'washing-machine'}
  274. color={this.props.theme.colors.text}
  275. style={{backgroundColor: 'transparent'}}/>}
  276. />
  277. <Card.Content>
  278. <Text>{message}</Text>
  279. </Card.Content>
  280. {button.onPress !== undefined ?
  281. <Card.Actions>
  282. <Button
  283. icon={button.icon}
  284. mode="contained"
  285. onPress={button.onPress}
  286. style={{marginLeft: 'auto', marginRight: 'auto'}}
  287. >
  288. {button.text}
  289. </Button>
  290. </Card.Actions> : null}
  291. </View>
  292. );
  293. }
  294. /**
  295. * Callback used when receiving modal ref
  296. *
  297. * @param ref
  298. */
  299. onModalRef = (ref: Object) => {
  300. this.modalRef = ref;
  301. };
  302. /**
  303. * Gets the number of machines available
  304. *
  305. * @param isDryer True if we are only checking for dryer, false for washers
  306. * @return {number} The number of machines available
  307. */
  308. getMachineAvailableNumber(isDryer: boolean) {
  309. let data;
  310. if (isDryer)
  311. data = this.fetchedData.dryers;
  312. else
  313. data = this.fetchedData.washers;
  314. let count = 0;
  315. for (let i = 0; i < data.length; i++) {
  316. if (data[i].state === ProxiwashConstants.machineStates.AVAILABLE)
  317. count += 1;
  318. }
  319. return count;
  320. }
  321. /**
  322. * Gets the section render item
  323. *
  324. * @param section The section to render
  325. * @return {*}
  326. */
  327. getRenderSectionHeader = ({section}: Object) => {
  328. const isDryer = section.title === i18n.t('screens.proxiwash.dryers');
  329. const nbAvailable = this.getMachineAvailableNumber(isDryer);
  330. return (
  331. <ProxiwashSectionHeader
  332. title={section.title}
  333. nbAvailable={nbAvailable}
  334. isDryer={isDryer}/>
  335. );
  336. };
  337. /**
  338. * Gets the list item to be rendered
  339. *
  340. * @param item The object containing the item's FetchedData
  341. * @param section The object describing the current SectionList section
  342. * @returns {React.Node}
  343. */
  344. getRenderItem = ({item, section}: Object) => {
  345. const isDryer = section.title === i18n.t('screens.proxiwash.dryers');
  346. return (
  347. <ProxiwashListItem
  348. item={item}
  349. onPress={this.showModal}
  350. isWatched={isMachineWatched(item, this.state.machinesWatched)}
  351. isDryer={isDryer}
  352. height={LIST_ITEM_HEIGHT}
  353. />
  354. );
  355. };
  356. render() {
  357. const nav = this.props.navigation;
  358. return (
  359. <View
  360. style={{flex: 1}}
  361. >
  362. <View style={{
  363. position: "absolute",
  364. width: "100%",
  365. height: "100%",
  366. }}>
  367. <WebSectionList
  368. createDataset={this.createDataset}
  369. navigation={nav}
  370. fetchUrl={DATA_URL}
  371. renderItem={this.getRenderItem}
  372. renderSectionHeader={this.getRenderSectionHeader}
  373. autoRefreshTime={REFRESH_TIME}
  374. refreshOnFocus={true}
  375. updateData={this.state.machinesWatched.length}/>
  376. </View>
  377. <MascotPopup
  378. visible={this.state.mascotDialogVisible}
  379. title={i18n.t("screens.proxiwash.mascotDialog.title")}
  380. message={i18n.t("screens.proxiwash.mascotDialog.message")}
  381. icon={"information"}
  382. buttons={{
  383. action: null,
  384. cancel: {
  385. message: i18n.t("screens.proxiwash.mascotDialog.ok"),
  386. icon: "check",
  387. onPress: this.onHideMascotDialog,
  388. }
  389. }}
  390. emotion={MASCOT_STYLE.NORMAL}
  391. />
  392. <CustomModal onRef={this.onModalRef}>
  393. {this.state.modalCurrentDisplayItem}
  394. </CustomModal>
  395. </View>
  396. );
  397. }
  398. }
  399. export default withTheme(ProxiwashScreen);