Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

mobile: fix db initialization in background (#2322)

Ammar Ahmed9b7af876113f
diff --git a/apps/mobile/app/common/database/index.js b/apps/mobile/app/common/database/index.js
index e2becd022..989d31574 100644
--- a/apps/mobile/app/common/database/index.js
+++ b/apps/mobile/app/common/database/index.js
@@ -68,14 +68,3 @@ db.host(
ISSUES_HOST: "https://issues.streetwriters.co"
}
);
-
-export async function loadDatabase() {
- // if (!DB) {
- // let module = await import(/* webpackChunkName: "notes-core" */ 'notes-core/api/index');
- // DB = module.default;
- // }
- // db = new DB(Storage, Platform.OS === 'ios' ? EventSource : AndroidEventSource, filesystem);
- // if (DOMParser) {
- // await DOMParser.prepare();
- // }
-}
diff --git a/apps/mobile/app/components/launcher/index.js b/apps/mobile/app/components/launcher/index.js
index b7651ce07..a6a0fc007 100644
--- a/apps/mobile/app/components/launcher/index.js
+++ b/apps/mobile/app/components/launcher/index.js
@@ -17,12 +17,14 @@ 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 notifee from "@notifee/react-native";
import React, { useCallback, useEffect, useRef } from "react";
import { Platform, View } from "react-native";
import RNBootSplash from "react-native-bootsplash";
import { checkVersion } from "react-native-check-version";
+import Config from "react-native-config";
import { enabled } from "react-native-privacy-snapshot";
-import { DatabaseLogger, db, loadDatabase } from "../../common/database";
+import { DatabaseLogger, db } from "../../common/database";
import { useAppState } from "../../hooks/use-app-state";
import BiometricService from "../../services/biometrics";
import { eSendEvent, presentSheet } from "../../services/event-manager";
@@ -36,6 +38,7 @@ import { useSettingStore } from "../../stores/use-setting-store";
import { useThemeStore } from "../../stores/use-theme-store";
import { useUserStore } from "../../stores/use-user-store";
import { eOpenAnnouncementDialog } from "../../utils/events";
+import { getGithubVersion } from "../../utils/github-version";
import { SIZE } from "../../utils/size";
import { sleep } from "../../utils/time";
import { SVG } from "../auth/background";
@@ -50,9 +53,6 @@ import { SvgView } from "../ui/svg";
import Heading from "../ui/typography/heading";
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() {
@@ -69,7 +69,7 @@ const Launcher = React.memo(
const introCompleted = useSettingStore(
(state) => state.settings.introCompleted
);
- const dbInitCompleted = useRef(false);
+
const loadNotes = useCallback(async () => {
if (verifyUser) {
return;
@@ -80,28 +80,25 @@ const Launcher = React.memo(
initialize();
setImmediate(() => {
setLoading(false);
- if (!dbInitCompleted.current) {
- setImmediate(() => doAppLoadActions());
- }
});
});
});
- }, [doAppLoadActions, setLoading, verifyUser]);
+ }, [setLoading, verifyUser]);
const init = useCallback(async () => {
- if (!dbInitCompleted.current) {
+ if (!db.isInitialized) {
await RNBootSplash.hide({ fade: true });
- await loadDatabase();
DatabaseLogger.info("Initializing database");
await db.init();
- dbInitCompleted.current = true;
}
if (db.migrations.required() && !verifyUser) {
presentSheet({
component: <Migrate />,
onClose: async () => {
- await db.init();
+ if (!db.isInitialized) {
+ await db.init();
+ }
loadNotes();
},
disableClosing: true
@@ -120,9 +117,6 @@ const Launcher = React.memo(
if (!loading) {
doAppLoadActions();
}
- return () => {
- dbInitCompleted.current = false;
- };
}, [doAppLoadActions, loading]);
const doAppLoadActions = useCallback(async () => {
diff --git a/apps/mobile/app/hooks/use-app-events.js b/apps/mobile/app/hooks/use-app-events.js
index 8b3699eac..c580168a7 100644
--- a/apps/mobile/app/hooks/use-app-events.js
+++ b/apps/mobile/app/hooks/use-app-events.js
@@ -558,7 +558,7 @@ export const useAppEvents = () => {
let shareExtensionOpened = MMKV.getString("shareExtensionOpened");
if (notesAddedFromIntent) {
if (Platform.OS === "ios") {
- await db.init();
+ await db.initCollections();
await db.notes.init();
}
useNoteStore.getState().setNotes();
diff --git a/apps/mobile/app/screens/settings/settings-data.tsx b/apps/mobile/app/screens/settings/settings-data.tsx
index 2f51281c2..badfbc490 100644
--- a/apps/mobile/app/screens/settings/settings-data.tsx
+++ b/apps/mobile/app/screens/settings/settings-data.tsx
@@ -317,7 +317,6 @@ export const settingsGroups: SettingSection[] = [
await PremiumService.setPremiumStatus();
await BiometicService.resetCredentials();
MMKV.clearStore();
- await db.init();
await clearAllStores();
SettingsService.init();
setTimeout(() => {
diff --git a/apps/mobile/app/services/notifications.ts b/apps/mobile/app/services/notifications.ts
index 834576658..2800f5136 100644
--- a/apps/mobile/app/services/notifications.ts
+++ b/apps/mobile/app/services/notifications.ts
@@ -85,13 +85,20 @@ async function getNextMonthlyReminderDate(
return await getNextMonthlyReminderDate(reminder, dayjs().year() + 1);
}
+async function initDatabase(notes = true) {
+ if (db.isInitialized) return;
+ await db.initCollections();
+ if (notes) {
+ await db.notes?.init();
+ }
+}
+
const onEvent = async ({ type, detail }: Event) => {
const { notification, pressAction, input } = detail;
if (type === EventType.DELIVERED && Platform.OS === "android") {
const reminder = db.reminders?.reminder(notification?.id?.split("_")[0]);
if (reminder && reminder.recurringMode === "month") {
- await db.init();
- await db.notes?.init();
+ await initDatabase();
await scheduleNotification(reminder);
}
return;
@@ -100,8 +107,7 @@ const onEvent = async ({ type, detail }: Event) => {
notifee.decrementBadgeCount();
if (notification?.data?.type === "quickNote") return;
MMKV.removeItem("appState");
- await db.init();
- await db.notes?.init();
+ await initDatabase();
if (notification?.data?.type === "reminder") {
const reminder = db.reminders?.reminder(notification.id?.split("_")[0]);
await sleep(1000);
@@ -131,8 +137,7 @@ const onEvent = async ({ type, detail }: Event) => {
notifee.decrementBadgeCount();
switch (pressAction?.id) {
case "REMINDER_SNOOZE": {
- await db.init();
- await db.notes?.init();
+ await initDatabase();
const reminder = db.reminders?.reminder(
notification?.id?.split("_")[0]
);
@@ -151,8 +156,7 @@ const onEvent = async ({ type, detail }: Event) => {
break;
}
case "REMINDER_DISABLE": {
- await db.init();
- await db.notes?.init();
+ await initDatabase();
const reminder = db.reminders?.reminder(
notification?.id?.split("_")[0]
);
@@ -168,8 +172,7 @@ const onEvent = async ({ type, detail }: Event) => {
break;
}
case "UNPIN": {
- await db.init();
- await db.notes?.init();
+ await initDatabase();
remove(notification?.id as string);
const reminder = db.reminders?.reminder(
notification?.id?.split("_")[0]
@@ -198,7 +201,7 @@ const onEvent = async ({ type, detail }: Event) => {
reply_button_text: "Take note",
reply_placeholder_text: "Write something..."
});
- await db.init();
+ await initDatabase(false);
await db.notes?.add({
content: {
type: "tiptap",
diff --git a/apps/mobile/share/search.js b/apps/mobile/share/search.js
index 590dc92b8..1368e2d4f 100644
--- a/apps/mobile/share/search.js
+++ b/apps/mobile/share/search.js
@@ -32,7 +32,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import { db } from "../app/common/database";
import { getElevation } from "../app/utils";
-import { useShareStore } from "./store";
+import { initDatabase, useShareStore } from "./store";
const ListItem = ({ item, mode, close }) => {
const colors = useShareStore((state) => state.colors);
@@ -226,8 +226,7 @@ export const Search = ({ close, getKeyboardHeight, quicknote, mode }) => {
const onSearch = async () => {
if (!searchableItems.current) {
- await db.init();
- await db.notes.init();
+ await initDatabase();
searchableItems.current = get();
}
if (timer.current) {
@@ -248,8 +247,7 @@ export const Search = ({ close, getKeyboardHeight, quicknote, mode }) => {
useEffect(() => {
(async () => {
- await db.init();
- await db.notes.init();
+ await initDatabase();
searchableItems.current = get();
setSearchResults(searchableItems.current);
})();
diff --git a/apps/mobile/share/share.js b/apps/mobile/share/share.js
index 94068b2c3..bb94fdb6e 100644
--- a/apps/mobile/share/share.js
+++ b/apps/mobile/share/share.js
@@ -47,7 +47,7 @@ import { getElevation } from "../app/utils";
import { eOnLoadNote } from "../app/utils/events";
import { sleep } from "../app/utils/time";
import { Search } from "./search";
-import { useShareStore } from "./store";
+import { initDatabase, useShareStore } from "./store";
import { Editor } from "./editor";
const getLinkPreview = (url) => {
return getPreviewData(url, 5000);
@@ -314,8 +314,7 @@ const ShareView = ({ quicknote = false }) => {
const onPress = async () => {
setLoading(true);
- await db.init();
- await db.notes.init();
+ await initDatabase();
await sleep(1500);
if (!noteContent.current) return;
if (appendNote && !db.notes.note(appendNote.id)) {
diff --git a/apps/mobile/share/store.js b/apps/mobile/share/store.js
index f015ebf1e..395b416b3 100644
--- a/apps/mobile/share/store.js
+++ b/apps/mobile/share/store.js
@@ -25,6 +25,15 @@ import {
COLOR_SCHEME_LIGHT
} from "../app/utils/color-scheme";
import { MMKV } from "../app/common/database/mmkv";
+import { db } from "../app/common/database";
+
+export async function initDatabase() {
+ if (!db.isInitialized) {
+ // Only load collections in database.
+ await db.initCollections();
+ await db.notes.init();
+ }
+}
const StorageKeys = {
appendNote: "shareMenuAppendNote",
diff --git a/packages/core/api/index.js b/packages/core/api/index.js
index 1126d0767..914494af3 100644
--- a/packages/core/api/index.js
+++ b/packages/core/api/index.js
@@ -58,6 +58,7 @@ var NNEventSource;
// const DIFFERENCE_THRESHOLD = 20 * 1000;
// const MAX_TIME_ERROR_FAILURES = 5;
class Database {
+ isInitialized = false;
/**
*
* @param {any} storage
@@ -131,6 +132,19 @@ class Database {
this.pricing = new Pricing();
this.subscriptions = new Subscriptions(this.user.tokenManager);
+ await this.initCollections();
+
+ await this.settings.init();
+ await this.outbox.init();
+ await this.user.init();
+ await this.migrations.init();
+ this.isInitialized = true;
+ if (this.migrations.required()) {
+ logger.warn("Database migration is required.");
+ }
+ }
+
+ async initCollections() {
// collections
/** @type {Notes} */
this.notes = await Notes.new(this, "notes", true, true);
@@ -154,15 +168,6 @@ class Database {
this.relations = await Relations.new(this, "relations");
this.trash = new Trash(this);
-
- await this.settings.init();
- await this.outbox.init();
- await this.user.init();
- await this.migrations.init();
-
- if (this.migrations.required()) {
- logger.warn("Database migration is required.");
- }
}
disconnectSSE() {