Commit Graph
95 Commits
Author SHA1 Message Date
john-okeefe da1732285f fix(scanner): populate page count and total characters during media scanning
The media scanner never populated page_count or total_characters in
media_items, leaving progress display and reading position calculations
with no reliable data. This commit fixes data population for all formats:

Comics (CBZ/CBR/CB7/CBT):
- Add countArchiveImages() helper that walks archive entries and counts
  image files (.jpg, .jpeg, .png, .gif, .webp)
- Call it during comic metadata merge to set metadata.PageCount

PDFs:
- Extract pdfInfo.PageCount from the pdfcpu library (already available
  from PDFInfo call, just never used) and set metadata.PageCount

Reflowable EPUBs:
- Use book.AllChaptersText() to compute metadata.TotalCharacters
- Use book.ChapterCount() to set metadata.ChapterCount

Fixed-layout EPUBs (manga/comics in EPUB format):
- Merge .epub into the .cbz case in countArchiveImages since both are
  ZIP archives with images
- Detect fixed-layout EPUBs via DetectFixedLayoutEPUB() in both the
  Calibre sidecar path (mergeMetadata) and the no-sidecar path
  (extractMetadata), counting images when fixed-layout is detected

Format group on creation:
- Remove the guard condition on UpdateMediaItemFormatGroup so that
  format_group, is_reflowable, and has_fixed_layout are set immediately
  for every new item (not just items with text data)
- Use DetectFixedLayoutEPUB() instead of hardcoding all .epub as
  reflowable, correctly classifying fixed-layout EPUBs

Also pass PageCount to CreateMediaItem and add PageCount,
TotalCharacters, and ChapterCount fields to the MediaMetadata struct.
2026-04-24 14:01:57 -04:00
john-okeefe a4962a87b2 fix: replace invalid new(expression) calls with proper pointer allocation
Go's new() builtin takes a type and allocates a zero value — it cannot
wrap an expression. All instances of new(someExpression) were compile
errors. Replace each with a local variable assignment and address-of
operator.

Affected files:
- handlers/koreader.go: progress field pointers (Chapter, Page, etc.)
- handlers/kobo.go: pagesRemaining pointer
- handlers/queue.go: uuidPtrToString and timestamptzPtrToString helpers
- router/reader.go: bookmark pageNumber and chapterNumber pointers
- services/media_scanner.go: validation error message pointers
- services/worker.go: StartedAt and CompletedAt timestamps
- sync/offline.go: GetDeviceStatus return pointer
- tests/device_test.go: SyncEnabled and SyncFrequencyMinutes pointers
2026-04-23 20:39:50 -04:00
john-okeefe 133ca1fdaa fix(scanner): extract metadata and covers for comic archives and kepub files
Comic archive formats (.cbz, .cbr, .cb7, .cbt) and .kepub files were
falling through to the default case in extractMetadata(), which only
set the title from the filename. This meant ComicInfo.xml was never
parsed and no cover images were extracted for comics without a Calibre
metadata.opf sidecar file.

The fix adds dedicated switch cases:
- .cbz/.cbr/.cb7/.cbt: calls mergeMetadata() with nil, which triggers
  existing ComicInfo.xml parsing (title, series, issue number, writer,
  publisher, genre, reading direction, etc.) and cover image extraction
  from the archive. Falls back to sidecar cover if no image is found.
- .kepub: treated the same as .epub since KEPUB is an EPUB variant,
  enabling full metadata and cover extraction.
2026-04-22 21:18:53 -04:00
john-okeefe e389df92c3 refactor: remove unnecessary type conversions and handle ignored errors across codebase
Remove redundant type conversions that Go 1.26 makes unnecessary or that
were already no-ops:

- uuid.UUID(x.Bytes) → x.Bytes (uuid.UUID is [16]byte, same as pgtype UUID Bytes)
- pgtype.UUID{Bytes: [16]byte(u), Valid: true} → pgtype.UUID{Bytes: u, Valid: true}
- (*time.Time)(&x.Time) → &x.Time
- json.RawMessage(x) → x where x is already []byte
- []byte(stringVal) → stringVal where []byte is expected
- int()/int64()/byte() casts on values already of the target type
- Decompressor(fn) → fn (type is identical)

Handle previously ignored error returns:

- collections.go: check json.Unmarshal error in GetCollection
- conversion_service.go: check fileSize.Scan() error
- app_test.go: check app.Shutdown() error in benchmark
2026-04-21 21:15:59 -04:00
john-okeefe 8baecad379 fix(tests): use errors.Is() for error comparison and improve resource cleanup in analytics tests
Replace direct error equality check with errors.Is() in media_scanner_hash_test.

In analytics_test.go, improve defer patterns by capturing resp.Body as a named parameter
to avoid stale references, and add require.NoError() checks on all json.NewDecoder().Decode()
calls that were previously silently ignoring decode errors.
2026-04-20 21:20:38 -04:00
john-okeefe 9ccff320a1 refactor: use errors.Is()/errors.AsType() for error comparison and rename shadowed variables
Replace direct error equality checks (err == pgx.ErrNoRows, err != http.ErrServerClosed)
with the idiomatic errors.Is() function throughout handlers, services, middleware, and app
startup. This correctly handles wrapped error chains.

Also replace a raw type assertion (*HTTPError) with errors.AsType[*HTTPError]() in the
error handler middleware for consistency.

Additionally, rename shadowed variables for clarity:
- sidecar.go: config -> sidecarConfig, systemConfig (shadowed package-level vars)
- media_scanner.go: uuid -> uuidString (shadowed the uuid package import)
2026-04-20 21:20:22 -04:00
john-okeefe 5b2d105609 fix(scanner): always attempt cover extraction for EPUBs and relax manga detection
Two changes to EPUB metadata extraction:

1. Restructure extractMetadata so that fixed-layout detection and cover
   extraction always run for EPUBs, even when extractEPUBMetadata returns
   an error. Previously, a partial failure from the EPUB parser would skip
   cover and format detection entirely, leaving books without covers.

2. Remove the language restriction (ja/jpn) from manga reading direction
   detection. Manga tagged with 'manga' should default to RTL regardless
   of the language metadata, since the tag is an explicit signal from the
   user or metadata source.
2026-04-20 20:45:49 -04:00
john-okeefe 2b139afce6 refactor(services): replace temporary variable pointer pattern with new() builtin
Simplify pointer creation in media scanner validation messages and worker
job timestamps by using inline new() instead of local variable + address-of.

In media_scanner.go this cleans up three validation error message returns
(manga/comics library format checks). In worker.go it simplifies StartedAt
and CompletedAt timestamp assignments.
2026-04-20 08:58:19 -04:00
john-okeefe e1aef8e85f refactor(services): Modernize Go code style in collection and filters services
Apply Go 1.18+ language features and modern style:

internal/services/collection_service.go:
- Use map[string]any instead of map[string]interface{} (Go 1.18+)
- Use range clause with single variable for iteration-only loops
- Replace if-else chains with switch statements for better readability
- Remove explicit type initialization for zero values

internal/services/filters.go:
- Add Err prefix to custom error variable for error naming convention

internal/router/library.go:
- Use cfg.ProcessingIssuesHandler instead of local processingIssuesHandler variable
- Ensures proper dependency injection through router config

These changes follow current Go best practices and improve code readability.
2026-04-13 09:25:01 -04:00
john-okeefe 6398802d15 docs: Add package documentation for handlers and services
Add Go package documentation comments to clarify the purpose and scope of:

- internal/handlers/: HTTP request/response handlers for authentication,
  libraries, media items, reading, collections, dashboards, devices,
  analytics, and system features

- internal/services/: Core business logic layer including media scanning,
  library management, search, analytics, and conversion services

These doc comments improve code discoverability and help developers understand
the architectural separation between HTTP handling (handlers) and business
logic (services).
2026-04-13 09:23:12 -04:00
john-okeefe f7610c6063 feat(scanner): Add fixed-layout EPUB detection for manga support
- Add DetectFixedLayoutEPUB method to identify manga-style EPUBs
- Check for rendition:layout pre-paginated metadata
- Check for RTL page-progression-direction (manga indicator)
- Check image count threshold (>50 images suggests manga/comic)
- Check subject tags for manga/comic keywords
- Enable proper format detection for manga EPUBs in libraries
2026-04-12 20:43:49 -04:00
john-okeefe 83ba24e31a Expose library_type_name in API and remove redundant empty fields
- Add library_type_name to GetMediaItem handler response in media.go
- Remove empty LibraryName and LibraryTypeName fields from:
  - ListMediaItemsRow in collections.go handler
  - ListMediaItemsRow in dashboard_service.go
- These fields are now populated at the database level via trigger

The library_type_name is now automatically populated in the database
when a media item is created, so we remove the manual empty string
assignments and expose the actual value in the API response.
2026-04-04 22:49:12 -04:00
john-okeefe d91e5fac3d fix: update reader service and handler
- Add panel_layout to getDefaultSettings() for dockable panels
- Remove template rendering from ShowReader (router handles SSR)
- Fix pgtype.Int4 marshaling to JSON (no explicit int conversion)
- Remove unused strings import from handlers
2026-04-03 17:20:23 -04:00
john-okeefe 74575d9a86 feat: add reader service, handler, and router 2026-04-03 16:53:37 -04:00
john-okeefe 0ff34a683a feat(media_scanner): add genre field to MediaMetadata
Add Genre field to MediaMetadata struct to support genre information
extraction from media files during scanning.
2026-03-30 17:51:08 -04:00
john-okeefe fd74415a4a test: add unit tests for comic metadata processing
Phase 6.1 implementation: Unit tests for metadata helper functions.

Test Coverage:
- TestNormalizeMangaType: Verify Manga field normalization to database enum values
  (unknown, no, yes, yes_and_right_to_left)
- TestDetermineReadingDirection: Test reading direction computation heuristics
  (explicit Manga field, Japanese language, webtoon/manhwa genre tags, Western default)
- TestNormalizeAgeRating: Verify age rating standardization
  (Everyone, Teen, Mature, Adult with various input formats)

These tests ensure the helper functions correctly normalize ComicInfo.xml data
before storage in the database.

Relates to: Phase 6.1 unit testing
2026-03-29 21:12:24 -04:00
john-okeefe 831668a07d feat(media_scanner): implement smart metadata merging and ComicInfo.xml v2.0 support
Phase 2-3 implementation: Complete ComicInfo.xml parsing with intelligent Calibre merging.

Data Structure Updates:
- ComicInfo struct: Add 19 ComicInfo.xml v2.0 fields (Manga, LanguageISO, Count,
  AlternateSeries, AlternateNumber, AlternateCount, Summary, Imprint, StoryArc,
  SeriesGroup, AgeRating, CommunityRating, MainCharacterOrTeam, Review,
  BlackAndWhite, ScanInformation, Characters, Teams, Locations)
- MediaMetadata struct: Add 14 fields for reading direction and universal/comic metadata

New Functions:
- mergeMetadata(): Smart merging with priority: Calibre metadata.opf → ComicInfo.xml →
  embedded metadata. Extracts reading direction even when metadata.opf exists.
- normalizeMangaType(): Normalize ComicInfo.xml Manga field to database enum
- determineReadingDirection(): Compute reading direction from Manga + language + genre heuristics
- normalizeAgeRating(): Standardize age rating values (Everyone, Teen, Mature, Adult)
- processGenresAndTags(): Universal genre/tag processing for all formats
- extractGenreTagsFromEPUB(): Extract all <dc:subject> values from EPUB
- extractGenreTagsFromComicInfo(): Extract genres from Genre + Tags + Characters + Teams + Locations
- containsTag(): Helper to prevent duplicate tags

Logic Changes:
- extractMetadata(): Now calls mergeMetadata() for smart metadata combination
- processMediaFile(): Updated CreateMediaItem call with all 14 new fields
- Removed duplicate comic metadata extraction (now handled by mergeMetadata)
- CommunityRating uses simple pgtype.Float8 (DOUBLE PRECISION) instead of pgtype.Numeric

This enables complete ComicInfo.xml v2.0 support with 19 fields plus 5 universal fields
that apply to all media formats (ebooks, audiobooks, comics).

Relates to: Phase 2 (data structures), Phase 3 (smart merging), Phase 4 (media item creation)
2026-03-29 21:12:23 -04:00
john-okeefe 765123a545 Update default system collection names to Title Case format
Changed the 4 default system collection names from kebab-case to Title Case
with spaces for better readability and professional appearance:

Changes:
- "continue-reading" → "Continue Reading"
- "recently-added" → "Recently Added"
- "recently-read" → "Recently Read"
- "not-started" → "Not Started"

Implementation details:
- Collection Name field: Updated to Title Case (user-visible identifier)
- QueryType field: Unchanged, remains kebab-case (internal switch/case logic)
- All map keys updated to use new Title Case names as lookups
- Restore modal option values updated to match new names

Files modified:
- internal/handlers/auth.go: Default collection creation for new users
- internal/handlers/dashboard.go: Restore endpoint validation map
- internal/services/dashboard_service.go: System collection metadata map
- templates/restore_system_collection_modal.templ: Form option values

Benefits:
- Cleaner, more professional display names for end users
- Consistent with existing restore modal UI labels
- Improved user experience with properly formatted collection names
- Internal QueryType identifiers remain unchanged for code logic
2026-03-28 21:21:03 -04:00
john-okeefe ba243c223d fix: implement proper 3-state boolean handling in backend
Updated the backend services and handlers to properly detect and pass
the has_cover parameter's validity state to the database layer.

Changes:
- services/search.go: Changed HasCover type from bool to pgtype.Bool
  to support 3-state logic (NULL, TRUE, FALSE)
- handlers/media.go: Fixed 3-state detection by checking if has_cover
  exists in query params before setting Valid flag
- router/search.go: Fixed 3-state detection to match media.go logic
- router/frontend.go: Use pgtype.Bool{Valid: false} for SSR initial
  load to ensure no filtering occurs on first page load

The key fix is detecting whether the has_cover parameter was actually
sent in the request:
- Parameter not sent → pgtype.Bool{Bool: false, Valid: false}
- Parameter sent as "true" → pgtype.Bool{Bool: true, Valid: true}
- Parameter sent as "false" → pgtype.Bool{Bool: false, Valid: true}

Previously, media.go was hardcoding Valid: true, which meant it was
always filtering by has_cover=false (only books without covers) when
the parameter wasn't sent, causing searches to incorrectly return
0 results for queries like "1984".

This ensures consistency between the JSON API endpoint (media.go) and
the HTML endpoint (search.go), and fixes the critical bug where SSR
was returning 0 books on initial page load.
2026-03-27 18:07:51 -04:00
john-okeefe a33d521492 feat(search): add ExecuteSearch method to SearchService
Add shared search method that returns results with count. This method will be used by both JSON API endpoints and HTML rendering for HTMX, avoiding duplicate business logic.

- Extracts common search logic into reusable service method
- Returns search results with total count for pagination
- Follows DRY principle by eliminating duplicated search code
2026-03-27 14:50:21 -04:00
john-okeefe be31cc88f1 feat: enhance search with date-prioritized year filtering and true exact matching
Improve media item search functionality with two key enhancements:

1. Date-prioritized year filtering:
   - Prioritize date_published over copyright_year for year range queries
   - Fall back to copyright_year when date_published is NULL
   - Extract year from date_published timestamp for comparison

2. True exact search matching:
   - Replace ILIKE pattern matching with exact equality for quoted queries
   - Use search_query directly instead of wildcard pattern for exact matches
   - Remove SearchPattern parameter and related wildcard logic
   - Add COALESCE handling for author/series NULL values in exact matches

These changes make year filtering more accurate with published dates
and provide genuine exact matching when users wrap queries in quotes.

Refs internal/database/queries/queries.sql:475, internal/services/search.go:62
2026-03-26 15:35:31 -04:00
john-okeefe a900c78faf Add Calibre metadata.opf sidecar file support to media scanner
Implement sidecar-first metadata extraction approach that prioritizes
Calibre metadata.opf files over embedded metadata when available.

Key Features:
- Sidecar-first approach: Check for metadata.opf before extracting embedded
- Full Dublin Core namespace support: Use complete namespace URLs
- Calibre-specific meta tags: Extract series, series_index from <meta> tags
- Graceful degradation: Fall back to embedded metadata on parse failure
- Identifier extraction: Support ISBN and ASIN from Dublin Core identifiers
- Date parsing: Handle ISO 8601 timestamps and simple date formats

Implementation Details:
- Added extractCalibreSidecar() to check for and parse metadata.opf
- Added parseCalibreMetadataOPF() with full Dublin Core namespace handling
- Modified extractMetadata() to try sidecar first, fallback to embedded
- Added CalibreOPFMetadata struct for intermediate parsing
- Cover image support: findSidecarCover() for sidecar metadata

Tests:
- Unit tests for parseCalibreMetadataOPF() with real Calibre file examples
- Integration tests for Calibre library scanning

This allows users with Calibre-managed libraries to import their curated
metadata (series, tags, custom covers) into Bookhoard.

Fixes: #calibre-opf-support
2026-03-26 14:38:20 -04:00
john-okeefe bb8b4f9f63 feat: implement tags filter in service layer
- Add TagsFilter string to SearchParams struct
- Update dbParams building to include tags_filter
- Add tags case to SearchFieldValues service for autocomplete
- Handle SearchTagsValues query results

Enables the backend service layer to process tag filtering requests
and provide autocomplete suggestions for tag values.

Relates to IMPLEMENTATION_TAGS_FILTER.md Phase 2
2026-03-25 20:38:11 -04:00
john-okeefe a643bd43b8 refactor: clarify database parameter validation in search service
Add comment to document that filter parameters use pgtype.Text
with explicit Valid=true flag to ensure proper SQL parameter handling.
This clarifies the intent behind the parameter building logic.

Improves code documentation for future maintenance.
2026-03-25 18:03:02 -04:00
john-okeefe 83b40cb82a fix: replace empty mutex critical section with atomic scan tracking
Removes problematic empty critical section (lines 1993-1994) that
was intentionally waiting for mutex availability. Replaces with
atomic.Bool scan tracking to avoid linter warnings while maintaining
the same scan serialization behavior.

Old pattern:
  mu.Lock()
  // intentionally empty wait for mutex
  mu.Unlock()

New pattern:
  scanRunning atomic.Bool
  if !scanRunning.CompareAndSwap(false, true) {
      return ErrScanInProgress
  }
  defer scanRunning.Store(false)

This provides equivalent functionality with better performance
characteristics and clearer intent.
2026-03-24 16:47:36 -04:00
john-okeefe bd3057ec80 fix: correctly handle NULL library_id in search service
Updates SearchMediaItemsUnified to conditionally set LibraryID parameter
only when it's valid. Previously, the code always set LibraryID in the
dbParams struct, which caused pgx to pass a zero UUID instead of NULL
to PostgreSQL.

New behavior:
  - Only sets dbParams.LibraryID when params.LibraryID.Valid is true
  - When library_id is empty, LibraryID is omitted from the struct
  - Go's zero value + pgx's "field not set" detection = NULL in SQL

Also fixes type mismatches in SearchFieldValues method where
SearchQuery parameter needed explicit pgtype.Text wrapping with
Valid=true flag for proper nullable text handling.

This ensures that omitting the library_id query parameter results in
searching across all libraries, not filtering by zero UUID.
2026-03-24 16:47:30 -04:00
john-okeefe 871d5eafe6 feat: add SearchService for unified search functionality
- Create SearchService with SearchMediaItemsUnified method
- Add SearchFieldValues method for autocomplete dropdown population
- Add parseSearchQuery helper for quote detection (exact vs fuzzy search)
- Move all business logic from handler to service layer
- Follow established service pattern (FiltersService, CollectionService)
- Service created inside handler constructor, not in main.go
- SearchParams struct supports all filter types + sort parameter
- FieldSearchParams struct for field-specific autocomplete queries
- Returns FieldValue results with count and similarity scores

This provides a clean service layer abstraction for search operations.
2026-03-23 22:37:40 -04:00
john-okeefe 9ab2796902 feat: implement SearchService with unified search logic
Create new SearchService to encapsulate all search business logic:

Features:
- Unified search combining text search with filters
- Fuzzy matching using pg_trgm word_similarity (threshold: 0.3)
- Exact search when query is wrapped in quotes
- Field-specific autocomplete for dropdowns (author, genre, series, language)
- Proper pagination with configurable limit/offset

Implementation details:
- SearchMediaItems: Routes to SearchMediaItemsUnified query
  * Detects exact search by checking for quotes in query
  * Builds search pattern for ILIKE matching (%term%)
  * Converts string filters to pgtype.Text with proper Valid flags

- SearchFieldValues: Routes to appropriate field-specific query
  * Uses switch statement to call correct query based on field_type
  * Returns []FieldValue with value, count, and similarity score
  * Handles all 4 field types: author, genre, series, language

Design pattern: Service layer separates business logic from handlers,
following project's established architecture (FiltersService, CollectionService).
2026-03-22 20:35:09 -04:00
john-okeefe c3a98fb067 fix: use custom error type for saved filters not found
Fix failing test 'GET /api/saved-filters/:id_with_non-existent_filter_returns_404'
which was returning HTTP 500 instead of HTTP 404 due to string comparison
failure in error handling.

Root Cause:
- Service wrapped database error: fmt.Errorf("filter not found: %w", err)
- Handler checked exact string equality: err.Error() == "filter not found"
- Wrapped error message included database error: "filter not found: no rows in result set"
- String check failed → returned 500 instead of 404

Solution: Use Go error wrapping with custom error type

Changes to internal/services/filters.go:
- Add import: "errors" package
- Add custom error variable: ErrFilterNotFound
- Update GetSavedFilterByID() to return ErrFilterNotFound instead of wrapped error
- Error defined at service layer (domain authority)

Changes to internal/handlers/filters.go:
- Update error check from string comparison to errors.Is(err, services.ErrFilterNotFound)
- Uses Go's standard error wrapping pattern
- Cleaner, more maintainable, type-safe

Architectural Benefits:
-  Service layer owns domain errors (filter not found is a filter concept)
-  Handlers only translate service errors to HTTP status codes
-  Services reusable by any caller (API, WebSocket, CLI)
-  Clean dependency direction: Handlers → Services → Database
-  Follows Go best practices for error handling

Test Results:
- GET /api/saved-filters/:id with non-existent filter now returns 404
- Error message: "filter not found"
- No information leakage about other users' filters

Fixes test failure in TestSavedFilters.
2026-03-21 23:03:43 -04:00
john-okeefe 0960e36f30 feat: add GET /api/saved-filters/:id endpoint with comprehensive tests
Implement missing GET endpoint for retrieving individual saved filters by ID.
This completes the CRUD API for saved filters and enables mobile/SPA clients
to fetch filter details on-demand.

Backend Implementation:
- Add GetSavedFilterByID() handler method (internal/handlers/filters.go)
  - Parse filter ID from URL parameter
  - Validate UUID format, return 400 for invalid IDs
  - Call service layer for business logic + ownership verification
  - Return 404 if filter not found or doesn't belong to user
  - Return 200 with filter object including filters JSONB

- Add GetSavedFilterByID() service method (internal/services/filters.go)
  - Call existing database query GetSavedFilterByID
  - Verify filter exists and belongs to user
  - Return descriptive error: "filter not found or access denied"
  - Reuses existing database query (no new SQL needed)

- Register GET /:id route (internal/router/filters.go)
  - Add route before existing GET "" route
  - Follows RESTful routing conventions

Integration Tests (cmd/server/tests/filters_test.go):
- Test success case: Create filter, retrieve by ID, verify data
- Test error case: Invalid UUID format returns 400
- Test error case: Non-existent filter returns 404
- Test error case: No authentication returns 401
- Test security case: Cross-user access returns 404 (not 403)
  - Admin creates filter, regular user tries to access
  - Uses setup.Token (admin) and setup.RegularToken
  - Verifies information leakage prevention

API Design:
- Endpoint: GET /api/saved-filters/:id
- Authentication: JWT token required
- Response format: SavedFilterResponse with filters as JSON
- Error responses: 400 (invalid ID), 401 (no auth), 404 (not found)
- Security: Returns 404 for cross-user access (hides existence)

Benefits:
- Completes CRUD API for saved filters
- Enables future mobile/SPA clients
- Follows existing handler/service/test patterns
- Comprehensive security testing
- No database changes required (reuses existing queries)

Follows PROJECT_GUIDELINES.md service layer architecture and testing patterns.
2026-03-21 22:37:19 -04:00
john-okeefe 85964ec932 fix(api): enforce user isolation on saved filters delete operation
Fix critical security issue where admin users could delete other users'
saved filters due to incorrect error handling in DELETE query.

Database Schema Changes:
- Change DeleteSavedFilter from :exec to :one (queries.sql:1747-1750)
- Add RETURNING * to return deleted row for proper error detection
- Regenerate querier.go and queries.sql.go with updated signature

Service Layer (internal/services/filters.go):
- Update DeleteSavedFilter to capture returned row (using _ to discard)
- Properly propagate pgx.ErrNoRows when no rows are deleted
- Error wrapping preserves original error for handler detection

Handler Layer (internal/handlers/filters.go):
- Add errors.Is() check for pgx.ErrNoRows (line 148)
- Return 404 Not Found when filter doesn't exist or belongs to different user
- Return 500 Internal Server Error for other database errors
- Add "errors" import (line 8)

Security Fix Details:
Before: Admin could delete user's filter → 204 No Content (SUCCESS)
After:  Admin tries to delete user's filter → 404 Not Found (DENIED)

The DELETE query uses WHERE id = @id AND user_id = @user_id, which matches
0 rows when attempting to delete another user's filter. The old :exec query
didn't return row count, so 0 affected rows looked like success. The new :one
query with RETURNING * returns pgx.ErrNoRows when no rows match, allowing
the handler to return proper 404 error.

Test Impact:
- TestSavedFilters/User_cannot_access_another_user's_filter now passes
- All 6 integration tests pass with proper user isolation enforcement

Pattern Consistency:
- Matches DeleteLibraryFolder pattern (line 99 in queries.sql)
- Uses same error handling as media handlers (errors.Is + pgx.ErrNoRows)
- Follows user-scoping pattern used throughout codebase

Related: Saved filters implementation user isolation
Security: Prevents unauthorized deletion of user data
2026-03-21 01:24:15 -04:00
john-okeefe ddfc832b68 feat(api): implement saved filters backend service and handlers
Add complete backend implementation for saved filters CRUD operations
with proper service layer architecture and RESTful API endpoints.

Service Layer (internal/services/filters.go):
- NewFiltersService() constructor following project patterns
- GetSavedFilters(): Retrieve all filters for user + resource type
- CreateSavedFilter(): Create filter with duplicate name validation
- UpdateSavedFilter(): Update filter with ownership verification
- DeleteSavedFilter(): Delete filter with user scoping

Business Logic:
- Filter name uniqueness enforced per user + resource type
- User ownership validation on all operations (JWT user_id)
- JSONB marshaling/unmarshaling for flexible filter storage
- Proper error wrapping with context messages

Handler Layer (internal/handlers/filters.go):
- NewFiltersHandler() constructor (receives db.Queries)
- GetSavedFilters: GET /api/saved-filters?resource_type=X
- CreateSavedFilter: POST /api/saved-filters
- UpdateSavedFilter: PUT /api/saved-filters/:id
- DeleteSavedFilter: DELETE /api/saved-filters/:id

Content Negotiation:
- Supports both JSON (API clients) and HTML (HTMX) responses
- wantsHTML() helper checks Accept header
- HX-Redirect header for HTMX form submissions
- Proper status codes (200, 201, 204, 400, 401, 404, 409)

Router Configuration:
- registerFiltersRoutes() function in internal/router/filters.go
- JWT middleware protection on all endpoints
- RESTful route structure: /api/saved-filters
- Registered in main router.go RegisterRoutes() function
- Added FiltersHandler to router.Config struct

Test Infrastructure:
- Added FiltersHandler to test server setup (test_helpers_test.go)
- FiltersHandler initialized in setupTestServer() function
- Router.Config includes FiltersHandler for integration tests

Code Quality:
- Follows PROJECT_GUIDELINES.md service layer patterns
- Uses database models (not custom domain models)
- JSONB returned as []byte (matches collections pattern)
- All errors wrapped with context using fmt.Errorf
- Handlers create services internally (not dependency injection)

Part of: Saved Filters Implementation (Phase 2: Backend)
Related: #saved-filters-feature
2026-03-21 00:16:10 -04:00
john-okeefe 821cd3df4c refactor(services): remove debug logging and fix directory scanning
- Remove debug printf statements from media scanner and worker
- Remove unused debug tracking variables (filesSeen, filesProcessed)
- Fix directory walk logic to properly scan the root directory itself
  (previous implementation would skip the root path entirely)

Clean up production code by removing debug artifacts and improving
the directory scanning logic to handle root-level directories correctly.
2026-03-06 10:48:36 -05:00
john-okeefe bb0158e8fb refactor: improve worker type safety and scanner reliability
Worker improvements:
- Add strongly-typed result structs for all job types
- Replace map[string]interface{} with specific result types
- Add JSON tags to JobResult for proper API serialization
- Fix processJob to handle different result types correctly
- Improve directory scan job with proper library folder resolution
- Add debug logging for scan operations

Media scanner improvements:
- Add nil checks for database in GetPollInterval and GetAutoScanEnabled
- Fix pdfcpu API call signature (add validateOnly parameter)
- Add debug logging for scanDirectory with file counters
- Improve error handling and reporting

Test fixes:
- Fix default poll interval expectation from 30s to 60s
- Add settingsCache initialization to scanner tests
- Add folders initialization to ProcessDirtyDirectories test
2026-03-06 01:52:42 -05:00
john-okeefe ba2f29983c test: add integration and unit tests for file watching
Add comprehensive test coverage for media scanning functionality:

- fsnotify_integration_test.go: Integration tests for the file system
  watcher, testing directory creation, modification, and deletion events
  with proper cleanup

- media_scanner_test.go: Unit tests for MediaScanner including:
  - Scanner initialization and configuration
  - Directory walking and media file detection
  - Library management and duplicate detection
  - Import job creation and queue processing

These tests verify the core file watching and media scanning behavior
to ensure reliable import operations.
2026-03-05 20:26:49 -05:00
john-okeefe 71c415e958 feat: enhance Worker service with job tracking capabilities
- Add Priority field to Job struct for future job prioritization
- Add HasActiveScans() method to check if any scans are currently running
- Add GetActiveJobCount() method to count running and pending jobs
- Remove unused JobTypeSync constant

These changes enable more accurate health check reporting and prepare
for future job priority queue implementation.
2026-03-05 20:26:33 -05:00
john-okeefe b3263b2611 feat: add settings cache to reduce database queries in MediaScanner
- Add SettingsCache with TTL-based invalidation (30 seconds)
- Cache scan_poll_interval_seconds and auto_scan_enabled settings
- Reduce database queries from every poll/check to once per TTL period
- Improve error handling with proper fallback values
- Simplify boolean parsing with strings.ToLower for consistency

This optimization reduces database load when checking scan settings,
which occurs frequently during media scanning operations.
2026-03-05 19:35:02 -05:00
john-okeefe 40f303b004 feat: add user-scoped WebSocket broadcasting for scan progress
- Add UserID field to Job struct for tracking job ownership
- Broadcast scan progress updates to user's WebSocket connections
- Send real-time updates during scanning (progress, files scanned, new items, errors)

This allows the frontend to display live scan progress without HTTP polling.
Scanner now associates scan jobs with requesting user for targeted updates.
2026-03-05 17:13:21 -05:00
john-okeefe 51077887a1 Remove obsolete worker_test.go
The old test file is replaced by the new test structure in cmd/server/tests/
2026-03-05 16:28:51 -05:00
john-okeefe 54bfd778db Refactor MediaScanner for improved file watching and job queue integration
- Replace event queue with dirty directories tracking (Jellyfin approach)
- Add file stability checking to wait for file writes to complete
- Add initial scan on startup to detect existing files
- Integrate with Worker job queue for directory scanning
- Change WatchChanges to return error and use atomic.Bool for state
- Add scan_mutex to prevent concurrent scans
- Add Close method with proper cleanup of resources
- Enhance polling with configurable interval
2026-03-05 16:28:40 -05:00
john-okeefe a5ac1137e5 Enhance Worker with new job types and singleton pattern
- Add WorkerInstance global singleton for global access
- Add new job types: import, convert, thumbnails, backup, analytics, sync
- Add Enqueue method for non-blocking job submission
- Add job processors for each new job type:
  - processImportJob: OPDS and Calibre import support
  - processConvertJob: EPUB to KEPUB conversion
  - processThumbnailsJob: Cover thumbnail generation
  - processBackupJob: Database backup functionality
  - processAnalyticsJob: Library and system statistics
  - processDirectoryScanJob: Directory scanning for media scanner
- Add helper getTopN function for analytics
2026-03-05 16:28:32 -05:00
john-okeefe 0a0b7f4d2e fix: Update test files to match refactored method signatures
Update test files to work with recent backend refactoring changes.

Test changes in internal/services/dashboard_service_test.go:
- Fix method name casing for FilterHiddenCollections
  - Change from filterHiddenCollections (lowercase 'f')
  - Change to FilterHiddenCollections (uppercase 'F')
  - Matches exported method signature in DashboardService
  - Line 57: Update test call to use correct exported method

Test changes in internal/handlers/dashboard_test.go:
- Update getViewAllURL test to match simplified function signature
  - Remove queryType parameter from test call
  - Function now only takes collectionName parameter
  - Aligns with refactoring to use /collections/{id} routing
  - Line 178: Update test call to use new signature

These fixes ensure tests compile and run correctly after the
collection detail page refactoring where:
1. getViewAllURL() was simplified to return /collections/{id}
2. System collections now use the same routing as user collections
2026-03-01 00:33:20 -05:00
john-okeefe c6fa217092 feat: Add library ID support to media scanner and worker
Add default library ID functionality to improve library targeting
during media scans.

Service changes in internal/services/media_scanner.go:
- Add defaultLibraryID field to MediaScanner struct
- Add SetLibraryID() method to set default library
- Modify processMediaFile() to use defaultLibraryID when set
  - Prioritizes defaultLibraryID over folder-based library detection
  - Provides explicit library targeting for scans

Service changes in internal/services/worker.go:
- Add libraryUUID conversion from string to pgtype.UUID
- Call scanner.SetLibraryID() before ScanFolders()
  - Ensures scanner respects the job's library ID

These changes enable more precise library targeting during media scans,
allowing scans to be directed to specific libraries rather than relying
solely on folder-based detection.
2026-03-01 00:29:39 -05:00
john-okeefe 0b666f3fdd feat: Add collection detail page with /collections/:id route
Add comprehensive collection detail page that works for both system collections
(continue-reading, recently-added, not-started) and user collections.

Backend changes:
- Add new /collections/:id route in internal/router/frontend.go
  - Fetches collection using GetCollection with UUID parameter
  - Determines collection type from QueryType field
  - Resolves library_id for system collections
  - Converts database.MediaItems to handlers.BookInfo for display
  - Renders CollectionDetail template with collection and books data

- Update SectionData struct in internal/handlers/collections.go
  - Add CollectionID string field for view all links

- Update BuildSections() in internal/handlers/dashboard.go
  - Pass CollectionID to SectionData for proper link generation

- Simplify getViewAllURL() in internal/handlers/dashboard.go
  - Return /collections/{collectionID} instead of /section/{type}
  - Works uniformly for both system and user collections

Frontend changes:
- Fix CollectionDetail template in templates/collections.templ
  - Fix broken div nesting causing compilation error
  - Add null check for CoverImagePath to prevent broken images
  - Update aspect ratio to modern aspect-[3/4] syntax
  - Use responsive widths (w-16 sm:w-20) for mobile/desktop
  - Improve card layout with horizontal flex structure
  - Add placeholder image fallback for books without covers
  - Remove erroneous renderBooks() function call

This change aligns with the backend update where system collections are
now pre-made user collections in the database with query_type fields.
All collections can now use the same CollectionDetail template for a
consistent viewing experience.
2026-03-01 00:28:54 -05:00
john-okeefe 4bf8e933df test: add unit and integration tests for scan settings
- Add unit tests for MediaScanner.GetPollInterval and GetAutoScanEnabled
- Add integration tests for scan-settings API endpoints
- Update validation test cases to use seconds (1-3600) instead of minutes
- Fix worker.go to use new NewMediaScanner signature
2026-02-28 14:09:06 -05:00
john-okeefe ce72781ec0 refactor(scanner): make poll interval dynamic from database
- Add GetPollInterval() method to MediaScanner to read from database
- Add GetAutoScanEnabled() method to check if auto-scan is enabled
- Remove ScanPollIntervalSeconds from config (now DB-driven)
- Update NewMediaScanner signature to not require interval parameter
- Remove SCAN_POLL_INTERVAL_SECONDS from docker-compose env var
2026-02-28 12:57:06 -05:00
john-okeefe 4d0d86838a refactor(core): remove scheduler and simplify app lifecycle
- Delete scheduler.go and scheduler_test.go (no longer needed)
- Simplify App struct by removing Handler interface dependency
- Remove StartScheduler/StopScheduler from app lifecycle
- Update main.go to not pass handler to app constructor
- Remove scheduler mock from app tests, simplify test coverage
2026-02-28 12:56:59 -05:00
john-okeefe 286d0b5e06 feat(scanner): convert scan poll interval from minutes to seconds
- Rename SCAN_POLL_INTERVAL_MINUTES to SCAN_POLL_INTERVAL_SECONDS in config
- Update MediaScanner to accept interval in seconds instead of minutes
- Adjust default polling interval from 3 minutes to 30 seconds for faster response
- Add debug logging for fsnotify events to aid troubleshooting file watching

This change improves media file detection responsiveness by reducing the
polling interval from minutes to seconds, while maintaining the file
watcher as the primary detection mechanism.
2026-02-28 01:59:35 -05:00
john-okeefe 037e7c1189 feat(scanner): add debounced file watching with polling fallback
- Implement event queue with 3-second debouncing for file system events
- Add configurable polling fallback (default 3 min) via SCAN_POLL_INTERVAL_MINUTES
- Add SyncFilesystemWithDatabase to detect orphaned DB entries and new files
- Integrate utils.ResolveMediaURL for consistent media file path resolution
- Add COOKIE_SECURE env var with SameSite=LaxMode for session cookies
- Update media handler to properly decode URL paths for file serving
- Refactor scanner initialization to accept poll interval configuration
2026-02-28 01:16:27 -05:00
john-okeefe 6dd8e441d1 style: fix code alignment and indentation consistency
- Correct indentation in goroutine leak test setup block
- Align struct field tags in BookMatch and all matching methods for
  consistent column-style formatting (media_item_id, bookhoard_uuid,
  confidence, match_method)
- Improves code readability and adheres to project indentation guidelines
2026-02-27 17:09:05 -05:00