Skip to content

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

4.7 KB
Raw Blame
import { MaterialIcons } from '@expo/vector-icons';
import { Directory, Paths } from 'expo-file-system';
import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { View, StyleSheet, TouchableOpacity } from 'react-native';

import type { Item, Attachment } from '@aliasvault/models/vault';
import { getFileForFilename } from '@/utils/FileUtility';

import { useAttachmentViewer } from '@/hooks/useAttachmentViewer';
import { useColors } from '@/hooks/useColorScheme';

import { ThemedText } from '@/components/themed/ThemedText';
import { ThemedView } from '@/components/themed/ThemedView';
import { useDb } from '@/context/DbContext';
import { useDialog } from '@/context/DialogContext';

type AttachmentSectionProps = {
  item: Item;
};

/**
 * Attachment section component.
 */
export const AttachmentSection: React.FC<AttachmentSectionProps> = ({ item }): React.ReactNode => {
  const [attachments, setAttachments] = useState<Omit<Attachment, 'Blob'>[]>([]);
  const blobsRef = useRef(new Map<string, Attachment['Blob']>());
  const colors = useColors();
  const dbContext = useDb();
  const { t } = useTranslation();
  const { showAlert } = useDialog();
  const { openAttachment, viewerElement } = useAttachmentViewer();

  /**
   * Handle attachment action - preview or download.
   */
  const handleAttachment = async (attachment: Omit<Attachment, 'Blob'>): Promise<void> => {
    try {
      const downloadsDir = new Directory(Paths.document, 'Downloads');
      if (!downloadsDir.exists) {
        downloadsDir.create({ intermediates: true });
      }

      const file = getFileForFilename(downloadsDir, attachment.Filename);
      if (file.exists) {
        file.delete();
      }
      file.create();

      const blob = blobsRef.current.get(attachment.Id);
      if (typeof blob === 'string') {
        file.write(blob, { encoding: 'base64' });
      } else {
        file.write((blob ?? new Uint8Array(0)) as unknown as Uint8Array);
      }

      await openAttachment({ filePath: file.uri, fileName: attachment.Filename });
    } catch (error) {
      console.error('Error handling attachment:', error);
      showAlert(t('common.error'), t('items.attachmentReadError'));
    }
  };

  useEffect(() => {
    /**
     * Load the attachments.
     */
    const loadAttachments = async (): Promise<void> => {
      if (!dbContext?.sqliteClient) {
        return;
      }

      try {
        const attachmentList = await dbContext.sqliteClient.items.getAttachmentsForItem({ Id: item.Id, ManifestId: item.ManifestId });
        blobsRef.current = new Map(attachmentList.map(attachment => [attachment.Id, attachment.Blob]));
        setAttachments(attachmentList.map(({ Blob: _blob, ...attachment }) => attachment));
      } catch (error) {
        console.error('Error loading attachments:', error);
      }
    };

    // The details screen hands over a fresh item after every edit, which reloads the attachments too.
    loadAttachments();
  }, [item, dbContext?.sqliteClient]);

  if (attachments.length === 0) {
    return null;
  }

  const styles = StyleSheet.create({
    attachmentDate: {
      fontSize: 12,
    },
    attachmentInfo: {
      flex: 1,
    },
    attachmentItem: {
      alignItems: 'center',
      flexDirection: 'row',
      justifyContent: 'space-between',
      marginBottom: 8,
    },
    attachmentName: {
      fontSize: 14,
      fontWeight: '500',
      marginBottom: 2,
    },
    container: {
      paddingTop: 16,
    },
    content: {
      backgroundColor: colors.accentBackground,
      borderRadius: 8,
      marginTop: 8,
      padding: 12,
    },
    downloadIcon: {
      marginLeft: 12,
    },
  });

  return (
    <ThemedView style={styles.container}>
      <ThemedText type="subtitle">
        {t('common.attachments')}
      </ThemedText>
      {attachments.map(attachment => (
        <TouchableOpacity
          key={attachment.Id}
          style={styles.content}
          onPress={() => handleAttachment(attachment)}
        >
          <View style={styles.attachmentItem}>
            <View style={styles.attachmentInfo}>
              <ThemedText style={styles.attachmentName}>
                {attachment.Filename}
              </ThemedText>
              <ThemedText style={styles.attachmentDate} type="subtitle">
                {new Date(attachment.CreatedAt).toLocaleDateString()}
              </ThemedText>
            </View>
            <View style={styles.downloadIcon}>
              <MaterialIcons
                name={"visibility"}
                size={20}
                color={colors.primary}
              />
            </View>
          </View>
        </TouchableOpacity>
      ))}
      {viewerElement}
    </ThemedView>
  );
};