Skip to content

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

mobile: fix share extension crash on ios

ammarahm-ed4ac1d4a20ced
diff --git a/apps/mobile/app/common/filesystem/download-attachment.js b/apps/mobile/app/common/filesystem/download-attachment.js
new file mode 100644
index 000000000..86eb65588
--- /dev/null
+++ b/apps/mobile/app/common/filesystem/download-attachment.js
@@ -0,0 +1,116 @@
+/*
+This file is part of the Notesnook project (https://notesnook.com/)
+
+Copyright (C) 2022 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 from "react";
+import { Platform } from "react-native";
+import * as ScopedStorage from "react-native-scoped-storage";
+import Sodium from "react-native-sodium";
+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";
+
+export default async function downloadAttachment(hash, global = true) {
+ let attachment = db.attachments.attachment(hash);
+ if (!attachment) {
+ console.log("attachment not found");
+ return;
+ }
+
+ let folder = {};
+ if (Platform.OS === "android") {
+ folder = await ScopedStorage.openDocumentTree();
+ if (!folder) return;
+ } else {
+ folder.uri = await Storage.checkAndCreateDir("/downloads/");
+ }
+
+ try {
+ await db.fs.downloadFile(
+ attachment.metadata.hash,
+ attachment.metadata.hash
+ );
+ if (
+ !(await RNFetchBlob.fs.exists(`${cacheDir}/${attachment.metadata.hash}`))
+ )
+ return;
+
+ let key = await db.attachments.decryptKey(attachment.key);
+ let info = {
+ iv: attachment.iv,
+ salt: attachment.salt,
+ length: attachment.length,
+ alg: attachment.alg,
+ hash: attachment.metadata.hash,
+ hashType: attachment.metadata.hashType,
+ mime: attachment.metadata.type,
+ fileName: attachment.metadata.filename,
+ uri: folder.uri,
+ chunkSize: attachment.chunkSize
+ };
+
+ let fileUri = await Sodium.decryptFile(key, info, false);
+ ToastEvent.show({
+ heading: "Download successful",
+ message: attachment.metadata.filename + " downloaded",
+ type: "success"
+ });
+
+ if (attachment.dateUploaded) {
+ RNFetchBlob.fs
+ .unlink(RNFetchBlob.fs.dirs.CacheDir + `/${attachment.metadata.hash}`)
+ .catch(console.log);
+ }
+
+ if (Platform.OS === "ios") {
+ fileUri = folder.uri + `/${attachment.metadata.filename}`;
+ }
+ console.log("saved file uri: ", fileUri);
+
+ presentSheet({
+ title: "File downloaded",
+ paragraph: `${attachment.metadata.filename} saved to ${
+ Platform.OS === "android"
+ ? "selected path"
+ : "File Manager/Notesnook/downloads"
+ }`,
+ icon: "download",
+ context: global ? null : attachment.metadata.hash,
+ component: (
+ <ShareComponent
+ uri={fileUri}
+ name={attachment.metadata.filename}
+ padding={12}
+ />
+ )
+ });
+ return fileUri;
+ } catch (e) {
+ console.log("download attachment error: ", e);
+ if (attachment.dateUploaded) {
+ RNFetchBlob.fs
+ .unlink(RNFetchBlob.fs.dirs.CacheDir + `/${attachment.metadata.hash}`)
+ .catch(console.log);
+ }
+ useAttachmentStore.getState().remove(attachment.metadata.hash);
+ }
+}
diff --git a/apps/mobile/app/common/filesystem/download.js b/apps/mobile/app/common/filesystem/download.js
index 43c151b45..72e201834 100644
--- a/apps/mobile/app/common/filesystem/download.js
+++ b/apps/mobile/app/common/filesystem/download.js
@@ -17,18 +17,12 @@ 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 NetInfo from "@react-native-community/netinfo";
import hosts from "@notesnook/core/utils/constants";
-import React from "react";
-import { Platform } from "react-native";
-import * as ScopedStorage from "react-native-scoped-storage";
-import Sodium from "react-native-sodium";
+import NetInfo from "@react-native-community/netinfo";
import RNFetchBlob from "rn-fetch-blob";
-import { ShareComponent } from "../../components/sheets/export-notes/share";
-import { presentSheet, ToastEvent } from "../../services/event-manager";
+import { ToastEvent } from "../../services/event-manager";
import { useAttachmentStore } from "../../stores/use-attachment-store";
import { db } from "../database";
-import Storage from "../database/storage";
import { cacheDir, fileCheck } from "./utils";
export async function downloadFile(filename, data, cancelToken) {
@@ -92,92 +86,6 @@ export async function downloadFile(filename, data, cancelToken) {
}
}
-export async function downloadAttachment(hash, global = true) {
- let attachment = db.attachments.attachment(hash);
- if (!attachment) {
- console.log("attachment not found");
- return;
- }
-
- let folder = {};
- if (Platform.OS === "android") {
- folder = await ScopedStorage.openDocumentTree();
- if (!folder) return;
- } else {
- folder.uri = await Storage.checkAndCreateDir("/downloads/");
- }
-
- try {
- await db.fs.downloadFile(
- attachment.metadata.hash,
- attachment.metadata.hash
- );
- if (
- !(await RNFetchBlob.fs.exists(`${cacheDir}/${attachment.metadata.hash}`))
- )
- return;
-
- let key = await db.attachments.decryptKey(attachment.key);
- let info = {
- iv: attachment.iv,
- salt: attachment.salt,
- length: attachment.length,
- alg: attachment.alg,
- hash: attachment.metadata.hash,
- hashType: attachment.metadata.hashType,
- mime: attachment.metadata.type,
- fileName: attachment.metadata.filename,
- uri: folder.uri,
- chunkSize: attachment.chunkSize
- };
-
- let fileUri = await Sodium.decryptFile(key, info, false);
- ToastEvent.show({
- heading: "Download successful",
- message: attachment.metadata.filename + " downloaded",
- type: "success"
- });
-
- if (attachment.dateUploaded) {
- RNFetchBlob.fs
- .unlink(RNFetchBlob.fs.dirs.CacheDir + `/${attachment.metadata.hash}`)
- .catch(console.log);
- }
-
- if (Platform.OS === "ios") {
- fileUri = folder.uri + `/${attachment.metadata.filename}`;
- }
- console.log("saved file uri: ", fileUri);
-
- presentSheet({
- title: "File downloaded",
- paragraph: `${attachment.metadata.filename} saved to ${
- Platform.OS === "android"
- ? "selected path"
- : "File Manager/Notesnook/downloads"
- }`,
- icon: "download",
- context: global ? null : attachment.metadata.hash,
- component: (
- <ShareComponent
- uri={fileUri}
- name={attachment.metadata.filename}
- padding={12}
- />
- )
- });
- return fileUri;
- } catch (e) {
- console.log("download attachment error: ", e);
- if (attachment.dateUploaded) {
- RNFetchBlob.fs
- .unlink(RNFetchBlob.fs.dirs.CacheDir + `/${attachment.metadata.hash}`)
- .catch(console.log);
- }
- useAttachmentStore.getState().remove(attachment.metadata.hash);
- }
-}
-
export async function getUploadedFileSize(hash) {
const url = `${hosts.API_HOST}/s3?name=${hash}`;
const token = await db.user.tokenManager.getAccessToken();
diff --git a/apps/mobile/app/common/filesystem/index.js b/apps/mobile/app/common/filesystem/index.js
index 54d0e3fcc..2ff6d5e55 100644
--- a/apps/mobile/app/common/filesystem/index.js
+++ b/apps/mobile/app/common/filesystem/index.js
@@ -18,10 +18,8 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import {
- downloadAttachment,
- downloadFile,
- getUploadedFileSize,
- checkAttachment
+ checkAttachment, downloadFile,
+ getUploadedFileSize
} from "./download";
import {
clearFileStorage,
@@ -40,7 +38,6 @@ export default {
downloadFile: cancelable(downloadFile),
deleteFile,
exists,
- downloadAttachment,
clearFileStorage,
getUploadedFileSize,
checkAttachment
diff --git a/apps/mobile/app/components/attachments/actions.js b/apps/mobile/app/components/attachments/actions.js
index 017cc603b..d4279b4f1 100644
--- a/apps/mobile/app/components/attachments/actions.js
+++ b/apps/mobile/app/components/attachments/actions.js
@@ -18,11 +18,12 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Clipboard from "@react-native-clipboard/clipboard";
-import React, { useEffect, useState } from "react";
+import React, { useCallback, useEffect, useState } from "react";
import { View } from "react-native";
import { ScrollView } from "react-native-gesture-handler";
import { db } from "../../common/database";
import filesystem from "../../common/filesystem";
+import downloadAttachment from "../../common/filesystem/download-attachment";
import { useAttachmentProgress } from "../../hooks/use-attachment-progress";
import picker from "../../screens/editor/tiptap/picker";
import {
@@ -49,7 +50,6 @@ import { Notice } from "../ui/notice";
import { PressableButton } from "../ui/pressable";
import Heading from "../ui/typography/heading";
import Paragraph from "../ui/typography/paragraph";
-import { useCallback } from "react";
const Actions = ({ attachment, setAttachments, fwdRef }) => {
const colors = useThemeStore((state) => state.colors);
@@ -70,7 +70,7 @@ const Actions = ({ attachment, setAttachments, fwdRef }) => {
await db.fs.cancel(attachment.metadata.hash, "download");
useAttachmentStore.getState().remove(attachment.metadata.hash);
}
- filesystem.downloadAttachment(attachment.metadata.hash, false);
+ downloadAttachment(attachment.metadata.hash, false);
eSendEvent(eCloseProgressDialog, contextId);
},
icon: "download"
diff --git a/apps/mobile/app/screens/editor/index.tsx b/apps/mobile/app/screens/editor/index.tsx
index e773c85a5..cad0adf85 100755
--- a/apps/mobile/app/screens/editor/index.tsx
+++ b/apps/mobile/app/screens/editor/index.tsx
@@ -21,6 +21,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { EV, EVENTS } from "@notesnook/core/common";
import React, {
forwardRef,
+ useCallback,
useEffect,
useImperativeHandle,
useState
@@ -29,13 +30,13 @@ import { Platform, ViewStyle } from "react-native";
import WebView from "react-native-webview";
import { ShouldStartLoadRequest } from "react-native-webview/lib/WebViewTypes";
import { notesnook } from "../../../e2e/test.ids";
+import { db } from "../../common/database";
import {
eSubscribeEvent,
eUnSubscribeEvent
} from "../../services/event-manager";
import { useEditorStore } from "../../stores/use-editor-store";
import { getElevation } from "../../utils";
-import { db } from "../../common/database";
import { openLinkInBrowser } from "../../utils/functions";
import { NoteType } from "../../utils/types";
import { EDITOR_URI } from "./source";
@@ -43,7 +44,7 @@ import { EditorProps, useEditorType } from "./tiptap/types";
import { useEditor } from "./tiptap/use-editor";
import { useEditorEvents } from "./tiptap/use-editor-events";
import { editorController } from "./tiptap/utils";
-import { useCallback } from "react";
+import { useLayoutEffect } from "react";
const style: ViewStyle = {
height: "100%",
@@ -118,14 +119,18 @@ const Editor = React.memo(
}, [editor]);
useEffect(() => {
- onLoad && onLoad();
eSubscribeEvent("webview_reset", onError);
EV.subscribe(EVENTS.mediaAttachmentDownloaded, onMediaDownloaded);
return () => {
eUnSubscribeEvent("webview_reset", onError);
EV.unsubscribe(EVENTS.mediaAttachmentDownloaded, onMediaDownloaded);
};
- }, [onError, onLoad, onMediaDownloaded]);
+ }, [onError, onMediaDownloaded]);
+
+ useLayoutEffect(() => {
+ onLoad && onLoad();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [onLoad]);
if (withController) {
editorController.current = editor;
diff --git a/apps/mobile/app/screens/editor/source.ts b/apps/mobile/app/screens/editor/source.ts
index 7d7371863..f1c23a5a3 100644
--- a/apps/mobile/app/screens/editor/source.ts
+++ b/apps/mobile/app/screens/editor/source.ts
@@ -28,5 +28,5 @@ const EditorMobileSourceUrl =
* The url should be something like this: http://192.168.100.126:3000/index.html
*/
export const EDITOR_URI = __DEV__
- ? EditorMobileSourceUrl
+ ? "http://192.168.10.3:3000/index.html"
: EditorMobileSourceUrl;
diff --git a/apps/mobile/app/screens/editor/tiptap/use-editor-events.ts b/apps/mobile/app/screens/editor/tiptap/use-editor-events.ts
index 1642e514d..7bf93e783 100644
--- a/apps/mobile/app/screens/editor/tiptap/use-editor-events.ts
+++ b/apps/mobile/app/screens/editor/tiptap/use-editor-events.ts
@@ -19,8 +19,8 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
/* eslint-disable no-case-declarations */
/* eslint-disable @typescript-eslint/no-var-requires */
-import { getDefaultPresets } from "@notesnook/editor/dist/toolbar/tool-definitions";
import type { Attachment } from "@notesnook/editor/dist/extensions/attachment/index";
+import { getDefaultPresets } from "@notesnook/editor/dist/toolbar/tool-definitions";
import { useCallback, useEffect, useRef } from "react";
import {
BackHandler,
@@ -28,6 +28,9 @@ import {
NativeEventSubscription
} from "react-native";
import { WebViewMessageEvent } from "react-native-webview";
+import umami from "../../../common/analytics/index";
+import { db } from "../../../common/database";
+import useKeyboard from "../../../hooks/use-keyboard";
import { DDS } from "../../../services/device-detection";
import {
eSendEvent,
@@ -40,8 +43,6 @@ import { useEditorStore } from "../../../stores/use-editor-store";
import { useSettingStore } from "../../../stores/use-setting-store";
import { useTagStore } from "../../../stores/use-tag-store";
import { useUserStore } from "../../../stores/use-user-store";
-import umami from "../../../common/analytics/index";
-import { db } from "../../../common/database";
import {
eClearEditor,
eCloseFullscreenEditor,
@@ -52,9 +53,7 @@ import {
eOpenPublishNoteDialog,
eOpenTagsDialog
} from "../../../utils/events";
-import filesystem from "../../../common/filesystem";
import { tabBarRef } from "../../../utils/global-refs";
-import useKeyboard from "../../../hooks/use-keyboard";
import { NoteType } from "../../../utils/types";
import { useDragState } from "../../settings/editor/state";
import { EditorMessage, EditorProps, useEditorType } from "./types";
@@ -337,12 +336,13 @@ export const useEditorEvents = (
const { pick } = require("./picker.js").default;
pick({ type: editorMessage.value });
break;
- case EventTypes.download:
- filesystem.downloadAttachment(
- (editorMessage.value as Attachment)?.hash,
- true
- );
+ case EventTypes.download: {
+ const downloadAttachment =
+ require("../../../common/filesystem/download-attachment").default;
+ downloadAttachment((editorMessage.value as Attachment)?.hash, true);
break;
+ }
+
case EventTypes.pro:
if (editor.state.current?.isFocused) {
editor.state.current.isFocused = true;
diff --git a/apps/mobile/native/index.ext.js b/apps/mobile/native/index.ext.js
new file mode 100644
index 000000000..7a649c16d
--- /dev/null
+++ b/apps/mobile/native/index.ext.js
@@ -0,0 +1,20 @@
+/* eslint-disable @typescript-eslint/no-var-requires */
+import './globals.js';
+import React from 'react';
+import { AppRegistry, Platform } from 'react-native';
+import 'react-native-get-random-values';
+import { SafeAreaProvider } from 'react-native-safe-area-context';
+
+
+const ShareProvider = () => {
+ NotesnookShare = require('../share/index').default;
+ return Platform.OS === 'ios' ? (
+ <SafeAreaProvider>
+ <NotesnookShare quicknote={false} />
+ </SafeAreaProvider>
+ ) : (
+ <NotesnookShare quicknote={false} />
+ );
+ };
+AppRegistry.registerComponent('NotesnookShare', () => ShareProvider);
+
diff --git a/apps/mobile/native/ios/Make Note/ShareViewController.m b/apps/mobile/native/ios/Make Note/ShareViewController.m
index ec622b089..9b6285248 100644
--- a/apps/mobile/native/ios/Make Note/ShareViewController.m
+++ b/apps/mobile/native/ios/Make Note/ShareViewController.m
@@ -9,12 +9,16 @@
@implementation ShareViewController
++ (BOOL)requiresMainQueueSetup {
+ return true;
+}
+
RCT_EXPORT_MODULE();
- (UIView*) shareView {
NSURL *jsCodeLocation;
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
-
+
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"NotesnookShare"
initialProperties:nil
diff --git a/apps/mobile/native/ios/Notesnook.xcodeproj/project.pbxproj b/apps/mobile/native/ios/Notesnook.xcodeproj/project.pbxproj
index 6d9a886fe..997d24226 100644
--- a/apps/mobile/native/ios/Notesnook.xcodeproj/project.pbxproj
+++ b/apps/mobile/native/ios/Notesnook.xcodeproj/project.pbxproj
@@ -739,7 +739,7 @@
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
- shellScript = "export NODE_BINARY=node\nexport BUNDLE_COMMAND=webpack-bundle\n../../node_modules/react-native/scripts/react-native-xcode.sh\n";
+ shellScript = "export NODE_BINARY=node\nexport BUNDLE_COMMAND=webpack-bundle\nexport ENTRY_FILE=index.ext.js\n../../node_modules/react-native/scripts/react-native-xcode.sh\n";
};
74EE9ED768E52033B174E41C /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
diff --git a/apps/mobile/share/share.js b/apps/mobile/share/share.js
index 748b12343..0525b7a4b 100644
--- a/apps/mobile/share/share.js
+++ b/apps/mobile/share/share.js
@@ -278,7 +278,6 @@ const ShareView = ({ quicknote = false }) => {
}
}
setNote({ ...note });
-
onLoad();
} catch (e) {
console.error(e);
@@ -286,6 +285,17 @@ const ShareView = ({ quicknote = false }) => {
setLoadingIntent(false);
}, [onLoad]);
+ const onLoad = useCallback(() => {
+ eSendEvent(eOnLoadNote + "shareEditor", {
+ id: null,
+ content: {
+ type: "tiptap",
+ data: noteContent.current
+ },
+ forced: true
+ });
+ }, []);
+
useEffect(() => {
(async () => {
//await loadDatabase();
@@ -306,24 +316,6 @@ const ShareView = ({ quicknote = false }) => {
}
};
- const onLoad = useCallback(
- (editor) => {
- if (editor) {
- Storage.write("shareExtensionOpened", "opened");
- return loadData();
- }
- eSendEvent(eOnLoadNote + "shareEditor", {
- id: null,
- content: {
- type: "tiptap",
- data: noteContent.current
- },
- forced: true
- });
- },
- [loadData]
- );
-
const onPress = async () => {
setLoading(true);
await db.init();
@@ -392,6 +384,11 @@ const ShareView = ({ quicknote = false }) => {
}
};
+ const onLoadEditor = useCallback(() => {
+ Storage.write("shareExtensionOpened", "opened");
+ loadData();
+ }, [loadData]);
+
return loadingExtension ? null : (
<SafeAreaView
style={{
@@ -608,9 +605,7 @@ const ShareView = ({ quicknote = false }) => {
noHeader={true}
noToolbar={true}
readonly={false}
- onLoad={() => {
- onLoad(true);
- }}
+ onLoad={onLoadEditor}
onChange={(html) => {
noteContent.current = html;
}}
diff --git a/packages/editor-mobile/src/components/editor.tsx b/packages/editor-mobile/src/components/editor.tsx
index 04a50a3f4..e5bd71c15 100644
--- a/packages/editor-mobile/src/components/editor.tsx
+++ b/packages/editor-mobile/src/components/editor.tsx
@@ -95,7 +95,6 @@ const Tiptap = ({
const update = useCallback(() => {
setTick((tick) => tick + 1);
-
globalThis.editorController.setTitlePlaceholder("Note title");
}, []);