configuration.dart 22 KB

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