* 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>
902 lines
28 KiB
Go
902 lines
28 KiB
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"mime"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
apimw "github.com/Silo-Server/silo-server/internal/api/middleware"
|
|
"github.com/Silo-Server/silo-server/internal/auth"
|
|
"github.com/Silo-Server/silo-server/internal/catalog"
|
|
"github.com/Silo-Server/silo-server/internal/models"
|
|
)
|
|
|
|
func newEbookReaderAuthRequest(method, path string) *http.Request {
|
|
req := httptest.NewRequest(method, path, nil)
|
|
ctx := apimw.SetClaims(context.Background(), &auth.Claims{
|
|
UserID: 1,
|
|
Role: "user",
|
|
TokenType: auth.TokenTypeAccess,
|
|
})
|
|
ctx = apimw.SetProfileID(ctx, "profile-1")
|
|
return req.WithContext(ctx)
|
|
}
|
|
|
|
func withEbookReaderRouteParams(req *http.Request, contentID, fileID string) *http.Request {
|
|
routeCtx := chi.NewRouteContext()
|
|
routeCtx.URLParams.Add("content_id", contentID)
|
|
routeCtx.URLParams.Add("file_id", fileID)
|
|
return req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, routeCtx))
|
|
}
|
|
|
|
func withEbookReaderContentRouteParam(req *http.Request, contentID string) *http.Request {
|
|
routeCtx := chi.NewRouteContext()
|
|
routeCtx.URLParams.Add("content_id", contentID)
|
|
return req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, routeCtx))
|
|
}
|
|
|
|
func withEbookReaderAnnotationRouteParams(req *http.Request, contentID, annotationID string) *http.Request {
|
|
routeCtx := chi.NewRouteContext()
|
|
routeCtx.URLParams.Add("content_id", contentID)
|
|
routeCtx.URLParams.Add("annotation_id", annotationID)
|
|
return req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, routeCtx))
|
|
}
|
|
|
|
type fakeEbookProgressStore struct {
|
|
progress *EbookReaderProgress
|
|
upserted *EbookReaderProgress
|
|
err error
|
|
}
|
|
|
|
func (s *fakeEbookProgressStore) Get(
|
|
context.Context,
|
|
int,
|
|
string,
|
|
string,
|
|
) (*EbookReaderProgress, error) {
|
|
return s.progress, s.err
|
|
}
|
|
|
|
func (s *fakeEbookProgressStore) Upsert(_ context.Context, progress EbookReaderProgress) error {
|
|
if s.err != nil {
|
|
return s.err
|
|
}
|
|
s.upserted = &progress
|
|
return nil
|
|
}
|
|
|
|
type fakeEbookReaderConfigStore struct {
|
|
config *EbookReaderConfig
|
|
saved *EbookReaderConfig
|
|
getErr error
|
|
saveErr error
|
|
}
|
|
|
|
func (s *fakeEbookReaderConfigStore) Get(
|
|
context.Context,
|
|
int,
|
|
string,
|
|
string,
|
|
) (*EbookReaderConfig, error) {
|
|
return s.config, s.getErr
|
|
}
|
|
|
|
func (s *fakeEbookReaderConfigStore) Upsert(_ context.Context, config EbookReaderConfig) error {
|
|
if s.saveErr != nil {
|
|
return s.saveErr
|
|
}
|
|
s.saved = &config
|
|
return nil
|
|
}
|
|
|
|
type fakeEbookReaderAnnotationStore struct {
|
|
items []EbookReaderAnnotation
|
|
existing *EbookReaderAnnotation
|
|
created *EbookReaderAnnotation
|
|
updated *EbookReaderAnnotation
|
|
mergedFrom *EbookReaderAnnotation
|
|
mergeCalls int
|
|
deleted string
|
|
err error
|
|
}
|
|
|
|
func (s *fakeEbookReaderAnnotationStore) List(context.Context, int, string, string) ([]EbookReaderAnnotation, error) {
|
|
return s.items, s.err
|
|
}
|
|
|
|
func (s *fakeEbookReaderAnnotationStore) Create(_ context.Context, annotation EbookReaderAnnotation) error {
|
|
if s.err != nil {
|
|
return s.err
|
|
}
|
|
s.created = &annotation
|
|
s.items = append(s.items, annotation)
|
|
return nil
|
|
}
|
|
|
|
// Update models the PG store contract: read the stored row, invoke merge with
|
|
// it, and persist the merged result, all as one atomic operation.
|
|
func (s *fakeEbookReaderAnnotationStore) Update(
|
|
_ context.Context,
|
|
_ int,
|
|
_ string,
|
|
_ string,
|
|
annotationID string,
|
|
merge func(existing EbookReaderAnnotation) (EbookReaderAnnotation, error),
|
|
) (*EbookReaderAnnotation, error) {
|
|
if s.err != nil {
|
|
return nil, s.err
|
|
}
|
|
if s.existing == nil || s.existing.ID != annotationID {
|
|
return nil, nil
|
|
}
|
|
existing := *s.existing
|
|
s.mergedFrom = &existing
|
|
s.mergeCalls++
|
|
merged, err := merge(existing)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
s.updated = &merged
|
|
stored := merged
|
|
s.existing = &stored
|
|
return &merged, nil
|
|
}
|
|
|
|
func (s *fakeEbookReaderAnnotationStore) Delete(_ context.Context, userID int, profileID, contentID, annotationID string) error {
|
|
if s.err != nil {
|
|
return s.err
|
|
}
|
|
s.deleted = annotationID
|
|
return nil
|
|
}
|
|
|
|
func TestEbookReaderServesEbookInlineWithRangeSupport(t *testing.T) {
|
|
filePath := writePlaybackTestMediaFile(t, "book.epub")
|
|
if err := os.WriteFile(filePath, []byte("0123456789"), 0o644); err != nil {
|
|
t.Fatalf("write ebook: %v", err)
|
|
}
|
|
|
|
handler := NewEbookReaderHandler(&MediaFileAuthorizer{
|
|
FileResolver: stubMediaFileResolver{
|
|
file: &models.MediaFile{
|
|
ID: 42,
|
|
ContentID: "ebook-1",
|
|
FilePath: filePath,
|
|
Container: "epub",
|
|
BaseType: "ebook",
|
|
},
|
|
},
|
|
ItemAccess: stubItemAccessChecker{},
|
|
})
|
|
|
|
req := newEbookReaderAuthRequest(http.MethodGet, "/ebooks/ebook-1/files/42/read")
|
|
req.Header.Set("Range", "bytes=2-5")
|
|
req = withEbookReaderRouteParams(req, "ebook-1", "42")
|
|
|
|
rr := httptest.NewRecorder()
|
|
handler.HandleReadFile(rr, req)
|
|
|
|
if rr.Code != http.StatusPartialContent {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
if got := rr.Header().Get("Content-Type"); got != "application/epub+zip" {
|
|
t.Fatalf("content-type = %q", got)
|
|
}
|
|
if got := rr.Header().Get("Content-Disposition"); got != "inline; filename=book.epub" {
|
|
t.Fatalf("content-disposition = %q", got)
|
|
}
|
|
if got := rr.Header().Get("X-Content-Type-Options"); got != "nosniff" {
|
|
t.Fatalf("x-content-type-options = %q, want nosniff", got)
|
|
}
|
|
if rr.Body.String() != "2345" {
|
|
t.Fatalf("body = %q", rr.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderServesContainerMimeForMismatchedExtension(t *testing.T) {
|
|
filePath := writePlaybackTestMediaFile(t, "book.txt")
|
|
if err := os.WriteFile(filePath, []byte("<html>not really</html>"), 0o644); err != nil {
|
|
t.Fatalf("write ebook: %v", err)
|
|
}
|
|
|
|
handler := NewEbookReaderHandler(&MediaFileAuthorizer{
|
|
FileResolver: stubMediaFileResolver{
|
|
file: &models.MediaFile{
|
|
ID: 42,
|
|
ContentID: "ebook-1",
|
|
FilePath: filePath,
|
|
Container: "epub",
|
|
BaseType: "ebook",
|
|
},
|
|
},
|
|
ItemAccess: stubItemAccessChecker{},
|
|
})
|
|
|
|
req := newEbookReaderAuthRequest(http.MethodGet, "/ebooks/ebook-1/files/42/read")
|
|
req = withEbookReaderRouteParams(req, "ebook-1", "42")
|
|
|
|
rr := httptest.NewRecorder()
|
|
handler.HandleReadFile(rr, req)
|
|
|
|
if rr.Code != http.StatusOK {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
// The file is admitted via its validated container, so the response must
|
|
// carry that container's MIME type, never application/octet-stream.
|
|
if got := rr.Header().Get("Content-Type"); got != "application/epub+zip" {
|
|
t.Fatalf("content-type = %q, want application/epub+zip", got)
|
|
}
|
|
if got := rr.Header().Get("X-Content-Type-Options"); got != "nosniff" {
|
|
t.Fatalf("x-content-type-options = %q, want nosniff", got)
|
|
}
|
|
}
|
|
|
|
func TestEbookMimeTypeNeverReturnsOctetStreamForAdmittedFiles(t *testing.T) {
|
|
cases := []struct {
|
|
path string
|
|
container string
|
|
wantMime string
|
|
}{
|
|
{"/library/book.txt", "epub", "application/epub+zip"},
|
|
{"/library/book", "pdf", "application/pdf"},
|
|
{"/library/book.epub", "pdf", "application/epub+zip"}, // known extension wins
|
|
}
|
|
for _, tc := range cases {
|
|
file := &models.MediaFile{FilePath: tc.path, Container: tc.container, BaseType: "ebook"}
|
|
if !isEbookFile(file) {
|
|
t.Fatalf("isEbookFile(%q, %q) = false, want admitted", tc.path, tc.container)
|
|
}
|
|
if got := ebookMimeType(tc.path, tc.container); got != tc.wantMime {
|
|
t.Fatalf("ebookMimeType(%q, %q) = %q, want %q", tc.path, tc.container, got, tc.wantMime)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderRejectsNonEbookFile(t *testing.T) {
|
|
handler := NewEbookReaderHandler(&MediaFileAuthorizer{
|
|
FileResolver: stubMediaFileResolver{
|
|
file: &models.MediaFile{
|
|
ID: 42,
|
|
ContentID: "movie-1",
|
|
FilePath: "/tmp/movie.mkv",
|
|
Container: "mkv",
|
|
BaseType: "movie",
|
|
},
|
|
},
|
|
ItemAccess: stubItemAccessChecker{},
|
|
})
|
|
|
|
req := newEbookReaderAuthRequest(http.MethodGet, "/ebooks/movie-1/files/42/read")
|
|
req = withEbookReaderRouteParams(req, "movie-1", "42")
|
|
|
|
rr := httptest.NewRecorder()
|
|
handler.HandleReadFile(rr, req)
|
|
|
|
if rr.Code != http.StatusNotFound {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderRecognizesReadestFormats(t *testing.T) {
|
|
cases := map[string]string{
|
|
"book.epub": "application/epub+zip",
|
|
"book.pdf": "application/pdf",
|
|
"book.mobi": "application/x-mobipocket-ebook",
|
|
"book.azw": "application/vnd.amazon.ebook",
|
|
"book.azw3": "application/vnd.amazon.mobi8-ebook",
|
|
"book.cbz": "application/vnd.comicbook+zip",
|
|
"book.cbr": "application/vnd.comicbook-rar",
|
|
"book.fb2": "application/x-fictionbook+xml",
|
|
"book.fbz": "application/x-zip-compressed-fb2",
|
|
"book.fb2.zip": "application/x-zip-compressed-fb2",
|
|
"book.md": "application/octet-stream",
|
|
"book.unknown": "application/octet-stream",
|
|
}
|
|
rejected := map[string]bool{"book.md": true, "book.unknown": true}
|
|
|
|
for name, wantMime := range cases {
|
|
t.Run(name, func(t *testing.T) {
|
|
container := name
|
|
if name == "book.fb2.zip" {
|
|
container = "fbz"
|
|
}
|
|
file := &models.MediaFile{FilePath: "/library/" + name, Container: container}
|
|
if rejected[name] {
|
|
file.BaseType = "ebook"
|
|
if isEbookFile(file) {
|
|
t.Fatalf("%s should not be treated as an ebook reader format", name)
|
|
}
|
|
if got := ebookMimeType(file.FilePath, file.Container); got != wantMime {
|
|
t.Fatalf("ebookMimeType() = %q, want %q", got, wantMime)
|
|
}
|
|
return
|
|
}
|
|
file.BaseType = "ebook"
|
|
if !isEbookFile(file) {
|
|
t.Fatal("expected ebook reader format")
|
|
}
|
|
if got := ebookMimeType(file.FilePath, file.Container); got != wantMime {
|
|
t.Fatalf("ebookMimeType() = %q, want %q", got, wantMime)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderRejectsPlainText(t *testing.T) {
|
|
file := &models.MediaFile{
|
|
FilePath: "/library/book.txt",
|
|
BaseType: "ebook",
|
|
}
|
|
|
|
if isEbookFile(file) {
|
|
t.Fatal("plain text should not be treated as an ebook reader format")
|
|
}
|
|
if got := ebookMimeType(file.FilePath, file.Container); got == "text/plain; charset=utf-8" {
|
|
t.Fatal("plain text should not have an ebook reader MIME type")
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderRecognizesFBZFromCompoundFilenameWithoutContainer(t *testing.T) {
|
|
file := &models.MediaFile{
|
|
FilePath: "/library/book.fb2.zip",
|
|
BaseType: "ebook",
|
|
}
|
|
|
|
if !isEbookFile(file) {
|
|
t.Fatal("expected .fb2.zip path to be treated as an ebook reader format")
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderMapsAccessFailureToNotFound(t *testing.T) {
|
|
handler := NewEbookReaderHandler(&MediaFileAuthorizer{
|
|
FileResolver: stubMediaFileResolver{
|
|
file: &models.MediaFile{
|
|
ID: 42,
|
|
ContentID: "ebook-1",
|
|
FilePath: "/tmp/book.epub",
|
|
Container: "epub",
|
|
BaseType: "ebook",
|
|
},
|
|
},
|
|
ItemAccess: stubItemAccessChecker{err: catalog.ErrItemNotFound},
|
|
})
|
|
|
|
req := newEbookReaderAuthRequest(http.MethodGet, "/ebooks/ebook-1/files/42/read")
|
|
req = withEbookReaderRouteParams(req, "ebook-1", "42")
|
|
|
|
rr := httptest.NewRecorder()
|
|
handler.HandleReadFile(rr, req)
|
|
|
|
if rr.Code != http.StatusNotFound {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderReturnsInternalErrorForUnexpectedAuthorizeFailure(t *testing.T) {
|
|
handler := NewEbookReaderHandler(&MediaFileAuthorizer{
|
|
FileResolver: stubMediaFileResolver{err: errors.New("db down")},
|
|
ItemAccess: stubItemAccessChecker{},
|
|
})
|
|
|
|
req := newEbookReaderAuthRequest(http.MethodGet, "/ebooks/ebook-1/files/42/read")
|
|
req = withEbookReaderRouteParams(req, "ebook-1", "42")
|
|
|
|
rr := httptest.NewRecorder()
|
|
handler.HandleReadFile(rr, req)
|
|
|
|
if rr.Code != http.StatusInternalServerError {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderSavesProgressForAuthorizedEbookFile(t *testing.T) {
|
|
store := &fakeEbookProgressStore{}
|
|
handler := NewEbookReaderHandler(&MediaFileAuthorizer{
|
|
FileResolver: stubMediaFileResolver{
|
|
file: &models.MediaFile{
|
|
ID: 42,
|
|
ContentID: "ebook-1",
|
|
FilePath: "/tmp/book.epub",
|
|
Container: "epub",
|
|
BaseType: "ebook",
|
|
},
|
|
},
|
|
ItemAccess: stubItemAccessChecker{},
|
|
})
|
|
handler.ProgressStore = store
|
|
|
|
req := httptest.NewRequest(
|
|
http.MethodPut,
|
|
"/ebooks/ebook-1/progress",
|
|
strings.NewReader(`{"file_id":42,"location":"epubcfi(/6/4)","progress":0.42}`),
|
|
)
|
|
ctx := apimw.SetClaims(context.Background(), &auth.Claims{
|
|
UserID: 1,
|
|
Role: "user",
|
|
TokenType: auth.TokenTypeAccess,
|
|
})
|
|
req = req.WithContext(apimw.SetProfileID(ctx, "profile-9"))
|
|
req = withEbookReaderContentRouteParam(req, "ebook-1")
|
|
|
|
rr := httptest.NewRecorder()
|
|
handler.HandleSaveProgress(rr, req)
|
|
|
|
if rr.Code != http.StatusOK {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
if store.upserted == nil {
|
|
t.Fatal("expected progress to be saved")
|
|
}
|
|
if store.upserted.UserID != 1 || store.upserted.ProfileID != "profile-9" {
|
|
t.Fatalf("scope = user %d profile %q", store.upserted.UserID, store.upserted.ProfileID)
|
|
}
|
|
if store.upserted.ContentID != "ebook-1" || store.upserted.FileID != 42 {
|
|
t.Fatalf("target = content %q file %d", store.upserted.ContentID, store.upserted.FileID)
|
|
}
|
|
if store.upserted.Location != "epubcfi(/6/4)" || store.upserted.Progress != 0.42 {
|
|
t.Fatalf("progress = %+v", store.upserted)
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderReturnsSavedProgress(t *testing.T) {
|
|
updatedAt := time.Date(2026, 6, 8, 12, 0, 0, 0, time.UTC)
|
|
handler := NewEbookReaderHandler(&MediaFileAuthorizer{
|
|
FileResolver: stubMediaFileResolver{},
|
|
ItemAccess: stubItemAccessChecker{},
|
|
})
|
|
handler.ProgressStore = &fakeEbookProgressStore{
|
|
progress: &EbookReaderProgress{
|
|
UserID: 1,
|
|
ProfileID: "profile-1",
|
|
ContentID: "ebook-1",
|
|
FileID: 42,
|
|
Location: "epubcfi(/6/8)",
|
|
Progress: 0.75,
|
|
UpdatedAt: updatedAt,
|
|
},
|
|
}
|
|
|
|
req := newEbookReaderAuthRequest(http.MethodGet, "/ebooks/ebook-1/progress")
|
|
req = withEbookReaderContentRouteParam(req, "ebook-1")
|
|
|
|
rr := httptest.NewRecorder()
|
|
handler.HandleGetProgress(rr, req)
|
|
|
|
if rr.Code != http.StatusOK {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
body := rr.Body.String()
|
|
for _, want := range []string{
|
|
`"content_id":"ebook-1"`,
|
|
`"file_id":42`,
|
|
`"location":"epubcfi(/6/8)"`,
|
|
`"progress":0.75`,
|
|
`"updated_at":"2026-06-08T12:00:00Z"`,
|
|
} {
|
|
if !strings.Contains(body, want) {
|
|
t.Fatalf("response %s missing %s", body, want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderReturnsEmptyConfigWhenNoneSaved(t *testing.T) {
|
|
handler := NewEbookReaderHandler(&MediaFileAuthorizer{
|
|
FileResolver: stubMediaFileResolver{},
|
|
ItemAccess: stubItemAccessChecker{},
|
|
})
|
|
handler.ConfigStore = &fakeEbookReaderConfigStore{}
|
|
|
|
req := newEbookReaderAuthRequest(http.MethodGet, "/ebooks/ebook-1/reader-config")
|
|
req = withEbookReaderContentRouteParam(req, "ebook-1")
|
|
|
|
rr := httptest.NewRecorder()
|
|
handler.HandleGetConfig(rr, req)
|
|
|
|
if rr.Code != http.StatusOK {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
if got := strings.TrimSpace(rr.Body.String()); got != `{"config":{}}` {
|
|
t.Fatalf("body = %s", got)
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderSavesConfigForAccessibleEbook(t *testing.T) {
|
|
store := &fakeEbookReaderConfigStore{}
|
|
handler := NewEbookReaderHandler(&MediaFileAuthorizer{
|
|
FileResolver: stubMediaFileResolver{},
|
|
ItemAccess: stubItemAccessChecker{},
|
|
})
|
|
handler.ConfigStore = store
|
|
|
|
req := httptest.NewRequest(
|
|
http.MethodPut,
|
|
"/ebooks/ebook-1/reader-config",
|
|
strings.NewReader(`{"config":{"theme":"dark","flow":"scrolled","fontSize":120}}`),
|
|
)
|
|
ctx := apimw.SetClaims(context.Background(), &auth.Claims{
|
|
UserID: 1,
|
|
Role: "user",
|
|
TokenType: auth.TokenTypeAccess,
|
|
})
|
|
req = req.WithContext(apimw.SetProfileID(ctx, "profile-9"))
|
|
req = withEbookReaderContentRouteParam(req, "ebook-1")
|
|
|
|
rr := httptest.NewRecorder()
|
|
handler.HandleSaveConfig(rr, req)
|
|
|
|
if rr.Code != http.StatusOK {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
if store.saved == nil {
|
|
t.Fatal("expected config to be saved")
|
|
}
|
|
if store.saved.UserID != 1 || store.saved.ProfileID != "profile-9" || store.saved.ContentID != "ebook-1" {
|
|
t.Fatalf("scope = %+v", store.saved)
|
|
}
|
|
var config map[string]any
|
|
if err := json.Unmarshal(store.saved.Config, &config); err != nil {
|
|
t.Fatalf("config json: %v", err)
|
|
}
|
|
if config["theme"] != "dark" || config["flow"] != "scrolled" || config["fontSize"].(float64) != 120 {
|
|
t.Fatalf("config = %#v", config)
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderRejectsNonObjectConfig(t *testing.T) {
|
|
handler := NewEbookReaderHandler(&MediaFileAuthorizer{
|
|
FileResolver: stubMediaFileResolver{},
|
|
ItemAccess: stubItemAccessChecker{},
|
|
})
|
|
handler.ConfigStore = &fakeEbookReaderConfigStore{}
|
|
|
|
req := newEbookReaderAuthRequest(http.MethodPut, "/ebooks/ebook-1/reader-config")
|
|
req.Body = http.NoBody
|
|
req = httptest.NewRequest(
|
|
http.MethodPut,
|
|
"/ebooks/ebook-1/reader-config",
|
|
strings.NewReader(`{"config":["bad"]}`),
|
|
).WithContext(req.Context())
|
|
req = withEbookReaderContentRouteParam(req, "ebook-1")
|
|
|
|
rr := httptest.NewRecorder()
|
|
handler.HandleSaveConfig(rr, req)
|
|
|
|
if rr.Code != http.StatusBadRequest {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderConfigRequiresAccessibleContent(t *testing.T) {
|
|
handler := NewEbookReaderHandler(&MediaFileAuthorizer{
|
|
FileResolver: stubMediaFileResolver{},
|
|
ItemAccess: stubItemAccessChecker{err: catalog.ErrItemNotFound},
|
|
})
|
|
handler.ConfigStore = &fakeEbookReaderConfigStore{}
|
|
|
|
req := newEbookReaderAuthRequest(http.MethodGet, "/ebooks/ebook-1/reader-config")
|
|
req = withEbookReaderContentRouteParam(req, "ebook-1")
|
|
|
|
rr := httptest.NewRecorder()
|
|
handler.HandleGetConfig(rr, req)
|
|
|
|
if rr.Code != http.StatusNotFound {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderCreatesAnnotationForAccessibleEbook(t *testing.T) {
|
|
store := &fakeEbookReaderAnnotationStore{}
|
|
handler := NewEbookReaderHandler(&MediaFileAuthorizer{
|
|
FileResolver: stubMediaFileResolver{},
|
|
ItemAccess: stubItemAccessChecker{},
|
|
})
|
|
handler.AnnotationStore = store
|
|
|
|
req := httptest.NewRequest(
|
|
http.MethodPost,
|
|
"/ebooks/ebook-1/annotations",
|
|
strings.NewReader(`{"kind":"highlight","cfi_range":"epubcfi(/6/4,/1:0,/1:12)","selected_text":"sample text","note":"note text","style":"highlight","color":"#facc15"}`),
|
|
)
|
|
ctx := apimw.SetClaims(context.Background(), &auth.Claims{
|
|
UserID: 1,
|
|
Role: "user",
|
|
TokenType: auth.TokenTypeAccess,
|
|
})
|
|
req = req.WithContext(apimw.SetProfileID(ctx, "profile-9"))
|
|
req = withEbookReaderContentRouteParam(req, "ebook-1")
|
|
|
|
rr := httptest.NewRecorder()
|
|
handler.HandleCreateAnnotation(rr, req)
|
|
|
|
if rr.Code != http.StatusCreated {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
if store.created == nil {
|
|
t.Fatal("expected annotation to be created")
|
|
}
|
|
if store.created.UserID != 1 || store.created.ProfileID != "profile-9" || store.created.ContentID != "ebook-1" {
|
|
t.Fatalf("scope = %+v", store.created)
|
|
}
|
|
if store.created.Kind != "highlight" || store.created.CFIRange != "epubcfi(/6/4,/1:0,/1:12)" {
|
|
t.Fatalf("annotation = %+v", store.created)
|
|
}
|
|
if store.created.SelectedText != "sample text" || store.created.Note != "note text" {
|
|
t.Fatalf("annotation text = %+v", store.created)
|
|
}
|
|
if store.created.ID == "" {
|
|
t.Fatal("expected generated annotation id")
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderReturnsAnnotations(t *testing.T) {
|
|
updatedAt := time.Date(2026, 6, 8, 12, 0, 0, 0, time.UTC)
|
|
handler := NewEbookReaderHandler(&MediaFileAuthorizer{
|
|
FileResolver: stubMediaFileResolver{},
|
|
ItemAccess: stubItemAccessChecker{},
|
|
})
|
|
handler.AnnotationStore = &fakeEbookReaderAnnotationStore{
|
|
items: []EbookReaderAnnotation{
|
|
{
|
|
ID: "ann-1",
|
|
UserID: 1,
|
|
ProfileID: "profile-1",
|
|
ContentID: "ebook-1",
|
|
Kind: "bookmark",
|
|
Location: "epubcfi(/6/8)",
|
|
SelectedText: "",
|
|
Note: "Saved spot",
|
|
Style: "highlight",
|
|
Color: "#facc15",
|
|
Metadata: json.RawMessage(`{}`),
|
|
CreatedAt: updatedAt,
|
|
UpdatedAt: updatedAt,
|
|
},
|
|
},
|
|
}
|
|
|
|
req := newEbookReaderAuthRequest(http.MethodGet, "/ebooks/ebook-1/annotations")
|
|
req = withEbookReaderContentRouteParam(req, "ebook-1")
|
|
|
|
rr := httptest.NewRecorder()
|
|
handler.HandleListAnnotations(rr, req)
|
|
|
|
if rr.Code != http.StatusOK {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
body := rr.Body.String()
|
|
for _, want := range []string{`"items":[`, `"id":"ann-1"`, `"kind":"bookmark"`, `"location":"epubcfi(/6/8)"`} {
|
|
if !strings.Contains(body, want) {
|
|
t.Fatalf("response %s missing %s", body, want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func existingEbookReaderAnnotation() *EbookReaderAnnotation {
|
|
createdAt := time.Date(2026, 6, 1, 9, 0, 0, 0, time.UTC)
|
|
return &EbookReaderAnnotation{
|
|
ID: "ann-1",
|
|
UserID: 1,
|
|
ProfileID: "profile-1",
|
|
ContentID: "ebook-1",
|
|
Kind: "highlight",
|
|
CFIRange: "epubcfi(/6/4,/1:0,/1:12)",
|
|
SelectedText: "sample text",
|
|
Note: "original note",
|
|
Style: "highlight",
|
|
Color: "#facc15",
|
|
Metadata: json.RawMessage(`{"chapter":"one"}`),
|
|
CreatedAt: createdAt,
|
|
UpdatedAt: createdAt,
|
|
}
|
|
}
|
|
|
|
func patchEbookReaderAnnotation(t *testing.T, store *fakeEbookReaderAnnotationStore, body string) *httptest.ResponseRecorder {
|
|
t.Helper()
|
|
handler := NewEbookReaderHandler(&MediaFileAuthorizer{
|
|
FileResolver: stubMediaFileResolver{},
|
|
ItemAccess: stubItemAccessChecker{},
|
|
})
|
|
handler.AnnotationStore = store
|
|
|
|
req := newEbookReaderAuthRequest(http.MethodPatch, "/ebooks/ebook-1/annotations/ann-1")
|
|
req.Body = ioNopCloser{strings.NewReader(body)}
|
|
req = withEbookReaderAnnotationRouteParams(req, "ebook-1", "ann-1")
|
|
|
|
rr := httptest.NewRecorder()
|
|
handler.HandleUpdateAnnotation(rr, req)
|
|
return rr
|
|
}
|
|
|
|
func TestEbookReaderPatchKeepsAbsentFields(t *testing.T) {
|
|
store := &fakeEbookReaderAnnotationStore{existing: existingEbookReaderAnnotation()}
|
|
|
|
rr := patchEbookReaderAnnotation(t, store, `{"note":"updated","color":"#bfdbfe"}`)
|
|
|
|
if rr.Code != http.StatusOK {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
if store.updated == nil || store.updated.ID != "ann-1" || store.updated.Note != "updated" || store.updated.Color != "#bfdbfe" {
|
|
t.Fatalf("updated = %+v", store.updated)
|
|
}
|
|
if string(store.updated.Metadata) != `{"chapter":"one"}` {
|
|
t.Fatalf("metadata should be preserved when absent, got %s", store.updated.Metadata)
|
|
}
|
|
if store.updated.Kind != "highlight" || store.updated.CFIRange != "epubcfi(/6/4,/1:0,/1:12)" {
|
|
t.Fatalf("absent fields should keep stored values, got %+v", store.updated)
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderPatchClearsExplicitlyEmptyFields(t *testing.T) {
|
|
store := &fakeEbookReaderAnnotationStore{existing: existingEbookReaderAnnotation()}
|
|
|
|
rr := patchEbookReaderAnnotation(t, store, `{"note":"","metadata":{}}`)
|
|
|
|
if rr.Code != http.StatusOK {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
if store.updated == nil || store.updated.Note != "" {
|
|
t.Fatalf("note should be cleared, got %+v", store.updated)
|
|
}
|
|
if string(store.updated.Metadata) != `{}` {
|
|
t.Fatalf("metadata should be cleared to {}, got %s", store.updated.Metadata)
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderPatchValidatesResultingState(t *testing.T) {
|
|
cases := map[string]string{
|
|
"kind change without location": `{"kind":"bookmark"}`,
|
|
"clearing required cfi_range": `{"cfi_range":""}`,
|
|
"unknown kind": `{"kind":"doodle"}`,
|
|
"non-object metadata": `{"metadata":["bad"]}`,
|
|
}
|
|
for name, body := range cases {
|
|
t.Run(name, func(t *testing.T) {
|
|
store := &fakeEbookReaderAnnotationStore{existing: existingEbookReaderAnnotation()}
|
|
rr := patchEbookReaderAnnotation(t, store, body)
|
|
if rr.Code != http.StatusBadRequest {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
if store.updated != nil {
|
|
t.Fatalf("invalid patch must not reach the store, got %+v", store.updated)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderPatchAllowsKindChangeWithRequiredFields(t *testing.T) {
|
|
store := &fakeEbookReaderAnnotationStore{existing: existingEbookReaderAnnotation()}
|
|
|
|
rr := patchEbookReaderAnnotation(t, store, `{"kind":"bookmark","location":"epubcfi(/6/8)"}`)
|
|
|
|
if rr.Code != http.StatusOK {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
if store.updated == nil || store.updated.Kind != "bookmark" || store.updated.Location != "epubcfi(/6/8)" {
|
|
t.Fatalf("updated = %+v", store.updated)
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderPatchMergesOntoRowReadInsideStoreUpdate(t *testing.T) {
|
|
store := &fakeEbookReaderAnnotationStore{existing: existingEbookReaderAnnotation()}
|
|
|
|
rr := patchEbookReaderAnnotation(t, store, `{"note":"merged note"}`)
|
|
|
|
if rr.Code != http.StatusOK {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
// The handler must not pre-read and merge outside the store: the merge
|
|
// runs exactly once, on the row handed over by the (locked) store read.
|
|
if store.mergeCalls != 1 {
|
|
t.Fatalf("merge calls = %d, want 1", store.mergeCalls)
|
|
}
|
|
if store.mergedFrom == nil || store.mergedFrom.Note != "original note" {
|
|
t.Fatalf("merge input = %+v, want the stored row", store.mergedFrom)
|
|
}
|
|
if store.updated == nil || store.updated.Note != "merged note" {
|
|
t.Fatalf("written row = %+v, want merged note", store.updated)
|
|
}
|
|
if store.updated.CFIRange != store.mergedFrom.CFIRange || store.updated.Kind != store.mergedFrom.Kind {
|
|
t.Fatalf("written row %+v must keep unpatched fields from merge input %+v", store.updated, store.mergedFrom)
|
|
}
|
|
if !store.updated.UpdatedAt.After(store.mergedFrom.UpdatedAt) {
|
|
t.Fatalf("updated_at %v must advance past %v", store.updated.UpdatedAt, store.mergedFrom.UpdatedAt)
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderPatchReturnsNotFoundForMissingAnnotation(t *testing.T) {
|
|
store := &fakeEbookReaderAnnotationStore{}
|
|
|
|
rr := patchEbookReaderAnnotation(t, store, `{"note":"updated"}`)
|
|
|
|
if rr.Code != http.StatusNotFound {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderRejectsOversizedProgressBody(t *testing.T) {
|
|
store := &fakeEbookProgressStore{}
|
|
handler := NewEbookReaderHandler(&MediaFileAuthorizer{
|
|
FileResolver: stubMediaFileResolver{},
|
|
ItemAccess: stubItemAccessChecker{},
|
|
})
|
|
handler.ProgressStore = store
|
|
|
|
body := `{"file_id":42,"location":"` + strings.Repeat("x", int(ebookReaderProgressMaxBodySize)) + `","progress":0.5}`
|
|
req := newEbookReaderAuthRequest(http.MethodPut, "/ebooks/ebook-1/progress")
|
|
req.Body = ioNopCloser{strings.NewReader(body)}
|
|
req = withEbookReaderContentRouteParam(req, "ebook-1")
|
|
|
|
rr := httptest.NewRecorder()
|
|
handler.HandleSaveProgress(rr, req)
|
|
|
|
if rr.Code != http.StatusRequestEntityTooLarge {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
if store.upserted != nil {
|
|
t.Fatalf("oversized body must not be saved, got %+v", store.upserted)
|
|
}
|
|
}
|
|
|
|
func TestInlineContentDispositionProducesParseableHeaders(t *testing.T) {
|
|
cases := map[string]string{
|
|
"book.epub": "book.epub",
|
|
`bo"ok\.epub`: `bo"ok\.epub`,
|
|
`trailing-slash\`: `trailing-slash\`,
|
|
"börk \U0001F4DA.epub": "börk \U0001F4DA.epub",
|
|
"": "ebook",
|
|
".": "ebook",
|
|
}
|
|
for name, want := range cases {
|
|
t.Run(name, func(t *testing.T) {
|
|
got := inlineContentDisposition(name)
|
|
mediaType, params, err := mime.ParseMediaType(got)
|
|
if err != nil {
|
|
t.Fatalf("header %q is malformed: %v", got, err)
|
|
}
|
|
if mediaType != "inline" {
|
|
t.Fatalf("media type = %q", mediaType)
|
|
}
|
|
if params["filename"] != want {
|
|
t.Fatalf("filename = %q, want %q", params["filename"], want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestEbookReaderDeletesAnnotation(t *testing.T) {
|
|
store := &fakeEbookReaderAnnotationStore{}
|
|
handler := NewEbookReaderHandler(&MediaFileAuthorizer{
|
|
FileResolver: stubMediaFileResolver{},
|
|
ItemAccess: stubItemAccessChecker{},
|
|
})
|
|
handler.AnnotationStore = store
|
|
|
|
req := newEbookReaderAuthRequest(http.MethodDelete, "/ebooks/ebook-1/annotations/ann-1")
|
|
req = withEbookReaderAnnotationRouteParams(req, "ebook-1", "ann-1")
|
|
|
|
rr := httptest.NewRecorder()
|
|
handler.HandleDeleteAnnotation(rr, req)
|
|
|
|
if rr.Code != http.StatusNoContent {
|
|
t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String())
|
|
}
|
|
if store.deleted != "ann-1" {
|
|
t.Fatalf("deleted = %q", store.deleted)
|
|
}
|
|
}
|
|
|
|
type ioNopCloser struct {
|
|
*strings.Reader
|
|
}
|
|
|
|
func (c ioNopCloser) Close() error { return nil }
|