import 'dart:io'; import 'package:path_provider/path_provider.dart'; import 'package:path/path.dart' as path; /// Manages the persistent downloads directory structure class DownloadStorageService { /// Get the root downloads directory Future getDownloadsDir() async { final appDir = await getApplicationDocumentsDirectory(); final downloadsDir = Directory(path.join(appDir.path, 'downloads')); if (!await downloadsDir.exists()) { await downloadsDir.create(recursive: true); } return downloadsDir; } /// Get the directory for a specific series Future getSeriesDir(String seriesId) async { final downloadsDir = await getDownloadsDir(); final seriesDir = Directory(path.join(downloadsDir.path, seriesId)); if (!await seriesDir.exists()) { await seriesDir.create(recursive: true); } return seriesDir; } /// Get the directory for an image stream chapter Future getChapterDir(String seriesId, String chapterId) async { final seriesDir = await getSeriesDir(seriesId); final chapterDir = Directory(path.join(seriesDir.path, chapterId)); if (!await chapterDir.exists()) { await chapterDir.create(recursive: true); } return chapterDir; } /// Get the file path for an EPUB chapter Future getEpubPath(String seriesId, String chapterId) async { final seriesDir = await getSeriesDir(seriesId); return path.join(seriesDir.path, '$chapterId.epub'); } /// Delete all files for a series Future deleteSeriesFiles(String seriesId) async { final downloadsDir = await getDownloadsDir(); final seriesDir = Directory(path.join(downloadsDir.path, seriesId)); if (await seriesDir.exists()) { await seriesDir.delete(recursive: true); } } /// Delete files for a single chapter Future deleteChapterFiles( String seriesId, String chapterId, bool isEpub) async { if (isEpub) { final epubPath = await getEpubPath(seriesId, chapterId); final file = File(epubPath); if (await file.exists()) { await file.delete(); } } else { final downloadsDir = await getDownloadsDir(); final chapterDir = Directory(path.join(downloadsDir.path, seriesId, chapterId)); if (await chapterDir.exists()) { await chapterDir.delete(recursive: true); } } } /// Get total disk usage for all downloads Future getTotalDownloadSize() async { final downloadsDir = await getDownloadsDir(); if (!await downloadsDir.exists()) return 0; int totalSize = 0; await for (final entity in downloadsDir.list(recursive: true, followLinks: false)) { if (entity is File) { totalSize += await entity.length(); } } return totalSize; } }