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'; 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'; class HiveDatabase { static bool _isInitialised = false; static Future init() async { if (_isInitialised) { return; } List encryptionKeyUint8List = await _getEncryptKey(); await Hive.initFlutter(await getBoxDir()); Box chatSettingBox = await Hive.openBox('chat_setting'); final openedChats = chatSettingBox.values.where((element) => element.isOpen); for (var chatBox in openedChats) { await Hive.openBox( 'message_${chatBox.contactId}', encryptionCipher: HiveAesCipher(encryptionKeyUint8List), compactionStrategy: (entries, deletedEntries) => entries > 200, ); await Hive.openBox('msg_index_${chatBox.contactId}'); } await Hive.openBox('attachment_send'); await Hive.openBox('attachment_receive'); _isInitialised = true; } static void registerAdapter() { Hive.registerAdapter(ChatSettingAdapter()); Hive.registerAdapter(MessageTAdapter()); Hive.registerAdapter(AttachmentProgressAdapter()); } static Future> openMessageBox(String contactId) async { final encryptionKeyUint8List = await _getEncryptKey(); late Box messageTBox; try { messageTBox = Hive.box('message_$contactId'); } catch (e) { messageTBox = await Hive.openBox( 'message_$contactId', encryptionCipher: HiveAesCipher(encryptionKeyUint8List), compactionStrategy: (entries, deletedEntries) => entries > 200, ); } return messageTBox; } static Future> _getEncryptKey() async { final id = getIt.get().id; const secureStorage = FlutterSecureStorage(); final encryptionKeyString = await secureStorage.read(key: 'encryptKey:$id'); if (encryptionKeyString == null) { final key = Hive.generateSecureKey(); await secureStorage.write( key: 'encryptKey:$id', value: base64Encode(key), ); } String? key = await secureStorage.read(key: 'encryptKey:$id'); final encryptionKeyUint8List = base64Url.decode(key!); return encryptionKeyUint8List; } static Future close() async { _isInitialised = false; await Hive.close(); } }