-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfastapi_app.py
More file actions
1470 lines (1197 loc) · 53.2 KB
/
Copy pathfastapi_app.py
File metadata and controls
1470 lines (1197 loc) · 53.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
FastAPI Application for MVidarr
Modern async web framework with native background job support
"""
import asyncio
import logging
import os
from contextlib import asynccontextmanager
from typing import Optional
from fastapi import Depends, FastAPI, HTTPException, Query, Request, WebSocket
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
from src.api.fastapi.logging_middleware import setup_logging_middleware
from src.api.fastapi.wizard_middleware import setup_wizard_middleware
# OpenAPI documentation configuration
from src.api.openapi_config import (
add_openapi_metadata_to_routers,
custom_openapi_schema,
setup_custom_docs,
)
from src.config.config import Config
# Database and services
from src.database.connection import DatabaseManager, get_db
# Database initialization
from src.database.init_db import initialize_database
# Background job system imports
from src.services.background_workers import (
start_background_workers,
stop_background_workers,
)
from src.services.settings_service import SettingsService
from src.services.ytdlp_service import ytdlp_service
from src.utils.logger import get_logger
from src.utils.structured_logger import get_structured_logger, setup_structured_logging
# Setup structured logging
setup_structured_logging()
logger = get_logger("mvidarr.fastapi")
structured_logger = get_structured_logger("mvidarr.fastapi")
# FastAPI-specific database initialization
async def init_database_for_fastapi():
"""
Initialize database for FastAPI application
IMPORTANT: Runs synchronous database operations in thread executor to prevent
event loop blocking and connection pool issues.
"""
import src.database.connection as db_conn
def _sync_db_init():
"""Synchronous database initialization to run in thread executor"""
# Initialize database manager
config = Config()
db_conn.db_manager = DatabaseManager(config)
# Create database if it doesn't exist
if not db_conn.db_manager.create_database_if_not_exists():
logger.error("Failed to create database")
raise RuntimeError("Database creation failed")
# Test connection
if not db_conn.db_manager.test_connection():
logger.error("Database connection test failed")
raise RuntimeError("Database connection failed")
# Create engine and session factory
db_conn.engine = db_conn.db_manager.create_engine()
db_conn.SessionLocal = db_conn.db_manager.create_session_factory()
# Initialize database tables and data
if not initialize_database():
logger.error("Failed to initialize database tables")
raise RuntimeError("Database initialization failed")
logger.info("Database initialization completed successfully")
return True
# Run synchronous database initialization in thread executor to prevent event loop blocking
logger.info("Starting database initialization in thread executor...")
try:
await asyncio.to_thread(_sync_db_init)
logger.info("✅ Database initialization completed successfully")
except Exception as e:
logger.error(f"❌ Database initialization failed: {e}")
raise
# Global references for cleanup
job_queue = None
worker_tasks = []
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan handler - starts/stops background services and initializes database"""
global job_queue, worker_tasks
logger.info("FastAPI MVidarr application starting up...")
try:
# Initialize database first
logger.info("Initializing database...")
await init_database_for_fastapi()
logger.info("✅ Database initialized successfully")
# Initialize background job system with minimal configuration
logger.info("🔄 Initializing background job system...")
# Start background workers for video indexing, organization, and quality checks
await start_background_workers(num_workers=3)
logger.info(
"✅ Background workers started (3 workers for video indexing/organization)"
)
# Note: Celery + Redis system handles metadata enrichment separately
logger.info("✅ Celery + Redis system handles metadata enrichment")
# Initialize WebSocket system for real-time job progress
logger.info("🔄 Initializing WebSocket job progress system...")
await init_websocket_system(app)
logger.info("✅ WebSocket job progress system initialized")
# Start job scheduler for advanced job features
logger.info("🔄 Starting advanced job scheduler...")
await start_job_scheduler()
logger.info("✅ Advanced job scheduler started")
# Start Scheduler V2 service for scheduled downloads and video discovery (v0.10.1)
logger.info("🔄 Starting Scheduler V2 service for downloads/discovery...")
from src.services.scheduler_service_v2 import scheduler_v2
# Run scheduler_v2.start() in thread executor (it's synchronous)
result = await asyncio.to_thread(scheduler_v2.start)
if result.get("status") == "started":
logger.info("✅ Scheduler V2 service started successfully")
else:
logger.warning(f"⚠️ Scheduler V2: {result.get('message', 'Unknown status')}")
# ytdlp_service is already initialized and pending downloads resumed during import
logger.info(
"✅ ytdlp_service initialized (pending downloads auto-resumed during init)"
)
yield # Application is running
except Exception as e:
logger.error(f"Failed to start application services: {e}")
raise
finally:
# Cleanup on shutdown
logger.info("Shutting down application services...")
try:
# Stop job scheduler
logger.info("🔄 Stopping advanced job scheduler...")
await stop_job_scheduler()
logger.info("✅ Advanced job scheduler stopped")
# Stop Scheduler V2 service for scheduled downloads and video discovery (v0.10.1)
logger.info("🔄 Stopping Scheduler V2 service...")
from src.services.scheduler_service_v2 import scheduler_v2
result = await asyncio.to_thread(scheduler_v2.stop)
logger.info(f"✅ Scheduler V2 service stopped: {result.get('message', '')}")
# Cleanup WebSocket system
logger.info("🔄 Stopping WebSocket job progress system...")
await cleanup_websocket_system()
logger.info("✅ WebSocket system stopped")
# Stop background workers
logger.info("🔄 Stopping background workers...")
await stop_background_workers()
logger.info("✅ Background workers stopped")
# Celery workers are managed independently
logger.info("✅ Background job system (Celery) managed independently")
# Close database connections
import src.database.connection as db_conn
if db_conn.db_manager:
db_conn.db_manager.close_connections()
logger.info("✅ Application services stopped cleanly")
except Exception as e:
logger.error(f"Error during shutdown: {e}")
# Create FastAPI app with comprehensive OpenAPI configuration
app = FastAPI(
title="MVidarr API",
description="""
## MVidarr - Music Video Management and Automation System
**Complete FastAPI implementation with advanced async operations and comprehensive admin functionality.**
### Key Features
- **Video Management**: Complete CRUD operations with HTTP range-based streaming
- **Artist Management**: Full artist lifecycle with metadata enrichment
- **Playlist Management**: Dynamic playlists with auto-update capabilities
- **System Administration**: User management, settings, authentication, and monitoring
- **Advanced Processing**: FFmpeg operations, image processing, bulk operations
- **Performance Monitoring**: Real-time system health and performance tracking
### Authentication
This API uses session-based authentication with support for:
- OAuth providers (Google, GitHub, Authentik)
- Two-factor authentication (2FA)
- Role-based access control (USER, MANAGER, ADMIN)
- Session management and audit logging
### API Architecture
- **Async Operations**: All endpoints use async/await patterns for optimal performance
- **Pydantic Validation**: Type-safe request/response models with comprehensive validation
- **Database Integration**: SQLAlchemy ORM with async database operations
- **Background Jobs**: Native asyncio-based job system for long-running tasks
### Week 29 Consumer Features (✅ Complete)
- **Personal Cloud Backup**: Google Drive, Dropbox, OneDrive integration for music video backup
- **YouTube Import**: Import playlists, channels, and individual videos with music detection
- **Local Network Sharing**: mDNS discovery, QR codes, home network device access
- **Mobile Access**: Mobile-optimized API endpoints and responsive web app
- **Sync Manager**: Automated file synchronization with personal cloud storage
---
**Version**: 0.9.10 - Phase 3 Week 29 Consumer Features Complete
""",
version="0.9.8",
contact={
"name": "MVidarr Development Team",
"url": "https://github.com/prefect421/mvidarr",
"email": "support@mvidarr.local",
},
license_info={"name": "MIT License", "url": "https://opensource.org/licenses/MIT"},
servers=[
{"url": "http://192.168.1.145:5000", "description": "Development server"},
{"url": "http://localhost:5000", "description": "Local development server"},
],
openapi_tags=[
{
"name": "videos",
"description": "Video management operations including CRUD, streaming, thumbnails, and bulk operations",
},
{
"name": "artists",
"description": "Artist management with metadata enrichment, IMVDb integration, and video associations",
},
{
"name": "playlists",
"description": "Playlist management with dynamic filtering, file uploads, and advanced access control",
},
{
"name": "admin",
"description": "System administration including user management, audit logs, and system control",
},
{
"name": "settings",
"description": "Application settings management, scheduler control, and database configuration",
},
{
"name": "authentication",
"description": "Authentication, OAuth, session management, and credential handling",
},
{
"name": "system",
"description": "System health monitoring, performance metrics, and application status",
},
],
lifespan=lifespan,
docs_url="/docs" if os.environ.get("MVIDARR_ENV") == "dev" else None,
redoc_url="/redoc" if os.environ.get("MVIDARR_ENV") == "dev" else None,
openapi_url="/openapi.json" if os.environ.get("MVIDARR_ENV") == "dev" else None,
)
from src.api.fastapi.mobile_access import mobile_router
# Phase 3 Week 29 Integration - Personal Cloud Backup & Basic Integrations
from src.api.fastapi.week29_integration import youtube_router # Re-enabled
from src.api.fastapi.week29_integration import (
backup_router,
network_router,
sync_router,
)
# Include Week 29 API routers
app.include_router(backup_router, prefix="/api")
app.include_router(youtube_router, prefix="/api") # Re-enabled for full functionality
app.include_router(network_router, prefix="/api")
app.include_router(sync_router, prefix="/api")
app.include_router(mobile_router)
# Enhanced Artist Discovery Router
from src.api.fastapi.enhanced_artist_discovery import (
router as enhanced_discovery_router,
)
app.include_router(enhanced_discovery_router)
# YouTube Playlists Router
from src.api.fastapi.youtube_playlists import router as youtube_playlists_router
from src.api.fastapi.youtube_quota import router as youtube_quota_router
app.include_router(youtube_playlists_router)
app.include_router(
youtube_quota_router, prefix="/api/youtube-quota", tags=["YouTube Quota"]
)
# Enhanced Scheduler Router - REMOVED in v0.10.1, replaced by Scheduler V2
# Legacy enhanced_scheduler.py removed - use scheduler_v2.py and scheduled_jobs.py instead
# Webhooks Router
from src.api.fastapi.webhooks import router as webhooks_router
app.include_router(webhooks_router)
# Video Discovery Router
from src.api.fastapi.video_discovery import router as video_discovery_router
app.include_router(video_discovery_router)
# Security Router
from src.api.fastapi.security import router as security_router
app.include_router(security_router)
# Video Organization Router
from src.api.fastapi.video_organization import router as video_org_router
app.include_router(video_org_router)
# Video Indexing Router
from src.api.fastapi.video_indexing import router as video_indexing_router
app.include_router(video_indexing_router)
# MeTube Router
from src.api.fastapi.metube import router as metube_router
app.include_router(metube_router)
# YTDLP Router
from src.api.fastapi.ytdlp import router as ytdlp_router
app.include_router(ytdlp_router)
# Optimization Router
from src.api.fastapi.optimization import router as optimization_router
app.include_router(optimization_router)
# VLC Streaming Router
from src.api.fastapi.vlc_streaming import router as vlc_router
app.include_router(vlc_router)
# Spotify Enhanced Router
from src.api.fastapi.spotify_enhanced import router as spotify_enhanced_router
app.include_router(spotify_enhanced_router)
# IMVDb Router
from src.api.fastapi.imvdb import router as imvdb_router
app.include_router(imvdb_router)
# Plex Router
from src.api.fastapi.plex import router as plex_router
app.include_router(plex_router)
# Lidarr Router
from src.api.fastapi.lidarr import router as lidarr_router
app.include_router(lidarr_router)
# Health Check Router - Comprehensive Production Health Monitoring
from src.api.fastapi.health import health_router
from src.api.fastapi.maintenance import page_router as maintenance_page_router
from src.api.fastapi.maintenance import router as maintenance_router
from src.api.fastapi.personal_insights import page_router as analytics_page_router
from src.api.fastapi.personal_insights import router as analytics_router
from src.api.fastapi.system_health import page_router as system_health_page_router
from src.api.fastapi.system_health import router as system_health_router
from src.api.fastapi.video_indexing_page import (
page_router as video_indexing_page_router,
)
app.include_router(health_router, prefix="/api")
app.include_router(system_health_router)
app.include_router(system_health_page_router)
app.include_router(maintenance_router)
app.include_router(maintenance_page_router)
app.include_router(analytics_router)
app.include_router(analytics_page_router)
app.include_router(video_indexing_page_router)
logger.info(
"✅ Phase 3 Week 29 services integrated: Personal Cloud Backup, YouTube Import, Network Sharing, Sync Manager, Mobile Access"
)
# Add CORS middleware with optimized configuration
app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://192.168.1.145:5000",
"http://192.168.1.145:5010",
"http://localhost:5000",
"http://localhost:5010",
"http://127.0.0.1:5000",
"http://127.0.0.1:5010",
],
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
allow_headers=["*"],
max_age=86400, # Cache preflight requests for 24 hours
)
# Add proxy headers middleware for HTTPS reverse proxy support
# This allows FastAPI to trust X-Forwarded-* headers from reverse proxies
# Fixes mixed content issues when accessing via HTTPS proxy (e.g., https://mvidarr.prefect42.com)
app.add_middleware(
ProxyHeadersMiddleware,
trusted_hosts=os.environ.get("TRUSTED_PROXY_HOSTS", "*").split(","),
)
logger.info("✅ Proxy headers middleware enabled for reverse proxy support")
# Add request size limit middleware for DoS prevention (Issue #171)
from src.middleware.request_size_middleware import RequestSizeLimitMiddleware
app.add_middleware(
RequestSizeLimitMiddleware,
max_upload_size=100 * 1024 * 1024, # 100 MB for file uploads
max_form_size=10 * 1024 * 1024, # 10 MB for form submissions
)
logger.info("✅ Request size limit middleware enabled (uploads: 100MB, forms: 10MB)")
# Add analytics middleware - Phase 3 Week 36
from src.middleware.analytics_middleware import AnalyticsMiddleware
# Add API Gateway middleware - Phase 3 Week 37
from src.middleware.api_gateway_middleware import (
APIGatewayMiddleware,
GatewayManagementMiddleware,
)
# Add production middleware - Phase 3 Week 35
from src.middleware.auto_scaling_middleware import AutoScalingMiddleware
# Add caching middleware
from src.middleware.cache_middleware import (
APIResponseCacheMiddleware,
CacheInvalidationMiddleware,
)
from src.middleware.circuit_breaker_middleware import (
CircuitBreakerConfig,
CircuitBreakerMiddleware,
)
from src.middleware.jwt_auth_middleware import JWTAuthMiddleware, TokenConfig
# Add performance monitoring middleware
from src.middleware.performance_middleware import (
CacheHeadersMiddleware,
PerformanceTrackingMiddleware,
ResourceMonitoringMiddleware,
)
from src.middleware.rate_limiting_middleware import (
RateLimitingConfig,
RateLimitingMiddleware,
)
# Add security middleware - Phase 3 Week 34
from src.middleware.security_validation_middleware import (
SecurityValidationConfig,
SecurityValidationMiddleware,
)
# Add middleware in correct order (last added = first executed)
# Re-enabling basic authentication middleware with safe configuration
try:
from src.middleware.jwt_auth_middleware import JWTAuthMiddleware, TokenConfig
# Use basic token config to prevent timeout issues
basic_token_config = TokenConfig(
access_token_expire_minutes=60, # Longer timeout
refresh_token_expire_days=7, # Shorter refresh period
algorithm="HS256",
)
app.add_middleware(JWTAuthMiddleware, config=basic_token_config)
logger.info("✅ JWT Authentication middleware enabled with safe configuration")
except Exception as e:
logger.warning(
f"⚠️ Failed to load JWT middleware: {e}, continuing without authentication middleware"
)
# Setup structured logging middleware for production monitoring
setup_logging_middleware(app)
structured_logger.info(
"Structured logging middleware enabled for production monitoring"
)
# Setup first-run wizard middleware for v1.0.0 (Issue #163)
setup_wizard_middleware(app, wizard_redirect_url="/wizard")
logger.info("✅ First-run wizard middleware enabled")
# Security middleware - enabled
# Note: RateLimitingMiddleware disabled - SecurityValidationMiddleware has built-in
# rate limiting. Two stacked rate limiters caused 429 errors on normal page loads.
# app.add_middleware(RateLimitingMiddleware, config=RateLimitingConfig())
app.add_middleware(SecurityValidationMiddleware, config=SecurityValidationConfig())
# TODO: Re-enable other middleware after fixing MediaCacheManager and Redis issues
# app.add_middleware(CircuitBreakerMiddleware, config=CircuitBreakerConfig())
# app.add_middleware(AutoScalingMiddleware)
# app.add_middleware(CacheInvalidationMiddleware)
# app.add_middleware(APIResponseCacheMiddleware, cache_ttl=300)
# app.add_middleware(ResourceMonitoringMiddleware, track_memory=True)
# app.add_middleware(CacheHeadersMiddleware, default_cache_ttl=300)
# app.add_middleware(PerformanceTrackingMiddleware)
# app.add_middleware(AnalyticsMiddleware)
# app.add_middleware(GatewayManagementMiddleware)
# app.add_middleware(APIGatewayMiddleware, gateway_enabled=True)
# Static files and templates
app.mount("/static", StaticFiles(directory="frontend/static"), name="static")
app.mount("/css", StaticFiles(directory="frontend/CSS"), name="css")
# Use AsyncTemplateSystem instead of basic Jinja2Templates for Flask compatibility
from src.api.fastapi.template_system import get_template_system
template_system = get_template_system()
templates = template_system.templates
from src.api.fastapi.advanced_image_processing import router as advanced_image_router
from src.api.fastapi.advanced_jobs import router as advanced_jobs_router
from src.api.fastapi.image_processing import router as image_processing_router
# Include API routers - Re-enabling critical endpoints
from src.api.fastapi.jobs import router as jobs_router
from src.api.fastapi.media_processing import router as media_processing_router
# Re-enable critical missing routers
try:
from src.api.fastapi.video_quality import router as video_quality_router
logger.info("✅ Video quality router loaded successfully")
except Exception as e:
logger.warning(f"⚠️ Failed to load video quality router: {e}")
video_quality_router = None
try:
from src.api.fastapi.bulk_operations import router as bulk_operations_router
logger.info("✅ Bulk operations router loaded successfully")
except Exception as e:
logger.warning(f"⚠️ Failed to load bulk operations router: {e}")
bulk_operations_router = None
from src.api.fastapi.admin import router as fastapi_admin_router
from src.api.fastapi.api_gateway_management import router as gateway_router
from src.api.fastapi.artists import router as fastapi_artists_router
from src.api.fastapi.auth import legacy_router as fastapi_auth_legacy_router
from src.api.fastapi.auth import router as fastapi_auth_router
from src.api.fastapi.backups import router as backups_router
from src.api.fastapi.filesystem import router as filesystem_router
from src.api.fastapi.frontend_router import frontend_router
from src.api.fastapi.genres import router as fastapi_genres_router
from src.api.fastapi.monitoring_dashboard import router as dashboard_router
from src.api.fastapi.performance import router as performance_router
from src.api.fastapi.playlists import router as fastapi_playlists_router
from src.api.fastapi.production_monitoring import router as monitoring_router
# Scheduler V2 routers (v0.10.1)
from src.api.fastapi.scheduled_jobs import router as scheduled_jobs_router
from src.api.fastapi.scheduler_v2 import router as scheduler_v2_router
from src.api.fastapi.settings import router as fastapi_settings_router
from src.api.fastapi.videos import router as fastapi_videos_router
from src.api.fastapi.videos_search import router as fastapi_videos_search_router
from src.api.fastapi.videos_streaming import router as fastapi_videos_streaming_router
from src.api.fastapi.wizard import router as wizard_router
# from src.api.fastapi.music_recommendations import recommendations_router # Temporarily disabled
# from src.api.system_health import router as system_health_router
# from src.api.fastapi.model_demo import router as model_demo_router
app.include_router(jobs_router)
app.include_router(advanced_jobs_router)
app.include_router(media_processing_router)
app.include_router(image_processing_router)
app.include_router(advanced_image_router)
# Include critical routers if they loaded successfully
if video_quality_router:
app.include_router(video_quality_router)
logger.info("✅ Video quality router included")
if bulk_operations_router:
app.include_router(bulk_operations_router)
logger.info("✅ Bulk operations router included")
# Re-enable real database routers after fixing database initialization
app.include_router(fastapi_videos_router)
app.include_router(fastapi_videos_streaming_router, prefix="/api/videos")
app.include_router(fastapi_videos_search_router, prefix="/api/videos")
app.include_router(fastapi_artists_router)
app.include_router(fastapi_playlists_router)
app.include_router(fastapi_genres_router)
app.include_router(fastapi_admin_router)
app.include_router(fastapi_settings_router)
app.include_router(backups_router) # v1.0.0 Backup & Recovery (Issue #93)
app.include_router(wizard_router) # v1.0.0 Installation Wizard (Issue #163)
app.include_router(filesystem_router) # v1.0.0 Custom Directory Import (Issue #164)
app.include_router(scheduler_v2_router) # v0.10.1 Scheduler V2 control API
app.include_router(scheduled_jobs_router) # v0.10.1 Job management API
app.include_router(fastapi_auth_router)
app.include_router(fastapi_auth_legacy_router)
app.include_router(frontend_router)
from src.api.fastapi.advanced_search import router as advanced_search_router
from src.api.fastapi.discogs import router as discogs_router
from src.api.fastapi.lastfm import router as lastfm_router
# Metadata enrichment routers
from src.api.fastapi.metadata_enrichment import router as metadata_enrichment_router
from src.api.fastapi.musicbrainz import router as musicbrainz_router
from src.api.fastapi.spotify import router as spotify_router
from src.api.fastapi.themes import router as themes_router
from src.api.fastapi.two_factor_auth import router as two_factor_router
from src.api.fastapi.users import router as users_router
app.include_router(metadata_enrichment_router)
app.include_router(spotify_router)
app.include_router(musicbrainz_router)
app.include_router(discogs_router)
app.include_router(themes_router)
app.include_router(users_router)
app.include_router(lastfm_router)
app.include_router(advanced_search_router)
app.include_router(two_factor_router)
app.include_router(performance_router)
app.include_router(monitoring_router)
app.include_router(dashboard_router)
app.include_router(gateway_router)
# Add Week 29 Integration Router - Personal Cloud & YouTube Import
try:
from src.api.fastapi.week29_integration import (
backup_router,
network_router,
sync_router,
youtube_router,
)
app.include_router(backup_router, prefix="/api")
app.include_router(youtube_router, prefix="/api")
app.include_router(network_router, prefix="/api")
app.include_router(sync_router, prefix="/api")
logger.info("✅ Week 29 integration routers included")
except Exception as e:
logger.warning(f"⚠️ Failed to load Week 29 integration routers: {e}")
# Add critical missing integration endpoints temporarily using simple FastAPI routers
# These provide basic compatibility with existing frontend templates
@app.get("/api/lidarr/status", tags=["lidarr"])
async def get_lidarr_status():
"""Basic Lidarr status endpoint for template compatibility"""
return {
"status": "not_configured",
"message": "Lidarr integration not yet migrated to FastAPI",
}
@app.post("/api/lidarr/test", tags=["lidarr"])
async def test_lidarr_connection():
"""Basic Lidarr test endpoint for template compatibility"""
return {
"success": False,
"message": "Lidarr integration not yet migrated to FastAPI",
}
@app.get("/api/plex/status", tags=["plex"])
async def get_plex_status():
"""Basic Plex status endpoint for template compatibility"""
return {
"configured": False,
"connected": False,
"message": "Plex integration not yet migrated to FastAPI",
}
# app.include_router(recommendations_router) # Temporarily disabled
# app.include_router(system_health_router)
# app.include_router(model_demo_router)
# Setup enhanced OpenAPI documentation - temporarily disabled for startup
# app.openapi = lambda: custom_openapi_schema(app)
# setup_custom_docs(app)
# add_openapi_metadata_to_routers(app)
# Basic health check - Redirect to comprehensive health router
@app.get("/health")
async def health_check():
"""Simple health check endpoint - Use /api/health for comprehensive monitoring"""
return {
"status": "healthy",
"version": "0.9.8",
"framework": "FastAPI",
"job_system": "native_asyncio",
"comprehensive_health": "/api/health",
}
# NOTE: /test-login, /api/test/artists, /api/test/videos removed in v0.12.0 security hardening
@app.get("/api/discover")
async def discover_search(q: str = Query(...)):
"""Universal search endpoint for videos, artists, and external sources (IMVDb, YouTube)"""
try:
from sqlalchemy.orm import Session
from src.database.connection import get_db_session
from src.database.models import Artist, Video
# Initialize result containers
local_videos = []
local_artists = []
imvdb_results = []
youtube_results = []
# Search local database
session_gen = get_db_session()
session: Session = next(session_gen)
try:
query = q.lower()
# Search local videos
videos = (
session.query(Video)
.filter(Video.title.ilike(f"%{query}%"))
.limit(10)
.all()
)
# Search local artists
artists = (
session.query(Artist)
.filter(Artist.name.ilike(f"%{query}%"))
.limit(5)
.all()
)
# Format local video results
for video in videos:
local_videos.append(
{
"id": video.id,
"title": video.title,
"artist": video.artist.name if video.artist else "Unknown",
"status": (
video.status.value
if hasattr(video.status, "value")
else str(video.status)
),
"youtube_id": getattr(video, "youtube_id", None),
"source": "local",
"type": "video",
}
)
# Format local artist results
for artist in artists:
local_artists.append(
{
"id": artist.id,
"name": artist.name,
"video_count": len(artist.videos) if artist.videos else 0,
"source": "local",
"type": "artist",
}
)
finally:
session.close()
# Search external sources in parallel
external_search_tasks = []
# Search IMVDb
try:
from src.services.imvdb_service import imvdb_service
if imvdb_service:
import asyncio
imvdb_task = asyncio.create_task(
asyncio.to_thread(imvdb_service.search_artist, q)
)
external_search_tasks.append(("imvdb", imvdb_task))
except Exception as e:
logger.warning(f"Failed to initialize IMVDb search: {e}")
# Search YouTube
try:
from src.services.youtube_search_service import youtube_search_service
if youtube_search_service and youtube_search_service.api_key:
import asyncio
youtube_task = asyncio.create_task(
asyncio.to_thread(youtube_search_service.search_artist_videos, q, 5)
)
external_search_tasks.append(("youtube", youtube_task))
except Exception as e:
logger.warning(f"Failed to initialize YouTube search: {e}")
# Wait for external search results
if external_search_tasks:
import asyncio
for source, task in external_search_tasks:
try:
result = await asyncio.wait_for(
task, timeout=3.0
) # 3 second timeout
if source == "imvdb" and result:
if isinstance(result, list):
for item in result[:5]: # Limit to 5 results
imvdb_results.append(
{
"id": item.get("id"),
"name": item.get("name"),
"url": item.get("url"),
"source": "imvdb",
"type": "artist",
}
)
else:
imvdb_results.append(
{
"id": result.get("id"),
"name": result.get("name"),
"url": result.get("url"),
"source": "imvdb",
"type": "artist",
}
)
elif source == "youtube" and result and result.get("videos"):
for video in result["videos"][:5]: # Limit to 5 results
youtube_results.append(
{
"id": video.get("id"),
"title": video.get("title"),
"channel": video.get("channel_title"),
"thumbnail": video.get("thumbnail_url"),
"url": f"https://youtube.com/watch?v={video.get('id')}",
"source": "youtube",
"type": "video",
}
)
except asyncio.TimeoutError:
logger.warning(f"{source} search timed out")
except Exception as e:
logger.warning(f"{source} search failed: {e}")
# Combine all results
all_results = {
"videos": local_videos,
"artists": local_artists,
"external": {"imvdb": imvdb_results, "youtube": youtube_results},
}
total_count = (
len(local_videos)
+ len(local_artists)
+ len(imvdb_results)
+ len(youtube_results)
)
return {
"success": True,
"query": q,
"results": all_results,
"total": total_count,
"external_enabled": len(external_search_tasks) > 0,
}
except Exception as e:
logger.error(f"Discover search error: {e}")
return {
"success": False,
"error": str(e),
"results": {"videos": [], "artists": []},
"total": 0,
}
# Root endpoint with authentication checking
@app.get("/")
async def root(request: Request):
"""Root endpoint - redirect to dashboard if authenticated, otherwise to login"""
from fastapi.responses import RedirectResponse
try:
# Check if user is authenticated via session or other means
# For now, since we have simplified auth, check for basic auth indicators
# Try to get authentication from headers/cookies
auth_header = request.headers.get("authorization")
cookie_auth = request.cookies.get("session_token") or request.cookies.get(
"auth_token"
)
# Simple check - if we have any auth indicators, assume authenticated
# In a real system, this would validate the token/session properly
if auth_header or cookie_auth:
return RedirectResponse(url="/dashboard", status_code=302)
# Check if this is coming from a successful login (check referer)
referer = request.headers.get("referer", "")
if "auth/login" in referer or "simple-login" in referer:
# If coming from login page, redirect to dashboard
return RedirectResponse(url="/dashboard", status_code=302)
# Otherwise redirect to login
return RedirectResponse(url="/auth/login", status_code=302)
except Exception as e:
logger.error(f"Root endpoint error: {e}")
# Fallback to login on any error
return RedirectResponse(url="/auth/login", status_code=302)
# Additional missing API endpoints that frontend is looking for
@app.get("/api/metube/queue")
async def get_metube_queue():
"""Get download queue from database"""
try:
from sqlalchemy.orm import Session, joinedload
from src.database.connection import get_db_session
from src.database.models import Download
session_gen = get_db_session()
session: Session = next(session_gen)
try:
# Get downloads with queued, downloading, or processing status
downloads = (
session.query(Download)
.options(joinedload(Download.video), joinedload(Download.artist))
.filter(Download.status.in_(["queued", "downloading", "processing"]))
.order_by(Download.created_at.desc())
.all()
)
queue_items = []
for download in downloads:
queue_items.append(
{
"id": download.id,
"title": download.title,
"url": download.original_url,
"status": download.status,
"progress": download.progress or 0,
"priority": download.priority,
"created_at": (
download.created_at.isoformat()
if download.created_at
else None
),
"artist": (
download.artist.name
if download.artist
else "Unknown Artist"
),
"video_id": download.video_id,
}
)