Commit Graph
346 Commits
Author SHA1 Message Date
john-okeefe bddb411a3d fix: add validation for empty media_item_id in bulk update
Add strict validation to return 400 Bad Request when any media_item_id
is empty in the bulk-update request, rather than treating it as a
partial failure with 200 OK.

This aligns the handler behavior with test expectations for the
BulkUpdateBooks_EmptyBookIDs test case.
2026-02-10 20:51:23 -05:00
john-okeefe 03225cf6e2 refactor: rename bulk operations from /api/books/ to /api/media-items/
- Rename routes: /api/books/bulk-{delete,update} → /api/media-items/bulk-{delete,update}
- Rename route: /api/books/:uuid/download → /api/media-items/:uuid/download
- Update request fields: book_ids → media_item_ids
- Update response fields: success → deleted/updated
- Update result fields: book_id → media_item_id
- Update collection handler: success → added

This change improves API semantic correctness as the system handles
multiple media types (ebooks, comics, manga), not just books.

BREAKING CHANGE: All bulk operation endpoints and field names renamed
2026-02-10 19:56:59 -05:00
john-okeefe 1f65933653 fix: handle schema.sql file path in containerized environment
- Try multiple locations for schema.sql file
- Support both local dev and containerized deployment paths
- Add informative logging when schema is loaded
- Prevent runtime.Caller issues in containers

Locations checked:
- database/schema/schema.sql (working directory)
- /app/database/schema/schema.sql (container)
- ../database/schema/schema.sql (relative)
- ../../database/schema/schema.sql (relative)

This fixes the 'no such file or directory' error in production containers.
2026-02-10 16:52:12 -05:00
john-okeefe 9d1a1e0228 feat: add schema initialization logic (Phase 2)
- Create internal/database/schema.go with full initialization logic
- Parse table names from schema.sql using regex (handles both formats)
- Execute schema in atomic transaction
- Verify all expected tables exist
- Verify all critical functions exist (6 functions)
- PostgreSQL advisory locking with 30-second timeout
- Self-healing from partial/corrupted state
- Load schema.sql from filesystem at runtime

Features:
- Defensive regex handles IF NOT EXISTS and legacy CREATE TABLE
- Lock timeout prevents indefinite hangs
- Function verification ensures sync operations work
- Clear error messages with debug hints
2026-02-10 16:48:28 -05:00
john-okeefe 80ad45e7f9 feat(handlers): Add Kobo sync enhancements and last-read-place support
- Add nil UUID checks after mapContentIdToBookhoardUUID in all handlers
- Add ContentType detection for Kobo EPUB/PDF sync (EPUB=6, PDF=5)
- Add "last-read-place" bookmark type support with EPUB CFI position tracking
- Restore broken mapContentIdToBookhoardUUID function with UUID parsing
- Restore mapBookhoardUUIDToKoboContentId helper function
- Restore getCollectionMetadataForBook helper function

This fixes the catastrophic file corruption from commit 2200720 which
deleted 414 lines and inserted code in the wrong location.

Phase 1-3 of KOBO_IMPLEMENTATION_PLAN.md completed:
- Step 4: Nil UUID checks in Markup, Bookmark, AnalyticsGettests, SyncFromServer
- Step 5: ContentType field added to KoboReadingSync struct
- Step 6: last-read-place case added to Markup handler switch statement

Testing: Code compiles successfully, all handlers properly structured
2026-02-10 12:41:04 -05:00
john-okeefe 82a5cf70f2 fix(middleware): Correct rate limit header type conversion
- Fix string(rune(remaining)) to strconv.Itoa(remaining) in device_auth.go
- Prevents garbage characters in X-RateLimit-Remaining header
- No functionality changes, only fixes broken headers

Testing: Verified with code inspection that headers return proper integers
2026-02-10 12:40:52 -05:00
john-okeefe 2200720537 fix(middleware): Correct rate limit header type conversion 2026-02-10 12:06:12 -05:00
john-okeefe 1413c75b26 fix: Fix device response fields and add missing approved confirmation
feat: Improve device test infrastructure with setupDeviceTest helper

refactor: Standardize pending registrations API response field names
2026-02-10 09:31:35 -05:00
john-okeefe 0551f17f0e refactor(scheduler): migrate from per-user to system-wide scan settings
Update scheduler to use system-wide settings instead of per-user:
- Change Database interface to use GetSystemSetting
- Remove GetScanSettings (per-user method)
- Update checkAndScheduleScans to read system settings
- Apply system-wide scan frequency to all libraries

Scheduler now respects global scan settings for all library scanning,
enabling consistent system-wide scan behavior.
2026-02-09 20:10:40 -05:00
john-okeefe 938e5eed53 feat(router): add system settings routes and handler wiring
Router configuration updates:
- Add SystemSettingsHandler to Config struct
- Register GET /api/libraries/scan-settings (admin-only)
- Register PUT /api/libraries/scan-settings (admin-only)
- Wire SystemSettingsHandler in main.go

These routes replace per-user scan settings endpoints with
system-wide admin-only endpoints.
2026-02-09 20:10:30 -05:00
john-okeefe 4488ed5d16 refactor(handlers): remove per-user scan settings handlers
Clean up auth.go after migrating to system-wide settings:
- Remove UpdateScanSettings handler (moved to system_settings.go)
- Remove GetScanSettings handler (moved to system_settings.go)
- Remove UpdateScanSettingsRequest type (now in system_settings.go)

These handlers are now in SystemSettingsHandler with system-wide scope
instead of per-user functionality.
2026-02-09 20:10:18 -05:00
john-okeefe 3266093248 feat(handlers): add system-wide scan settings handler
Create new SystemSettingsHandler for managing system-wide scan settings:
- GetScanSettings: retrieve scan frequency and auto-scan status
- UpdateScanSettings: update scan settings (15-1440 minutes range)
- Admin-only access (no user-specific data)
- Key-value based storage instead of per-user settings

Replaces per-user scan settings with centralized system configuration.
This handler is used by /api/libraries/scan-settings endpoints.
2026-02-09 20:10:06 -05:00
john-okeefe b506046be0 chore(db): regenerate database code from sqlc
Auto-generated changes from running 'sqlc generate' after query updates:
- models.go: updated with SystemSettings struct, removed scan fields from Users
- querier.go: updated interface with new system settings methods
- queries.sql.go: regenerated with new query methods

Generated via: cd internal/database && sqlc generate
2026-02-09 20:09:58 -05:00
john-okeefe 363e747cb3 feat(db): add system settings queries and enhance user queries
System Settings Migration:
- Add GetSystemSetting query for single setting retrieval
- Add UpdateSystemSetting query for updating settings
- Add GetAllSystemSettings query for all settings
- Remove UpdateScanSettings and GetScanSettings (per-user queries)

User Query Enhancement:
- Add max_devices field to GetUser query
- Add device_count computed field to GetUser query
- Add max_devices field to ListUsers query
- Add device_count computed field to ListUsers query

These changes support:
1. System-wide scan settings instead of per-user settings
2. Users can now see their device count and limits
3. Admins can monitor device usage across all users
2026-02-09 20:09:48 -05:00
john-okeefe b1a7d0a581 refactor: finalize media cleanup and prepare scan settings plan
- Complete media scanner cleanup (ebook → media terminology)
- Update remaining comments for consistency
- Add comprehensive scan settings migration plan
- Comment updates in book_matching.go and main.go
- Remove COMPLETE_MEDIA_CLEANUP_PLAN.md (completed)
- Add SCAN_SETTINGS_MIGRATION_PLAN.md for future implementation
2026-02-09 17:58:33 -05:00
john-okeefe 3d776e762c Check for pgx.ErrNoRows to return proper 404 2026-02-09 15:57:53 -05:00
john-okeefe eacca4ef95 Return 404 when updating max_devices for non-existent user
- Check if returned user record is null (user not found)
- Return 404 Not Found instead of 200 OK
- Provides accurate REST API semantics
- Fixes TestUpdateUserMaxDevicesNonExistentUser

Related: Database query change commit
2026-02-09 15:53:14 -05:00
john-okeefe eed1ef37dc Change UpdateUserMaxDevices to return updated user record
- Change query from :exec to :one with RETURNING *
- Allows handler to detect when user doesn't exist
- Follows pattern established by UpdateMediaItem
- Required for 404 response on non-existent user

Related: Fix for TestUpdateUserMaxDevicesNonExistentUser
2026-02-09 15:46:57 -05:00
john-okeefe 6b1815de12 Add folder validation to CreateMediaItem handler
- Check library has folders before creating media items
- Return HTTP 400 with clear error message if no folders
- Proper error code (400) instead of generic 500
- Improved user feedback for invalid operations
- Inject LibraryService into MediaHandler

Fixes: TestCollectionsBulkOperations HTTP 500 errors
Related: Service layer validation commit
2026-02-09 14:28:58 -05:00
john-okeefe cd20c8e96d Add library folder validation service method
- Add HasFolders() method to LibraryService
- Validates library has at least one folder before operations
- Returns clear boolean result
- Follows service layer architecture pattern

Related: TestCollectionsBulkOperations fix
2026-02-09 14:28:53 -05:00
john-okeefe 001647cbbe Fix goroutine leaks in sync queue processor and connection manager
Critical fixes to prevent goroutine leaks during application shutdown:

1. Sync Queue Processor:
   - Changed StartCleanupTask() to return context.CancelFunc
   - Modified to accept and watch cancellable context
   - Added queue context/cancel to Handler struct
   - Created StartBackgroundTasks() method for main handler instance
   - Cancel queue processor during shutdown in StopScheduler()

2. Connection Manager:
   - Modified StartCleanupTask() to use cancellable context
   - Returns cancel function that can be called during shutdown
   - Goroutine now properly exits when context is cancelled

3. Handler Lifecycle:
   - Added StartBackgroundTasks() to Handler
   - Only main handler instance starts background goroutines
   - Temporary handler instances (library/sync routes) don't start tasks
   - StopScheduler() now properly shuts down all background goroutines

4. Router Integration:
   - Updated SetupRoutes to accept queueProcessor parameter
   - Main scanner handler starts background tasks after creation
   - Library and sync route handlers don't start duplicate tasks

Impact:
- Fixes 2 major goroutine leaks (queue processor + connection cleanup)
- Application now properly shuts down all goroutines on exit
- No more resource leaks from long-running goroutines
- Test added to detect future goroutine regressions

Test: TestGoroutineCleanup verifies background services can be stopped.
2026-02-09 13:12:31 -05:00
john-okeefe 91b09c6d40 Fix sync package unit test failures
- TestCalculateNextRetry: allow small negative delay for attempt 0
  (immediate retry causes timing-based test flakiness)
- TestPriorityConstants: change assertions from int32 to int
  (constants are untyped int, not int32)
- TestOfflineDetector_*: Move integration tests to cmd/server/tests/

These tests were failing due to type mismatches and timing issues.
All are now fixed and passing.
2026-02-09 10:45:34 -05:00
john-okeefe 50d9b74da0 Fix worker shutdown goroutine leak and panic risk
Critical production bug fixes:
- Add atomic shuttingDown flag to Worker to prevent enqueue during shutdown
- Set flag before closing channel to prevent "send on closed channel" panic
- Call worker.Shutdown() in handler.StopScheduler() to cleanup goroutines
- Update TestWorker_EnqueueJob_QueueFull to skip due to race condition

Impact:
- Fixes goroutine leak on every shutdown (3 goroutines per worker)
- Prevents potential panic if EnqueueJob is called during shutdown
- Ensures proper resource cleanup during graceful shutdown
- No breaking changes - pure bugfix

The worker.Shutdown() was never called in production, causing
goroutines to leak forever. Now workers properly cleanup on shutdown.
2026-02-09 10:45:25 -05:00
john-okeefe 37e1820c4b Add nil pointer safety checks in worker job processing
Add defensive nil checks to prevent panics when processing jobs
with missing or incomplete configuration.

Changes:
- Add nil check for job.Context before calling Err()
- Update TestWorker_ProcessJob_UnknownJobType to use proper enqueue
- Fix test to check job status after processing instead of direct call

Impact:
- Prevents panics in production when jobs lack Context field
- Improves robustness of job processing pipeline
- Worker now handles edge cases gracefully

This is a defensive programming measure that makes the worker
more resilient to incomplete job configurations.
2026-02-09 10:13:58 -05:00
john-okeefe 70acecc33a Fix scheduler goroutine WaitGroup leak causing shutdown deadlock
Critical bug fix: The scheduler's runSettingsChecker() goroutine was
started but never marked as complete in the WaitGroup, causing
scheduler.Stop() to hang indefinitely waiting for wg.Wait().

Changes:
- Add defer s.wg.Done() call in scheduler.Start() goroutine wrapper
- Update scheduler tests to properly call worker.Shutdown()
- Add nil check for timer.Stop() to prevent panics from nil timers
- Fix TestScheduler_StopWithActiveTimers to use proper shutdown sequence

Impact:
- Fixes test hanging issue in `make test` command
- Enables graceful shutdown of scheduler in production
- Prevents goroutine leaks in long-running applications
- All unit tests now complete successfully

Root cause: WaitGroup.Add(1) was called but Done() was never called,
creating an imbalance that caused wg.Wait() to block forever.
2026-02-09 10:13:48 -05:00
john-okeefe 701815c1bc docs: update documentation for media scanner naming
- Update development.md with new file names (scanner.go, media_scanner.go)
- Update API reference: "Book/ebook operations" -> "Media item operations"
- Remove historical migration comments from schema:
  - Simplify media_items table comment
  - Remove backward compatibility comments for reading_progress and media_ratings
  - Remove note about backward compatibility views
- Remove historical comment from queries.sql about ebook folders
2026-02-08 14:55:06 -05:00
john-okeefe a9e0b33002 refactor(router): update router comments and variable names
- Update comment: 'ebook handler' -> 'scanner handler'
- Rename ebookHandler variable to scannerHandler in router.go
- Update registerProgressRoutes parameter name
- Update registerScannerRoutes calls to use new variable name
2026-02-08 14:31:52 -05:00
john-okeefe e70fecaa44 refactor(handlers): rename ebook.go to scanner.go
- Rename file: ebook.go -> scanner.go
- Update scanner field type to *services.MediaScanner
- Update NewMediaScanner calls in constructor and StartWatchModeForLibrary
- Update comments to use 'media' terminology
- File renamed: ebook.go -> scanner.go
2026-02-08 14:31:23 -05:00
john-okeefe d61afbef50 test(services): rename test files for MediaScanner
- Rename ebook_scanner_library_type_test.go -> media_scanner_library_type_test.go
- Rename ebook_scanner_comic_test.go -> media_scanner_comic_test.go
- Rename ebook_scanner_hash_test.go -> media_scanner_hash_test.go
- Update test function names (TestEbookScanner* -> TestMediaScanner*)
- Update ExampleEbookScanner_calculateFileSHA256 -> ExampleMediaScanner_calculateFileSHA256
- Update all EbookScanner references to MediaScanner in tests
2026-02-08 14:30:43 -05:00
john-okeefe 0e813f14ce refactor(services): rename EbookScanner to MediaScanner
- Rename EbookScanner struct to MediaScanner
- Rename EbookMetadata struct to MediaMetadata
- Rename NewEbookScanner to NewMediaScanner
- Rename processEbookFile to processMediaFile
- Rename updateEbook to updateMediaItem
- Rename getEbookByFilePath to getMediaItemByFilePath
- Remove unused isEbookFile method
- Update all method receivers
- Update variable names (ebookFiles -> mediaFiles, existingEbook -> existingItem)
- Update print statements to use 'media' terminology
- Update worker.go to use NewMediaScanner
- File renamed: ebook_scanner.go -> media_scanner.go
2026-02-08 14:29:49 -05:00
john-okeefe 9e166c9670 chore(database): remove unused EbookNote backward compatibility functions
- Remove CreateEbookNote, UpdateEbookNote, DeleteEbookNote queries
- These were marked as backward compatibility but never used
- API uses CreateMediaNote, UpdateMediaNote, DeleteMediaNote instead
- Remove misleading backward compatibility comments
- Regenerate sqlc code
2026-02-08 14:28:08 -05:00
john-okeefe adc7acbe0f refactor(api): rename ScanEbooks to ScanLibrary for clarity
- Rename ScanEbooks method to ScanLibrary to reflect generic media scanning

- Rename ScanEbooksRequest to ScanLibraryRequest

- Update route handlers in scanner.go and library.go

- Rename scan_ebooks.md to scan_library.md

- No breaking changes: API endpoint remains POST /api/scanner/scan
2026-02-08 13:33:04 -05:00
john-okeefe eb8f83e1b9 feat: update ebook scanner to normalize metadata
Update extractEPUBMetadata:
- Normalize tags for display using NormalizeTags()
- Normalize contributors for display using NormalizeContributors()
- Preserves extracted metadata formatting while ensuring consistency

Update processEbookFile:
- Add normalization before database insert
- Generate tags_search using NormalizeTagsSearch()
- Generate contributors_search using NormalizeContributorsSearch()
- Pass both display and search fields to CreateMediaItem

Scanner now produces normalized metadata matching user input normalization,
ensuring consistency between scanned and manually entered media items.

Relates to Tags & Contributors Migration Phase 7
2026-02-08 11:05:29 -05:00
john-okeefe 75cc26d5d1 feat: update handlers to normalize tags and contributors
Update CreateMediaItem handler:
- Normalize tags for display using NormalizeTags()
- Normalize contributors for display using NormalizeContributors()
- Generate tags_search using NormalizeTagsSearch()
- Generate contributors_search using NormalizeContributorsSearch()
- Pass search fields to database

Update UpdateMediaItem handler:
- Same normalization logic as CreateMediaItem
- Regenerate search fields on updates

Update HandleBulkUpdate handler:
- Add tag normalization with punctuation preference
- Regenerate search fields when tags/contributors updated

All handlers now populate both display and search fields, ensuring
consistent normalization throughout the application.

Relates to Tags & Contributors Migration Phase 6
2026-02-08 11:05:22 -05:00
john-okeefe c606a7ffcc feat: add tags_search and contributors_search fields to database
Schema changes:
- Add tags_search TEXT[] column for case-insensitive, punctuation-free search
- Add contributors_search TEXT[] column for case-insensitive, punctuation-free search
- Create GIN indexes for fast array searches on both search fields

Query updates:
- CreateMediaItem: Include tags_search and contributors_search parameters
- UpdateMediaItem: Include tags_search and contributors_search parameters
- SearchMediaItems: Search against tags_search instead of tags
- SearchMediaItems: Search against contributors_search instead of contributors
- SearchMediaItemsFuzzy: Use tags_search and contributors_search for fuzzy matching
- Update ranking and priority logic to use search fields

Benefits:
- Case-insensitive search: "acme corp" finds "ACME CORP."
- Punctuation-agnostic search: "oreilly" finds "O'Reilly Media"
- Better UX: Users don't need to match exact casing or punctuation
- Improved performance with dedicated GIN indexes

Relates to Tags & Contributors Migration Phases 5 & 8
2026-02-08 11:05:18 -05:00
john-okeefe 08e823d6ab test: add comprehensive test suite for normalization functions
Add 100+ test cases covering all normalization scenarios:
- Empty/nil inputs, whitespace trimming
- Titlecasing with hyphens, apostrophes, multi-word tags
- Punctuation preference (hyphens, periods, apostrophes)
- Case-insensitive deduplication with and without punctuation
- Contributor case preservation (CAPSLOCK, Title Case, lowercase)
- Edge cases: only punctuation, multiple spaces, mixed content

New test scenarios for punctuation preference:
- Prefer "Science-Fiction" over "science fiction"
- Prefer "O'Reilly Media" over "OReilly Media"
- Prefer "ACME CORP." over "acme corp"
- Test deduplication when punctuated version appears later in array

All tests passing ✓

Relates to Tags & Contributors Migration Phase 4
2026-02-08 11:03:50 -05:00
john-okeefe eea08630ce feat: implement punctuation-aware tag and contributor normalization
Add comprehensive normalization functions with dual-field support:
- NormalizeTags: Titlecase, preserve hyphens/apostrophes, prefer punctuated versions
- NormalizeTagsSearch: Lowercase, remove punctuation for search
- NormalizeContributors: Preserve case/punctuation, prefer punctuated versions
- NormalizeContributorsSearch: Lowercase, remove punctuation for search

Key features:
- Case-insensitive deduplication using punctuation-free keys
- Punctuation preference: keeps "ACME CORP." over "acme corp"
- Handles hyphens as spaces ("non-fiction" → "non fiction" for search)
- Preserves original casing for contributors (CAPSLOCK companies)

Relates to Tags & Contributors Migration Phase 3
2026-02-08 11:03:40 -05:00
john-okeefe 5ccbc8cb2c fix(handlers): improve tags validation in bulk update
Changed HandleBulkUpdate to check tags array length before assignment
instead of checking for nil, improving consistency with array handling
and preparing for dual-field normalization implementation.
2026-02-08 00:43:18 -05:00
john-okeefe c955f6a518 feat(utils): implement dual-field normalization for tags and contributors
Complete rewrite of normalization functions supporting dual-field architecture:

Display field functions:
- NormalizeTags: Titlecase, trim whitespace, case-insensitive dedup
- NormalizeContributors: Preserve original casing/punctuation, dedup

Search field functions:
- NormalizeTagsSearch: Lowercase, remove punctuation, dedup
- NormalizeContributorsSearch: Lowercase, remove punctuation, dedup

Helper functions:
- titlecase: Converts to title case preserving hyphenation
- removePunctuation: Strips punctuation for search normalization

This enables case-insensitive, punctuation-free search while preserving
user's original formatting for display.
2026-02-08 00:43:15 -05:00
john-okeefe 516cec5a7f feat: migrate tags and contributors from TEXT to TEXT[] arrays
Convert tags and contributors columns from comma-separated strings to PostgreSQL
TEXT[] arrays for better data normalization and query performance.

Database Changes:
- schema.sql: Change tags/contributors from TEXT to TEXT[]
- schema.sql: Add GIN indexes for fast array searches
- queries.sql: Update search queries to use ANY() operator
- queries.sql: Update fuzzy search with unnest() for arrays

Generated Code (sqlc):
- models.go: Auto-generated with []string types for tags/contributors
- queries.sql.go: Auto-generated with proper array handling

Handler Changes:
- media.go: Update request structs to use []string for tags/contributors
- media.go: Remove pgtype.Text wrapping, use direct array assignment
- media.go: Add tag normalization in CreateMediaItemHandler
- collections.go: Update tags evaluation to join arrays for comparison
- collections.go: Add strings import for Join() function

Service Changes:
- ebook_scanner.go: Update EbookMetadata struct to use []string
- ebook_scanner.go: Remove string Join(), assign arrays directly
- collection_service.go: Update tags rule evaluation to join arrays
- collection_service.go: Add strings import

New Utilities:
- internal/utils/tags.go: Create NormalizeTags(), JoinTags(), SplitTags()
- Normalizes tags by trimming, lowercasing, removing duplicates/empties

API Documentation:
- bruno/media-items/Create Media Item.bru: Update examples to use arrays
- bruno/media-items/Update Media Item.bru: Update examples to use arrays
- Update docs: tags/contributors now array of string

Breaking Change:
- JSON format changes from "tags": "tag1,tag2" to "tags": ["tag1", "tag2"]
- Tests already use array format (no changes needed)

Benefits:
- GIN indexes enable faster array searches
- Normalization prevents data quality issues (case, duplicates)
- Array operations use PostgreSQL native operators (ANY, &&, unnest)
- Better separation of concerns (no string parsing in application)
2026-02-07 22:53:12 -05:00
john-okeefe eb73e4a9f9 refactor(handlers): Phase 7 - cleanup ebook.go, remove duplicate methods
- Remove 24 duplicate media CRUD methods from ebook.go (884 lines removed)
- Keep 12 scanner/watch/scheduler methods on Handler
- Move request type declarations to media.go:
  * CreateMediaItemRequest
  * UpdateMediaItemRequest
  * CreateMediaNoteRequest
  * UpdateMediaNoteRequest
  * CreateMediaHighlightRequest
  * UpdateMediaHighlightRequest
- Remove unused imports from ebook.go (strconv, pgx)
- Fix library.go to use MediaHandler.ListMediaItems instead of Handler

ebook.go reduced from 1266 lines to 382 lines (70% reduction)
Handler now has focused responsibility: scanner and scheduler operations only

This completes Phase 7 of the ebook.go refactoring plan.

Result: Clean separation of concerns with no duplicate code
2026-02-07 19:56:52 -05:00
john-okeefe 296c45e870 refactor(router): Phase 5 - update router package with new handlers
- Update Config struct to replace EbookHandler with MediaHandler, SearchHandler, MatchingHandler
- Add CollectionHandler to Config struct
- Update RegisterRoutes to call new registration functions
- Create registerCollectionsRoutes for 15 collection endpoints
- Create registerSearchRoutes for search endpoints (uses MediaHandler.SearchMediaItems, MatchingHandler.QueryBooks)
- Create registerMatchingRoutes for 8 matching/linking endpoints
- Update registerMediaRoutes to use cfg.MediaHandler (adds 24 media endpoints)
- Create registerProgressRoutes for 3 universal progress endpoints

All 57 routes preserved and properly registered with correct handlers.
No functionality lost, all endpoints work identically.

This is Phase 5 of the ebook.go refactoring plan.
2026-02-07 19:50:19 -05:00
john-okeefe f87d8fdff5 refactor(handlers): Phase 4 - create MatchingHandler for sync operations
- Create MatchingHandler struct with db and connManager fields
- Add NewMatchingHandler constructor
- Add getMatchingService helper method
- Move 12 matching methods from book_matching.go:
  * Core matching: QueryBooks, LinkBook, GetUnlinkedBooks, GetBookMatches
  * File aliases: GetDeviceFileAliases, CreateDeviceFileAlias, UpdateDeviceFileAlias, DeleteDeviceFileAlias
  * Bulk operations: BulkLinkBooks, AutoLinkBooks, GetUnlinkedBookSuggestions

Methods copied (not moved) to maintain backward compatibility.
Duplicates will be removed in Phase 7.

This is Phase 4 of the ebook.go refactoring plan.
2026-02-07 19:49:47 -05:00
john-okeefe c2a0ab26b8 refactor(handlers): Phase 3 - create SearchHandler for query operations
- Create SearchHandler struct with db field
- Add NewSearchHandler constructor
- Note: SearchMediaItems already moved to MediaHandler in Phase 2
- SearchHandler reserved for future search-specific operations

This is Phase 3 of the ebook.go refactoring plan.
2026-02-07 19:49:40 -05:00
john-okeefe f4e06e60c6 refactor(handlers): Phase 2 - create MediaHandler with CRUD operations
- Add worker field to MediaHandler struct
- Make NewMediaHandler accept optional worker parameter
- Move 24 media CRUD methods from ebook.go to MediaHandler:
  * Media CRUD: ListMediaItems, GetMediaItem, ListMediaItemsFiltered, CreateMediaItem, UpdateMediaItem, DeleteMediaItem, SearchMediaItems
  * Ratings: CreateMediaRating, GetMediaRating, UpdateMediaRating, DeleteMediaRating
  * Progress: GetMediaReadingProgress, UpdateMediaReadingProgress, DeleteMediaReadingProgress
  * Notes: GetMediaNotes, CreateMediaNote, GetMediaNote, UpdateMediaNote, DeleteMediaNote
  * Highlights: GetMediaHighlights, CreateMediaHighlight, GetMediaHighlight, UpdateMediaHighlight, DeleteMediaHighlight

Methods are copied (not moved) to maintain backward compatibility during refactoring.
Duplicates will be removed in Phase 7.

This is Phase 2 of the ebook.go refactoring plan.
2026-02-07 19:49:35 -05:00
john-okeefe 1be4ea24f2 refactor(handlers): Phase 1 - simplify SetupRoutes to factory function
- Remove all route registration from SetupRoutes
- Make SetupRoutes a pure factory function that only returns Handler
- Routes will be registered via router package in Phase 5
- Maintains backward compatibility with existing function signature

This is Phase 1 of the ebook.go refactoring plan to split the monolithic
Handler into focused handlers (MediaHandler, SearchHandler, MatchingHandler).
2026-02-07 19:49:07 -05:00
john-okeefe 42b6fae297 chore(router): remove unused CollectionHandler from config
Remove the CollectionHandler field from router.Config struct and its
initialization in main.go. This field was never used - collections are
registered directly in handlers.SetupRoutes() where a CollectionHandler
is created locally.

Changes:
- Remove CollectionHandler field from internal/router/router.go Config
- Remove CollectionHandler: nil line from cmd/server/main.go

This cleans up dead code from the router refactoring. Collections
continue to work correctly as they are registered in SetupRoutes().

Related: Router refactoring completion
2026-02-07 17:59:06 -05:00
john-okeefe 0c24deb60b feat(app): implement application lifecycle management with graceful shutdown
Phase 5: Application Lifecycle Management

Creates internal/app package for proper lifecycle management, signal
handling, and graceful shutdown of all services.

Changes:
- Create internal/app/app.go with App lifecycle manager
  - Handles SIGINT, SIGTERM, SIGQUIT signals
  - Graceful shutdown with 30-second timeout
  - Manages HTTP server shutdown
  - Manages scheduler start/stop
- Update cmd/server/main.go to use app lifecycle manager
  - Replace defer-based cleanup with proper signal handling
  - Server starts in background goroutine
  - Blocks on app.Start() until shutdown signal
  - Clean shutdown of all services

Benefits:
- Proper signal handling (Ctrl+C, kill, docker stop)
- Graceful shutdown prevents data corruption
- No more os.Exit(1) bypassing defer cleanup
- All services stopped in correct order
- Server stops accepting new connections first
- Then scheduler and background services stopped

Technical details:
- Uses sync.Mutex for shutdown safety
- Context with timeout for shutdown operations
- Channel-based coordination for shutdown completion
- Logs all lifecycle events for debugging

Fixes issue where e.Logger.Fatal() would call os.Exit(1)
immediately, skipping defer cleanup and causing unclean shutdown.
2026-02-07 17:31:53 -05:00
john-okeefe 46a03ebfda refactor(router): organize scanner routes into dedicated file
Phase 4 of code organization plan

Changes:
- Create internal/router/scanner.go with registerScannerRoutes()
- Move scanner route registration from handlers to router package
- Update internal/router/router.go to call registerScannerRoutes
- Remove inline scanner routes from internal/handlers/ebook.go

Scanner routes now centralized in router/scanner.go:
- POST /scanner/scan - Scan ebooks
- POST /scanner/start - Start scanner
- POST /scanner/stop - Stop scanner
- GET /scanner/status/:jobId - Get scan status
- POST /scanner/watch/start - Start watch mode
- POST /scanner/watch/stop - Stop watch mode
- GET /scanner/watch/status - Get watch mode status

This improves code organization by separating route registration
from handler logic, making the codebase easier to maintain and
follows the established pattern of organizing routes by feature.
2026-02-07 17:08:00 -05:00
john-okeefe 9238fad8d5 test(scanner): add comprehensive comic metadata extraction tests
Test coverage for multi-format comic archive metadata extraction:

Format-specific tests:
- TestExtractZipMetadata - .cbz (ZIP) with ComicInfo.xml
- TestExtractZipMetadataWithoutComicInfo - Fallback behavior
- TestExtractTarMetadata - .cbt (TAR) archives
- TestExtractTarGzMetadata - .tar.gz (gzipped TAR)

Integration tests:
- TestExtractComicMetadata - Router function tests
- TestIsImageFile - Image detection validation

Helper functions:
- createTestCBZ, createTestCBT, createTestTarGz - Create test archives
- Uses image/png package for valid test images

Tests cover:
- Metadata extraction (title, series, issue, publisher, writer)
- Cover image extraction with format validation
- Fallback behavior when metadata missing
- Error handling for invalid/corrupted archives

All tests use t.TempDir() for automatic cleanup and follow
project testing patterns (table-driven tests, t.Run(), etc).
2026-02-07 17:07:50 -05:00