configuration.dart 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. import "dart:async";
  2. import 'dart:convert';
  3. import "dart:io";
  4. import 'dart:typed_data';
  5. import 'package:bip39/bip39.dart' as bip39;
  6. import 'package:flutter_secure_storage/flutter_secure_storage.dart';
  7. import 'package:logging/logging.dart';
  8. import 'package:path_provider/path_provider.dart';
  9. import 'package:photos/core/constants.dart';
  10. import 'package:photos/core/error-reporting/super_logging.dart';
  11. import 'package:photos/core/event_bus.dart';
  12. import 'package:photos/db/collections_db.dart';
  13. import "package:photos/db/embeddings_db.dart";
  14. import 'package:photos/db/files_db.dart';
  15. import 'package:photos/db/memories_db.dart';
  16. import 'package:photos/db/public_keys_db.dart';
  17. import 'package:photos/db/trash_db.dart';
  18. import 'package:photos/db/upload_locks_db.dart';
  19. import 'package:photos/events/signed_in_event.dart';
  20. import 'package:photos/events/user_logged_out_event.dart';
  21. import 'package:photos/models/key_attributes.dart';
  22. import 'package:photos/models/key_gen_result.dart';
  23. import 'package:photos/models/private_key_attributes.dart';
  24. import 'package:photos/services/billing_service.dart';
  25. import 'package:photos/services/collections_service.dart';
  26. import 'package:photos/services/favorites_service.dart';
  27. import 'package:photos/services/ignored_files_service.dart';
  28. import 'package:photos/services/machine_learning/semantic_search/semantic_search_service.dart';
  29. import 'package:photos/services/memories_service.dart';
  30. import 'package:photos/services/search_service.dart';
  31. import 'package:photos/services/sync_service.dart';
  32. import 'package:photos/utils/crypto_util.dart';
  33. import 'package:photos/utils/file_uploader.dart';
  34. import "package:photos/utils/home_widget_util.dart";
  35. import 'package:photos/utils/validator_util.dart';
  36. import 'package:shared_preferences/shared_preferences.dart';
  37. import "package:tuple/tuple.dart";
  38. import 'package:uuid/uuid.dart';
  39. import 'package:wakelock_plus/wakelock_plus.dart';
  40. class Configuration {
  41. Configuration._privateConstructor();
  42. static final Configuration instance = Configuration._privateConstructor();
  43. static const endpoint = String.fromEnvironment(
  44. "endpoint",
  45. defaultValue: kDefaultProductionEndpoint,
  46. );
  47. static const emailKey = "email";
  48. static const foldersToBackUpKey = "folders_to_back_up";
  49. static const keyAttributesKey = "key_attributes";
  50. static const keyKey = "key";
  51. static const keyShouldBackupOverMobileData = "should_backup_over_mobile_data";
  52. static const keyShouldBackupVideos = "should_backup_videos";
  53. // keyShouldKeepDeviceAwake is used to determine whether the device screen
  54. // should be kept on while the app is in foreground.
  55. static const keyShouldKeepDeviceAwake = "should_keep_device_awake";
  56. static const keyShouldShowLockScreen = "should_show_lock_screen";
  57. static const keyHasSelectedAnyBackupFolder =
  58. "has_selected_any_folder_for_backup";
  59. static const lastTempFolderClearTimeKey = "last_temp_folder_clear_time";
  60. static const secretKeyKey = "secret_key";
  61. static const tokenKey = "token";
  62. static const encryptedTokenKey = "encrypted_token";
  63. static const userIDKey = "user_id";
  64. static const hasMigratedSecureStorageKey = "has_migrated_secure_storage";
  65. static const hasSelectedAllFoldersForBackupKey =
  66. "has_selected_all_folders_for_backup";
  67. static const anonymousUserIDKey = "anonymous_user_id";
  68. final kTempFolderDeletionTimeBuffer = const Duration(hours: 6).inMicroseconds;
  69. static final _logger = Logger("Configuration");
  70. String? _cachedToken;
  71. late String _documentsDirectory;
  72. String? _key;
  73. late SharedPreferences _preferences;
  74. String? _secretKey;
  75. late FlutterSecureStorage _secureStorage;
  76. late String _tempDocumentsDirPath;
  77. late String _thumbnailCacheDirectory;
  78. // 6th July 22: Remove this after 3 months. Hopefully, active users
  79. // will migrate to newer version of the app, where shared media is stored
  80. // on appSupport directory which OS won't clean up automatically
  81. late String _sharedTempMediaDirectory;
  82. late String _sharedDocumentsMediaDirectory;
  83. String? _volatilePassword;
  84. final _secureStorageOptionsIOS = const IOSOptions(
  85. accessibility: KeychainAccessibility.first_unlock_this_device,
  86. );
  87. Future<void> init() async {
  88. _preferences = await SharedPreferences.getInstance();
  89. _secureStorage = const FlutterSecureStorage();
  90. _documentsDirectory = (await getApplicationDocumentsDirectory()).path;
  91. _tempDocumentsDirPath = _documentsDirectory + "/temp/";
  92. final tempDocumentsDir = Directory(_tempDocumentsDirPath);
  93. try {
  94. final currentTime = DateTime.now().microsecondsSinceEpoch;
  95. if (tempDocumentsDir.existsSync() &&
  96. (_preferences.getInt(lastTempFolderClearTimeKey) ?? 0) <
  97. (currentTime - kTempFolderDeletionTimeBuffer)) {
  98. await tempDocumentsDir.delete(recursive: true);
  99. await _preferences.setInt(lastTempFolderClearTimeKey, currentTime);
  100. _logger.info("Cleared temp folder");
  101. } else {
  102. _logger.info("Skipping temp folder clear");
  103. }
  104. } catch (e) {
  105. _logger.warning(e);
  106. }
  107. tempDocumentsDir.createSync(recursive: true);
  108. final tempDirectoryPath = (await getTemporaryDirectory()).path;
  109. _thumbnailCacheDirectory = tempDirectoryPath + "/thumbnail-cache";
  110. Directory(_thumbnailCacheDirectory).createSync(recursive: true);
  111. _sharedTempMediaDirectory = tempDirectoryPath + "/ente-shared-media";
  112. Directory(_sharedTempMediaDirectory).createSync(recursive: true);
  113. _sharedDocumentsMediaDirectory = _documentsDirectory + "/ente-shared-media";
  114. Directory(_sharedDocumentsMediaDirectory).createSync(recursive: true);
  115. if (!_preferences.containsKey(tokenKey)) {
  116. await _secureStorage.deleteAll(iOptions: _secureStorageOptionsIOS);
  117. } else {
  118. _key = await _secureStorage.read(
  119. key: keyKey,
  120. iOptions: _secureStorageOptionsIOS,
  121. );
  122. _secretKey = await _secureStorage.read(
  123. key: secretKeyKey,
  124. iOptions: _secureStorageOptionsIOS,
  125. );
  126. if (_key == null) {
  127. await logout(autoLogout: true);
  128. }
  129. await _migrateSecurityStorageToFirstUnlock();
  130. }
  131. SuperLogging.setUserID(await _getOrCreateAnonymousUserID()).ignore();
  132. }
  133. Future<void> logout({bool autoLogout = false}) async {
  134. if (SyncService.instance.isSyncInProgress()) {
  135. SyncService.instance.stopSync();
  136. try {
  137. await SyncService.instance
  138. .existingSync()
  139. .timeout(const Duration(seconds: 5));
  140. } catch (e) {
  141. // ignore
  142. }
  143. }
  144. await _preferences.clear();
  145. await _secureStorage.deleteAll(iOptions: _secureStorageOptionsIOS);
  146. _key = null;
  147. _cachedToken = null;
  148. _secretKey = null;
  149. await FilesDB.instance.clearTable();
  150. SemanticSearchService.instance.hasInitialized
  151. ? await EmbeddingsDB.instance.clearTable()
  152. : null;
  153. await CollectionsDB.instance.clearTable();
  154. await MemoriesDB.instance.clearTable();
  155. await PublicKeysDB.instance.clearTable();
  156. await UploadLocksDB.instance.clearTable();
  157. await IgnoredFilesService.instance.reset();
  158. await TrashDB.instance.clearTable();
  159. FileUploader.instance.clearCachedUploadURLs();
  160. if (!autoLogout) {
  161. CollectionsService.instance.clearCache();
  162. FavoritesService.instance.clearCache();
  163. MemoriesService.instance.clearCache();
  164. BillingService.instance.clearCache();
  165. SearchService.instance.clearCache();
  166. unawaited(clearHomeWidget());
  167. Bus.instance.fire(UserLoggedOutEvent());
  168. } else {
  169. await _preferences.setBool("auto_logout", true);
  170. }
  171. }
  172. bool showAutoLogoutDialog() {
  173. return _preferences.containsKey("auto_logout");
  174. }
  175. Future<bool> clearAutoLogoutFlag() {
  176. return _preferences.remove("auto_logout");
  177. }
  178. Future<KeyGenResult> generateKey(String password) async {
  179. // Create a master key
  180. final masterKey = CryptoUtil.generateKey();
  181. // Create a recovery key
  182. final recoveryKey = CryptoUtil.generateKey();
  183. // Encrypt master key and recovery key with each other
  184. final encryptedMasterKey = CryptoUtil.encryptSync(masterKey, recoveryKey);
  185. final encryptedRecoveryKey = CryptoUtil.encryptSync(recoveryKey, masterKey);
  186. // Derive a key from the password that will be used to encrypt and
  187. // decrypt the master key
  188. final kekSalt = CryptoUtil.getSaltToDeriveKey();
  189. final derivedKeyResult = await CryptoUtil.deriveSensitiveKey(
  190. utf8.encode(password) as Uint8List,
  191. kekSalt,
  192. );
  193. final loginKey = await CryptoUtil.deriveLoginKey(derivedKeyResult.key);
  194. // Encrypt the key with this derived key
  195. final encryptedKeyData =
  196. CryptoUtil.encryptSync(masterKey, derivedKeyResult.key);
  197. // Generate a public-private keypair and encrypt the latter
  198. final keyPair = await CryptoUtil.generateKeyPair();
  199. final encryptedSecretKeyData =
  200. CryptoUtil.encryptSync(keyPair.sk, masterKey);
  201. final attributes = KeyAttributes(
  202. CryptoUtil.bin2base64(kekSalt),
  203. CryptoUtil.bin2base64(encryptedKeyData.encryptedData!),
  204. CryptoUtil.bin2base64(encryptedKeyData.nonce!),
  205. CryptoUtil.bin2base64(keyPair.pk),
  206. CryptoUtil.bin2base64(encryptedSecretKeyData.encryptedData!),
  207. CryptoUtil.bin2base64(encryptedSecretKeyData.nonce!),
  208. derivedKeyResult.memLimit,
  209. derivedKeyResult.opsLimit,
  210. CryptoUtil.bin2base64(encryptedMasterKey.encryptedData!),
  211. CryptoUtil.bin2base64(encryptedMasterKey.nonce!),
  212. CryptoUtil.bin2base64(encryptedRecoveryKey.encryptedData!),
  213. CryptoUtil.bin2base64(encryptedRecoveryKey.nonce!),
  214. );
  215. final privateAttributes = PrivateKeyAttributes(
  216. CryptoUtil.bin2base64(masterKey),
  217. CryptoUtil.bin2hex(recoveryKey),
  218. CryptoUtil.bin2base64(keyPair.sk),
  219. );
  220. return KeyGenResult(attributes, privateAttributes, loginKey);
  221. }
  222. Future<Tuple2<KeyAttributes, Uint8List>> getAttributesForNewPassword(
  223. String password,
  224. ) async {
  225. // Get master key
  226. final masterKey = getKey();
  227. // Derive a key from the password that will be used to encrypt and
  228. // decrypt the master key
  229. final kekSalt = CryptoUtil.getSaltToDeriveKey();
  230. final derivedKeyResult = await CryptoUtil.deriveSensitiveKey(
  231. utf8.encode(password) as Uint8List,
  232. kekSalt,
  233. );
  234. final loginKey = await CryptoUtil.deriveLoginKey(derivedKeyResult.key);
  235. // Encrypt the key with this derived key
  236. final encryptedKeyData =
  237. CryptoUtil.encryptSync(masterKey!, derivedKeyResult.key);
  238. final existingAttributes = getKeyAttributes();
  239. final updatedAttributes = existingAttributes!.copyWith(
  240. kekSalt: CryptoUtil.bin2base64(kekSalt),
  241. encryptedKey: CryptoUtil.bin2base64(encryptedKeyData.encryptedData!),
  242. keyDecryptionNonce: CryptoUtil.bin2base64(encryptedKeyData.nonce!),
  243. memLimit: derivedKeyResult.memLimit,
  244. opsLimit: derivedKeyResult.opsLimit,
  245. );
  246. return Tuple2(updatedAttributes, loginKey);
  247. }
  248. // decryptSecretsAndGetLoginKey decrypts the master key and recovery key
  249. // with the given password and save them in local secure storage.
  250. // This method also returns the keyEncKey that can be used for performing
  251. // SRP setup for existing users.
  252. Future<Uint8List> decryptSecretsAndGetKeyEncKey(
  253. String password,
  254. KeyAttributes attributes, {
  255. Uint8List? keyEncryptionKey,
  256. }) async {
  257. validatePreVerificationStateCheck(
  258. attributes,
  259. password,
  260. getEncryptedToken(),
  261. );
  262. // Derive key-encryption-key from the entered password and existing
  263. // mem and ops limits
  264. keyEncryptionKey ??= await CryptoUtil.deriveKey(
  265. utf8.encode(password) as Uint8List,
  266. CryptoUtil.base642bin(attributes.kekSalt),
  267. attributes.memLimit!,
  268. attributes.opsLimit!,
  269. );
  270. Uint8List key;
  271. try {
  272. // Decrypt the master key with the derived key
  273. key = CryptoUtil.decryptSync(
  274. CryptoUtil.base642bin(attributes.encryptedKey),
  275. keyEncryptionKey,
  276. CryptoUtil.base642bin(attributes.keyDecryptionNonce),
  277. );
  278. } catch (e) {
  279. _logger.severe('master-key decryption failed', e);
  280. throw Exception("Incorrect password");
  281. }
  282. await setKey(CryptoUtil.bin2base64(key));
  283. final secretKey = CryptoUtil.decryptSync(
  284. CryptoUtil.base642bin(attributes.encryptedSecretKey),
  285. key,
  286. CryptoUtil.base642bin(attributes.secretKeyDecryptionNonce),
  287. );
  288. await setSecretKey(CryptoUtil.bin2base64(secretKey));
  289. final token = CryptoUtil.openSealSync(
  290. CryptoUtil.base642bin(getEncryptedToken()!),
  291. CryptoUtil.base642bin(attributes.publicKey),
  292. secretKey,
  293. );
  294. await setToken(
  295. CryptoUtil.bin2base64(token, urlSafe: true),
  296. );
  297. return keyEncryptionKey;
  298. }
  299. Future<KeyAttributes> createNewRecoveryKey() async {
  300. final masterKey = getKey()!;
  301. final existingAttributes = getKeyAttributes();
  302. // Create a recovery key
  303. final recoveryKey = CryptoUtil.generateKey();
  304. // Encrypt master key and recovery key with each other
  305. final encryptedMasterKey = CryptoUtil.encryptSync(masterKey, recoveryKey);
  306. final encryptedRecoveryKey = CryptoUtil.encryptSync(recoveryKey, masterKey);
  307. return existingAttributes!.copyWith(
  308. masterKeyEncryptedWithRecoveryKey:
  309. CryptoUtil.bin2base64(encryptedMasterKey.encryptedData!),
  310. masterKeyDecryptionNonce:
  311. CryptoUtil.bin2base64(encryptedMasterKey.nonce!),
  312. recoveryKeyEncryptedWithMasterKey:
  313. CryptoUtil.bin2base64(encryptedRecoveryKey.encryptedData!),
  314. recoveryKeyDecryptionNonce:
  315. CryptoUtil.bin2base64(encryptedRecoveryKey.nonce!),
  316. );
  317. }
  318. Future<void> recover(String recoveryKey) async {
  319. // Legacy users will have recoveryKey in the form of a hex string, while
  320. // newer users will have it as a mnemonic code
  321. if (recoveryKey.contains(' ')) {
  322. // Check if user has entered a mnemonic code
  323. if (recoveryKey.split(' ').length != mnemonicKeyWordCount) {
  324. throw AssertionError(
  325. 'recovery code should have $mnemonicKeyWordCount words',
  326. );
  327. }
  328. // Convert mnemonic code to hex
  329. recoveryKey = bip39.mnemonicToEntropy(recoveryKey);
  330. }
  331. final attributes = getKeyAttributes();
  332. Uint8List masterKey;
  333. try {
  334. // Decrypt the master key that was earlier encrypted with the recovery key
  335. masterKey = await CryptoUtil.decrypt(
  336. CryptoUtil.base642bin(attributes!.masterKeyEncryptedWithRecoveryKey!),
  337. CryptoUtil.hex2bin(recoveryKey),
  338. CryptoUtil.base642bin(attributes.masterKeyDecryptionNonce!),
  339. );
  340. } catch (e) {
  341. _logger.severe(e);
  342. rethrow;
  343. }
  344. await setKey(CryptoUtil.bin2base64(masterKey));
  345. final secretKey = CryptoUtil.decryptSync(
  346. CryptoUtil.base642bin(attributes.encryptedSecretKey),
  347. masterKey,
  348. CryptoUtil.base642bin(attributes.secretKeyDecryptionNonce),
  349. );
  350. await setSecretKey(CryptoUtil.bin2base64(secretKey));
  351. final token = CryptoUtil.openSealSync(
  352. CryptoUtil.base642bin(getEncryptedToken()!),
  353. CryptoUtil.base642bin(attributes.publicKey),
  354. secretKey,
  355. );
  356. await setToken(CryptoUtil.bin2base64(token, urlSafe: true));
  357. }
  358. String getHttpEndpoint() {
  359. return endpoint;
  360. }
  361. String? getToken() {
  362. _cachedToken ??= _preferences.getString(tokenKey);
  363. return _cachedToken;
  364. }
  365. bool isLoggedIn() {
  366. return getToken() != null;
  367. }
  368. Future<void> setToken(String token) async {
  369. _cachedToken = token;
  370. await _preferences.setString(tokenKey, token);
  371. Bus.instance.fire(SignedInEvent());
  372. }
  373. Future<void> setEncryptedToken(String encryptedToken) async {
  374. await _preferences.setString(encryptedTokenKey, encryptedToken);
  375. }
  376. String? getEncryptedToken() {
  377. return _preferences.getString(encryptedTokenKey);
  378. }
  379. String? getEmail() {
  380. return _preferences.getString(emailKey);
  381. }
  382. Future<void> setEmail(String email) async {
  383. await _preferences.setString(emailKey, email);
  384. }
  385. int? getUserID() {
  386. return _preferences.getInt(userIDKey);
  387. }
  388. Future<void> setUserID(int userID) async {
  389. await _preferences.setInt(userIDKey, userID);
  390. }
  391. Set<String> getPathsToBackUp() {
  392. if (_preferences.containsKey(foldersToBackUpKey)) {
  393. return _preferences.getStringList(foldersToBackUpKey)!.toSet();
  394. } else {
  395. return <String>{};
  396. }
  397. }
  398. Future<void> setKeyAttributes(KeyAttributes attributes) async {
  399. await _preferences.setString(keyAttributesKey, attributes.toJson());
  400. }
  401. KeyAttributes? getKeyAttributes() {
  402. final jsonValue = _preferences.getString(keyAttributesKey);
  403. if (jsonValue == null) {
  404. return null;
  405. } else {
  406. return KeyAttributes.fromJson(jsonValue);
  407. }
  408. }
  409. Future<void> setKey(String? key) async {
  410. _key = key;
  411. if (key == null) {
  412. // Used to clear key from secure storage
  413. await _secureStorage.delete(
  414. key: keyKey,
  415. iOptions: _secureStorageOptionsIOS,
  416. );
  417. } else {
  418. await _secureStorage.write(
  419. key: keyKey,
  420. value: key,
  421. iOptions: _secureStorageOptionsIOS,
  422. );
  423. }
  424. }
  425. Future<void> setSecretKey(String? secretKey) async {
  426. _secretKey = secretKey;
  427. if (secretKey == null) {
  428. // Used to clear secret key from secure storage
  429. await _secureStorage.delete(
  430. key: secretKeyKey,
  431. iOptions: _secureStorageOptionsIOS,
  432. );
  433. } else {
  434. await _secureStorage.write(
  435. key: secretKeyKey,
  436. value: secretKey,
  437. iOptions: _secureStorageOptionsIOS,
  438. );
  439. }
  440. }
  441. Uint8List? getKey() {
  442. return _key == null ? null : CryptoUtil.base642bin(_key!);
  443. }
  444. Uint8List? getSecretKey() {
  445. return _secretKey == null ? null : CryptoUtil.base642bin(_secretKey!);
  446. }
  447. Uint8List getRecoveryKey() {
  448. final keyAttributes = getKeyAttributes()!;
  449. return CryptoUtil.decryptSync(
  450. CryptoUtil.base642bin(keyAttributes.recoveryKeyEncryptedWithMasterKey!),
  451. getKey()!,
  452. CryptoUtil.base642bin(keyAttributes.recoveryKeyDecryptionNonce!),
  453. );
  454. }
  455. // Caution: This directory is cleared on app start
  456. String getTempDirectory() {
  457. return _tempDocumentsDirPath;
  458. }
  459. String getThumbnailCacheDirectory() {
  460. return _thumbnailCacheDirectory;
  461. }
  462. String getOldSharedMediaCacheDirectory() {
  463. return _sharedTempMediaDirectory;
  464. }
  465. String getSharedMediaDirectory() {
  466. return _sharedDocumentsMediaDirectory;
  467. }
  468. bool hasConfiguredAccount() {
  469. return isLoggedIn() && _key != null;
  470. }
  471. bool shouldBackupOverMobileData() {
  472. if (_preferences.containsKey(keyShouldBackupOverMobileData)) {
  473. return _preferences.getBool(keyShouldBackupOverMobileData)!;
  474. } else {
  475. return false;
  476. }
  477. }
  478. Future<void> setBackupOverMobileData(bool value) async {
  479. await _preferences.setBool(keyShouldBackupOverMobileData, value);
  480. if (value) {
  481. SyncService.instance.sync().ignore();
  482. }
  483. }
  484. bool shouldBackupVideos() {
  485. if (_preferences.containsKey(keyShouldBackupVideos)) {
  486. return _preferences.getBool(keyShouldBackupVideos)!;
  487. } else {
  488. return true;
  489. }
  490. }
  491. bool shouldKeepDeviceAwake() {
  492. final keepAwake = _preferences.get(keyShouldKeepDeviceAwake);
  493. return keepAwake == null ? false : keepAwake as bool;
  494. }
  495. Future<void> setShouldKeepDeviceAwake(bool value) async {
  496. await _preferences.setBool(keyShouldKeepDeviceAwake, value);
  497. await WakelockPlus.toggle(enable: value);
  498. }
  499. Future<void> setShouldBackupVideos(bool value) async {
  500. await _preferences.setBool(keyShouldBackupVideos, value);
  501. if (value) {
  502. SyncService.instance.sync().ignore();
  503. } else {
  504. SyncService.instance.onVideoBackupPaused();
  505. }
  506. }
  507. bool shouldShowLockScreen() {
  508. if (_preferences.containsKey(keyShouldShowLockScreen)) {
  509. return _preferences.getBool(keyShouldShowLockScreen)!;
  510. } else {
  511. return false;
  512. }
  513. }
  514. Future<void> setShouldShowLockScreen(bool value) {
  515. return _preferences.setBool(keyShouldShowLockScreen, value);
  516. }
  517. void setVolatilePassword(String volatilePassword) {
  518. _volatilePassword = volatilePassword;
  519. }
  520. void resetVolatilePassword() {
  521. _volatilePassword = null;
  522. }
  523. String? getVolatilePassword() {
  524. return _volatilePassword;
  525. }
  526. Future<void> setHasSelectedAnyBackupFolder(bool val) async {
  527. await _preferences.setBool(keyHasSelectedAnyBackupFolder, val);
  528. }
  529. bool hasSelectedAnyBackupFolder() {
  530. return _preferences.getBool(keyHasSelectedAnyBackupFolder) ?? false;
  531. }
  532. bool hasSelectedAllFoldersForBackup() {
  533. return _preferences.getBool(hasSelectedAllFoldersForBackupKey) ?? false;
  534. }
  535. Future<void> setSelectAllFoldersForBackup(bool value) async {
  536. await _preferences.setBool(hasSelectedAllFoldersForBackupKey, value);
  537. }
  538. Future<void> _migrateSecurityStorageToFirstUnlock() async {
  539. final hasMigratedSecureStorage =
  540. _preferences.getBool(hasMigratedSecureStorageKey) ?? false;
  541. if (!hasMigratedSecureStorage && _key != null && _secretKey != null) {
  542. await _secureStorage.write(
  543. key: keyKey,
  544. value: _key,
  545. iOptions: _secureStorageOptionsIOS,
  546. );
  547. await _secureStorage.write(
  548. key: secretKeyKey,
  549. value: _secretKey,
  550. iOptions: _secureStorageOptionsIOS,
  551. );
  552. await _preferences.setBool(
  553. hasMigratedSecureStorageKey,
  554. true,
  555. );
  556. }
  557. }
  558. Future<String> _getOrCreateAnonymousUserID() async {
  559. if (!_preferences.containsKey(anonymousUserIDKey)) {
  560. //ignore: prefer_const_constructors
  561. await _preferences.setString(anonymousUserIDKey, Uuid().v4());
  562. }
  563. return _preferences.getString(anonymousUserIDKey)!;
  564. }
  565. }