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 17KB

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