From eb146e826dc3b8b8d5ff2dd4596cc7554845e112 Mon Sep 17 00:00:00 2001 From: lifegpc Date: Sat, 10 Jun 2023 21:11:17 +0800 Subject: [PATCH] Bug fix: A gallery may contains two image which have same name --- tasks/download.ts | 14 +++++++++++++- utils.ts | 12 ++++++++++++ utils_test.ts | 12 +++++++++++- 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/tasks/download.ts b/tasks/download.ts index cb3834f..addc57c 100644 --- a/tasks/download.ts +++ b/tasks/download.ts @@ -5,6 +5,7 @@ import { EhDb } from "../db.ts"; import { Task, TaskDownloadProgess, TaskType } from "../task.ts"; import { TaskManager } from "../task_manager.ts"; import { + add_suffix_to_path, asyncFilter, promiseState, PromiseStatus, @@ -117,6 +118,13 @@ export async function download_task( if (cfg.mpv) { const mpv = await client.fetchMPVPage(task.gid, task.token); m.set_total_page(mpv.pagecount); + const names = mpv.imagelist.reduce( + (acc: Record, cur) => { + const curr = cur.name; + return acc[curr] ? ++acc[curr] : acc[curr] = 1, acc; + }, + {}, + ); for (const i of mpv.imagelist) { if (abort.aborted) break; await m.add_new_task(async () => { @@ -167,7 +175,11 @@ export async function download_task( const download_original = cfg.download_original_img && !i.is_original; if (download_original) console.log(i.index, i.data.o); - const path = resolve(join(base_path, i.name)); + let path = resolve(join(base_path, i.name)); + if (names[i.name] > 1) { + path = add_suffix_to_path(path, i.page_token); + console.log("Changed path to", path); + } function download_img() { return new Promise((resolve, reject) => { async function download() { diff --git a/utils.ts b/utils.ts index 4047b93..9719714 100644 --- a/utils.ts +++ b/utils.ts @@ -152,3 +152,15 @@ export function configureZipJs() { configure({ useWebWorkers: false }); zipjs_configured = true; } + +export function add_suffix_to_path(path: string, suffix?: string) { + if (suffix === undefined) { + suffix = Math.round(Math.random() * 100000).toString(); + } + const ext = extname(path); + if (ext) { + return `${path.slice(0, path.length - ext.length)}-${suffix}${ext}`; + } else { + return `${path}-${suffix}`; + } +} diff --git a/utils_test.ts b/utils_test.ts index 6e9f942..55939a9 100644 --- a/utils_test.ts +++ b/utils_test.ts @@ -1,6 +1,7 @@ -import { assertEquals } from "std/testing/asserts.ts"; +import { assert, assertEquals } from "std/testing/asserts.ts"; import { check_running } from "./pid_check.ts"; import { + add_suffix_to_path, asyncFilter, asyncForEach, filterFilename, @@ -69,3 +70,12 @@ Deno.test("filterFilename_test", () => { assertEquals(filterFilename("d|?ad.ts"), "d__ad.ts"); } }); + +Deno.test("add_suffix_to_path_test", () => { + assertEquals(add_suffix_to_path("test.ts", "ok"), "test-ok.ts"); + assertEquals(add_suffix_to_path("test", "ok"), "test-ok"); + const t = add_suffix_to_path("test.ts"); + console.log(t); + assert(t.startsWith("test-")); + assert(t.endsWith(".ts")); +});