worldhopper/lib/services/image_cache_service.dart
Felipe M. 0b57896793 feat: eink-mode (#1)
Co-authored-by: Felipe M. <me@fmartingr.com>
Co-committed-by: Felipe M. <me@fmartingr.com>
2026-02-12 22:25:38 +01:00

96 lines
2.7 KiB
Dart

import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
/// Service for caching publication cover images locally
class ImageCacheService {
final Directory _imageDirectory;
ImageCacheService(this._imageDirectory);
static Future<ImageCacheService> create() async {
final appDir = await getApplicationDocumentsDirectory();
final imageDir = Directory('${appDir.path}/images');
// Create subdirectories
await Directory('${imageDir.path}/covers').create(recursive: true);
await Directory('${imageDir.path}/thumbnails').create(recursive: true);
return ImageCacheService(imageDir);
}
/// Download and cache a cover image
Future<String?> cacheCoverImage(String publicationId, String imageUrl) async {
try {
final dio = Dio();
final response = await dio.get(
imageUrl,
options: Options(responseType: ResponseType.bytes),
);
if (response.statusCode != 200) return null;
final file = File('${_imageDirectory.path}/covers/$publicationId.jpg');
await file.writeAsBytes(response.data as List<int>);
return file.path;
} catch (e) {
debugPrint('Error caching cover: $e');
return null;
}
}
/// Download and cache a thumbnail image
Future<String?> cacheThumbnailImage(
String publicationId, String imageUrl) async {
try {
final dio = Dio();
final response = await dio.get(
imageUrl,
options: Options(responseType: ResponseType.bytes),
);
if (response.statusCode != 200) return null;
final file =
File('${_imageDirectory.path}/thumbnails/$publicationId.jpg');
await file.writeAsBytes(response.data as List<int>);
return file.path;
} catch (e) {
debugPrint('Error caching thumbnail: $e');
return null;
}
}
/// Check if a local image file exists
bool hasLocalImage(String? path) {
if (path == null) return false;
return File(path).existsSync();
}
/// Delete cached images for a publication
Future<void> deleteCachedImages(String publicationId) async {
final coverFile = File('${_imageDirectory.path}/covers/$publicationId.jpg');
final thumbFile =
File('${_imageDirectory.path}/thumbnails/$publicationId.jpg');
if (await coverFile.exists()) await coverFile.delete();
if (await thumbFile.exists()) await thumbFile.delete();
}
/// Get cache directory size in bytes
Future<int> getCacheSize() async {
int totalSize = 0;
await for (final entity in _imageDirectory.list(recursive: true)) {
if (entity is File) {
totalSize += await entity.length();
}
}
return totalSize;
}
}