Commit Graph
96 Commits
Author SHA1 Message Date
john-okeefe 6495cc2c7c feat(handlers): Add OPDS, collections, book matching, and sync handlers
- Add OPDS handler for device catalog and book downloads
- Add collections handler for collection CRUD
- Add book matching service for cross-device book linking
- Add sidecar handler for Kobo metadata sync
- Add sync handler for device synchronization
2026-01-31 22:32:23 -05:00
john-okeefe d28002e4cb feat(sync): Add Kobo/Koreader sync and conflict handling
- Add Kobo markup/sync endpoints for bookshelves
- Add Koreader progress sync with SHA-256 support
- Add sync conflict detection and resolution
- Update ebook scanner for better file matching
2026-01-31 22:32:09 -05:00
john-okeefe 63008001c6 feat(db): Add kobo_shelves and device catalog tables
- Add kobo_shelves table for Kobo device shelves management
- Add device_shelf_mappings for collection<->device shelf mappings
- Update device_catalogs with better ContentId tracking
- Add indexes for performance
2026-01-31 22:32:04 -05:00
john-okeefe cd8f313b16 feat(handlers): Add helper methods for hybrid SSR
- Add GetPendingRegistrationsData() to DeviceHandler
- Add GetQueueData() to QueueHandler
- Add template types: DeviceData, PendingRegistrationData, ConflictData, QueueItemData
- Add collection types: CollectionData, CollectionDetailData, BookData

All changes are non-breaking and preserve API compatibility
2026-01-31 22:31:33 -05:00
john-okeefe a7f2b83bdd Integrate sync queue system and device cap API
- Start queue processor as background goroutine
- Initialize and register queue handler
- Add queue management routes (7 endpoints)
- Update KOReader handler to use checkpoint sync mode
- Add device cap management route (PUT /api/auth/users/:id/max-devices)
- Register all new endpoints with proper middleware
2026-01-31 13:06:56 -05:00
john-okeefe 50c632babf Update SSL/TLS handling for Docker reverse proxy deployments
- Disable HTTPSRedirectMiddleware (SSL handled by proxy)
- Keep SSLProxyMiddleware for X-Forwarded-* headers
- Add note about Docker deployment architecture
- Database connections use sslmode=disable
- No redirect needed for reverse proxy setup
2026-01-31 13:06:50 -05:00
john-okeefe 5039071ea3 Add admin-configurable device cap per user
- Add max_devices column to users table (default: 10)
- Add UpdateUserMaxDevices database query
- Add CountUserDevices database query
- Add UpdateUserMaxDevices handler with validation (1-100 devices)
- Add PUT /api/auth/users/:id/max-devices endpoint (admin only)
- Update UserList struct to include max_devices field
- Validate user ID format and max_devices range
- Return appropriate errors for invalid requests
2026-01-31 13:06:21 -05:00
john-okeefe 030d30a225 Add queue management API and database queries
- Add 7 new database queries for queue management
- GetStuckSyncQueueItems - Detect stuck items
- GetSyncQueueStats - Queue statistics
- GetNextRetryTime - Exponential backoff calc
- ListAllSyncQueueItems - Admin view
- IncrementSyncQueueAttempts - Retry counter
- Add queue handler with 7 REST endpoints
- GET /api/queue/devices/:id/stats - Queue statistics
- GET /api/queue/devices/:id/items - List device queue
- POST /api/queue/items/:id/retry - Retry failed item
- DELETE /api/queue/items/:id - Delete queue item
- DELETE /api/queue/devices/:id/clear - Clear device queue
- GET /api/queue/items - List all items (admin)
- Add full user/admin access control
2026-01-31 13:06:12 -05:00
john-okeefe 11ee4901a5 Add offline detection and recovery system (Phase 6)
- Implement OfflineDetector with 5-minute online threshold
- Add automatic device scanning (2-minute intervals)
- Add offline mode enforcement (disable sync)
- Add reconnection handling with priority item processing
- Add force reconnect API endpoint
- Add comprehensive offline detection tests
- Handle device offline/reconnected events
2026-01-31 13:06:05 -05:00
john-okeefe b9de7c48d5 Add sync queue system with exponential backoff retry logic (Phase 6)
- Implement SyncQueueProcessor with 5-second polling interval
- Add priority-based queuing (1-10 scale)
- Add exponential backoff retry logic (1m, 5m, 15m, 1h, 24h)
- Add stuck item detection (> 1 hour in processing state)
- Add batch processing (50 items per cycle)
- Add comprehensive test suite (15+ test cases)
- Test enqueue/dequeue, priority ordering, retry logic, concurrent operations
2026-01-31 13:06:00 -05:00
john-okeefe 2d2d643873 Add sync conflict detection and resolution system
Implement conflict detection for concurrent reading progress updates from different devices. Adds conflict management endpoints for listing, viewing, and resolving conflicts.

- Add ConflictHandler with CRUD endpoints for conflict management
- Implement automatic conflict detection in KOReader progress updates
- Add WebSocket broadcast for real-time conflict notifications
- Add database query for listing user conflicts by status
- Add integration tests and Bruno API test collection
2026-01-31 11:45:52 -05:00
john-okeefe d440e55f05 Update handlers to work with UUID refresh tokens
- Add parseTokenUUID() helper to convert string to pgtype.UUID
- Update RefreshAccessToken to parse token string to UUID before validation
- Update Logout to parse token string to UUID before revoking
- Update CreateRefreshToken to pass UUID directly to database
- Update auth.go: fix return value order from CreateRefreshToken
- Remove unnecessary comments for cleaner code
2026-01-31 11:44:35 -05:00
john-okeefe db5d51e77e Regenerate database code for UUID token support
- Update models: RefreshTokens.Token now pgtype.UUID
- Update querier: GetRefreshToken/RevokeRefreshToken accept pgtype.UUID
- Regenerate queries.sql.go via sqlc after schema change
2026-01-31 11:44:26 -05:00
john-okeefe 42c3168fcf feat: add server sync to Kobo endpoint and media routes 2026-01-31 00:29:39 -05:00
john-okeefe fef41dc168 feat: add media handler for book download and shelf management 2026-01-31 00:29:38 -05:00
john-okeefe cd240d3054 feat: add Kobo shelf and entitlement SQL queries 2026-01-31 00:29:38 -05:00
john-okeefe ed336c6c41 feat: add Kobo entitlements and shelves models 2026-01-31 00:29:37 -05:00
john-okeefe a3aa9f67ac feat: add Kobo device sync support and fix device route protection
- Add Kobo sync handler with markup, bookmark, analytics, and initialization endpoints
- Add Kobo integration tests and Bruno API test collection
- Move device approve/reject routes from public to protected routes
- Enhance test infrastructure with DATABASE_URL support and helper functions
- Fix device GetDevice handler nil pointer handling
- Clean up test reports and session files
2026-01-30 23:58:34 -05:00
john-okeefe 885cbd5d47 feat: broadcast progress updates from KOReader sync
Add WebSocket broadcast to KOReader progress sync:
- Integrate ConnectionManager into KOReaderHandler
- Broadcast progress updates on successful sync
- Include source device information (model, type)
- Real-time updates to all connected clients

When KOReader devices sync reading progress, all connected
WebSocket clients (web browsers, mobile apps, other devices)
receive instant updates.
2026-01-30 21:48:14 -05:00
john-okeefe 4681fb474e feat: integrate ConnectionManager into Handler struct
Add WebSocket ConnectionManager to Handler:
- Add connManager field to Handler struct
- Update NewHandler to accept ConnectionManager parameter
- Update SetupRoutes to pass ConnectionManager through
- Import sync package with alias to avoid conflicts

This enables progress handlers to broadcast updates via WebSocket.
2026-01-30 21:47:56 -05:00
john-okeefe c9ec222945 feat: add ValidateDeviceToken method to device auth middleware
Add device token validation method for WebSocket authentication:
- Validates device auth tokens against database
- Returns device information for valid tokens
- Used by WebSocket handler for device authentication

This enables devices to authenticate WebSocket connections
using their bearer tokens.
2026-01-30 21:47:30 -05:00
john-okeefe 317a4e82a0 feat: add WebSocket handler with dual authentication
Add WSHandler for WebSocket connection management:
- Upgrade HTTP to WebSocket connections
- Dual authentication support:
  - JWT token via query parameter (web clients)
  - Bearer token via Authorization header (devices)
- Client info extraction for users and devices
- Separate read and write pumps for concurrent I/O
- Ping/pong heartbeat mechanism (30s interval)
- Initial state delivery on connection
- Connection cleanup on disconnect

Implements Week 9 WebSocket endpoint functionality from
Universal Sync Implementation Guide.
2026-01-30 21:47:11 -05:00
john-okeefe 9bfe14bb38 feat: add WebSocket connection manager infrastructure
Add ConnectionManager for real-time WebSocket communication:
- Message types for progress updates, annotations, conflicts
- Broadcast message structure with source device tracking
- Device connection tracking with user and device metadata
- Automatic broadcast loop with concurrent message delivery
- Connection management (add, remove, get by ID/user)
- Stale connection cleanup (2-minute timeout)
- Connection statistics by device type
- Background cleanup task runs every minute

This implements the core WebSocket infrastructure needed for
Week 9 of the Universal Sync Implementation Guide.
2026-01-30 21:46:53 -05:00
john-okeefe f6124dc537 Phase 3 Week 7: Fix device auth middleware to set device object
- Update device auth middleware to set actual device object
- Change from DeviceContext to database.Devices
- Fix RequirePermission to use database.Devices
- Ensures handlers can access full device information
- Required for KOReader sync handlers to function properly
2026-01-30 20:55:13 -05:00
john-okeefe 7a5d38b886 Phase 3 Week 7: Implement KOReader sync protocol handlers
- Create SyncProgress for bidirectional progress synchronization
- Create GetMetadata for book progress and annotation retrieval
- Create GetLibrary for user library sync
- Create SyncBookmarks for annotation management
- Support device matching by UUID, file path, or title/author
- Implement immediate and checkpoint sync modes
- Handle bookmarks, highlights, and notes synchronization
- Part of Phase 3 KOReader Integration implementation
2026-01-30 20:55:04 -05:00
john-okeefe 4c01c0d12e Phase 3 Week 7: Add KOReader bulk sync function to database schema
- Add bulk_update_progress_from_koreader() function for batch processing
- Handles progress, annotations, and conflict detection
- Returns success/failure status for each book
- Supports device matching by UUID, file path, or title/author
- Implements automatic conflict detection for concurrent syncs
- Part of Phase 3 KOReader Integration implementation
2026-01-30 20:54:51 -05:00
john-okeefe 6432d4cb00 Fix BaseURL construction to use consistent port
- Use SERVER_PORT for both port and BaseURL construction
- Ensures BaseURL matches the actual server port
2026-01-30 20:16:25 -05:00
john-okeefe a9fdd44471 Add library-based scanning and media item endpoints
- Add POST /api/libraries/:id/scan endpoint for admin library scanning
- Add GET /api/libraries/:id/media-items endpoint for library media items
- Move /api/libraries/types to public endpoint (no auth required)
- Update ScanEbooks handler to support library_id parameter
2026-01-30 20:16:22 -05:00
john-okeefe 1a769783dc Phase 2 Week 6: Device Authentication & Rate Limiting
Implement per-device authentication with rate limiting and permissions.

Device Rate Limiter (device_rate_limiter.go):
- DeviceRateLimiter: Track requests per device and request type
- CheckRateLimit: Verify device hasn't exceeded limits
- GetRemainingRequests: Return remaining request quota
- Reset: Clear rate limit data for specific device
- cleanupOldEntries: Remove stale entries automatically
- Request Types: sync, progress, metadata
- Rate Limits:
  * Sync requests: 60/minute
  * Progress updates: 120/minute (page turns)
  * Metadata requests: 30/minute

Device Auth Middleware Updates:
- Add rateLimiter to DeviceAuthMiddleware
- Check rate limits during authentication
- Return 429 Too Many Requests when limits exceeded
- Set rate limit headers:
  * X-RateLimit-Limit: Request limit
  * X-RateLimit-Remaining: Quota remaining
  * X-RateLimit-Reset: Reset time
- getRequestType: Determine request type from URL path

Request Type Detection:
- /progress endpoints → progress type (120/min)
- /metadata, /library endpoints → metadata type (30/min)
- All other sync endpoints → sync type (60/min)

Benefits:
- Prevent device abuse and DoS attacks
- Fair resource allocation across devices
- Higher limits for frequent operations (page turns)
- Lower limits for expensive operations (metadata)
- Automatic cleanup of stale data
- Per-device isolation (one device can't affect others)

Integration with Device Auth:
- Rate limit check happens after token validation
- Before processing actual sync request
- Returns standard HTTP 429 with retry info
- Works seamlessly with existing device middleware

Device revocation still available via:
- DELETE /api/devices/:id endpoint
- Sets auth_token to NULL
- Disables sync_enabled flag
2026-01-30 16:47:29 -05:00
john-okeefe 23ad70158c Phase 2 Week 5: Device Registration & Management
Implement device registration and management system for universal sync.

Database Changes:
- Add device queries to queries.sql (CRUD operations, registration, auth)
- Add sync queue management queries
- Add conflict resolution queries
- Regenerate sqlc models with new device-related types

Device Handler (devices.go):
- InitiateRegistration: Start device registration with auth URL and QR code
- CheckRegistrationStatus: Poll for registration approval
- ListDevices: Get all devices for current user
- GetDevice: Get specific device details
- UpdateDevice: Update device settings (name, sync settings, frequency)
- DeleteDevice: Remove device from account
- ApproveDevice: User approves device registration via web
- RejectDevice: Reject pending device registration
- ListPendingRegistrations: Show all pending registrations
- generateDeviceToken: Generate secure Bearer token for devices

Device Authentication Middleware (device_auth.go):
- Authenticate: Validate device Bearer tokens
- RequirePermission: Check device permissions by type
- hasPermission: Define permissions per device type
- UpdateLastSeen: Auto-update device last_seen timestamp

Configuration:
- Add BaseURL field to Config for device setup URLs

API Endpoints:
POST /api/devices/register - Initiate device registration
POST /api/devices/register/status - Check registration status
GET /api/devices/approve/:id - Approve device (web UI)
POST /api/devices/reject/:id - Reject device
GET /api/devices - List user's devices
GET /api/devices/:id - Get device details
PUT /api/devices/:id - Update device settings
DELETE /api/devices/:id - Delete device
GET /api/devices/pending - List pending registrations

Bruno API Collection:
- Initiate Device Registration
- Check Registration Status
- List Devices
- Get Device
- Update Device
- Delete Device

Dependencies:
- github.com/skip2/go-qrcode for QR code generation

Device Types Supported:
- koreader: Calibre-compatible sync
- kobo: Kobo sync protocol
- web: Web interface
- mobile: Mobile apps

Device Permissions:
- sync:progress
- sync:annotations
- sync:metadata
- device:manage (web only)
2026-01-30 16:45:10 -05:00
john-okeefe a2424bcf74 Phase 1 Week 4: Testing & Validation
- Create comprehensive unit tests for sync package
- format_test.go: 60+ tests for format detection
  - EPUB format detection (mimetype, extension, uppercase)
  - MOBI/AZW3/FB2/TXT reflowable formats
  - PDF/DJVU fixed layout formats
  - CBZ/CBR/CB7/CBT comic archive formats
  - Unknown format handling
  - MimeType lookup tests
  - IsReflowable/HasFixedLayout/IsComicArchive helpers
- progress_test.go: 45+ tests for progress conversion
  - PageToPercentage/PercentageToPage (with clamping)
  - CharacterToPercentage/PercentageToCharacter
  - ConvertProgress between format groups
  - MergeProgress with 'max progress wins' strategy
  - FormatProgressForDisplay for UI rendering
  - Round-trip conversion tests
  - Edge cases (very small/large values, floating point precision)
- All tests pass successfully
- Test coverage: format detection, progress conversion, display formatting
- Validates Phase 1 implementation quality
2026-01-30 16:13:10 -05:00
john-okeefe 6ddc551d64 Phase 1 Week 3: Core Progress APIs
- Create internal/handlers/progress.go with universal progress endpoints
- GET /api/progress/:id - Get progress with all location references
- POST /api/progress/:id - Update progress with automatic conversion
- GET /api/progress/:id/history - Get reading session history
- Progress response includes:
  - format_group (reflowable, fixed_layout, comic_archive)
  - percentage (0.0-1.0)
  - location_references (page, epubcfi, chapter, character)
  - device_sync information
- UpdateUniversalProgress accepts multiple input formats:
  - percentage directly
  - page/total_pages (auto-converts to percentage)
  - epubcfi for EPUBs
  - chapter/chapter_progress
- Uses sync package for format conversion
- Backward compatible with existing progress endpoints
- Add routes to SetupRoutes in ebook.go
- Fixes pgtype wrapper type access (.Float64, .Int32, .Int64)
2026-01-30 16:11:11 -05:00
john-okeefe bb3c32c59f Phase 1 Week 2: Format detection and progress conversion engine
- Add internal/sync package with format detection
- FormatGroup types: reflowable, fixed_layout, comic_archive
- DetectFormatGroup() function based on mimetype and file extension
- MimeType mappings for common ebook formats
- Progress conversion engine with:
  - ConvertProgress() between format groups
  - Extract percentage from various progress formats
  - PageToPercentage / PercentageToPage helpers
  - CharacterToPercentage / PercentageToCharacter helpers
  - MergeProgress() with 'max progress wins' strategy
  - FormatProgressForDisplay() for UI rendering
- Add sqlc queries for format detection and progress updates
- BulkUpdateFormatGroups query for auto-format detection
- GetUniversalProgress query with all location references
- UpdateUniversalProgress query with device sync metadata
- ReadingHistory queries for session tracking
2026-01-30 16:07:00 -05:00
john-okeefe fa4a9c35bb Phase 1 Week 1: Database schema for universal sync system
- Add format_group columns to media_items table
- Add universal progress tracking to reading_progress (percentage, epubcfi, chapter, etc.)
- Add device sync metadata (last_sync_device, conflict tracking)
- Add location enhancements to media_notes and media_highlights
- Create devices table for device registry
- Create sync_queue table for offline support
- Create sync_conflicts table for conflict resolution
- Create reading_history table for session tracking
- Add 15 new indexes for performance
- Create update_updated_at_column trigger function
- Add SQL helper functions: detect_format_group, convert_progress, detect_conflict, merge_progress

Schema grew from 272 to 598 lines (+326 lines)
Verified with sqlc generate
2026-01-30 16:04:06 -05:00
john-okeefe 37b8380533 fix: sync database queries with enhanced media-items schema
- Add missing enhanced fields to CreateMediaItem INSERT statement
- Add missing enhanced fields to UpdateMediaItem UPDATE statement
- Include language, edition, page_count, genre, copyright_year
- Include integration fields: goodreads_id, openlibrary_id, google_books_id
- Add corresponding indexes for enhanced fields
- Add column comments for better documentation
- Resolves schema-query mismatch causing field removal cycles
2026-01-30 14:11:52 -05:00
john-okeefe dc820dfb92 cleanup: remove outdated documentation and summaries
- Remove API_TESTING_SUMMARY.md, IMPLEMENTATION_SUMMARY.md
- Remove MIGRATION_PROGRESS.md, SECURITY_*.md files
- Clean up temporary documentation files from previous sessions
- Repository now focused on current working code
2026-01-30 13:52:01 -05:00
john-okeefe 2044c1a631 fix: resolve GetLibraryByFolder undefined error
- ebook_scanner.go:293 now compiles successfully
- GetLibraryByFolder method available after database code regeneration
- Scanner service can properly find libraries by folder path

Fixes primary compilation error blocking build
2026-01-30 13:51:52 -05:00
john-okeefe 74e8815bd3 fix: handler ISBN field type corrections
- Fix CreateMediaItem ISBN field to use pgtype.Text wrapper
- Fix UpdateMediaItem to use correct Isbn field name
- Resolve type mismatch between request and database params

Resolves compilation errors in media item handlers
2026-01-30 13:51:48 -05:00
john-okeefe fc71c2ef76 fix: database queries and schema sync
- Remove references to non-existent columns (language, edition, page_count, etc.)
- Fix CreateMediaItem and UpdateMediaItem queries
- Remove normalize_isbn() function calls (moved to Go code)
- Regenerate database code with sqlc generate
- Add GetLibraryByFolder method to queries

Fixes compiler error: s.db.GetLibraryByFolder undefined
2026-01-30 13:51:44 -05:00
john-okeefe f96044b6c7 refactor: remove ebook system, unify on media-items
Phase 1-3: Database layer cleanup
- Remove 5 backward compatibility VIEWs (ebooks, ebook_ratings, etc.)
- Remove all ebook-specific database queries
- Add new admin media-items queries (Create, Update, Delete)
- Fix sqlc.yaml to point to schema.sql file
- Regenerate database code successfully

Phase 4: Remove old ebook handlers
- Remove all 23 ebook handler functions:
  * ListEbooks, GetEbook, CreateEbook, UpdateEbook, DeleteEbook
  * GetEbookRating, CreateOrUpdateEbookRating, DeleteEbookRating, GetEbookRatings
  * GetEbookNotes, CreateEbookNote, GetEbookNote, UpdateEbookNote, DeleteEbookNote
  * GetEbookHighlights, CreateEbookHighlight, GetEbookHighlight, UpdateEbookHighlight, DeleteEbookHighlight
  * GetReadingProgress, UpdateReadingProgress
- Remove ebook request types (CreateEbookRequest, UpdateEbookRequest, etc.)

Phase 5: Add new admin media-items handlers
- CreateMediaItem (admin only, requires library_id)
- UpdateMediaItem (admin only)
- DeleteMediaItem (admin only)
- Add CreateMediaItemRequest, UpdateMediaItemRequest types
- All use MustGetAuthenticatedUser for safe context access
- Validate admin role before allowing operations
- Validate library exists before creating items

Phase 6: Update routes
- Remove ALL /api/ebooks routes from SetupRoutes()
- Remove ebook progress, rating, notes, highlights routes
- Add admin.POST/PUT/DELETE /api/media-items routes
- Keep all media-items, scanner, and watch mode routes intact

Result: Unified API with only /api/media-items endpoints
- All features preserved (filtering, sorting, searching)
- Better features than old ebook system (more fields, library scoping)
- Cleaner codebase with single system
- All code compiles successfully

Breaking Change: /api/ebooks endpoints removed (use /api/media-items instead)
Status: 85% complete (Phases 1-6 done, Phases 7-8 pending: tests + rebuild)

Tests: Need update (rename Ebooks → MediaItems, update API paths)
Build: Need rebuild with clean cache
2026-01-30 10:03:13 -05:00
john-okeefe 420af7978a fix: critical security vulnerabilities
- Fix type assertion panics in auth.go (9 handlers)
  * GetProfile, UpdateProfile, UpdateTheme, UpdateUsername
  * UpdateEmail, UpdatePassword, DeleteAccount
  * UpdateScanSettings, GetScanSettings, Register admin check
  * Replace c.Get("user_id").(string) with MustGetAuthenticatedUser()

- Fix type assertion panic in library.go
  * GetUserVisibleLibraries now uses MustGetAuthenticatedUser()

- Add path traversal protection to AddLibraryFolder
  * Detect and block ".." in paths
  * Clean paths with filepath.Clean()
  * Verify path is a directory before adding

- Remove debug logging from Login handler
  * Removed all fmt.Printf statements
  * No more plaintext password logging

- Create safe context helper functions
  * internal/handlers/context.go added
  * GetAuthenticatedUser() for safe retrieval
  * MustGetAuthenticatedUser() for post-auth middleware

Security: Critical
Tests: All 62 integration tests pass
Breaking: None - backward compatible
2026-01-30 08:58:43 -05:00
john-okeefe 3b2075fc70 Phase 1: Add enhanced database fields and sorting
- Add 9 new fields to media_items table (language, edition, page_count, goodreads_id, openlibrary_id, google_books_id, copyright_year, genre, subjects)
- Add indexes for new fields (language, genre, page_count, copyright_year, series_order, date_published)
- Add ListMediaItemsSorted SQL query for dynamic sorting
- Update ListMediaItems handler to process sort parameter
- Support 16 sorting options (title, author, created_at, date_published, copyright_year, page_count, genre, series)
- Add /api/media-items/filtered endpoint for advanced filtering
- Register new filtered endpoint in routes
2026-01-30 08:32:49 -05:00
john-okeefe ff44115be2 fix: correct user context type extraction in CreateLibrary handler
- Use c.Get("user").(database.Users) instead of c.Get("user_id").(string)
- Extract userUUID from user.ID.Bytes ([16]byte)
- Properly convert to pgtype.UUID for service layer
- Remove unnecessary uuid.Parse call

This fixes 500 Internal Server Error when creating libraries via API.
The JWT middleware sets user as database.Users struct, not string.

Related to Bruno Create Library request testing.
2026-01-29 21:16:26 -05:00
john-okeefe 5658dc70f4 fix: correct folder path validation error handling in AddLibraryFolder
- Fix scoping issue with err variable in os.Stat check
- Properly check for non-existent vs inaccessible folders
- Use reassignment (=) instead of declaration (:=) since err already declared
2026-01-29 20:20:39 -05:00
john-okeefe 59b32f4827 feat: implement search endpoint with partial match and fuzzy fallback
- Add GET /api/media-items/search endpoint
- Try partial matching first (ILIKE with wildcards)
- Fallback to fuzzy search if no results found
- Return 404 with 'no results found' when no matches
- Limit results to 50 items by default
- Supports search across title, author, series, tags, contributors
- Respects library visibility settings per user
2026-01-29 20:20:35 -05:00
john-okeefe 3145f64a66 feat: add search queries with partial matching and fuzzy fallback
- Add SearchMediaItems query with ILIKE partial matching
- Add SearchMediaItemsFuzzy query with word_similarity()
- Use sqlc.narg() for named parameters (search_pattern, search_query)
- Rank results by relevance: title > author > series > tags
- Fuzzy threshold set to 0.3 for word_similarity
- Generated Go models with proper parameter types
2026-01-29 20:20:30 -05:00
john-okeefe d9ca3d5a65 feat: add /bookshelf route and update redirects
- Add /bookshelf route as default page for logged-in users
- Update login and register handlers to redirect to /bookshelf
- Update homepage to auto-redirect to /bookshelf when logged in
- Preserve /dashboard route for backward compatibility
- Update test redirects to use /bookshelf

Changes:
- main.go: Add /bookshelf protected route
- auth.go: Change login/register redirects from /api/dashboard to /bookshelf (2 locations)
- edge_cases_test.go: Update test redirect to /bookshelf
- Maintains backward compatibility with existing /dashboard route

This makes the beautiful bookshelf the default landing page
for all authenticated users while keeping the old dashboard accessible.
2026-01-29 15:52:11 -05:00
john-okeefe 8f739af285 fix: correct UUID format string issues in logging and tests
- Fix scheduler.go log.Printf calls to convert pgtype.UUID to string before formatting
- Fix ebook.go fmt.Printf calls to convert pgtype.UUID to string before formatting
- Add missing Enabled field to rate limiter config in security test
- Prevents format string errors when logging library IDs

This resolves compilation errors where pgtype.UUID was being formatted
with %s which expects a string, not a UUID struct.
2026-01-29 15:51:05 -05:00
john-okeefe 4b8cb58c84 feat: add configurable test mode and rate limiting
- Add TestMode, RateLimitEnabled, RequestsPerMinute to Config
- Add getEnvBool() and getEnvInt() helper functions
- Update rate limiter to support enabled/disabled state
- Pass test environment variables through docker-compose
- Configure rate limiter dynamically in main.go

This allows disabling rate limiting for integration testing while
maintaining security in production environments.
2026-01-29 13:33:18 -05:00
john-okeefe ce0e448e58 refactor: standardize API response formats for list endpoints
- ListLibraries now returns {"data": []} instead of []
- ListUsers now returns {"data": []} instead of []
- ListMediaItems now returns {"data": []} instead of []

This provides consistent response structure across all list endpoints
and aligns with integration test expectations.
2026-01-29 13:33:08 -05:00