feat: hive

This commit is contained in:
Christian Pauly 2022-05-25 17:51:42 +02:00
parent 3010616b9f
commit 1f113060f9
9 changed files with 168 additions and 128 deletions

View File

@ -46,13 +46,11 @@ class SearchView extends StatelessWidget {
}).then((QueryPublicRoomsResponse res) {
final genericSearchTerm = controller.genericSearchTerm;
if (genericSearchTerm != null &&
!res.chunk.any((room) =>
(room.aliases?.contains(controller.genericSearchTerm) ?? false) ||
room.canonicalAlias == controller.genericSearchTerm)) {
!res.chunk.any(
(room) => room.canonicalAlias == controller.genericSearchTerm)) {
// we have to tack on the original alias
res.chunk.add(
PublicRoomsChunk(
aliases: [genericSearchTerm],
name: genericSearchTerm,
numJoinedMembers: 0,
roomId: '!unknown',

View File

@ -8,10 +8,10 @@ import 'package:matrix/matrix.dart';
import 'package:path_provider/path_provider.dart';
import 'package:fluffychat/utils/custom_image_resizer.dart';
import 'package:fluffychat/utils/matrix_sdk_extensions.dart/flutter_hive_database.dart';
import 'package:fluffychat/utils/platform_infos.dart';
import 'famedlysdk_store.dart';
import 'matrix_sdk_extensions.dart/fluffybox_database.dart';
import 'matrix_sdk_extensions.dart/flutter_matrix_hive_database.dart';
abstract class ClientManager {
static const String clientNamespace = 'im.fluffychat.store.clients';
@ -95,8 +95,8 @@ abstract class ClientManager {
// To check which story room we can post in
EventTypes.RoomPowerLevels,
},
databaseBuilder: FlutterFluffyBoxDatabase.databaseBuilder,
legacyDatabaseBuilder: FlutterMatrixHiveStore.hiveDatabaseBuilder,
databaseBuilder: FlutterHiveDatabase.databaseBuilder,
legacyDatabaseBuilder: FlutterFluffyBoxDatabase.databaseBuilder,
supportedLoginTypes: {
AuthenticationTypes.password,
if (PlatformInfos.isMobile ||

View File

@ -14,6 +14,7 @@ import 'package:path_provider/path_provider.dart';
import '../client_manager.dart';
import '../famedlysdk_store.dart';
// ignore: deprecated_member_use
class FlutterFluffyBoxDatabase extends FluffyBoxDatabase {
FlutterFluffyBoxDatabase(
String name,
@ -27,6 +28,7 @@ class FlutterFluffyBoxDatabase extends FluffyBoxDatabase {
static const String _cipherStorageKey = 'database_encryption_key';
// ignore: deprecated_member_use
static Future<FluffyBoxDatabase> databaseBuilder(Client client) async {
Logs().d('Open FluffyBox...');
fluffybox.HiveAesCipher? hiverCipher;
@ -59,6 +61,7 @@ class FlutterFluffyBoxDatabase extends FluffyBoxDatabase {
rethrow;
}
// ignore: deprecated_member_use
final db = FluffyBoxDatabase(
'fluffybox_${client.clientName.replaceAll(' ', '_').toLowerCase()}',
await _findDatabasePath(client),

View File

@ -0,0 +1,145 @@
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/foundation.dart' hide Key;
import 'package:flutter/services.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:matrix/matrix.dart';
import 'package:path_provider/path_provider.dart';
import '../client_manager.dart';
import '../famedlysdk_store.dart';
class FlutterHiveDatabase extends HiveCollectionsDatabase {
FlutterHiveDatabase(
String name,
String path, {
HiveCipher? key,
}) : super(
name,
path,
key: key,
);
static const String _cipherStorageKey = 'database_encryption_key';
static Future<HiveCollectionsDatabase> databaseBuilder(Client client) async {
Logs().d('Open FluffyBox...');
HiveAesCipher? hiverCipher;
try {
// Workaround for secure storage is calling Platform.operatingSystem on web
if (kIsWeb) throw MissingPluginException();
const secureStorage = FlutterSecureStorage();
final containsEncryptionKey =
await secureStorage.containsKey(key: _cipherStorageKey);
if (!containsEncryptionKey) {
// do not try to create a buggy secure storage for new Linux users
if (Platform.isLinux) throw MissingPluginException();
final key = Hive.generateSecureKey();
await secureStorage.write(
key: _cipherStorageKey,
value: base64UrlEncode(key),
);
}
// workaround for if we just wrote to the key and it still doesn't exist
final rawEncryptionKey = await secureStorage.read(key: _cipherStorageKey);
if (rawEncryptionKey == null) throw MissingPluginException();
hiverCipher = HiveAesCipher(base64Url.decode(rawEncryptionKey));
} on MissingPluginException catch (_) {
Logs().i('FluffyBox encryption is not supported on this platform');
} catch (_) {
const FlutterSecureStorage().delete(key: _cipherStorageKey);
rethrow;
}
final db = HiveCollectionsDatabase(
'fluffybox_${client.clientName.replaceAll(' ', '_').toLowerCase()}',
await _findDatabasePath(client),
key: hiverCipher,
);
try {
await db.open();
} catch (_) {
Logs().w('Unable to open FluffyBox. Delete database and storage key...');
await Store().deleteItem(ClientManager.clientNamespace);
const FlutterSecureStorage().delete(key: _cipherStorageKey);
await db.clear();
rethrow;
}
Logs().d('FluffyBox is ready');
return db;
}
static Future<String> _findDatabasePath(Client client) async {
String path = client.clientName;
if (!kIsWeb) {
Directory directory;
try {
if (Platform.isLinux) {
directory = await getApplicationSupportDirectory();
} else {
directory = await getApplicationDocumentsDirectory();
}
} catch (_) {
try {
directory = await getLibraryDirectory();
} catch (_) {
directory = Directory.current;
}
}
// do not destroy your stable FluffyChat in debug mode
if (kDebugMode) {
directory = Directory(directory.uri.resolve('debug').toFilePath());
directory.create(recursive: true);
}
path = directory.path;
}
return path;
}
@override
int get maxFileSize => supportsFileStoring ? 100 * 1024 * 1024 : 0;
@override
bool get supportsFileStoring => !kIsWeb;
Future<String> _getFileStoreDirectory() async {
try {
try {
return (await getApplicationSupportDirectory()).path;
} catch (_) {
return (await getApplicationDocumentsDirectory()).path;
}
} catch (_) {
return (await getDownloadsDirectory())!.path;
}
}
@override
Future<Uint8List?> getFile(Uri mxcUri) async {
if (!supportsFileStoring) return null;
final tempDirectory = await _getFileStoreDirectory();
final file =
File('$tempDirectory/${Uri.encodeComponent(mxcUri.toString())}');
if (await file.exists() == false) return null;
final bytes = await file.readAsBytes();
return bytes;
}
@override
Future storeFile(Uri mxcUri, Uint8List bytes, int time) async {
if (!supportsFileStoring) return null;
final tempDirectory = await _getFileStoreDirectory();
final file =
File('$tempDirectory/${Uri.encodeComponent(mxcUri.toString())}');
if (await file.exists()) return;
await file.writeAsBytes(bytes);
return;
}
}

View File

@ -1,111 +0,0 @@
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:matrix/matrix.dart';
import 'package:path_provider/path_provider.dart';
import '../platform_infos.dart';
class FlutterMatrixHiveStore extends FamedlySdkHiveDatabase {
FlutterMatrixHiveStore(String name, {HiveCipher? encryptionCipher})
: super(
name,
encryptionCipher: encryptionCipher,
);
static bool _hiveInitialized = false;
static const String _hiveCipherStorageKey = 'hive_encryption_key';
static Future<FamedlySdkHiveDatabase> hiveDatabaseBuilder(
Client client) async {
if (!kIsWeb && !_hiveInitialized) {
_hiveInitialized = true;
}
HiveCipher? hiverCipher;
try {
// Workaround for secure storage is calling Platform.operatingSystem on web
if (kIsWeb || Platform.isLinux) throw MissingPluginException();
const secureStorage = FlutterSecureStorage();
final containsEncryptionKey =
await secureStorage.containsKey(key: _hiveCipherStorageKey);
if (!containsEncryptionKey) {
final key = Hive.generateSecureKey();
await secureStorage.write(
key: _hiveCipherStorageKey,
value: base64UrlEncode(key),
);
}
// workaround for if we just wrote to the key and it still doesn't exist
final rawEncryptionKey =
await secureStorage.read(key: _hiveCipherStorageKey);
if (rawEncryptionKey == null) throw MissingPluginException();
final encryptionKey = base64Url.decode(rawEncryptionKey);
hiverCipher = HiveAesCipher(encryptionKey);
} on MissingPluginException catch (_) {
Logs().i('Hive encryption is not supported on this platform');
}
final db = FlutterMatrixHiveStore(
client.clientName,
encryptionCipher: hiverCipher,
);
try {
await db.open();
} catch (e, s) {
Logs().e('Unable to open Hive. Delete and try again...', e, s);
await db.clear();
await db.open();
}
return db;
}
@override
int get maxFileSize => supportsFileStoring ? 100 * 1024 * 1024 : 0;
@override
bool get supportsFileStoring => (PlatformInfos.isIOS ||
PlatformInfos.isAndroid ||
PlatformInfos.isDesktop);
Future<String> _getFileStoreDirectory() async {
try {
try {
return (await getApplicationSupportDirectory()).path;
} catch (_) {
return (await getApplicationDocumentsDirectory()).path;
}
} catch (_) {
return (await getDownloadsDirectory())!.path;
}
}
@override
Future<Uint8List?> getFile(Uri mxcUri) async {
if (!supportsFileStoring) return null;
final tempDirectory = await _getFileStoreDirectory();
final file =
File('$tempDirectory/${Uri.encodeComponent(mxcUri.toString())}');
if (await file.exists() == false) return null;
final bytes = await file.readAsBytes();
return bytes;
}
@override
Future storeFile(Uri mxcUri, Uint8List bytes, int time) async {
if (!supportsFileStoring) return null;
final tempDirectory = await _getFileStoreDirectory();
final file =
File('$tempDirectory/${Uri.encodeComponent(mxcUri.toString())}');
if (await file.exists()) return;
await file.writeAsBytes(bytes);
return;
}
}

View File

@ -41,9 +41,7 @@ class PublicRoomBottomSheet extends StatelessWidget {
}
}
bool _testRoom(PublicRoomsChunk r) =>
r.canonicalAlias == roomAlias ||
(r.aliases?.contains(roomAlias) ?? false);
bool _testRoom(PublicRoomsChunk r) => r.canonicalAlias == roomAlias;
Future<PublicRoomsChunk> _search(BuildContext context) async {
final chunk = this.chunk;

View File

@ -395,6 +395,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "5.0.1"
enhanced_enum:
dependency: transitive
description:
name: enhanced_enum
url: "https://pub.dartlang.org"
source: hosted
version: "0.1.2"
fake_async:
dependency: transitive
description:
@ -788,7 +795,7 @@ packages:
name: hive
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.0"
version: "2.2.1"
hive_flutter:
dependency: "direct main"
description:
@ -1012,21 +1019,21 @@ packages:
name: matrix
url: "https://pub.dartlang.org"
source: hosted
version: "0.9.4"
version: "0.9.7"
matrix_api_lite:
dependency: transitive
description:
name: matrix_api_lite
url: "https://pub.dartlang.org"
source: hosted
version: "0.5.3"
version: "1.0.0"
matrix_homeserver_recommendations:
dependency: "direct main"
description:
name: matrix_homeserver_recommendations
url: "https://pub.dartlang.org"
source: hosted
version: "0.2.0"
version: "0.2.1"
matrix_link_text:
dependency: "direct main"
description:

View File

@ -57,7 +57,7 @@ dependencies:
keyboard_shortcuts: ^0.1.4
localstorage: ^4.0.0+1
lottie: ^1.2.2
matrix: ^0.9.4
matrix: ^0.9.7
matrix_homeserver_recommendations: ^0.2.0
matrix_link_text: ^1.0.2
native_imaging:

View File

@ -2,7 +2,7 @@ import 'package:matrix/encryption/utils/key_verification.dart';
import 'package:matrix/matrix.dart';
import 'package:matrix_api_lite/fake_matrix_api.dart';
import 'package:fluffychat/utils/matrix_sdk_extensions.dart/flutter_matrix_hive_database.dart';
import 'package:fluffychat/utils/matrix_sdk_extensions.dart/flutter_hive_database.dart';
Future<Client> prepareTestClient({
bool loggedIn = false,
@ -20,7 +20,7 @@ Future<Client> prepareTestClient({
importantStateEvents: <String>{
'im.ponies.room_emotes', // we want emotes to work properly
},
databaseBuilder: FlutterMatrixHiveStore.hiveDatabaseBuilder,
databaseBuilder: FlutterHiveDatabase.databaseBuilder,
supportedLoginTypes: {
AuthenticationTypes.password,
AuthenticationTypes.sso