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 { GooglePlayBooks } from "./platforms/google-play-books"; const platforms = { "dmm-books": DmmBooks, "google-play-books": GooglePlayBooks, }; export type TPlatform = keyof typeof platforms; export function site(url: string): TPlatform { const { origin } = new URL(url); for (const [platform, { site }] of Object.entries(platforms)) { if (site.includes(origin)) 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(`Available platform: ${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); await platform.download(dir, book); }, async logout() { await opts.db.run( `update platforms set secrets = 'null' where name = ?`, opts.platform, ); }, }; }