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

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