Something went wrong. Try again.
BookOrbit plugin that syncs reading progress to Goodreads, StoryGraph and BookHive
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133import { createInterface } from "node:readline/promises";
import { BookHiveClient } from "./bookhive.ts";import { BookOrbitClient } from "./bookorbit.ts";import { ConfigError, readBookOrbitCredentials, readConfig, type BookOrbitCredentials, type Config } from "./config.ts";import { GoodreadsClient } from "./goodreads.ts";import { SyncState, type Target } from "./state.ts";import { runSyncCycle } from "./sync.ts";
const POLL_INTERVAL_MS = 5 * 60_000;const TARGETS: readonly Target[] = ["goodreads", "bookhive"];const EXIT_OK = 0;const EXIT_FAILURE = 1;
export const USAGE = `usage: performative-male <command>
run [--dry-run] [--post-progress] sync every 5 minutes; --dry-run prints one cycle and exits goodreads-auth authorize your Goodreads account once link <bookorbit-book-id> <goodreads|bookhive> <target-id> replace the match of a book on a target status list books with no match and the last errors`;
export interface CliIo { stdout: (line: string) => void; stderr: (line: string) => void; /** Waits for the user to press Enter, for the Goodreads authorization. */ waitForEnter: () => Promise<void>; fetch?: typeof fetch; sleep?: (ms: number) => Promise<void>;}
/** Runs one command and returns its exit code. */export async function main(argv: readonly string[], env: NodeJS.ProcessEnv, io: CliIo): Promise<number> { const [command, ...args] = argv; try { const config = readConfig(env); // Every command checks the credentials, so a broken file shows up before anything else runs. const credentials = await readBookOrbitCredentials(config.credentialsFile); switch (command) { case "run": return await runCommand(config, credentials, args, io); case "goodreads-auth": return await goodreadsAuthCommand(config, io); case "link": return linkCommand(config, args, io); case "status": return statusCommand(config, io); default: io.stderr(USAGE); return EXIT_FAILURE; } } catch (error) { if (!(error instanceof ConfigError)) throw error; io.stderr(error.message); return EXIT_FAILURE; }}
async function runCommand(config: Config, credentials: BookOrbitCredentials, args: string[], io: CliIo): Promise<number> { const dryRun = args.includes("--dry-run"); const postProgressOnFirstRun = args.includes("--post-progress"); const fetchImplementation = io.fetch ?? fetch; const sleep = io.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
const state = SyncState.open(config.stateFile, { readOnly: dryRun }); const bookOrbit = new BookOrbitClient({ baseUrl: config.bookOrbitUrl, credentials, fetch: fetchImplementation }); const goodreads = new GoodreadsClient({ ...config.goodreads, authorization: state.getGoodreadsAuthorization(), fetch: fetchImplementation }); const bookHive = new BookHiveClient({ ...config.bookHive, fetch: fetchImplementation }); const dependencies = { bookOrbit, goodreads, bookHive, state };
// Docker stops the service with SIGTERM, which ends the process between two SQLite writes; // each write is atomic, so no shutdown handler is needed. for (;;) { await runSyncCycle(dependencies, { dryRun, postProgressOnFirstRun, now: new Date(), log: io.stdout }); if (dryRun) { state.close(); return EXIT_OK; } await sleep(POLL_INTERVAL_MS); }}
async function goodreadsAuthCommand(config: Config, io: CliIo): Promise<number> { const state = SyncState.open(config.stateFile, { readOnly: false }); const client = new GoodreadsClient({ ...config.goodreads, authorization: null, fetch: io.fetch }); const requestToken = await client.getRequestToken(); io.stdout(`Open this link, approve access, then press Enter:\n${client.authorizeUrl(requestToken)}`); await io.waitForEnter(); const authorization = await client.getAuthorization(requestToken); state.saveGoodreadsAuthorization(authorization); state.clearProblem("goodreads", null); state.close(); io.stdout(`Authorized Goodreads user ${authorization.userId}.`); return EXIT_OK;}
function linkCommand(config: Config, args: string[], io: CliIo): number { const [bookIdText, target, targetBookId] = args; const bookId = Number(bookIdText); if (!Number.isInteger(bookId) || !TARGETS.includes(target as Target) || !targetBookId) { io.stderr(USAGE); return EXIT_FAILURE; } const state = SyncState.open(config.stateFile, { readOnly: false }); state.saveMatch(bookId, target as Target, { targetBookId, method: "manual" }); state.clearProblem(target as Target, bookId); state.close(); io.stdout(`Linked BookOrbit book ${bookId} to ${target} book ${targetBookId}.`); return EXIT_OK;}
function statusCommand(config: Config, io: CliIo): number { const state = SyncState.open(config.stateFile, { readOnly: true }); const problems = state.listProblems(); state.close(); if (problems.length === 0) { io.stdout("No problems."); return EXIT_OK; } for (const problem of problems) { const subject = problem.bookId === null ? problem.source : `${problem.source} book ${problem.bookId}`; io.stdout(`${subject}: ${problem.message} (since ${problem.occurredAt})`); } return EXIT_OK;}
/** Reads one line from the terminal. */export async function waitForEnterOnStdin(): Promise<void> { const prompt = createInterface({ input: process.stdin, output: process.stdout }); await prompt.question(""); prompt.close();}