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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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: AsyncStorageManager.getInstance().preferences.proxiwashShowBanner.current === '1',
  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. }
  96. /**
  97. * Callback used when pressing the about button.
  98. * This will open the ProxiwashAboutScreen.
  99. */
  100. onAboutPress = () => this.props.navigation.navigate('proxiwash-about');
  101. /**
  102. * Extracts the key for the given item
  103. *
  104. * @param item The item to extract the key from
  105. * @return {*} The extracted key
  106. */
  107. getKeyExtractor = (item: Machine) => item.number;
  108. /**
  109. * Setups notifications for the machine with the given ID.
  110. * One notification will be sent at the end of the program.
  111. * Another will be send a few minutes before the end, based on the value of reminderNotifTime
  112. *
  113. * @param machine The machine to watch
  114. */
  115. setupNotifications(machine: Machine) {
  116. if (!isMachineWatched(machine, this.state.machinesWatched)) {
  117. Notifications.setupMachineNotification(machine.number, true, getMachineEndDate(machine))
  118. .then(() => {
  119. this.saveNotificationToState(machine);
  120. })
  121. .catch(() => {
  122. this.showNotificationsDisabledWarning();
  123. });
  124. } else {
  125. Notifications.setupMachineNotification(machine.number, false, null)
  126. .then(() => {
  127. this.removeNotificationFromState(machine);
  128. });
  129. }
  130. }
  131. /**
  132. * Shows a warning telling the user notifications are disabled for the app
  133. */
  134. showNotificationsDisabledWarning() {
  135. Alert.alert(
  136. i18n.t("proxiwashScreen.modal.notificationErrorTitle"),
  137. i18n.t("proxiwashScreen.modal.notificationErrorDescription"),
  138. );
  139. }
  140. /**
  141. * Adds the given notifications associated to a machine ID to the watchlist, and saves the array to the preferences
  142. *
  143. * @param machine
  144. */
  145. saveNotificationToState(machine: Machine) {
  146. let data = this.state.machinesWatched;
  147. data.push(machine);
  148. this.saveNewWatchedList(data);
  149. }
  150. /**
  151. * Removes the given index from the watchlist array and saves it to preferences
  152. *
  153. * @param machine
  154. */
  155. removeNotificationFromState(machine: Machine) {
  156. let data = this.state.machinesWatched;
  157. for (let i = 0; i < data.length; i++) {
  158. if (data[i].number === machine.number && data[i].endTime === machine.endTime) {
  159. data.splice(i, 1);
  160. break;
  161. }
  162. }
  163. this.saveNewWatchedList(data);
  164. }
  165. saveNewWatchedList(list: Array<Machine>) {
  166. this.setState({machinesWatched: list});
  167. AsyncStorageManager.getInstance().savePref(
  168. AsyncStorageManager.getInstance().preferences.proxiwashWatchedMachines.key,
  169. JSON.stringify(list),
  170. );
  171. }
  172. /**
  173. * Creates the dataset to be used by the flatlist
  174. *
  175. * @param fetchedData
  176. * @return {*}
  177. */
  178. createDataset = (fetchedData: Object) => {
  179. let data = fetchedData;
  180. if (AprilFoolsManager.getInstance().isAprilFoolsEnabled()) {
  181. data = JSON.parse(JSON.stringify(fetchedData)); // Deep copy
  182. AprilFoolsManager.getNewProxiwashDryerOrderedList(data.dryers);
  183. AprilFoolsManager.getNewProxiwashWasherOrderedList(data.washers);
  184. }
  185. this.fetchedData = data;
  186. this.state.machinesWatched =
  187. getCleanedMachineWatched(this.state.machinesWatched, [...data.dryers, ...data.washers]);
  188. return [
  189. {
  190. title: i18n.t('proxiwashScreen.dryers'),
  191. icon: 'tumble-dryer',
  192. data: data.dryers === undefined ? [] : data.dryers,
  193. keyExtractor: this.getKeyExtractor
  194. },
  195. {
  196. title: i18n.t('proxiwashScreen.washers'),
  197. icon: 'washing-machine',
  198. data: data.washers === undefined ? [] : data.washers,
  199. keyExtractor: this.getKeyExtractor
  200. },
  201. ];
  202. };
  203. /**
  204. * Shows a modal for the given item
  205. *
  206. * @param title The title to use
  207. * @param item The item to display information for in the modal
  208. * @param isDryer True if the given item is a dryer
  209. */
  210. showModal = (title: string, item: Object, isDryer: boolean) => {
  211. this.setState({
  212. modalCurrentDisplayItem: this.getModalContent(title, item, isDryer)
  213. });
  214. if (this.modalRef) {
  215. this.modalRef.open();
  216. }
  217. };
  218. /**
  219. * Callback used when the user clicks on enable notifications for a machine
  220. *
  221. * @param machine The machine to set notifications for
  222. */
  223. onSetupNotificationsPress(machine: Machine) {
  224. if (this.modalRef) {
  225. this.modalRef.close();
  226. }
  227. this.setupNotifications(machine);
  228. }
  229. /**
  230. * Generates the modal content.
  231. * This shows information for the given machine.
  232. *
  233. * @param title The title to use
  234. * @param item The item to display information for in the modal
  235. * @param isDryer True if the given item is a dryer
  236. * @return {*}
  237. */
  238. getModalContent(title: string, item: Object, isDryer: boolean) {
  239. let button = {
  240. text: i18n.t("proxiwashScreen.modal.ok"),
  241. icon: '',
  242. onPress: undefined
  243. };
  244. let message = modalStateStrings[item.state];
  245. const onPress = this.onSetupNotificationsPress.bind(this, item);
  246. if (item.state === ProxiwashConstants.machineStates.RUNNING) {
  247. let remainingTime = parseInt(item.remainingTime)
  248. if (remainingTime < 0)
  249. remainingTime = 0;
  250. button =
  251. {
  252. text: isMachineWatched(item, this.state.machinesWatched) ?
  253. i18n.t("proxiwashScreen.modal.disableNotifications") :
  254. i18n.t("proxiwashScreen.modal.enableNotifications"),
  255. icon: '',
  256. onPress: onPress
  257. }
  258. ;
  259. message = i18n.t('proxiwashScreen.modal.running',
  260. {
  261. start: item.startTime,
  262. end: item.endTime,
  263. remaining: remainingTime
  264. });
  265. } else if (item.state === ProxiwashConstants.machineStates.AVAILABLE) {
  266. if (isDryer)
  267. message += '\n' + i18n.t('proxiwashScreen.dryersTariff');
  268. else
  269. message += '\n' + i18n.t('proxiwashScreen.washersTariff');
  270. }
  271. return (
  272. <View style={{
  273. flex: 1,
  274. padding: 20
  275. }}>
  276. <Card.Title
  277. title={title}
  278. left={() => <Avatar.Icon
  279. icon={isDryer ? 'tumble-dryer' : 'washing-machine'}
  280. color={this.props.theme.colors.text}
  281. style={{backgroundColor: 'transparent'}}/>}
  282. />
  283. <Card.Content>
  284. <Text>{message}</Text>
  285. </Card.Content>
  286. {button.onPress !== undefined ?
  287. <Card.Actions>
  288. <Button
  289. icon={button.icon}
  290. mode="contained"
  291. onPress={button.onPress}
  292. style={{marginLeft: 'auto', marginRight: 'auto'}}
  293. >
  294. {button.text}
  295. </Button>
  296. </Card.Actions> : null}
  297. </View>
  298. );
  299. }
  300. /**
  301. * Callback used when receiving modal ref
  302. *
  303. * @param ref
  304. */
  305. onModalRef = (ref: Object) => {
  306. this.modalRef = ref;
  307. };
  308. /**
  309. * Gets the number of machines available
  310. *
  311. * @param isDryer True if we are only checking for dryer, false for washers
  312. * @return {number} The number of machines available
  313. */
  314. getMachineAvailableNumber(isDryer: boolean) {
  315. let data;
  316. if (isDryer)
  317. data = this.fetchedData.dryers;
  318. else
  319. data = this.fetchedData.washers;
  320. let count = 0;
  321. for (let i = 0; i < data.length; i++) {
  322. if (data[i].state === ProxiwashConstants.machineStates.AVAILABLE)
  323. count += 1;
  324. }
  325. return count;
  326. }
  327. /**
  328. * Gets the section render item
  329. *
  330. * @param section The section to render
  331. * @return {*}
  332. */
  333. getRenderSectionHeader = ({section}: Object) => {
  334. const isDryer = section.title === i18n.t('proxiwashScreen.dryers');
  335. const nbAvailable = this.getMachineAvailableNumber(isDryer);
  336. return (
  337. <ProxiwashSectionHeader
  338. title={section.title}
  339. nbAvailable={nbAvailable}
  340. isDryer={isDryer}/>
  341. );
  342. };
  343. /**
  344. * Gets the list item to be rendered
  345. *
  346. * @param item The object containing the item's FetchedData
  347. * @param section The object describing the current SectionList section
  348. * @returns {React.Node}
  349. */
  350. getRenderItem = ({item, section}: Object) => {
  351. const isDryer = section.title === i18n.t('proxiwashScreen.dryers');
  352. return (
  353. <ProxiwashListItem
  354. item={item}
  355. onPress={this.showModal}
  356. isWatched={isMachineWatched(item, this.state.machinesWatched)}
  357. isDryer={isDryer}
  358. height={LIST_ITEM_HEIGHT}
  359. />
  360. );
  361. };
  362. render() {
  363. const nav = this.props.navigation;
  364. const {containerPaddingTop} = this.props.collapsibleStack;
  365. return (
  366. <View
  367. style={{flex: 1}}
  368. >
  369. <View style={{
  370. position: "absolute",
  371. width: "100%",
  372. height: "100%",
  373. }}>
  374. <WebSectionList
  375. createDataset={this.createDataset}
  376. navigation={nav}
  377. fetchUrl={DATA_URL}
  378. renderItem={this.getRenderItem}
  379. renderSectionHeader={this.getRenderSectionHeader}
  380. autoRefreshTime={REFRESH_TIME}
  381. refreshOnFocus={true}
  382. updateData={this.state.machinesWatched.length}/>
  383. </View>
  384. <Banner
  385. style={{marginTop: containerPaddingTop,}}
  386. visible={this.state.bannerVisible}
  387. actions={[
  388. {
  389. label: 'OK',
  390. onPress: this.onHideBanner,
  391. },
  392. ]}
  393. icon={() => <Avatar.Icon
  394. icon={'information'}
  395. size={40}
  396. />}
  397. >
  398. {i18n.t('proxiwashScreen.enableNotificationsTip')}
  399. </Banner>
  400. <CustomModal onRef={this.onModalRef}>
  401. {this.state.modalCurrentDisplayItem}
  402. </CustomModal>
  403. </View>
  404. );
  405. }
  406. }
  407. export default withCollapsible(withTheme(ProxiwashScreen));