Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add attachment file preview for images and text files (#1010)
Leendert de Borstfa6ff5153a88
diff --git a/apps/mobile-app/components/credentials/details/AttachmentSection.tsx b/apps/mobile-app/components/credentials/details/AttachmentSection.tsxindex 519125064..102a68ca7 100644--- a/apps/mobile-app/components/credentials/details/AttachmentSection.tsx+++ b/apps/mobile-app/components/credentials/details/AttachmentSection.tsx@@ -2,9 +2,10 @@ import { Buffer } from 'buffer';import { Ionicons } from '@expo/vector-icons';import * as FileSystem from 'expo-file-system';+import * as Sharing from 'expo-sharing';import React, { useState, useEffect, useCallback } from 'react';import { useTranslation } from 'react-i18next';-import { View, StyleSheet, TouchableOpacity, Alert, Share } from 'react-native';+import { View, StyleSheet, TouchableOpacity, Alert } from 'react-native';import type { Credential, Attachment } from '@/utils/dist/shared/models/vault';import emitter from '@/utils/EventEmitter';@@ -15,6 +16,8 @@ import { ThemedText } from '@/components/themed/ThemedText';import { ThemedView } from '@/components/themed/ThemedView';import { useDb } from '@/context/DbContext';+import { FilePreviewModal } from './FilePreviewModal';+type AttachmentSectionProps = {credential: Credential;};@@ -24,47 +27,146 @@ type AttachmentSectionProps = {*/export const AttachmentSection: React.FC<AttachmentSectionProps> = ({ credential }): React.ReactNode => {const [attachments, setAttachments] = useState<Attachment[]>([]);+ const [previewModalVisible, setPreviewModalVisible] = useState(false);+ const [selectedFile, setSelectedFile] = useState<{+ name: string;+ path: string;+ extension: string;+ } | null>(null);const colors = useColors();const dbContext = useDb();const { t } = useTranslation();/**- * Download and share an attachment.+ * Handle attachment action - preview or download.*/- const downloadAttachment = async (attachment: Attachment): Promise<void> => {+ const handleAttachment = async (attachment: Attachment): Promise<void> => {try {- const tempFile = `${FileSystem.cacheDirectory}${attachment.Filename}`;+ const filename = attachment.Filename;+ const fileExtension = filename.split('.').pop()?.toLowerCase() ?? '';+ const downloadsDir = FileSystem.documentDirectory + 'Downloads/';+ const filePath = downloadsDir + filename;- // Step 1: Create a Blob- if (typeof attachment.Blob === 'string') {- // If attachment.Blob is already a base64 string- const base64Data = attachment.Blob;+ // Ensure Downloads directory exists+ const dirInfo = await FileSystem.getInfoAsync(downloadsDir);+ if (!dirInfo.exists) {+ await FileSystem.makeDirectoryAsync(downloadsDir, { intermediates: true });+ }- await FileSystem.writeAsStringAsync(tempFile, base64Data, {- encoding: FileSystem.EncodingType.Base64,- });+ // Check if file already exists, if not, create it+ const fileInfo = await FileSystem.getInfoAsync(filePath);+ if (!fileInfo.exists) {+ if (typeof attachment.Blob === 'string') {+ await FileSystem.writeAsStringAsync(filePath, attachment.Blob, {+ encoding: FileSystem.EncodingType.Base64,+ });+ } else {+ const base64Data = Buffer.from(attachment.Blob as unknown as string, 'base64');+ await FileSystem.writeAsStringAsync(filePath, base64Data.toString(), {+ encoding: FileSystem.EncodingType.Base64,+ });+ }}- else {- // Convert attachment.Blob to base64- const base64Data = Buffer.from(attachment.Blob as unknown as string, 'base64');- await FileSystem.writeAsStringAsync(tempFile, base64Data.toString(), {- encoding: FileSystem.EncodingType.Base64,++ // Define supported file types+ const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];+ const textExtensions = ['txt', 'md', 'json', 'csv', 'log', 'xml', 'js', 'ts', 'tsx', 'jsx', 'html', 'css'];+ const previewableExtensions = [...imageExtensions, ...textExtensions];++ if (previewableExtensions.includes(fileExtension)) {+ // Show preview modal for supported file types+ setSelectedFile({+ name: filename,+ path: filePath,+ extension: fileExtension,});+ setPreviewModalVisible(true);+ } else {+ // For other file types, offer download directly+ await downloadFileToSystem(filePath, filename);}+ } catch (error) {+ console.error('Error handling attachment:', error);+ Alert.alert('Error', 'Failed to process attachment');+ }+ };- // Step 2: Share using Sharing API (better handles mime types)- await Share.share({- url: tempFile,- title: attachment.Filename,- });-- // Optional cleanup- await FileSystem.deleteAsync(tempFile);+ /**+ * Download file to system (iOS Files app or Android file manager).+ */+ const downloadFileToSystem = async (filePath: string, filename: string): Promise<void> => {+ try {+ const canShare = await Sharing.isAvailableAsync();+ if (canShare) {+ // Use Sharing API to trigger system save dialog+ await Sharing.shareAsync(filePath, {+ dialogTitle: `Save ${filename}`,+ mimeType: getMimeType(filename),+ UTI: getUTI(filename),+ });+ } else {+ Alert.alert(+ t('credentials.fileReady'),+ `${t('credentials.fileSavedTo')}: ${filePath}`+ );+ }} catch (error) {- console.error('Error downloading attachment:', error);- Alert.alert('Error', 'Failed to download attachment');+ console.error('Error downloading file:', error);+ Alert.alert('Error', 'Failed to download file');}};++ /**+ * Get MIME type for file.+ */+ const getMimeType = (filename: string): string => {+ const extension = filename.split('.').pop()?.toLowerCase() ?? '';+ const mimeTypes: Record<string, string> = {+ 'pdf': 'application/pdf',+ 'doc': 'application/msword',+ 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+ 'xls': 'application/vnd.ms-excel',+ 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+ 'ppt': 'application/vnd.ms-powerpoint',+ 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',+ 'txt': 'text/plain',+ 'csv': 'text/csv',+ 'xml': 'application/xml',+ 'json': 'application/json',+ 'zip': 'application/zip',+ 'jpg': 'image/jpeg',+ 'jpeg': 'image/jpeg',+ 'png': 'image/png',+ 'gif': 'image/gif',+ 'bmp': 'image/bmp',+ 'webp': 'image/webp',+ };+ return mimeTypes[extension] ?? 'application/octet-stream';+ };++ /**+ * Get UTI (Uniform Type Identifier) for iOS.+ */+ const getUTI = (filename: string): string => {+ const extension = filename.split('.').pop()?.toLowerCase() ?? '';+ const utis: Record<string, string> = {+ 'pdf': 'com.adobe.pdf',+ 'doc': 'com.microsoft.word.doc',+ 'docx': 'org.openxmlformats.wordprocessingml.document',+ 'xls': 'com.microsoft.excel.xls',+ 'xlsx': 'org.openxmlformats.spreadsheetml.sheet',+ 'txt': 'public.plain-text',+ 'csv': 'public.comma-separated-values-text',+ 'xml': 'public.xml',+ 'json': 'public.json',+ 'zip': 'public.zip-archive',+ 'jpg': 'public.jpeg',+ 'jpeg': 'public.jpeg',+ 'png': 'public.png',+ 'gif': 'com.compuserve.gif',+ };+ return utis[extension] ?? 'public.data';+ };/*** Load the attachments.*/@@ -140,7 +242,7 @@ export const AttachmentSection: React.FC<AttachmentSectionProps> = ({ credential<TouchableOpacitykey={attachment.Id}style={styles.content}- onPress={() => downloadAttachment(attachment)}+ onPress={() => handleAttachment(attachment)}><View style={styles.attachmentItem}><View style={styles.attachmentInfo}>@@ -152,11 +254,24 @@ export const AttachmentSection: React.FC<AttachmentSectionProps> = ({ credential</ThemedText></View><View style={styles.downloadIcon}>- <Ionicons name="download-outline" size={24} color={colors.text} />+ <Ionicons name="eye-outline" size={24} color={colors.text} /></View></View></TouchableOpacity>))}++ {selectedFile && (+ <FilePreviewModal+ visible={previewModalVisible}+ onClose={() => {+ setPreviewModalVisible(false);+ setSelectedFile(null);+ }}+ fileName={selectedFile.name}+ filePath={selectedFile.path}+ fileExtension={selectedFile.extension}+ />+ )}</ThemedView>);};diff --git a/apps/mobile-app/components/credentials/details/FilePreviewModal.tsx b/apps/mobile-app/components/credentials/details/FilePreviewModal.tsxnew file mode 100644index 000000000..cae8c2796--- /dev/null+++ b/apps/mobile-app/components/credentials/details/FilePreviewModal.tsx@@ -0,0 +1,303 @@+import { Ionicons } from '@expo/vector-icons';+import * as FileSystem from 'expo-file-system';+import * as Sharing from 'expo-sharing';+import React, { useState, useEffect, useCallback } from 'react';+import { useTranslation } from 'react-i18next';+import {+ Modal,+ View,+ StyleSheet,+ TouchableOpacity,+ ScrollView,+ Image,+ Dimensions,+ Alert+} from 'react-native';++import { useColors } from '@/hooks/useColorScheme';++import { ThemedText } from '@/components/themed/ThemedText';+import { ThemedView } from '@/components/themed/ThemedView';++type FilePreviewModalProps = {+ visible: boolean;+ /**+ * Close modal handler.+ */+ onClose: () => void;+ fileName: string;+ filePath: string;+ fileExtension: string;+};++const { width: screenWidth, height: screenHeight } = Dimensions.get('window');++/**+ * File preview modal component for displaying images and text files.+ */+export const FilePreviewModal: React.FC<FilePreviewModalProps> = ({+ visible,+ onClose,+ fileName,+ filePath,+ fileExtension,+}) => {+ const [fileContent, setFileContent] = useState<string>('');+ const [loading, setLoading] = useState(true);+ const [fileSize, setFileSize] = useState<string>('');+ const colors = useColors();+ const { t } = useTranslation();++ const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];+ const textExtensions = ['txt', 'md', 'json', 'csv', 'log', 'xml', 'js', 'ts', 'tsx', 'jsx', 'html', 'css'];++ const isImage = imageExtensions.includes(fileExtension.toLowerCase());+ const isText = textExtensions.includes(fileExtension.toLowerCase());++ /**+ * Get file size formatted string.+ */+ const getFileSize = useCallback(async (): Promise<void> => {+ try {+ const fileInfo = await FileSystem.getInfoAsync(filePath);+ if (fileInfo.exists && 'size' in fileInfo) {+ const size = fileInfo.size;+ if (size < 1024) {+ setFileSize(`${size} B`);+ } else if (size < 1024 * 1024) {+ setFileSize(`${(size / 1024).toFixed(1)} KB`);+ } else {+ setFileSize(`${(size / (1024 * 1024)).toFixed(1)} MB`);+ }+ }+ } catch (error) {+ console.error('Error getting file size:', error);+ }+ }, [filePath]);++ /**+ * Load text file content.+ */+ const loadTextFile = useCallback(async (): Promise<void> => {+ try {+ setLoading(true);+ const content = await FileSystem.readAsStringAsync(filePath);+ setFileContent(content);+ } catch (error) {+ console.error('Error reading text file:', error);+ Alert.alert('Error', 'Could not read file content');+ setFileContent('Error loading file content');+ } finally {+ setLoading(false);+ }+ }, [filePath]);++ useEffect(() => {+ if (visible) {+ getFileSize();+ if (isText) {+ loadTextFile();+ } else {+ setLoading(false);+ }+ }+ }, [visible, filePath, isText, loadTextFile, getFileSize]);++ /**+ * Download file to system.+ */+ const downloadFile = async (): Promise<void> => {+ try {+ const canShare = await Sharing.isAvailableAsync();+ if (canShare) {+ await Sharing.shareAsync(filePath, {+ dialogTitle: `Save ${fileName}`,+ });+ } else {+ Alert.alert(+ t('credentials.fileReady'),+ `${t('credentials.fileSavedTo')}: ${filePath}`+ );+ }+ } catch (error) {+ console.error('Error downloading file:', error);+ Alert.alert('Error', 'Failed to download file');+ }+ };++ const styles = StyleSheet.create({+ closeButton: {+ alignItems: 'center',+ backgroundColor: colors.accentBackground,+ borderRadius: 20,+ height: 40,+ justifyContent: 'center',+ width: 40,+ },+ downloadButton: {+ alignItems: 'center',+ backgroundColor: colors.accentBackground,+ borderRadius: 20,+ height: 40,+ justifyContent: 'center',+ marginRight: 12,+ width: 40,+ },+ fileInfo: {+ flex: 1,+ marginRight: 12,+ },+ fileName: {+ fontSize: 16,+ fontWeight: '600',+ marginBottom: 2,+ },+ fileSize: {+ fontSize: 12,+ opacity: 0.7,+ },+ header: {+ alignItems: 'center',+ backgroundColor: colors.background,+ borderBottomColor: colors.border ?? colors.text + '20',+ borderBottomWidth: 1,+ flexDirection: 'row',+ paddingBottom: 12,+ paddingHorizontal: 20,+ paddingTop: 60,+ },+ headerButtons: {+ flexDirection: 'row',+ },+ image: {+ height: screenHeight * 0.8,+ resizeMode: 'contain',+ width: screenWidth,+ },+ loadingText: {+ fontSize: 16,+ textAlign: 'center',+ },+ modalView: {+ backgroundColor: colors.background,+ flex: 1,+ },+ scrollContainer: {+ flexGrow: 1,+ },+ textContent: {+ fontFamily: 'monospace',+ fontSize: 13,+ lineHeight: 20,+ padding: 20,+ },+ textScrollView: {+ flex: 1,+ },+ unsupportedContainer: {+ alignItems: 'center',+ flex: 1,+ justifyContent: 'center',+ padding: 40,+ },+ unsupportedSubtext: {+ fontSize: 14,+ opacity: 0.7,+ textAlign: 'center',+ },+ unsupportedText: {+ fontSize: 16,+ marginBottom: 16,+ textAlign: 'center',+ },+ });++ /**+ * Render the file content based on file type.+ */+ const renderContent = (): React.ReactNode => {+ if (loading) {+ return (+ <View style={styles.unsupportedContainer}>+ <ThemedText style={styles.loadingText}>+ {t('common.loading')}...+ </ThemedText>+ </View>+ );+ }++ if (isImage) {+ return (+ <ScrollView+ contentContainerStyle={styles.scrollContainer}+ maximumZoomScale={3}+ minimumZoomScale={1}+ >+ <Image+ source={{ uri: filePath }}+ style={styles.image}+ /**+ * Handle image load error.+ */+ onError={(): void => Alert.alert('Error', 'Could not load image')}+ />+ </ScrollView>+ );+ }++ if (isText) {+ return (+ <ScrollView style={styles.textScrollView}>+ <ThemedText style={styles.textContent}>+ {fileContent}+ </ThemedText>+ </ScrollView>+ );+ }++ return (+ <View style={styles.unsupportedContainer}>+ <Ionicons name="document-outline" size={80} color={colors.text} />+ <ThemedText style={styles.unsupportedText}>+ {t('credentials.previewNotSupported')}+ </ThemedText>+ <ThemedText style={styles.unsupportedSubtext}>+ {t('credentials.downloadToView')}+ </ThemedText>+ </View>+ );+ };++ return (+ <Modal+ animationType="slide"+ transparent={false}+ visible={visible}+ onRequestClose={onClose}+ >+ <ThemedView style={styles.modalView}>+ <View style={styles.header}>+ <View style={styles.fileInfo}>+ <ThemedText style={styles.fileName} numberOfLines={1}>+ {fileName}+ </ThemedText>+ {fileSize ? (+ <ThemedText style={styles.fileSize}>+ {fileSize}+ </ThemedText>+ ) : null}+ </View>+ <View style={styles.headerButtons}>+ <TouchableOpacity style={styles.downloadButton} onPress={downloadFile}>+ <Ionicons name="download-outline" size={20} color={colors.text} />+ </TouchableOpacity>+ <TouchableOpacity style={styles.closeButton} onPress={onClose}>+ <Ionicons name="close" size={20} color={colors.text} />+ </TouchableOpacity>+ </View>+ </View>+ {renderContent()}+ </ThemedView>+ </Modal>+ );+};