import 'dart:io'; import 'package:crypto/crypto.dart'; import 'package:flutter/foundation.dart'; import 'package:path_provider/path_provider.dart'; class CacheManager { static const _cacheDir = 'melo_cache'; late Directory _cacheFolder; Future init() async { final appDir = await getApplicationCacheDirectory(); _cacheFolder = Directory('${appDir.path}/$_cacheDir'); if (!await _cacheFolder.exists()) { await _cacheFolder.create(recursive: true); } } Future getCacheSize() async { int size = 0; final files = _cacheFolder.listSync(recursive: true); for (final file in files) { if (file is File) { size += await file.length(); } } return size; } Future clearCache() async { try { if (await _cacheFolder.exists()) { await _cacheFolder.delete(recursive: true); } await _cacheFolder.create(recursive: true); debugPrint('Cache gelöscht'); } catch (e) { debugPrint('Fehler beim Löschen des Cache: $e'); } } Future getCachedFile(String streamUrl) async { try { final hash = md5.convert(streamUrl.codeUnits).toString(); final file = File('${_cacheFolder.path}/$hash.mp3'); if (await file.exists()) { return file; } return null; } catch (e) { debugPrint('Fehler beim Abrufen der Cache-Datei: $e'); return null; } } Future getCacheFile(String streamUrl) async { final hash = md5.convert(streamUrl.codeUnits).toString(); return File('${_cacheFolder.path}/$hash.mp3'); } Stream streamAndCache(Stream> sourceStream, String streamUrl) async* { final cacheFile = await getCacheFile(streamUrl); final sink = cacheFile.openWrite(); await for (final chunk in sourceStream) { sink.add(chunk); yield cacheFile; } await sink.close(); } }