Application Android et IOS pour l'amicale des élèves
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 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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 * as React from 'react';
  20. import {Alert, View} from 'react-native';
  21. import i18n from 'i18n-js';
  22. import {Avatar, Button, Card, Text, withTheme} from 'react-native-paper';
  23. import {StackNavigationProp} from '@react-navigation/stack';
  24. import {Modalize} from 'react-native-modalize';
  25. import WebSectionList from '../../components/Screens/WebSectionList';
  26. import * as Notifications from '../../utils/Notifications';
  27. import AsyncStorageManager from '../../managers/AsyncStorageManager';
  28. import ProxiwashListItem from '../../components/Lists/Proxiwash/ProxiwashListItem';
  29. import ProxiwashConstants, {
  30. MachineStates,
  31. } from '../../constants/ProxiwashConstants';
  32. import CustomModal from '../../components/Overrides/CustomModal';
  33. import AprilFoolsManager from '../../managers/AprilFoolsManager';
  34. import MaterialHeaderButtons, {
  35. Item,
  36. } from '../../components/Overrides/CustomHeaderButton';
  37. import ProxiwashSectionHeader from '../../components/Lists/Proxiwash/ProxiwashSectionHeader';
  38. import {
  39. getCleanedMachineWatched,
  40. getMachineEndDate,
  41. isMachineWatched,
  42. } from '../../utils/Proxiwash';
  43. import {MASCOT_STYLE} from '../../components/Mascot/Mascot';
  44. import MascotPopup from '../../components/Mascot/MascotPopup';
  45. import type {SectionListDataType} from '../../components/Screens/WebSectionList';
  46. import type {LaundromatType} from './ProxiwashAboutScreen';
  47. const modalStateStrings: {[key in MachineStates]: string} = {
  48. [MachineStates.AVAILABLE]: i18n.t('screens.proxiwash.modal.ready'),
  49. [MachineStates.RUNNING]: i18n.t('screens.proxiwash.modal.running'),
  50. [MachineStates.RUNNING_NOT_STARTED]: i18n.t(
  51. 'screens.proxiwash.modal.runningNotStarted',
  52. ),
  53. [MachineStates.FINISHED]: i18n.t('screens.proxiwash.modal.finished'),
  54. [MachineStates.UNAVAILABLE]: i18n.t('screens.proxiwash.modal.broken'),
  55. [MachineStates.ERROR]: i18n.t('screens.proxiwash.modal.error'),
  56. [MachineStates.UNKNOWN]: i18n.t('screens.proxiwash.modal.unknown'),
  57. };
  58. const REFRESH_TIME = 1000 * 10; // Refresh every 10 seconds
  59. const LIST_ITEM_HEIGHT = 64;
  60. export type ProxiwashMachineType = {
  61. number: string;
  62. state: MachineStates;
  63. maxWeight: number;
  64. startTime: string;
  65. endTime: string;
  66. donePercent: string;
  67. remainingTime: string;
  68. program: string;
  69. };
  70. type PropsType = {
  71. navigation: StackNavigationProp<any>;
  72. theme: ReactNativePaper.Theme;
  73. };
  74. type StateType = {
  75. modalCurrentDisplayItem: React.ReactNode;
  76. machinesWatched: Array<ProxiwashMachineType>;
  77. selectedWash: string;
  78. };
  79. /**
  80. * Class defining the app's proxiwash screen. This screen shows information about washing machines and
  81. * dryers, taken from a scrapper reading proxiwash website
  82. */
  83. class ProxiwashScreen extends React.Component<PropsType, StateType> {
  84. /**
  85. * Shows a warning telling the user notifications are disabled for the app
  86. */
  87. static showNotificationsDisabledWarning() {
  88. Alert.alert(
  89. i18n.t('screens.proxiwash.modal.notificationErrorTitle'),
  90. i18n.t('screens.proxiwash.modal.notificationErrorDescription'),
  91. );
  92. }
  93. modalRef: null | Modalize;
  94. fetchedData: {
  95. dryers: Array<ProxiwashMachineType>;
  96. washers: Array<ProxiwashMachineType>;
  97. };
  98. /**
  99. * Creates machine state parameters using current theme and translations
  100. */
  101. constructor(props: PropsType) {
  102. super(props);
  103. this.modalRef = null;
  104. this.fetchedData = {dryers: [], washers: []};
  105. this.state = {
  106. modalCurrentDisplayItem: null,
  107. machinesWatched: AsyncStorageManager.getObject(
  108. AsyncStorageManager.PREFERENCES.proxiwashWatchedMachines.key,
  109. ),
  110. selectedWash: AsyncStorageManager.getString(
  111. AsyncStorageManager.PREFERENCES.selectedWash.key,
  112. ),
  113. };
  114. }
  115. /**
  116. * Setup notification channel for android and add listeners to detect notifications fired
  117. */
  118. componentDidMount() {
  119. const {navigation} = this.props;
  120. navigation.setOptions({
  121. headerRight: () => (
  122. <MaterialHeaderButtons>
  123. <Item
  124. title="switch"
  125. iconName="swap-horizontal"
  126. onPress={(): void => navigation.navigate('settings')}
  127. />
  128. <Item
  129. title="information"
  130. iconName="information"
  131. onPress={this.onAboutPress}
  132. />
  133. </MaterialHeaderButtons>
  134. ),
  135. });
  136. navigation.addListener('focus', this.onScreenFocus);
  137. }
  138. onScreenFocus = () => {
  139. const {state} = this;
  140. const selected = AsyncStorageManager.getString(
  141. AsyncStorageManager.PREFERENCES.selectedWash.key,
  142. );
  143. if (selected !== state.selectedWash) {
  144. this.setState({
  145. selectedWash: selected,
  146. });
  147. }
  148. };
  149. /**
  150. * Callback used when pressing the about button.
  151. * This will open the ProxiwashAboutScreen.
  152. */
  153. onAboutPress = () => {
  154. const {navigation} = this.props;
  155. navigation.navigate('proxiwash-about');
  156. };
  157. /**
  158. * Callback used when the user clicks on enable notifications for a machine
  159. *
  160. * @param machine The machine to set notifications for
  161. */
  162. onSetupNotificationsPress(machine: ProxiwashMachineType) {
  163. if (this.modalRef) {
  164. this.modalRef.close();
  165. }
  166. this.setupNotifications(machine);
  167. }
  168. /**
  169. * Callback used when receiving modal ref
  170. *
  171. * @param ref
  172. */
  173. onModalRef = (ref: Modalize) => {
  174. this.modalRef = ref;
  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. getModalContent(title: string, item: ProxiwashMachineType, isDryer: boolean) {
  186. const {props, state} = this;
  187. let button: {text: string; icon: string; onPress: () => void} = {
  188. text: i18n.t('screens.proxiwash.modal.ok'),
  189. icon: '',
  190. onPress: () => undefined,
  191. };
  192. let message = modalStateStrings[item.state];
  193. const onPress = () => this.onSetupNotificationsPress(item);
  194. if (item.state === MachineStates.RUNNING) {
  195. let remainingTime = parseInt(item.remainingTime, 10);
  196. if (remainingTime < 0) {
  197. remainingTime = 0;
  198. }
  199. button = {
  200. text: isMachineWatched(item, state.machinesWatched)
  201. ? i18n.t('screens.proxiwash.modal.disableNotifications')
  202. : i18n.t('screens.proxiwash.modal.enableNotifications'),
  203. icon: '',
  204. onPress: onPress,
  205. };
  206. message = i18n.t('screens.proxiwash.modal.running', {
  207. start: item.startTime,
  208. end: item.endTime,
  209. remaining: remainingTime,
  210. program: item.program,
  211. });
  212. }
  213. return (
  214. <View
  215. style={{
  216. flex: 1,
  217. padding: 20,
  218. }}>
  219. <Card.Title
  220. title={title}
  221. left={() => (
  222. <Avatar.Icon
  223. icon={isDryer ? 'tumble-dryer' : 'washing-machine'}
  224. color={props.theme.colors.text}
  225. style={{backgroundColor: 'transparent'}}
  226. />
  227. )}
  228. />
  229. <Card.Content>
  230. <Text>{message}</Text>
  231. </Card.Content>
  232. {button.onPress ? (
  233. <Card.Actions>
  234. <Button
  235. icon={button.icon}
  236. mode="contained"
  237. onPress={button.onPress}
  238. style={{marginLeft: 'auto', marginRight: 'auto'}}>
  239. {button.text}
  240. </Button>
  241. </Card.Actions>
  242. ) : null}
  243. </View>
  244. );
  245. }
  246. /**
  247. * Gets the section render item
  248. *
  249. * @param section The section to render
  250. * @return {*}
  251. */
  252. getRenderSectionHeader = ({section}: {section: {title: string}}) => {
  253. const isDryer = section.title === i18n.t('screens.proxiwash.dryers');
  254. const nbAvailable = this.getMachineAvailableNumber(isDryer);
  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. getRenderItem = ({
  271. item,
  272. section,
  273. }: {
  274. item: ProxiwashMachineType;
  275. section: {title: string};
  276. }) => {
  277. const {machinesWatched} = this.state;
  278. const isDryer = section.title === i18n.t('screens.proxiwash.dryers');
  279. return (
  280. <ProxiwashListItem
  281. item={item}
  282. onPress={this.showModal}
  283. isWatched={isMachineWatched(item, machinesWatched)}
  284. isDryer={isDryer}
  285. height={LIST_ITEM_HEIGHT}
  286. />
  287. );
  288. };
  289. /**
  290. * Extracts the key for the given item
  291. *
  292. * @param item The item to extract the key from
  293. * @return {*} The extracted key
  294. */
  295. getKeyExtractor = (item: ProxiwashMachineType): string => item.number;
  296. /**
  297. * Setups notifications for the machine with the given ID.
  298. * One notification will be sent at the end of the program.
  299. * Another will be send a few minutes before the end, based on the value of reminderNotifTime
  300. *
  301. * @param machine The machine to watch
  302. */
  303. setupNotifications(machine: ProxiwashMachineType) {
  304. const {machinesWatched} = this.state;
  305. if (!isMachineWatched(machine, machinesWatched)) {
  306. Notifications.setupMachineNotification(
  307. machine.number,
  308. true,
  309. getMachineEndDate(machine),
  310. )
  311. .then(() => {
  312. this.saveNotificationToState(machine);
  313. })
  314. .catch(() => {
  315. ProxiwashScreen.showNotificationsDisabledWarning();
  316. });
  317. } else {
  318. Notifications.setupMachineNotification(machine.number, false, null).then(
  319. () => {
  320. this.removeNotificationFromState(machine);
  321. },
  322. );
  323. }
  324. }
  325. /**
  326. * Gets the number of machines available
  327. *
  328. * @param isDryer True if we are only checking for dryer, false for washers
  329. * @return {number} The number of machines available
  330. */
  331. getMachineAvailableNumber(isDryer: boolean): number {
  332. let data;
  333. if (isDryer) {
  334. data = this.fetchedData.dryers;
  335. } else {
  336. data = this.fetchedData.washers;
  337. }
  338. let count = 0;
  339. data.forEach((machine: ProxiwashMachineType) => {
  340. if (machine.state === MachineStates.AVAILABLE) {
  341. count += 1;
  342. }
  343. });
  344. return count;
  345. }
  346. /**
  347. * Creates the dataset to be used by the FlatList
  348. *
  349. * @param fetchedData
  350. * @return {*}
  351. */
  352. createDataset = (fetchedData: {
  353. dryers: Array<ProxiwashMachineType>;
  354. washers: Array<ProxiwashMachineType>;
  355. }): SectionListDataType<ProxiwashMachineType> => {
  356. const {state} = this;
  357. let data = fetchedData;
  358. if (AprilFoolsManager.getInstance().isAprilFoolsEnabled()) {
  359. data = JSON.parse(JSON.stringify(fetchedData)); // Deep copy
  360. AprilFoolsManager.getNewProxiwashDryerOrderedList(data.dryers);
  361. AprilFoolsManager.getNewProxiwashWasherOrderedList(data.washers);
  362. }
  363. this.fetchedData = data;
  364. this.state.machinesWatched = getCleanedMachineWatched(
  365. state.machinesWatched,
  366. [...data.dryers, ...data.washers],
  367. );
  368. return [
  369. {
  370. title: i18n.t('screens.proxiwash.dryers'),
  371. icon: 'tumble-dryer',
  372. data: data.dryers === undefined ? [] : data.dryers,
  373. keyExtractor: this.getKeyExtractor,
  374. },
  375. {
  376. title: i18n.t('screens.proxiwash.washers'),
  377. icon: 'washing-machine',
  378. data: data.washers === undefined ? [] : data.washers,
  379. keyExtractor: this.getKeyExtractor,
  380. },
  381. ];
  382. };
  383. /**
  384. * Callback used when the user clicks on the navigate to settings button.
  385. * This will hide the banner and open the SettingsScreen
  386. */
  387. onGoToSettings = () => {
  388. const {navigation} = this.props;
  389. navigation.navigate('settings');
  390. };
  391. /**
  392. * Shows a modal for the given item
  393. *
  394. * @param title The title to use
  395. * @param item The item to display information for in the modal
  396. * @param isDryer True if the given item is a dryer
  397. */
  398. showModal = (title: string, item: ProxiwashMachineType, isDryer: boolean) => {
  399. this.setState({
  400. modalCurrentDisplayItem: this.getModalContent(title, item, isDryer),
  401. });
  402. if (this.modalRef) {
  403. this.modalRef.open();
  404. }
  405. };
  406. /**
  407. * Adds the given notifications associated to a machine ID to the watchlist, and saves the array to the preferences
  408. *
  409. * @param machine
  410. */
  411. saveNotificationToState(machine: ProxiwashMachineType) {
  412. const {machinesWatched} = this.state;
  413. const data = machinesWatched;
  414. data.push(machine);
  415. this.saveNewWatchedList(data);
  416. }
  417. /**
  418. * Removes the given index from the watchlist array and saves it to preferences
  419. *
  420. * @param selectedMachine
  421. */
  422. removeNotificationFromState(selectedMachine: ProxiwashMachineType) {
  423. const {machinesWatched} = this.state;
  424. const newList = [...machinesWatched];
  425. machinesWatched.forEach((machine: ProxiwashMachineType, index: number) => {
  426. if (
  427. machine.number === selectedMachine.number &&
  428. machine.endTime === selectedMachine.endTime
  429. ) {
  430. newList.splice(index, 1);
  431. }
  432. });
  433. this.saveNewWatchedList(newList);
  434. }
  435. saveNewWatchedList(list: Array<ProxiwashMachineType>) {
  436. this.setState({machinesWatched: list});
  437. AsyncStorageManager.set(
  438. AsyncStorageManager.PREFERENCES.proxiwashWatchedMachines.key,
  439. list,
  440. );
  441. }
  442. render() {
  443. const {state} = this;
  444. const {navigation} = this.props;
  445. let data: LaundromatType;
  446. switch (state.selectedWash) {
  447. case 'tripodeB':
  448. data = ProxiwashConstants.tripodeB;
  449. break;
  450. default:
  451. data = ProxiwashConstants.washinsa;
  452. }
  453. return (
  454. <View
  455. style={{
  456. flex: 1,
  457. }}>
  458. <View
  459. style={{
  460. position: 'absolute',
  461. width: '100%',
  462. height: '100%',
  463. }}>
  464. <WebSectionList
  465. createDataset={this.createDataset}
  466. navigation={navigation}
  467. fetchUrl={data.url}
  468. renderItem={this.getRenderItem}
  469. renderSectionHeader={this.getRenderSectionHeader}
  470. autoRefreshTime={REFRESH_TIME}
  471. refreshOnFocus
  472. updateData={state.machinesWatched.length}
  473. />
  474. </View>
  475. <MascotPopup
  476. prefKey={AsyncStorageManager.PREFERENCES.proxiwashShowMascot.key}
  477. title={i18n.t('screens.proxiwash.mascotDialog.title')}
  478. message={i18n.t('screens.proxiwash.mascotDialog.message')}
  479. icon="information"
  480. buttons={{
  481. action: {
  482. message: i18n.t('screens.proxiwash.mascotDialog.ok'),
  483. icon: 'cog',
  484. onPress: this.onGoToSettings,
  485. },
  486. cancel: {
  487. message: i18n.t('screens.proxiwash.mascotDialog.cancel'),
  488. icon: 'close',
  489. },
  490. }}
  491. emotion={MASCOT_STYLE.NORMAL}
  492. />
  493. <CustomModal onRef={this.onModalRef}>
  494. {state.modalCurrentDisplayItem}
  495. </CustomModal>
  496. </View>
  497. );
  498. }
  499. }
  500. export default withTheme(ProxiwashScreen);