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 cache entries (mp4 files + HLS directories)
final entries = await _collectCacheEntries(dir);
// Calculate total size
int totalSize = 0;
for (final entry in entries) {
totalSize += entry.size;
}
// Check if eviction needed
if (totalSize <= maxCacheSizeBytes) return;
// Sort by last accessed time (oldest first)
entries.sort((a, b) => a.accessed.compareTo(b.accessed));
// Target 80% of max to avoid frequent evictions
final targetSize = (maxCacheSizeBytes * 0.8).toInt();
for (final entry in entries) {
if (totalSize <= targetSize) break;
try {
totalSize -= entry.size;
if (entry.isDirectory) {
await entry.directory!.delete(recursive: true);
} else {
await entry.file!.delete();
}
await CacheMetadataStore.removeByHash(entry.hash);
} catch (_) {
// Ignore deletion failures
}
}
}