configuration.dart 21 KB

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