Skip to content

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

mobile: download mutliple attachments

ammarahm-ede021d938937f
diff --git a/apps/mobile/app/common/filesystem/download-attachment.js b/apps/mobile/app/common/filesystem/download-attachment.js
index 123d4cd45..63fa1c8e5 100644
--- a/apps/mobile/app/common/filesystem/download-attachment.js
+++ b/apps/mobile/app/common/filesystem/download-attachment.js
@@ -17,25 +17,165 @@ 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 Sodium from "@ammarahmed/react-native-sodium";
+import { getFileNameWithExtension } from "@notesnook/core/utils/filename";
import React from "react";
import { Platform } from "react-native";
import * as ScopedStorage from "react-native-scoped-storage";
-import Sodium from "@ammarahmed/react-native-sodium";
+import { subscribe, zip } from "react-native-zip-archive";
import RNFetchBlob from "rn-fetch-blob";
import { ShareComponent } from "../../components/sheets/export-notes/share";
import { presentSheet, ToastEvent } from "../../services/event-manager";
import { useAttachmentStore } from "../../stores/use-attachment-store";
import { db } from "../database";
import Storage from "../database/storage";
-import { cacheDir } from "./utils";
-import { getFileNameWithExtension } from "@notesnook/core/utils/filename";
+import { cacheDir, copyFileAsync, releasePermissions } from "./utils";
+
+export const FileDownloadStatus = {
+ Success: 1,
+ Fail: 0
+};
+
+/**
+ * Download all user's attachments
+ * @returns
+ */
+export function downloadAllAttachments() {
+ const attachments = db.attachments.all;
+ return downloadAttachments(attachments);
+}
+
+/**
+ * Downloads provided attachments to a .zip file
+ * on user's device.
+ * @param attachments
+ * @param onProgress
+ * @returns
+ */
+export async function downloadAttachments(
+ attachments,
+ onProgress,
+ canceled,
+ groupId
+) {
+ if (!attachments || !attachments.length) return;
+ const result = new Map();
+
+ let outputFolder;
+ if (Platform.OS === "android") {
+ // Ask the user to select a directory to store the file
+ let file = await ScopedStorage.openDocumentTree(true);
+ outputFolder = file.uri;
+ if (!outputFolder) return;
+ } else {
+ outputFolder = await Storage.checkAndCreateDir("/downloads/");
+ }
+
+ // Create the folder to zip;
+ const zipSourceFolder = `${cacheDir}/notesnook-attachments`;
+ const zipOutputFile =
+ Platform.OS === "ios"
+ ? `${outputFolder}/notesnook-attachments-${Date.now()}.zip`
+ : `${cacheDir}/notesnook-attachments.zip`;
+ if (await RNFetchBlob.fs.exists(zipSourceFolder))
+ await RNFetchBlob.fs.unlink(zipSourceFolder);
+ await RNFetchBlob.fs.mkdir(zipSourceFolder);
+
+ for (let i = 0; i < attachments.length; i++) {
+ let attachment = attachments[i];
+ const hash = attachment.metadata.hash;
+ try {
+ if (canceled.current) {
+ RNFetchBlob.fs.unlink(zipSourceFolder).catch(console.log);
+ return;
+ }
+ onProgress?.(
+ i + 1 / attachments.length,
+ `Downloading attachments (${i + 1}/${
+ attachments.length
+ })... Please wait`
+ );
+ // Download to cache
+ let uri = await downloadAttachment(hash, false, {
+ silent: true,
+ cache: true,
+ groupId: groupId
+ });
+ if (canceled.current) {
+ RNFetchBlob.fs.unlink(zipSourceFolder).catch(console.log);
+ return;
+ }
+ if (!uri) throw new Error("Failed to download file");
+ // Move file to the source folder we will zip eventually and rename the file to it's actual name.
+ const filePath = `${zipSourceFolder}/${attachment.metadata.filename}`;
+ await RNFetchBlob.fs.mv(`${cacheDir}/${uri}`, filePath);
+ result.set(hash, {
+ filename: attachment.metadata.filename,
+ status: FileDownloadStatus.Success
+ });
+ } catch (e) {
+ result.set(hash, {
+ filename: attachment.metadata.filename,
+ status: FileDownloadStatus.Fail,
+ reason: e
+ });
+ console.log("Error downloading attachment", e);
+ }
+ }
+ if (canceled.current) {
+ RNFetchBlob.fs.unlink(zipSourceFolder).catch(console.log);
+ return;
+ }
+ if (result.size) {
+ let sub;
+ try {
+ onProgress?.(0, `Zipping... Please wait`);
+ // If all goes well, zip the notesnook-attachments folder in cache.
+
+ sub = subscribe(({ progress }) => {
+ onProgress(
+ progress,
+ `Saving zip file (${(progress * 100).toFixed(1)}%)... Please wait`
+ );
+ });
+ await zip(zipSourceFolder, zipOutputFile);
+ sub?.remove();
+ onProgress(1, `Saving zip file... Please wait`);
+ if (Platform.OS === "android") {
+ // Move the zip to user selected directory.
+ const file = await ScopedStorage.createFile(
+ outputFolder,
+ `notesnook-attachments-${Date.now()}.zip`,
+ "application/zip"
+ );
+ await copyFileAsync(`file://${zipOutputFile}`, file.uri);
+ }
+
+ onProgress?.(1, `Done`);
+ releasePermissions(outputFolder);
+ } catch (e) {
+ releasePermissions(outputFolder);
+ sub?.remove();
+ console.log("Error zipping attachments", e);
+ }
+ // Remove source & zip file from cache.
+ RNFetchBlob.fs.unlink(zipSourceFolder).catch(console.log);
+ if (Platform.OS === "android") {
+ RNFetchBlob.fs.unlink(zipOutputFile).catch(console.log);
+ }
+ }
+
+ return result;
+}
export default async function downloadAttachment(
hash,
global = true,
options = {
silent: false,
- cache: false
+ cache: false,
+ throwError: false,
+ groupId: undefined
}
) {
let attachment = db.attachments.attachment(hash);
@@ -55,8 +195,9 @@ export default async function downloadAttachment(
}
try {
+ console.log("starting download attachment", attachment.metadata.hash);
await db.fs.downloadFile(
- attachment.metadata.hash,
+ options.groupId || attachment.metadata.hash,
attachment.metadata.hash
);
if (
@@ -131,5 +272,8 @@ export default async function downloadAttachment(
.catch(console.log);
}
useAttachmentStore.getState().remove(attachment.metadata.hash);
+ if (options.throwError) {
+ throw e;
+ }
}
}
diff --git a/apps/mobile/app/common/filesystem/utils.js b/apps/mobile/app/common/filesystem/utils.js
index 7605d59de..39490edfb 100644
--- a/apps/mobile/app/common/filesystem/utils.js
+++ b/apps/mobile/app/common/filesystem/utils.js
@@ -18,6 +18,8 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import RNFetchBlob from "rn-fetch-blob";
+import * as ScopedStorage from "react-native-scoped-storage";
+import { Platform } from "react-native";
export const cacheDir = RNFetchBlob.fs.dirs.CacheDir;
@@ -62,3 +64,22 @@ export function cancelable(operation) {
};
};
}
+
+export function copyFileAsync(source, dest) {
+ return new Promise((resolve) => {
+ ScopedStorage.copyFile(source, dest, (e, r) => {
+ console.log(e, r);
+ resolve();
+ });
+ });
+}
+
+export async function releasePermissions(path) {
+ if (Platform.OS === "ios") return;
+ const uris = await ScopedStorage.getPersistedUriPermissions();
+ for (let uri of uris) {
+ if (path.startsWith(uri)) {
+ await ScopedStorage.releasePersistableUriPermission(uri);
+ }
+ }
+}
diff --git a/apps/mobile/app/components/attachments/download-attachments.js b/apps/mobile/app/components/attachments/download-attachments.js
new file mode 100644
index 000000000..036cb8c2c
--- /dev/null
+++ b/apps/mobile/app/components/attachments/download-attachments.js
@@ -0,0 +1,235 @@
+/*
+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 React, { useRef, useState } from "react";
+import { Platform, View } from "react-native";
+import { db } from "../../common/database";
+import { downloadAttachments } from "../../common/filesystem/download-attachment";
+import { presentSheet } from "../../services/event-manager";
+import { Button } from "../ui/button";
+import Heading from "../ui/typography/heading";
+import Paragraph from "../ui/typography/paragraph";
+import { ProgressBarComponent } from "../ui/svg/lazy";
+import { useThemeStore } from "../../stores/use-theme-store";
+
+const DownloadAttachments = ({ close, attachments, isNote, update }) => {
+ const colors = useThemeStore((state) => state.colors);
+ const [downloading, setDownloading] = useState(false);
+ const [progress, setProgress] = useState({
+ value: 0,
+ statusText: "Download started... Please wait"
+ });
+ const [result, setResult] = useState(new Map());
+ const canceled = useRef(false);
+ const groupId = useRef();
+
+ const onDownload = async () => {
+ update({
+ disableClosing: true
+ });
+ setDownloading(true);
+ canceled.current = false;
+ groupId.current = Date.now().toString();
+ const result = await downloadAttachments(
+ attachments,
+ (progress, statusText) => setProgress({ value: progress, statusText }),
+ canceled,
+ groupId
+ );
+ if (canceled.current) return;
+ setResult(result);
+ setDownloading(false);
+ update({
+ disableClosing: false
+ });
+ };
+
+ const cancel = async () => {
+ update({
+ disableClosing: false
+ });
+ canceled.current = true;
+ await db.fs.cancel(groupId.current);
+ setDownloading(false);
+ groupId.current = null;
+ };
+
+ const successResults = () => {
+ const results = [];
+ for (let [key, value] of result.entries()) {
+ if (value.status === 1) results.push(db.attachments.attachment(key));
+ }
+ return results;
+ };
+
+ const failedResults = () => {
+ const results = [];
+ for (let [key, value] of result.entries()) {
+ if (value.status === 0) results.push(db.attachments.attachment(key));
+ }
+ return results;
+ };
+
+ function getResultText() {
+ const downloadedAttachmentsCount =
+ attachments.length - failedResults().length;
+ if (downloadedAttachmentsCount === 0)
+ return "Failed to download all attachments";
+ return `Successfully downloaded ${downloadedAttachmentsCount}/${
+ attachments.length
+ } attachments as a zip file at ${
+ Platform.OS === "android" ? "the selected folder" : "Notesnook/downloads"
+ }`;
+ }
+
+ return (
+ <View
+ style={{
+ alignItems: "center",
+ width: "100%",
+ paddingVertical: 12,
+ paddingHorizontal: 12
+ }}
+ >
+ <Heading>
+ {downloading
+ ? "Downloading attachments"
+ : result.size
+ ? "Downloaded attachments"
+ : "Download attachments"}
+ </Heading>
+
+ {downloading ? (
+ <Paragraph
+ style={{
+ textAlign: "center"
+ }}
+ >
+ {progress.statusText}
+ </Paragraph>
+ ) : result.size ? (
+ <Paragraph
+ style={{
+ textAlign: "center"
+ }}
+ >
+ {getResultText()}
+ </Paragraph>
+ ) : (
+ <Paragraph
+ style={{
+ textAlign: "center"
+ }}
+ >
+ Are you sure you want to download all attachments
+ {isNote ? " of this note?" : "?"}
+ </Paragraph>
+ )}
+
+ {downloading ? (
+ <View
+ style={{
+ width: 200,
+ marginTop: 10
+ }}
+ >
+ <ProgressBarComponent
+ height={5}
+ width={null}
+ animated={true}
+ useNativeDriver
+ progress={progress.value || 0}
+ unfilledColor={colors.nav}
+ color={colors.accent}
+ borderWidth={0}
+ />
+ </View>
+ ) : null}
+
+ {result.size ? (
+ <Button
+ style={{
+ width: 250,
+ borderRadius: 100,
+ marginTop: 20
+ }}
+ onPress={close}
+ type="accent"
+ title="Done"
+ />
+ ) : !downloading ? (
+ <View
+ style={{
+ flexDirection: "row",
+ width: "100%",
+ marginTop: 20
+ }}
+ >
+ <Button
+ style={{
+ flex: 1,
+ borderRadius: 100,
+ marginRight: 5
+ }}
+ onPress={close}
+ type="grayBg"
+ title="No"
+ />
+ <Button
+ style={{
+ flex: 1,
+ borderRadius: 100,
+ marginLeft: 5
+ }}
+ onPress={onDownload}
+ type="accent"
+ title="Yes"
+ />
+ </View>
+ ) : (
+ <Button
+ style={{
+ width: 250,
+ borderRadius: 100,
+ marginTop: 20
+ }}
+ onPress={cancel}
+ type="error"
+ title="Cancel"
+ />
+ )}
+ </View>
+ );
+};
+
+DownloadAttachments.present = (context, attachments, isNote) => {
+ presentSheet({
+ context: context,
+ component: (ref, close, update) => (
+ <DownloadAttachments
+ close={close}
+ attachments={attachments}
+ isNote={isNote}
+ update={update}
+ />
+ )
+ });
+};
+
+export default DownloadAttachments;
diff --git a/apps/mobile/app/components/attachments/index.js b/apps/mobile/app/components/attachments/index.js
index bea7ff242..99c1e6e89 100644
--- a/apps/mobile/app/components/attachments/index.js
+++ b/apps/mobile/app/components/attachments/index.js
@@ -19,25 +19,27 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import React, { useRef, useState } from "react";
import { View } from "react-native";
+import { FlatList } from "react-native-actions-sheet";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import { db } from "../../common/database";
import filesystem from "../../common/filesystem";
import { presentSheet } from "../../services/event-manager";
import { useThemeStore } from "../../stores/use-theme-store";
import { SIZE } from "../../utils/size";
-import DialogHeader from "../dialog/dialog-header";
+import SheetProvider from "../sheet-provider";
+import { IconButton } from "../ui/icon-button";
import Input from "../ui/input";
import Seperator from "../ui/seperator";
+import Heading from "../ui/typography/heading";
import Paragraph from "../ui/typography/paragraph";
import { AttachmentItem } from "./attachment-item";
-import { FlatList } from "react-native-actions-sheet";
+import DownloadAttachments from "./download-attachments";
-export const AttachmentDialog = ({ data }) => {
+export const AttachmentDialog = ({ note }) => {
const colors = useThemeStore((state) => state.colors);
- const [note, setNote] = useState(data);
const [attachments, setAttachments] = useState(
- data
- ? db.attachments.ofNote(data.id, "all")
+ note
+ ? db.attachments.ofNote(note.id, "all")
: [...(db.attachments.all || [])]
);
const attachmentSearchValue = useRef();
@@ -67,6 +69,20 @@ export const AttachmentDialog = ({ data }) => {
<AttachmentItem setAttachments={setAttachments} attachment={item} />
);
+ const onCheck = async () => {
+ setLoading(true);
+ for (let attachment of attachments) {
+ let result = await filesystem.checkAttachment(attachment.metadata.hash);
+ if (result.failed) {
+ db.attachments.markAsFailed(attachment.metadata.hash, result.failed);
+ } else {
+ db.attachments.markAsFailed(attachment.id, null);
+ }
+ setAttachments([...db.attachments.all]);
+ }
+ setLoading(false);
+ };
+
return (
<View
style={{
@@ -75,33 +91,50 @@ export const AttachmentDialog = ({ data }) => {
paddingHorizontal: 12
}}
>
- <DialogHeader
- title={note ? "Attachments" : "Manage attachments"}
- paragraph="Tap on an attachment to view properties"
- button={{
- title: "Check all",
- type: "grayAccent",
- loading: loading,
- onPress: async () => {
- setLoading(true);
- for (let attachment of attachments) {
- let result = await filesystem.checkAttachment(
- attachment.metadata.hash
- );
- if (result.failed) {
- db.attachments.markAsFailed(
- attachment.metadata.hash,
- result.failed
- );
- } else {
- db.attachments.markAsFailed(attachment.id, null);
- }
- setAttachments([...db.attachments.all]);
- }
- setLoading(false);
- }
+ <SheetProvider context="attachments-list" />
+ <View
+ style={{
+ flexDirection: "row",
+ justifyContent: "space-between",
+ alignItems: "center"
}}
- />
+ >
+ <Heading>Attachments</Heading>
+
+ <View
+ style={{
+ flexDirection: "row"
+ }}
+ >
+ <IconButton
+ name="check-all"
+ customStyle={{
+ height: 40,
+ width: 40,
+ marginRight: 10
+ }}
+ size={SIZE.lg}
+ onPress={onCheck}
+ />
+
+ <IconButton
+ name="download"
+ customStyle={{
+ height: 40,
+ width: 40
+ }}
+ onPress={() => {
+ DownloadAttachments.present(
+ "attachments-list",
+ attachments,
+ !!note
+ );
+ }}
+ size={SIZE.lg}
+ />
+ </View>
+ </View>
+
<Seperator />
{!note ? (
<Input
@@ -162,6 +195,6 @@ export const AttachmentDialog = ({ data }) => {
AttachmentDialog.present = (note) => {
presentSheet({
- component: () => <AttachmentDialog data={note} />
+ component: () => <AttachmentDialog note={note} />
});
};
diff --git a/apps/mobile/native/package.json b/apps/mobile/native/package.json
index c03a6fc69..3f6bc6bd1 100644
--- a/apps/mobile/native/package.json
+++ b/apps/mobile/native/package.json
@@ -60,7 +60,8 @@
"@bam.tech/react-native-image-resizer": "3.0.5",
"react-native-navigation-bar-color": "2.0.2",
"react-native-actions-shortcuts": "^1.0.1",
- "react-native-in-app-review": "4.3.3"
+ "react-native-in-app-review": "4.3.3",
+ "react-native-zip-archive": "6.0.9"
},
"devDependencies": {
"@babel/core": "^7.12.9",
diff --git a/apps/mobile/package-lock.json b/apps/mobile/package-lock.json
index 547e04313..c013547ed 100644
--- a/apps/mobile/package-lock.json
+++ b/apps/mobile/package-lock.json
@@ -112,6 +112,7 @@
"react-native-tooltips": "^1.0.3",
"react-native-vector-icons": "^9.0.0",
"react-native-webview": "^11.14.1",
+ "react-native-zip-archive": "6.0.9",
"rn-extensions-share": "^2.4.0",
"rn-fetch-blob": "^0.12.0"
},
@@ -18518,6 +18519,15 @@
"node": ">=8"
}
},
+ "node_modules/react-native-zip-archive": {
+ "version": "6.0.9",
+ "resolved": "https://registry.npmjs.org/react-native-zip-archive/-/react-native-zip-archive-6.0.9.tgz",
+ "integrity": "sha512-IYf3yHJ7sHzj9ucO3Amx/TtsZcTgHdfj+Dar8p1e32E+wBsn7mv0PDp2X/oCLGci0nG9i2DBstrnCW74/7NLYQ==",
+ "peerDependencies": {
+ "react": ">=16.8.6",
+ "react-native": ">=0.60.0"
+ }
+ },
"node_modules/react-native/node_modules/react-refresh": {
"version": "0.4.3",
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.4.3.tgz",
@@ -24327,6 +24337,7 @@
"react-native-tooltips": "^1.0.3",
"react-native-vector-icons": "^9.0.0",
"react-native-webview": "^11.14.1",
+ "react-native-zip-archive": "6.0.9",
"react-test-renderer": "18.0.0",
"rn-extensions-share": "^2.4.0",
"rn-fetch-blob": "^0.12.0",
@@ -35147,6 +35158,11 @@
}
}
},
+ "react-native-zip-archive": {
+ "version": "6.0.9",
+ "resolved": "https://registry.npmjs.org/react-native-zip-archive/-/react-native-zip-archive-6.0.9.tgz",
+ "integrity": "sha512-IYf3yHJ7sHzj9ucO3Amx/TtsZcTgHdfj+Dar8p1e32E+wBsn7mv0PDp2X/oCLGci0nG9i2DBstrnCW74/7NLYQ=="
+ },
"react-refresh": {
"version": "0.14.0",
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.14.0.tgz",