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.tsx 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. /*
  2. * Copyright (c) 2019 - 2020 Arnaud Vergnet.
  3. *
  4. * This file is part of Campus INSAT.
  5. *
  6. * Campus INSAT is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Campus INSAT is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Campus INSAT. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. import React, { useLayoutEffect, useRef, useState } from 'react';
  20. import {
  21. Linking,
  22. SectionListData,
  23. SectionListRenderItemInfo,
  24. StyleSheet,
  25. View,
  26. } from 'react-native';
  27. import i18n from 'i18n-js';
  28. import { Avatar, Button, Card, Text, useTheme } from 'react-native-paper';
  29. import { Modalize } from 'react-native-modalize';
  30. import WebSectionList from '../../components/Screens/WebSectionList';
  31. import ProxiwashListItem from '../../components/Lists/Proxiwash/ProxiwashListItem';
  32. import ProxiwashConstants, {
  33. MachineStates,
  34. } from '../../constants/ProxiwashConstants';
  35. import CustomModal from '../../components/Overrides/CustomModal';
  36. import AprilFoolsManager from '../../managers/AprilFoolsManager';
  37. import MaterialHeaderButtons, {
  38. Item,
  39. } from '../../components/Overrides/CustomHeaderButton';
  40. import ProxiwashSectionHeader from '../../components/Lists/Proxiwash/ProxiwashSectionHeader';
  41. import {
  42. getCleanedMachineWatched,
  43. getMachineEndDate,
  44. isMachineWatched,
  45. } from '../../utils/Proxiwash';
  46. import { MASCOT_STYLE } from '../../components/Mascot/Mascot';
  47. import MascotPopup from '../../components/Mascot/MascotPopup';
  48. import type { SectionListDataType } from '../../components/Screens/WebSectionList';
  49. import type { LaundromatType } from './ProxiwashAboutScreen';
  50. import GENERAL_STYLES from '../../constants/Styles';
  51. import { readData } from '../../utils/WebData';
  52. import { useNavigation } from '@react-navigation/core';
  53. import { setupMachineNotification } from '../../utils/Notifications';
  54. import ProxiwashListHeader from '../../components/Lists/Proxiwash/ProxiwashListHeader';
  55. import {
  56. getPreferenceNumber,
  57. getPreferenceObject,
  58. getPreferenceString,
  59. ProxiwashPreferenceKeys,
  60. } from '../../utils/asyncStorage';
  61. import { useProxiwashPreferences } from '../../context/preferencesContext';
  62. import { useSubsequentEffect } from '../../utils/customHooks';
  63. const REFRESH_TIME = 1000 * 10; // Refresh every 10 seconds
  64. const LIST_ITEM_HEIGHT = 64;
  65. export type ProxiwashMachineType = {
  66. number: string;
  67. state: MachineStates;
  68. maxWeight: number;
  69. startTime: string;
  70. endTime: string;
  71. donePercent: string;
  72. remainingTime: string;
  73. program: string;
  74. };
  75. export type ProxiwashInfoType = {
  76. message: string;
  77. last_checked: number;
  78. };
  79. type FetchedDataType = {
  80. info: ProxiwashInfoType;
  81. dryers: Array<ProxiwashMachineType>;
  82. washers: Array<ProxiwashMachineType>;
  83. };
  84. const styles = StyleSheet.create({
  85. modalContainer: {
  86. flex: 1,
  87. padding: 20,
  88. },
  89. icon: {
  90. backgroundColor: 'transparent',
  91. },
  92. container: {
  93. position: 'absolute',
  94. width: '100%',
  95. height: '100%',
  96. },
  97. });
  98. function ProxiwashScreen() {
  99. const navigation = useNavigation();
  100. const theme = useTheme();
  101. const { preferences, updatePreferences } = useProxiwashPreferences();
  102. const [modalCurrentDisplayItem, setModalCurrentDisplayItem] =
  103. useState<React.ReactElement | null>(null);
  104. const reminder = getPreferenceNumber(
  105. ProxiwashPreferenceKeys.proxiwashNotifications,
  106. preferences
  107. );
  108. const [refresh, setRefresh] = useState(false);
  109. const getMachinesWatched = () => {
  110. const data = getPreferenceObject(
  111. ProxiwashPreferenceKeys.proxiwashWatchedMachines,
  112. preferences
  113. ) as Array<ProxiwashMachineType>;
  114. return data ? (data as Array<ProxiwashMachineType>) : [];
  115. };
  116. const getSelectedWash = () => {
  117. const data = getPreferenceString(
  118. ProxiwashPreferenceKeys.selectedWash,
  119. preferences
  120. );
  121. if (data !== 'washinsa' && data !== 'tripodeB') {
  122. return 'washinsa';
  123. } else {
  124. return data;
  125. }
  126. };
  127. const machinesWatched: Array<ProxiwashMachineType> = getMachinesWatched();
  128. const selectedWash: 'washinsa' | 'tripodeB' = getSelectedWash();
  129. useSubsequentEffect(() => {
  130. // Refresh the list when the selected wash changes
  131. setRefresh(true);
  132. }, [selectedWash]);
  133. const modalStateStrings: { [key in MachineStates]: string } = {
  134. [MachineStates.AVAILABLE]: i18n.t('screens.proxiwash.modal.ready'),
  135. [MachineStates.RUNNING]: i18n.t('screens.proxiwash.modal.running'),
  136. [MachineStates.RUNNING_NOT_STARTED]: i18n.t(
  137. 'screens.proxiwash.modal.runningNotStarted'
  138. ),
  139. [MachineStates.FINISHED]: i18n.t('screens.proxiwash.modal.finished'),
  140. [MachineStates.UNAVAILABLE]: i18n.t('screens.proxiwash.modal.broken'),
  141. [MachineStates.ERROR]: i18n.t('screens.proxiwash.modal.error'),
  142. [MachineStates.UNKNOWN]: i18n.t('screens.proxiwash.modal.unknown'),
  143. };
  144. const modalRef = useRef<Modalize>(null);
  145. useLayoutEffect(() => {
  146. navigation.setOptions({
  147. headerRight: () => (
  148. <MaterialHeaderButtons>
  149. <Item
  150. title={'web'}
  151. iconName={'open-in-new'}
  152. onPress={() =>
  153. Linking.openURL(ProxiwashConstants[selectedWash].webPageUrl)
  154. }
  155. />
  156. <Item
  157. title={'information'}
  158. iconName={'information'}
  159. onPress={() => navigation.navigate('proxiwash-about')}
  160. />
  161. </MaterialHeaderButtons>
  162. ),
  163. });
  164. }, [navigation, selectedWash]);
  165. /**
  166. * Callback used when the user clicks on enable notifications for a machine
  167. *
  168. * @param machine The machine to set notifications for
  169. */
  170. const onSetupNotificationsPress = (machine: ProxiwashMachineType) => {
  171. if (modalRef.current) {
  172. modalRef.current.close();
  173. }
  174. setupNotifications(machine);
  175. };
  176. /**
  177. * Generates the modal content.
  178. * This shows information for the given machine.
  179. *
  180. * @param title The title to use
  181. * @param item The item to display information for in the modal
  182. * @param isDryer True if the given item is a dryer
  183. * @return {*}
  184. */
  185. const getModalContent = (
  186. title: string,
  187. item: ProxiwashMachineType,
  188. isDryer: boolean
  189. ) => {
  190. let button: { text: string; icon: string; onPress: () => void } | undefined;
  191. let message = modalStateStrings[item.state];
  192. const onPress = () => onSetupNotificationsPress(item);
  193. if (item.state === MachineStates.RUNNING) {
  194. let remainingTime = parseInt(item.remainingTime, 10);
  195. if (remainingTime < 0) {
  196. remainingTime = 0;
  197. }
  198. button = {
  199. text: isMachineWatched(item, machinesWatched)
  200. ? i18n.t('screens.proxiwash.modal.disableNotifications')
  201. : i18n.t('screens.proxiwash.modal.enableNotifications'),
  202. icon: '',
  203. onPress: onPress,
  204. };
  205. message = i18n.t('screens.proxiwash.modal.running', {
  206. start: item.startTime,
  207. end: item.endTime,
  208. remaining: remainingTime,
  209. program: item.program,
  210. });
  211. }
  212. return (
  213. <View style={styles.modalContainer}>
  214. <Card.Title
  215. title={title}
  216. left={() => (
  217. <Avatar.Icon
  218. icon={isDryer ? 'tumble-dryer' : 'washing-machine'}
  219. color={theme.colors.text}
  220. style={styles.icon}
  221. />
  222. )}
  223. />
  224. <Card.Content>
  225. <Text>{message}</Text>
  226. </Card.Content>
  227. {button ? (
  228. <Card.Actions>
  229. <Button
  230. icon={button.icon}
  231. mode="contained"
  232. onPress={button.onPress}
  233. style={GENERAL_STYLES.centerHorizontal}
  234. >
  235. {button.text}
  236. </Button>
  237. </Card.Actions>
  238. ) : null}
  239. </View>
  240. );
  241. };
  242. /**
  243. * Gets the section render item
  244. *
  245. * @param section The section to render
  246. * @return {*}
  247. */
  248. const getRenderSectionHeader = ({
  249. section,
  250. }: {
  251. section: SectionListData<ProxiwashMachineType>;
  252. }) => {
  253. const isDryer = section.title === i18n.t('screens.proxiwash.dryers');
  254. const nbAvailable = getMachineAvailableNumber(section.data);
  255. return (
  256. <ProxiwashSectionHeader
  257. title={section.title}
  258. nbAvailable={nbAvailable}
  259. isDryer={isDryer}
  260. />
  261. );
  262. };
  263. /**
  264. * Gets the list item to be rendered
  265. *
  266. * @param item The object containing the item's FetchedData
  267. * @param section The object describing the current SectionList section
  268. * @returns {React.Node}
  269. */
  270. const getRenderItem = (
  271. data: SectionListRenderItemInfo<ProxiwashMachineType>
  272. ) => {
  273. const isDryer = data.section.title === i18n.t('screens.proxiwash.dryers');
  274. return (
  275. <ProxiwashListItem
  276. item={data.item}
  277. onPress={showModal}
  278. isWatched={isMachineWatched(data.item, machinesWatched)}
  279. isDryer={isDryer}
  280. height={LIST_ITEM_HEIGHT}
  281. />
  282. );
  283. };
  284. /**
  285. * Extracts the key for the given item
  286. *
  287. * @param item The item to extract the key from
  288. * @return {*} The extracted key
  289. */
  290. const getKeyExtractor = (item: ProxiwashMachineType): string => item.number;
  291. /**
  292. * Setups notifications for the machine with the given ID.
  293. * One notification will be sent at the end of the program.
  294. * Another will be send a few minutes before the end, based on the value of reminderNotifTime
  295. *
  296. * @param machine The machine to watch
  297. */
  298. const setupNotifications = (machine: ProxiwashMachineType) => {
  299. if (!isMachineWatched(machine, machinesWatched)) {
  300. setupMachineNotification(
  301. machine.number,
  302. true,
  303. reminder,
  304. getMachineEndDate(machine)
  305. );
  306. saveNotificationToState(machine);
  307. } else {
  308. setupMachineNotification(machine.number, false);
  309. removeNotificationFromState(machine);
  310. }
  311. };
  312. /**
  313. * Gets the number of machines available
  314. *
  315. * @param isDryer True if we are only checking for dryer, false for washers
  316. * @return {number} The number of machines available
  317. */
  318. const getMachineAvailableNumber = (
  319. data: ReadonlyArray<ProxiwashMachineType>
  320. ): number => {
  321. let count = 0;
  322. data.forEach((machine: ProxiwashMachineType) => {
  323. if (machine.state === MachineStates.AVAILABLE) {
  324. count += 1;
  325. }
  326. });
  327. return count;
  328. };
  329. /**
  330. * Creates the dataset to be used by the FlatList
  331. *
  332. * @param fetchedData
  333. * @return {*}
  334. */
  335. const createDataset = (
  336. fetchedData: FetchedDataType | undefined
  337. ): SectionListDataType<ProxiwashMachineType> => {
  338. if (fetchedData) {
  339. let data = fetchedData;
  340. if (AprilFoolsManager.getInstance().isAprilFoolsEnabled()) {
  341. data = JSON.parse(JSON.stringify(fetchedData)); // Deep copy
  342. AprilFoolsManager.getNewProxiwashDryerOrderedList(data.dryers);
  343. AprilFoolsManager.getNewProxiwashWasherOrderedList(data.washers);
  344. }
  345. fetchedData = data;
  346. const cleanedList = getCleanedMachineWatched(machinesWatched, [
  347. ...data.dryers,
  348. ...data.washers,
  349. ]);
  350. if (cleanedList.length !== machinesWatched.length) {
  351. updatePreferences(
  352. ProxiwashPreferenceKeys.proxiwashWatchedMachines,
  353. cleanedList
  354. );
  355. }
  356. return [
  357. {
  358. title: i18n.t('screens.proxiwash.dryers'),
  359. icon: 'tumble-dryer',
  360. data: data.dryers === undefined ? [] : data.dryers,
  361. keyExtractor: getKeyExtractor,
  362. },
  363. {
  364. title: i18n.t('screens.proxiwash.washers'),
  365. icon: 'washing-machine',
  366. data: data.washers === undefined ? [] : data.washers,
  367. keyExtractor: getKeyExtractor,
  368. },
  369. ];
  370. } else {
  371. return [];
  372. }
  373. };
  374. /**
  375. * Shows a modal for the given item
  376. *
  377. * @param title The title to use
  378. * @param item The item to display information for in the modal
  379. * @param isDryer True if the given item is a dryer
  380. */
  381. const showModal = (
  382. title: string,
  383. item: ProxiwashMachineType,
  384. isDryer: boolean
  385. ) => {
  386. setModalCurrentDisplayItem(getModalContent(title, item, isDryer));
  387. if (modalRef.current) {
  388. modalRef.current.open();
  389. }
  390. };
  391. /**
  392. * Adds the given notifications associated to a machine ID to the watchlist, and saves the array to the preferences
  393. *
  394. * @param machine
  395. */
  396. const saveNotificationToState = (machine: ProxiwashMachineType) => {
  397. let data = [...machinesWatched];
  398. data.push(machine);
  399. saveNewWatchedList(data);
  400. };
  401. /**
  402. * Removes the given index from the watchlist array and saves it to preferences
  403. *
  404. * @param selectedMachine
  405. */
  406. const removeNotificationFromState = (
  407. selectedMachine: ProxiwashMachineType
  408. ) => {
  409. const newList = machinesWatched.filter(
  410. (m) => m.number !== selectedMachine.number
  411. );
  412. saveNewWatchedList(newList);
  413. };
  414. const saveNewWatchedList = (list: Array<ProxiwashMachineType>) => {
  415. updatePreferences(ProxiwashPreferenceKeys.proxiwashWatchedMachines, list);
  416. };
  417. const renderListHeaderComponent = (
  418. data: FetchedDataType | undefined,
  419. _loading: boolean,
  420. lastRefreshDate: Date | undefined
  421. ) => {
  422. if (data) {
  423. return (
  424. <ProxiwashListHeader
  425. date={lastRefreshDate}
  426. selectedWash={selectedWash}
  427. info={data?.info}
  428. />
  429. );
  430. } else {
  431. return null;
  432. }
  433. };
  434. let data: LaundromatType;
  435. switch (selectedWash) {
  436. case 'tripodeB':
  437. data = ProxiwashConstants.tripodeB;
  438. break;
  439. default:
  440. data = ProxiwashConstants.washinsa;
  441. }
  442. return (
  443. <View style={GENERAL_STYLES.flex}>
  444. <View style={styles.container}>
  445. <WebSectionList
  446. request={() => readData<FetchedDataType>(data.url)}
  447. createDataset={createDataset}
  448. renderItem={getRenderItem}
  449. renderSectionHeader={getRenderSectionHeader}
  450. autoRefreshTime={REFRESH_TIME}
  451. refreshOnFocus={true}
  452. extraData={machinesWatched.length}
  453. renderListHeaderComponent={renderListHeaderComponent}
  454. refresh={refresh}
  455. onFinish={() => setRefresh(false)}
  456. />
  457. </View>
  458. <MascotPopup
  459. title={i18n.t('screens.proxiwash.mascotDialog.title')}
  460. message={i18n.t('screens.proxiwash.mascotDialog.message')}
  461. icon="information"
  462. buttons={{
  463. action: {
  464. message: i18n.t('screens.proxiwash.mascotDialog.ok'),
  465. icon: 'cog',
  466. onPress: () => navigation.navigate('settings'),
  467. },
  468. cancel: {
  469. message: i18n.t('screens.proxiwash.mascotDialog.cancel'),
  470. icon: 'close',
  471. },
  472. }}
  473. emotion={MASCOT_STYLE.NORMAL}
  474. />
  475. <CustomModal ref={modalRef}>{modalCurrentDisplayItem}</CustomModal>
  476. </View>
  477. );
  478. }
  479. export default ProxiwashScreen;