|
| 1 | +import 'dart:async'; |
| 2 | +import 'dart:convert'; |
| 3 | +import 'dart:io'; |
| 4 | + |
| 5 | +import 'package:flutter/material.dart'; |
| 6 | +import 'package:flutter_riverpod/flutter_riverpod.dart'; |
| 7 | +import 'package:http/http.dart' as http; |
| 8 | +import 'package:open_authenticator/model/settings/cache_totp_pictures.dart'; |
| 9 | +import 'package:open_authenticator/model/totp/decrypted.dart'; |
| 10 | +import 'package:open_authenticator/model/totp/repository.dart'; |
| 11 | +import 'package:open_authenticator/model/totp/totp.dart'; |
| 12 | +import 'package:open_authenticator/utils/utils.dart'; |
| 13 | +import 'package:path/path.dart'; |
| 14 | +import 'package:path_provider/path_provider.dart'; |
| 15 | + |
| 16 | +/// The TOTP image cache manager provider. |
| 17 | +final totpImageCacheManagerProvider = AsyncNotifierProvider.autoDispose<TotpImageCacheManager, Map<String, String>>(TotpImageCacheManager.new); |
| 18 | + |
| 19 | +/// Manages the cache of TOTPs images. |
| 20 | +class TotpImageCacheManager extends AutoDisposeAsyncNotifier<Map<String, String>> { |
| 21 | + @override |
| 22 | + FutureOr<Map<String, String>> build() async { |
| 23 | + File index = await _getIndexFile(); |
| 24 | + return index.existsSync() ? jsonDecode(index.readAsStringSync()).cast<String, String>() : {}; |
| 25 | + } |
| 26 | + |
| 27 | + /// Caches the TOTP image. |
| 28 | + Future<void> cacheImage(Totp totp, {bool checkSettings = true}) async { |
| 29 | + try { |
| 30 | + if (!totp.isDecrypted) { |
| 31 | + return; |
| 32 | + } |
| 33 | + if (checkSettings) { |
| 34 | + bool cacheEnabled = await ref.read(cacheTotpPicturesSettingsEntryProvider.future); |
| 35 | + if (!cacheEnabled) { |
| 36 | + return; |
| 37 | + } |
| 38 | + } |
| 39 | + String? imageUrl = (totp as DecryptedTotp).imageUrl; |
| 40 | + if (imageUrl == null) { |
| 41 | + await deleteCachedImage(totp.uuid); |
| 42 | + } else { |
| 43 | + Map<String, String> cached = Map.from(await future); |
| 44 | + String? previousImageUrl = cached[totp.uuid]; |
| 45 | + File file = await _getTotpCachedImageFile(totp.uuid, createDirectory: true); |
| 46 | + if (previousImageUrl == imageUrl && file.existsSync()) { |
| 47 | + return; |
| 48 | + } |
| 49 | + http.Response response = await http.get(Uri.parse(imageUrl)); |
| 50 | + await file.writeAsBytes(response.bodyBytes); |
| 51 | + cached[totp.uuid] = imageUrl; |
| 52 | + state = AsyncData(cached); |
| 53 | + imageCache.clear(); |
| 54 | + _saveIndex(content: cached); |
| 55 | + } |
| 56 | + } catch (ex, stacktrace) { |
| 57 | + handleException(ex, stacktrace); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + /// Returns the cached image that corresponds to the TOTP UUID and current image URL. |
| 62 | + static Future<File?> getCachedImage(Map<String, String> cached, String uuid, String? imageUrl) async { |
| 63 | + if (!cached.containsKey(uuid)) { |
| 64 | + return null; |
| 65 | + } |
| 66 | + String? cachedImageUrl = cached[uuid]; |
| 67 | + if (cachedImageUrl != imageUrl) { |
| 68 | + return null; |
| 69 | + } |
| 70 | + return _getTotpCachedImageFile(uuid); |
| 71 | + } |
| 72 | + |
| 73 | + /// Deletes the cached image, if possible. |
| 74 | + Future<void> deleteCachedImage(String uuid) async { |
| 75 | + Map<String, String> cached = Map.from(await future); |
| 76 | + File file = await _getTotpCachedImageFile(uuid); |
| 77 | + await file.deleteIfExists(); |
| 78 | + cached.remove(uuid); |
| 79 | + state = AsyncData(cached); |
| 80 | + _saveIndex(content: cached); |
| 81 | + } |
| 82 | + |
| 83 | + /// Fills the cache with all TOTPs that can be read from the TOTP repository. |
| 84 | + Future<void> fillCache() async { |
| 85 | + TotpList totps = await ref.read(totpRepositoryProvider.future); |
| 86 | + for (Totp totp in totps) { |
| 87 | + await cacheImage(totp); |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + /// Clears the cache. |
| 92 | + Future<void> clearCache() async { |
| 93 | + Directory directory = await _getTotpImagesDirectory(); |
| 94 | + if (directory.existsSync()) { |
| 95 | + directory.deleteSync(recursive: true); |
| 96 | + } |
| 97 | + state = const AsyncData({}); |
| 98 | + } |
| 99 | + |
| 100 | + /// Returns the cache index. |
| 101 | + Future<File> _getIndexFile() async => File(join((await _getTotpImagesDirectory()).path, 'index.json')); |
| 102 | + |
| 103 | + /// Saves the content to the index. |
| 104 | + Future<void> _saveIndex({Map<String, String>? content}) async { |
| 105 | + content ??= await future; |
| 106 | + (await _getIndexFile()).writeAsStringSync(jsonEncode(content)); |
| 107 | + } |
| 108 | + |
| 109 | + /// Returns the TOTP cached image file. |
| 110 | + static Future<File> _getTotpCachedImageFile(String uuid, {bool createDirectory = false}) async => File(join((await _getTotpImagesDirectory(create: createDirectory)).path, uuid)); |
| 111 | + |
| 112 | + /// Returns the totp images directory, creating it if doesn't exist yet. |
| 113 | + static Future<Directory> _getTotpImagesDirectory({bool create = false}) async { |
| 114 | + Directory directory = Directory(join((await getApplicationCacheDirectory()).path, 'totps_images')); |
| 115 | + if (create && !directory.existsSync()) { |
| 116 | + directory.createSync(recursive: true); |
| 117 | + } |
| 118 | + return directory; |
| 119 | + } |
| 120 | +} |
| 121 | + |
| 122 | +/// Allows to easily delete a file without checking if it exists. |
| 123 | +extension _DeleteIfExists on File { |
| 124 | + /// Deletes the current file if it exists. |
| 125 | + Future<void> deleteIfExists() async { |
| 126 | + if (await exists()) { |
| 127 | + await delete(); |
| 128 | + } |
| 129 | + } |
| 130 | +} |
0 commit comments