2023-07-17 01:00:16 +08:00
|
|
|
import 'dart:convert';
|
|
|
|
|
|
|
|
import 'package:hive_flutter/hive_flutter.dart';
|
|
|
|
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
2023-07-27 18:17:52 +08:00
|
|
|
|
2023-07-17 01:00:16 +08:00
|
|
|
import 'package:together_mobile/database/box_type.dart';
|
2023-07-27 18:17:52 +08:00
|
|
|
import 'package:together_mobile/models/init_get_it.dart';
|
|
|
|
import 'package:together_mobile/models/user_model.dart';
|
|
|
|
import 'package:together_mobile/utils/app_dir.dart';
|
2023-07-17 01:00:16 +08:00
|
|
|
|
|
|
|
void initDatabase() async {
|
|
|
|
List<int> encryptionKeyUint8List = await _getEncryptKey();
|
|
|
|
|
2023-07-27 18:17:52 +08:00
|
|
|
await Hive.initFlutter(await getBoxPath());
|
2023-07-17 01:00:16 +08:00
|
|
|
|
|
|
|
_registerAdapter();
|
|
|
|
|
|
|
|
Box<ChatList> chatBoxListBox = await Hive.openBox<ChatList>('chat_list');
|
|
|
|
final openChats = chatBoxListBox.values.where((element) => element.isOpen);
|
|
|
|
for (var chatBox in openChats) {
|
|
|
|
await Hive.openLazyBox<Message>(
|
|
|
|
'message_${chatBox.contactId}',
|
|
|
|
encryptionCipher: HiveAesCipher(encryptionKeyUint8List),
|
|
|
|
compactionStrategy: (entries, deletedEntries) => entries > 200,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void _registerAdapter() {
|
|
|
|
Hive.registerAdapter(ChatListAdapter());
|
|
|
|
Hive.registerAdapter(MessageAdapter());
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<List<int>> _getEncryptKey() async {
|
2023-07-27 18:17:52 +08:00
|
|
|
final id = getIt.get<UserAccount>().id;
|
2023-07-17 01:00:16 +08:00
|
|
|
const secureStorage = FlutterSecureStorage();
|
2023-07-27 18:17:52 +08:00
|
|
|
final encryptionKeyString = await secureStorage.read(key: 'encryptKey:$id');
|
2023-07-17 01:00:16 +08:00
|
|
|
if (encryptionKeyString == null) {
|
|
|
|
final key = Hive.generateSecureKey();
|
|
|
|
await secureStorage.write(
|
2023-07-27 18:17:52 +08:00
|
|
|
key: 'encryptKey:$id',
|
2023-07-17 01:00:16 +08:00
|
|
|
value: base64Encode(key),
|
|
|
|
);
|
|
|
|
}
|
2023-07-27 18:17:52 +08:00
|
|
|
String? key = await secureStorage.read(key: 'encryptKey:$id');
|
2023-07-17 01:00:16 +08:00
|
|
|
final encryptionKeyUint8List = base64Url.decode(key!);
|
|
|
|
|
|
|
|
return encryptionKeyUint8List;
|
|
|
|
}
|
|
|
|
|
|
|
|
void openNewMessageBox(String contactId) async {
|
|
|
|
final encryptionKeyUint8List = await _getEncryptKey();
|
2023-07-27 18:17:52 +08:00
|
|
|
|
2023-07-17 01:00:16 +08:00
|
|
|
var chatListBox = Hive.box<ChatList>('chat_list');
|
|
|
|
chatListBox.add(ChatList(contactId, true, false));
|
|
|
|
|
|
|
|
await Hive.openLazyBox(
|
|
|
|
'message_$contactId',
|
|
|
|
encryptionCipher: HiveAesCipher(encryptionKeyUint8List),
|
|
|
|
compactionStrategy: (entries, deletedEntries) => entries > 200,
|
|
|
|
);
|
|
|
|
}
|