evictIfNeeded static method
Evict oldest files if cache exceeds maximum size. Uses LRU (Least Recently Used) strategy based on file access time. Evicts until cache is under 80% of max size.
Implementation
static Future<void> evictIfNeeded() async {
final dir = Directory(await getCacheDir());
if (!dir.existsSync()) return;
// Collect all files with their stats
final files = <File>[];
await for (final entity in dir.list()) {
if (entity is File) {
files.add(entity);
}
}
// Calculate total size
int totalSize = 0;
final fileStats = <(File, FileStat)>[];
for (final file in files) {
try {
final stat = await file.stat();
totalSize += stat.size;
fileStats.add((file, stat));
} catch (_) {
// Skip files that can't be stat'd
}
}
// Check if eviction needed
if (totalSize <= maxCacheSizeBytes) return;
// Sort by last accessed time (oldest first)
fileStats.sort((a, b) => a.$2.accessed.compareTo(b.$2.accessed));
// Target 80% of max to avoid frequent evictions
final targetSize = (maxCacheSizeBytes * 0.8).toInt();
for (final (file, stat) in fileStats) {
if (totalSize <= targetSize) break;
try {
totalSize -= stat.size;
await file.delete();
// Extract hash from filename (format: hash.mp4)
final hash = file.path.split('/').last.replaceAll('.mp4', '');
await CacheMetadataStore.removeByHash(hash);
} catch (_) {
// Ignore deletion failures
}
}
}