Something went wrong. Try again.
BookOrbit plugin that syncs reading progress to Goodreads, StoryGraph and BookHive
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548import { mkdtemp, readFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { describe, expect, it } from "vitest";
import book30Rows from "../test/fixtures/book-30-reading-sessions.json" with { type: "json" };import { BookOrbitLoginRejectedError } from "./bookorbit.ts";import { GoodreadsHttpError, NOT_AUTHORIZED_MESSAGE } from "./goodreads.ts";import type { BookHiveBookFields, BookSnapshot, GoodreadsBookFields } from "./mapping.ts";import type { ReadingSession } from "./sittings.ts";import { SyncState } from "./state.ts";import { NO_BOOKHIVE_RECORD_MESSAGE, NO_MATCH_MESSAGE, runSyncCycle, type BookHiveTarget, type BookOrbitSource, type GoodreadsTarget, type SyncOptions } from "./sync.ts";
// In-memory stand-ins for the three services. Their HTTP behaviour has its own tests per client.
type Write = { target: string; kind: "fields" | "progress" | "record"; bookId: string; value: unknown };
class FakeBookOrbit implements BookOrbitSource { books = new Map<number, BookSnapshot>(); sessions = new Map<number, ReadingSession[]>(); listFailure: Error | null = null; /** The newest sessions that one page holds, as BookOrbit pages them. */ sessionsPageSize = Infinity; sessionReads: { bookId: number; allPages: boolean }[] = [];
async listTrackedBookIds() { if (this.listFailure) throw this.listFailure; return [...this.books.keys()]; } async getBookSnapshot(bookId: number) { const book = this.books.get(bookId); if (!book) throw new Error(`no book ${bookId}`); return book; } async listReadingSessions(bookId: number, { allPages }: { allPages: boolean }) { this.sessionReads.push({ bookId, allPages }); const newestFirst = [...(this.sessions.get(bookId) ?? [])].sort((a, b) => b.startedAt.getTime() - a.startedAt.getTime()); if (allPages) return { sessions: newestFirst, hasOlder: false }; return { sessions: newestFirst.slice(0, this.sessionsPageSize), hasOlder: newestFirst.length > this.sessionsPageSize }; }}
class FakeGoodreads implements GoodreadsTarget { authorized = true; idsByIsbn = new Map<string, string>(); current = new Map<string, Partial<GoodreadsBookFields>>(); failingBookIds = new Map<string, number>(); lookups: string[] = []; private readonly writes: Write[];
constructor(writes: Write[]) { this.writes = writes; }
isAuthorized() { return this.authorized; } async findBookIdByIsbn(isbn13: string) { this.lookups.push(`isbn ${isbn13}`); return this.idsByIsbn.get(isbn13) ?? null; } async searchBookId(book: { title: string }) { this.lookups.push(`search ${book.title}`); return null; } async readBookFields(bookId: string) { const current = this.current.get(bookId); return current ? { shelf: null, rating: null, readAt: null, review: null, ...current } : null; } async sendBookFields(bookId: string, fields: GoodreadsBookFields) { this.failIfAsked(bookId); this.writes.push({ target: "goodreads", kind: "fields", bookId, value: fields }); } async sendProgress(bookId: string, percent: number) { this.failIfAsked(bookId); this.writes.push({ target: "goodreads", kind: "progress", bookId, value: percent }); } private failIfAsked(bookId: string) { const status = this.failingBookIds.get(bookId); if (status) throw new GoodreadsHttpError(status, "POST", "/shelf/add_to_shelf.xml"); }}
class FakeBookHive implements BookHiveTarget { idsByIsbn = new Map<string, string>(); idsByGoodreadsId = new Map<string, string>(); current = new Map<string, Partial<BookHiveBookFields>>(); recordUris = new Map<string, string>(); private readonly writes: Write[];
constructor(writes: Write[]) { this.writes = writes; }
async findHiveIdByIsbn(isbn13: string) { return this.idsByIsbn.get(isbn13) ?? null; } async findHiveIdByGoodreadsId(goodreadsId: string) { return this.idsByGoodreadsId.get(goodreadsId) ?? null; } async searchHiveId() { return null; } async readBookFields(hiveId: string) { return this.current.get(hiveId) ?? null; } async sendBookFields(hiveId: string, _book: unknown, fields: BookHiveBookFields) { this.writes.push({ target: "bookhive", kind: "fields", bookId: hiveId, value: fields }); } async sendProgress(hiveId: string, _book: unknown, percent: number) { this.writes.push({ target: "bookhive", kind: "progress", bookId: hiveId, value: percent }); } async recordUriFor(hiveId: string) { return this.recordUris.get(hiveId) ?? null; } async putReadingSession(recordKey: string, record: Record<string, unknown>) { this.writes.push({ target: "reading-sessions", kind: "record", bookId: recordKey, value: record }); }}
const PROJECT_HAIL_MARY: BookSnapshot = { bookId: 30, title: "Project Hail Mary", authors: ["Andy Weir"], isbn13: "9780593135204", goodreadsId: null, status: "reading", startedOn: "2026-10-19", finishedOn: null, rating: null, review: null,};const GOODREADS_ID = "54493401";const HIVE_ID = "bk_8W2yvFBhN0NOAWoMzmOm";
// The last sitting of book 30 on 2026-10-20 ended at 14:16:14.317 with 11.23 percent.const LAST_SITTING_SESSIONS: ReadingSession[] = [ { startedAt: new Date("2026-10-20T14:06:25.662Z"), endedAt: new Date("2026-10-20T14:10:44.980Z"), durationSeconds: 256, progressDelta: 1.14, endProgress: 9.726776 }, { startedAt: new Date("2026-10-20T14:10:57.064Z"), endedAt: new Date("2026-10-20T14:16:14.317Z"), durationSeconds: 315, progressDelta: 1.5, endProgress: 11.226599 },];// Real BookOrbit rows of book 30 from 2026-10-19 and 2026-10-20: four sittings.const BOOK_30_SESSIONS: ReadingSession[] = book30Rows.map((row) => ({ startedAt: new Date(row.startedAt), endedAt: new Date(row.endedAt), durationSeconds: row.durationSeconds, progressDelta: row.progressDelta, endProgress: row.endProgress,}));const BOOKHIVE_RECORD_URI = "at://did:plc:wpmrw7djrrifumaxhzyaxpeb/buzz.bookhive.book/3kexisting";const DURING_THE_QUIET_PERIOD = new Date("2026-10-20T14:40:00.000Z");const AFTER_THE_SITTING_ENDED = new Date("2026-10-20T15:00:00.000Z");const NEXT_CYCLE = new Date("2026-10-20T15:05:00.000Z");
async function newStatePath(): Promise<string> { return join(await mkdtemp(join(tmpdir(), "performative-male-")), "state.sqlite");}
async function setUp() { const writes: Write[] = []; const bookOrbit = new FakeBookOrbit(); const goodreads = new FakeGoodreads(writes); const bookHive = new FakeBookHive(writes); bookOrbit.books.set(30, PROJECT_HAIL_MARY); bookOrbit.sessions.set(30, LAST_SITTING_SESSIONS); goodreads.idsByIsbn.set(PROJECT_HAIL_MARY.isbn13 ?? "", GOODREADS_ID); bookHive.idsByGoodreadsId.set(GOODREADS_ID, HIVE_ID); const statePath = await newStatePath(); const state = SyncState.open(statePath, { readOnly: false }); const log: string[] = []; const run = (overrides: Partial<SyncOptions> = {}, runState = state) => runSyncCycle( { bookOrbit, goodreads, bookHive, state: runState }, { dryRun: false, postProgressOnFirstRun: false, now: AFTER_THE_SITTING_ENDED, log: (line) => log.push(line), ...overrides }, ); return { writes, bookOrbit, goodreads, bookHive, state, statePath, log, run };}
/** Sends the book's fields once, so that later cycles are no longer a first run. */async function afterFirstRun(context: Awaited<ReturnType<typeof setUp>>) { await context.run({ now: DURING_THE_QUIET_PERIOD }); context.writes.length = 0;}
describe("runSyncCycle progress", () => { it("posts no progress while the sitting is still open", async () => { const context = await setUp(); await afterFirstRun(context);
await context.run({ now: DURING_THE_QUIET_PERIOD });
expect(context.writes.filter((write) => write.kind === "progress")).toEqual([]); });
it("posts one progress update per target for an ended sitting, and never again for it", async () => { const context = await setUp(); await afterFirstRun(context);
await context.run({ now: AFTER_THE_SITTING_ENDED }); await context.run({ now: NEXT_CYCLE });
expect(context.writes.filter((write) => write.kind === "progress")).toEqual([ { target: "goodreads", kind: "progress", bookId: GOODREADS_ID, value: 11 }, { target: "bookhive", kind: "progress", bookId: HIVE_ID, value: 11 }, ]); });
it("posts no progress for a sitting without progress", async () => { const context = await setUp(); context.bookOrbit.sessions.set(30, BOOK_30_SESSIONS); await afterFirstRun(context);
await context.run({ now: AFTER_THE_SITTING_ENDED }); // At 16:00 the 14:47 sitting has also ended, at the same 11.23% as the sitting before it. await context.run({ now: new Date("2026-10-20T16:00:00.000Z") });
expect(context.writes.filter((write) => write.kind === "progress")).toEqual([ { target: "goodreads", kind: "progress", bookId: GOODREADS_ID, value: 11 }, { target: "bookhive", kind: "progress", bookId: HIVE_ID, value: 11 }, ]); });
it("posts no progress for a finished book", async () => { const context = await setUp(); context.bookOrbit.books.set(30, { ...PROJECT_HAIL_MARY, status: "read", finishedOn: "2026-10-20" }); await afterFirstRun(context);
await context.run({ now: AFTER_THE_SITTING_ENDED });
expect(context.writes.filter((write) => write.kind === "progress")).toEqual([]); });});
describe("runSyncCycle first run", () => { it("posts no progress without the flag, and the next cycle does not post that sitting either", async () => { const context = await setUp();
await context.run({ now: AFTER_THE_SITTING_ENDED }); await context.run({ now: NEXT_CYCLE });
expect(context.writes.filter((write) => write.kind === "progress")).toEqual([]); });
it("posts progress for an ended sitting with the flag", async () => { const context = await setUp();
await context.run({ now: AFTER_THE_SITTING_ENDED, postProgressOnFirstRun: true });
expect(context.writes.filter((write) => write.kind === "progress").map((write) => write.target)).toEqual(["goodreads", "bookhive"]); });
it("sends fields only where the target holds other values", async () => { const context = await setUp(); context.goodreads.current.set(GOODREADS_ID, { shelf: "currently-reading" });
await context.run();
expect(context.writes.filter((write) => write.kind === "fields")).toEqual([ { target: "bookhive", kind: "fields", bookId: HIVE_ID, value: { status: "buzz.bookhive.defs#reading", stars: null, startedAt: "2026-10-19T00:00:00.000Z", finishedAt: null, review: null }, }, ]); });});
describe("runSyncCycle change log", () => { it("names a book that the target does not hold yet as new", async () => { const context = await setUp();
await context.run({ dryRun: true });
expect(context.log).toContainEqual( '[dry-run] goodreads book 30 "Project Hail Mary": new {"shelf":"currently-reading","rating":null,"readAt":null,"review":null}', ); });
it("lists only the fields that change on a book the target already holds", async () => { const context = await setUp(); context.bookOrbit.books.set(30, { ...PROJECT_HAIL_MARY, status: "read", finishedOn: "2026-10-21", rating: 4 }); context.goodreads.current.set(GOODREADS_ID, { shelf: "currently-reading", rating: 4 });
await context.run({ dryRun: true });
expect(context.log).toContainEqual('[dry-run] goodreads book 30 "Project Hail Mary": update shelf "currently-reading" -> "read", readAt none -> "2026-10-21"'); });});
describe("runSyncCycle dates", () => { it("sends nothing to BookHive when its stored dates fall on the same days", async () => { const context = await setUp(); context.bookHive.current.set(HIVE_ID, { status: "buzz.bookhive.defs#reading", startedAt: "2026-10-19T09:14:57.005Z" });
await context.run({ dryRun: true });
expect(context.log.filter((line) => line.includes("bookhive") && !line.includes("progress"))).toEqual([]); });
it("updates a BookHive date that falls on another day", async () => { const context = await setUp(); context.bookHive.current.set(HIVE_ID, { status: "buzz.bookhive.defs#reading", startedAt: "2026-08-09T17:19:26.575Z" });
await context.run({ dryRun: true });
expect(context.log).toContainEqual( '[dry-run] bookhive book 30 "Project Hail Mary": update startedAt "2026-08-09T17:19:26.575Z" -> "2026-10-19T00:00:00.000Z"', ); });});
describe("runSyncCycle reading-session log", () => { const recordWrites = (writes: Write[]) => writes.filter((write) => write.kind === "record");
async function setUpWithBook30History() { const context = await setUp(); context.bookOrbit.sessions.set(30, BOOK_30_SESSIONS); context.bookHive.recordUris.set(HIVE_ID, BOOKHIVE_RECORD_URI); return context; }
it("writes the sitting of 14:06 on 20 October with its key, book, time and progress", async () => { const context = await setUpWithBook30History();
await context.run({ now: AFTER_THE_SITTING_ENDED });
expect(recordWrites(context.writes).find((write) => write.bookId === "b30-20261020T140625Z")?.value).toEqual({ book: BOOKHIVE_RECORD_URI, startedAt: "2026-10-20T14:06:25.662Z", endedAt: "2026-10-20T14:16:14.317Z", durationSeconds: 571, startProgress: 859, endProgress: 1123, }); });
it("writes only the sittings that ended, and each one once over two cycles", async () => { const context = await setUpWithBook30History();
await context.run({ now: AFTER_THE_SITTING_ENDED }); await context.run({ now: NEXT_CYCLE });
// The 14:47 sitting ends at 15:18, after both cycles. expect(recordWrites(context.writes).map((write) => write.bookId)).toEqual([ "b30-20261019T161741Z", "b30-20261020T123848Z", "b30-20261020T140625Z", ]); });
it("writes no record for a sitting without progress", async () => { const context = await setUpWithBook30History();
// At 16:00 the 14:47 sitting has ended. It opened the book for 30 seconds and stayed at 11.23%. await context.run({ now: new Date("2026-10-20T16:00:00.000Z") });
expect(recordWrites(context.writes).map((write) => write.bookId)).not.toContain("b30-20261020T144758Z"); expect(recordWrites(context.writes)).toHaveLength(3); });
it("writes no record for a book without a BookHive record, and reports it", async () => { const context = await setUp(); context.bookOrbit.sessions.set(30, BOOK_30_SESSIONS);
await context.run({ now: AFTER_THE_SITTING_ENDED });
expect(recordWrites(context.writes)).toEqual([]); expect(context.state.listProblems()).toContainEqual({ source: "reading-sessions", bookId: 30, message: NO_BOOKHIVE_RECORD_MESSAGE, occurredAt: AFTER_THE_SITTING_ENDED.toISOString(), }); });
it("reads every page of sessions on the first cycle and writes the whole history, then reads one page", async () => { const context = await setUpWithBook30History(); context.bookOrbit.sessionsPageSize = 2;
await context.run({ now: AFTER_THE_SITTING_ENDED }); await context.run({ now: NEXT_CYCLE });
expect(context.bookOrbit.sessionReads.map((read) => read.allPages)).toEqual([true, false]); expect(recordWrites(context.writes)).toHaveLength(3); });});
describe("runSyncCycle failures", () => { it("records the login problem and writes nothing when BookOrbit rejects the login", async () => { const context = await setUp(); context.bookOrbit.listFailure = new BookOrbitLoginRejectedError();
await context.run();
expect(context.writes).toEqual([]); expect(context.state.listProblems()).toEqual([ { source: "bookorbit", bookId: null, message: "bookorbit: login rejected", occurredAt: AFTER_THE_SITTING_ENDED.toISOString() }, ]); });
it("skips Goodreads without authorization and still writes to BookHive", async () => { const context = await setUp(); context.goodreads.authorized = false; context.bookHive.idsByIsbn.set(PROJECT_HAIL_MARY.isbn13 ?? "", HIVE_ID);
await context.run();
expect(context.writes.map((write) => write.target)).toEqual(["bookhive"]); expect(context.state.listProblems()).toContainEqual({ source: "goodreads", bookId: null, message: NOT_AUTHORIZED_MESSAGE, occurredAt: AFTER_THE_SITTING_ENDED.toISOString(), }); });
it("keeps a Goodreads failure with its book, saves nothing as sent, and still writes to BookHive", async () => { const context = await setUp(); context.goodreads.failingBookIds.set(GOODREADS_ID, 403);
await context.run();
expect(context.state.getSentFields(30, "goodreads")).toBeNull(); expect(context.writes.map((write) => write.target)).toEqual(["bookhive"]); expect(context.state.listProblems()).toContainEqual({ source: "goodreads", bookId: 30, message: "goodreads: HTTP 403 from POST /shelf/add_to_shelf.xml", occurredAt: AFTER_THE_SITTING_ENDED.toISOString(), }); });
it("writes nothing to a target that has no match, and reports the book", async () => { const context = await setUp(); context.bookHive.idsByGoodreadsId.clear();
await context.run();
expect(context.writes.map((write) => write.target)).toEqual(["goodreads"]); expect(context.state.listProblems()).toContainEqual({ source: "bookhive", bookId: 30, message: NO_MATCH_MESSAGE, occurredAt: AFTER_THE_SITTING_ENDED.toISOString(), }); });
it("writes nothing for an unread book", async () => { const context = await setUp(); context.bookOrbit.books.set(30, { ...PROJECT_HAIL_MARY, status: "unread" });
await context.run();
expect(context.writes).toEqual([]); });});
describe("runSyncCycle matching", () => { it("uses a match set by hand without a new lookup", async () => { const context = await setUp(); context.state.saveMatch(30, "goodreads", { targetBookId: "999", method: "manual" });
await context.run();
expect(context.goodreads.lookups).toEqual([]); expect(context.writes.find((write) => write.target === "goodreads")?.bookId).toBe("999"); });
it("uses the Goodreads id in BookOrbit over the ISBN and over a saved match", async () => { const context = await setUp(); context.bookOrbit.books.set(30, { ...PROJECT_HAIL_MARY, goodreadsId: "45479298" }); context.state.saveMatch(30, "goodreads", { targetBookId: "999", method: "manual" });
await context.run();
expect(context.goodreads.lookups).toEqual([]); expect(context.writes.find((write) => write.target === "goodreads")?.bookId).toBe("45479298"); expect(context.state.getMatch(30, "goodreads")).toEqual({ targetBookId: "45479298", method: "bookorbit" }); });
it("finds the BookHive book through the Goodreads id in BookOrbit", async () => { const context = await setUp(); context.bookOrbit.books.set(30, { ...PROJECT_HAIL_MARY, goodreadsId: "45479298" }); context.bookHive.idsByGoodreadsId.set("45479298", "bk_paired");
await context.run();
expect(context.state.getMatch(30, "bookhive")).toEqual({ targetBookId: "bk_paired", method: "goodreads-id" }); });
it("matches by ISBN first and sends no title search", async () => { const context = await setUp();
await context.run();
expect(context.goodreads.lookups).toEqual(["isbn 9780593135204"]); expect(context.state.getMatch(30, "goodreads")).toEqual({ targetBookId: GOODREADS_ID, method: "isbn" }); });
it("finds the BookHive book through the Goodreads id when BookHive misses the ISBN", async () => { const context = await setUp();
await context.run();
expect(context.state.getMatch(30, "bookhive")).toEqual({ targetBookId: HIVE_ID, method: "goodreads-id" }); });});
describe("runSyncCycle dry-run", () => { it("writes to no target and leaves the state file byte-for-byte unchanged", async () => { const context = await setUp(); await afterFirstRun(context); context.state.close(); const before = await readFile(context.statePath); const readOnlyState = SyncState.open(context.statePath, { readOnly: true }); context.bookOrbit.books.set(30, { ...PROJECT_HAIL_MARY, rating: 5, review: "Amaze." });
await context.run({ dryRun: true, now: AFTER_THE_SITTING_ENDED }, readOnlyState); readOnlyState.close();
expect(context.writes).toEqual([]); expect(await readFile(context.statePath)).toEqual(before); });
it("prints the writes of a fixed input as in the golden file", async () => { const context = await setUp(); context.bookOrbit.books.set(31, { bookId: 31, title: "The Left Hand of Darkness", authors: ["Ursula K. Le Guin"], isbn13: "9780441478125", goodreadsId: null, status: "read", startedOn: "2026-09-01", finishedOn: "2026-09-20", rating: 5, review: "Cold, patient, and kind.", }); context.goodreads.idsByIsbn.set("9780441478125", "18423"); context.bookHive.idsByIsbn.set("9780441478125", "bk_LeftHandOfDarkness0"); const readOnlyState = SyncState.open(await newStatePath(), { readOnly: true });
await context.run({ dryRun: true, postProgressOnFirstRun: true }, readOnlyState);
await expect(`${context.log.join("\n")}\n`).toMatchFileSnapshot("../test/fixtures/dry-run.golden.txt"); });});