Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Update expo-file-system API for (email) attachment download (#150)

Leendert de Borstcc186d7497cb
diff --git a/apps/mobile-app/app/(tabs)/emails/[id].tsx b/apps/mobile-app/app/(tabs)/emails/[id].tsx
index 06a330103..47d48990b 100644
--- a/apps/mobile-app/app/(tabs)/emails/[id].tsx
+++ b/apps/mobile-app/app/(tabs)/emails/[id].tsx
@@ -1,11 +1,10 @@
-import { Buffer } from 'buffer';
-
import { Ionicons } from '@expo/vector-icons';
-import * as FileSystem from 'expo-file-system';
+import { File, Paths } from 'expo-file-system';
import { useLocalSearchParams, useRouter, useNavigation, Stack } from 'expo-router';
import React, { useEffect, useMemo, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { StyleSheet, View, ActivityIndicator, useColorScheme, Linking, Text, TextInput, Platform } from 'react-native';
+import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { WebView } from 'react-native-webview';
import ConversionUtility from '@/utils/ConversionUtility';
@@ -38,6 +37,7 @@ export default function EmailDetailsScreen() : React.ReactNode {
const colors = useColors();
const { t } = useTranslation();
const { openAttachment, viewerElement } = useAttachmentViewer();
+ const insets = useSafeAreaInsets();
const [error, setError] = useState<string | null>(null);
const [email, setEmail] = useState<Email | null>(null);
const [isLoading, setIsLoading] = useState(true);
@@ -168,21 +168,23 @@ export default function EmailDetailsScreen() : React.ReactNode {
return;
}
- // Convert decrypted bytes to base64 for FileSystem.writeAsStringAsync
- const base64Data = Buffer.from(decryptedBytes).toString('base64');
- const tempFile = `${FileSystem.cacheDirectory}${attachment.filename}`;
- await FileSystem.writeAsStringAsync(tempFile, base64Data, {
- encoding: FileSystem.EncodingType.Base64,
- });
+ const tempFile = new File(Paths.cache, attachment.filename);
+ if (tempFile.exists) {
+ tempFile.delete();
+ }
+ tempFile.create();
+ tempFile.write(decryptedBytes);
try {
await openAttachment({
- filePath: tempFile,
+ filePath: tempFile.uri,
fileName: attachment.filename,
mimeType: attachment.mimeType,
});
} finally {
- await FileSystem.deleteAsync(tempFile, { idempotent: true });
+ if (tempFile.exists) {
+ tempFile.delete();
+ }
}
} catch (err) {
console.error('handleDownloadAttachment error', err);
@@ -250,8 +252,9 @@ export default function EmailDetailsScreen() : React.ReactNode {
borderTopColor: colors.accentBorder,
borderTopWidth: 1,
gap: 4,
+ paddingBottom: Platform.OS === 'ios' ? insets.bottom + 60 : 8,
paddingHorizontal: 12,
- paddingVertical: 8,
+ paddingTop: 8,
},
attachmentsTitle: {
color: colors.text,
@@ -351,6 +354,8 @@ export default function EmailDetailsScreen() : React.ReactNode {
paddingTop: 4,
},
plainText: {
+ backgroundColor: '#ffffff',
+ color: '#000000',
flex: 1,
fontSize: 15,
padding: 16,
@@ -359,6 +364,10 @@ export default function EmailDetailsScreen() : React.ReactNode {
fontFamily: Platform.OS === 'ios' ? 'Menlo' : 'monospace',
fontSize: 12,
},
+ textContainer: {
+ backgroundColor: '#ffffff',
+ flex: 1,
+ },
subject: {
color: colors.text,
fontSize: 14,
@@ -371,12 +380,6 @@ export default function EmailDetailsScreen() : React.ReactNode {
paddingTop: 8,
width: '90%',
},
- textDark: {
- color: colors.text,
- },
- textLight: {
- color: colors.text,
- },
topBox: {
alignSelf: 'flex-start',
backgroundColor: colors.background,
@@ -555,21 +558,24 @@ export default function EmailDetailsScreen() : React.ReactNode {
const text = (isSource ? email.messageSource : email.messagePlain) ?? '';
const textStyle = [
styles.plainText,
- isDarkMode ? styles.textDark : styles.textLight,
isSource ? styles.sourceText : null,
];
- emailView = Platform.OS === 'ios' ? (
- <TextInput
- multiline
- editable={false}
- selectTextOnFocus={true}
- style={textStyle}
- value={text}
- />
- ) : (
- <Text selectable style={textStyle}>
- {text}
- </Text>
+ emailView = (
+ <View style={styles.textContainer}>
+ {Platform.OS === 'ios' ? (
+ <TextInput
+ multiline
+ editable={false}
+ selectTextOnFocus={true}
+ style={textStyle}
+ value={text}
+ />
+ ) : (
+ <Text selectable style={textStyle}>
+ {text}
+ </Text>
+ )}
+ </View>
);
}
diff --git a/apps/mobile-app/app/(tabs)/settings/import-export.tsx b/apps/mobile-app/app/(tabs)/settings/import-export.tsx
index dc0632b8b..86ecb84f1 100644
--- a/apps/mobile-app/app/(tabs)/settings/import-export.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/import-export.tsx
@@ -1,5 +1,5 @@
import { Ionicons } from '@expo/vector-icons';
-import * as FileSystem from 'expo-file-system';
+import { Directory, File, Paths } from 'expo-file-system';
import * as Sharing from 'expo-sharing';
import { useState } from 'react';
import { StyleSheet, View, TouchableOpacity } from 'react-native';
@@ -302,32 +302,32 @@ export default function ImportExportScreen(): React.ReactNode {
const csvContent = await itemsToCsv(items);
const filename = `aliasvault-export-${dateStr}.csv`;
- const downloadsDir = FileSystem.documentDirectory + 'Exports/';
- const filePath = downloadsDir + filename;
-
- // Ensure Exports directory exists
- const dirInfo = await FileSystem.getInfoAsync(downloadsDir);
- if (!dirInfo.exists) {
- await FileSystem.makeDirectoryAsync(downloadsDir, { intermediates: true });
+ const downloadsDir = new Directory(Paths.document, 'Exports');
+ if (!downloadsDir.exists) {
+ downloadsDir.create({ intermediates: true });
}
- // Write CSV file
- await FileSystem.writeAsStringAsync(filePath, csvContent, {
- encoding: FileSystem.EncodingType.UTF8,
- });
+ const file = new File(downloadsDir, filename);
+ if (file.exists) {
+ file.delete();
+ }
+ file.create();
+ file.write(csvContent);
// Share the file using the system share dialog
const canShare = await Sharing.isAvailableAsync();
if (canShare) {
- await Sharing.shareAsync(filePath, {
+ await Sharing.shareAsync(file.uri, {
dialogTitle: filename,
mimeType: 'text/csv',
});
// Clean up the temporary file after sharing
- setTimeout(async () => {
+ setTimeout(() => {
try {
- await FileSystem.deleteAsync(filePath, { idempotent: true });
+ if (file.exists) {
+ file.delete();
+ }
} catch (error) {
console.error('Error cleaning up export file:', error);
}
diff --git a/apps/mobile-app/components/common/FilePreviewModal.tsx b/apps/mobile-app/components/common/FilePreviewModal.tsx
index 2f1c85780..93d6ae2e3 100644
--- a/apps/mobile-app/components/common/FilePreviewModal.tsx
+++ b/apps/mobile-app/components/common/FilePreviewModal.tsx
@@ -1,5 +1,5 @@
import { Ionicons } from '@expo/vector-icons';
-import * as FileSystem from 'expo-file-system';
+import { File } from 'expo-file-system';
import * as Sharing from 'expo-sharing';
import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -58,11 +58,11 @@ export const FilePreviewModal: React.FC<FilePreviewModalProps> = ({
/**
* Get file size formatted string.
*/
- const getFileSize = useCallback(async (): Promise<void> => {
+ const getFileSize = useCallback((): void => {
try {
- const fileInfo = await FileSystem.getInfoAsync(filePath);
- if (fileInfo.exists && 'size' in fileInfo) {
- const size = fileInfo.size;
+ const file = new File(filePath);
+ if (file.exists) {
+ const size = file.size;
if (size < 1024) {
setFileSize(`${size} B`);
} else if (size < 1024 * 1024) {
@@ -82,7 +82,7 @@ export const FilePreviewModal: React.FC<FilePreviewModalProps> = ({
const loadTextFile = useCallback(async (): Promise<void> => {
try {
setLoading(true);
- const content = await FileSystem.readAsStringAsync(filePath);
+ const content = await new File(filePath).text();
setFileContent(content);
} catch (error) {
console.error('Error reading text file:', error);
diff --git a/apps/mobile-app/components/items/details/AttachmentSection.tsx b/apps/mobile-app/components/items/details/AttachmentSection.tsx
index e745c79ed..6b46b0397 100644
--- a/apps/mobile-app/components/items/details/AttachmentSection.tsx
+++ b/apps/mobile-app/components/items/details/AttachmentSection.tsx
@@ -1,7 +1,5 @@
-import { Buffer } from 'buffer';
-
import { MaterialIcons } from '@expo/vector-icons';
-import * as FileSystem from 'expo-file-system';
+import { Directory, File, Paths } from 'expo-file-system';
import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { View, StyleSheet, TouchableOpacity } from 'react-native';
@@ -39,33 +37,24 @@ export const AttachmentSection: React.FC<AttachmentSectionProps> = ({ item }): R
try {
// Sanitize filename
const sanitizedFilename = attachment.Filename.replace(/[/\\]/g, '_');
- const downloadsDir = FileSystem.documentDirectory + 'Downloads/';
- const filePath = downloadsDir + sanitizedFilename;
-
- // Ensure Downloads directory exists
- const dirInfo = await FileSystem.getInfoAsync(downloadsDir);
- if (!dirInfo.exists) {
- await FileSystem.makeDirectoryAsync(downloadsDir, { intermediates: true });
+ const downloadsDir = new Directory(Paths.document, 'Downloads');
+ if (!downloadsDir.exists) {
+ downloadsDir.create({ intermediates: true });
}
- // Always recreate file to ensure fresh data
- const fileInfo = await FileSystem.getInfoAsync(filePath);
- if (fileInfo.exists) {
- await FileSystem.deleteAsync(filePath);
+ const file = new File(downloadsDir, sanitizedFilename);
+ if (file.exists) {
+ file.delete();
}
+ file.create();
if (typeof attachment.Blob === 'string') {
- await FileSystem.writeAsStringAsync(filePath, attachment.Blob, {
- encoding: FileSystem.EncodingType.Base64,
- });
+ file.write(attachment.Blob, { encoding: 'base64' });
} else {
- const base64Data = Buffer.from(attachment.Blob as unknown as string, 'base64');
- await FileSystem.writeAsStringAsync(filePath, base64Data.toString(), {
- encoding: FileSystem.EncodingType.Base64,
- });
+ file.write(attachment.Blob as unknown as Uint8Array);
}
- await openAttachment({ filePath, fileName: sanitizedFilename });
+ await openAttachment({ filePath: file.uri, fileName: sanitizedFilename });
} catch (error) {
console.error('Error handling attachment:', error);
showAlert('Error', 'Failed to process attachment');
diff --git a/apps/mobile-app/components/items/details/AttachmentUploader.tsx b/apps/mobile-app/components/items/details/AttachmentUploader.tsx
index 3ee13381e..384b840f5 100644
--- a/apps/mobile-app/components/items/details/AttachmentUploader.tsx
+++ b/apps/mobile-app/components/items/details/AttachmentUploader.tsx
@@ -1,6 +1,6 @@
import { Ionicons } from '@expo/vector-icons';
import * as DocumentPicker from 'expo-document-picker';
-import * as FileSystem from 'expo-file-system';
+import { File, Paths } from 'expo-file-system';
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { View, StyleSheet, TouchableOpacity } from 'react-native';
@@ -47,32 +47,23 @@ export const AttachmentUploader: React.FC<AttachmentUploaderProps> = ({
for (const file of result.assets) {
if (file.uri) {
try {
- let fileUri = file.uri;
+ let sourceFile = new File(file.uri);
+ let tempFile: File | null = null;
/*
* If the URI is a content:// URI and copyToCacheDirectory didn't work,
* try to copy it to a readable location
*/
- if (fileUri.startsWith('content://')) {
- const tempUri = `${FileSystem.cacheDirectory}${file.name}`;
- await FileSystem.copyAsync({
- from: fileUri,
- to: tempUri,
- });
- fileUri = tempUri;
+ if (file.uri.startsWith('content://')) {
+ tempFile = new File(Paths.cache, file.name);
+ if (tempFile.exists) {
+ tempFile.delete();
+ }
+ await sourceFile.copy(tempFile);
+ sourceFile = tempFile;
}
- // Read file as base64 string using FileSystem
- const base64Data = await FileSystem.readAsStringAsync(fileUri, {
- encoding: FileSystem.EncodingType.Base64,
- });
-
- // Convert base64 to Uint8Array
- const binaryString = atob(base64Data);
- const byteArray = new Uint8Array(binaryString.length);
- for (let i = 0; i < binaryString.length; i++) {
- byteArray[i] = binaryString.charCodeAt(i);
- }
+ const byteArray = await sourceFile.bytes();
const attachment: Attachment = {
Id: crypto.randomUUID(),
@@ -87,9 +78,9 @@ export const AttachmentUploader: React.FC<AttachmentUploaderProps> = ({
newAttachments.push(attachment);
// Clean up temporary file if we created one
- if (fileUri !== file.uri) {
+ if (tempFile?.exists) {
try {
- await FileSystem.deleteAsync(fileUri);
+ tempFile.delete();
} catch (cleanupError) {
console.warn('Failed to cleanup temporary file:', cleanupError);
}
diff --git a/apps/mobile-app/hooks/useAttachmentViewer.tsx b/apps/mobile-app/hooks/useAttachmentViewer.tsx
index 5cf2264f8..dc629ba1b 100644
--- a/apps/mobile-app/hooks/useAttachmentViewer.tsx
+++ b/apps/mobile-app/hooks/useAttachmentViewer.tsx
@@ -1,4 +1,4 @@
-import * as FileSystem from 'expo-file-system';
+import { File } from 'expo-file-system';
import * as IntentLauncher from 'expo-intent-launcher';
import * as Sharing from 'expo-sharing';
import React, { useCallback, useRef, useState } from 'react';
@@ -88,7 +88,7 @@ export const useAttachmentViewer = (): {
if (Platform.OS === 'android') {
try {
- const contentUri = await FileSystem.getContentUriAsync(filePath);
+ const contentUri = new File(filePath).contentUri;
await IntentLauncher.startActivityAsync('android.intent.action.VIEW', {
data: contentUri,
flags: 1, // FLAG_GRANT_READ_URI_PERMISSION