import fs from "node:fs/promises"; import path from "node:path"; import type { Book } from "./library"; import type { Browser } from "./browser"; import type { Database } from "./database"; import { DmmBooks } from "./platforms/dmm-books"; import { FanzaDoujin } from "./platforms/fanza-doujin"; import { GooglePlayBooks } from "./platforms/google-play-books"; const platforms = { "dmm-books": DmmBooks, "fanza-doujin": FanzaDoujin, "google-play-books": GooglePlayBooks, }; export type TPlatform = keyof typeof platforms; export function site(url: string): TPlatform { for (const [platform, { siteUrl }] of Object.entries(platforms)) { if (siteUrl(new URL(url))) return platform as TPlatform; } throw new Error(`Unsupported URL: ${url}`); } export function createPlatform(opts: { platform: TPlatform; db: Database; browser: Browser; }) { if (!(opts.platform in platforms)) { throw new Error( `The value must be a platform type: ${[...Object.keys(platforms)].join( ", ", )}.`, ); } const platform = platforms[opts.platform](opts.browser); return { ...platform, async download(dir: string, book: Book): Promise { await fs.mkdir(path.dirname(dir), { recursive: true }); await fs.mkdir(dir); const files: Array<() => Promise> = await platform.getFiles(book); const digits = String(files.length).length; function pad(n: string) { return n.padStart(digits, "0"); } const supportedTypes = { "image/png": "png", "image/jpeg": "jpg", }; for (const [n, dataUrl] of Object.entries(files)) { const [prefix, base64] = (await dataUrl()).split(",", 2); const [, type, encoding] = /^data:([^;]*)(;base64)?$/.exec(prefix) ?? []; const extension = supportedTypes[type]; if (!extension) { throw new Error( `It was ${type}. The image must be a file of type: ${[ ...Object.keys(supportedTypes), ].join(", ")}.`, ); } if (encoding !== ";base64") { throw new Error("Only base64 is supported."); } const buffer = Buffer.from(base64, "base64"); await fs.writeFile(`${dir}/${pad(n)}.${extension}`, buffer); } process.stderr.write(`\n`); }, async logout() { await opts.db.run( `update platforms set secrets = 'null' where name = ?`, opts.platform, ); }, }; }