Something went wrong. Try again.
BookOrbit plugin that syncs reading progress to Goodreads, StoryGraph and BookHive
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290import type { BookHiveClient } from "./bookhive.ts";import type { BookOrbitClient } from "./bookorbit.ts";import { NOT_AUTHORIZED_MESSAGE, type GoodreadsClient } from "./goodreads.ts";import { toBookHiveFields, toGoodreadsFields, toProgressPercent, type BookHiveBookFields, type BookSnapshot, type GoodreadsBookFields, type ReadStatus,} from "./mapping.ts";import { isSameIsoDay } from "./dates.ts";import { hasProgress, recordKeyFor, toReadingSessionRecord } from "./reading-sessions.ts";import { groupIntoSittings, isSittingEnded, type Sitting } from "./sittings.ts";import type { Match, ProblemSource, SyncState, Target } from "./state.ts";
export type BookOrbitSource = Pick<BookOrbitClient, "listTrackedBookIds" | "getBookSnapshot" | "listReadingSessions">;export type GoodreadsTarget = Pick< GoodreadsClient, "isAuthorized" | "findBookIdByIsbn" | "searchBookId" | "readBookFields" | "sendBookFields" | "sendProgress">;export type BookHiveTarget = Pick< BookHiveClient, | "findHiveIdByIsbn" | "findHiveIdByGoodreadsId" | "searchHiveId" | "readBookFields" | "sendBookFields" | "sendProgress" | "recordUriFor" | "putReadingSession">;
export interface SyncDependencies { bookOrbit: BookOrbitSource; goodreads: GoodreadsTarget; bookHive: BookHiveTarget; state: SyncState;}
export interface SyncOptions { /** Prints every write instead of sending it, and changes nothing in the targets or the state. */ dryRun: boolean; /** On the first run, old sittings are only marked as seen unless this is set. */ postProgressOnFirstRun: boolean; now: Date; log: (line: string) => void;}
export const NO_MATCH_MESSAGE = "no match";export const NO_BOOKHIVE_RECORD_MESSAGE = "no BookHive record";
type KnownMatch = (bookId: number, target: Target) => Match | null;
// Progress goes only to a book in progress: a progress update on Goodreads can move a finished// book back to currently-reading.const STATUSES_WITH_PROGRESS: ReadonlySet<ReadStatus> = new Set(["reading", "rereading"]);
/** What a target needs from the sync: how to match a book, what to send, and how to send it. */interface TargetAdapter<Fields extends object = object> { target: Target; findMatch(book: BookSnapshot): Promise<Match | null>; desiredFields(book: BookSnapshot): Fields | null; readCurrentFields(targetBookId: string): Promise<object | null>; sendFields(targetBookId: string, book: BookSnapshot, fields: Fields): Promise<void>; sendProgress(targetBookId: string, book: BookSnapshot, percent: number, sitting: Sitting): Promise<void>;}
/** One pass over every tracked BookOrbit book. A failure stays with its book and target. */export async function runSyncCycle(dependencies: SyncDependencies, options: SyncOptions): Promise<void> { const { bookOrbit, goodreads, state } = dependencies; const isFirstRun = !state.hasSentAnything(); // The reading-session log writes its whole history once, so its first cycle reads every page. const writeLogHistory = !state.hasLoggedAnySitting(); const recordProblem = (source: ProblemSource, bookId: number | null, message: string) => { options.log(`problem ${source}${bookId === null ? "" : ` book ${bookId}`}: ${message}`); if (!options.dryRun) state.recordProblem(source, bookId, message, options.now); }; const clearProblem = (source: ProblemSource, bookId: number | null) => { if (!options.dryRun) state.clearProblem(source, bookId); };
let bookIds: number[]; try { bookIds = await bookOrbit.listTrackedBookIds(); clearProblem("bookorbit", null); } catch (error) { recordProblem("bookorbit", null, messageOf(error)); return; }
// Matches found in a dry-run are not saved, so the cycle remembers them itself. const cycleMatches = new Map<string, Match>(); const knownMatch: KnownMatch = (bookId, target) => state.getMatch(bookId, target) ?? cycleMatches.get(`${bookId}:${target}`) ?? null; const adapters = buildAdapters(dependencies, knownMatch); if (goodreads.isAuthorized()) { clearProblem("goodreads", null); } else { recordProblem("goodreads", null, NOT_AUTHORIZED_MESSAGE); } const activeAdapters = adapters.filter((adapter) => adapter.target !== "goodreads" || goodreads.isAuthorized());
for (const bookId of bookIds) { let book: BookSnapshot; let endedSittings: Sitting[]; try { book = await bookOrbit.getBookSnapshot(bookId); const { sessions, hasOlder } = await bookOrbit.listReadingSessions(bookId, { allPages: writeLogHistory }); const sittings = groupIntoSittings(sessions); // With older sessions unread, the oldest sitting on the page may lack its start, and so its record key. if (hasOlder) sittings.shift(); endedSittings = sittings.filter((sitting) => isSittingEnded(sitting, options.now)); clearProblem("bookorbit", bookId); } catch (error) { recordProblem("bookorbit", bookId, messageOf(error)); continue; } if (book.status === "unread") continue;
// A sitting without progress reaches no target: its post would repeat the last percentage. const latestSitting = endedSittings.filter(hasProgress).at(-1) ?? null; for (const adapter of activeAdapters) { try { await syncBookToTarget(adapter, book, latestSitting, { ...dependencies, cycleMatches }, options, isFirstRun); clearProblem(adapter.target, bookId); } catch (error) { recordProblem(adapter.target, bookId, messageOf(error)); } }
try { await logSittings(book, endedSittings, dependencies, knownMatch, options); clearProblem("reading-sessions", bookId); } catch (error) { recordProblem("reading-sessions", bookId, messageOf(error)); } }}
/** Writes one reading-session record for each ended sitting with progress that the log does not hold yet. */async function logSittings( book: BookSnapshot, endedSittings: readonly Sitting[], { bookHive, state }: SyncDependencies, knownMatch: KnownMatch, options: SyncOptions,): Promise<void> { const unlogged = endedSittings.filter((sitting) => hasProgress(sitting) && !state.isSittingLogged(recordKeyFor(book.bookId, sitting))); if (unlogged.length === 0) return;
const hiveId = knownMatch(book.bookId, "bookhive")?.targetBookId ?? null; const bookUri = hiveId ? await bookHive.recordUriFor(hiveId) : null; // A dry-run does not create the BookHive record that a real run would create first in this cycle. const bookReference = bookUri ?? (options.dryRun && hiveId ? `(BookHive record for ${hiveId}, created in this run)` : null); if (!bookReference) throw new Error(NO_BOOKHIVE_RECORD_MESSAGE);
const label = `reading-sessions book ${book.bookId} "${book.title}"`; for (const sitting of unlogged) { const recordKey = recordKeyFor(book.bookId, sitting); const record = toReadingSessionRecord(bookReference, sitting); if (options.dryRun) { options.log(`[dry-run] ${label}: ${recordKey} ${JSON.stringify(record)}`); continue; } await bookHive.putReadingSession(recordKey, { ...record }); state.markSittingLogged(recordKey, book.bookId); options.log(`sent ${label}: ${recordKey}`); }}
async function syncBookToTarget( adapter: TargetAdapter, book: BookSnapshot, sitting: Sitting | null, context: SyncDependencies & { cycleMatches: Map<string, Match> }, options: SyncOptions, isFirstRun: boolean,): Promise<void> { const { state } = context; const { target } = adapter; const label = `${target} book ${book.bookId} "${book.title}"`;
const match = await adapter.findMatch(book); if (!match) throw new Error(NO_MATCH_MESSAGE); if (options.dryRun) { context.cycleMatches.set(`${book.bookId}:${target}`, match); } else { state.saveMatch(book.bookId, target, match); }
const fields = adapter.desiredFields(book); const fieldsJson = JSON.stringify(fields); const lastSentJson = state.getSentFields(book.bookId, target); if (fields && lastSentJson !== fieldsJson) { // With nothing sent yet, the target may already hold these values from before this service. const previous = lastSentJson === null ? await adapter.readCurrentFields(match.targetBookId) : (JSON.parse(lastSentJson) as object); const change = describeChange(fields, previous); if (change !== null) { if (!options.dryRun) await adapter.sendFields(match.targetBookId, book, fields); options.log(`${options.dryRun ? "[dry-run]" : "sent"} ${label}: ${change}`); } if (!options.dryRun) state.saveSentFields(book.bookId, target, fieldsJson); }
if (!sitting || !STATUSES_WITH_PROGRESS.has(book.status)) return; const lastSentSittingEnd = state.getSentProgressSittingEnd(book.bookId, target); if (lastSentSittingEnd !== null && new Date(lastSentSittingEnd) >= sitting.endedAt) return;
const percent = toProgressPercent(sitting.endProgress); const sittingEnd = sitting.endedAt.toISOString(); if (isFirstRun && !options.postProgressOnFirstRun) { options.log(`${options.dryRun ? "[dry-run] " : ""}${label}: first run, progress ${percent}% of the sitting that ended ${sittingEnd} is not posted`); } else if (options.dryRun) { options.log(`[dry-run] ${label}: progress ${percent}% for the sitting that ended ${sittingEnd}`); } else { await adapter.sendProgress(match.targetBookId, book, percent, sitting); options.log(`sent ${label}: progress ${percent}% for the sitting that ended ${sittingEnd}`); } if (!options.dryRun) state.saveSentProgress(book.bookId, target, sittingEnd);}
function buildAdapters({ goodreads, bookHive }: SyncDependencies, knownMatch: KnownMatch): TargetAdapter[] { const goodreadsAdapter: TargetAdapter<GoodreadsBookFields> = { target: "goodreads", async findMatch(book) { // The Goodreads id in BookOrbit is the user's own pairing, and its edition always wins. if (book.goodreadsId) return { targetBookId: book.goodreadsId, method: "bookorbit" }; const known = knownMatch(book.bookId, "goodreads"); if (known) return known; const byIsbn = book.isbn13 ? await goodreads.findBookIdByIsbn(book.isbn13) : null; if (byIsbn) return { targetBookId: byIsbn, method: "isbn" }; const bySearch = await goodreads.searchBookId(book); return bySearch ? { targetBookId: bySearch, method: "search" } : null; }, desiredFields: toGoodreadsFields, readCurrentFields: (bookId) => goodreads.readBookFields(bookId), sendFields: (bookId, _book, fields) => goodreads.sendBookFields(bookId, fields), sendProgress: (bookId, _book, percent) => goodreads.sendProgress(bookId, percent), };
const bookHiveAdapter: TargetAdapter<BookHiveBookFields> = { target: "bookhive", async findMatch(book) { const known = knownMatch(book.bookId, "bookhive"); if (known) return known; // BookHive's catalog comes from Goodreads, and its ISBN index misses books that the catalog holds. const goodreadsId = book.goodreadsId ?? knownMatch(book.bookId, "goodreads")?.targetBookId; const byGoodreadsId = goodreadsId ? await bookHive.findHiveIdByGoodreadsId(goodreadsId) : null; if (byGoodreadsId) return { targetBookId: byGoodreadsId, method: "goodreads-id" }; const byIsbn = book.isbn13 ? await bookHive.findHiveIdByIsbn(book.isbn13) : null; if (byIsbn) return { targetBookId: byIsbn, method: "isbn" }; const bySearch = await bookHive.searchHiveId(book); return bySearch ? { targetBookId: bySearch, method: "search" } : null; }, desiredFields: toBookHiveFields, readCurrentFields: (hiveId) => bookHive.readBookFields(hiveId), sendFields: (hiveId, book, fields) => bookHive.sendBookFields(hiveId, book, fields), sendProgress: (hiveId, book, percent, sitting) => bookHive.sendProgress(hiveId, book, percent, sitting.endedAt), };
// Goodreads goes first, because the BookHive match can use the Goodreads book id. return [goodreadsAdapter, bookHiveAdapter];}
/** * "new" when the target has nothing for the book, the fields that would change otherwise, and null * when every field the sync would send already holds the same value. */function describeChange(desired: object, previous: object | null): string | null { if (!previous) return `new ${JSON.stringify(desired)}`; const previousValues = previous as Record<string, unknown>; const changes = Object.entries(desired) .filter(([key, value]) => value !== null && previousValues[key] !== value && !isSameIsoDay(previousValues[key], value)) .map(([key, value]) => `${key} ${formatValue(previousValues[key])} -> ${formatValue(value)}`); return changes.length === 0 ? null : `update ${changes.join(", ")}`;}
const MAX_LOGGED_TEXT_LENGTH = 40;
function formatValue(value: unknown): string { if (value === null || value === undefined) return "none"; if (typeof value === "string" && value.length > MAX_LOGGED_TEXT_LENGTH) return `"${value.slice(0, MAX_LOGGED_TEXT_LENGTH)}..."`; return JSON.stringify(value);}
function messageOf(error: unknown): string { return error instanceof Error ? error.message : String(error);}