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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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 REFRESH_TIME = 1000 * 10; // Refresh every 10 seconds
  48. const LIST_ITEM_HEIGHT = 64;
  49. export type ProxiwashMachineType = {
  50. number: string;
  51. state: MachineStates;
  52. maxWeight: number;
  53. startTime: string;
  54. endTime: string;
  55. donePercent: string;
  56. remainingTime: string;
  57. program: string;
  58. };
  59. type PropsType = {
  60. navigation: StackNavigationProp<any>;
  61. theme: ReactNativePaper.Theme;
  62. };
  63. type StateType = {
  64. modalCurrentDisplayItem: React.ReactNode;
  65. machinesWatched: Array<ProxiwashMachineType>;
  66. selectedWash: string;
  67. };
  68. /**
  69. * Class defining the app's proxiwash screen. This screen shows information about washing machines and
  70. * dryers, taken from a scrapper reading proxiwash website
  71. */
  72. class ProxiwashScreen extends React.Component<PropsType, StateType> {
  73. /**
  74. * Shows a warning telling the user notifications are disabled for the app
  75. */
  76. static showNotificationsDisabledWarning() {
  77. Alert.alert(
  78. i18n.t('screens.proxiwash.modal.notificationErrorTitle'),
  79. i18n.t('screens.proxiwash.modal.notificationErrorDescription'),
  80. );
  81. }
  82. modalStateStrings: {[key in MachineStates]: string} = {
  83. [MachineStates.AVAILABLE]: i18n.t('screens.proxiwash.modal.ready'),
  84. [MachineStates.RUNNING]: i18n.t('screens.proxiwash.modal.running'),
  85. [MachineStates.RUNNING_NOT_STARTED]: i18n.t(
  86. 'screens.proxiwash.modal.runningNotStarted',
  87. ),
  88. [MachineStates.FINISHED]: i18n.t('screens.proxiwash.modal.finished'),
  89. [MachineStates.UNAVAILABLE]: i18n.t('screens.proxiwash.modal.broken'),
  90. [MachineStates.ERROR]: i18n.t('screens.proxiwash.modal.error'),
  91. [MachineStates.UNKNOWN]: i18n.t('screens.proxiwash.modal.unknown'),
  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} | undefined;
  188. let message = this.modalStateStrings[item.state];
  189. const onPress = () => this.onSetupNotificationsPress(item);
  190. if (item.state === MachineStates.RUNNING) {
  191. let remainingTime = parseInt(item.remainingTime, 10);
  192. if (remainingTime < 0) {
  193. remainingTime = 0;
  194. }
  195. button = {
  196. text: isMachineWatched(item, state.machinesWatched)
  197. ? i18n.t('screens.proxiwash.modal.disableNotifications')
  198. : i18n.t('screens.proxiwash.modal.enableNotifications'),
  199. icon: '',
  200. onPress: onPress,
  201. };
  202. message = i18n.t('screens.proxiwash.modal.running', {
  203. start: item.startTime,
  204. end: item.endTime,
  205. remaining: remainingTime,
  206. program: item.program,
  207. });
  208. }
  209. return (
  210. <View
  211. style={{
  212. flex: 1,
  213. padding: 20,
  214. }}>
  215. <Card.Title
  216. title={title}
  217. left={() => (
  218. <Avatar.Icon
  219. icon={isDryer ? 'tumble-dryer' : 'washing-machine'}
  220. color={props.theme.colors.text}
  221. style={{backgroundColor: 'transparent'}}
  222. />
  223. )}
  224. />
  225. <Card.Content>
  226. <Text>{message}</Text>
  227. </Card.Content>
  228. {button ? (
  229. <Card.Actions>
  230. <Button
  231. icon={button.icon}
  232. mode="contained"
  233. onPress={button.onPress}
  234. style={{marginLeft: 'auto', marginRight: 'auto'}}>
  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. getRenderSectionHeader = ({section}: {section: {title: string}}) => {
  249. const isDryer = section.title === i18n.t('screens.proxiwash.dryers');
  250. const nbAvailable = this.getMachineAvailableNumber(isDryer);
  251. return (
  252. <ProxiwashSectionHeader
  253. title={section.title}
  254. nbAvailable={nbAvailable}
  255. isDryer={isDryer}
  256. />
  257. );
  258. };
  259. /**
  260. * Gets the list item to be rendered
  261. *
  262. * @param item The object containing the item's FetchedData
  263. * @param section The object describing the current SectionList section
  264. * @returns {React.Node}
  265. */
  266. getRenderItem = ({
  267. item,
  268. section,
  269. }: {
  270. item: ProxiwashMachineType;
  271. section: {title: string};
  272. }) => {
  273. const {machinesWatched} = this.state;
  274. const isDryer = section.title === i18n.t('screens.proxiwash.dryers');
  275. return (
  276. <ProxiwashListItem
  277. item={item}
  278. onPress={this.showModal}
  279. isWatched={isMachineWatched(item, machinesWatched)}
  280. isDryer={isDryer}
  281. height={LIST_ITEM_HEIGHT}
  282. />
  283. );
  284. };
  285. /**
  286. * Extracts the key for the given item
  287. *
  288. * @param item The item to extract the key from
  289. * @return {*} The extracted key
  290. */
  291. getKeyExtractor = (item: ProxiwashMachineType): string => item.number;
  292. /**
  293. * Setups notifications for the machine with the given ID.
  294. * One notification will be sent at the end of the program.
  295. * Another will be send a few minutes before the end, based on the value of reminderNotifTime
  296. *
  297. * @param machine The machine to watch
  298. */
  299. setupNotifications(machine: ProxiwashMachineType) {
  300. const {machinesWatched} = this.state;
  301. if (!isMachineWatched(machine, machinesWatched)) {
  302. Notifications.setupMachineNotification(
  303. machine.number,
  304. true,
  305. getMachineEndDate(machine),
  306. )
  307. .then(() => {
  308. this.saveNotificationToState(machine);
  309. })
  310. .catch(() => {
  311. ProxiwashScreen.showNotificationsDisabledWarning();
  312. });
  313. } else {
  314. Notifications.setupMachineNotification(machine.number, false, null).then(
  315. () => {
  316. this.removeNotificationFromState(machine);
  317. },
  318. );
  319. }
  320. }
  321. /**
  322. * Gets the number of machines available
  323. *
  324. * @param isDryer True if we are only checking for dryer, false for washers
  325. * @return {number} The number of machines available
  326. */
  327. getMachineAvailableNumber(isDryer: boolean): number {
  328. let data;
  329. if (isDryer) {
  330. data = this.fetchedData.dryers;
  331. } else {
  332. data = this.fetchedData.washers;
  333. }
  334. let count = 0;
  335. data.forEach((machine: ProxiwashMachineType) => {
  336. if (machine.state === MachineStates.AVAILABLE) {
  337. count += 1;
  338. }
  339. });
  340. return count;
  341. }
  342. /**
  343. * Creates the dataset to be used by the FlatList
  344. *
  345. * @param fetchedData
  346. * @return {*}
  347. */
  348. createDataset = (fetchedData: {
  349. dryers: Array<ProxiwashMachineType>;
  350. washers: Array<ProxiwashMachineType>;
  351. }): SectionListDataType<ProxiwashMachineType> => {
  352. const {state} = this;
  353. let data = fetchedData;
  354. if (AprilFoolsManager.getInstance().isAprilFoolsEnabled()) {
  355. data = JSON.parse(JSON.stringify(fetchedData)); // Deep copy
  356. AprilFoolsManager.getNewProxiwashDryerOrderedList(data.dryers);
  357. AprilFoolsManager.getNewProxiwashWasherOrderedList(data.washers);
  358. }
  359. this.fetchedData = data;
  360. this.state.machinesWatched = getCleanedMachineWatched(
  361. state.machinesWatched,
  362. [...data.dryers, ...data.washers],
  363. );
  364. return [
  365. {
  366. title: i18n.t('screens.proxiwash.dryers'),
  367. icon: 'tumble-dryer',
  368. data: data.dryers === undefined ? [] : data.dryers,
  369. keyExtractor: this.getKeyExtractor,
  370. },
  371. {
  372. title: i18n.t('screens.proxiwash.washers'),
  373. icon: 'washing-machine',
  374. data: data.washers === undefined ? [] : data.washers,
  375. keyExtractor: this.getKeyExtractor,
  376. },
  377. ];
  378. };
  379. /**
  380. * Callback used when the user clicks on the navigate to settings button.
  381. * This will hide the banner and open the SettingsScreen
  382. */
  383. onGoToSettings = () => {
  384. const {navigation} = this.props;
  385. navigation.navigate('settings');
  386. };
  387. /**
  388. * Shows a modal for the given item
  389. *
  390. * @param title The title to use
  391. * @param item The item to display information for in the modal
  392. * @param isDryer True if the given item is a dryer
  393. */
  394. showModal = (title: string, item: ProxiwashMachineType, isDryer: boolean) => {
  395. this.setState({
  396. modalCurrentDisplayItem: this.getModalContent(title, item, isDryer),
  397. });
  398. if (this.modalRef) {
  399. this.modalRef.open();
  400. }
  401. };
  402. /**
  403. * Adds the given notifications associated to a machine ID to the watchlist, and saves the array to the preferences
  404. *
  405. * @param machine
  406. */
  407. saveNotificationToState(machine: ProxiwashMachineType) {
  408. const {machinesWatched} = this.state;
  409. const data = machinesWatched;
  410. data.push(machine);
  411. this.saveNewWatchedList(data);
  412. }
  413. /**
  414. * Removes the given index from the watchlist array and saves it to preferences
  415. *
  416. * @param selectedMachine
  417. */
  418. removeNotificationFromState(selectedMachine: ProxiwashMachineType) {
  419. const {machinesWatched} = this.state;
  420. const newList = [...machinesWatched];
  421. machinesWatched.forEach((machine: ProxiwashMachineType, index: number) => {
  422. if (
  423. machine.number === selectedMachine.number &&
  424. machine.endTime === selectedMachine.endTime
  425. ) {
  426. newList.splice(index, 1);
  427. }
  428. });
  429. this.saveNewWatchedList(newList);
  430. }
  431. saveNewWatchedList(list: Array<ProxiwashMachineType>) {
  432. this.setState({machinesWatched: list});
  433. AsyncStorageManager.set(
  434. AsyncStorageManager.PREFERENCES.proxiwashWatchedMachines.key,
  435. list,
  436. );
  437. }
  438. render() {
  439. const {state} = this;
  440. const {navigation} = this.props;
  441. let data: LaundromatType;
  442. switch (state.selectedWash) {
  443. case 'tripodeB':
  444. data = ProxiwashConstants.tripodeB;
  445. break;
  446. default:
  447. data = ProxiwashConstants.washinsa;
  448. }
  449. return (
  450. <View
  451. style={{
  452. flex: 1,
  453. }}>
  454. <View
  455. style={{
  456. position: 'absolute',
  457. width: '100%',
  458. height: '100%',
  459. }}>
  460. <WebSectionList
  461. createDataset={this.createDataset}
  462. navigation={navigation}
  463. fetchUrl={data.url}
  464. renderItem={this.getRenderItem}
  465. renderSectionHeader={this.getRenderSectionHeader}
  466. autoRefreshTime={REFRESH_TIME}
  467. refreshOnFocus
  468. updateData={state.machinesWatched.length}
  469. />
  470. </View>
  471. <MascotPopup
  472. prefKey={AsyncStorageManager.PREFERENCES.proxiwashShowMascot.key}
  473. title={i18n.t('screens.proxiwash.mascotDialog.title')}
  474. message={i18n.t('screens.proxiwash.mascotDialog.message')}
  475. icon="information"
  476. buttons={{
  477. action: {
  478. message: i18n.t('screens.proxiwash.mascotDialog.ok'),
  479. icon: 'cog',
  480. onPress: this.onGoToSettings,
  481. },
  482. cancel: {
  483. message: i18n.t('screens.proxiwash.mascotDialog.cancel'),
  484. icon: 'close',
  485. },
  486. }}
  487. emotion={MASCOT_STYLE.NORMAL}
  488. />
  489. <CustomModal onRef={this.onModalRef}>
  490. {state.modalCurrentDisplayItem}
  491. </CustomModal>
  492. </View>
  493. );
  494. }
  495. }
  496. export default withTheme(ProxiwashScreen);