mobile: add background sync

This commit is contained in:
ammarahm-ed
2023-01-17 15:12:23 +05:00
committed by Ammar Ahmed
parent 1ffb6b3c57
commit f1f8a35ea5
11 changed files with 257 additions and 33 deletions

View File

@@ -25,10 +25,7 @@ import { enabled } from "react-native-privacy-snapshot";
import { DatabaseLogger, db, loadDatabase } from "../../common/database";
import { useAppState } from "../../hooks/use-app-state";
import BiometricService from "../../services/biometrics";
import {
eSendEvent,
presentSheet
} from "../../services/event-manager";
import { eSendEvent, presentSheet } from "../../services/event-manager";
import { setRateAppMessage } from "../../services/message";
import PremiumService from "../../services/premium";
import SettingsService from "../../services/settings";
@@ -55,6 +52,8 @@ import Paragraph from "../ui/typography/paragraph";
import { Walkthrough } from "../walkthroughs";
import Config from "react-native-config";
import { getGithubVersion } from "../../utils/github-version";
import notifee from "@notifee/react-native";
const Launcher = React.memo(
function Launcher() {
@@ -133,6 +132,7 @@ const Launcher = React.memo(
eSendEvent("session_expired");
return;
}
notifee.setBadgeCount(0);
await useMessageStore.getState().setAnnouncement();
if (NewFeature.present()) return;
if (await checkAppUpdateAvailable()) return;

View File

@@ -0,0 +1,121 @@
/*
This file is part of the Notesnook project (https://notesnook.com/)
Copyright (C) 2023 Streetwriters (Private) Limited
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import BackgroundFetch from "react-native-background-fetch";
import { DatabaseLogger, db } from "../common/database";
import { AppState, AppRegistry } from "react-native";
import Notifications from "./notifications";
import SettingsService from "./settings";
let backgroundFetchStarted = false;
async function start() {
if (backgroundFetchStarted) return;
backgroundFetchStarted = true;
// BackgroundFetch event handler.
const onEvent = async (taskId: string) => {
console.log("[BackgroundFetch] task: ", taskId, AppState.currentState);
// Do your background work...
await onBackgroundSyncStarted();
// IMPORTANT: You must signal to the OS that your task is complete.
BackgroundFetch.finish(taskId);
};
// Timeout callback is executed when your Task has exceeded its allowed running-time.
// You must stop what you're doing immediately BackgroundFetch.finish(taskId)
const onTimeout = async (taskId: string) => {
console.warn("[BackgroundFetch] TIMEOUT: ", taskId);
BackgroundFetch.finish(taskId);
};
// Initialize BackgroundFetch only once when component mounts.
const status = await BackgroundFetch.configure(
{
minimumFetchInterval: 15,
enableHeadless: true,
startOnBoot: true,
stopOnTerminate: false,
requiredNetworkType: BackgroundFetch.NETWORK_TYPE_ANY
},
onEvent,
onTimeout
);
DatabaseLogger.info(`[BackgroundFetch] configure status: ${status}`);
console.log(`[BackgroundFetch] configure status: ${status}`);
}
const task = async (event: { taskId: string; timeout: boolean }) => {
// Get task id from event {}:
const taskId = event.taskId;
const isTimeout = event.timeout; // <-- true when your background-time has expired.
if (isTimeout) {
console.log("[BackgroundFetch] Headless TIMEOUT:", taskId);
BackgroundFetch.finish(taskId);
return;
}
console.log(
"[BackgroundFetch HeadlessTask] start: ",
taskId,
AppState.currentState
);
await onBackgroundSyncStarted();
BackgroundFetch.finish(taskId);
};
BackgroundFetch.registerHeadlessTask(task);
async function onBackgroundSyncStarted() {
try {
console.log("Background Sync", "start");
await db.init();
const user = await db.user?.getUser();
if (user) {
await db.sync(true, false);
}
await Notifications.setupReminders();
console.log("Background Sync", "end");
} catch (e) {
DatabaseLogger.error(e as Error);
console.log("Background Sync Error", (e as Error).message);
}
}
const onBoot = async () => {
try {
console.log("BOOT TASK STARTED");
await db.init();
await Notifications.setupReminders();
SettingsService.init();
if (SettingsService.get().notifNotes) {
Notifications.pinQuickNote(false);
}
console.log("BOOT TASK COMPLETE");
} catch (e) {
console.log(e);
}
};
AppRegistry.registerHeadlessTask(
"com.streetwriters.notesnook.BOOT_TASK",
() => {
return onBoot;
}
);
export const BackgroundSync = {
start
};

View File

@@ -97,6 +97,7 @@ const onEvent = async ({ type, detail }: Event) => {
return;
}
if (type === EventType.PRESS) {
notifee.decrementBadgeCount();
if (notification?.data?.type === "quickNote") return;
editorState().movedAway = false;
MMKV.removeItem("appState");
@@ -125,8 +126,11 @@ const onEvent = async ({ type, detail }: Event) => {
}
if (type === EventType.ACTION_PRESS) {
notifee.decrementBadgeCount();
switch (pressAction?.id) {
case "REMINDER_SNOOZE": {
await db.init();
await db.notes?.init();
const reminder = db.reminders?.reminder(
notification?.id?.split("_")[0]
);
@@ -145,6 +149,8 @@ const onEvent = async ({ type, detail }: Event) => {
break;
}
case "REMINDER_DISABLE": {
await db.init();
await db.notes?.init();
const reminder = db.reminders?.reminder(
notification?.id?.split("_")[0]
);
@@ -160,6 +166,8 @@ const onEvent = async ({ type, detail }: Event) => {
break;
}
case "UNPIN": {
await db.init();
await db.notes?.init();
remove(notification?.id as string);
const reminder = db.reminders?.reminder(
notification?.id?.split("_")[0]
@@ -254,21 +262,25 @@ async function scheduleNotification(
try {
const { title, description, priority } = reminder;
await clearAllPendingTriggersForId(reminder.id);
await remove(reminder.id);
if (reminder.disabled) return;
if (reminder.disabled) {
remove(reminder.id);
return;
}
const triggers = await getTriggers(reminder);
console.log(triggers);
if (!triggers && reminder.mode === "permanent") {
displayNotification({
id: reminder.id,
title: title,
message: description || "",
ongoing: true,
subtitle: description || "",
actions: ["UNPIN"]
});
if (reminder.mode === "permanent") {
const notifications = await get();
const pinned = notifications.findIndex((i) => i.id === reminder.id) > -1;
if (!pinned) {
displayNotification({
id: reminder.id,
title: title,
message: description || "",
ongoing: true,
subtitle: description || "",
actions: ["UNPIN"]
});
}
return;
}
await setupIOSCategories();
@@ -320,6 +332,7 @@ async function scheduleNotification(
id: "default",
mainComponent: "notesnook"
},
badgeCount: 1,
actions: androidActions,
sound: notificationSound?.url,
style: !description
@@ -332,6 +345,7 @@ async function scheduleNotification(
ios: {
interruptionLevel: "active",
criticalVolume: 1.0,
badgeCount: 1,
critical:
reminder.priority === "silent" || reminder.priority === "urgent"
? false
@@ -370,7 +384,8 @@ async function getChannelId(id: "silent" | "vibrate" | "urgent" | "default") {
case "default":
return await notifee.createChannel({
id: "com.streetwriters.notesnook",
name: "Default"
name: "Default",
vibration: false
});
case "silent":
return await notifee.createChannel({
@@ -419,6 +434,7 @@ async function displayNotification({
id?: string;
}) {
if (!(await checkAndRequestPermissions())) return;
try {
await notifee.displayNotification({
id: id,
@@ -430,6 +446,7 @@ async function displayNotification({
},
android: {
ongoing: ongoing,
smallIcon: "ic_stat_name",
localOnly: true,
channelId: await getChannelId("default"),
autoCancel: false,
@@ -733,6 +750,9 @@ async function setupReminders(checkNeedsScheduling = false) {
const triggers = await notifee.getTriggerNotifications();
for (const reminder of reminders) {
if (reminder.mode === "permanent") {
await scheduleNotification(reminder);
}
const pending = triggers.filter((t) =>
t.notification.id?.startsWith(reminder.id)
);

View File

@@ -54,4 +54,7 @@
# Wix
-keep class org.apache.commons.lang3.** { *; }
-keep class org.apache.commons.io.** { *; }
-keep class org.apache.commons.io.** { *; }
# Background fetch
-keep class com.transistorsoft.rnbackgroundfetch.HeadlessTask { *; }

View File

@@ -130,6 +130,8 @@
android:stopWithTask="false" />
<service android:name="com.asterinet.react.bgactions.RNBackgroundActionsTask" />
<service android:name="com.streetwriters.notesnook.BootTaskService" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
@@ -150,22 +152,13 @@
android:resource="@xml/file_viewer_provider_paths" />
</provider>
<!-- Change the value to true to enable pop-up for in foreground on receiving remote notifications (for prevent duplicating while showing local notifications set this to false) -->
<meta-data android:name="com.dieam.reactnativepushnotification.notification_foreground"
android:value="false"/>
<!-- Change the resource name to your App's accent color - or any other color you want -->
<meta-data android:name="com.dieam.reactnativepushnotification.notification_color"
android:resource="@android:color/white"/> <!-- or @android:color/{name} to use a standard color -->
<receiver android:exported="true" android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
<receiver android:exported="true" android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
<receiver android:exported="true" android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
<receiver android:exported="true" android:name=".BootRecieverService" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
</application>

View File

@@ -0,0 +1,48 @@
package com.streetwriters.notesnook;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.app.ActivityManager;
import com.facebook.react.HeadlessJsTaskService;
import java.util.List;
public class BootRecieverService extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (!isAppOnForeground((context))) {
/**
We will start our service and send extra info about
network connections
**/
Intent serviceIntent = new Intent(context, BootTaskService.class);
context.startService(serviceIntent);
HeadlessJsTaskService.acquireWakeLockNow(context);
}
}
private boolean isAppOnForeground(Context context) {
/**
We need to check if app is in foreground otherwise the app will crash.
http://stackoverflow.com/questions/8489993/check-android-application-is-in-foreground-or-not
**/
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses =
activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = context.getPackageName();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance ==
ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,20 @@
package com.streetwriters.notesnook;
import android.content.Intent;
import com.facebook.react.HeadlessJsTaskService;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.jstasks.HeadlessJsTaskConfig;
import javax.annotation.Nullable;
public class BootTaskService extends HeadlessJsTaskService {
@Override
protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) {
return new HeadlessJsTaskConfig(
"com.streetwriters.notesnook.BOOT_TASK",
Arguments.createMap(),
30000, // timeout for the task
false // optional: defines whether or not the task is allowed in foreground. Default is false
);
}
}

View File

@@ -69,5 +69,8 @@ allprojects {
maven { url 'https://www.jitpack.io' }
maven {
url("${project(':react-native-background-fetch').projectDir}/libs")
}
}
}

View File

@@ -8,6 +8,8 @@ import Config from 'react-native-config';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import appJson from './app.json';
import Notifications from '../app/services/notifications';
import {BackgroundSync} from '../app/services/background-sync';
const appName = appJson.name;
if (Config.isTesting) {
Date.prototype.toLocaleString = () => 'XX-XX-XX';
@@ -20,6 +22,7 @@ if (__DEV__) {
LogBox.ignoreAllLogs();
}
let NotesnookShare;
BackgroundSync.start();
Notifications.init();
let QuickNoteIOS;

View File

@@ -56,7 +56,8 @@
"react-native-modal-datetime-picker":"14.0.0",
"@react-native-community/datetimepicker":"6.6.0",
"react-native-date-picker": "4.2.6",
"react-native-notification-sounds": "0.5.5"
"react-native-notification-sounds": "0.5.5",
"react-native-background-fetch": "4.1.7"
},
"devDependencies": {
"@babel/core": "^7.12.9",

View File

@@ -1,12 +1,12 @@
{
"name": "@notesnook/mobile",
"version": "2.3.0",
"version": "2.4.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "@notesnook/mobile",
"version": "2.3.0",
"version": "2.4.0",
"license": "GPL-3.0-or-later",
"workspaces": [
"native/",
@@ -78,6 +78,7 @@
"react": "18.0.0",
"react-native": "0.69.7",
"react-native-background-actions": "^2.6.6",
"react-native-background-fetch": "4.1.7",
"react-native-begin-background-task": "https://github.com/blockfirm/react-native-begin-background-task.git",
"react-native-bootsplash": "^4.1.4",
"react-native-config": "^1.4.6",
@@ -17976,6 +17977,11 @@
"react-native": ">=0.47.0"
}
},
"node_modules/react-native-background-fetch": {
"version": "4.1.7",
"resolved": "https://registry.npmjs.org/react-native-background-fetch/-/react-native-background-fetch-4.1.7.tgz",
"integrity": "sha512-dFY/AOZbEH+ldwZvq/UhhWI5+dyBYL1Xo5wqy6u5DLH+ef8jLIrwKQRmfLAWiP5BtZe6ktA55HM19X39qHoKEQ=="
},
"node_modules/react-native-begin-background-task": {
"version": "0.1.0",
"resolved": "git+ssh://git@github.com/blockfirm/react-native-begin-background-task.git#c2aa793249db6cc6298a812905f955a99b864e78",
@@ -24359,6 +24365,7 @@
"react-native": "0.69.7",
"react-native-actions-shortcuts": "^1.0.1",
"react-native-background-actions": "^2.6.6",
"react-native-background-fetch": "4.1.7",
"react-native-begin-background-task": "https://github.com/blockfirm/react-native-begin-background-task.git",
"react-native-bootsplash": "^4.1.4",
"react-native-bundle-visualizer": "^3.1.1",
@@ -34852,6 +34859,11 @@
"eventemitter3": "^4.0.7"
}
},
"react-native-background-fetch": {
"version": "4.1.7",
"resolved": "https://registry.npmjs.org/react-native-background-fetch/-/react-native-background-fetch-4.1.7.tgz",
"integrity": "sha512-dFY/AOZbEH+ldwZvq/UhhWI5+dyBYL1Xo5wqy6u5DLH+ef8jLIrwKQRmfLAWiP5BtZe6ktA55HM19X39qHoKEQ=="
},
"react-native-begin-background-task": {
"version": "git+ssh://git@github.com/blockfirm/react-native-begin-background-task.git#c2aa793249db6cc6298a812905f955a99b864e78",
"from": "react-native-begin-background-task@https://github.com/blockfirm/react-native-begin-background-task.git"