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.

Notifications.js 2.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // @flow
  2. import {checkNotifications, requestNotifications, RESULTS} from 'react-native-permissions';
  3. import AsyncStorageManager from "../managers/AsyncStorageManager";
  4. const PushNotification = require("react-native-push-notification");
  5. const reminderIdMultiplicator = 100;
  6. /**
  7. * Async function asking permission to send notifications to the user
  8. *
  9. * @returns {Promise}
  10. */
  11. export async function askPermissions() {
  12. return new Promise(((resolve, reject) => {
  13. checkNotifications().then(({status}) => {
  14. if (status === RESULTS.GRANTED)
  15. resolve();
  16. else if (status === RESULTS.BLOCKED)
  17. reject()
  18. else {
  19. requestNotifications().then(({status}) => {
  20. if (status === RESULTS.GRANTED)
  21. resolve();
  22. else
  23. reject();
  24. });
  25. }
  26. });
  27. }));
  28. }
  29. function createNotifications(machineID: string, date: Date) {
  30. let reminder = parseInt(AsyncStorageManager.getInstance().preferences.proxiwashNotifications.current);
  31. if (!isNaN(reminder)) {
  32. let id = reminderIdMultiplicator * parseInt(machineID);
  33. let reminderDate = new Date(date);
  34. reminderDate.setMinutes(reminderDate.getMinutes() - reminder);
  35. PushNotification.localNotificationSchedule({
  36. title: "Title",
  37. message: "Message",
  38. id: id.toString(),
  39. date: reminderDate,
  40. });
  41. console.log("Setting up notifications for ", date, " and reminder for ", reminderDate);
  42. } else
  43. console.log("Setting up notifications for ", date);
  44. PushNotification.localNotificationSchedule({
  45. title: "Title",
  46. message: "Message",
  47. id: machineID,
  48. date: date,
  49. });
  50. }
  51. /**
  52. * Asks the server to enable/disable notifications for the specified machine
  53. *
  54. * @param machineID The machine ID
  55. * @param isEnabled True to enable notifications, false to disable
  56. * @param endDate
  57. */
  58. export async function setupMachineNotification(machineID: string, isEnabled: boolean, endDate?: Date) {
  59. return new Promise((resolve, reject) => {
  60. if (isEnabled && endDate != null) {
  61. askPermissions()
  62. .then(() => {
  63. createNotifications(machineID, endDate);
  64. resolve();
  65. })
  66. .catch(() => {
  67. reject();
  68. });
  69. } else {
  70. PushNotification.cancelLocalNotifications({id: machineID});
  71. let reminderId = reminderIdMultiplicator * parseInt(machineID);
  72. PushNotification.cancelLocalNotifications({id: reminderId.toString()});
  73. resolve();
  74. }
  75. });
  76. }