Files
readest/apps/readest-app/src/app/reader/hooks/useHardcoverSync.ts
T
AK Venugopal 80cab8e56d feat: Hardcover.app Sync (#3724)
* feat(hardcover): add one-way Hardcover sync integration

- Add HardcoverClient with ISBN/title-based book lookup, progress push, and note sync
- Add HardcoverSyncMapStore for persistent local mapping of note IDs to Hardcover journal IDs
- Add GraphQL queries/mutations for Hardcover API (insert/update/recreate journal entries)
- Add DB migration for hardcover_note_mappings table (schema: hardcover-sync)
- Add HardcoverSettings dialog component (connect/disconnect/enable toggle)
- Add useHardcoverSync hook wired in Annotator for push-notes and push-progress events
- Add Hardcover Sync section in BookMenu with per-book toggle (persisted in BookConfig)
- Add HardcoverSettings type and DEFAULT_HARDCOVER_SETTINGS to system settings
- Add hardcoverSyncEnabled per-book flag to BookConfig
- Mount HardcoverSettingsWindow in Reader alongside KOSync and Readwise windows

Sync is one-way (Readest → Hardcover), manual-action only, per-book opt-in.
Supports idempotent note sync: insert new, skip unchanged, update changed, recreate on stale remote ID.

* fix(hardcover): proxy API calls server-side to fix CORS, normalize Bearer token

- Add /api/hardcover/graphql Next.js route that proxies POST requests server-side,
  bypassing CORS restrictions (Hardcover API has no Access-Control-Allow-Origin header)
- On Tauri (desktop), calls Hardcover directly; on web, routes through the proxy
- Normalize token in HardcoverClient: accept raw JWT or 'Bearer <jwt>' format
- Update helper text to point to hardcover.app → Settings → API

* fix(hardcover): surface note-sync no-ops and harden book resolution

- Show toast feedback when book data is still loading, Hardcover is not configured,
  or the current book has no annotations/excerpts to sync
- Show an explicit info toast when note sync finds no new changes
- Parse Hardcover search results in the current hits/document response shape
- Resolve note sync through ensureBookInLibrary for parity with progress sync
- Add console logging for note/progress sync failures

* debug(hardcover): add runtime instrumentation for note sync

* feat(metadata): keep identifier stable and store ISBN separately

- Add dedicated metadata.isbn field
- Expose ISBN as its own editable field in book metadata
- Preserve identifier semantics for existing source IDs and hashes
- Route metadata auto-retrieval ISBN handling through the new field
- Prefer metadata.isbn for Hardcover matching

* fix(hardcover): avoid wasm sqlite for note mappings on web

- Store Hardcover note sync mappings in localStorage on web
- Keep sqlite-backed mappings for desktop/native environments
- Remove the web-only database dependency from manual note sync

* fix(hardcover): dedupe notes by payload hash across unstable note IDs

- Add payload-hash lookup in HardcoverSyncMapStore
- Reuse existing journal mapping when payload already synced
- Prevent duplicate insertions when note IDs change or duplicate locally

* fix(hardcover): avoid duplicate quote export when annotation note exists

- Detect excerpt+annotation pairs for the same highlight
- Skip standalone excerpt export when annotation has note text
- Keep annotation export as the single source of truth

* docs(hardcover): add consolidated change summary for review

* fix(hardcover): suppress excerpt export by CFI when annotation note exists

* fix(hardcover): suppress empty-note annotation duplicates when note exists

* fix(hardcover): deduplicate notes by text and cfi base node

* refactor(hardcover): optimize sync performance, add rate limiting and clean up debug tools

* chore: remove dev-only change log from main

* test(hardcover): add unit tests for sync mapping and client logic

* chore: custom deployment and UI fixes

* fix(hardcover): use timestamptz for accurate annotation time

* fix(hardcover): use date scalar and RFC 3339 formatting for journal entries

* Revert "chore: custom deployment and UI fixes"

This reverts commit 0329aba7129d1e1ebf2c663804b8fba9a9f87b91.

* Fix hardcover progress dates and surface imported ISBNs

* Fix Hardcover currently reading sync

* fix(hardcover): avoid promoting note sync status

* style(hardcover): apply prettier formatting

* test(hardcover): fix strict TypeScript assertions

* test(hardcover): harden sync regression coverage

* test(hardcover): fix lint and formatting regressions

* fix(hardcover): narrow note dedupe range matching

* refactor(hardcover): extract note dedupe helpers

* refactor(isbn): extract metadata normalization helpers

* feat(hardcover): improve synced quote formatting
2026-04-03 09:06:43 +02:00

159 lines
5.1 KiB
TypeScript

import { useCallback, useEffect } from 'react';
import { useEnv } from '@/context/EnvContext';
import { useSettingsStore } from '@/store/settingsStore';
import { useBookDataStore } from '@/store/bookDataStore';
import { useTranslation } from '@/hooks/useTranslation';
import { eventDispatcher } from '@/utils/event';
import { HardcoverClient, HardcoverSyncMapStore } from '@/services/hardcover';
import { BookNote } from '@/types/book';
export const useHardcoverSync = (bookKey: string) => {
const _ = useTranslation();
const { envConfig } = useEnv();
const { getConfig, getBookData } = useBookDataStore();
const updateLastSyncedAt = useCallback(
async (timestamp: number) => {
const { settings, setSettings, saveSettings } = useSettingsStore.getState();
const newSettings = {
...settings,
hardcover: { ...settings.hardcover, lastSyncedAt: timestamp },
};
setSettings(newSettings);
await saveSettings(envConfig, newSettings);
},
[envConfig],
);
const getClient = useCallback(async () => {
const { settings } = useSettingsStore.getState();
if (!settings.hardcover?.enabled || !settings.hardcover?.accessToken) {
return null;
}
const appService = await envConfig.getAppService();
const mapStore = new HardcoverSyncMapStore(appService);
return new HardcoverClient(settings.hardcover, mapStore);
}, [envConfig]);
const pushNotes = useCallback(async () => {
const config = getConfig(bookKey);
const book = getBookData(bookKey)?.book;
if (!config || !book) return;
if (!config.hardcoverSyncEnabled) {
eventDispatcher.dispatch('toast', {
message: _('Enable Hardcover sync for this book first.'),
type: 'info',
});
return;
}
const eligibleNotes = (config.booknotes ?? []).filter(
(note: BookNote) =>
(note.type === 'annotation' || note.type === 'excerpt') && !note.deletedAt,
);
if (eligibleNotes.length === 0) {
eventDispatcher.dispatch('toast', {
message: _('No annotations or excerpts to sync for this book.'),
type: 'info',
});
return;
}
const client = await getClient();
if (!client) {
eventDispatcher.dispatch('toast', {
message: _('Configure Hardcover in Settings first.'),
type: 'info',
});
return;
}
try {
const result = await client.syncBookNotes(book, config);
await updateLastSyncedAt(Date.now());
eventDispatcher.dispatch('toast', {
message:
result.inserted === 0 && result.updated === 0
? _('No new Hardcover note changes to sync.')
: _('Hardcover synced: {{inserted}} new, {{updated}} updated, {{skipped}} unchanged', {
inserted: result.inserted,
updated: result.updated,
skipped: result.skipped,
}),
type: result.inserted === 0 && result.updated === 0 ? 'info' : 'success',
});
} catch (error) {
console.error('Hardcover notes sync failed:', error);
eventDispatcher.dispatch('toast', {
message: _('Hardcover notes sync failed: {{error}}', {
error: (error as Error).message,
}),
type: 'error',
});
}
}, [_, bookKey, getBookData, getClient, getConfig, updateLastSyncedAt]);
const pushProgress = useCallback(async () => {
const config = getConfig(bookKey);
const book = getBookData(bookKey)?.book;
if (!config || !book) return;
if (!config.hardcoverSyncEnabled) {
eventDispatcher.dispatch('toast', {
message: _('Enable Hardcover sync for this book first.'),
type: 'info',
});
return;
}
const client = await getClient();
if (!client) {
eventDispatcher.dispatch('toast', {
message: _('Configure Hardcover in Settings first.'),
type: 'info',
});
return;
}
try {
await client.pushProgress(book, config);
await updateLastSyncedAt(Date.now());
eventDispatcher.dispatch('toast', {
message: _('Reading progress synced to Hardcover'),
type: 'success',
});
} catch (error) {
console.error('Hardcover progress sync failed:', error);
eventDispatcher.dispatch('toast', {
message: _('Hardcover progress sync failed: {{error}}', {
error: (error as Error).message,
}),
type: 'error',
});
}
}, [_, bookKey, getBookData, getClient, getConfig, updateLastSyncedAt]);
useEffect(() => {
const handlePushNotes = async (event: CustomEvent) => {
if (event.detail.bookKey !== bookKey) return;
await pushNotes();
};
const handlePushProgress = async (event: CustomEvent) => {
if (event.detail.bookKey !== bookKey) return;
await pushProgress();
};
eventDispatcher.on('hardcover-push-notes', handlePushNotes);
eventDispatcher.on('hardcover-push-progress', handlePushProgress);
return () => {
eventDispatcher.off('hardcover-push-notes', handlePushNotes);
eventDispatcher.off('hardcover-push-progress', handlePushProgress);
};
}, [bookKey, pushNotes, pushProgress]);
return { pushNotes, pushProgress };
};