A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
mobile: add support for attachments cache
Ammar Ahmed6ec9370afb81
diff --git a/apps/mobile/app/common/filesystem/compress.js b/apps/mobile/app/common/filesystem/compress.jsindex 3695ebbf9..cc32a1160 100644--- a/apps/mobile/app/common/filesystem/compress.js+++ b/apps/mobile/app/common/filesystem/compress.js@@ -20,7 +20,6 @@ import { Dimensions, Image, Platform } from "react-native";import ImageResizer from "@bam.tech/react-native-image-resizer";import RNFetchBlob from "react-native-blob-util";-console.log("hello world");/*** Scale down & compress images to screen width* for loading in editor.diff --git a/apps/mobile/app/common/filesystem/download-attachment.js b/apps/mobile/app/common/filesystem/download-attachment.jsindex eb4110ada..4a18e7e0f 100644--- a/apps/mobile/app/common/filesystem/download-attachment.js+++ b/apps/mobile/app/common/filesystem/download-attachment.js@@ -18,24 +18,20 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.*/import Sodium from "@ammarahmed/react-native-sodium";-import {- getFileNameWithExtension,- isImage,- isDocument-} from "@notesnook/core/dist/utils/filename";+import { getFileNameWithExtension } from "@notesnook/core/dist/utils/filename";import React from "react";import { Platform } from "react-native";+import RNFetchBlob from "react-native-blob-util";import * as ScopedStorage from "react-native-scoped-storage";import { subscribe, zip } from "react-native-zip-archive";-import RNFetchBlob from "react-native-blob-util";import { ShareComponent } from "../../components/sheets/export-notes/share";import { ToastManager, presentSheet } from "../../services/event-manager";import { useAttachmentStore } from "../../stores/use-attachment-store";+import { IOS_APPGROUPID } from "../../utils/constants";import { DatabaseLogger, db } from "../database";import Storage from "../database/storage";-import { cacheDir, copyFileAsync, releasePermissions } from "./utils";import { createCacheDir, exists } from "./io";-import { IOS_APPGROUPID } from "../../utils/constants";+import { cacheDir, copyFileAsync, releasePermissions } from "./utils";export const FileDownloadStatus = {Success: 1,diff --git a/apps/mobile/app/common/filesystem/download.js b/apps/mobile/app/common/filesystem/download.jsindex c8b423be6..024d22b16 100644--- a/apps/mobile/app/common/filesystem/download.js+++ b/apps/mobile/app/common/filesystem/download.js@@ -35,8 +35,8 @@ export async function downloadFile(filename, data, cancelToken) {DatabaseLogger.log(`Downloading ${filename}`);await createCacheDir();let { url, headers } = data;- let path = `${cacheDir}/${filename}`;-+ let tempFilePath = `${cacheDir}/${filename}_temp`;+ let originalFilePath = `${cacheDir}/${filename}`;try {if (await exists(filename)) {DatabaseLogger.log(`File Exists already: ${filename}`);@@ -66,7 +66,7 @@ export async function downloadFile(filename, data, cancelToken) {let totalSize = 0;DatabaseLogger.log(`Download starting: ${filename}`);let request = RNFetchBlob.config({- path: path,+ path: tempFilePath,IOSBackgroundTask: true}).fetch("GET", downloadUrl, null)@@ -81,13 +81,21 @@ export async function downloadFile(filename, data, cancelToken) {cancelToken.cancel = () => {useAttachmentStore.getState().remove(filename);request.cancel();+ RNFetchBlob.fs.unlink(tempFilePath).catch(console.log);DatabaseLogger.log(`Download cancelled: ${filename}`);};let response = await request;+await fileCheck(response, totalSize);let status = response.info().status;useAttachmentStore.getState().remove(filename);+ await RNFetchBlob.fs.mv(tempFilePath, originalFilePath);++ if (!(await exists(filename))) {+ throw new Error("File size mismatch");+ }+return status >= 200 && status < 300;} catch (e) {if (e.message !== "canceled" && !e.message.includes("NoSuchKey")) {@@ -106,7 +114,8 @@ export async function downloadFile(filename, data, cancelToken) {}useAttachmentStore.getState().remove(filename);- RNFetchBlob.fs.unlink(path).catch(console.log);+ RNFetchBlob.fs.unlink(tempFilePath).catch(console.log);+ RNFetchBlob.fs.unlink(originalFilePath).catch(console.log);DatabaseLogger.error(e, {url,headersdiff --git a/apps/mobile/app/common/filesystem/index.js b/apps/mobile/app/common/filesystem/index.jsindex f7b0c64ca..bb6099c9e 100644--- a/apps/mobile/app/common/filesystem/index.js+++ b/apps/mobile/app/common/filesystem/index.js@@ -27,7 +27,9 @@ import {hashBase64,clearCache,deleteCacheFileByName,- deleteCacheFileByPath+ deleteCacheFileByPath,+ bulkExists,+ getCacheSize} from "./io";import { uploadFile } from "./upload";import { cancelable } from "./utils";@@ -45,5 +47,7 @@ export default {checkAttachment,clearCache,deleteCacheFileByName,- deleteCacheFileByPath+ deleteCacheFileByPath,+ bulkExists,+ getCacheSize};diff --git a/apps/mobile/app/common/filesystem/io.js b/apps/mobile/app/common/filesystem/io.jsindex ae3d26dbb..6a0fa289e 100644--- a/apps/mobile/app/common/filesystem/io.js+++ b/apps/mobile/app/common/filesystem/io.js@@ -20,6 +20,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.import Sodium from "@ammarahmed/react-native-sodium";import { Platform } from "react-native";import RNFetchBlob from "react-native-blob-util";+import { eSendEvent } from "../../services/event-manager";import { IOS_APPGROUPID } from "../../utils/constants";import { DatabaseLogger, db } from "../database";import { cacheDir, cacheDirOld, getRandomId } from "./utils";@@ -159,10 +160,9 @@ export async function migrateFilesFromCache() {}export async function clearCache() {- const files = await RNFetchBlob.fs.ls(cacheDir);- for (const file of files) {- await RNFetchBlob.fs.unlink(file).catch(console.log);- }+ await RNFetchBlob.fs.unlink(cacheDir).catch(console.log);+ await createCacheDir();+ eSendEvent("cache-cleared");}export async function deleteCacheFileByPath(path) {@@ -224,3 +224,29 @@ export async function exists(filename) {}return exists;}++export async function bulkExists(files) {+ const cacheFiles = await RNFetchBlob.fs.ls(cacheDir);+ let missingFiles = files.filter((file) => !cacheFiles.includes(file));++ if (Platform.OS === "ios") {+ const iosAppGroup =+ Platform.OS === "ios"+ ? await RNFetchBlob.fs.pathForAppGroup(IOS_APPGROUPID)+ : null;+ const appGroupFiles = await RNFetchBlob.fs.ls(iosAppGroup);+ missingFiles = missingFiles.filter((file) => !appGroupFiles.includes(file));+ }++ return missingFiles;+}++export async function getCacheSize() {+ const stat = await RNFetchBlob.fs.lstat(`file://` + cacheDir);+ let total = 0;+ console.log("Total files", stat.length);+ stat.forEach((s) => {+ total += parseInt(s.size);+ });+ return total;+}diff --git a/apps/mobile/app/common/filesystem/upload.js b/apps/mobile/app/common/filesystem/upload.jsindex b511b016c..54631ebf5 100644--- a/apps/mobile/app/common/filesystem/upload.js+++ b/apps/mobile/app/common/filesystem/upload.js@@ -17,16 +17,15 @@ You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*/+import { Platform } from "react-native";import RNFetchBlob from "react-native-blob-util";+import { ToastManager } from "../../services/event-manager";import { useAttachmentStore } from "../../stores/use-attachment-store";-import { DatabaseLogger, db } from "../database";-import { cacheDir } from "./utils";-import { isImage, isDocument } from "@notesnook/core/dist/utils/filename";-import { Platform } from "react-native";import { IOS_APPGROUPID } from "../../utils/constants";-import { createCacheDir } from "./io";+import { DatabaseLogger, db } from "../database";import { getUploadedFileSize } from "./download";-import { ToastManager } from "../../services/event-manager";+import { createCacheDir } from "./io";+import { cacheDir } from "./utils";export async function uploadFile(filename, data, cancelToken) {if (!data) return false;diff --git a/apps/mobile/app/common/filesystem/utils.js b/apps/mobile/app/common/filesystem/utils.jsindex 5d57420b4..921e4278d 100644--- a/apps/mobile/app/common/filesystem/utils.js+++ b/apps/mobile/app/common/filesystem/utils.js@@ -64,7 +64,6 @@ export function cancelable(operation) {execute: () => operation(filename, { url, headers }, cancelToken),cancel: async () => {await cancelToken.cancel();- RNFetchBlob.fs.unlink(`${cacheDir}/${filename}`).catch(console.log);}};};diff --git a/apps/mobile/app/hooks/use-app-events.tsx b/apps/mobile/app/hooks/use-app-events.tsxindex 6edaa66a4..80f751076 100644--- a/apps/mobile/app/hooks/use-app-events.tsx+++ b/apps/mobile/app/hooks/use-app-events.tsx@@ -465,32 +465,32 @@ export const useAppEvents = () => {const user = await db.user.getUser();if (PremiumService.get() && user) {if (- !SettingsService.get().backupDirectoryAndroid &&- Platform.OS === "android"- )- return;+ SettingsService.get().backupDirectoryAndroid ||+ Platform.OS !== "android"+ ) {+ const partialBackup = await BackupService.checkBackupRequired(+ SettingsService.get().reminder,+ "lastBackupDate"+ );+ const fullBackup = await BackupService.checkBackupRequired(+ SettingsService.get().fullBackupReminder,+ "lastFullBackupDate"+ );- const partialBackup = await BackupService.checkBackupRequired(- SettingsService.get().reminder,- "lastBackupDate"- );- const fullBackup = await BackupService.checkBackupRequired(- SettingsService.get().fullBackupReminder,- "lastFullBackupDate"- );+ await sleep(2000);- sleep(2000).then(() => {if (partialBackup) {- BackupService.run().then(() => {- if (fullBackup) {- eSendEvent(eCloseSheet);- BackupService.run(true, undefined, "full");- }- });- } else if (fullBackup) {- BackupService.run(true, undefined, "full");+ await BackupService.run();}- });++ if (fullBackup) {+ await BackupService.run(true, undefined, "full");+ }+ }++ if (SettingsService.getProperty("offlineMode")) {+ db.attachments.cacheAttachments().catch(console.log);+ }}}, []);diff --git a/apps/mobile/app/screens/settings/picker/pickers.jsx b/apps/mobile/app/screens/settings/picker/pickers.jsxindex 12006d2d8..3b1cf3c38 100644--- a/apps/mobile/app/screens/settings/picker/pickers.jsx+++ b/apps/mobile/app/screens/settings/picker/pickers.jsx@@ -141,7 +141,7 @@ export const BackupReminderPicker = createSettingsPicker({});export const BackupWithAttachmentsReminderPicker = createSettingsPicker({- getValue: () => useSettingStore.getState().settings.reminder,+ getValue: () => useSettingStore.getState().settings.fullBackupReminder,updateValue: (item) => {SettingsService.set({ fullBackupReminder: item });},diff --git a/apps/mobile/app/screens/settings/settings-data.tsx b/apps/mobile/app/screens/settings/settings-data.tsxindex f2c89a7ec..be2654a3f 100644--- a/apps/mobile/app/screens/settings/settings-data.tsx+++ b/apps/mobile/app/screens/settings/settings-data.tsx@@ -43,6 +43,7 @@ import BiometricService from "../../services/biometrics";import {ToastManager,eSendEvent,+ eSubscribeEvent,openVault,presentSheet} from "../../services/event-manager";@@ -70,6 +71,8 @@ import { useDragState } from "./editor/state";import { verifyUser, verifyUserWithApplock } from "./functions";import { SettingSection } from "./types";import { getTimeLeft } from "./user-section";+import filesystem from "../../common/filesystem";+import { formatBytes } from "@notesnook/common";type User = any;@@ -373,6 +376,44 @@ export const settingsGroups: SettingSection[] = [});}},+ {+ id: "clear-cache",+ name: "Clear cache",+ icon: "delete",+ modifer: async () => {+ presentDialog({+ title: "Clear cache",+ paragraph: "Are you sure you want to clear the cache?",+ positiveText: "Clear",+ positivePress: async () => {+ filesystem.clearCache();+ ToastManager.show({+ heading: "Cache cleared",+ message: "All cached attachments have been removed",+ type: "success"+ });+ }+ });+ },+ description(current) {+ return `Clear all cached attachments. Current cache size: ${+ current as number+ }`;+ },+ useHook: () => {+ const [cacheSize, setCacheSize] = React.useState(0);+ React.useEffect(() => {+ filesystem.getCacheSize().then(setCacheSize).catch(console.log);+ const sub = eSubscribeEvent("cache-cleared", () => {+ setCacheSize(0);+ });+ return () => {+ sub?.unsubscribe();+ };+ }, []);+ return formatBytes(cacheSize);+ }+ },{id: "delete-account",type: "danger",@@ -439,10 +480,17 @@ export const settingsGroups: SettingSection[] = [description: "Download everything including attachments on sync",type: "switch",property: "offlineMode",- onChange: (value) => {- if (value) {- Sync.run(undefined, false, "fetch");+ modifer: () => {+ const current = SettingsService.get().offlineMode;+ if (current) {+ SettingsService.setProperty("offlineMode", false);+ db.fs().cancel("offline-mode");+ return;}+ PremiumService.verify(() => {+ SettingsService.setProperty("offlineMode", true);+ db.attachments.cacheAttachments().catch(console.log);+ });}},{diff --git a/apps/mobile/app/services/backup.ts b/apps/mobile/app/services/backup.tsindex 9935cf00c..b26dfbcdb 100644--- a/apps/mobile/app/services/backup.ts+++ b/apps/mobile/app/services/backup.ts@@ -339,13 +339,13 @@ async function checkBackupRequired(}if (type === "daily" && lastBackupDate + MS_DAY < now) {- DatabaseLogger.info("Daily backup started");+ DatabaseLogger.info(`Daily backup started: ${type}`);return true;} else if (type === "weekly" && lastBackupDate + MS_WEEK < now) {- DatabaseLogger.info("Weekly backup started");+ DatabaseLogger.info(`Weekly backup started: ${type}`);return true;} else if (type === "monthly" && lastBackupDate + MONTH < now) {- DatabaseLogger.info("Monthly backup started");+ DatabaseLogger.info(`Monthly backup started: ${type}`);return true;}return false;