Browse Source

Added local notifications on android

Arnaud Vergnet 3 years ago
parent
commit
087331258a

+ 0
- 1
.gitignore View File

10
 web-report/
10
 web-report/
11
 /.expo-shared/
11
 /.expo-shared/
12
 /package-lock.json
12
 /package-lock.json
13
-/passwords.json
14
 
13
 
15
 !/.idea/
14
 !/.idea/
16
 /.idea/*
15
 /.idea/*

+ 0
- 2
App.js View File

9
 import ThemeManager from './src/managers/ThemeManager';
9
 import ThemeManager from './src/managers/ThemeManager';
10
 import {NavigationContainer} from '@react-navigation/native';
10
 import {NavigationContainer} from '@react-navigation/native';
11
 import MainNavigator from './src/navigation/MainNavigator';
11
 import MainNavigator from './src/navigation/MainNavigator';
12
-import {initExpoToken} from "./src/utils/Notifications";
13
 import {Provider as PaperProvider} from 'react-native-paper';
12
 import {Provider as PaperProvider} from 'react-native-paper';
14
 import AprilFoolsManager from "./src/managers/AprilFoolsManager";
13
 import AprilFoolsManager from "./src/managers/AprilFoolsManager";
15
 import Update from "./src/constants/Update";
14
 import Update from "./src/constants/Update";
145
      */
144
      */
146
     loadAssetsAsync = async () => {
145
     loadAssetsAsync = async () => {
147
         await this.storageManager.loadPreferences();
146
         await this.storageManager.loadPreferences();
148
-        await initExpoToken();
149
         try {
147
         try {
150
             await ConnectionManager.getInstance().recoverLogin();
148
             await ConnectionManager.getInstance().recoverLogin();
151
         } catch (e) {
149
         } catch (e) {

+ 30
- 1
android/app/src/main/AndroidManifest.xml View File

1
 <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="fr.amicaleinsat.application">
1
 <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="fr.amicaleinsat.application">
2
     <uses-permission android:name="android.permission.INTERNET"/>
2
     <uses-permission android:name="android.permission.INTERNET"/>
3
     <uses-permission android:name="android.permission.CAMERA"/>
3
     <uses-permission android:name="android.permission.CAMERA"/>
4
-    <uses-permission android:name="android.permission.VIBRATE"/>
4
+    <uses-permission android:name="android.permission.WAKE_LOCK" />
5
+    <uses-permission android:name="android.permission.VIBRATE" />
6
+    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
5
     <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
7
     <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
6
 
8
 
7
     <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
9
     <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
14
             android:theme="@style/AppTheme"
16
             android:theme="@style/AppTheme"
15
             android:usesCleartextTraffic="true"
17
             android:usesCleartextTraffic="true"
16
     >
18
     >
19
+<!--        NOTIFICATIONS -->
20
+        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_name"
21
+                    android:value="reminders"/>
22
+        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_description"
23
+                    android:value="reminders"/>
24
+        <!-- Change the resource name to your App's accent color - or any other color you want -->
25
+        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_color"
26
+                    android:resource="@color/colorPrimary"/> <!-- or @android:color/{name} to use a standard color -->
27
+
28
+        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
29
+        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
30
+            <intent-filter>
31
+                <action android:name="android.intent.action.BOOT_COMPLETED" />
32
+            </intent-filter>
33
+        </receiver>
34
+
35
+        <service
36
+                android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
37
+                android:exported="false" >
38
+            <intent-filter>
39
+                <action android:name="com.google.firebase.MESSAGING_EVENT" />
40
+            </intent-filter>
41
+        </service>
42
+
43
+<!--        END NOTIFICATIONS-->
44
+
45
+
17
         <meta-data android:name="com.facebook.sdk.AutoInitEnabled" android:value="false"/>
46
         <meta-data android:name="com.facebook.sdk.AutoInitEnabled" android:value="false"/>
18
         <meta-data android:name="com.facebook.sdk.AutoLogAppEventsEnabled" android:value="false"/>
47
         <meta-data android:name="com.facebook.sdk.AutoLogAppEventsEnabled" android:value="false"/>
19
         <meta-data android:name="com.facebook.sdk.AdvertiserIDCollectionEnabled" android:value="false"/>
48
         <meta-data android:name="com.facebook.sdk.AdvertiserIDCollectionEnabled" android:value="false"/>

+ 3
- 1
android/app/src/release/AndroidManifest.xml View File

3
 
3
 
4
     <uses-permission android:name="android.permission.INTERNET"/>
4
     <uses-permission android:name="android.permission.INTERNET"/>
5
     <uses-permission android:name="android.permission.CAMERA" />
5
     <uses-permission android:name="android.permission.CAMERA" />
6
+    <uses-permission android:name="android.permission.WAKE_LOCK"/>
6
     <uses-permission android:name="android.permission.VIBRATE"/>
7
     <uses-permission android:name="android.permission.VIBRATE"/>
8
+    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
7
     <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
9
     <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
8
 
10
 
9
     <uses-permission tools:node="remove" android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
11
     <uses-permission tools:node="remove" android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
21
     <uses-permission tools:node="remove" android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
23
     <uses-permission tools:node="remove" android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
22
     <uses-permission tools:node="remove" android:name="android.permission.WRITE_SETTINGS"/>
24
     <uses-permission tools:node="remove" android:name="android.permission.WRITE_SETTINGS"/>
23
     <uses-permission tools:node="remove" android:name="android.permission.ACCESS_NETWORK_STATE"/>
25
     <uses-permission tools:node="remove" android:name="android.permission.ACCESS_NETWORK_STATE"/>
24
-    <uses-permission tools:node="remove" android:name="android.permission.WAKE_LOCK"/>
26
+
25
 </manifest>
27
 </manifest>

+ 1
- 0
package.json View File

44
     "react-native-modalize": "^1.3.6",
44
     "react-native-modalize": "^1.3.6",
45
     "react-native-paper": "^3.8.0",
45
     "react-native-paper": "^3.8.0",
46
     "react-native-permissions": "^2.1.3",
46
     "react-native-permissions": "^2.1.3",
47
+    "react-native-push-notification": "^3.3.0",
47
     "react-native-reanimated": "~1.7.0",
48
     "react-native-reanimated": "~1.7.0",
48
     "react-native-render-html": "^4.1.2",
49
     "react-native-render-html": "^4.1.2",
49
     "react-native-safe-area-context": "0.7.3",
50
     "react-native-safe-area-context": "0.7.3",

+ 5
- 0
src/managers/AsyncStorageManager.js View File

69
             default: '1',
69
             default: '1',
70
             current: '',
70
             current: '',
71
         },
71
         },
72
+        proxiwashWatchedMachines: {
73
+            key: 'proxiwashWatchedMachines',
74
+            default: '[]',
75
+            current: '',
76
+        },
72
         planexShowBanner: {
77
         planexShowBanner: {
73
             key: 'planexShowBanner',
78
             key: 'planexShowBanner',
74
             default: '1',
79
             default: '1',

+ 0
- 5
src/screens/Other/SettingsScreen.js View File

5
 import ThemeManager from '../../managers/ThemeManager';
5
 import ThemeManager from '../../managers/ThemeManager';
6
 import i18n from "i18n-js";
6
 import i18n from "i18n-js";
7
 import AsyncStorageManager from "../../managers/AsyncStorageManager";
7
 import AsyncStorageManager from "../../managers/AsyncStorageManager";
8
-import {setMachineReminderNotificationTime} from "../../utils/Notifications";
9
 import {Card, List, Switch, ToggleButton} from 'react-native-paper';
8
 import {Card, List, Switch, ToggleButton} from 'react-native-paper';
10
 import {Appearance} from "react-native-appearance";
9
 import {Appearance} from "react-native-appearance";
11
 import AnimatedAccordion from "../../components/Animations/AnimatedAccordion";
10
 import AnimatedAccordion from "../../components/Animations/AnimatedAccordion";
49
             this.setState({
48
             this.setState({
50
                 proxiwashNotifPickerSelected: value
49
                 proxiwashNotifPickerSelected: value
51
             });
50
             });
52
-            let intVal = 0;
53
-            if (value !== 'never')
54
-                intVal = parseInt(value);
55
-            setMachineReminderNotificationTime(intVal);
56
         }
51
         }
57
     };
52
     };
58
 
53
 

+ 106
- 80
src/screens/Proxiwash/ProxiwashScreen.js View File

6
 import WebSectionList from "../../components/Screens/WebSectionList";
6
 import WebSectionList from "../../components/Screens/WebSectionList";
7
 import * as Notifications from "../../utils/Notifications";
7
 import * as Notifications from "../../utils/Notifications";
8
 import AsyncStorageManager from "../../managers/AsyncStorageManager";
8
 import AsyncStorageManager from "../../managers/AsyncStorageManager";
9
-// import * as Expo from "expo";
10
 import {Avatar, Banner, Button, Card, Text, withTheme} from 'react-native-paper';
9
 import {Avatar, Banner, Button, Card, Text, withTheme} from 'react-native-paper';
11
 import ProxiwashListItem from "../../components/Lists/Proxiwash/ProxiwashListItem";
10
 import ProxiwashListItem from "../../components/Lists/Proxiwash/ProxiwashListItem";
12
 import ProxiwashConstants from "../../constants/ProxiwashConstants";
11
 import ProxiwashConstants from "../../constants/ProxiwashConstants";
15
 import MaterialHeaderButtons, {Item} from "../../components/Overrides/CustomHeaderButton";
14
 import MaterialHeaderButtons, {Item} from "../../components/Overrides/CustomHeaderButton";
16
 import ProxiwashSectionHeader from "../../components/Lists/Proxiwash/ProxiwashSectionHeader";
15
 import ProxiwashSectionHeader from "../../components/Lists/Proxiwash/ProxiwashSectionHeader";
17
 import {withCollapsible} from "../../utils/withCollapsible";
16
 import {withCollapsible} from "../../utils/withCollapsible";
17
+import type {CustomTheme} from "../../managers/ThemeManager";
18
+import {Collapsible} from "react-navigation-collapsible";
19
+import {StackNavigationProp} from "@react-navigation/stack";
20
+
21
+const PushNotification = require("react-native-push-notification");
18
 
22
 
19
 const DATA_URL = "https://etud.insa-toulouse.fr/~amicale_app/washinsa/washinsa.json";
23
 const DATA_URL = "https://etud.insa-toulouse.fr/~amicale_app/washinsa/washinsa.json";
20
 
24
 
23
 const REFRESH_TIME = 1000 * 10; // Refresh every 10 seconds
27
 const REFRESH_TIME = 1000 * 10; // Refresh every 10 seconds
24
 const LIST_ITEM_HEIGHT = 64;
28
 const LIST_ITEM_HEIGHT = 64;
25
 
29
 
30
+type machine = {
31
+    number: string,
32
+    state: string,
33
+    startTime: string,
34
+    endTime: string,
35
+    donePercent: string,
36
+    remainingTime: string,
37
+}
38
+
26
 type Props = {
39
 type Props = {
27
-    navigation: Object,
28
-    route: Object,
29
-    theme: Object,
30
-    collapsibleStack: Object,
40
+    navigation: StackNavigationProp,
41
+    theme: CustomTheme,
42
+    collapsibleStack: Collapsible,
31
 }
43
 }
32
 
44
 
33
 type State = {
45
 type State = {
34
     refreshing: boolean,
46
     refreshing: boolean,
35
     modalCurrentDisplayItem: React.Node,
47
     modalCurrentDisplayItem: React.Node,
36
-    machinesWatched: Array<string>,
48
+    machinesWatched: Array<machine>,
37
     bannerVisible: boolean,
49
     bannerVisible: boolean,
38
 };
50
 };
39
 
51
 
47
     modalRef: Object;
59
     modalRef: Object;
48
 
60
 
49
     fetchedData: Object;
61
     fetchedData: Object;
62
+    allMachines: Array<machine>;
50
 
63
 
51
     state = {
64
     state = {
52
         refreshing: false,
65
         refreshing: false,
53
         modalCurrentDisplayItem: null,
66
         modalCurrentDisplayItem: null,
54
-        machinesWatched: [],
67
+        machinesWatched: JSON.parse(AsyncStorageManager.getInstance().preferences.proxiwashWatchedMachines.current),
55
         bannerVisible: AsyncStorageManager.getInstance().preferences.proxiwashShowBanner.current === '1',
68
         bannerVisible: AsyncStorageManager.getInstance().preferences.proxiwashShowBanner.current === '1',
56
     };
69
     };
57
 
70
 
65
         modalStateStrings[ProxiwashConstants.machineStates["EN COURS"]] = i18n.t('proxiwashScreen.modal.running');
78
         modalStateStrings[ProxiwashConstants.machineStates["EN COURS"]] = i18n.t('proxiwashScreen.modal.running');
66
         modalStateStrings[ProxiwashConstants.machineStates.HS] = i18n.t('proxiwashScreen.modal.broken');
79
         modalStateStrings[ProxiwashConstants.machineStates.HS] = i18n.t('proxiwashScreen.modal.broken');
67
         modalStateStrings[ProxiwashConstants.machineStates.ERREUR] = i18n.t('proxiwashScreen.modal.error');
80
         modalStateStrings[ProxiwashConstants.machineStates.ERREUR] = i18n.t('proxiwashScreen.modal.error');
81
+        this.allMachines = [];
68
     }
82
     }
69
 
83
 
70
     /**
84
     /**
86
         this.props.navigation.setOptions({
100
         this.props.navigation.setOptions({
87
             headerRight: this.getAboutButton,
101
             headerRight: this.getAboutButton,
88
         });
102
         });
89
-        if (AsyncStorageManager.getInstance().preferences.expoToken.current !== '') {
90
-            // Get latest watchlist from server
91
-            Notifications.getMachineNotificationWatchlist((fetchedList) => {
92
-                this.setState({machinesWatched: fetchedList})
93
-            });
94
-            // Get updated watchlist after received notification
95
-            // Expo.Notifications.addListener(() => {
96
-            //     Notifications.getMachineNotificationWatchlist((fetchedList) => {
97
-            //         this.setState({machinesWatched: fetchedList})
98
-            //     });
99
-            // });
100
-            // if (Platform.OS === 'android') {
101
-            //     Expo.Notifications.createChannelAndroidAsync('reminders', {
102
-            //         name: 'Reminders',
103
-            //         priority: 'max',
104
-            //         vibrate: [0, 250, 250, 250],
105
-            //     });
106
-            // }
107
-        }
108
     }
103
     }
109
 
104
 
110
     /**
105
     /**
129
      * @param item The item to extract the key from
124
      * @param item The item to extract the key from
130
      * @return {*} The extracted key
125
      * @return {*} The extracted key
131
      */
126
      */
132
-    getKeyExtractor(item: Object) {
133
-        return item !== undefined ? item.number : undefined;
127
+    getKeyExtractor = (item: machine) => item.number;
128
+
129
+
130
+    getMachineEndDate(machine: machine) {
131
+        const array = machine.endTime.split(":");
132
+        let date = new Date();
133
+        date.setHours(parseInt(array[0]), parseInt(array[1]));
134
+        if (date < new Date())
135
+            date.setDate(date.getDate() + 1);
136
+        return date;
134
     }
137
     }
135
 
138
 
136
     /**
139
     /**
138
      * One notification will be sent at the end of the program.
141
      * One notification will be sent at the end of the program.
139
      * Another will be send a few minutes before the end, based on the value of reminderNotifTime
142
      * Another will be send a few minutes before the end, based on the value of reminderNotifTime
140
      *
143
      *
141
-     * @param machineId The machine's ID
144
+     * @param machine The machine to watch
142
      * @returns {Promise<void>}
145
      * @returns {Promise<void>}
143
      */
146
      */
144
-    setupNotifications(machineId: string) {
145
-        if (AsyncStorageManager.getInstance().preferences.expoToken.current !== '') {
146
-            if (!this.isMachineWatched(machineId)) {
147
-                Notifications.setupMachineNotification(machineId, true);
148
-                this.saveNotificationToState(machineId);
149
-            } else
150
-                this.disableNotification(machineId);
147
+    setupNotifications(machine: machine) {
148
+        if (!this.isMachineWatched(machine)) {
149
+            Notifications.setupMachineNotification(machine.number, true, this.getMachineEndDate(machine))
150
+                .then(() => {
151
+                    this.saveNotificationToState(machine);
152
+                })
153
+                .catch(() => {
154
+                    this.showNotificationsDisabledWarning();
155
+                });
151
         } else {
156
         } else {
152
-            this.showNotificationsDisabledWarning();
157
+            Notifications.setupMachineNotification(machine.number, false)
158
+                .then(() => {
159
+                    this.removeNotificationFromState(machine);
160
+                });
153
         }
161
         }
154
     }
162
     }
155
 
163
 
164
     }
172
     }
165
 
173
 
166
     /**
174
     /**
167
-     * Stops scheduled notifications for the machine of the given ID.
168
-     * This will also remove the notification if it was already shown.
169
-     *
170
-     * @param machineId The machine's ID
171
-     */
172
-    disableNotification(machineId: string) {
173
-        let data = this.state.machinesWatched;
174
-        if (data.length > 0) {
175
-            let arrayIndex = data.indexOf(machineId);
176
-            if (arrayIndex !== -1) {
177
-                Notifications.setupMachineNotification(machineId, false);
178
-                this.removeNotificationFroState(arrayIndex);
179
-            }
180
-        }
181
-    }
182
-
183
-    /**
184
      * Adds the given notifications associated to a machine ID to the watchlist, and saves the array to the preferences
175
      * Adds the given notifications associated to a machine ID to the watchlist, and saves the array to the preferences
185
      *
176
      *
186
-     * @param machineId
177
+     * @param machine
187
      */
178
      */
188
-    saveNotificationToState(machineId: string) {
179
+    saveNotificationToState(machine: machine) {
189
         let data = this.state.machinesWatched;
180
         let data = this.state.machinesWatched;
190
-        data.push(machineId);
191
-        this.updateNotificationState(data);
181
+        data.push(machine);
182
+        this.saveNewWatchedList(data);
192
     }
183
     }
193
 
184
 
194
     /**
185
     /**
195
      * Removes the given index from the watchlist array and saves it to preferences
186
      * Removes the given index from the watchlist array and saves it to preferences
196
      *
187
      *
197
-     * @param index
188
+     * @param machine
198
      */
189
      */
199
-    removeNotificationFroState(index: number) {
190
+    removeNotificationFromState(machine: machine) {
200
         let data = this.state.machinesWatched;
191
         let data = this.state.machinesWatched;
201
-        data.splice(index, 1);
202
-        this.updateNotificationState(data);
192
+        for (let i = 0; i < data.length; i++) {
193
+            if (data[i].number === machine.number && data[i].endTime === machine.endTime) {
194
+                data.splice(i, 1);
195
+                break;
196
+            }
197
+        }
198
+        this.saveNewWatchedList(data);
203
     }
199
     }
204
 
200
 
205
-    /**
206
-     * Sets the given fetchedData as the watchlist
207
-     *
208
-     * @param data
209
-     */
210
-    updateNotificationState(data: Array<Object>) {
211
-        this.setState({machinesWatched: data});
201
+    saveNewWatchedList(list: Array<machine>) {
202
+        this.setState({machinesWatched: list});
203
+        AsyncStorageManager.getInstance().savePref(
204
+            AsyncStorageManager.getInstance().preferences.proxiwashWatchedMachines.key,
205
+            JSON.stringify(list),
206
+        );
212
     }
207
     }
213
 
208
 
214
     /**
209
     /**
215
      * Checks whether the machine of the given ID has scheduled notifications
210
      * Checks whether the machine of the given ID has scheduled notifications
216
      *
211
      *
217
-     * @param machineID The machine's ID
212
+     * @param machine
218
      * @returns {boolean}
213
      * @returns {boolean}
219
      */
214
      */
220
-    isMachineWatched(machineID: string) {
221
-        return this.state.machinesWatched.indexOf(machineID) !== -1;
215
+    isMachineWatched(machine: machine) {
216
+        let watched = false;
217
+        const list = this.state.machinesWatched;
218
+        for (let i = 0; i < list.length; i++) {
219
+            if (list[i].number === machine.number && list[i].endTime === machine.endTime) {
220
+                watched = true;
221
+                break;
222
+            }
223
+        }
224
+        return watched;
225
+    }
226
+
227
+    getMachineOfId(id: string) {
228
+        for (let i = 0; i < this.allMachines.length; i++) {
229
+            if (this.allMachines[i].number === id)
230
+                return this.allMachines[i];
231
+        }
232
+        return null;
233
+    }
234
+
235
+    getCleanedMachineWatched() {
236
+        const list = this.state.machinesWatched;
237
+        let newList = [];
238
+        for (let i = 0; i < list.length; i++) {
239
+            let machine = this.getMachineOfId(list[i].number);
240
+            if (machine !== null
241
+                && list[i].number === machine.number && list[i].endTime === machine.endTime
242
+                && ProxiwashConstants.machineStates[list[i].state] === ProxiwashConstants.machineStates["EN COURS"]) {
243
+                newList.push(machine);
244
+            }
245
+        }
246
+        return newList;
222
     }
247
     }
223
 
248
 
224
     /**
249
     /**
234
             AprilFoolsManager.getNewProxiwashDryerOrderedList(data.dryers);
259
             AprilFoolsManager.getNewProxiwashDryerOrderedList(data.dryers);
235
             AprilFoolsManager.getNewProxiwashWasherOrderedList(data.washers);
260
             AprilFoolsManager.getNewProxiwashWasherOrderedList(data.washers);
236
         }
261
         }
237
-        this.fetchedData = fetchedData;
238
-
262
+        this.fetchedData = data;
263
+        this.allMachines = [...data.dryers, ...data.washers];
264
+        this.state.machinesWatched = this.getCleanedMachineWatched();
239
         return [
265
         return [
240
             {
266
             {
241
                 title: i18n.t('proxiwashScreen.dryers'),
267
                 title: i18n.t('proxiwashScreen.dryers'),
271
     /**
297
     /**
272
      * Callback used when the user clicks on enable notifications for a machine
298
      * Callback used when the user clicks on enable notifications for a machine
273
      *
299
      *
274
-     * @param machineId The machine's id to set notifications for
300
+     * @param machine The machine to set notifications for
275
      */
301
      */
276
-    onSetupNotificationsPress(machineId: string) {
302
+    onSetupNotificationsPress(machine: machine) {
277
         if (this.modalRef) {
303
         if (this.modalRef) {
278
             this.modalRef.close();
304
             this.modalRef.close();
279
         }
305
         }
280
-        this.setupNotifications(machineId)
306
+        this.setupNotifications(machine);
281
     }
307
     }
282
 
308
 
283
     /**
309
     /**
296
             onPress: undefined
322
             onPress: undefined
297
         };
323
         };
298
         let message = modalStateStrings[ProxiwashConstants.machineStates[item.state]];
324
         let message = modalStateStrings[ProxiwashConstants.machineStates[item.state]];
299
-        const onPress = this.onSetupNotificationsPress.bind(this, item.number);
325
+        const onPress = this.onSetupNotificationsPress.bind(this, item);
300
         if (ProxiwashConstants.machineStates[item.state] === ProxiwashConstants.machineStates["EN COURS"]) {
326
         if (ProxiwashConstants.machineStates[item.state] === ProxiwashConstants.machineStates["EN COURS"]) {
301
             button =
327
             button =
302
                 {
328
                 {
409
         return (
435
         return (
410
             <ProxiwashListItem
436
             <ProxiwashListItem
411
                 item={item}
437
                 item={item}
412
-                onPress={this.showModal}
413
-                isWatched={this.isMachineWatched(item.number)}
438
+                onPress={() => this.onSetupNotificationsPress(item)}
439
+                isWatched={this.isMachineWatched(item)}
414
                 isDryer={isDryer}
440
                 isDryer={isDryer}
415
                 height={LIST_ITEM_HEIGHT}
441
                 height={LIST_ITEM_HEIGHT}
416
             />
442
             />

+ 26
- 95
src/utils/Notifications.js View File

1
 // @flow
1
 // @flow
2
 
2
 
3
 import {checkNotifications, requestNotifications, RESULTS} from 'react-native-permissions';
3
 import {checkNotifications, requestNotifications, RESULTS} from 'react-native-permissions';
4
-// import {Notifications} from 'expo';
5
-import AsyncStorageManager from "../managers/AsyncStorageManager";
6
-import LocaleManager from "../managers/LocaleManager";
7
-import passwords from "../../passwords";
8
 
4
 
9
-const EXPO_TOKEN_SERVER = 'https://etud.insa-toulouse.fr/~amicale_app/expo_notifications/save_token.php';
5
+const PushNotification = require("react-native-push-notification");
10
 
6
 
11
 /**
7
 /**
12
  * Async function asking permission to send notifications to the user
8
  * Async function asking permission to send notifications to the user
32
     }));
28
     }));
33
 }
29
 }
34
 
30
 
35
-/**
36
- * Save expo token to allow sending notifications to this device.
37
- * This token is unique for each device and won't change.
38
- * It only needs to be fetched once, then it will be saved in storage.
39
- *
40
- * @return {Promise<void>}
41
- */
42
-export async function initExpoToken() {
43
-    // let token = AsyncStorageManager.getInstance().preferences.expoToken.current;
44
-    // if (token === '') {
45
-    //     askPermissions().then(() => {
46
-    //         Notifications.getExpoPushTokenAsync().then((token) => {
47
-    //             // Save token for instant use later on
48
-    //             AsyncStorageManager.getInstance().savePref(AsyncStorageManager.getInstance().preferences.expoToken.key, token);
49
-    //         });
50
-    //     });
51
-    // }
52
-}
53
-
54
-/**
55
- * Gets the machines watched from the server
56
- *
57
- * @param callback Function to execute with the fetched data
58
- */
59
-export function getMachineNotificationWatchlist(callback: Function) {
60
-    let token = AsyncStorageManager.getInstance().preferences.expoToken.current;
61
-    if (token !== '') {
62
-        let data = {
63
-            function: 'get_machine_watchlist',
64
-            password: passwords.expoNotifications,
65
-            token: token,
66
-        };
67
-        fetch(EXPO_TOKEN_SERVER, {
68
-            method: 'POST',
69
-            headers: new Headers({
70
-                Accept: 'application/json',
71
-                'Content-Type': 'application/json',
72
-            }),
73
-            body: JSON.stringify(data) // <-- Post parameters
74
-        }).then((response) => response.json())
75
-            .then((responseJson) => {
76
-                callback(responseJson);
77
-            });
78
-    }
31
+function createNotifications(machineID: string, date: Date) {
32
+    PushNotification.localNotificationSchedule({
33
+        title: "Title",
34
+        message: "Message",
35
+        id: machineID,
36
+        date: date,
37
+    });
79
 }
38
 }
80
 
39
 
81
 /**
40
 /**
83
  *
42
  *
84
  * @param machineID The machine ID
43
  * @param machineID The machine ID
85
  * @param isEnabled True to enable notifications, false to disable
44
  * @param isEnabled True to enable notifications, false to disable
45
+ * @param endDate
86
  */
46
  */
87
-export function setupMachineNotification(machineID: string, isEnabled: boolean) {
88
-    let token = AsyncStorageManager.getInstance().preferences.expoToken.current;
89
-    if (token !== '') {
90
-        let data = {
91
-            function: 'setup_machine_notification',
92
-            password: passwords.expoNotifications,
93
-            locale: LocaleManager.getCurrentLocale(),
94
-            token: token,
95
-            machine_id: machineID,
96
-            enabled: isEnabled
97
-        };
98
-        fetch(EXPO_TOKEN_SERVER, {
99
-            method: 'POST',
100
-            headers: new Headers({
101
-                Accept: 'application/json',
102
-                'Content-Type': 'application/json',
103
-            }),
104
-            body: JSON.stringify(data) // <-- Post parameters
105
-        });
106
-    }
107
-}
108
-
109
-/**
110
- * Sends the selected reminder time for notifications to the server
111
- *
112
- * @param time The reminder time to use
113
- */
114
-export function setMachineReminderNotificationTime(time: number) {
115
-    let token = AsyncStorageManager.getInstance().preferences.expoToken.current;
116
-    if (token !== '') {
117
-        let data = {
118
-            function: 'set_machine_reminder',
119
-            password: passwords.expoNotifications,
120
-            token: token,
121
-            time: time,
122
-        };
123
-        fetch(EXPO_TOKEN_SERVER, {
124
-            method: 'POST',
125
-            headers: new Headers({
126
-                Accept: 'application/json',
127
-                'Content-Type': 'application/json',
128
-            }),
129
-            body: JSON.stringify(data) // <-- Post parameters
130
-        });
131
-    }
132
-}
47
+export async function setupMachineNotification(machineID: string, isEnabled: boolean, endDate?: Date) {
48
+    return new Promise((resolve, reject) => {
49
+        if (isEnabled && endDate != null) {
50
+            askPermissions()
51
+                .then(() => {
52
+                    createNotifications(machineID, endDate);
53
+                    resolve();
54
+                })
55
+                .catch(() => {
56
+                    reject();
57
+                });
58
+        } else {
59
+            PushNotification.cancelLocalNotifications({id: machineID});
60
+            resolve();
61
+        }
62
+    });
63
+}

Loading…
Cancel
Save