1
0
Fork 0
mirror of https://github.com/immich-app/immich.git synced 2025-01-09 05:16:47 +01:00
immich/mobile/lib/modules/home/services/asset_cache.service.dart

86 lines
1.9 KiB
Dart
Raw Normal View History

2022-10-15 23:20:15 +02:00
import 'dart:convert';
import 'dart:io';
2022-10-15 23:20:15 +02:00
2022-10-14 23:57:55 +02:00
import 'package:collection/collection.dart';
2022-10-15 23:20:15 +02:00
import 'package:flutter/foundation.dart';
2022-10-14 23:57:55 +02:00
import 'package:hooks_riverpod/hooks_riverpod.dart';
2022-10-17 14:53:27 +02:00
import 'package:http/http.dart';
2022-10-14 23:57:55 +02:00
import 'package:openapi/api.dart';
import 'package:path_provider/path_provider.dart';
2022-10-14 23:57:55 +02:00
2022-10-17 14:53:27 +02:00
abstract class JsonCache<T> {
final String cacheFileName;
2022-10-14 23:57:55 +02:00
JsonCache(this.cacheFileName);
2022-10-14 23:57:55 +02:00
Future<File> _getCacheFile() async {
final basePath = await getTemporaryDirectory();
final basePathName = basePath.path;
final file = File("$basePathName/$cacheFileName.bin");
return file;
}
Future<bool> isValid() async {
final file = await _getCacheFile();
return await file.exists();
2022-10-14 23:57:55 +02:00
}
Future<void> invalidate() async {
final file = await _getCacheFile();
await file.delete();
}
Future<void> putRawData(dynamic data) async {
2022-10-17 14:53:27 +02:00
final jsonString = json.encode(data);
final file = await _getCacheFile();
if (!await file.exists()) {
await file.create();
}
await file.writeAsString(jsonString);
2022-10-17 14:53:27 +02:00
}
2022-10-17 16:40:51 +02:00
dynamic readRawData() async {
final file = await _getCacheFile();
final data = await file.readAsString();
2022-10-17 16:40:51 +02:00
return json.decode(data);
2022-10-17 14:53:27 +02:00
}
void put(T data);
2022-10-17 16:40:51 +02:00
Future<T> get();
2022-10-17 14:53:27 +02:00
}
2022-10-14 23:57:55 +02:00
2022-10-17 14:53:27 +02:00
class AssetCacheService extends JsonCache<List<AssetResponseDto>> {
AssetCacheService() : super("asset_cache");
2022-10-17 14:53:27 +02:00
@override
void put(List<AssetResponseDto> data) {
putRawData(data.map((e) => e.toJson()).toList());
}
@override
2022-10-17 16:40:51 +02:00
Future<List<AssetResponseDto>> get() async {
2022-10-15 23:20:15 +02:00
try {
2022-10-17 16:40:51 +02:00
final mapList = await readRawData() as List<dynamic>;
2022-10-14 23:57:55 +02:00
2022-10-15 23:20:15 +02:00
final responseData = mapList
.map((e) => AssetResponseDto.fromJson(e))
.whereNotNull()
.toList();
2022-10-14 23:57:55 +02:00
2022-10-15 23:20:15 +02:00
return responseData;
} catch (e) {
debugPrint(e.toString());
2022-10-14 23:57:55 +02:00
2022-10-15 23:20:15 +02:00
return [];
}
2022-10-14 23:57:55 +02:00
}
}
2022-10-17 14:53:27 +02:00
final assetCacheServiceProvider = Provider(
(ref) => AssetCacheService(),
);