together_mobile/lib/database/init_database.dart

63 lines
2.0 KiB
Dart
Raw Normal View History

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
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';
void initDatabase() async {
List<int> encryptionKeyUint8List = await _getEncryptKey();
2023-07-27 18:17:52 +08:00
await Hive.initFlutter(await getBoxPath());
_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;
const secureStorage = FlutterSecureStorage();
2023-07-27 18:17:52 +08:00
final encryptionKeyString = await secureStorage.read(key: 'encryptKey:$id');
if (encryptionKeyString == null) {
final key = Hive.generateSecureKey();
await secureStorage.write(
2023-07-27 18:17:52 +08:00
key: 'encryptKey:$id',
value: base64Encode(key),
);
}
2023-07-27 18:17:52 +08:00
String? key = await secureStorage.read(key: 'encryptKey:$id');
final encryptionKeyUint8List = base64Url.decode(key!);
return encryptionKeyUint8List;
}
void openNewMessageBox(String contactId) async {
final encryptionKeyUint8List = await _getEncryptKey();
2023-07-27 18:17:52 +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,
);
}