together_mobile/lib/database/init_database.dart

63 lines
1.9 KiB
Dart

import 'dart:convert';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:together_mobile/database/box_type.dart';
void initDatabase() async {
List<int> encryptionKeyUint8List = await _getEncryptKey();
await Hive.initFlutter();
await Hive.openBox(
'token',
encryptionCipher: HiveAesCipher(encryptionKeyUint8List),
compactionStrategy: (entries, deletedEntries) => deletedEntries > 100,
);
_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 {
const secureStorage = FlutterSecureStorage();
final encryptionKeyString = await secureStorage.read(key: 'encryptKey');
if (encryptionKeyString == null) {
final key = Hive.generateSecureKey();
await secureStorage.write(
key: 'encryptKey',
value: base64Encode(key),
);
}
String? key = await secureStorage.read(key: 'encrypt_key');
final encryptionKeyUint8List = base64Url.decode(key!);
return encryptionKeyUint8List;
}
void openNewMessageBox(String contactId) async {
final encryptionKeyUint8List = await _getEncryptKey();
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,
);
}