From 6f12ae7e4af8581b5092051ec955a330bc517b54 Mon Sep 17 00:00:00 2001 From: schroda <50052685+schroda@users.noreply.github.com> Date: Sat, 20 Apr 2024 21:52:18 +0200 Subject: [PATCH] Correctly download ahead for batch download action --- src/lib/data/Mangas.ts | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/src/lib/data/Mangas.ts b/src/lib/data/Mangas.ts index 55b2469a..536066e1 100644 --- a/src/lib/data/Mangas.ts +++ b/src/lib/data/Mangas.ts @@ -248,7 +248,7 @@ export class Mangas { mangaIds: number[], { size, onlyUnread, downloadAhead = false }: DownloadChaptersOptions = {}, ): Promise { - const [unReadUnDownloadedChapters, unReadDownloadedChapters] = await Promise.all([ + const [chaptersToConsider, unReadDownloadedChapters] = await Promise.all([ Mangas.getChapterIdsWithState(mangaIds, { isRead: onlyUnread ? false : undefined, isDownloaded: false, @@ -256,12 +256,34 @@ export class Mangas { downloadAhead ? Mangas.getChapterIdsWithState(mangaIds, { isRead: false, isDownloaded: true }) : [], ]); - const downloadAheadSize = Math.abs(unReadDownloadedChapters.length - (size ?? unReadDownloadedChapters.length)); - const actualSize = downloadAhead ? downloadAheadSize : size; + type MangaIdToDownloadSize = [MangaId: string, DownloadSize: number | undefined]; - const mangaIdToChapters = Object.groupBy(unReadUnDownloadedChapters, ({ mangaId }) => mangaId); - const chapterIdsToDownload = Object.values(mangaIdToChapters) - .map((mangaChapters) => mangaChapters!.slice(0, actualSize)) // the result of groupBy can't result in undefined values + const mangaIdToDefaultDownloadSize = mangaIds.map((mangaId) => [ + String(mangaId), + size, + ]) satisfies MangaIdToDownloadSize[]; + + const mangaIdToChaptersToConsider = Object.groupBy(chaptersToConsider, ({ mangaId }) => mangaId); + const mangaIdToUnReadDownloadedChapters = Object.groupBy(unReadDownloadedChapters, ({ mangaId }) => mangaId); + + const mangaIdToDownloadSize = Object.entries(mangaIdToUnReadDownloadedChapters).map( + ([mangaId, downloadedChapters]) => { + const downloadAheadSize = Math.max( + 0, + (size ?? downloadedChapters!.length) - downloadedChapters!.length, + ); + const actualSize = downloadAhead ? downloadAheadSize : size; + + return [mangaId, actualSize]; + }, + ) satisfies MangaIdToDownloadSize[]; + + const mangaIdToActualDownloadSize = Object.entries( + Object.fromEntries([...mangaIdToDefaultDownloadSize, ...mangaIdToDownloadSize]), + ) satisfies MangaIdToDownloadSize[]; + + const chapterIdsToDownload = mangaIdToActualDownloadSize + .map(([mangaId, actualSize]) => mangaIdToChaptersToConsider[Number(mangaId)]!.slice(0, actualSize)) .flat(); if (!chapterIdsToDownload.length) {