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

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