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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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: JSON.parse(AsyncStorageManager.getInstance().preferences.proxiwashWatchedMachines.current),
  58. mascotDialogVisible: AsyncStorageManager.getInstance().preferences.proxiwashShowBanner.current === "1",
  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.getInstance().savePref(
  80. AsyncStorageManager.getInstance().preferences.proxiwashShowBanner.key,
  81. '0'
  82. );
  83. };
  84. /**
  85. * Setup notification channel for android and add listeners to detect notifications fired
  86. */
  87. componentDidMount() {
  88. this.props.navigation.setOptions({
  89. headerRight: () =>
  90. <MaterialHeaderButtons>
  91. <Item title="information" iconName="information" onPress={this.onAboutPress}/>
  92. </MaterialHeaderButtons>,
  93. });
  94. }
  95. /**
  96. * Callback used when pressing the about button.
  97. * This will open the ProxiwashAboutScreen.
  98. */
  99. onAboutPress = () => this.props.navigation.navigate('proxiwash-about');
  100. /**
  101. * Extracts the key for the given item
  102. *
  103. * @param item The item to extract the key from
  104. * @return {*} The extracted key
  105. */
  106. getKeyExtractor = (item: Machine) => item.number;
  107. /**
  108. * Setups notifications for the machine with the given ID.
  109. * One notification will be sent at the end of the program.
  110. * Another will be send a few minutes before the end, based on the value of reminderNotifTime
  111. *
  112. * @param machine The machine to watch
  113. */
  114. setupNotifications(machine: Machine) {
  115. if (!isMachineWatched(machine, this.state.machinesWatched)) {
  116. Notifications.setupMachineNotification(machine.number, true, getMachineEndDate(machine))
  117. .then(() => {
  118. this.saveNotificationToState(machine);
  119. })
  120. .catch(() => {
  121. this.showNotificationsDisabledWarning();
  122. });
  123. } else {
  124. Notifications.setupMachineNotification(machine.number, false, null)
  125. .then(() => {
  126. this.removeNotificationFromState(machine);
  127. });
  128. }
  129. }
  130. /**
  131. * Shows a warning telling the user notifications are disabled for the app
  132. */
  133. showNotificationsDisabledWarning() {
  134. Alert.alert(
  135. i18n.t("screens.proxiwash.modal.notificationErrorTitle"),
  136. i18n.t("screens.proxiwash.modal.notificationErrorDescription"),
  137. );
  138. }
  139. /**
  140. * Adds the given notifications associated to a machine ID to the watchlist, and saves the array to the preferences
  141. *
  142. * @param machine
  143. */
  144. saveNotificationToState(machine: Machine) {
  145. let data = this.state.machinesWatched;
  146. data.push(machine);
  147. this.saveNewWatchedList(data);
  148. }
  149. /**
  150. * Removes the given index from the watchlist array and saves it to preferences
  151. *
  152. * @param machine
  153. */
  154. removeNotificationFromState(machine: Machine) {
  155. let data = this.state.machinesWatched;
  156. for (let i = 0; i < data.length; i++) {
  157. if (data[i].number === machine.number && data[i].endTime === machine.endTime) {
  158. data.splice(i, 1);
  159. break;
  160. }
  161. }
  162. this.saveNewWatchedList(data);
  163. }
  164. saveNewWatchedList(list: Array<Machine>) {
  165. this.setState({machinesWatched: list});
  166. AsyncStorageManager.getInstance().savePref(
  167. AsyncStorageManager.getInstance().preferences.proxiwashWatchedMachines.key,
  168. JSON.stringify(list),
  169. );
  170. }
  171. /**
  172. * Creates the dataset to be used by the flatlist
  173. *
  174. * @param fetchedData
  175. * @return {*}
  176. */
  177. createDataset = (fetchedData: Object) => {
  178. let data = fetchedData;
  179. if (AprilFoolsManager.getInstance().isAprilFoolsEnabled()) {
  180. data = JSON.parse(JSON.stringify(fetchedData)); // Deep copy
  181. AprilFoolsManager.getNewProxiwashDryerOrderedList(data.dryers);
  182. AprilFoolsManager.getNewProxiwashWasherOrderedList(data.washers);
  183. }
  184. this.fetchedData = data;
  185. this.state.machinesWatched =
  186. getCleanedMachineWatched(this.state.machinesWatched, [...data.dryers, ...data.washers]);
  187. return [
  188. {
  189. title: i18n.t('screens.proxiwash.dryers'),
  190. icon: 'tumble-dryer',
  191. data: data.dryers === undefined ? [] : data.dryers,
  192. keyExtractor: this.getKeyExtractor
  193. },
  194. {
  195. title: i18n.t('screens.proxiwash.washers'),
  196. icon: 'washing-machine',
  197. data: data.washers === undefined ? [] : data.washers,
  198. keyExtractor: this.getKeyExtractor
  199. },
  200. ];
  201. };
  202. /**
  203. * Shows a modal for the given item
  204. *
  205. * @param title The title to use
  206. * @param item The item to display information for in the modal
  207. * @param isDryer True if the given item is a dryer
  208. */
  209. showModal = (title: string, item: Object, isDryer: boolean) => {
  210. this.setState({
  211. modalCurrentDisplayItem: this.getModalContent(title, item, isDryer)
  212. });
  213. if (this.modalRef) {
  214. this.modalRef.open();
  215. }
  216. };
  217. /**
  218. * Callback used when the user clicks on enable notifications for a machine
  219. *
  220. * @param machine The machine to set notifications for
  221. */
  222. onSetupNotificationsPress(machine: Machine) {
  223. if (this.modalRef) {
  224. this.modalRef.close();
  225. }
  226. this.setupNotifications(machine);
  227. }
  228. /**
  229. * Generates the modal content.
  230. * This shows information for the given machine.
  231. *
  232. * @param title The title to use
  233. * @param item The item to display information for in the modal
  234. * @param isDryer True if the given item is a dryer
  235. * @return {*}
  236. */
  237. getModalContent(title: string, item: Machine, isDryer: boolean) {
  238. let button = {
  239. text: i18n.t("screens.proxiwash.modal.ok"),
  240. icon: '',
  241. onPress: undefined
  242. };
  243. let message = modalStateStrings[item.state];
  244. const onPress = this.onSetupNotificationsPress.bind(this, item);
  245. if (item.state === ProxiwashConstants.machineStates.RUNNING) {
  246. let remainingTime = parseInt(item.remainingTime)
  247. if (remainingTime < 0)
  248. remainingTime = 0;
  249. button =
  250. {
  251. text: isMachineWatched(item, this.state.machinesWatched) ?
  252. i18n.t("screens.proxiwash.modal.disableNotifications") :
  253. i18n.t("screens.proxiwash.modal.enableNotifications"),
  254. icon: '',
  255. onPress: onPress
  256. }
  257. ;
  258. message = i18n.t('screens.proxiwash.modal.running',
  259. {
  260. start: item.startTime,
  261. end: item.endTime,
  262. remaining: remainingTime,
  263. program: item.program
  264. });
  265. } else if (item.state === ProxiwashConstants.machineStates.AVAILABLE) {
  266. if (isDryer)
  267. message += '\n' + i18n.t('screens.proxiwash.dryersTariff');
  268. else
  269. message += '\n' + i18n.t('screens.proxiwash.washersTariff');
  270. }
  271. return (
  272. <View style={{
  273. flex: 1,
  274. padding: 20
  275. }}>
  276. <Card.Title
  277. title={title}
  278. left={() => <Avatar.Icon
  279. icon={isDryer ? 'tumble-dryer' : 'washing-machine'}
  280. color={this.props.theme.colors.text}
  281. style={{backgroundColor: 'transparent'}}/>}
  282. />
  283. <Card.Content>
  284. <Text>{message}</Text>
  285. </Card.Content>
  286. {button.onPress !== undefined ?
  287. <Card.Actions>
  288. <Button
  289. icon={button.icon}
  290. mode="contained"
  291. onPress={button.onPress}
  292. style={{marginLeft: 'auto', marginRight: 'auto'}}
  293. >
  294. {button.text}
  295. </Button>
  296. </Card.Actions> : null}
  297. </View>
  298. );
  299. }
  300. /**
  301. * Callback used when receiving modal ref
  302. *
  303. * @param ref
  304. */
  305. onModalRef = (ref: Object) => {
  306. this.modalRef = ref;
  307. };
  308. /**
  309. * Gets the number of machines available
  310. *
  311. * @param isDryer True if we are only checking for dryer, false for washers
  312. * @return {number} The number of machines available
  313. */
  314. getMachineAvailableNumber(isDryer: boolean) {
  315. let data;
  316. if (isDryer)
  317. data = this.fetchedData.dryers;
  318. else
  319. data = this.fetchedData.washers;
  320. let count = 0;
  321. for (let i = 0; i < data.length; i++) {
  322. if (data[i].state === ProxiwashConstants.machineStates.AVAILABLE)
  323. count += 1;
  324. }
  325. return count;
  326. }
  327. /**
  328. * Gets the section render item
  329. *
  330. * @param section The section to render
  331. * @return {*}
  332. */
  333. getRenderSectionHeader = ({section}: Object) => {
  334. const isDryer = section.title === i18n.t('screens.proxiwash.dryers');
  335. const nbAvailable = this.getMachineAvailableNumber(isDryer);
  336. return (
  337. <ProxiwashSectionHeader
  338. title={section.title}
  339. nbAvailable={nbAvailable}
  340. isDryer={isDryer}/>
  341. );
  342. };
  343. /**
  344. * Gets the list item to be rendered
  345. *
  346. * @param item The object containing the item's FetchedData
  347. * @param section The object describing the current SectionList section
  348. * @returns {React.Node}
  349. */
  350. getRenderItem = ({item, section}: Object) => {
  351. const isDryer = section.title === i18n.t('screens.proxiwash.dryers');
  352. return (
  353. <ProxiwashListItem
  354. item={item}
  355. onPress={this.showModal}
  356. isWatched={isMachineWatched(item, this.state.machinesWatched)}
  357. isDryer={isDryer}
  358. height={LIST_ITEM_HEIGHT}
  359. />
  360. );
  361. };
  362. render() {
  363. const nav = this.props.navigation;
  364. return (
  365. <View
  366. style={{flex: 1}}
  367. >
  368. <View style={{
  369. position: "absolute",
  370. width: "100%",
  371. height: "100%",
  372. }}>
  373. <WebSectionList
  374. createDataset={this.createDataset}
  375. navigation={nav}
  376. fetchUrl={DATA_URL}
  377. renderItem={this.getRenderItem}
  378. renderSectionHeader={this.getRenderSectionHeader}
  379. autoRefreshTime={REFRESH_TIME}
  380. refreshOnFocus={true}
  381. updateData={this.state.machinesWatched.length}/>
  382. </View>
  383. <MascotPopup
  384. visible={this.state.mascotDialogVisible}
  385. title={i18n.t("screens.proxiwash.mascotDialog.title")}
  386. message={i18n.t("screens.proxiwash.mascotDialog.message")}
  387. icon={"information"}
  388. buttons={{
  389. action: null,
  390. cancel: {
  391. message: i18n.t("screens.proxiwash.mascotDialog.ok"),
  392. icon: "check",
  393. onPress: this.onHideMascotDialog,
  394. }
  395. }}
  396. emotion={MASCOT_STYLE.NORMAL}
  397. />
  398. <CustomModal onRef={this.onModalRef}>
  399. {this.state.modalCurrentDisplayItem}
  400. </CustomModal>
  401. </View>
  402. );
  403. }
  404. }
  405. export default withTheme(ProxiwashScreen);