* docs: define ebook architecture matching audiobooks * docs: plan ebook audiobook-parity implementation * feat: add ebook scanner parser foundation * fix: harden ebook scanner foundation * fix: handle ebook isbn labels * fix: guard ebook subtree scans * feat: scan ebook libraries in core * fix: preserve ebook scan people credits * fix: refresh ebook scan metadata safely * feat: persist ebook series membership * test: cover ebook series persistence decisions * fix: address ebook scanner PR review * docs: clarify ebook foundation PR scope * feat: add ebook metadata enricher * fix: harden ebook poster cache * feat: wire ebook metadata sync task * feat: expose ebook library metadata setup * feat: add ebook catalog scope support * feat: add ebook detail view * feat: label ebook file versions by format * feat: use file-size copy for downloads * feat: use file language in download dialog * test: cover ebook detail authors and downloads * fix: drop narrator credits from ebook scanner merges * fix: align ebook collection filters with book media * fix: drop asin provider ids from ebook enrichment * fix: force ebook people refresh for stale narrators * chore: omit ebook planning docs from branch * feat: add ebook detail related content * feat: add ebook reader file entrypoint * feat: render ebooks with foliate reader * feat: persist ebook reader progress * feat: add ebook reader controls * feat: extract ebook pdf metadata * feat: favor scanner isbn during ebook enrichment * feat: extract fbz ebook metadata * feat: count cbz ebook pages * feat: show ebook file page counts * feat: show ebook download summaries * feat: switch ebook reader files * feat: prefer epub for ebook read action * feat: surface ebook reader progress * feat: sync ebook reader progress cache * feat: hide ebook read action for unsupported files * feat: filter ebook reader file selector * fix: serve fbz ebook archives with reader mime type * fix: detect fbz ebooks from compound filename * fix: authorize fbz ebooks from compound filename * fix: scope ebook catalog facets * fix: reject narrator queries for ebooks * fix: build ebook recommendation text from authors * fix: include ebooks in embedding eligibility * fix: include ebooks in recommendation media mix * fix: include ebooks in recently added recommendations * feat: include ebook progress in recommendation signals * feat: include ebooks in continue watching sections * feat: include ebooks in catalog progress metrics * fix: read ebook isbn from epub metadata * fix: filter ebook asin provider aliases * fix: fall back from unsupported ebook reader files * fix: sort ebook catalogs by reader progress * fix: filter ebook catalogs by reader progress * fix: include ebooks in last watched catalog filters * feat: reflect ebook reader progress in item user state * feat: share ebook progress state across item surfaces * feat: report ebook scan progress * fix: include ebook activity in recommendations * fix: expose ebook reader progress on item detail * fix: support ebook subtree scans * fix: honor profile header for ebook item progress * fix: add ebook library default sections * fix: route ebook continue cards to reader * fix: hide watched toggle for ebooks * fix: route ebook watch tonight cards to reader * fix: route ebook hero actions to reader * fix: detect archive ebook reader formats by filename * feat: cache embedded ebook covers during scan * fix: encode ebook hero reader links * fix: persist non-epub ebook reader progress * fix: scope narrator catalog badges to audiobooks * fix: merge ebook reader progress during item repair * fix: label ebook progress filters as read * fix: show ebook related rails as book covers * fix: remove txt ebook reader support * fix: reject txt ebook reader files * fix: label ebook advanced filters as read * fix: label ebook personalized sorts as read * fix: remove plain text reader loader path * test: cover ebook unread catalog rules * fix: preserve ebook reader library context * fix: link ebook genres with library scope * fix: encode related rail item links * fix: encode catalog card item links * fix: encode hero and continue item links * fix: encode watch tonight item links * fix: encode recommendation and search item links * test: cover ebook scan format set * fix: label ebook search results clearly * fix: make global search prompt media neutral * fix: encode catalog read API ids * fix: encode item API ids * fix: include ebook reader vendor in docker build * fix: make ebook reader build clean * fix: clean ebook embedded descriptions * docs: plan ebook reader shell parity * feat: add ebook reader shell controls * fix: widen ebook scrolled reader flow * fix: remove scrolled reader content width cap * docs: plan ebook reader full parity * feat: persist ebook reader config * feat: add ebook annotations and bookmarks * feat: add ebook reader tools and aids * feat: add ebook advanced reader settings * fix: keep ebook reader panel in viewport * fix: use foliate sizing units for ebook scroll flow * fix: keep ebook settings controls readable * fix: simplify ebook reader settings controls * feat(ebooks): extract local covers during scan (#98) * feat(ebooks): extract local covers during scan * fix(ebooks): read nullable poster paths during cover scan * fix(catalog): coalesce nullable media artwork fields * fix(ebooks): group sibling formats by book identity * fix(ebooks): tolerate legacy ebook metadata encodings * fix(ebooks): decode PDF hex metadata strings * fix(ebooks): harden local cover extraction and format grouping Address review findings on the local cover scan: - Restrict generic sidecar covers (cover.jpg, folder.png, ...) to single-book directories, always accept images named after the book file, and apply exactly one cover per reconcile with sidecar taking precedence over the embedded cover. - Replace the read-then-write poster update with an atomic conditional UPDATE (ItemRepository.SetLocalPoster) so provider/admin artwork is never clobbered by concurrent writers, and refresh locally owned posters when the extracted cover bytes change (thumbhash compare). - Preserve UTF-8 PDF Info strings (including a UTF-8 BOM) instead of forcing everything through Windows-1252; the cp1252 fallback now only applies to non-UTF-8 bytes. - Select EPUB covers by manifest media-type with properties="cover-image" outranking the EPUB2 meta name="cover" id, so XHTML cover pages no longer shadow the real image. - Order CBZ pages naturally (2.jpg before 10.jpg, ch2/ before ch10/) when picking the cover page, via a single O(n) min-scan. - Bump the ebook content group key scheme to version 2 and reprocess rows written under older versions so pre-existing libraries gain sibling-format grouping instead of accumulating duplicates. - Group different formats only (a same-format sibling with colliding sparse metadata stays a separate item) and stop a joining sibling's embedded metadata from overwriting a provider-matched item. - Decode any IANA-labelled OPF/FB2 XML charset (windows-1251, koi8-r, shift_jis, ...) via x/net/html/charset, and wire the charset reader into FB2 parsing which previously had none. - Strip the full .fb2.zip double extension from filename-derived titles and group keys. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> * feat(ebooks): add reader profiles and ruler (#99) * feat(ebooks): extract local covers during scan * fix(ebooks): read nullable poster paths during cover scan * fix(catalog): coalesce nullable media artwork fields * fix(ebooks): group sibling formats by book identity * fix(ebooks): tolerate legacy ebook metadata encodings * fix(ebooks): decode PDF hex metadata strings * feat(ebooks): add reader profiles and ruler * fix(ebooks): address reader ruler and profile review findings - skip renderer setStyles/render when computed styles and attributes are unchanged, so ruler position updates no longer re-style the book view - drag the ruler via a local draft that commits on release, with the surface rect cached at pointer-down - migrate font values persisted before the generic stacks (Inter, Georgia, Merriweather, legacy serif) so the font select never renders blank, with a Custom fallback option for unknown values - make the ruler band click-through and move dragging to a dedicated keyboard-accessible slider handle so links and text selection keep working under the band - share font stacks between options and profiles via READER_FONT_STACKS - surface the active reading profile, move presets to the top of the settings panel, and drop the redundant profile button aria-labels Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ebooks): resolve prefer-const lint error in readest document lib `pnpm run lint` failed on the branch because `direction` is never reassigned in getDirection; split the destructure so only the reassigned `writingMode` stays mutable. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> * Merge branch 'main' into work/ebooks-reader-base Brings the ebook integration branch up to date with main (audiobook library redesign, continue-watching rework and card affordances, quic-go bump, jellycompat fixes). Conflict resolutions favor main's generalized mechanisms and register ebooks with them: - media scope validation goes through IsValidMediaScope (now including "ebook" alongside main's "video" group scope), in Go and in the web filter/search types - continue-watching uses main's typed rails; reading-type sections pull resume points from ebook_reader_progress and the ebook library default section is wired to ContinueTypeConfig(ContinueTypeReading) - item_repo keeps main's derived select-list machinery (itemColumnExpr) and both poster accessors (GetPoster/SetLocalPoster for ebook covers, GetPosterPath for audiobook covers) - web cards/hero/watch-tonight adopt main's buildMediaPlayHref helpers, which now route ebooks to /reader/ebook and encode content ids; ebook affordances (BookOpen icon, Read verb, percent-read subtitle) carry over onto main's reworked components - LibraryForm ebook support ported into main's refactored useLibraryForm/libraryTypes modules Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(docker): copy foliate-js vendor into Dockerfile.dev frontend stage foliate-js is a file:vendor/foliate-js dependency, so pnpm install needs the vendor directory before the lockfile install layer. The production Dockerfile already copies it; the dev image was missed, breaking make dev-deploy with ENOENT on /app/web/vendor/foliate-js. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(ebooks): render Continue Reading sections as upright poster cards All-ebook continue sections previously fell through to the horizontal 16:9 wide card; include ebooks in the poster-variant check so book covers render in their natural 2:3 framing. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ui): stop related-rail highlight ring clipping on detail pages Move the current-item ring onto the cover artwork with a themed ring-offset color (matching the sidebar profile highlight) and give the scroll container top headroom so the ring is not cut off by overflow-x-auto. Applies to both ebook and audiobook detail rails. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(scanner): harden ebook scanning against data loss and bad metadata - Reconcile missing ebook files like video/audio, with real per-root walk failure tracking (failed/unmounted roots are excluded from deletion), symlinked-root support via the shared logical walker, and the empty-root cleanup allowance before any destructive reconciliation. - Create ebook items as 'pending' so enrichment can promote them to 'matched' (backfill migration included), and protect matched items from re-scan clobbering: title/year skipped, people/series fill-empty only. - PDF metadata: scan head + tail windows (non-linearized PDFs keep the Info dict at the end), require proper key delimiters, head values win. - Cap plain .fb2 reads like .fbz entries; drop .md as an ebook format. - gofmt internal/scanner/audiobook.go (pre-existing drift). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ebooks): make enrichment failures non-terminal with dedicated backoff state - Provider errors now record a failure (capped retries) instead of stamping last_refreshed, which permanently excluded items after transient outages. - Unconfigured metadata chains and the scan-window membership race skip the item without stamping or burning a retry. - Failure tracking moves to a new ebook_enrichment_state table, decoupling it from media_items.refresh_failures (shared with metadata refresh debt). - Preserve non-author people credits when persisting enrichment results. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(catalog): gate ebook progress on hidden history and centralize threshold - Apply user_history_hidden_items gating (video semantics) to the ebook watched/in-progress filters, progress sort plan, and Continue Reading. - Continue Reading pages past dismissed items via the shared collector and dedupes items across pages (also fixes the video path's latent exposure). - Centralize the 0.9 finished threshold as models.EbookFinishedProgressThreshold with a single SQL-interpolated mirror in catalog. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(recommendations): correct watcher counting and wire ebook taste signals - itemWatchersQuery dedupes to distinct (watcher, item) rows so one binge-watcher can no longer satisfy minWatchers; the eligibility floor now counts distinct accounts rather than profiles. - Hidden-history gating on GetEbookReaderProgressForUser (signal reader). - Ebook reading produces canonical implicit taste signals (weighted like the equivalent movie progress ratio); ebooks join taste-seed candidates. - Stale GetRecentlyAddedItems doc comment corrected. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): harden ebook reader endpoints and serve a Content-Security-Policy - Serve a CSP on all SPA HTML responses: blob/srcdoc book iframes inherit it, so script-src 'self' 'wasm-unsafe-eval' blocks script execution from malicious book content (sandbox alone is defeated by the WebKit allow-scripts requirement). Threat model documented on the constant. - X-Content-Type-Options: nosniff on frontend, jellycompat, and ebook file responses; MIME resolution can no longer fall through to octet-stream for an admitted ebook file. - Annotation PATCH: presence-aware field semantics (absent keeps, present sets/clears), invariant re-validation on the merged row, and an atomic SELECT ... FOR UPDATE read-merge-write. - Request size caps (413) on progress/config/annotation writes; Content-Disposition via mime.FormatMediaType; hidden-history gating in the shared ebook progress lister; FK-cascade indexes for reader tables. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(api): native read-state endpoints for ebooks - POST/DELETE /watched/{id} accepts ebook content IDs: mark read upserts progress 1.0 preserving the reader's file/location (or picks the preferred reader file for never-opened books); mark unread mirrors video unwatch semantics and deletes the progress row. - /history/remove accepts ebooks: hides via user_history_hidden_items without touching the reading position (hidden != unread; next reading activity resurfaces the book, mirroring video re-watch). - Access-filter checks match the video branch; shared logic lives in ebook_read_state.go. Sort metrics/user-state thresholds use the shared constant; profile-header fallback deduplicated. Clients: response is {type: "ebook", affected_count: 1, played: bool}; the existing watched SSE event fires. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(web): harden the ebook reader UI - Open-flow race: cancellation checked after every await with full stale-run teardown (no wrong-file progress saves, no leaked views/blob URLs); book.destroy() on cleanup. - Progress: monotonic stale-response guard; visibilitychange flush uses the refresh-capable client, pagehide uses keepalive; per-book cross-format progress documented as deliberate. - Settings: side effects out of the setState updater; local edits no longer clobbered by late server config; pending saves flushed on unmount/pagehide. - TTS: generation token so Stop actually stops (Chromium/Firefox synthetic events); Media Session uninstalled on unmount. - External book links: http(s) only, opened with noopener,noreferrer. - apiBlob 512 MiB guard with a user-facing error; fraction bookmarks navigable; search-result key collisions fixed; dead e-ink code removed; getLibrarySortRelevanceScope deduplicated; md format dropped. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): mark read/unread affordances for ebooks - Item detail gets a Mark Read/Unread button; card menus drop the ebook gate and share type-aware labels/toasts (also dedupes audiobook wording). - Watched-state invalidation includes the reader progress query key so the Continue button and percent refresh after toggling. - Continue Reading dismiss copy for ebooks; dismissal path now URL-encodes item IDs (ebook content IDs can contain reserved characters). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: record the PR #124 review and hardening pass Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
1070 lines
35 KiB
Go
1070 lines
35 KiB
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"mime"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
apimw "github.com/Silo-Server/silo-server/internal/api/middleware"
|
|
"github.com/Silo-Server/silo-server/internal/catalog"
|
|
"github.com/Silo-Server/silo-server/internal/models"
|
|
)
|
|
|
|
// EbookReaderProgress is the persisted reader position for one profile and ebook.
|
|
type EbookReaderProgress struct {
|
|
UserID int `json:"-"`
|
|
ProfileID string `json:"-"`
|
|
ContentID string `json:"content_id"`
|
|
FileID int `json:"file_id"`
|
|
Location string `json:"location"`
|
|
Progress float64 `json:"progress"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
}
|
|
|
|
type EbookReaderProgressStore interface {
|
|
Get(ctx context.Context, userID int, profileID string, contentID string) (*EbookReaderProgress, error)
|
|
Upsert(ctx context.Context, progress EbookReaderProgress) error
|
|
}
|
|
|
|
// EbookReaderConfig is persisted reader configuration for one profile and ebook.
|
|
type EbookReaderConfig struct {
|
|
UserID int `json:"-"`
|
|
ProfileID string `json:"-"`
|
|
ContentID string `json:"content_id"`
|
|
Config json.RawMessage `json:"config"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
}
|
|
|
|
type EbookReaderConfigStore interface {
|
|
Get(ctx context.Context, userID int, profileID string, contentID string) (*EbookReaderConfig, error)
|
|
Upsert(ctx context.Context, config EbookReaderConfig) error
|
|
}
|
|
|
|
// EbookReaderAnnotation is a persisted reader annotation or bookmark.
|
|
type EbookReaderAnnotation struct {
|
|
ID string `json:"id"`
|
|
UserID int `json:"-"`
|
|
ProfileID string `json:"-"`
|
|
ContentID string `json:"content_id"`
|
|
Kind string `json:"kind"`
|
|
CFIRange string `json:"cfi_range,omitempty"`
|
|
Location string `json:"location,omitempty"`
|
|
SelectedText string `json:"selected_text"`
|
|
Note string `json:"note"`
|
|
Style string `json:"style"`
|
|
Color string `json:"color"`
|
|
Metadata json.RawMessage `json:"metadata"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
}
|
|
|
|
type EbookReaderAnnotationStore interface {
|
|
List(ctx context.Context, userID int, profileID string, contentID string) ([]EbookReaderAnnotation, error)
|
|
Create(ctx context.Context, annotation EbookReaderAnnotation) error
|
|
// Update atomically rewrites the scoped annotation: the stored row is
|
|
// read under a write lock, merge is invoked with the current value, and
|
|
// the merged result is written back in the same transaction so concurrent
|
|
// PATCHes cannot lose updates. It returns (nil, nil) when no annotation
|
|
// matches the scope and propagates merge errors unchanged.
|
|
Update(
|
|
ctx context.Context,
|
|
userID int,
|
|
profileID string,
|
|
contentID string,
|
|
annotationID string,
|
|
merge func(existing EbookReaderAnnotation) (EbookReaderAnnotation, error),
|
|
) (*EbookReaderAnnotation, error)
|
|
Delete(ctx context.Context, userID int, profileID string, contentID string, annotationID string) error
|
|
}
|
|
|
|
// EbookReaderHandler serves ebook files for the in-app reader.
|
|
type EbookReaderHandler struct {
|
|
FileAuthorizer *MediaFileAuthorizer
|
|
ProgressStore EbookReaderProgressStore
|
|
ConfigStore EbookReaderConfigStore
|
|
AnnotationStore EbookReaderAnnotationStore
|
|
}
|
|
|
|
func NewEbookReaderHandler(authorizer *MediaFileAuthorizer) *EbookReaderHandler {
|
|
return &EbookReaderHandler{FileAuthorizer: authorizer}
|
|
}
|
|
|
|
// HandleReadFile serves an ebook file inline with byte-range support.
|
|
func (h *EbookReaderHandler) HandleReadFile(w http.ResponseWriter, r *http.Request) {
|
|
if apimw.GetUserID(r.Context()) == 0 {
|
|
writeError(w, http.StatusUnauthorized, "unauthorized", "Authentication required")
|
|
return
|
|
}
|
|
if h == nil || h.FileAuthorizer == nil {
|
|
writeError(w, http.StatusServiceUnavailable, "unavailable", "Ebook reader is not configured")
|
|
return
|
|
}
|
|
|
|
contentID := strings.TrimSpace(chi.URLParam(r, "content_id"))
|
|
fileID, err := strconv.Atoi(chi.URLParam(r, "file_id"))
|
|
if contentID == "" || err != nil || fileID <= 0 {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "content_id and file_id are required")
|
|
return
|
|
}
|
|
|
|
file, err := h.FileAuthorizer.Authorize(r, fileID)
|
|
if err != nil {
|
|
h.writeReadError(w, err)
|
|
return
|
|
}
|
|
if file == nil || file.ContentID != contentID || !isEbookFile(file) {
|
|
writeError(w, http.StatusNotFound, "not_found", "Ebook file not found")
|
|
return
|
|
}
|
|
|
|
if err := serveEbookInline(w, r, file); err != nil {
|
|
if errors.Is(err, catalog.ErrItemNotFound) {
|
|
writeError(w, http.StatusNotFound, "not_found", "Ebook file not found")
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to serve ebook file")
|
|
}
|
|
}
|
|
|
|
// Request body caps for the ebook reader write endpoints. Progress payloads
|
|
// are tiny; reader config and annotations can carry user text and metadata
|
|
// but should never approach these limits.
|
|
const (
|
|
ebookReaderProgressMaxBodySize = 16 << 10 // 16 KiB
|
|
ebookReaderConfigMaxBodySize = 256 << 10 // 256 KiB
|
|
ebookReaderAnnotationMaxBodySize = 256 << 10 // 256 KiB
|
|
)
|
|
|
|
// decodeEbookReaderBody decodes a JSON request body with a hard size cap.
|
|
// It writes the error response and returns false when decoding fails.
|
|
func decodeEbookReaderBody(w http.ResponseWriter, r *http.Request, maxBodySize int64, dst any) bool {
|
|
r.Body = http.MaxBytesReader(w, r.Body, maxBodySize)
|
|
if err := json.NewDecoder(r.Body).Decode(dst); err != nil {
|
|
var maxBytesErr *http.MaxBytesError
|
|
if errors.As(err, &maxBytesErr) {
|
|
writeError(w, http.StatusRequestEntityTooLarge, "too_large", "Request body is too large")
|
|
return false
|
|
}
|
|
writeError(w, http.StatusBadRequest, "bad_request", "Invalid request body")
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
type ebookReaderProgressRequest struct {
|
|
FileID int `json:"file_id"`
|
|
Location string `json:"location"`
|
|
Progress float64 `json:"progress"`
|
|
}
|
|
|
|
type ebookReaderConfigRequest struct {
|
|
Config json.RawMessage `json:"config"`
|
|
}
|
|
|
|
type ebookReaderAnnotationRequest struct {
|
|
Kind string `json:"kind"`
|
|
CFIRange string `json:"cfi_range"`
|
|
Location string `json:"location"`
|
|
SelectedText string `json:"selected_text"`
|
|
Note string `json:"note"`
|
|
Style string `json:"style"`
|
|
Color string `json:"color"`
|
|
Metadata json.RawMessage `json:"metadata"`
|
|
}
|
|
|
|
// ebookReaderAnnotationPatchRequest distinguishes absent fields (nil: keep the
|
|
// stored value) from present fields (set, including empty values to clear).
|
|
type ebookReaderAnnotationPatchRequest struct {
|
|
Kind *string `json:"kind"`
|
|
CFIRange *string `json:"cfi_range"`
|
|
Location *string `json:"location"`
|
|
SelectedText *string `json:"selected_text"`
|
|
Note *string `json:"note"`
|
|
Style *string `json:"style"`
|
|
Color *string `json:"color"`
|
|
Metadata json.RawMessage `json:"metadata"`
|
|
}
|
|
|
|
func (h *EbookReaderHandler) HandleGetProgress(w http.ResponseWriter, r *http.Request) {
|
|
userID := apimw.GetUserID(r.Context())
|
|
profileID := apimw.GetProfileID(r.Context())
|
|
if userID == 0 {
|
|
writeError(w, http.StatusUnauthorized, "unauthorized", "Authentication required")
|
|
return
|
|
}
|
|
if h == nil || h.ProgressStore == nil || h.FileAuthorizer == nil || h.FileAuthorizer.ItemAccess == nil {
|
|
writeError(w, http.StatusServiceUnavailable, "unavailable", "Ebook reader progress is not configured")
|
|
return
|
|
}
|
|
|
|
contentID := strings.TrimSpace(chi.URLParam(r, "content_id"))
|
|
if contentID == "" {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "content_id is required")
|
|
return
|
|
}
|
|
if err := h.FileAuthorizer.ItemAccess.EnsureAccessible(r.Context(), contentID, requestAccessFilter(r)); err != nil {
|
|
h.writeReadError(w, err)
|
|
return
|
|
}
|
|
|
|
progress, err := h.ProgressStore.Get(r.Context(), userID, profileID, contentID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to load ebook progress")
|
|
return
|
|
}
|
|
if progress == nil {
|
|
writeJSON(w, http.StatusOK, map[string]any{})
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, progress)
|
|
}
|
|
|
|
func (h *EbookReaderHandler) HandleSaveProgress(w http.ResponseWriter, r *http.Request) {
|
|
userID := apimw.GetUserID(r.Context())
|
|
profileID := apimw.GetProfileID(r.Context())
|
|
if userID == 0 {
|
|
writeError(w, http.StatusUnauthorized, "unauthorized", "Authentication required")
|
|
return
|
|
}
|
|
if h == nil || h.ProgressStore == nil || h.FileAuthorizer == nil {
|
|
writeError(w, http.StatusServiceUnavailable, "unavailable", "Ebook reader progress is not configured")
|
|
return
|
|
}
|
|
|
|
contentID := strings.TrimSpace(chi.URLParam(r, "content_id"))
|
|
if contentID == "" {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "content_id is required")
|
|
return
|
|
}
|
|
|
|
var req ebookReaderProgressRequest
|
|
if !decodeEbookReaderBody(w, r, ebookReaderProgressMaxBodySize, &req) {
|
|
return
|
|
}
|
|
req.Location = strings.TrimSpace(req.Location)
|
|
if req.FileID <= 0 || req.Location == "" || req.Progress < 0 || req.Progress > 1 {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "file_id, location, and progress are required")
|
|
return
|
|
}
|
|
|
|
file, err := h.FileAuthorizer.Authorize(r, req.FileID)
|
|
if err != nil {
|
|
h.writeReadError(w, err)
|
|
return
|
|
}
|
|
if file == nil || file.ContentID != contentID || !isEbookFile(file) {
|
|
writeError(w, http.StatusNotFound, "not_found", "Ebook file not found")
|
|
return
|
|
}
|
|
|
|
progress := EbookReaderProgress{
|
|
UserID: userID,
|
|
ProfileID: profileID,
|
|
ContentID: contentID,
|
|
FileID: req.FileID,
|
|
Location: req.Location,
|
|
Progress: req.Progress,
|
|
UpdatedAt: time.Now().UTC(),
|
|
}
|
|
if err := h.ProgressStore.Upsert(r.Context(), progress); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to save ebook progress")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, progress)
|
|
}
|
|
|
|
func (h *EbookReaderHandler) HandleGetConfig(w http.ResponseWriter, r *http.Request) {
|
|
userID := apimw.GetUserID(r.Context())
|
|
profileID := apimw.GetProfileID(r.Context())
|
|
if userID == 0 {
|
|
writeError(w, http.StatusUnauthorized, "unauthorized", "Authentication required")
|
|
return
|
|
}
|
|
if h == nil || h.ConfigStore == nil || h.FileAuthorizer == nil || h.FileAuthorizer.ItemAccess == nil {
|
|
writeError(w, http.StatusServiceUnavailable, "unavailable", "Ebook reader config is not configured")
|
|
return
|
|
}
|
|
|
|
contentID := strings.TrimSpace(chi.URLParam(r, "content_id"))
|
|
if contentID == "" {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "content_id is required")
|
|
return
|
|
}
|
|
if err := h.FileAuthorizer.ItemAccess.EnsureAccessible(r.Context(), contentID, requestAccessFilter(r)); err != nil {
|
|
h.writeReadError(w, err)
|
|
return
|
|
}
|
|
|
|
config, err := h.ConfigStore.Get(r.Context(), userID, profileID, contentID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to load ebook reader config")
|
|
return
|
|
}
|
|
if config == nil {
|
|
writeJSON(w, http.StatusOK, map[string]any{"config": map[string]any{}})
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, config)
|
|
}
|
|
|
|
func (h *EbookReaderHandler) HandleSaveConfig(w http.ResponseWriter, r *http.Request) {
|
|
userID := apimw.GetUserID(r.Context())
|
|
profileID := apimw.GetProfileID(r.Context())
|
|
if userID == 0 {
|
|
writeError(w, http.StatusUnauthorized, "unauthorized", "Authentication required")
|
|
return
|
|
}
|
|
if h == nil || h.ConfigStore == nil || h.FileAuthorizer == nil || h.FileAuthorizer.ItemAccess == nil {
|
|
writeError(w, http.StatusServiceUnavailable, "unavailable", "Ebook reader config is not configured")
|
|
return
|
|
}
|
|
|
|
contentID := strings.TrimSpace(chi.URLParam(r, "content_id"))
|
|
if contentID == "" {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "content_id is required")
|
|
return
|
|
}
|
|
|
|
var req ebookReaderConfigRequest
|
|
if !decodeEbookReaderBody(w, r, ebookReaderConfigMaxBodySize, &req) {
|
|
return
|
|
}
|
|
if !jsonObject(req.Config) {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "config must be a JSON object")
|
|
return
|
|
}
|
|
if err := h.FileAuthorizer.ItemAccess.EnsureAccessible(r.Context(), contentID, requestAccessFilter(r)); err != nil {
|
|
h.writeReadError(w, err)
|
|
return
|
|
}
|
|
|
|
config := EbookReaderConfig{
|
|
UserID: userID,
|
|
ProfileID: profileID,
|
|
ContentID: contentID,
|
|
Config: req.Config,
|
|
UpdatedAt: time.Now().UTC(),
|
|
}
|
|
if err := h.ConfigStore.Upsert(r.Context(), config); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to save ebook reader config")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, config)
|
|
}
|
|
|
|
func jsonObject(raw json.RawMessage) bool {
|
|
if len(raw) == 0 {
|
|
return false
|
|
}
|
|
var value map[string]any
|
|
return json.Unmarshal(raw, &value) == nil && value != nil
|
|
}
|
|
|
|
func (h *EbookReaderHandler) HandleListAnnotations(w http.ResponseWriter, r *http.Request) {
|
|
userID, profileID, contentID, ok := h.annotationRequestScope(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
items, err := h.AnnotationStore.List(r.Context(), userID, profileID, contentID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to load ebook annotations")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
|
}
|
|
|
|
func (h *EbookReaderHandler) HandleCreateAnnotation(w http.ResponseWriter, r *http.Request) {
|
|
userID, profileID, contentID, ok := h.annotationRequestScope(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
var req ebookReaderAnnotationRequest
|
|
if !decodeEbookReaderBody(w, r, ebookReaderAnnotationMaxBodySize, &req) {
|
|
return
|
|
}
|
|
annotation, err := buildEbookReaderAnnotation(req)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "bad_request", err.Error())
|
|
return
|
|
}
|
|
now := time.Now().UTC()
|
|
annotation.ID = uuid.NewString()
|
|
annotation.UserID = userID
|
|
annotation.ProfileID = profileID
|
|
annotation.ContentID = contentID
|
|
annotation.CreatedAt = now
|
|
annotation.UpdatedAt = now
|
|
if err := h.AnnotationStore.Create(r.Context(), annotation); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to create ebook annotation")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusCreated, annotation)
|
|
}
|
|
|
|
func (h *EbookReaderHandler) HandleUpdateAnnotation(w http.ResponseWriter, r *http.Request) {
|
|
userID, profileID, contentID, ok := h.annotationRequestScope(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
annotationID := strings.TrimSpace(chi.URLParam(r, "annotation_id"))
|
|
if annotationID == "" {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "annotation_id is required")
|
|
return
|
|
}
|
|
var req ebookReaderAnnotationPatchRequest
|
|
if !decodeEbookReaderBody(w, r, ebookReaderAnnotationMaxBodySize, &req) {
|
|
return
|
|
}
|
|
// The merge runs inside the store transaction between the locked read and
|
|
// the write, so concurrent PATCHes serialize instead of losing updates.
|
|
var validationErr error
|
|
updated, err := h.AnnotationStore.Update(
|
|
r.Context(), userID, profileID, contentID, annotationID,
|
|
func(existing EbookReaderAnnotation) (EbookReaderAnnotation, error) {
|
|
merged, mergeErr := mergeEbookReaderAnnotationPatch(existing, req)
|
|
if mergeErr != nil {
|
|
validationErr = mergeErr
|
|
return EbookReaderAnnotation{}, mergeErr
|
|
}
|
|
merged.UpdatedAt = time.Now().UTC()
|
|
return merged, nil
|
|
},
|
|
)
|
|
if validationErr != nil {
|
|
writeError(w, http.StatusBadRequest, "bad_request", validationErr.Error())
|
|
return
|
|
}
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to update ebook annotation")
|
|
return
|
|
}
|
|
if updated == nil {
|
|
writeError(w, http.StatusNotFound, "not_found", "Ebook annotation not found")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, updated)
|
|
}
|
|
|
|
func (h *EbookReaderHandler) HandleDeleteAnnotation(w http.ResponseWriter, r *http.Request) {
|
|
userID, profileID, contentID, ok := h.annotationRequestScope(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
annotationID := strings.TrimSpace(chi.URLParam(r, "annotation_id"))
|
|
if annotationID == "" {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "annotation_id is required")
|
|
return
|
|
}
|
|
if err := h.AnnotationStore.Delete(r.Context(), userID, profileID, contentID, annotationID); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to delete ebook annotation")
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func (h *EbookReaderHandler) annotationRequestScope(w http.ResponseWriter, r *http.Request) (int, string, string, bool) {
|
|
userID := apimw.GetUserID(r.Context())
|
|
profileID := apimw.GetProfileID(r.Context())
|
|
if userID == 0 {
|
|
writeError(w, http.StatusUnauthorized, "unauthorized", "Authentication required")
|
|
return 0, "", "", false
|
|
}
|
|
if h == nil || h.AnnotationStore == nil || h.FileAuthorizer == nil || h.FileAuthorizer.ItemAccess == nil {
|
|
writeError(w, http.StatusServiceUnavailable, "unavailable", "Ebook annotations are not configured")
|
|
return 0, "", "", false
|
|
}
|
|
contentID := strings.TrimSpace(chi.URLParam(r, "content_id"))
|
|
if contentID == "" {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "content_id is required")
|
|
return 0, "", "", false
|
|
}
|
|
if err := h.FileAuthorizer.ItemAccess.EnsureAccessible(r.Context(), contentID, requestAccessFilter(r)); err != nil {
|
|
h.writeReadError(w, err)
|
|
return 0, "", "", false
|
|
}
|
|
return userID, profileID, contentID, true
|
|
}
|
|
|
|
// validateEbookReaderAnnotation enforces the annotation invariants shared by
|
|
// create and patch: a known kind, a location for bookmarks, a CFI range for
|
|
// highlights/notes, and object-shaped metadata.
|
|
func validateEbookReaderAnnotation(annotation EbookReaderAnnotation) error {
|
|
if annotation.Kind != "highlight" && annotation.Kind != "note" && annotation.Kind != "bookmark" {
|
|
return fmt.Errorf("kind must be highlight, note, or bookmark")
|
|
}
|
|
if annotation.Kind == "bookmark" {
|
|
if annotation.Location == "" {
|
|
return fmt.Errorf("location is required for bookmarks")
|
|
}
|
|
} else if annotation.CFIRange == "" {
|
|
return fmt.Errorf("cfi_range is required for annotations")
|
|
}
|
|
if !jsonObject(annotation.Metadata) {
|
|
return fmt.Errorf("metadata must be a JSON object")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func buildEbookReaderAnnotation(req ebookReaderAnnotationRequest) (EbookReaderAnnotation, error) {
|
|
kind := strings.ToLower(strings.TrimSpace(req.Kind))
|
|
if kind == "" {
|
|
kind = "highlight"
|
|
}
|
|
metadata := req.Metadata
|
|
if len(metadata) == 0 {
|
|
metadata = json.RawMessage(`{}`)
|
|
}
|
|
style := strings.TrimSpace(req.Style)
|
|
if style == "" {
|
|
style = "highlight"
|
|
}
|
|
color := strings.TrimSpace(req.Color)
|
|
if color == "" {
|
|
color = "#facc15"
|
|
}
|
|
annotation := EbookReaderAnnotation{
|
|
Kind: kind,
|
|
CFIRange: strings.TrimSpace(req.CFIRange),
|
|
Location: strings.TrimSpace(req.Location),
|
|
SelectedText: strings.TrimSpace(req.SelectedText),
|
|
Note: strings.TrimSpace(req.Note),
|
|
Style: style,
|
|
Color: color,
|
|
Metadata: metadata,
|
|
}
|
|
if err := validateEbookReaderAnnotation(annotation); err != nil {
|
|
return EbookReaderAnnotation{}, err
|
|
}
|
|
return annotation, nil
|
|
}
|
|
|
|
// mergeEbookReaderAnnotationPatch applies a PATCH request onto the stored
|
|
// annotation. Absent fields keep their stored values; present fields are set
|
|
// to the provided value (empty values clear). The merged result is validated
|
|
// against the same invariants as annotation creation.
|
|
func mergeEbookReaderAnnotationPatch(
|
|
existing EbookReaderAnnotation,
|
|
req ebookReaderAnnotationPatchRequest,
|
|
) (EbookReaderAnnotation, error) {
|
|
merged := existing
|
|
if req.Kind != nil {
|
|
merged.Kind = strings.ToLower(strings.TrimSpace(*req.Kind))
|
|
}
|
|
if req.CFIRange != nil {
|
|
merged.CFIRange = strings.TrimSpace(*req.CFIRange)
|
|
}
|
|
if req.Location != nil {
|
|
merged.Location = strings.TrimSpace(*req.Location)
|
|
}
|
|
if req.SelectedText != nil {
|
|
merged.SelectedText = strings.TrimSpace(*req.SelectedText)
|
|
}
|
|
if req.Note != nil {
|
|
merged.Note = strings.TrimSpace(*req.Note)
|
|
}
|
|
if req.Style != nil {
|
|
merged.Style = strings.TrimSpace(*req.Style)
|
|
}
|
|
if req.Color != nil {
|
|
merged.Color = strings.TrimSpace(*req.Color)
|
|
}
|
|
if req.Metadata != nil {
|
|
merged.Metadata = req.Metadata
|
|
}
|
|
if err := validateEbookReaderAnnotation(merged); err != nil {
|
|
return EbookReaderAnnotation{}, err
|
|
}
|
|
return merged, nil
|
|
}
|
|
|
|
func (h *EbookReaderHandler) writeReadError(w http.ResponseWriter, err error) {
|
|
switch {
|
|
case errors.Is(err, catalog.ErrItemNotFound), errors.Is(err, catalog.ErrEpisodeNotFound):
|
|
writeError(w, http.StatusNotFound, "not_found", "Ebook file not found")
|
|
default:
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to authorize ebook file")
|
|
}
|
|
}
|
|
|
|
func serveEbookInline(w http.ResponseWriter, r *http.Request, file *models.MediaFile) error {
|
|
f, err := os.Open(file.FilePath)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return catalog.ErrItemNotFound
|
|
}
|
|
return fmt.Errorf("opening ebook file: %w", err)
|
|
}
|
|
defer f.Close()
|
|
|
|
stat, err := f.Stat()
|
|
if err != nil {
|
|
return fmt.Errorf("stat ebook file: %w", err)
|
|
}
|
|
|
|
w.Header().Set("Content-Type", ebookMimeType(file.FilePath, file.Container))
|
|
w.Header().Set("Content-Disposition", inlineContentDisposition(filepath.Base(file.FilePath)))
|
|
// Ebook files are served inline on the API origin (and reachable via the
|
|
// ?token= query fallback), so browsers must never content-sniff them.
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
http.ServeContent(w, r, stat.Name(), stat.ModTime(), f)
|
|
return nil
|
|
}
|
|
|
|
// inlineContentDisposition builds an inline Content-Disposition header value.
|
|
// mime.FormatMediaType handles quoting, backslash escaping, and RFC 5987
|
|
// (filename*) encoding for non-ASCII names.
|
|
func inlineContentDisposition(name string) string {
|
|
name = strings.TrimSpace(name)
|
|
if name == "" || name == "." || name == string(filepath.Separator) {
|
|
name = "ebook"
|
|
}
|
|
if disposition := mime.FormatMediaType("inline", map[string]string{"filename": name}); disposition != "" {
|
|
return disposition
|
|
}
|
|
return `inline; filename="ebook"`
|
|
}
|
|
|
|
func isEbookFile(file *models.MediaFile) bool {
|
|
if file == nil {
|
|
return false
|
|
}
|
|
if !strings.EqualFold(file.BaseType, "ebook") {
|
|
return false
|
|
}
|
|
return ebookReaderFormat(file.FilePath, file.Container) != ""
|
|
}
|
|
|
|
// ebookReaderFormat resolves the whitelisted reader format for a file from
|
|
// its filename extension, falling back to the catalog container when the
|
|
// extension is not a known ebook format. It returns "" when neither identity
|
|
// is whitelisted. isEbookFile admission and ebookMimeType both key off this
|
|
// resolution, so an admitted file always maps to a concrete ebook MIME type
|
|
// and never falls through to application/octet-stream.
|
|
func ebookReaderFormat(path, container string) string {
|
|
if strings.HasSuffix(strings.ToLower(path), ".fb2.zip") {
|
|
return "fbz"
|
|
}
|
|
if format := normalizeEbookReaderFormat(filepath.Ext(path)); format != "" {
|
|
return format
|
|
}
|
|
return normalizeEbookReaderFormat(container)
|
|
}
|
|
|
|
// normalizeEbookReaderFormat maps an extension or container value onto the
|
|
// ebook reader format whitelist, returning "" for unknown values.
|
|
func normalizeEbookReaderFormat(value string) string {
|
|
format := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(value)), ".")
|
|
switch format {
|
|
case "epub", "pdf", "mobi", "azw", "azw3", "cbz", "cbr", "fb2", "fbz":
|
|
return format
|
|
default:
|
|
return ""
|
|
}
|
|
}
|
|
|
|
func ebookMimeType(path, container string) string {
|
|
switch ebookReaderFormat(path, container) {
|
|
case "epub":
|
|
return "application/epub+zip"
|
|
case "pdf":
|
|
return "application/pdf"
|
|
case "mobi":
|
|
return "application/x-mobipocket-ebook"
|
|
case "azw":
|
|
return "application/vnd.amazon.ebook"
|
|
case "azw3":
|
|
return "application/vnd.amazon.mobi8-ebook"
|
|
case "cbz":
|
|
return "application/vnd.comicbook+zip"
|
|
case "cbr":
|
|
return "application/vnd.comicbook-rar"
|
|
case "fb2":
|
|
return "application/x-fictionbook+xml"
|
|
case "fbz":
|
|
return "application/x-zip-compressed-fb2"
|
|
default:
|
|
return "application/octet-stream"
|
|
}
|
|
}
|
|
|
|
type PGEbookReaderProgressStore struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
func NewPGEbookReaderProgressStore(pool *pgxpool.Pool) *PGEbookReaderProgressStore {
|
|
return &PGEbookReaderProgressStore{pool: pool}
|
|
}
|
|
|
|
type PGEbookReaderConfigStore struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
func NewPGEbookReaderConfigStore(pool *pgxpool.Pool) *PGEbookReaderConfigStore {
|
|
return &PGEbookReaderConfigStore{pool: pool}
|
|
}
|
|
|
|
func (s *PGEbookReaderConfigStore) Get(ctx context.Context, userID int, profileID string, contentID string) (*EbookReaderConfig, error) {
|
|
if s == nil || s.pool == nil {
|
|
return nil, fmt.Errorf("ebook reader config store is not configured")
|
|
}
|
|
var config EbookReaderConfig
|
|
err := s.pool.QueryRow(ctx, `
|
|
SELECT user_id, profile_id, content_id, config, updated_at
|
|
FROM ebook_reader_config
|
|
WHERE user_id = $1 AND profile_id = $2 AND content_id = $3`,
|
|
userID, profileID, contentID,
|
|
).Scan(
|
|
&config.UserID,
|
|
&config.ProfileID,
|
|
&config.ContentID,
|
|
&config.Config,
|
|
&config.UpdatedAt,
|
|
)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("get ebook reader config: %w", err)
|
|
}
|
|
return &config, nil
|
|
}
|
|
|
|
func (s *PGEbookReaderConfigStore) Upsert(ctx context.Context, config EbookReaderConfig) error {
|
|
if s == nil || s.pool == nil {
|
|
return fmt.Errorf("ebook reader config store is not configured")
|
|
}
|
|
if _, err := s.pool.Exec(ctx, `
|
|
INSERT INTO ebook_reader_config
|
|
(user_id, profile_id, content_id, config, updated_at)
|
|
VALUES ($1, $2, $3, $4::jsonb, $5)
|
|
ON CONFLICT (user_id, profile_id, content_id) DO UPDATE SET
|
|
config = EXCLUDED.config,
|
|
updated_at = EXCLUDED.updated_at`,
|
|
config.UserID,
|
|
config.ProfileID,
|
|
config.ContentID,
|
|
config.Config,
|
|
config.UpdatedAt,
|
|
); err != nil {
|
|
return fmt.Errorf("upsert ebook reader config: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type PGEbookReaderAnnotationStore struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
func NewPGEbookReaderAnnotationStore(pool *pgxpool.Pool) *PGEbookReaderAnnotationStore {
|
|
return &PGEbookReaderAnnotationStore{pool: pool}
|
|
}
|
|
|
|
func (s *PGEbookReaderAnnotationStore) List(ctx context.Context, userID int, profileID string, contentID string) ([]EbookReaderAnnotation, error) {
|
|
if s == nil || s.pool == nil {
|
|
return nil, fmt.Errorf("ebook reader annotation store is not configured")
|
|
}
|
|
rows, err := s.pool.Query(ctx, `
|
|
SELECT id, user_id, profile_id, content_id, kind,
|
|
COALESCE(cfi_range, ''), COALESCE(location, ''),
|
|
selected_text, note, style, color, metadata, created_at, updated_at
|
|
FROM ebook_reader_annotations
|
|
WHERE user_id = $1 AND profile_id = $2 AND content_id = $3
|
|
ORDER BY updated_at DESC`,
|
|
userID, profileID, contentID,
|
|
)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list ebook reader annotations: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
var items []EbookReaderAnnotation
|
|
for rows.Next() {
|
|
annotation, err := scanEbookReaderAnnotation(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, annotation)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("iterate ebook reader annotations: %w", err)
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
func (s *PGEbookReaderAnnotationStore) Create(ctx context.Context, annotation EbookReaderAnnotation) error {
|
|
if s == nil || s.pool == nil {
|
|
return fmt.Errorf("ebook reader annotation store is not configured")
|
|
}
|
|
_, err := s.pool.Exec(ctx, `
|
|
INSERT INTO ebook_reader_annotations
|
|
(id, user_id, profile_id, content_id, kind, cfi_range, location,
|
|
selected_text, note, style, color, metadata, created_at, updated_at)
|
|
VALUES ($1, $2, $3, $4, $5, NULLIF($6, ''), NULLIF($7, ''),
|
|
$8, $9, $10, $11, $12::jsonb, $13, $14)`,
|
|
annotation.ID,
|
|
annotation.UserID,
|
|
annotation.ProfileID,
|
|
annotation.ContentID,
|
|
annotation.Kind,
|
|
annotation.CFIRange,
|
|
annotation.Location,
|
|
annotation.SelectedText,
|
|
annotation.Note,
|
|
annotation.Style,
|
|
annotation.Color,
|
|
annotation.Metadata,
|
|
annotation.CreatedAt,
|
|
annotation.UpdatedAt,
|
|
)
|
|
if err != nil {
|
|
return fmt.Errorf("create ebook reader annotation: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *PGEbookReaderAnnotationStore) Update(
|
|
ctx context.Context,
|
|
userID int,
|
|
profileID string,
|
|
contentID string,
|
|
annotationID string,
|
|
merge func(existing EbookReaderAnnotation) (EbookReaderAnnotation, error),
|
|
) (*EbookReaderAnnotation, error) {
|
|
if s == nil || s.pool == nil {
|
|
return nil, fmt.Errorf("ebook reader annotation store is not configured")
|
|
}
|
|
tx, err := s.pool.Begin(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("begin ebook reader annotation update: %w", err)
|
|
}
|
|
defer func() { _ = tx.Rollback(ctx) }()
|
|
|
|
existing, err := scanEbookReaderAnnotation(tx.QueryRow(ctx, `
|
|
SELECT id, user_id, profile_id, content_id, kind,
|
|
COALESCE(cfi_range, ''), COALESCE(location, ''),
|
|
selected_text, note, style, color, metadata, created_at, updated_at
|
|
FROM ebook_reader_annotations
|
|
WHERE id = $1 AND user_id = $2 AND profile_id = $3 AND content_id = $4
|
|
FOR UPDATE`,
|
|
annotationID, userID, profileID, contentID,
|
|
))
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("get ebook reader annotation for update: %w", err)
|
|
}
|
|
|
|
merged, err := merge(existing)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
updated, err := scanEbookReaderAnnotation(tx.QueryRow(ctx, `
|
|
UPDATE ebook_reader_annotations
|
|
SET kind = $5,
|
|
cfi_range = NULLIF($6, ''),
|
|
location = NULLIF($7, ''),
|
|
selected_text = $8,
|
|
note = $9,
|
|
style = $10,
|
|
color = $11,
|
|
metadata = $12::jsonb,
|
|
updated_at = $13
|
|
WHERE id = $1 AND user_id = $2 AND profile_id = $3 AND content_id = $4
|
|
RETURNING id, user_id, profile_id, content_id, kind,
|
|
COALESCE(cfi_range, ''), COALESCE(location, ''),
|
|
selected_text, note, style, color, metadata, created_at, updated_at`,
|
|
annotationID,
|
|
userID,
|
|
profileID,
|
|
contentID,
|
|
merged.Kind,
|
|
merged.CFIRange,
|
|
merged.Location,
|
|
merged.SelectedText,
|
|
merged.Note,
|
|
merged.Style,
|
|
merged.Color,
|
|
merged.Metadata,
|
|
merged.UpdatedAt,
|
|
))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("update ebook reader annotation: %w", err)
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return nil, fmt.Errorf("commit ebook reader annotation update: %w", err)
|
|
}
|
|
return &updated, nil
|
|
}
|
|
|
|
func (s *PGEbookReaderAnnotationStore) Delete(ctx context.Context, userID int, profileID string, contentID string, annotationID string) error {
|
|
if s == nil || s.pool == nil {
|
|
return fmt.Errorf("ebook reader annotation store is not configured")
|
|
}
|
|
if _, err := s.pool.Exec(ctx, `
|
|
DELETE FROM ebook_reader_annotations
|
|
WHERE id = $1 AND user_id = $2 AND profile_id = $3 AND content_id = $4`,
|
|
annotationID, userID, profileID, contentID,
|
|
); err != nil {
|
|
return fmt.Errorf("delete ebook reader annotation: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func scanEbookReaderAnnotation(scanner interface{ Scan(dest ...any) error }) (EbookReaderAnnotation, error) {
|
|
var annotation EbookReaderAnnotation
|
|
if err := scanner.Scan(
|
|
&annotation.ID,
|
|
&annotation.UserID,
|
|
&annotation.ProfileID,
|
|
&annotation.ContentID,
|
|
&annotation.Kind,
|
|
&annotation.CFIRange,
|
|
&annotation.Location,
|
|
&annotation.SelectedText,
|
|
&annotation.Note,
|
|
&annotation.Style,
|
|
&annotation.Color,
|
|
&annotation.Metadata,
|
|
&annotation.CreatedAt,
|
|
&annotation.UpdatedAt,
|
|
); err != nil {
|
|
return EbookReaderAnnotation{}, fmt.Errorf("scan ebook reader annotation: %w", err)
|
|
}
|
|
return annotation, nil
|
|
}
|
|
|
|
func (s *PGEbookReaderProgressStore) Get(ctx context.Context, userID int, profileID string, contentID string) (*EbookReaderProgress, error) {
|
|
if s == nil || s.pool == nil {
|
|
return nil, fmt.Errorf("ebook reader progress store is not configured")
|
|
}
|
|
var progress EbookReaderProgress
|
|
err := s.pool.QueryRow(ctx, `
|
|
SELECT user_id, profile_id, content_id, file_id, location, progress, updated_at
|
|
FROM ebook_reader_progress
|
|
WHERE user_id = $1 AND profile_id = $2 AND content_id = $3`,
|
|
userID, profileID, contentID,
|
|
).Scan(
|
|
&progress.UserID,
|
|
&progress.ProfileID,
|
|
&progress.ContentID,
|
|
&progress.FileID,
|
|
&progress.Location,
|
|
&progress.Progress,
|
|
&progress.UpdatedAt,
|
|
)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("get ebook reader progress: %w", err)
|
|
}
|
|
return &progress, nil
|
|
}
|
|
|
|
// ListByContentIDs lists reading progress for a set of items, excluding rows
|
|
// hidden from history. The hidden gating mirrors the video path
|
|
// (internal/userstore/pgstore/progress.go): a row is hidden while its
|
|
// updated_at <= hidden_before, and counts again once progress is updated
|
|
// after the hide.
|
|
func (s *PGEbookReaderProgressStore) ListByContentIDs(ctx context.Context, userID int, profileID string, contentIDs []string) (map[string]EbookReaderProgress, error) {
|
|
if s == nil || s.pool == nil {
|
|
return nil, fmt.Errorf("ebook reader progress store is not configured")
|
|
}
|
|
if userID <= 0 || profileID == "" || len(contentIDs) == 0 {
|
|
return nil, nil
|
|
}
|
|
rows, err := s.pool.Query(ctx, `
|
|
SELECT user_id, profile_id, content_id, file_id, location, progress, updated_at
|
|
FROM ebook_reader_progress
|
|
WHERE user_id = $1 AND profile_id = $2 AND content_id = ANY($3::text[])
|
|
AND NOT EXISTS (
|
|
SELECT 1
|
|
FROM user_history_hidden_items hhi
|
|
WHERE hhi.user_id = ebook_reader_progress.user_id
|
|
AND hhi.profile_id = ebook_reader_progress.profile_id
|
|
AND hhi.media_item_id = ebook_reader_progress.content_id
|
|
AND ebook_reader_progress.updated_at <= hhi.hidden_before
|
|
)`,
|
|
userID, profileID, contentIDs,
|
|
)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list ebook reader progress: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
progressByContentID := make(map[string]EbookReaderProgress, len(contentIDs))
|
|
for rows.Next() {
|
|
var progress EbookReaderProgress
|
|
if err := rows.Scan(
|
|
&progress.UserID,
|
|
&progress.ProfileID,
|
|
&progress.ContentID,
|
|
&progress.FileID,
|
|
&progress.Location,
|
|
&progress.Progress,
|
|
&progress.UpdatedAt,
|
|
); err != nil {
|
|
return nil, fmt.Errorf("scan ebook reader progress: %w", err)
|
|
}
|
|
progressByContentID[progress.ContentID] = progress
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("iterate ebook reader progress: %w", err)
|
|
}
|
|
return progressByContentID, nil
|
|
}
|
|
|
|
func (s *PGEbookReaderProgressStore) Delete(ctx context.Context, userID int, profileID string, contentID string) error {
|
|
if s == nil || s.pool == nil {
|
|
return fmt.Errorf("ebook reader progress store is not configured")
|
|
}
|
|
if _, err := s.pool.Exec(ctx, `
|
|
DELETE FROM ebook_reader_progress
|
|
WHERE user_id = $1 AND profile_id = $2 AND content_id = $3`,
|
|
userID, profileID, contentID,
|
|
); err != nil {
|
|
return fmt.Errorf("delete ebook reader progress: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *PGEbookReaderProgressStore) Upsert(ctx context.Context, progress EbookReaderProgress) error {
|
|
if s == nil || s.pool == nil {
|
|
return fmt.Errorf("ebook reader progress store is not configured")
|
|
}
|
|
if _, err := s.pool.Exec(ctx, `
|
|
INSERT INTO ebook_reader_progress
|
|
(user_id, profile_id, content_id, file_id, location, progress, updated_at)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
|
ON CONFLICT (user_id, profile_id, content_id) DO UPDATE SET
|
|
file_id = EXCLUDED.file_id,
|
|
location = EXCLUDED.location,
|
|
progress = EXCLUDED.progress,
|
|
updated_at = EXCLUDED.updated_at`,
|
|
progress.UserID,
|
|
progress.ProfileID,
|
|
progress.ContentID,
|
|
progress.FileID,
|
|
progress.Location,
|
|
progress.Progress,
|
|
progress.UpdatedAt,
|
|
); err != nil {
|
|
return fmt.Errorf("upsert ebook reader progress: %w", err)
|
|
}
|
|
return nil
|
|
}
|