Run the new migration to create required tables:
# Apply the new migration
./migrate up
# or however you run migrations in your systemNew Tables Created:
plex_servers- Stores unique Plex serversplex_libraries- Stores libraries from serversuser_plex_access- Tracks user access to librariesplex_library_items- Cached library contentssync_jobs- Background job managementtmdb_rate_limits- Rate limiting tracking
In your main server file (e.g., cmd/server/main.go):
// Add these imports
import (
"moviedb/internal/services"
"moviedb/internal/handlers"
)
// Initialize Plex integration (add this after database setup)
plexIntegration := services.NewPlexIntegrationManager(db, tmdbClient)
// Start background services
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if err := plexIntegration.Start(ctx); err != nil {
log.Fatalf("Failed to start Plex integration: %v", err)
}
// Setup graceful shutdown
go func() {
<-ctx.Done()
if err := plexIntegration.Stop(); err != nil {
log.Printf("Error stopping Plex integration: %v", err)
}
}()
// Add new API routes
syncHandler := handlers.NewPlexSyncEnhancedHandler(
plexIntegration.GetSyncService(),
plexIntegration.GetJobManager(),
)
mux.HandleFunc("POST /api/plex/sync", requireAuth(syncHandler.TriggerFullSync))
mux.HandleFunc("GET /api/plex/sync/status/{jobId}", requireAuth(syncHandler.GetJobStatus))
mux.HandleFunc("GET /api/plex/sync/jobs", requireAuth(syncHandler.GetUserJobs))
mux.HandleFunc("POST /api/plex/sync/cancel/{jobId}", requireAuth(syncHandler.CancelJob))
mux.HandleFunc("GET /api/plex/libraries", requireAuth(syncHandler.GetUserLibraries))CRITICAL: Update the getUserID function in internal/handlers/plex_sync_enhanced.go:
// Replace this placeholder with your actual auth implementation
func getUserID(r *http.Request) int64 {
// Example for JWT-based auth:
// token := r.Header.Get("Authorization")
// claims, err := parseJWT(token)
// if err != nil { return 0 }
// return claims.UserID
// Example for session-based auth:
// session := getSession(r)
// return session.UserID
// REPLACE THIS WITH YOUR ACTUAL AUTH LOGIC
return 0
}Add to go.mod if not already present:
require (
github.com/LukeHagar/plexgo v0.23.0
// ... other dependencies
)Run:
go mod tidyAdd these optional environment variables:
# Rate limiting configuration
TMDB_RATE_LIMIT_REQUESTS=40
TMDB_RATE_LIMIT_WINDOW=10s
# Job processing
PLEX_SYNC_WORKERS=3
PLEX_SYNC_TIMEOUT=2h
# Cleanup scheduling
PLEX_CLEANUP_INTERVAL=6hThe frontend changes are already in place. Build the frontend:
cd web
npm run buildBefore running the migration, backup your database:
# For SQLite
cp your-database.db your-database.backup.db
# For PostgreSQL
pg_dump your_db > backup.sql- No changes to existing Plex authentication - The existing PIN flow still works
- No changes to existing movie data - All existing data is preserved
- No changes to user management - Uses existing user authentication
- No changes to TMDB client - Uses existing TMDB integration
- Test migration:
# Check that new tables exist
sqlite3 your-database.db ".schema" | grep plex_- Test API endpoints:
# Test sync trigger (with proper auth headers)
curl -X POST http://localhost:8080/api/plex/sync \
-H "Authorization: Bearer YOUR_TOKEN"- Test UI:
- Connect to Plex via existing flow
- Look for "Sync Plex Data" button in user dropdown
- Click to trigger sync and watch progress
- Migration fails: Check database permissions and syntax
- Jobs not processing: Ensure job manager is started in main server
- Auth errors: Verify
getUserIDfunction is properly implemented - Rate limiting: Check TMDB API key and rate limits
The system includes extensive debug logging. Look for:
DEBUG: [GetServers]- Server discoveryDEBUG: [SearchAllLibraries]- Library searchDEBUG: [searchMovieWithPlexgo]- Movie search- Job progress updates in console
- Initial sync: May take 10-30 minutes for large libraries
- Memory usage: Each worker uses ~50MB during sync
- Database size: Expect 1-2MB per 1000 movies
- TMDB calls: Rate limited to 40 requests per 10 seconds
If issues occur:
- Stop the server
- Restore database backup
- Revert code changes
- Restart with old system
The new system is additive - it won't break existing functionality.