123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- // @flow
-
- import {checkNotifications, requestNotifications, RESULTS} from 'react-native-permissions';
- import AsyncStorageManager from "../managers/AsyncStorageManager";
- import i18n from "i18n-js";
-
- const PushNotification = require("react-native-push-notification");
-
- const reminderIdMultiplicator = 100;
-
- /**
- * Async function asking permission to send notifications to the user
- *
- * @returns {Promise}
- */
- export async function askPermissions() {
- return new Promise(((resolve, reject) => {
- checkNotifications().then(({status}) => {
- if (status === RESULTS.GRANTED)
- resolve();
- else if (status === RESULTS.BLOCKED)
- reject()
- else {
- requestNotifications().then(({status}) => {
- if (status === RESULTS.GRANTED)
- resolve();
- else
- reject();
- });
- }
- });
- }));
- }
-
- function createNotifications(machineID: string, date: Date) {
- let reminder = parseInt(AsyncStorageManager.getInstance().preferences.proxiwashNotifications.current);
- if (!isNaN(reminder)) {
- let id = reminderIdMultiplicator * parseInt(machineID);
- let reminderDate = new Date(date);
- reminderDate.setMinutes(reminderDate.getMinutes() - reminder);
- PushNotification.localNotificationSchedule({
- title: i18n.t("proxiwashScreen.notifications.machineRunningTitle", {time: reminder}),
- message: i18n.t("proxiwashScreen.notifications.machineRunningBody", {number: machineID}),
- id: id.toString(),
- date: reminderDate,
- });
- console.log("Setting up notifications for ", date, " and reminder for ", reminderDate);
- } else
- console.log("Setting up notifications for ", date);
-
- PushNotification.localNotificationSchedule({
- title: i18n.t("proxiwashScreen.notifications.machineFinishedTitle"),
- message: i18n.t("proxiwashScreen.notifications.machineFinishedBody", {number: machineID}),
- id: machineID,
- date: date,
- });
- }
-
- /**
- * Asks the server to enable/disable notifications for the specified machine
- *
- * @param machineID The machine ID
- * @param isEnabled True to enable notifications, false to disable
- * @param endDate
- */
- export async function setupMachineNotification(machineID: string, isEnabled: boolean, endDate: Date | null) {
- return new Promise((resolve, reject) => {
- if (isEnabled && endDate != null) {
- askPermissions()
- .then(() => {
- createNotifications(machineID, endDate);
- resolve();
- })
- .catch(() => {
- reject();
- });
- } else {
- PushNotification.cancelLocalNotifications({id: machineID});
- let reminderId = reminderIdMultiplicator * parseInt(machineID);
- PushNotification.cancelLocalNotifications({id: reminderId.toString()});
- resolve();
- }
- });
- }
|