configuration.dart 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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/trash_db.dart';
  17. import 'package:photos/db/upload_locks_db.dart';
  18. import "package:photos/events/endpoint_updated_event.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/home_widget_service.dart";
  28. import 'package:photos/services/ignored_files_service.dart';
  29. import 'package:photos/services/machine_learning/semantic_search/semantic_search_service.dart';
  30. import 'package:photos/services/memories_service.dart';
  31. import 'package:photos/services/search_service.dart';
  32. import 'package:photos/services/sync_service.dart';
  33. import 'package:photos/utils/crypto_util.dart';
  34. import 'package:photos/utils/file_uploader.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. static const endPointKey = "endpoint";
  69. final kTempFolderDeletionTimeBuffer = const Duration(hours: 6).inMicroseconds;
  70. static final _logger = Logger("Configuration");
  71. String? _cachedToken;
  72. late String _documentsDirectory;
  73. String? _key;
  74. late SharedPreferences _preferences;
  75. String? _secretKey;
  76. late FlutterSecureStorage _secureStorage;
  77. late String _tempDocumentsDirPath;
  78. late String _thumbnailCacheDirectory;
  79. // 6th July 22: Remove this after 3 months. Hopefully, active users
  80. // will migrate to newer version of the app, where shared media is stored
  81. // on appSupport directory which OS won't clean up automatically
  82. late String _sharedTempMediaDirectory;
  83. late String _sharedDocumentsMediaDirectory;
  84. String? _volatilePassword;
  85. final _secureStorageOptionsIOS = const IOSOptions(
  86. accessibility: KeychainAccessibility.first_unlock_this_device,
  87. );
  88. Future<void> init() async {
  89. _preferences = await SharedPreferences.getInstance();
  90. _secureStorage = const FlutterSecureStorage();
  91. _documentsDirectory = (await getApplicationDocumentsDirectory()).path;
  92. _tempDocumentsDirPath = _documentsDirectory + "/temp/";
  93. final tempDocumentsDir = Directory(_tempDocumentsDirPath);
  94. try {
  95. final currentTime = DateTime.now().microsecondsSinceEpoch;
  96. if (tempDocumentsDir.existsSync() &&
  97. (_preferences.getInt(lastTempFolderClearTimeKey) ?? 0) <
  98. (currentTime - kTempFolderDeletionTimeBuffer)) {
  99. await tempDocumentsDir.delete(recursive: true);
  100. await _preferences.setInt(lastTempFolderClearTimeKey, currentTime);
  101. _logger.info("Cleared temp folder");
  102. } else {
  103. _logger.info("Skipping temp folder clear");
  104. }
  105. } catch (e) {
  106. _logger.warning(e);
  107. }
  108. tempDocumentsDir.createSync(recursive: true);
  109. final tempDirectoryPath = (await getTemporaryDirectory()).path;
  110. _thumbnailCacheDirectory = tempDirectoryPath + "/thumbnail-cache";
  111. Directory(_thumbnailCacheDirectory).createSync(recursive: true);
  112. _sharedTempMediaDirectory = tempDirectoryPath + "/ente-shared-media";
  113. Directory(_sharedTempMediaDirectory).createSync(recursive: true);
  114. _sharedDocumentsMediaDirectory = _documentsDirectory + "/ente-shared-media";
  115. Directory(_sharedDocumentsMediaDirectory).createSync(recursive: true);
  116. if (!_preferences.containsKey(tokenKey)) {
  117. await _secureStorage.deleteAll(iOptions: _secureStorageOptionsIOS);
  118. } else {
  119. _key = await _secureStorage.read(
  120. key: keyKey,
  121. iOptions: _secureStorageOptionsIOS,
  122. );
  123. _secretKey = await _secureStorage.read(
  124. key: secretKeyKey,
  125. iOptions: _secureStorageOptionsIOS,
  126. );
  127. if (_key == null) {
  128. await logout(autoLogout: true);
  129. }
  130. await _migrateSecurityStorageToFirstUnlock();
  131. }
  132. SuperLogging.setUserID(await _getOrCreateAnonymousUserID()).ignore();
  133. }
  134. Future<void> logout({bool autoLogout = false}) async {
  135. if (SyncService.instance.isSyncInProgress()) {
  136. SyncService.instance.stopSync();
  137. try {
  138. await SyncService.instance
  139. .existingSync()
  140. .timeout(const Duration(seconds: 5));
  141. } catch (e) {
  142. // ignore
  143. }
  144. }
  145. await _preferences.clear();
  146. await _secureStorage.deleteAll(iOptions: _secureStorageOptionsIOS);
  147. _key = null;
  148. _cachedToken = null;
  149. _secretKey = null;
  150. await FilesDB.instance.clearTable();
  151. SemanticSearchService.instance.hasInitialized
  152. ? await EmbeddingsDB.instance.clearTable()
  153. : null;
  154. await CollectionsDB.instance.clearTable();
  155. await MemoriesDB.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(HomeWidgetService.instance.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 _preferences.getString(endPointKey) ?? endpoint;
  360. }
  361. Future<void> setHttpEndpoint(String endpoint) async {
  362. await _preferences.setString(endPointKey, endpoint);
  363. Bus.instance.fire(EndpointUpdatedEvent());
  364. }
  365. String? getToken() {
  366. _cachedToken ??= _preferences.getString(tokenKey);
  367. return _cachedToken;
  368. }
  369. bool isLoggedIn() {
  370. return getToken() != null;
  371. }
  372. Future<void> setToken(String token) async {
  373. _cachedToken = token;
  374. await _preferences.setString(tokenKey, token);
  375. Bus.instance.fire(SignedInEvent());
  376. }
  377. Future<void> setEncryptedToken(String encryptedToken) async {
  378. await _preferences.setString(encryptedTokenKey, encryptedToken);
  379. }
  380. String? getEncryptedToken() {
  381. return _preferences.getString(encryptedTokenKey);
  382. }
  383. String? getEmail() {
  384. return _preferences.getString(emailKey);
  385. }
  386. Future<void> setEmail(String email) async {
  387. await _preferences.setString(emailKey, email);
  388. }
  389. int? getUserID() {
  390. return _preferences.getInt(userIDKey);
  391. }
  392. Future<void> setUserID(int userID) async {
  393. await _preferences.setInt(userIDKey, userID);
  394. }
  395. Set<String> getPathsToBackUp() {
  396. if (_preferences.containsKey(foldersToBackUpKey)) {
  397. return _preferences.getStringList(foldersToBackUpKey)!.toSet();
  398. } else {
  399. return <String>{};
  400. }
  401. }
  402. Future<void> setKeyAttributes(KeyAttributes attributes) async {
  403. await _preferences.setString(keyAttributesKey, attributes.toJson());
  404. }
  405. KeyAttributes? getKeyAttributes() {
  406. final jsonValue = _preferences.getString(keyAttributesKey);
  407. if (jsonValue == null) {
  408. return null;
  409. } else {
  410. return KeyAttributes.fromJson(jsonValue);
  411. }
  412. }
  413. Future<void> setKey(String? key) async {
  414. _key = key;
  415. if (key == null) {
  416. // Used to clear key from secure storage
  417. await _secureStorage.delete(
  418. key: keyKey,
  419. iOptions: _secureStorageOptionsIOS,
  420. );
  421. } else {
  422. await _secureStorage.write(
  423. key: keyKey,
  424. value: key,
  425. iOptions: _secureStorageOptionsIOS,
  426. );
  427. }
  428. }
  429. Future<void> setSecretKey(String? secretKey) async {
  430. _secretKey = secretKey;
  431. if (secretKey == null) {
  432. // Used to clear secret key from secure storage
  433. await _secureStorage.delete(
  434. key: secretKeyKey,
  435. iOptions: _secureStorageOptionsIOS,
  436. );
  437. } else {
  438. await _secureStorage.write(
  439. key: secretKeyKey,
  440. value: secretKey,
  441. iOptions: _secureStorageOptionsIOS,
  442. );
  443. }
  444. }
  445. Uint8List? getKey() {
  446. return _key == null ? null : CryptoUtil.base642bin(_key!);
  447. }
  448. Uint8List? getSecretKey() {
  449. return _secretKey == null ? null : CryptoUtil.base642bin(_secretKey!);
  450. }
  451. Uint8List getRecoveryKey() {
  452. final keyAttributes = getKeyAttributes()!;
  453. return CryptoUtil.decryptSync(
  454. CryptoUtil.base642bin(keyAttributes.recoveryKeyEncryptedWithMasterKey!),
  455. getKey()!,
  456. CryptoUtil.base642bin(keyAttributes.recoveryKeyDecryptionNonce!),
  457. );
  458. }
  459. // Caution: This directory is cleared on app start
  460. String getTempDirectory() {
  461. return _tempDocumentsDirPath;
  462. }
  463. String getThumbnailCacheDirectory() {
  464. return _thumbnailCacheDirectory;
  465. }
  466. String getOldSharedMediaCacheDirectory() {
  467. return _sharedTempMediaDirectory;
  468. }
  469. String getSharedMediaDirectory() {
  470. return _sharedDocumentsMediaDirectory;
  471. }
  472. bool hasConfiguredAccount() {
  473. return isLoggedIn() && _key != null;
  474. }
  475. bool shouldBackupOverMobileData() {
  476. if (_preferences.containsKey(keyShouldBackupOverMobileData)) {
  477. return _preferences.getBool(keyShouldBackupOverMobileData)!;
  478. } else {
  479. return false;
  480. }
  481. }
  482. Future<void> setBackupOverMobileData(bool value) async {
  483. await _preferences.setBool(keyShouldBackupOverMobileData, value);
  484. if (value) {
  485. SyncService.instance.sync().ignore();
  486. }
  487. }
  488. bool shouldBackupVideos() {
  489. if (_preferences.containsKey(keyShouldBackupVideos)) {
  490. return _preferences.getBool(keyShouldBackupVideos)!;
  491. } else {
  492. return true;
  493. }
  494. }
  495. bool shouldKeepDeviceAwake() {
  496. final keepAwake = _preferences.get(keyShouldKeepDeviceAwake);
  497. return keepAwake == null ? false : keepAwake as bool;
  498. }
  499. Future<void> setShouldKeepDeviceAwake(bool value) async {
  500. await _preferences.setBool(keyShouldKeepDeviceAwake, value);
  501. await WakelockPlus.toggle(enable: value);
  502. }
  503. Future<void> setShouldBackupVideos(bool value) async {
  504. await _preferences.setBool(keyShouldBackupVideos, value);
  505. if (value) {
  506. SyncService.instance.sync().ignore();
  507. } else {
  508. SyncService.instance.onVideoBackupPaused();
  509. }
  510. }
  511. bool shouldShowLockScreen() {
  512. if (_preferences.containsKey(keyShouldShowLockScreen)) {
  513. return _preferences.getBool(keyShouldShowLockScreen)!;
  514. } else {
  515. return false;
  516. }
  517. }
  518. Future<void> setShouldShowLockScreen(bool value) {
  519. return _preferences.setBool(keyShouldShowLockScreen, value);
  520. }
  521. void setVolatilePassword(String volatilePassword) {
  522. _volatilePassword = volatilePassword;
  523. }
  524. void resetVolatilePassword() {
  525. _volatilePassword = null;
  526. }
  527. String? getVolatilePassword() {
  528. return _volatilePassword;
  529. }
  530. Future<void> setHasSelectedAnyBackupFolder(bool val) async {
  531. await _preferences.setBool(keyHasSelectedAnyBackupFolder, val);
  532. }
  533. bool hasSelectedAnyBackupFolder() {
  534. return _preferences.getBool(keyHasSelectedAnyBackupFolder) ?? false;
  535. }
  536. bool hasSelectedAllFoldersForBackup() {
  537. return _preferences.getBool(hasSelectedAllFoldersForBackupKey) ?? false;
  538. }
  539. Future<void> setSelectAllFoldersForBackup(bool value) async {
  540. await _preferences.setBool(hasSelectedAllFoldersForBackupKey, value);
  541. }
  542. Future<void> _migrateSecurityStorageToFirstUnlock() async {
  543. final hasMigratedSecureStorage =
  544. _preferences.getBool(hasMigratedSecureStorageKey) ?? false;
  545. if (!hasMigratedSecureStorage && _key != null && _secretKey != null) {
  546. await _secureStorage.write(
  547. key: keyKey,
  548. value: _key,
  549. iOptions: _secureStorageOptionsIOS,
  550. );
  551. await _secureStorage.write(
  552. key: secretKeyKey,
  553. value: _secretKey,
  554. iOptions: _secureStorageOptionsIOS,
  555. );
  556. await _preferences.setBool(
  557. hasMigratedSecureStorageKey,
  558. true,
  559. );
  560. }
  561. }
  562. Future<String> _getOrCreateAnonymousUserID() async {
  563. if (!_preferences.containsKey(anonymousUserIDKey)) {
  564. //ignore: prefer_const_constructors
  565. await _preferences.setString(anonymousUserIDKey, Uuid().v4());
  566. }
  567. return _preferences.getString(anonymousUserIDKey)!;
  568. }
  569. }