From d1ce075b5b87b554b862ff934706012db159d676 Mon Sep 17 00:00:00 2001 From: Sorunome Date: Thu, 17 Dec 2020 11:59:31 +0100 Subject: [PATCH] feat: Automatically cache storable files on upload --- lib/src/client.dart | 15 +++++++++++++++ test/client_test.dart | 8 ++++++++ 2 files changed, 23 insertions(+) diff --git a/lib/src/client.dart b/lib/src/client.dart index e179bdcf..5bec6059 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -19,6 +19,7 @@ import 'dart:async'; import 'dart:convert'; import 'dart:core'; +import 'dart:typed_data'; import 'package:http/http.dart' as http; @@ -520,6 +521,20 @@ class Client extends MatrixApi { return archiveList; } + /// Uploads a file and automatically caches it in the database, if it is small enough + /// and returns the mxc url as a string. + @override + Future upload(Uint8List file, String fileName, + {String contentType}) async { + final mxc = await super.upload(file, fileName, contentType: contentType); + final storeable = database != null && file.length <= database.maxFileSize; + if (storeable) { + await database.storeFile( + mxc, file, DateTime.now().millisecondsSinceEpoch); + } + return mxc; + } + /// Uploads a new user avatar for this user. Future setAvatar(MatrixFile file) async { final uploadResp = await upload(file.bytes, file.name); diff --git a/test/client_test.dart b/test/client_test.dart index 275ac2e4..3a140483 100644 --- a/test/client_test.dart +++ b/test/client_test.dart @@ -31,6 +31,7 @@ import 'package:test/test.dart'; import 'fake_matrix_api.dart'; import 'fake_database.dart'; +import 'fake_client.dart'; void main() { Client matrix; @@ -444,6 +445,13 @@ void main() { await matrix.ignoreUser('@charley2:stupid.abc'); await matrix.unignoreUser('@charley:stupid.abc'); }); + test('upload', () async { + final client = await getClient(); + final response = await client.upload(Uint8List(0), 'file.jpeg'); + expect(response, 'mxc://example.com/AQwafuaFswefuhsfAFAgsw'); + expect(await client.database.getFile(response) != null, true); + await client.dispose(closeDatabase: true); + }); test('dispose', () async { await matrix.dispose(closeDatabase: true);