Commit Graph
276 Commits
Author SHA1 Message Date
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 eb2da1e05b fix: Change library ordering to oldest-first
Change library ordering in dropdown from DESC to ASC to display
libraries in creation order (oldest first).

Database changes in internal/database/queries/queries.sql:
- Modify GetUserLibraries query ORDER BY clause
  - Change from ORDER BY l.created_at DESC to ASC
  - Displays oldest libraries first in dropdown

This provides a more intuitive ordering where users see their
first-created libraries at the top of the list.
2026-03-01 00:29:27 -05:00
john-okeefe 62d3d50140 fix: Dashboard modal and slider library-specific behavior
Fix multiple issues with dashboard customization modal and slider
not working correctly per library.

Frontend changes in web/src/dashboard.ts:
- Fix openDashboardSettings() to use current library ID
  - Add library_id parameter to dashboard preferences API call
  - Show toast error message on API failure instead of opening modal
  - Prevent opening modal with stale/inaccurate data

- Fix slider query parameter mismatch
  - Change from 'libraryId' to 'library_id' to match backend API
  - Fix DOM query from collectionList.querySelector to document.querySelector
  - Ensure slider targets correct input element

- Fix saveDashboardSettings() to refresh current library
  - Fetch current library data before saving preferences
  - Use library_id from current library, not from URL
  - Show toast error message on save failure
  - Keep modal open on error for user to retry

- Add localStorage persistence for selected library
  - Store selectedLibrary in localStorage after switching
  - Enables persistence across page refreshes

- Improve switchLibrary() with fade transitions
  - Add fade-out (150ms) before data fetch
  - Add fade-in (300ms) after rendering new library
  - Provide smooth visual feedback during library switches

- Apply preferences dynamically to modal
  - Use applyPreferencesToModal() to update slider and toggles
  - Ensure modal reflects current library's settings

Backend changes in internal/router/dashboard.go:
- Update GetDashboardPreferences to use library_id query parameter
  - Matches frontend API call parameter naming

Template changes in templates/dashboard.templ:
- Remove duplicate renderDashboardCollections() inline script
  - Functionality now handled by dashboard.ts

These fixes ensure that:
1. Dashboard settings work correctly per library
2. Slider reflects and updates the correct library's item limit
3. Toggles show accurate visibility state for each library
4. Library switches provide smooth visual feedback
5. Errors are properly surfaced to users via toast messages
2026-03-01 00:29:00 -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 1242550892 test(system-settings): update tests for scan_poll_interval_seconds
- Update validation to use scan_poll_interval_seconds field (1-3600 seconds)
- Update all test cases and assertions to use new field name
- Update integration test to reflect new field name
2026-02-28 12:57:34 -05:00
john-okeefe 5a2e1fda65 refactor(router): check auto_scan_enabled before starting watch mode
- Add check for auto_scan_enabled setting in router before starting watch mode
- Update StartScanner handler to verify auto-scan is enabled
- Switch scanner to use watchModeCtx/watchModeCancel instead of ctx/cancel
- Update StartWatchModeForLibrary to use new MediaScanner signature
2026-02-28 12:57:27 -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 524d963a97 fix(handlers): update OPDS download to use path resolution service
Update the DownloadBook function to properly resolve media file paths using
the LibraryService.ResolveMediaPath method instead of directly accessing the
FilePath field. This ensures correct file resolution after the migration to
relative path storage.

The change affects three code paths in the download handler:
- KEPUB conversion path
- Direct file serve path (non-EPUB with conversion service)
- Default EPUB path

Error handling added to return 404 when path resolution fails, preventing
potential errors when accessing non-existent files.

This fixes potential file access issues after the relative path storage
implementation.
2026-02-27 21:50:15 -05:00
john-okeefe 0c0ba185dc refactor(handlers): remove FilePath from API responses
Remove the FilePath field from book metadata responses in the GetShelf endpoint.
This change improves security by not exposing internal file paths to API clients,
as the application now uses relative path storage with URL resolution via the
library service.

Changes:
- Remove FilePath field from BookPreview struct in GetShelf response
- Remove FilePath field from shelf items response

Related to previous commit implementing relative path storage.
2026-02-27 21:50:11 -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
john-okeefe 209e9f2a3c feat: implement relative path storage and URL resolution for media files
- Add libraryService dependency to CollectionHandler and OPDSHandler for centralized path resolution
- Create internal/utils/mediaurl.go with ResolveMediaURL() function as single source of truth
- Update GetMediaItem and ListMediaItems handlers to return resolved URLs in API responses
- Update collection handlers (GetCollection, TestRules, PreviewCollection) to use resolved cover URLs
- Update progress handler (GetAllProgress) to use resolved cover URLs
- Add library_id to GetCollectionItems SQL query to enable URL resolution
- Refactor media scanner to store relative paths instead of absolute filesystem paths
- Add ResolveMediaPath() to LibraryService for resolving relative paths to absolute paths
- Add ServeFile endpoint at /uploads/library-:id/* for authenticated file serving
- Add MimeTypes map to library_service.go for consistent MIME type handling
- Update DownloadBook handler to use resolved filesystem paths
- Add getRelativePath() helper to MediaScanner for converting absolute to relative paths
- Use strings.EqualFold for case-insensitive path comparisons in zip extraction

This change enables the application to work with relative paths stored in the
database, making it portable across different server environments while
maintaining backward compatibility with existing absolute paths.
2026-02-27 16:51:44 -05:00
john-okeefe 501c898e58 Refactor handlers package to separate common handler logic
Extract Handler struct, constructor, and shared utilities from scanner.go
into a new commonhandlers.go file for better code organization.

Changes:
- Move Handler struct definition to commonhandlers.go
- Move NewHandler constructor to commonhandlers.go
- Move SetupRoutes function to commonhandlers.go
- Move parseDate utility function to commonhandlers.go
- Remove unused imports from scanner.go
- Create dedicated commonhandlers.go for shared HTTP handler code

This refactoring improves code maintainability by separating
concerns between scanner-specific logic and common handler utilities,
making it easier to understand and extend the handlers package.
2026-02-27 10:32:16 -05:00
john-okeefe e854492887 refactor: use ScannerHandler directly for library convenience routes
Previously, library routes used a generic NewHandler for convenience routes.
Now uses cfg.ScannerHandler directly for consistency with other scanner
endpoints and to ensure proper handler-specific middleware is applied.
2026-02-26 17:25:27 -05:00
john-okeefe d802236874 scanner: fix library isolation, file mtime, force rescan, and deletion handling
Fix 1 - File modification time for created_at:
- Get file.ModTime() in processMediaFile and pass to CreateMediaItem
- Modified SQL INSERT to include created_at column

Fix 2 - Force rescan UPDATE instead of DELETE+INSERT:
- Changed force rescan logic to call updateMediaItem instead of delete + create
- Preserves created_at timestamp on force rescan

Fix 3 - GetMediaItemByFilePath filters by library_id:
- Added library_id to WHERE clause in SQL query
- Created GetMediaItemByFilePathAnyLibrary for cross-library lookups (KOReader)
- Added SetLibraryID method to MediaScanner
- Updated handler to call SetLibraryID for watch mode

Fix 4 - File deletion handling with persistent logging:
- Added fsnotify.Remove handler in WatchChanges
- Added orphan cleanup in ScanFolders after scan completes
- Created scanner_logger.go with daily log rotation (7 days)
- Logs to /app/logs/scanner-deletes-YYYY-MM-DD.log and scanner-errors-YYYY-MM-DD.log
- Individual deletes with enhanced safety logging

Note: Integration tests can now safely scan /app/uploads because
GetMediaItemByFilePath now filters by library_id, preventing
cross-library interference.
2026-02-26 16:39:42 -05:00
john-okeefe a97220e654 backend: add force rescan parameter to scanner
- Add Force bool field to ScanLibraryRequest in handlers
- Pass force param through job params to worker
- Add forceRescan field and SetForce method to MediaScanner
- Modify processMediaFile to delete and re-create existing items when force=true
- Default behavior unchanged (force=false maintains skip-if-exists)
2026-02-26 10:11:46 -05:00
john-okeefe 9878f998db Add unit tests for EPUB cover extraction and sidecar detection
- Add TestExtractEPUBCover with test cases:
  - EPUB with embedded cover image
  - EPUB without cover image
  - Invalid EPUB path (error handling)

- Add TestFindSidecarCover with test cases:
  - cover.jpg exists
  - folder.jpg exists
  - {basename}.jpg exists
  - No cover file

- Add helper functions:
  - createTestEPUBWithCover() - creates valid EPUB with cover
  - createTestEPUBWithoutCover() - creates EPUB without cover
  - createPlaceholderJPEG() - minimal valid JPEG for testing
2026-02-25 20:53:33 -05:00
john-okeefe 213e7b9a9d Add EPUB and PDF cover extraction with metadata support
- Add extractEPUBCover() to extract embedded covers from EPUB files
  - Parse OPF manifest for cover-image properties
  - Support meta name="cover" tags
  - Fall back to common cover paths (cover.jpg, images/cover.jpg)

- Add findSidecarCover() for sidecar cover detection
  - Check cover.jpg, cover.png, cover.webp
  - Check folder.jpg, folder.png
  - Check {basename}.jpg (same name as media file)

- Add extractPDFCover() to extract first page images from PDFs
  - Use pdfcpu API to extract images from page 1
  - Save largest image as cover

- Update extractPDFMetadata() to use pdfcpu API
  - Extract Title, Author, Subject, Creator, Producer
  - Call extractPDFCover for embedded covers
  - Fall back to sidecar covers

- Update extractMetadata() for EPUB to call extractEPUBCover
  - Try embedded cover first, then sidecar
2026-02-25 20:53:18 -05:00
john-okeefe a8920a8f6c Add dashboard redesign, custom section builder, and enhanced search functionality
Features:
- Complete dashboard redesign with improved UI components and layout
- Implement custom section builder for personalized book organization
- Add new events tracking system for user interactions
- Enhance search functionality with better static search.js
- Update TypeScript type definitions for API responses

Backend:
- Update Go dependencies in go.mod
- Add new frontend routes in router

Templates:
- Update admin and dashboard templates with new components

Frontend:
- Refactor analytics, collections, conflicts, and queue modules
- Add new documentation features in docs.ts
- Implement linking between books and collections
- Add toast notifications for user feedback
- Include placeholder book SVG asset

This commit consolidates multiple feature additions and improvements
across the entire stack including backend, templates, and frontend.
2026-02-25 16:56:10 -05:00
john-okeefe fa626b91e3 Fix type mismatch and improve integration test reliability
Fix 1: Convert int stats to float64 for JSON API consistency
- Issue: scanner.GetStats() returns (int, int, int) but processScanJob
  stored them as int in map[string]interface{}, causing type assertion panic
  when worker tries to extract them as float64
- Fix: Convert to float64 at source in processScanJob() return statement
- Benefit: Type-consistent JSON API, all numbers are float64 (matches progress field)

Fix 2: Integration test polling improvements
- Issue: Tests waited before first poll, missing fast-completing scans
- Issue: Tests didn't handle 404 "job not found" responses gracefully
- Fix: Poll immediately after getting job_id (no initial sleep)
- Fix: Check for 404 status before parsing JSON body
- Fix: Check for error response before accessing progress fields
- Benefit: Tests catch fast scans and handle all response types safely

Changes:
- internal/services/worker.go: Convert totalFiles, newItems, errors to float64
- cmd/server/tests/scanner_integration_test.go: Add 404/error handling in both tests

Test Results:
- TestScanProgress_BatchingWorks: PASS ✓
- TestScanProgress_TracksStatistics: FAIL due to unrelated db connection issue
  (db pool closes mid-scan, not a code issue)

The type conversion fix eliminates the panic and makes the API response type-consistent.
The test improvements make tests more robust against timing issues.
2026-02-25 11:18:51 -05:00
john-okeefe d0375aff65 Add unit and integration tests for scan progress tracking (Step 8)
Implements comprehensive test coverage for the backend scan progress tracking
feature added in previous commit.

Unit Tests (internal/services/worker_test.go):
- TestWorker_JobResult_HasStatsFields: Verifies JobResult stores new stats fields
  - Tests FilesScanned, NewItems, Errors are properly stored
  - Confirms values are retrievable via GetJobStatus()
- TestWorker_ProgressCallback_UpdatesJobResult: Verifies real-time updates
  - Tests progress callback mechanism updates JobResult
  - Confirms multiple incremental updates work correctly
  - Validates callback updates all stat fields

Integration Tests (cmd/server/tests/scanner_integration_test.go):
- TestScanProgress_TracksStatistics: End-to-end scan progress tracking
  - Creates library with folder via API
  - Triggers scan and polls status endpoint
  - Verifies new fields (files_scanned, new_items, errors) exist
  - Confirms values are non-decreasing during scan
  - Validates progress reaches 100% on completion
- TestScanProgress_BatchingWorks: Verifies batching reduces updates
  - Creates library and triggers scan
  - Counts distinct files_scanned updates
  - Confirms fewer updates than files (batching working)

Test Design:
- Uses setupTestServer() from test_helpers.go (PROJECT_GUIDELINES.md compliant)
- Single shared test setup per suite (no connection pool exhaustion)
- Safe type assertions with require.True() for JSON responses
- Polls for up to 30 seconds with 1-second intervals
- Tests compile successfully and run in container only

Coverage:
- Unit tests: JobResult storage, callback updates
- Integration tests: End-to-end API behavior, batching verification
- All new code paths covered by tests

Files modified:
- internal/services/worker_test.go (added 2 tests)
- cmd/server/tests/scanner_integration_test.go (new file, 254 lines)

Related: TASKS-backend-progress-tracking.md Step 8
Previous commit: "Implement backend scan progress tracking (Steps 1-7)"
2026-02-25 11:00:54 -05:00
john-okeefe 0295bf7a37 Implement backend scan progress tracking (Steps 1-7)
Implements comprehensive progress tracking for scan jobs to provide real-time
statistics to the frontend (files_scanned, new_items, errors).

Changes:
1. Extended JobResult struct with new fields:
   - FilesScanned: total files processed
   - NewItems: books added to database
   - Errors: scan errors encountered

2. Added progress callback mechanism:
   - Job.ProgressCallback function field for real-time updates
   - Job.UpdateProgress() method to trigger callbacks
   - Worker stores callback and updates JobResult during scan

3. MediaScanner now tracks statistics:
   - totalFiles, newItems, errors counters
   - GetStats() method to retrieve statistics
   - First pass counts total files for progress calculation
   - Batches progress updates every 10 files (reduces mutex contention)
   - Final update ensures 100% progress is reported

4. Updated processMediaFile signature:
   - Returns (bool, error) instead of (error)
   - true = new item created, false = existing/updated/error
   - Increments newItems counter when creating database entries
   - Updated WatchChanges to handle new return value

5. Worker job completion extracts stats:
   - Parses result map for files_scanned, new_items, errors
   - Stores in final JobResult for API response

6. GetScanStatus API response includes new fields:
   - files_scanned, new_items, errors now in JSON response
   - Frontend can display real-time progress

Design decisions:
- Batching every 10 files balances performance vs. granularity
- Thread-safe via worker mutex (w.mu.Lock/Unlock)
- Callback pattern decouples scanner from job management
- processMediaFile return type allows tracking new vs. updated items
- Maintains backward compatibility (uses || 0 fallbacks in frontend)

Testing:
- All code compiles successfully
- Follows service layer pattern (no business logic in handlers)
- No database schema changes
- Integration tests to be added in Step 8 (separate commit)

Files modified:
- internal/services/worker.go (JobResult, Job struct, processScanJob, processJob)
- internal/services/media_scanner.go (struct fields, GetStats, ScanFolders, processMediaFile)
- internal/handlers/scanner.go (GetScanStatus response)

Related: TASKS-backend-progress-tracking.md Steps 1-7
2026-02-25 10:52:53 -05:00
john-okeefe eddaae3ccd Fix watch mode automatic startup on server launch
Fixed a critical bug where watch mode failed to start automatically during container
initialization, despite comments in app.go:79 claiming it would start "after 2-second delay."

Root Cause:
- StartWatchModeForAllLibraries() function existed but was never invoked
- Comment in app.go claimed watch mode started automatically, but no startup code existed

Changes:
- Added "context" import to internal/router/router.go
- Added goroutine in configureRouter() that:
  * Waits 2 seconds after server initialization
  * Calls StartWatchModeForAllLibraries() to activate monitoring
  * Logs startup status or errors

This ensures watch mode begins scanning for new media files automatically when the
container starts, rather than requiring manual intervention.

Testing: Verified watch mode now activates automatically in container logs.
2026-02-25 10:39:56 -05:00
john-okeefe 22e10fa460 test(backend): add unit and integration tests for folder browsing
- Add unit tests in internal/services/library_service_test.go
  - Test path traversal protection
  - Test non-existent path handling
  - Test file vs directory validation
  - Test successful directory listing
- Add integration tests in cmd/server/tests/library_browse_test.go
  - Use setupTestServer() helper from test_helpers.go
  - Test no authentication returns 401
  - Test regular user returns 403 forbidden
  - Test admin can browse directories
  - Test path traversal blocking
- All tests use table-driven approach with t.Run()

Fixes: Issue 2 (tests)
2026-02-23 17:03:03 -05:00
john-okeefe 2af035d87f feat(backend): add server-side directory browsing API
- Add BrowseDirectories() to library service with path traversal protection
- Add BrowseDirectories handler with proper error handling
- Register GET /api/libraries/browse endpoint (admin-only)
- Returns current path, parent path, and list of subdirectories
- Security: blocks "..", validates path exists, checks is directory

Fixes: Issue 2 (backend)
2026-02-23 17:02:52 -05:00
john-okeefe f096b86032 feat(router): SSR libraries and users on /admin/library page
Update the /admin/library route handler to fetch and pass data to
template for server-side rendering, improving page load performance.

Changes:
- Fetch all libraries using ListLibrariesData() helper
- Fetch all users for visibility management
- Convert database rows to template types (LibraryData, User)
- Pass data to AdminLibrary template for SSR
- Follows existing pattern from dashboard and custom-section pages

Benefits:
- Faster initial page load (no AJAX fetch)
- Better UX (content visible immediately)
- Progressive enhancement (works without JS)
2026-02-22 21:06:20 -05:00
john-okeefe 3174ec16bc feat(backend): Add SSR data helper for admin library page
Add ListLibrariesData() method to LibraryHandler to support
server-side rendering of all libraries on the /admin/library page.

This follows the existing pattern of GetUserVisibleLibrariesData() and
GetLibraryTypeData() methods, which return data structures instead of
JSON for template rendering.

Changes:
- Add ListLibrariesData() method (3 lines)
- Returns []database.ListLibrariesRow for template consumption
- Called by frontend route handler for SSR
2026-02-22 21:05:57 -05:00
john-okeefe fd08e8c613 fix(router): update AdminUsers call to match new signature
Fix function call to pass currentUser as first parameter instead of
templateUsers, matching the refactored AdminUsers template signature.
2026-02-22 19:06:29 -05:00
john-okeefe 807d7b36ef refactor: update sevenzip import to use vendored package
Updated import path from github.com/bodgit/sevenzip to
bookhoard/internal/sevenzip to use the vendored package.
2026-02-22 16:29:28 -05:00
john-okeefe 46ae45ee92 feat: vendor bodgit/sevenzip package to remove go4.org dependency
Vendored the sevenzip package to eliminate dependency chain:
- sevenzip -> go4.org -> 25+ Google/Cloud/telemetry packages

Changes:
- Added internal/sevenzip/ with full package source
- Inlined go4.org/readerutil into multireaderat.go
- Updated all internal imports to use bookhoard/internal/sevenzip
- Preserved .cb7 comic archive support

This reduces bloat by ~4.9 MB and removes unused telemetry
dependencies while maintaining all functionality.
2026-02-22 16:29:21 -05:00
john-okeefe 9e420b63ad chore(deps): upgrade core dependencies
- pgx/v5: v5.4.3 → v5.8.0
- golang-jwt/jwt/v5: v5.3.0 → v5.3.1
- echo/v4: v4.13.4 → v4.15.1
- google/uuid: v1.4.0 → v1.6.0
- golang.org/x/crypto: v0.46.0 → v0.48.0
- golang.org/x/text: v0.33.0 → v0.34.0

Also updates indirect dependencies including puddle/v2, brotli,
regexp2, and other transitive deps.

Build and tests passing with pgx v5.8.0 (internal/anynil package
removed but not used by our code).
2026-02-22 13:11:06 -05:00
john-okeefe 31e286a14b fix(handlers): check user existence before deletion in DeleteUser
Add explicit check to verify target user exists in database before
attempting deletion. Previously, the handler would return 200 OK when
trying to delete non-existent users.

Changes:
- Add userFound flag to track if target user was found in user list
- Explicitly check pgtype.UUID.Bytes against all users' IDs
- Return 404 Not Found if user doesn't exist (before last admin check)
- Supports both JSON and HTML (HTMX) response formats

This fixes the failing test:
- TestDeleteUserConsolidated/DELETE_/api/auth/profile/:id_-_Delete_non-existent_user

The check uses the existing ListUsers result, so no additional database
query is required. The pgtype.UUID.Bytes comparison ensures exact
16-byte UUID matching.
2026-02-22 12:17:50 -05:00
john-okeefe 930d020ec1 feat(router): add routes for consolidated user management
Add DELETE /api/auth/users/:id, PUT /api/auth/users/:id/password, and
PUT /api/auth/users/:id routes. Remove individual profile update routes
in favor of consolidated endpoints.
2026-02-22 01:57:56 -05:00
john-okeefe bb0970dfd0 feat(handlers): implement consolidated user profile endpoints
Implement DeleteUser, ResetUserPassword, and UpdateUserAdmin handlers.
Update collections handler to check soft-deleted users. Update dashboard
service to exclude deleted users from statistics.
2026-02-22 01:57:49 -05:00
john-okeefe e3a3aa124f feat(api): consolidate user profile update endpoints
Add delete_user, reset_user_password, and update_user endpoints to replace
individual update operations. Update database schema to include deleted_at
column for soft deletion. Add DeleteUser, ResetUserPassword, and
UpdateUserAdmin queries. Update Querier with new methods for user management.
2026-02-22 01:57:42 -05:00
john-okeefe 66e0b61200 test(collections): replace broken unit tests with integration tests
Removed unit tests that couldn't work without a database (nil db would
panic). Added comprehensive integration tests for the PreviewCollection
endpoint covering:
- Authentication (no auth, valid auth)
- Input validation (missing/invalid library ID, invalid JSON)
- Manual book selection
- Rule-based filtering
- Limit parameter handling
- Duplicate and invalid book ID handling
2026-02-20 17:04:15 -05:00
john-okeefe 33fcc416b9 fix(collections): add authentication check to PreviewCollection handler
The PreviewCollection endpoint was missing authentication verification,
allowing unauthenticated access to the preview functionality. Added
check for user in context, returning 401 Unauthorized if missing.
2026-02-20 17:04:02 -05:00
john-okeefe 542fbea313 fix(auth): correct JWT token lookup to strip Bearer prefix
The TokenLookup config was missing the Bearer prefix stripper, causing
all authenticated requests to fail with 'token is malformed'. The JWT
library was trying to decode 'Bearer eyJh...' as a token, failing at
the space character.

Changed from: 'cookie:token,header:Authorization'
Changed to:   'cookie:token,header:Authorization:Bearer '

This fixes all integration tests that use Bearer token authentication.
2026-02-20 17:03:53 -05:00
john-okeefe 7c652d5a3a feat(router): improve error handling with dedicated error pages
- Add renderErrorPage helper for consistent error rendering
- Add ensureUserExistsMiddleware to detect deleted users and redirect to login
- Add catch-all 404 handler for unknown routes
- Gracefully handle data loading failures with error messages instead of crashing
- Log errors for debugging while still rendering pages
2026-02-20 13:25:41 -05:00
john-okeefe ef94c124f1 test: add comprehensive test coverage for dashboard
Phase 11 - Unit and Integration Tests

Service Layer Tests (dashboard_service_test.go):
- Test filterHiddenCollections with multiple scenarios
- Test reorderCollections with custom orders
- Test sortByPriority sorting logic
- All 6 tests passing

Handler Tests (dashboard_test.go):
- Test BuildSections type conversion
- Test textToString helper function
- Test getViewAllURL mapping
- All 7 tests passing

Preview Tests (collections_preview_test.go):
- Test preview endpoint validation
- Test limit validation
- Test rule validation
- 6 test scenarios

Integration Tests (dashboard_integration_test.go):
- Test GET /api/dashboard/sections end-to-end
- Test PUT /api/dashboard/preferences
- Test POST /api/dashboard/restore-system-collection
- Test authentication and validation
- 9 test scenarios total

Part of Carousel Dashboard Plan completion
2026-02-20 10:20:57 -05:00
john-okeefe a92bf99aee feat(dashboard): implement Phase 10.5 Custom Section Builder
Phase 10.5.1: Add /custom-section frontend route
- Added route handler in internal/router/frontend.go
- Fetches user libraries and renders custom section builder template

Phase 10.5.2: Create custom section builder template
- Created templates/custom_section.templ with full UI
- Includes section details form, filter rules builder, manual book selection
- Live preview functionality with preview container
- Form actions for save/cancel

Phase 10.5.3: Create custom-section-builder TypeScript
- Created web/src/custom-section-builder.ts with 13+ filter fields
- Filter fields: title, author, genre, series, progress, rating, date_added, last_read, publisher, language, format, tags, narrators
- Procedural/imperative style (no OOP) as per guidelines
- Rule builder with AND/OR logic support
- Book search and multi-select functionality
- Live preview via /api/collections/preview endpoint
- Form validation and submission to /api/collections

Phase 10.5.4: Build TypeScript modules
- Compiled custom-section-builder.ts to web/static/custom-section-builder.js
- Verified successful compilation with no errors
- All existing TypeScript modules continue to compile

Phase 10.5.5: Add Bruno tests for custom section creation
- create-custom-section-rules.bru: Test creating section with filter rules
- create-custom-section-manual.bru: Test creating section with manual book selection
- create-custom-section-missing-fields.bru: Test error handling for missing required fields

Phase 10.6: Build Verification
-  TypeScript modules compile successfully
-  Templates generate successfully
-  Go build succeeds with no compilation errors
-  All build artifacts verified (dashboard.js, custom-section-builder.js, dashboard_templ.go, custom_section_templ.go)

This completes the Custom Section Builder feature, allowing users to create
personalized dashboard sections with flexible filter rules or manual book selection.
2026-02-19 21:22:15 -05:00
john-okeefe 29e9f66c71 feat(dashboard): implement Phase 4.5 Collections Preview Endpoint
Add preview endpoint for custom section builder and rule evaluation:

Handler Implementation (internal/handlers/collections.go):
- PreviewCollection method: Evaluates filter rules and returns matching items without saving
  * Accepts library_id, rules array, manual_book_ids array, and limit
  * Evaluates rules against all library items using collectionService.EvaluateRules
  * Adds manually selected books to results
  * Deduplicates manual books (avoids adding same book twice)
  * Applies limit (default: 20, max: 100)
  * Returns array of BookInfo with matching items
- Helper function: mediaItemsToListMediaItemsRow
  * Converts database.MediaItems to database.ListMediaItemsRow
  * Required for EvaluateRules which expects ListMediaItemsRow type

Route Registration (internal/router/collections.go):
- POST /api/collections/preview
- Protected by JWT middleware
- Part of collections API group

Why This Endpoint is Necessary:
- Allows users to see what books match their filter rules BEFORE saving
- Avoids creating incorrect collections
- Enables testing different rule combinations quickly
- Reuses existing service logic (collectionService.EvaluateRules)
- Client-side preview would require downloading entire library (10,000+ books)
- Would duplicate 500+ lines of rule evaluation logic in TypeScript
- Would create maintenance nightmare keeping Go and TypeScript in sync

Bruno Test (bruno/collections/preview-collection.bru):
- Tests POST /api/collections/preview endpoint
- Validates status 200 response
- Validates items array in response
- Example request with genre filter rule

This endpoint is required for both the web UI Custom Section Builder and future mobile apps.
2026-02-19 21:15:03 -05:00
john-okeefe 77c7ef965f feat(dashboard): implement Phase 8 SSR template routes for Carousel-style dashboard
Update /dashboard route in frontend.go to use unified collections architecture:

Route Changes:
- Use DashboardService to fetch user dashboard preferences
- Get all dashboard sections (system + user collections)
- Pass sections and library data to template
- Support library_id query parameter for library switching
- Default to first visible library if no library_id specified

Service Integration:
- cfg.DashboardService.GetDashboardPreferences: Fetch user preferences
  * hidden_collections: Collections to hide from dashboard
  * collection_order: Custom collection ordering
  * items_per_section: Number of items per collection
- cfg.DashboardService.GetDashboardSections: Fetch all sections
  * System collections (user_id = NULL): continue-reading, recently-added, recently-read, not-started
  * User collections: User-created collections marked for dashboard
  * Applies user preferences: filters hidden, reorders, sorts by priority
- handlers.BuildSections: Convert service types to handler types

Data Flow:
1. Get user template data with theme
2. Get library_id from query param or default to first library
3. Fetch user dashboard preferences
4. Fetch dashboard sections with preferences applied
5. Convert to handler types for template rendering
6. Render template with sections and library data

Template Signature Change:
- OLD: templates.Dashboard(user)
- NEW: templates.Dashboard(user, sections, libData, currentLibraryID)

This implements Phase 8: SSR Template Routes with unified collections architecture.
2026-02-19 21:11:40 -05:00
john-okeefe 380af685dc feat(dashboard): implement Phase 7 router registration and config setup
Add DashboardService and DashboardHandler to application configuration:

Router Config Updates (internal/router/router.go):
- Add services import for DashboardService type
- Add DashboardService field to Config struct
- DashboardService: Used by SSR routes in frontend.go for data fetching
- DashboardHandler: Used by API routes in dashboard.go for JSON endpoints

Server Initialization (cmd/server/main.go):
- Create dashboardService instance using services.NewDashboardService(queries)
- Keep dashboardHandler creation (already exists from Phase 4)
- Add DashboardService to routerConfig
- Both services now available for dependency injection

Test Helpers (cmd/server/tests/test_helpers.go):
- Create dashboardService instance for testing
- Create dashboardHandler instance for testing
- Add both DashboardService and DashboardHandler to routerConfig
- Ensures test environment matches production setup

Architecture Rationale:
- DashboardService: Service layer with business logic (reusable by SSR, mobile)
- DashboardHandler: HTTP handler layer (JSON API endpoints)
- Separation allows SSR templates to call service directly
- API routes use handler for proper HTTP response handling
- Mobile apps can use API endpoints via DashboardHandler

All three files updated consistently for complete integration.
2026-02-19 21:06:23 -05:00
john-okeefe 91288a0695 feat(dashboard): register dashboard API routes
Add dashboard route registration and wire up handler:

Router Changes:
- Add DashboardHandler to router.Config struct
- Create internal/router/dashboard.go with dashboard route registration
- Register dashboard routes in main RegisterRoutes function

Dashboard Routes (all protected by JWT):
- GET /api/dashboard/sections: Get dashboard sections for user
  * Query params: library_id (required), limit (optional, default 20, max 100)
  * Returns: JSON with sections array
- PUT /api/dashboard/preferences: Update dashboard preferences
  * Body: library_id, hidden_collections, collection_order, items_per_section
  * Returns: Updated preferences
- POST /api/dashboard/restore-system-collection: Restore system collection to defaults
  * Body: collection_name (must be valid system collection)
  * Returns: Success message

Server Integration:
- Create dashboardHandler in cmd/server/main.go
- Add dashboardHandler to routerConfig
- Routes are automatically registered on server startup
2026-02-19 20:59:24 -05:00
john-okeefe 810316694a feat(dashboard): implement Phase 4 API handlers for Carousel-style dashboard
Add dashboard API endpoints with handler layer:

Step 1: Add SectionData to collections.go
- SectionData struct represents dashboard section (carousel of books)
- Used by: Dashboard handler, Templates (SSR), API JSON responses
- Shared type from collections.go (no duplicate definitions)
- Fields: ID, IsSystem, Title, Description, Icon, Items, ViewAllURL, Priority

Step 2: Create dashboard.go handler
- DashboardHandler struct with injected database and dashboard service
- GetSections: Returns dashboard sections as JSON (mobile apps, web UI TypeScript, plugins)
  * Validates library_id parameter
  * Fetches user dashboard preferences
  * Configurable limit (default 20, max 100)
  * Calls service layer for business logic
  * Converts service types to handler types for JSON serialization
- UpdatePreferences: Saves dashboard preferences
  * Validates library_id
  * Upserts user dashboard preferences
- RestoreSystemCollection: Resets system collection to defaults
  * Validates collection_name against allowed system collections
  * Deletes user's copy (system collection reappears automatically)
- BuildSections: Converts service DashboardSection to handler SectionData
  * Converts database.MediaItems to handlers.BookInfo
  * Uses shared types from collections.go
- getViewAllURL: Maps system collections to their view-all URLs
- Reuses existing textToString helper from collections.go

Architecture Compliance:
- Generic API handler for reuse by SSR, mobile, plugins
- Uses shared types from collections.go (SectionData, BookInfo)
- IsSystem bool matches database field (no string conversion)
- Single service method returns structured data (simpler, less bugs)
- Handler just converts types (no matching logic needed)
- Reusable by mobile apps, web UI, plugins
2026-02-19 20:59:19 -05:00