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.

NotificationsManager.js 7.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. // @flow
  2. import * as Permissions from 'expo-permissions';
  3. import {Notifications} from 'expo';
  4. import AsyncStorageManager from "./AsyncStorageManager";
  5. import LocaleManager from "./LocaleManager";
  6. import passwords from "../passwords";
  7. const EXPO_TOKEN_SERVER = 'https://srv-falcon.etud.insa-toulouse.fr/~amicale_app/expo_notifications/save_token.php';
  8. /**
  9. * Static class used to manage notifications sent to the user
  10. */
  11. export default class NotificationsManager {
  12. /**
  13. * Async function asking permission to send notifications to the user
  14. *
  15. * @returns {Promise}
  16. */
  17. static async askPermissions() {
  18. const {status: existingStatus} = await Permissions.getAsync(Permissions.NOTIFICATIONS);
  19. let finalStatus = existingStatus;
  20. if (existingStatus !== 'granted') {
  21. const {status} = await Permissions.askAsync(Permissions.NOTIFICATIONS);
  22. finalStatus = status;
  23. }
  24. return finalStatus === 'granted';
  25. }
  26. /**
  27. * Async function sending a notification without delay to the user
  28. *
  29. * @param title {String} Notification title
  30. * @param body {String} Notification body text
  31. * @returns {Promise<import("react").ReactText>} Notification Id
  32. */
  33. static async sendNotificationImmediately(title: string, body: string) {
  34. await NotificationsManager.askPermissions();
  35. return await Notifications.presentLocalNotificationAsync({
  36. title: title,
  37. body: body,
  38. });
  39. };
  40. /**
  41. * Async function sending notification at the specified time
  42. *
  43. * @param title Notification title
  44. * @param body Notification body text
  45. * @param time Time at which we should send the notification
  46. * @param data Data to send with the notification, used for listeners
  47. * @param androidChannelID
  48. * @returns {Promise<import("react").ReactText>} Notification Id
  49. */
  50. static async scheduleNotification(title: string, body: string, time: number, data: Object, androidChannelID: string): Promise<string> {
  51. await NotificationsManager.askPermissions();
  52. let date = new Date();
  53. date.setTime(time);
  54. return Notifications.scheduleLocalNotificationAsync(
  55. {
  56. title: title,
  57. body: body,
  58. data: data,
  59. ios: { // configuration for iOS.
  60. sound: true
  61. },
  62. android: { // configuration for Android.
  63. channelId: androidChannelID,
  64. }
  65. },
  66. {
  67. time: time,
  68. },
  69. );
  70. };
  71. /**
  72. * Async function used to cancel the notification of a specific ID
  73. * @param notificationID {Number} The notification ID
  74. * @returns {Promise}
  75. */
  76. static async cancelScheduledNotification(notificationID: number) {
  77. await Notifications.cancelScheduledNotificationAsync(notificationID);
  78. }
  79. /**
  80. * Save expo token to allow sending notifications to this device.
  81. * This token is unique for each device and won't change.
  82. * It only needs to be fetched once, then it will be saved in storage.
  83. *
  84. * @return {Promise<void>}
  85. */
  86. static async initExpoToken() {
  87. let token = AsyncStorageManager.getInstance().preferences.expoToken.current;
  88. if (token === '') {
  89. await NotificationsManager.askPermissions();
  90. let expoToken = await Notifications.getExpoPushTokenAsync();
  91. // Save token for instant use later on
  92. AsyncStorageManager.getInstance().savePref(AsyncStorageManager.getInstance().preferences.expoToken.key, expoToken);
  93. }
  94. }
  95. static async forceExpoTokenUpdate() {
  96. await NotificationsManager.askPermissions();
  97. let expoToken = await Notifications.getExpoPushTokenAsync();
  98. // Save token for instant use later on
  99. AsyncStorageManager.getInstance().savePref(AsyncStorageManager.getInstance().preferences.expoToken.key, expoToken);
  100. }
  101. static getMachineNotificationWatchlist(callback: Function) {
  102. let token = AsyncStorageManager.getInstance().preferences.expoToken.current;
  103. if (token === '') {
  104. throw Error('Expo token not available');
  105. }
  106. let data = {
  107. function: 'get_machine_watchlist',
  108. password: passwords.expoNotifications,
  109. token: token,
  110. };
  111. fetch(EXPO_TOKEN_SERVER, {
  112. method: 'POST',
  113. headers: new Headers({
  114. Accept: 'application/json',
  115. 'Content-Type': 'application/json',
  116. }),
  117. body: JSON.stringify(data) // <-- Post parameters
  118. })
  119. .then((response) => response.json())
  120. .then((responseJson) => {
  121. callback(responseJson);
  122. })
  123. .catch((error) => {
  124. console.log(error);
  125. });
  126. }
  127. /**
  128. * Ask the server to enable/disable notifications for the specified machine
  129. *
  130. * @param machineID
  131. * @param isEnabled
  132. */
  133. static setupMachineNotification(machineID: string, isEnabled: boolean) {
  134. let token = AsyncStorageManager.getInstance().preferences.expoToken.current;
  135. if (token === '') {
  136. throw Error('Expo token not available');
  137. }
  138. let data = {
  139. function: 'setup_machine_notification',
  140. password: passwords.expoNotifications,
  141. locale: LocaleManager.getCurrentLocale(),
  142. token: token,
  143. machine_id: machineID,
  144. enabled: isEnabled
  145. };
  146. fetch(EXPO_TOKEN_SERVER, {
  147. method: 'POST',
  148. headers: new Headers({
  149. Accept: 'application/json',
  150. 'Content-Type': 'application/json',
  151. }),
  152. body: JSON.stringify(data) // <-- Post parameters
  153. })
  154. .then((response) => response.text())
  155. .then((responseText) => {
  156. console.log(responseText);
  157. })
  158. .catch((error) => {
  159. console.log(error);
  160. });
  161. }
  162. /**
  163. * Send the selected reminder time for notifications to the server
  164. * @param time
  165. */
  166. static setMachineReminderNotificationTime(time: number) {
  167. let token = AsyncStorageManager.getInstance().preferences.expoToken.current;
  168. if (token === '') {
  169. throw Error('Expo token not available');
  170. }
  171. let data = {
  172. function: 'set_machine_reminder',
  173. password: passwords.expoNotifications,
  174. token: token,
  175. time: time,
  176. };
  177. fetch(EXPO_TOKEN_SERVER, {
  178. method: 'POST',
  179. headers: new Headers({
  180. Accept: 'application/json',
  181. 'Content-Type': 'application/json',
  182. }),
  183. body: JSON.stringify(data) // <-- Post parameters
  184. })
  185. .then((response) => response.text())
  186. .then((responseText) => {
  187. console.log(responseText);
  188. })
  189. .catch((error) => {
  190. console.log(error);
  191. });
  192. }
  193. }