saveFile method

Future<Attachment> saveFile({
  1. required Stream<List<int>> data,
  2. required String mediaType,
  3. String? fileExtension,
  4. String? metaData,
  5. String? id,
  6. required Future<void> updateHook(
    1. SqliteWriteContext context,
    2. Attachment attachment
    ),
})

Creates a new attachment locally and queues it for upload. The filename is resolved using resolveNewAttachmentFilename.

Implementation

Future<Attachment> saveFile({
  required Stream<List<int>> data,
  required String mediaType,
  String? fileExtension,
  String? metaData,
  String? id,
  required Future<void> Function(
          SqliteWriteContext context, Attachment attachment)
      updateHook,
}) async {
  final resolvedId = id ?? await generateAttachmentId();

  final filename = await resolveNewAttachmentFilename(
    resolvedId,
    fileExtension,
  );

  // Write the file to the filesystem.
  final fileSize = await _localStorage.saveFile(filename, data);

  return await _attachmentsService.withContext((attachmentContext) async {
    return await _db.writeTransaction((tx) async {
      final attachment = Attachment(
        id: resolvedId,
        filename: filename,
        size: fileSize,
        mediaType: mediaType,
        state: AttachmentState.queuedUpload,
        localUri: filename,
        metaData: metaData,
      );

      // Allow consumers to set relationships to this attachment ID.
      await updateHook(tx, attachment);

      return await attachmentContext.upsertAttachment(attachment, tx);
    });
  });
}