From ca68c28d416ad406b531a39fc6da7fd970e8d466 Mon Sep 17 00:00:00 2001 From: Lanna Michalke Date: Wed, 17 Aug 2022 11:34:07 +0200 Subject: [PATCH] chore: support MIME in file factory - defaultly generate MatrixFile based on the present MIME type Related: https://gitlab.com/famedly/company/frontend/famedly-web/-/merge_requests/598 Signed-off-by: Lanna Michalke --- lib/src/utils/matrix_file.dart | 36 +++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/lib/src/utils/matrix_file.dart b/lib/src/utils/matrix_file.dart index ceceea4f..b51bd1ad 100644 --- a/lib/src/utils/matrix_file.dart +++ b/lib/src/utils/matrix_file.dart @@ -45,9 +45,37 @@ class MatrixFile { 'application/octet-stream', name = name.split('/').last.toLowerCase(); + /// derivatives the MIME type from the [bytes] and correspondingly creates a + /// [MatrixFile], [MatrixImageFile], [MatrixAudioFile] or a [MatrixVideoFile] + factory MatrixFile.fromMimeType( + {required Uint8List bytes, required String name, String? mimeType}) { + final msgType = msgTypeFromMime(mimeType ?? + lookupMimeType(name, headerBytes: bytes) ?? + 'application/octet-stream'); + if (msgType == MessageTypes.Image) { + return MatrixImageFile(bytes: bytes, name: name, mimeType: mimeType); + } + if (msgType == MessageTypes.Video) { + return MatrixVideoFile(bytes: bytes, name: name, mimeType: mimeType); + } + if (msgType == MessageTypes.Audio) { + return MatrixAudioFile(bytes: bytes, name: name, mimeType: mimeType); + } + return MatrixFile(bytes: bytes, name: name, mimeType: mimeType); + } + int get size => bytes.length; String get msgType { + return msgTypeFromMime(mimeType); + } + + Map get info => ({ + 'mimetype': mimeType, + 'size': size, + }); + + static String msgTypeFromMime(String mimeType) { if (mimeType.toLowerCase().startsWith('image/')) { return MessageTypes.Image; } @@ -59,11 +87,6 @@ class MatrixFile { } return MessageTypes.File; } - - Map get info => ({ - 'mimetype': mimeType, - 'size': size, - }); } class MatrixImageFile extends MatrixFile { @@ -374,7 +397,6 @@ class MatrixAudioFile extends MatrixFile { extension ToMatrixFile on EncryptedFile { MatrixFile toMatrixFile() { - return MatrixFile( - bytes: data, name: 'crypt', mimeType: 'application/octet-stream'); + return MatrixFile.fromMimeType(bytes: data, name: 'crypt'); } }