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.js 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. // @flow
  2. import * as React from 'react';
  3. import {Alert, Platform, View} from 'react-native';
  4. import i18n from "i18n-js";
  5. import WebSectionList from "../../components/Lists/WebSectionList";
  6. import * as Notifications from "../../utils/Notifications";
  7. import AsyncStorageManager from "../../managers/AsyncStorageManager";
  8. import * as Expo from "expo";
  9. import {Avatar, Banner, Button, Card, Text, withTheme} from 'react-native-paper';
  10. import HeaderButton from "../../components/Custom/HeaderButton";
  11. import ProxiwashListItem from "../../components/Lists/ProxiwashListItem";
  12. import ProxiwashConstants from "../../constants/ProxiwashConstants";
  13. import CustomModal from "../../components/Custom/CustomModal";
  14. import AprilFoolsManager from "../../managers/AprilFoolsManager";
  15. const DATA_URL = "https://etud.insa-toulouse.fr/~amicale_app/washinsa/washinsa.json";
  16. let stateStrings = {};
  17. let modalStateStrings = {};
  18. let stateIcons = {};
  19. const REFRESH_TIME = 1000 * 10; // Refresh every 10 seconds
  20. const LIST_ITEM_HEIGHT = 64;
  21. type Props = {
  22. navigation: Object,
  23. theme: Object,
  24. }
  25. type State = {
  26. refreshing: boolean,
  27. firstLoading: boolean,
  28. modalCurrentDisplayItem: React.Node,
  29. machinesWatched: Array<string>,
  30. bannerVisible: boolean,
  31. };
  32. /**
  33. * Class defining the app's proxiwash screen. This screen shows information about washing machines and
  34. * dryers, taken from a scrapper reading proxiwash website
  35. */
  36. class ProxiwashScreen extends React.Component<Props, State> {
  37. modalRef: Object;
  38. onAboutPress: Function;
  39. getRenderItem: Function;
  40. getRenderSectionHeader: Function;
  41. createDataset: Function;
  42. onHideBanner: Function;
  43. onModalRef: Function;
  44. fetchedData: Object;
  45. colors: Object;
  46. state = {
  47. refreshing: false,
  48. firstLoading: true,
  49. fetchedData: {},
  50. machinesWatched: [],
  51. modalCurrentDisplayItem: null,
  52. bannerVisible: AsyncStorageManager.getInstance().preferences.proxiwashShowBanner.current === '1',
  53. };
  54. /**
  55. * Creates machine state parameters using current theme and translations
  56. */
  57. constructor(props) {
  58. super(props);
  59. stateStrings[ProxiwashConstants.machineStates.TERMINE] = i18n.t('proxiwashScreen.states.finished');
  60. stateStrings[ProxiwashConstants.machineStates.DISPONIBLE] = i18n.t('proxiwashScreen.states.ready');
  61. stateStrings[ProxiwashConstants.machineStates["EN COURS"]] = i18n.t('proxiwashScreen.states.running');
  62. stateStrings[ProxiwashConstants.machineStates.HS] = i18n.t('proxiwashScreen.states.broken');
  63. stateStrings[ProxiwashConstants.machineStates.ERREUR] = i18n.t('proxiwashScreen.states.error');
  64. modalStateStrings[ProxiwashConstants.machineStates.TERMINE] = i18n.t('proxiwashScreen.modal.finished');
  65. modalStateStrings[ProxiwashConstants.machineStates.DISPONIBLE] = i18n.t('proxiwashScreen.modal.ready');
  66. modalStateStrings[ProxiwashConstants.machineStates["EN COURS"]] = i18n.t('proxiwashScreen.modal.running');
  67. modalStateStrings[ProxiwashConstants.machineStates.HS] = i18n.t('proxiwashScreen.modal.broken');
  68. modalStateStrings[ProxiwashConstants.machineStates.ERREUR] = i18n.t('proxiwashScreen.modal.error');
  69. stateIcons[ProxiwashConstants.machineStates.TERMINE] = 'check-circle';
  70. stateIcons[ProxiwashConstants.machineStates.DISPONIBLE] = 'radiobox-blank';
  71. stateIcons[ProxiwashConstants.machineStates["EN COURS"]] = 'progress-check';
  72. stateIcons[ProxiwashConstants.machineStates.HS] = 'alert-octagram-outline';
  73. stateIcons[ProxiwashConstants.machineStates.ERREUR] = 'alert';
  74. // let dataString = AsyncStorageManager.getInstance().preferences.proxiwashWatchedMachines.current;
  75. this.onAboutPress = this.onAboutPress.bind(this);
  76. this.getRenderItem = this.getRenderItem.bind(this);
  77. this.getRenderSectionHeader = this.getRenderSectionHeader.bind(this);
  78. this.createDataset = this.createDataset.bind(this);
  79. this.onHideBanner = this.onHideBanner.bind(this);
  80. this.onModalRef = this.onModalRef.bind(this);
  81. this.colors = props.theme.colors;
  82. }
  83. /**
  84. * Callback used when closing the banner.
  85. * This hides the banner and saves to preferences to prevent it from reopening
  86. */
  87. onHideBanner() {
  88. this.setState({bannerVisible: false});
  89. AsyncStorageManager.getInstance().savePref(
  90. AsyncStorageManager.getInstance().preferences.proxiwashShowBanner.key,
  91. '0'
  92. );
  93. }
  94. /**
  95. * Setup notification channel for android and add listeners to detect notifications fired
  96. */
  97. componentDidMount() {
  98. const rightButton = this.getAboutButton.bind(this);
  99. this.props.navigation.setOptions({
  100. headerRight: rightButton,
  101. });
  102. if (AsyncStorageManager.getInstance().preferences.expoToken.current !== '') {
  103. // Get latest watchlist from server
  104. Notifications.getMachineNotificationWatchlist((fetchedList) => {
  105. this.setState({machinesWatched: fetchedList})
  106. });
  107. // Get updated watchlist after received notification
  108. Expo.Notifications.addListener(() => {
  109. Notifications.getMachineNotificationWatchlist((fetchedList) => {
  110. this.setState({machinesWatched: fetchedList})
  111. });
  112. });
  113. if (Platform.OS === 'android') {
  114. Expo.Notifications.createChannelAndroidAsync('reminders', {
  115. name: 'Reminders',
  116. priority: 'max',
  117. vibrate: [0, 250, 250, 250],
  118. });
  119. }
  120. }
  121. }
  122. /**
  123. * Callback used when pressing the about button.
  124. * This will open the ProxiwashAboutScreen.
  125. */
  126. onAboutPress() {
  127. this.props.navigation.navigate('ProxiwashAboutScreen');
  128. }
  129. /**
  130. * Gets the about header button
  131. *
  132. * @return {*}
  133. */
  134. getAboutButton() {
  135. return <HeaderButton icon={'information'} onPress={this.onAboutPress}/>;
  136. }
  137. /**
  138. * Extracts the key for the given item
  139. *
  140. * @param item The item to extract the key from
  141. * @return {*} The extracted key
  142. */
  143. getKeyExtractor(item: Object) {
  144. return item !== undefined ? item.number : undefined;
  145. }
  146. /**
  147. * Setups notifications for the machine with the given ID.
  148. * One notification will be sent at the end of the program.
  149. * Another will be send a few minutes before the end, based on the value of reminderNotifTime
  150. *
  151. * @param machineId The machine's ID
  152. * @returns {Promise<void>}
  153. */
  154. setupNotifications(machineId: string) {
  155. if (AsyncStorageManager.getInstance().preferences.expoToken.current !== '') {
  156. if (!this.isMachineWatched(machineId)) {
  157. Notifications.setupMachineNotification(machineId, true);
  158. this.saveNotificationToState(machineId);
  159. } else
  160. this.disableNotification(machineId);
  161. } else {
  162. this.showNotificationsDisabledWarning();
  163. }
  164. }
  165. /**
  166. * Shows a warning telling the user notifications are disabled for the app
  167. */
  168. showNotificationsDisabledWarning() {
  169. Alert.alert(
  170. i18n.t("proxiwashScreen.modal.notificationErrorTitle"),
  171. i18n.t("proxiwashScreen.modal.notificationErrorDescription"),
  172. );
  173. }
  174. /**
  175. * Stops scheduled notifications for the machine of the given ID.
  176. * This will also remove the notification if it was already shown.
  177. *
  178. * @param machineId The machine's ID
  179. */
  180. disableNotification(machineId: string) {
  181. let data = this.state.machinesWatched;
  182. if (data.length > 0) {
  183. let arrayIndex = data.indexOf(machineId);
  184. if (arrayIndex !== -1) {
  185. Notifications.setupMachineNotification(machineId, false);
  186. this.removeNotificationFroState(arrayIndex);
  187. }
  188. }
  189. }
  190. /**
  191. * Adds the given notifications associated to a machine ID to the watchlist, and saves the array to the preferences
  192. *
  193. * @param machineId
  194. */
  195. saveNotificationToState(machineId: string) {
  196. let data = this.state.machinesWatched;
  197. data.push(machineId);
  198. this.updateNotificationState(data);
  199. }
  200. /**
  201. * Removes the given index from the watchlist array and saves it to preferences
  202. *
  203. * @param index
  204. */
  205. removeNotificationFroState(index: number) {
  206. let data = this.state.machinesWatched;
  207. data.splice(index, 1);
  208. this.updateNotificationState(data);
  209. }
  210. /**
  211. * Sets the given data as the watchlist
  212. *
  213. * @param data
  214. */
  215. updateNotificationState(data: Array<Object>) {
  216. this.setState({machinesWatched: data});
  217. }
  218. /**
  219. * Checks whether the machine of the given ID has scheduled notifications
  220. *
  221. * @param machineID The machine's ID
  222. * @returns {boolean}
  223. */
  224. isMachineWatched(machineID: string) {
  225. return this.state.machinesWatched.indexOf(machineID) !== -1;
  226. }
  227. /**
  228. * Creates the dataset to be used by the flatlist
  229. *
  230. * @param fetchedData
  231. * @return {*}
  232. */
  233. createDataset(fetchedData: Object) {
  234. let data = fetchedData;
  235. if (AprilFoolsManager.getInstance().isAprilFoolsEnabled()) {
  236. data = JSON.parse(JSON.stringify(fetchedData)); // Deep copy
  237. AprilFoolsManager.getNewProxiwashDryerOrderedList(data.dryers);
  238. AprilFoolsManager.getNewProxiwashWasherOrderedList(data.washers);
  239. }
  240. this.fetchedData = fetchedData;
  241. return [
  242. {
  243. title: i18n.t('proxiwashScreen.dryers'),
  244. icon: 'tumble-dryer',
  245. data: data.dryers === undefined ? [] : data.dryers,
  246. keyExtractor: this.getKeyExtractor
  247. },
  248. {
  249. title: i18n.t('proxiwashScreen.washers'),
  250. icon: 'washing-machine',
  251. data: data.washers === undefined ? [] : data.washers,
  252. keyExtractor: this.getKeyExtractor
  253. },
  254. ];
  255. }
  256. /**
  257. * Shows a modal for the given item
  258. *
  259. * @param title The title to use
  260. * @param item The item to display information for in the modal
  261. * @param isDryer True if the given item is a dryer
  262. */
  263. showModal(title: string, item: Object, isDryer: boolean) {
  264. this.setState({
  265. modalCurrentDisplayItem: this.getModalContent(title, item, isDryer)
  266. });
  267. if (this.modalRef) {
  268. this.modalRef.open();
  269. }
  270. }
  271. /**
  272. * Callback used when the user clicks on enable notifications for a machine
  273. *
  274. * @param machineId The machine's id to set notifications for
  275. */
  276. onSetupNotificationsPress(machineId: string) {
  277. if (this.modalRef) {
  278. this.modalRef.close();
  279. }
  280. this.setupNotifications(machineId)
  281. }
  282. /**
  283. * Generates the modal content.
  284. * This shows information for the given machine.
  285. *
  286. * @param title The title to use
  287. * @param item The item to display information for in the modal
  288. * @param isDryer True if the given item is a dryer
  289. * @return {*}
  290. */
  291. getModalContent(title: string, item: Object, isDryer: boolean) {
  292. let button = {
  293. text: i18n.t("proxiwashScreen.modal.ok"),
  294. icon: '',
  295. onPress: undefined
  296. };
  297. let message = modalStateStrings[ProxiwashConstants.machineStates[item.state]];
  298. const onPress = this.onSetupNotificationsPress.bind(this, item.number);
  299. if (ProxiwashConstants.machineStates[item.state] === ProxiwashConstants.machineStates["EN COURS"]) {
  300. button =
  301. {
  302. text: this.isMachineWatched(item.number) ?
  303. i18n.t("proxiwashScreen.modal.disableNotifications") :
  304. i18n.t("proxiwashScreen.modal.enableNotifications"),
  305. icon: '',
  306. onPress: onPress
  307. }
  308. ;
  309. message = i18n.t('proxiwashScreen.modal.running',
  310. {
  311. start: item.startTime,
  312. end: item.endTime,
  313. remaining: item.remainingTime
  314. });
  315. } else if (ProxiwashConstants.machineStates[item.state] === ProxiwashConstants.machineStates.DISPONIBLE) {
  316. if (isDryer)
  317. message += '\n' + i18n.t('proxiwashScreen.dryersTariff');
  318. else
  319. message += '\n' + i18n.t('proxiwashScreen.washersTariff');
  320. }
  321. return (
  322. <View style={{
  323. flex: 1,
  324. padding: 20
  325. }}>
  326. <Card.Title
  327. title={title}
  328. left={() => <Avatar.Icon
  329. icon={isDryer ? 'tumble-dryer' : 'washing-machine'}
  330. color={this.colors.text}
  331. style={{backgroundColor: 'transparent'}}/>}
  332. />
  333. <Card.Content>
  334. <Text>{message}</Text>
  335. </Card.Content>
  336. {button.onPress !== undefined ?
  337. <Card.Actions>
  338. <Button
  339. icon={button.icon}
  340. mode="contained"
  341. onPress={button.onPress}
  342. style={{marginLeft: 'auto', marginRight: 'auto'}}
  343. >
  344. {button.text}
  345. </Button>
  346. </Card.Actions> : null}
  347. </View>
  348. );
  349. }
  350. /**
  351. * Callback used when receiving modal ref
  352. *
  353. * @param ref
  354. */
  355. onModalRef(ref: Object) {
  356. this.modalRef = ref;
  357. }
  358. /**
  359. * Gets the number of machines available
  360. *
  361. * @param isDryer True if we are only checking for dryer, false for washers
  362. * @return {number} The number of machines available
  363. */
  364. getMachineAvailableNumber(isDryer: boolean) {
  365. let data;
  366. if (isDryer)
  367. data = this.fetchedData.dryers;
  368. else
  369. data = this.fetchedData.washers;
  370. let count = 0;
  371. for (let i = 0; i < data.length; i++) {
  372. if (ProxiwashConstants.machineStates[data[i].state] === ProxiwashConstants.machineStates["DISPONIBLE"])
  373. count += 1;
  374. }
  375. return count;
  376. }
  377. /**
  378. * Gets the section render item
  379. *
  380. * @param section The section to render
  381. * @return {*}
  382. */
  383. getRenderSectionHeader({section}: Object) {
  384. const isDryer = section.title === i18n.t('proxiwashScreen.dryers');
  385. const nbAvailable = this.getMachineAvailableNumber(isDryer);
  386. const subtitle = nbAvailable + ' ' + ((nbAvailable <= 1) ? i18n.t('proxiwashScreen.numAvailable')
  387. : i18n.t('proxiwashScreen.numAvailablePlural'));
  388. return (
  389. <View style={{
  390. flexDirection: 'row',
  391. marginLeft: 5,
  392. marginRight: 5,
  393. marginBottom: 10,
  394. marginTop: 20,
  395. }}>
  396. <Avatar.Icon
  397. icon={isDryer ? 'tumble-dryer' : 'washing-machine'}
  398. color={this.colors.primary}
  399. style={{backgroundColor: 'transparent'}}
  400. />
  401. <View style={{
  402. justifyContent: 'center',
  403. }}>
  404. <Text style={{
  405. fontSize: 20,
  406. fontWeight: 'bold',
  407. }}>
  408. {section.title}
  409. </Text>
  410. <Text style={{
  411. color: this.colors.subtitle,
  412. }}>
  413. {subtitle}
  414. </Text>
  415. </View>
  416. </View>
  417. );
  418. }
  419. /**
  420. * Gets the list item to be rendered
  421. *
  422. * @param item The object containing the item's FetchedData
  423. * @param section The object describing the current SectionList section
  424. * @returns {React.Node}
  425. */
  426. getRenderItem({item, section}: Object) {
  427. const isMachineRunning = ProxiwashConstants.machineStates[item.state] === ProxiwashConstants.machineStates["EN COURS"];
  428. let displayNumber = item.number;
  429. if (AprilFoolsManager.getInstance().isAprilFoolsEnabled())
  430. displayNumber = AprilFoolsManager.getProxiwashMachineDisplayNumber(parseInt(item.number));
  431. const machineName = (section.title === i18n.t('proxiwashScreen.dryers') ?
  432. i18n.t('proxiwashScreen.dryer') :
  433. i18n.t('proxiwashScreen.washer')) + ' n°' + displayNumber;
  434. const isDryer = section.title === i18n.t('proxiwashScreen.dryers');
  435. const onPress = this.showModal.bind(this, machineName, item, isDryer);
  436. let width = item.donePercent !== '' ? (parseInt(item.donePercent)).toString() + '%' : 0;
  437. if (ProxiwashConstants.machineStates[item.state] === '0')
  438. width = '100%';
  439. return (
  440. <ProxiwashListItem
  441. title={machineName}
  442. description={isMachineRunning ? item.startTime + '/' + item.endTime : ''}
  443. onPress={onPress}
  444. progress={width}
  445. state={item.state}
  446. isWatched={this.isMachineWatched(item.number)}
  447. isDryer={isDryer}
  448. statusText={stateStrings[ProxiwashConstants.machineStates[item.state]]}
  449. statusIcon={stateIcons[ProxiwashConstants.machineStates[item.state]]}
  450. height={LIST_ITEM_HEIGHT}
  451. />
  452. );
  453. }
  454. render() {
  455. const nav = this.props.navigation;
  456. return (
  457. <View>
  458. <Banner
  459. visible={this.state.bannerVisible}
  460. actions={[
  461. {
  462. label: 'OK',
  463. onPress: this.onHideBanner,
  464. },
  465. ]}
  466. icon={() => <Avatar.Icon
  467. icon={'information'}
  468. size={40}
  469. />}
  470. >
  471. {i18n.t('proxiwashScreen.enableNotificationsTip')}
  472. </Banner>
  473. <CustomModal onRef={this.onModalRef}>
  474. {this.state.modalCurrentDisplayItem}
  475. </CustomModal>
  476. <WebSectionList
  477. createDataset={this.createDataset}
  478. navigation={nav}
  479. fetchUrl={DATA_URL}
  480. renderItem={this.getRenderItem}
  481. renderSectionHeader={this.getRenderSectionHeader}
  482. autoRefreshTime={REFRESH_TIME}
  483. refreshOnFocus={true}
  484. updateData={this.state.machinesWatched.length}/>
  485. </View>
  486. );
  487. }
  488. }
  489. export default withTheme(ProxiwashScreen);