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
feat: manage attachments
ammarahm-ed14090ea37108
diff --git a/apps/mobile/src/components/attachments/actions.js b/apps/mobile/src/components/attachments/actions.jsnew file mode 100644index 000000000..5c353f6fb--- /dev/null+++ b/apps/mobile/src/components/attachments/actions.js@@ -0,0 +1,222 @@+import Clipboard from '@react-native-clipboard/clipboard';+import React, { useState } from 'react';+import { View } from 'react-native';+import picker from '../../screens/editor/tiny/toolbar/picker';+import { eSendEvent, presentSheet, ToastEvent } from '../../services/event-manager';+import { useAttachmentStore } from '../../stores/stores';+import { useThemeStore } from '../../stores/theme';+import { formatBytes } from '../../utils';+import { db } from '../../utils/database';+import { eCloseProgressDialog } from '../../utils/events';+import filesystem from '../../utils/filesystem';+import { useAttachmentProgress } from '../../utils/hooks/use-attachment-progress';+import { SIZE } from '../../utils/size';+import { Dialog } from '../dialog';+import { presentDialog } from '../dialog/functions';+import { DateMeta } from '../properties/date-meta';+import { Button } from '../ui/button';+import { Notice } from '../ui/notice';+import Heading from '../ui/typography/heading';+import Paragraph from '../ui/typography/paragraph';++const Actions = ({ attachment, setAttachments }) => {+ const colors = useThemeStore(state => state.colors);+ const contextId = attachment.metadata.hash;+ const [filename, setFilename] = useState(attachment.metadata.filename);+ const [currentProgress, setCurrentProgress] = useAttachmentProgress(attachment);+ const [failed, setFailed] = useState(attachment.failed);++ const actions = [+ {+ name: 'Download',+ onPress: async () => {+ if (currentProgress) {+ await db.fs.cancel(attachment.metadata.hash, 'download');+ useAttachmentStore.getState().remove(attachment.metadata.hash);+ }+ filesystem.downloadAttachment(attachment.metadata.hash, false);+ eSendEvent(eCloseProgressDialog, contextId);+ },+ icon: 'download'+ },+ {+ name: 'Reupload',+ onPress: async () => {+ await picker.pick({+ reupload: true,+ hash: attachment.metadata.hash,+ context: contextId,+ type: attachment.metadata.type+ });+ },+ icon: 'upload'+ },+ {+ name: 'Run file check',+ onPress: async () => {+ let res = await filesystem.checkAttachment(attachment.metadata.hash);+ if (res.failed) {+ db.attachments.markAsFailed(attachment.id, res.failed);+ setFailed(res.failed);+ }+ },+ icon: 'file-check'+ },+ {+ name: 'Rename',+ onPress: () => {+ presentDialog({+ context: contextId,+ input: true,+ title: 'Rename file',+ paragraph: 'Enter a new name for the file',+ defaultValue: attachment.metadata.filename,+ positivePress: async value => {+ if (value && value.length > 0) {+ await db.attachments.add({+ hash: attachment.metadata.hash,+ filename: value+ });+ setFilename(value);+ setAttachments([...db.attachments.all]);+ }+ },+ positiveText: 'Rename'+ });+ },+ icon: 'form-textbox'+ },+ {+ name: 'Delete',+ onPress: async () => {+ await db.attachments.remove(attachment.metadata.hash, false);+ setAttachments([...db.attachments.all]);+ eSendEvent(eCloseProgressDialog, contextId);+ },+ icon: 'delete-outline'+ }+ ];+ console.log(attachment);++ return (+ <View>+ <Dialog context={contextId} />+ <View+ style={{+ marginBottom: 12,+ borderBottomWidth: 1,+ borderBottomColor: colors.nav+ }}+ >+ <Heading+ style={{+ paddingHorizontal: 12+ }}+ size={SIZE.lg}+ >+ {filename}+ </Heading>++ <View+ style={{+ flexDirection: 'row',+ marginBottom: 10,+ paddingHorizontal: 12+ }}+ >+ <Paragraph+ size={SIZE.xs + 1}+ style={{+ marginRight: 10+ }}+ color={colors.icon}+ >+ {attachment.metadata.type}+ </Paragraph>+ <Paragraph+ style={{+ marginRight: 10+ }}+ size={SIZE.xs + 1}+ color={colors.icon}+ >+ {formatBytes(attachment.length)}+ </Paragraph>++ <Paragraph+ style={{+ marginRight: 10+ }}+ size={SIZE.xs + 1}+ color={colors.icon}+ >+ {attachment.noteIds.length} note{attachment.noteIds.length > 1 ? 's' : ''}+ </Paragraph>+ <Paragraph+ onPress={() => {+ Clipboard.setString(attachment.metadata.hash);+ ToastEvent.show({+ type: 'success',+ heading: 'Attachment hash copied',+ context: 'local'+ });+ }}+ size={SIZE.xs + 1}+ color={colors.icon}+ >+ {attachment.metadata.hash}+ </Paragraph>+ </View>++ <DateMeta item={attachment} />+ </View>++ {actions.map(item => (+ <Button+ key={item.name}+ buttonType={{+ text: item.on+ ? colors.accent+ : item.name === 'Delete' || item.name === 'PermDelete'+ ? colors.errorText+ : colors.pri+ }}+ onPress={item.onPress}+ title={item.name}+ icon={item.icon}+ type={item.on ? 'shade' : 'gray'}+ fontSize={SIZE.sm}+ style={{+ borderRadius: 0,+ justifyContent: 'flex-start',+ alignSelf: 'flex-start',+ width: '100%'+ }}+ />+ ))}++ <View+ style={{+ paddingHorizontal: 12+ }}+ >+ {failed ? (+ <Notice+ type="alert"+ text={`File check failed with error: ${attachment.failed} Try reuploading the file to fix the issue.`}+ size="small"+ />+ ) : null}+ </View>+ </View>+ );+};++Actions.present = (attachment, set, context) => {+ presentSheet({+ context: context,+ component: <Actions setAttachments={set} attachment={attachment} />+ });+};++export default Actions;diff --git a/apps/mobile/src/components/attachments/attachmentitem.js b/apps/mobile/src/components/attachments/attachmentitem.jsindex 5dacc1898..17b25ca75 100644--- a/apps/mobile/src/components/attachments/attachmentitem.js+++ b/apps/mobile/src/components/attachments/attachmentitem.js@@ -1,77 +1,37 @@-import React, { useEffect, useState } from 'react';+import React from 'react';import { TouchableOpacity, View } from 'react-native';import * as Progress from 'react-native-progress';import Icon from 'react-native-vector-icons/MaterialCommunityIcons';-import { useThemeStore } from '../../stores/theme';import { useAttachmentStore } from '../../stores/stores';+import { useThemeStore } from '../../stores/theme';+import { formatBytes } from '../../utils';import { db } from '../../utils/database';-import filesystem from '../../utils/filesystem';+import { useAttachmentProgress } from '../../utils/hooks/use-attachment-progress';import { SIZE } from '../../utils/size';import SheetProvider from '../sheet-provider';import { IconButton } from '../ui/icon-button';import Paragraph from '../ui/typography/paragraph';--function formatBytes(bytes, decimals = 2) {- if (bytes === 0) return '0 Bytes';-- const k = 1024;- const dm = decimals < 0 ? 0 : decimals;- const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];-- const i = Math.floor(Math.log(bytes) / Math.log(k));-- return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];-}+import Actions from './actions';function getFileExtension(filename) {var ext = /^.+\.([^.]+)$/.exec(filename);return ext == null ? '' : ext[1];}-export const AttachmentItem = ({ attachment, encryption }) => {+export const AttachmentItem = ({ attachment, encryption, setAttachments }) => {const colors = useThemeStore(state => state.colors);- const progress = useAttachmentStore(state => state.progress);- const [currentProgress, setCurrentProgress] = useState(- encryption- ? {- type: 'encrypt'- }- : null- );+ const [currentProgress, setCurrentProgress] = useAttachmentProgress(attachment, encryption);const encryptionProgress = encryption? useAttachmentStore(state => state.encryptionProgress): null;- const onPress = async () => {- if (currentProgress) {- db.fs.cancel(attachment.metadata.hash, 'download');- useAttachmentStore.getState().remove(attachment.metadata.hash);- return;- }- filesystem.downloadAttachment(attachment.metadata.hash, false);+ const onPress = () => {+ Actions.present(attachment, setAttachments, attachment.metadata.hash);};-- useEffect(() => {- let prog = progress[attachment.metadata.hash];- if (prog) {- let type = prog.type;- let loaded = prog.type === 'download' ? prog.recieved : prog.sent;- prog = loaded / prog.total;- prog = (prog * 100).toFixed(0);- console.log('progress: ', prog);- console.log(prog);- setCurrentProgress({- value: prog,- percent: prog + '%',- type: type- });- } else {- setCurrentProgress(null);- }- }, [progress]);-return (- <View+ <TouchableOpacity+ activeOpacity={0.9}+ onPress={onPress}style={{flexDirection: 'row',marginVertical: 5,@@ -173,13 +133,12 @@ export const AttachmentItem = ({ attachment, encryption }) => {/></TouchableOpacity>) : (- <IconButton- onPress={() => !encryption && onPress(attachment)}- name="download"- size={SIZE.lg}- color={colors.pri}- />+ <>+ {attachment.failed ? (+ <IconButton onPress={onPress} name="alert-circle-outline" color={colors.errorText} />+ ) : null}+ </>)}- </View>+ </TouchableOpacity>);};diff --git a/apps/mobile/src/components/attachments/index.js b/apps/mobile/src/components/attachments/index.jsindex 72fe1193a..dfbd8b2c1 100644--- a/apps/mobile/src/components/attachments/index.js+++ b/apps/mobile/src/components/attachments/index.js@@ -2,12 +2,16 @@ import React, { useEffect, useRef, useState } from 'react';import { View } from 'react-native';import { FlatList } from 'react-native-gesture-handler';import Icon from 'react-native-vector-icons/MaterialCommunityIcons';-import { useThemeStore } from '../../stores/theme';import { eSubscribeEvent, eUnSubscribeEvent } from '../../services/event-manager';+import { useThemeStore } from '../../stores/theme';import { db } from '../../utils/database';import { eCloseAttachmentDialog, eOpenAttachmentsDialog } from '../../utils/events';+import filesystem from '../../utils/filesystem';import { SIZE } from '../../utils/size';import DialogHeader from '../dialog/dialog-header';+import { Toast } from '../toast';+import Input from '../ui/input';+import Seperator from '../ui/seperator';import SheetWrapper from '../ui/sheet';import Paragraph from '../ui/typography/paragraph';import { AttachmentItem } from './attachment-item';@@ -17,6 +21,8 @@ export const AttachmentDialog = () => {const [note, setNote] = useState(null);const actionSheetRef = useRef();const [attachments, setAttachments] = useState([]);+ const attachmentSearchValue = useRef();+ const searchTimer = useRef();useEffect(() => {eSubscribeEvent(eOpenAttachmentsDialog, open);@@ -27,11 +33,15 @@ export const AttachmentDialog = () => {};}, [visible]);- const open = item => {- setNote(item);+ const open = data => {+ if (data?.id) {+ setNote(data);+ let _attachments = db.attachments.ofNote(data.id, 'all');+ setAttachments(_attachments);+ } else {+ setAttachments([...db.attachments.all]);+ }setVisible(true);- let _attachments = db.attachments.ofNote(item.id, 'all');- setAttachments(_attachments);};useEffect(() => {@@ -45,6 +55,27 @@ export const AttachmentDialog = () => {setVisible(false);};+ const onChangeText = text => {+ attachmentSearchValue.current = text;+ console.log(attachmentSearchValue.current?.length);+ if (!attachmentSearchValue.current || attachmentSearchValue.current === '') {+ console.log('resetting all');+ setAttachments([...db.attachments.all]);+ }+ console.log(attachments.length);+ clearTimeout(searchTimer.current);+ searchTimer.current = setTimeout(() => {+ let results = db.lookup.attachments(db.attachments.all, attachmentSearchValue.current);+ console.log('results', results.length, attachments.length);+ if (results.length === 0) return;+ setAttachments(results);+ }, 300);+ };++ const renderItem = ({ item, index }) => (+ <AttachmentItem setAttachments={setAttachments} attachment={item} />+ );+return !visible ? null : (<SheetWrappercentered={false}@@ -53,6 +84,7 @@ export const AttachmentDialog = () => {setVisible(false);}}>+ <Toast context="local" /><Viewstyle={{width: '100%',@@ -60,7 +92,34 @@ export const AttachmentDialog = () => {paddingHorizontal: 12}}>- <DialogHeader title="Attachments" />+ <DialogHeader+ title={note ? 'Attachments' : 'Manage attachments'}+ paragraph="Tap on an attachment to view properties"+ button={{+ title: 'Check all',+ type: 'accent',+ onPress: async () => {+ for (let attachment of attachments) {+ let result = await filesystem.checkAttachment(attachment.metadata.hash);+ if (result.failed) {+ db.attachments.markAsFailed(attachment.metadata.hash, result.failed);+ }+ }+ setAttachments([...db.attachments.all]);+ }+ }}+ />+ <Seperator />+ {!note ? (+ <Input+ placeholder="Filter attachments by filename, type or hash"+ onChangeText={onChangeText}+ onSubmit={() => {+ onChangeText(attachmentSearchValue.current);+ }}+ />+ ) : null}+<FlatListnestedScrollEnabledoverScrollMode="never"@@ -79,13 +138,19 @@ export const AttachmentDialog = () => {}}><Icon name="attachment" size={60} color={colors.icon} />- <Paragraph>No attachments on this note</Paragraph>+ <Paragraph>{note ? `No attachments on this note` : `No attachments`}</Paragraph></View>}+ ListFooterComponent={+ <View+ style={{+ height: 350+ }}+ />+ }data={attachments}- renderItem={({ item, index }) => (- <AttachmentItem attachment={item} note={note} setNote={setNote} />- )}+ keyExtractor={item => item.id}+ renderItem={renderItem}/><Paragraphdiff --git a/apps/mobile/src/components/dialogprovider/index.js b/apps/mobile/src/components/dialogprovider/index.jsindex a30d7db90..62dd9c70c 100644--- a/apps/mobile/src/components/dialogprovider/index.js+++ b/apps/mobile/src/components/dialogprovider/index.js@@ -23,35 +23,38 @@ import SheetProvider from '../sheet-provider';import ManageTagsSheet from '../sheets/manage-tags';import { VaultDialog } from '../dialogs/vault';-function DialogProvider() {- const colors = useThemeStore(state => state.colors);+const DialogProvider = React.memo(+ () => {+ const colors = useThemeStore(state => state.colors);- return (- <>- <Dialog context="global" />- <AddTopicDialog colors={colors} />- <AddNotebookSheet colors={colors} />- <PremiumDialog colors={colors} />- <Auth colors={colors} />- <MergeConflicts />- <ExportNotesSheet />- <RecoveryKeySheet colors={colors} />- <SheetProvider />- <RestoreDataSheet />- <ResultDialog />- <VaultDialog colors={colors} />- <AddToNotebookSheet colors={colors} />- <RateAppSheet />- <ImagePreview />- <EditorSettings />- <PublishNoteSheet />- <ManageTagsSheet />- <AttachmentDialog />- <Expiring />- <AnnouncementDialog />- <SessionExpired />- </>- );-}+ return (+ <>+ <Dialog context="global" />+ <AddTopicDialog colors={colors} />+ <AddNotebookSheet colors={colors} />+ <PremiumDialog colors={colors} />+ <Auth colors={colors} />+ <MergeConflicts />+ <ExportNotesSheet />+ <RecoveryKeySheet colors={colors} />+ <SheetProvider />+ <RestoreDataSheet />+ <ResultDialog />+ <VaultDialog colors={colors} />+ <AddToNotebookSheet colors={colors} />+ <RateAppSheet />+ <ImagePreview />+ <EditorSettings />+ <PublishNoteSheet />+ <ManageTagsSheet />+ <AttachmentDialog />+ <Expiring />+ <AnnouncementDialog />+ <SessionExpired />+ </>+ );+ },+ () => true+);-export default React.memo(DialogProvider, () => true);+export default DialogProvider;diff --git a/apps/mobile/src/components/launcher/index.js b/apps/mobile/src/components/launcher/index.jsindex 7308e8e61..ef4237f6a 100644--- a/apps/mobile/src/components/launcher/index.js+++ b/apps/mobile/src/components/launcher/index.js@@ -110,6 +110,9 @@ const Launcher = () => {if (!loading) {doAppLoadActions();}+ return () => {+ dbInitCompleted.current = false;+ };}, [loading]);const doAppLoadActions = async () => {diff --git a/apps/mobile/src/components/properties/datemeta.js b/apps/mobile/src/components/properties/datemeta.jsindex b41b4399b..b4970a153 100644--- a/apps/mobile/src/components/properties/datemeta.js+++ b/apps/mobile/src/components/properties/datemeta.js@@ -16,6 +16,8 @@ export const DateMeta = ({ item }) => {return 'Last edited at:';case 'dateDeleted':return 'Deleted at:';+ case 'dateUploaded':+ return 'Uploaded at:';default:return key;}diff --git a/apps/mobile/src/components/sheetprovider/index.js b/apps/mobile/src/components/sheetprovider/index.jsindex a2ae95add..ddcb7d6e8 100644--- a/apps/mobile/src/components/sheetprovider/index.js+++ b/apps/mobile/src/components/sheetprovider/index.js@@ -72,9 +72,8 @@ const SheetProvider = ({ context = 'global' }) => {}, [visible, dialogData]);const close = ctx => {- if ((ctx && !context) || (ctx && ctx !== context)) {- return;- }+ if (!ctx) ctx = 'global';+ if (ctx !== context) return;actionSheetRef.current?.setModalVisible(false);};diff --git a/apps/mobile/src/components/ui/notice/index.tsx b/apps/mobile/src/components/ui/notice/index.tsxindex 86ee26bb6..f9384ef60 100644--- a/apps/mobile/src/components/ui/notice/index.tsx+++ b/apps/mobile/src/components/ui/notice/index.tsx@@ -25,7 +25,7 @@ export const Notice = ({ type = 'alert', text, size = 'large' }: NoticeProps) =>}}><IconButton- size={isSmall ? SIZE.xs + 1 : SIZE.xxl}+ size={isSmall ? SIZE.lg + 1 : SIZE.xxl}name={type}customStyle={{width: isSmall ? undefined : 40,diff --git a/apps/mobile/src/screens/editor/tiny/toolbar/picker.js b/apps/mobile/src/screens/editor/tiny/toolbar/picker.jsindex d13a4f414..b26f625ee 100644--- a/apps/mobile/src/screens/editor/tiny/toolbar/picker.js+++ b/apps/mobile/src/screens/editor/tiny/toolbar/picker.js@@ -48,7 +48,7 @@ const santizeUri = uri => {return uri;};-const file = async () => {+const file = async fileOptions => {try {let options = {mode: 'import',@@ -104,7 +104,7 @@ const file = async () => {type: 'url'});console.log('decoded uri: ', uri);- let result = await attachFile(uri, hash, file.type, file.name, 'file');+ let result = await attachFile(uri, hash, file.type, file.name, fileOptions);console.log('attach file: ', result);setTimeout(() => {@@ -143,7 +143,7 @@ const file = async () => {}};-const camera = async () => {+const camera = async options => {try {await db.attachments.generateKey();eSendEvent(eCloseProgressDialog);@@ -156,7 +156,7 @@ const camera = async () => {quality: 0.8,mediaType: 'photo'},- handleImageResponse+ response => handleImageResponse(response, options));} catch (e) {ToastEvent.show({@@ -169,7 +169,7 @@ const camera = async () => {}};-const gallery = async () => {+const gallery = async options => {try {await db.attachments.generateKey();eSendEvent(eCloseProgressDialog);@@ -183,7 +183,7 @@ const gallery = async () => {mediaType: 'photo',selectionLimit: 1},- handleImageResponse+ response => handleImageResponse(response, options));} catch (e) {ToastEvent.show({@@ -196,7 +196,7 @@ const gallery = async () => {}};-const pick = async () => {+const pick = async options => {if (!PremiumService.get()) {let user = await db.user.getUser();if (editing.isFocused) {@@ -210,28 +210,40 @@ const pick = async () => {}return;}++ if (options?.reupload) {+ if (options?.type.startsWith('image')) {+ gallery(options);+ } else {+ file(options);+ }+ return;+ }+if (editing.isFocused) {safeKeyboardDismiss();editing.isFocused = true;}+presentSheet({+ context: options?.context,actionsArray: [{action: async () => {eSendEvent(eCloseProgressDialog);await sleep(400);- await file();+ await file(options);},actionText: 'Attach a file',icon: 'file'},{- action: camera,+ action: () => camera(options),actionText: 'Open camera',icon: 'camera'},{- action: gallery,+ action: () => gallery(options),actionText: 'Select image from gallery',icon: 'image-multiple'}@@ -241,7 +253,7 @@ const pick = async () => {return;};-const handleImageResponse = async response => {+const handleImageResponse = async (response, options) => {if (response.didCancel ||response.errorMessage ||@@ -267,8 +279,9 @@ const handleImageResponse = async response => {uri: uri,type: 'url'});+let fileName = image.originalFileName || image.fileName;- let result = await attachFile(uri, hash, image.type, fileName, 'image');+ let result = await attachFile(uri, hash, image.type, fileName, options);if (!result) return;tiny.call(EditorWebView,@@ -293,11 +306,22 @@ const handleImageResponse = async response => {);};-async function attachFile(uri, hash, type, filename) {+async function attachFile(uri, hash, type, filename, options) {try {let exists = db.attachments.exists(hash);let encryptionInfo;- if (!exists) {++ if (options?.hash && options.hash !== hash) {+ ToastEvent.show({+ heading: 'Please select the same file for reuploading',+ message: `Expected hash ${options.hash} but got ${hash}.`,+ type: 'error',+ context: 'local'+ });+ return false;+ }++ if (!exists || options?.reupload) {let key = await db.attachments.generateKey();encryptionInfo = await Sodium.encryptFile(key, {uri: uri,@@ -309,6 +333,7 @@ async function attachFile(uri, hash, type, filename) {encryptionInfo.alg = `xcha-stream`;encryptionInfo.size = encryptionInfo.length;encryptionInfo.key = key;+ if (options?.reupload && exists) await db.attachments.reset(hash);} else {encryptionInfo = { hash: hash };}diff --git a/apps/mobile/src/screens/settings/usersection.js b/apps/mobile/src/screens/settings/usersection.jsindex 6ed88967e..fa8975908 100644--- a/apps/mobile/src/screens/settings/usersection.js+++ b/apps/mobile/src/screens/settings/usersection.js@@ -20,6 +20,7 @@ import {} from '../../utils/constants';import {eCloseProgressDialog,+ eOpenAttachmentsDialog,eOpenLoginDialog,eOpenPremiumDialog,eOpenRecoveryKeyDialog@@ -266,6 +267,13 @@ const SettingsUserSection = () => {},desc: 'Recover your data using the recovery key if your password is lost.'},+ {+ name: 'Manage attachments',+ func: () => {+ eSendEvent(eOpenAttachmentsDialog);+ },+ desc: 'Manage all attachments in one place.'+ },{name: 'Change password',func: async () => {diff --git a/apps/mobile/src/services/eventmanager.ts b/apps/mobile/src/services/eventmanager.tsindex 1561644de..6d35703cb 100644--- a/apps/mobile/src/services/eventmanager.ts+++ b/apps/mobile/src/services/eventmanager.ts@@ -76,7 +76,7 @@ export const ToastEvent = {message,type = 'error',context,- duration,+ duration = 3000,func,actionText}: ShowToastEvent) =>diff --git a/apps/mobile/src/utils/filesystem/download.js b/apps/mobile/src/utils/filesystem/download.jsindex 4d4b4445b..cbf5d6cab 100644--- a/apps/mobile/src/utils/filesystem/download.js+++ b/apps/mobile/src/utils/filesystem/download.js@@ -9,6 +9,7 @@ import { presentSheet, ToastEvent } from '../../services/event-manager';import { db } from '../database';import Storage from '../database/storage';import { cacheDir, fileCheck } from './utils';+import hosts from 'notes-core/utils/constants';export async function downloadFile(filename, data, cancelToken) {if (!data) return false;@@ -54,7 +55,14 @@ export async function downloadFile(filename, data, cancelToken) {ToastEvent.show({heading: 'Error downloading file',message: e.message,- type: 'error'+ type: 'error',+ context: 'global'+ });+ ToastEvent.show({+ heading: 'Error downloading file',+ message: e.message,+ type: 'error',+ context: 'local'});useAttachmentStore.getState().remove(filename);@@ -138,3 +146,29 @@ export async function downloadAttachment(hash, global = true) {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();++ const attachmentInfo = await fetch(url, {+ method: 'HEAD',+ headers: { Authorization: `Bearer ${token}` }+ });++ const contentLength = parseInt(attachmentInfo.headers['content-length']);+ return isNaN(contentLength) ? 0 : contentLength;+}++export async function checkAttachment(hash) {+ const attachment = db.attachments.attachment(hash);+ if (!attachment) return { failed: 'Attachment not found.' };++ try {+ const size = await getUploadedFileSize(hash);+ if (size <= 0) return { failed: 'File length is 0.' };+ } catch (e) {+ return { failed: e.message };+ }+ return { success: true };+}diff --git a/apps/mobile/src/utils/filesystem/index.js b/apps/mobile/src/utils/filesystem/index.jsindex 4402e7cd9..c7e1753d5 100644--- a/apps/mobile/src/utils/filesystem/index.js+++ b/apps/mobile/src/utils/filesystem/index.js@@ -1,4 +1,4 @@-import { downloadAttachment, downloadFile } from './download';+import { downloadAttachment, downloadFile, getUploadedFileSize, checkAttachment } from './download';import { clearFileStorage, deleteFile, exists, readEncrypted, writeEncrypted } from './io';import { uploadFile } from './upload';import { cancelable } from './utils';@@ -11,5 +11,7 @@ export default {deleteFile,exists,downloadAttachment,- clearFileStorage+ clearFileStorage,+ getUploadedFileSize,+ checkAttachment};diff --git a/apps/mobile/src/utils/filesystem/io.js b/apps/mobile/src/utils/filesystem/io.jsindex 95465f736..6b98cbd0c 100644--- a/apps/mobile/src/utils/filesystem/io.js+++ b/apps/mobile/src/utils/filesystem/io.js@@ -48,9 +48,9 @@ export async function writeEncrypted(filename, { data, type, key }) {}export async function deleteFile(filename, data) {+ let delFilePath = cacheDir + `/${filename}`;if (!data) {if (!filename) return;- let delFilePath = cacheDir + `/${filename}`;RNFetchBlob.fs.unlink(delFilePath).catch(console.log);return true;}@@ -59,7 +59,9 @@ export async function deleteFile(filename, data) {try {let response = await RNFetchBlob.fetch('DELETE', url, headers);let status = response.info().status;- return status >= 200 && status < 300;+ if (status >= 200 && status < 300) {+ RNFetchBlob.fs.unlink(delFilePath).catch(console.log);+ }} catch (e) {console.log('delete file: ', e, url, headers);return false;diff --git a/apps/mobile/src/utils/filesystem/utils.js b/apps/mobile/src/utils/filesystem/utils.jsindex 926679cc9..05ca87d68 100644--- a/apps/mobile/src/utils/filesystem/utils.js+++ b/apps/mobile/src/utils/filesystem/utils.js@@ -16,7 +16,6 @@ export function extractValueFromXmlTag(code, xml) {export async function fileCheck(response, totalSize) {if (totalSize < 1000) {let text = await response.text();- console.log(text);if (text.startsWith('<?xml')) {let errorJson = {Code: extractValueFromXmlTag('Code', text),diff --git a/apps/mobile/src/utils/hooks/useAttachmentProgress.js b/apps/mobile/src/utils/hooks/useAttachmentProgress.jsnew file mode 100644index 000000000..8ce8a0acf--- /dev/null+++ b/apps/mobile/src/utils/hooks/useAttachmentProgress.js@@ -0,0 +1,34 @@+import { useEffect, useState } from 'react';+import { useAttachmentStore } from '../../stores/stores';++export const useAttachmentProgress = (attachment, encryption) => {+ const progress = useAttachmentStore(state => state.progress);+ const [currentProgress, setCurrentProgress] = useState(+ encryption+ ? {+ type: 'encrypt'+ }+ : null+ );++ useEffect(() => {+ let prog = progress[attachment.metadata.hash];+ if (prog) {+ let type = prog.type;+ let loaded = prog.type === 'download' ? prog.recieved : prog.sent;+ prog = loaded / prog.total;+ prog = (prog * 100).toFixed(0);+ console.log('progress: ', prog);+ console.log(prog);+ setCurrentProgress({+ value: prog,+ percent: prog + '%',+ type: type+ });+ } else {+ setCurrentProgress(null);+ }+ }, [progress]);++ return [currentProgress, setCurrentProgress];+};diff --git a/apps/mobile/src/utils/index.js b/apps/mobile/src/utils/index.jsindex 29ad46802..c093e4c2a 100755--- a/apps/mobile/src/utils/index.js+++ b/apps/mobile/src/utils/index.js@@ -47,6 +47,18 @@ export const history = {selectionMode: false};+export function formatBytes(bytes, decimals = 2) {+ if (bytes === 0) return '0 Bytes';++ const k = 1024;+ const dm = decimals < 0 ? 0 : decimals;+ const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];++ const i = Math.floor(Math.log(bytes) / Math.log(k));++ return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];+}+export const AndroidModule = NativeModules.NNativeModule;export let dWidth = Dimensions.get('window').width;diff --git a/apps/mobile/tsconfig.json b/apps/mobile/tsconfig.jsonindex cf1c2f080..6d96122b8 100644--- a/apps/mobile/tsconfig.json+++ b/apps/mobile/tsconfig.json@@ -13,7 +13,7 @@"allowSyntheticDefaultImports": true,"esModuleInterop": true,"skipLibCheck": false,- "maxNodeModuleJsDepth": 5,+ "maxNodeModuleJsDepth": 10,"downlevelIteration": true},"exclude": ["node_modules", "babel.config.js", "metro.config.js", "jest.config.js"]