uploadAttachment method

  1. @override
Future<Attachment?> uploadAttachment(
  1. LocalAttachment attachment
)
override

Creates a new Attachment linked to the authenticated MyUser for a later use in the sendChatMessage method.

Implementation

@override
Future<Attachment?> uploadAttachment(LocalAttachment attachment) async {
  Log.debug('uploadAttachment($attachment)', '$runtimeType');

  if (attachment.upload.value?.isCompleted != false) {
    attachment.upload.value = Completer();
  }

  if (attachment.read.value?.isCompleted != false) {
    attachment.read.value = Completer();
  }

  attachment.status.value = SendingStatus.sending;
  await attachment.file.ensureCorrectMediaType();

  try {
    await attachment.file.readFile();
    attachment.read.value?.complete(null);
    attachment.status.refresh();

    var response = await _graphQlProvider.uploadAttachment(
      await attachment.file.toMultipartFile(),
      onSendProgress: (now, max) => attachment.progress.value = now / max,
      cancelToken: attachment.cancelToken,
    );

    var model = response.attachment.toModel();
    attachment.id = model.id;
    attachment.filename = model.filename;
    attachment.original = model.original;
    attachment.upload.value?.complete(model);
    attachment.status.value = SendingStatus.sent;
    attachment.progress.value = 1;
    return model;
  } on dio.DioException {
    if (attachment.isCanceled) {
      attachment.upload.value?.complete(null);
      return null;
    }

    rethrow;
  } catch (e) {
    if (attachment.read.value?.isCompleted == false) {
      attachment.read.value?.complete(null);
    }
    attachment.upload.value?.completeError(e);
    attachment.status.value = SendingStatus.error;
    attachment.progress.value = 0;
    rethrow;
  }
}