File size: 33,965 Bytes
36dde81
 
 
1404692
36dde81
1404692
b5f02cc
36dde81
1404692
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1404692
36dde81
1404692
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1404692
36dde81
 
1404692
b5f02cc
 
1404692
 
 
 
 
 
36dde81
1404692
 
 
 
 
 
 
 
 
 
 
14ad4e9
1404692
36dde81
f697c3b
 
 
36dde81
 
f697c3b
36dde81
 
1404692
36dde81
1404692
36dde81
 
1404692
36dde81
1404692
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
1404692
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1404692
 
 
 
f697c3b
 
 
 
1404692
36dde81
 
b5f02cc
 
 
 
 
1404692
 
 
 
 
 
14ad4e9
 
 
1404692
36dde81
1404692
 
36dde81
1404692
 
 
 
 
 
 
 
 
 
14ad4e9
 
1404692
 
14ad4e9
 
1404692
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
1404692
 
d3a7f5b
 
 
 
 
 
 
 
36dde81
 
 
 
d3a7f5b
 
 
 
 
 
 
 
f697c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
d7f8332
 
 
 
e581a8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
e581a8c
 
 
 
 
 
 
 
 
 
36dde81
e581a8c
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f697c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c778c21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5f02cc
36dde81
 
b5f02cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
b5f02cc
 
 
 
 
 
 
 
 
 
bed5e23
 
36dde81
bed5e23
 
36dde81
bed5e23
 
 
 
 
36dde81
 
 
 
 
 
 
 
bed5e23
 
 
 
 
 
 
 
b5f02cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
36dde81
07f63a8
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532c525
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532c525
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1404692
 
36dde81
 
 
 
 
 
 
 
 
 
d7f8332
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
import asyncio

from fastapi import Depends, FastAPI, Form, HTTPException, Query, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

from Backend import __version__
from Backend.fastapi.themes import get_theme, theme_key
from Backend.fastapi.routes.api_routes import (
    add_custom_catalog_item_api,
    add_subscription_plan_api,
    apply_media_rescan_api,
    assign_plan_api,
    auto_catalog_sync_status_api,
    auto_sync_custom_catalogs_api,
    cancel_dbcheck_api,
    cancel_duplicate_check_api,
    cancel_scan_api,
    clear_cache_api,
    clear_stream_analytics_api,
    create_custom_catalog_api,
    create_token_api,
    grant_lifetime_api,
    set_token_lifetime_api,
    set_token_expiry_api,
    subscription_preflight_api,
    backfill_subscriber_names_api,
    dbcheck_status_api,
    duplicate_check_status_api,
    delete_custom_catalog_api,
    delete_media_api,
    delete_movie_quality_api,
    delete_request_api,
    delete_subscription_plan_api,
    export_config_api,
    import_config_api,
    delete_tv_episode_api,
    delete_tv_quality_api,
    delete_tv_season_api,
    download_logs_api,
    get_admin_stats_api,
    get_db_stats_api,
    get_all_subscribers_api,
    get_all_tokens_api,
    get_auto_catalog_settings_api,
    get_catalog_order_api,
    update_catalog_order_api,
    get_user_activity_api,
    session_send_code_api,
    session_verify_code_api,
    session_verify_password_api,
    session_status_api,
    session_disconnect_api,
    session_reconnect_api,
    session_remove_api,
    get_custom_catalog_items_api,
    get_dead_links_api,
    get_media_visibility_api,
    get_requests_api,
    request_popular_api,
    request_search_api,
    request_submit_api,
    get_stream_analytics_api,
    get_subscription_plans_api,
    get_settings_api,
    get_logs_api,
    get_manual_session_api,
    get_system_stats_api,
    get_tools_channels_api,
    bot_admin_scan_api,
    bot_admin_apply_api,
    bot_admin_apply_status_api,
    clear_manual_session_api,
    search_manual_session_api,
    set_manual_session_api,
    health_api,
    health_report_api,
    version_status_api,
    setup_status_api,
    link_token_user_api,
    list_custom_catalogs_api,
    list_media_api,
    manage_subscriber_api,
    manual_add_media_api,
    list_manual_add_catalogs_api,
    resolve_manual_metadata_api,
    purge_dead_links_api,
    purge_duplicates_api,
    remove_custom_catalog_item_api,
    resolve_telegram_api,
    resolve_subtitle_api,
    list_subtitle_languages_api,
    list_subtitles_api,
    add_subtitles_api,
    remove_subtitle_api,
    restart_app_api,
    revoke_token_api,
    scan_status_api,
    search_catalog_media_api,
    set_media_visibility_api,
    search_media_rescan_api,
    tag_media_api,
    speed_test_api,
    speed_test_stream_api,
    start_dbcheck_api,
    start_duplicate_check_api,
    start_scan_api,
    update_auto_catalog_settings_api,
    update_custom_catalog_api,
    update_media_api,
    update_request_api,
    update_settings_api,
    update_subscription_plan_api,
    update_token_cf_api,
    update_token_limits_api,
)
from Backend.fastapi.routes.stream_routes import decay_client_failures
from Backend.fastapi.routes.stream_routes import router as stream_router
from Backend.fastapi.routes.cf_routes import router as cf_router
from Backend.fastapi.routes.stremio_routes import router as stremio_router
from Backend.fastapi.routes.webdav_routes import router as webdav_router
from Backend.fastapi.routes.template_routes import (
    admin_access_page,
    admin_dashboard_page,
    admin_requests_page,
    admin_subscriptions_page,
    public_request_page,
    custom_catalogs_page,
    dashboard_page,
    edit_media_page,
    login_page,
    login_post,
    logout,
    media_management_page,
    settings_page,
    set_theme,
    tools_page,
)
from Backend.fastapi.security.credentials import require_auth
from Backend.pyrofork.bot import work_loads_summary

templates = Jinja2Templates(directory="Backend/fastapi/templates")

app = FastAPI(
    title="Telegram Stremio Media Server",
    description="A powerful, self-hosted Telegram Stremio Media Server built with FastAPI, MongoDB, and PyroFork seamlessly integrated with Stremio for automated media streaming and discovery.",
    version=__version__
)

#----- Middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

try:
    app.mount("/static", StaticFiles(directory="Backend/fastapi/static"), name="static")
except Exception:
    pass


@app.on_event("startup")
async def _startup():
    asyncio.create_task(decay_client_failures())
    from Backend.helper.version_check import version_check_loop
    asyncio.create_task(version_check_loop())


#----- Streaming and Stremio routers
app.include_router(stream_router)
app.include_router(cf_router)
app.include_router(stremio_router)
app.include_router(webdav_router)


#----- Public routes (no authentication)
@app.get("/login", response_class=HTMLResponse)
async def login_get(request: Request):
    return await login_page(request)

@app.post("/login", response_class=HTMLResponse)
async def login_post_route(request: Request, username: str = Form(...), password: str = Form(...)):
    return await login_post(request, username, password)

@app.get("/logout")
async def logout_route(request: Request):
    return await logout(request)

@app.post("/set-theme")
async def set_theme_route(request: Request, theme: str = Form(None)):
    return await set_theme(request, theme)

@app.get("/manifest.webmanifest")
async def pwa_manifest(request: Request):
    theme = get_theme(theme_key(request))
    return JSONResponse(
        {
            "name": "Telegram Stremio",
            "short_name": "TG Stremio",
            "description": "Telegram Stremio media management",
            "start_url": "/",
            "scope": "/",
            "display": "standalone",
            "orientation": "any",
            "background_color": theme["colors"]["background"],
            "theme_color": theme["colors"]["primary"],
            "icons": [
                {
                    "src": "/pwa-icon.svg",
                    "sizes": "any",
                    "type": "image/svg+xml",
                    "purpose": "any"
                },
                {
                    "src": "/pwa-icon.svg",
                    "sizes": "any",
                    "type": "image/svg+xml",
                    "purpose": "maskable"
                }
            ]
        },
        media_type="application/manifest+json",
        headers={"Cache-Control": "no-cache"}
    )

@app.get("/pwa-icon.svg")
async def pwa_icon(request: Request):
    theme = get_theme(theme_key(request))
    primary = theme["colors"]["primary"]
    svg = (
        f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">'
        f'<rect width="512" height="512" rx="96" fill="{primary}"/>'
        f'<path d="M200 152l176 104-176 104z" fill="{theme["colors"]["on_primary"]}"/>'
        f'</svg>'
    )
    return Response(
        content=svg,
        media_type="image/svg+xml",
        headers={"Cache-Control": "no-cache"}
    )

@app.get("/sw.js")
async def service_worker():
    js = (
        "self.addEventListener('install',e=>self.skipWaiting());"
        "self.addEventListener('activate',e=>e.waitUntil(clients.claim()));"
        "self.addEventListener('fetch',e=>e.respondWith(fetch(e.request).catch(()=>caches.match(e.request))));"
    )
    return Response(
        content=js,
        media_type="application/javascript",
        headers={"Cache-Control": "no-cache", "Service-Worker-Allowed": "/"}
    )

@app.get("/status")
async def public_status():
    return {"status": "ok", "version": __version__}

@app.get("/open/{app_name}/{media_type}/{content_id}", response_class=HTMLResponse)
async def open_in_app(app_name: str, media_type: str, content_id: str):
    stremio_type = "series" if media_type in ("series", "tv") else "movie"
    web = f"https://web.stremio.com/#/detail/{stremio_type}/{content_id}/{content_id}"
    schemes = {
        "nuvio": f"nuvio://meta?type={stremio_type}&id={content_id}",
        "stremio": f"stremio:///detail/{stremio_type}/{content_id}",
    }
    scheme = schemes.get(app_name, schemes["stremio"])
    label = "Nuvio" if app_name == "nuvio" else "Stremio"
    html = f"""<!doctype html><html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Opening {label}…</title>
<style>body{{font-family:system-ui,-apple-system,sans-serif;background:#0f172a;color:#f8fafc;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0;text-align:center}}a{{color:#60a5fa}}.b{{display:inline-block;margin-top:16px;padding:12px 22px;background:#3b82f6;color:#fff;border-radius:12px;text-decoration:none;font-weight:700}}</style>
</head><body><div><h2>Opening in {label}…</h2>
<p>If nothing happens, use the buttons below.</p>
<a class="b" href="{scheme}">Open {label}</a><br>
<a class="b" style="background:#334155" href="{web}">Open Stremio Web</a></div>
<script>setTimeout(function(){{window.location.href="{scheme}";}},200);</script>
</body></html>"""
    return HTMLResponse(html)


#----- Protected routes (authentication required)
@app.get("/", response_class=HTMLResponse)
async def root(request: Request, _: bool = Depends(require_auth)):
    return await dashboard_page(request, _)

@app.get("/admin/dashboard", response_class=HTMLResponse)
async def admin_dashboard(request: Request, _: bool = Depends(require_auth)):
    return await admin_dashboard_page(request, _)

@app.get("/media/manage", response_class=HTMLResponse)
async def media_management(request: Request, media_type: str = "movie", custom: bool = False, _: bool = Depends(require_auth)):
    return await media_management_page(request, media_type, custom, _)

@app.get("/catalogs", response_class=HTMLResponse)
async def custom_catalogs(request: Request, _: bool = Depends(require_auth)):
    return await custom_catalogs_page(request, _)

@app.get("/media/edit", response_class=HTMLResponse)
async def edit_media(request: Request, tmdb_id: int, db_index: int, media_type: str, _: bool = Depends(require_auth)):
    return await edit_media_page(request, tmdb_id, db_index, media_type, _)

@app.get("/api/media/list")
async def list_media(
    media_type: str = Query("movie", regex="^(movie|tv)$"),
    page: int = Query(1, ge=1),
    page_size: int = Query(24, ge=1, le=100),
    search: str = Query("", max_length=100),
    custom: bool = Query(False),
    _: bool = Depends(require_auth)
):
    return await list_media_api(media_type, page, page_size, search, custom)

@app.delete("/api/media/delete")
async def delete_media(tmdb_id: int, db_index: int, media_type: str, _: bool = Depends(require_auth)):
    return await delete_media_api(tmdb_id, db_index, media_type)

@app.put("/api/media/update")
async def update_media(request: Request, tmdb_id: int, db_index: int, media_type: str, _: bool = Depends(require_auth)):
    return await update_media_api(request, tmdb_id, db_index, media_type)

@app.delete("/api/media/delete-quality")
async def delete_movie_quality(tmdb_id: int, db_index: int, id: str, _: bool = Depends(require_auth)):
    return await delete_movie_quality_api(tmdb_id, db_index, id)

@app.delete("/api/media/delete-tv-quality")
async def delete_tv_quality(tmdb_id: int, db_index: int, season: int, episode: int, id: str, _: bool = Depends(require_auth)):
    return await delete_tv_quality_api(tmdb_id, db_index, season, episode, id)

@app.delete("/api/media/delete-tv-episode")
async def delete_tv_episode(tmdb_id: int, db_index: int, season: int, episode: int, _: bool = Depends(require_auth)):
    return await delete_tv_episode_api(tmdb_id, db_index, season, episode)

@app.delete("/api/media/delete-tv-season")
async def delete_tv_season(tmdb_id: int, db_index: int, season: int, _: bool = Depends(require_auth)):
    return await delete_tv_season_api(tmdb_id, db_index, season)

@app.get("/api/system/workloads")
async def get_workloads(_: bool = Depends(require_auth)):
    try:
        return {"loads": work_loads_summary()}
    except Exception:
        return {"loads": {}}

@app.post("/api/tokens")
async def create_token(payload: dict, _: bool = Depends(require_auth)):
    return await create_token_api(payload)

@app.put("/api/tokens/{token}")
async def update_token(token: str, payload: dict, _: bool = Depends(require_auth)):
    return await update_token_limits_api(token, payload)

@app.put("/api/tokens/{token}/cf")
async def update_token_cf(token: str, payload: dict, _: bool = Depends(require_auth)):
    return await update_token_cf_api(token, payload)

@app.delete("/api/tokens/{token}")
async def revoke_token(token: str, _: bool = Depends(require_auth)):
    return await revoke_token_api(token)

@app.get("/api/system/stats")
async def get_system_stats(_: bool = Depends(require_auth)):
    return await get_system_stats_api()

@app.get("/api/admin/system-stats")
async def admin_system_stats(_: bool = Depends(require_auth)):
    return await get_admin_stats_api()

@app.post("/api/admin/clear-cache")
async def clear_cache(_: bool = Depends(require_auth)):
    return await clear_cache_api()

@app.get("/api/admin/dead-links")
async def get_dead_links(_: bool = Depends(require_auth)):
    return await get_dead_links_api()

@app.get("/api/admin/stream-analytics")
async def get_stream_analytics(_: bool = Depends(require_auth)):
    return await get_stream_analytics_api()

@app.get("/api/admin/user-activity")
async def get_user_activity(page: int = 1, per_page: int = 5, _: bool = Depends(require_auth)):
    return await get_user_activity_api(page, per_page)

@app.post("/api/admin/clear-analytics")
async def clear_analytics(_: bool = Depends(require_auth)):
    return await clear_stream_analytics_api()

@app.get("/admin/subscriptions", response_class=HTMLResponse)
async def admin_subscriptions(request: Request, _: bool = Depends(require_auth)):
    return await admin_subscriptions_page(request, _)

@app.get("/api/admin/subscriptions/plans")
async def get_subscription_plans(_: bool = Depends(require_auth)):
    return await get_subscription_plans_api()

@app.post("/api/admin/subscriptions/plans")
async def add_subscription_plan(payload: dict, _: bool = Depends(require_auth)):
    return await add_subscription_plan_api(payload)

@app.put("/api/admin/subscriptions/plans/{plan_id}")
async def update_subscription_plan(plan_id: str, payload: dict, _: bool = Depends(require_auth)):
    return await update_subscription_plan_api(plan_id, payload)

@app.delete("/api/admin/subscriptions/plans/{plan_id}")
async def delete_subscription_plan(plan_id: str, _: bool = Depends(require_auth)):
    return await delete_subscription_plan_api(plan_id)

@app.get("/api/admin/subscriptions/users")
async def get_subscribers(_: bool = Depends(require_auth)):
    return await get_all_subscribers_api()

@app.post("/api/admin/subscriptions/users/{user_id}/manage")
async def manage_subscriber(user_id: int, payload: dict, _: bool = Depends(require_auth)):
    return await manage_subscriber_api(user_id, payload)


#----- Access management
@app.get("/admin/access", response_class=HTMLResponse)
async def admin_access(request: Request, _: bool = Depends(require_auth)):
    return await admin_access_page(request, _)

@app.get("/api/admin/access/tokens")
async def get_access_tokens(_: bool = Depends(require_auth)):
    return await get_all_tokens_api()

@app.delete("/api/admin/access/tokens/{token}")
async def delete_access_token(token: str, _: bool = Depends(require_auth)):
    return await revoke_token_api(token)

@app.post("/api/admin/access/users/{user_id}/assign-plan")
async def assign_access_plan(user_id: int, payload: dict, _: bool = Depends(require_auth)):
    days = int(payload.get("days", 0))
    return await assign_plan_api(user_id, days)

@app.patch("/api/admin/access/tokens/{token}/link-user")
async def link_token_to_user(token: str, payload: dict, _: bool = Depends(require_auth)):
    user_id = int(payload.get("user_id", 0))
    if not user_id:
        raise HTTPException(status_code=400, detail="user_id is required.")
    return await link_token_user_api(token, user_id)

@app.patch("/api/admin/access/tokens/{token}/lifetime")
async def set_token_lifetime(token: str, payload: dict, _: bool = Depends(require_auth)):
    return await set_token_lifetime_api(token, payload)

@app.post("/api/admin/access/tokens/{token}/expiry")
async def set_token_expiry(token: str, payload: dict, _: bool = Depends(require_auth)):
    return await set_token_expiry_api(token, payload)

@app.post("/api/admin/access/grant-lifetime")
async def grant_lifetime(_: bool = Depends(require_auth)):
    return await grant_lifetime_api()

@app.get("/api/admin/subscriptions/preflight")
async def subscription_preflight(_: bool = Depends(require_auth)):
    return await subscription_preflight_api()

@app.post("/api/admin/subscriptions/backfill-names")
async def backfill_subscriber_names(_: bool = Depends(require_auth)):
    return await backfill_subscriber_names_api()


#----- Public content request page (no auth)
@app.get("/request", response_class=HTMLResponse)
async def public_request(request: Request):
    return await public_request_page(request)

@app.get("/api/request/search")
async def request_search(q: str = Query("")):
    return await request_search_api(q)

@app.get("/api/request/popular")
async def request_popular():
    return await request_popular_api()

@app.post("/api/request/submit")
async def request_submit(payload: dict, request: Request):
    client_ip = request.client.host if request.client else None
    return await request_submit_api(payload, client_ip)


#----- Admin content requests
@app.get("/admin/requests", response_class=HTMLResponse)
async def admin_requests(request: Request, _: bool = Depends(require_auth)):
    return await admin_requests_page(request, _)

@app.get("/api/admin/requests")
async def get_requests(_: bool = Depends(require_auth)):
    return await get_requests_api()

@app.patch("/api/admin/requests/{request_id}")
async def update_request(request_id: str, payload: dict, _: bool = Depends(require_auth)):
    return await update_request_api(request_id, payload)

@app.delete("/api/admin/requests/{request_id}")
async def delete_request_route(request_id: str, _: bool = Depends(require_auth)):
    return await delete_request_api(request_id)

@app.get("/api/system/speedtest")
async def speed_test(
    quality_id: str = Query(...),
    tmdb_id: int = Query(...),
    db_index: int = Query(...),
    media_type: str = Query(...),
    _: bool = Depends(require_auth)
):
    return await speed_test_api(quality_id, tmdb_id, db_index, media_type)

@app.get("/api/system/speedtest/stream")
async def speed_test_stream(
    quality_id: str = Query(...),
    tmdb_id: int = Query(...),
    db_index: int = Query(...),
    media_type: str = Query(...),
    _: bool = Depends(require_auth)
):
    return await speed_test_stream_api(quality_id, tmdb_id, db_index, media_type)

@app.get("/api/media/rescan/search")
async def search_media_rescan(
    media_type: str,
    query: str,
    year: int | None = None,
    _: bool = Depends(require_auth)
):
    return await search_media_rescan_api(media_type, query, year)

@app.post("/api/media/rescan/apply")
async def apply_media_rescan(
    request: Request,
    tmdb_id: int,
    db_index: int,
    media_type: str,
    _: bool = Depends(require_auth)
):
    return await apply_media_rescan_api(request, tmdb_id, db_index, media_type)

@app.post("/api/media/tag")
async def tag_media(tmdb_id: int, db_index: int, media_type: str, _: bool = Depends(require_auth)):
    return await tag_media_api(tmdb_id, db_index, media_type)


#----- Manual add (custom movie/tv/season/episode/stream)
@app.post("/api/media/resolve-telegram")
async def resolve_telegram(payload: dict, _: bool = Depends(require_auth)):
    return await resolve_telegram_api(payload)

@app.post("/api/media/manual-add")
async def manual_add_media(payload: dict, _: bool = Depends(require_auth)):
    return await manual_add_media_api(payload)

@app.get("/api/media/manual-add/catalogs")
async def manual_add_catalogs(_: bool = Depends(require_auth)):
    return await list_manual_add_catalogs_api()

@app.get("/api/media/manual-add/resolve-meta")
async def manual_add_resolve_meta(media_type: str, selected_id: str, _: bool = Depends(require_auth)):
    return await resolve_manual_metadata_api(media_type, selected_id)


#----- Manual subtitle management
@app.get("/api/media/subtitles/languages")
async def subtitle_languages(_: bool = Depends(require_auth)):
    return list_subtitle_languages_api()

@app.get("/api/media/subtitles")
async def list_subtitles(media_type: str, tmdb_id: int, db_index: int, _: bool = Depends(require_auth)):
    return await list_subtitles_api(media_type, tmdb_id, db_index)

@app.post("/api/media/subtitles/resolve")
async def resolve_subtitle(payload: dict, _: bool = Depends(require_auth)):
    return await resolve_subtitle_api(payload)

@app.post("/api/media/subtitles/add")
async def add_subtitles(payload: dict, _: bool = Depends(require_auth)):
    return await add_subtitles_api(payload)

@app.post("/api/media/subtitles/remove")
async def remove_subtitle_route(payload: dict, _: bool = Depends(require_auth)):
    return await remove_subtitle_api(payload)


#----- Custom catalog management
@app.get("/api/custom-catalogs")
async def list_custom_catalogs(
    tmdb_id: int | None = None,
    db_index: int | None = None,
    media_type: str | None = None,
    _: bool = Depends(require_auth)
):
    return await list_custom_catalogs_api(tmdb_id, db_index, media_type)

@app.post("/api/custom-catalogs")
async def create_custom_catalog(payload: dict, _: bool = Depends(require_auth)):
    return await create_custom_catalog_api(payload)

@app.put("/api/custom-catalogs/{catalog_id}")
async def update_custom_catalog(catalog_id: str, payload: dict, _: bool = Depends(require_auth)):
    return await update_custom_catalog_api(catalog_id, payload)

@app.delete("/api/custom-catalogs/{catalog_id}")
async def delete_custom_catalog(catalog_id: str, _: bool = Depends(require_auth)):
    return await delete_custom_catalog_api(catalog_id)

@app.post("/api/custom-catalogs/media-visibility")
async def set_media_visibility(payload: dict, _: bool = Depends(require_auth)):
    return await set_media_visibility_api(payload)

@app.get("/api/custom-catalogs/media-visibility")
async def get_media_visibility(
    tmdb_id: int,
    db_index: int,
    media_type: str = Query("movie", regex="^(movie|tv|series)$"),
    _: bool = Depends(require_auth)
):
    return await get_media_visibility_api(tmdb_id, db_index, media_type)

@app.get("/api/custom-catalogs/search-media")
async def search_catalog_media(
    query: str,
    media_type: str = Query("movie", regex="^(movie|tv)$"),
    page: int = Query(1, ge=1),
    page_size: int = Query(12, ge=1, le=50),
    _: bool = Depends(require_auth)
):
    return await search_catalog_media_api(query, media_type, page, page_size)

@app.post("/api/custom-catalogs/auto-sync")
async def auto_sync_custom_catalogs(
    force_refresh: bool = Query(False),
    _: bool = Depends(require_auth)
):
    return await auto_sync_custom_catalogs_api(force_refresh)

@app.get("/api/custom-catalogs/auto-sync/status")
async def auto_catalog_sync_status(_: bool = Depends(require_auth)):
    return await auto_catalog_sync_status_api()

@app.get("/api/custom-catalogs-order")
async def get_catalog_order_route(_: bool = Depends(require_auth)):
    return await get_catalog_order_api()

@app.put("/api/custom-catalogs-order")
async def update_catalog_order_route(payload: dict, _: bool = Depends(require_auth)):
    return await update_catalog_order_api(payload)

@app.get("/api/custom-catalogs/auto-sync/settings")
async def get_auto_catalog_settings_route(_: bool = Depends(require_auth)):
    return await get_auto_catalog_settings_api()

@app.put("/api/custom-catalogs/auto-sync/settings")
async def update_auto_catalog_settings_route(payload: dict, _: bool = Depends(require_auth)):
    return await update_auto_catalog_settings_api(payload)

@app.get("/api/custom-catalogs/{catalog_id}/items")
async def get_custom_catalog_items(
    catalog_id: str,
    media_type: str | None = Query(None, regex="^(movie|tv)$"),
    page: int = Query(1, ge=1),
    page_size: int = Query(24, ge=1, le=100),
    _: bool = Depends(require_auth)
):
    return await get_custom_catalog_items_api(catalog_id, media_type, page, page_size)

@app.post("/api/custom-catalogs/{catalog_id}/items")
async def add_custom_catalog_item(catalog_id: str, payload: dict, _: bool = Depends(require_auth)):
    return await add_custom_catalog_item_api(catalog_id, payload)

@app.delete("/api/custom-catalogs/{catalog_id}/items")
async def remove_custom_catalog_item(
    catalog_id: str,
    tmdb_id: int,
    db_index: int,
    media_type: str = Query("movie", regex="^(movie|tv)$"),
    _: bool = Depends(require_auth)
):
    return await remove_custom_catalog_item_api(catalog_id, tmdb_id, db_index, media_type)


#----- Settings
@app.get("/admin/settings", response_class=HTMLResponse)
async def admin_settings(request: Request, _: bool = Depends(require_auth)):
    return await settings_page(request, _)

@app.get("/api/admin/settings")
async def get_settings(_: bool = Depends(require_auth)):
    return await get_settings_api()

@app.put("/api/admin/settings")
async def update_settings(payload: dict, _: bool = Depends(require_auth)):
    return await update_settings_api(payload)


@app.post("/api/admin/settings/formatter-preview")
async def formatter_preview(payload: dict, _: bool = Depends(require_auth)):
    from Backend.helper.stream_formatter import PRESETS, build_parse_value, render
    tpl = PRESETS.get(payload.get("preset")) or {"name": str(payload.get("name") or ""), "description": str(payload.get("description") or "")}
    pv = build_parse_value(str(payload.get("filename") or "video.mkv"), 2_500_000_000, channel="My Channel",
                           meta={"queryType": "movie", "type": "movie"})
    return {"name": render(tpl["name"], pv), "description": render(tpl["description"], pv)}


#----- Telegram user session login (replaces manual USER_SESSION_STRING)
@app.get("/api/admin/settings/session")
async def session_status(_: bool = Depends(require_auth)):
    return await session_status_api()

@app.post("/api/admin/settings/session/send-code")
async def session_send_code(payload: dict, _: bool = Depends(require_auth)):
    return await session_send_code_api(payload)

@app.post("/api/admin/settings/session/verify-code")
async def session_verify_code(payload: dict, _: bool = Depends(require_auth)):
    return await session_verify_code_api(payload)

@app.post("/api/admin/settings/session/verify-password")
async def session_verify_password(payload: dict, _: bool = Depends(require_auth)):
    return await session_verify_password_api(payload)

@app.post("/api/admin/settings/session/disconnect")
async def session_disconnect(_: bool = Depends(require_auth)):
    return await session_disconnect_api()

@app.post("/api/admin/settings/session/reconnect")
async def session_reconnect(_: bool = Depends(require_auth)):
    return await session_reconnect_api()

@app.delete("/api/admin/settings/session")
async def session_remove(_: bool = Depends(require_auth)):
    return await session_remove_api()


#----- System & Maintenance (WebUI replacement for /stats, /log, /restart bot commands)
@app.get("/api/admin/stats")
async def admin_db_stats(_: bool = Depends(require_auth)):
    return await get_db_stats_api()

@app.get("/api/admin/health")
async def admin_health(_: bool = Depends(require_auth)):
    return await health_api()

@app.get("/api/admin/health/report")
async def admin_health_report(fresh: bool = Query(False), _: bool = Depends(require_auth)):
    return await health_report_api(force=fresh)

@app.get("/api/admin/version")
async def admin_version(force: bool = Query(False), _: bool = Depends(require_auth)):
    return await version_status_api(force=force)

@app.get("/api/admin/setup-status")
async def admin_setup_status(_: bool = Depends(require_auth)):
    return await setup_status_api()

@app.get("/api/admin/backup/export")
async def admin_backup_export(_: bool = Depends(require_auth)):
    from fastapi.responses import JSONResponse
    data = await export_config_api()
    return JSONResponse(
        content=data,
        headers={"Content-Disposition": 'attachment; filename="telegram-stremio-backup.json"'},
    )

@app.get("/api/admin/backup/library")
async def admin_backup_library(_: bool = Depends(require_auth)):
    from fastapi.responses import StreamingResponse
    from Backend.helper.backup import export_library
    return StreamingResponse(
        export_library(), media_type="application/gzip",
        headers={"Content-Disposition": 'attachment; filename="telestremio-catalog.json.gz"'},
    )

@app.post("/api/admin/backup/import")
async def admin_backup_import(payload: dict, _: bool = Depends(require_auth)):
    return await import_config_api(payload)

@app.get("/api/admin/logs")
async def admin_logs(lines: int = Query(300, ge=1, le=2000), _: bool = Depends(require_auth)):
    return await get_logs_api(lines)

@app.get("/api/admin/logs/download")
async def admin_logs_download(_: bool = Depends(require_auth)):
    return await download_logs_api()

@app.post("/api/admin/restart")
async def admin_restart(_: bool = Depends(require_auth)):
    return await restart_app_api()


#----- Tools (WebUI replacement for /scan, /rescan, /dbcheck bot commands)
@app.get("/admin/tools", response_class=HTMLResponse)
async def admin_tools(request: Request, _: bool = Depends(require_auth)):
    return await tools_page(request, _)

@app.get("/api/admin/tools/channels")
async def tools_channels(_: bool = Depends(require_auth)):
    return await get_tools_channels_api()

@app.get("/api/admin/tools/bot-admin/scan")
async def tools_bot_admin_scan(_: bool = Depends(require_auth)):
    return await bot_admin_scan_api()

@app.post("/api/admin/tools/bot-admin/apply")
async def tools_bot_admin_apply(payload: dict, _: bool = Depends(require_auth)):
    return await bot_admin_apply_api(payload)

@app.get("/api/admin/tools/bot-admin/apply/status")
async def tools_bot_admin_apply_status(_: bool = Depends(require_auth)):
    return await bot_admin_apply_status_api()

@app.get("/api/admin/tools/manual-session")
async def tools_manual_session_get(_: bool = Depends(require_auth)):
    return await get_manual_session_api()

@app.get("/api/admin/tools/manual-session/search")
async def tools_manual_session_search(query: str = Query(""), _: bool = Depends(require_auth)):
    return await search_manual_session_api(query)

@app.post("/api/admin/tools/manual-session")
async def tools_manual_session_set(payload: dict, _: bool = Depends(require_auth)):
    return await set_manual_session_api(payload)

@app.delete("/api/admin/tools/manual-session")
async def tools_manual_session_clear(_: bool = Depends(require_auth)):
    return await clear_manual_session_api()

@app.post("/api/admin/tools/scan/start")
async def tools_scan_start(payload: dict, _: bool = Depends(require_auth)):
    return await start_scan_api(payload)

@app.post("/api/admin/tools/scan/cancel")
async def tools_scan_cancel(_: bool = Depends(require_auth)):
    return await cancel_scan_api()

@app.get("/api/admin/tools/scan/status")
async def tools_scan_status(_: bool = Depends(require_auth)):
    return await scan_status_api()

@app.post("/api/admin/tools/dbcheck/start")
async def tools_dbcheck_start(_: bool = Depends(require_auth)):
    return await start_dbcheck_api()

@app.post("/api/admin/tools/dbcheck/cancel")
async def tools_dbcheck_cancel(_: bool = Depends(require_auth)):
    return await cancel_dbcheck_api()

@app.get("/api/admin/tools/dbcheck/status")
async def tools_dbcheck_status(_: bool = Depends(require_auth)):
    return await dbcheck_status_api()

@app.post("/api/admin/tools/dead-links/purge")
async def tools_purge_dead_links(payload: dict | None = None, _: bool = Depends(require_auth)):
    return await purge_dead_links_api(payload)

@app.post("/api/admin/tools/duplicates/start")
async def tools_duplicates_start(_: bool = Depends(require_auth)):
    return await start_duplicate_check_api()

@app.post("/api/admin/tools/duplicates/cancel")
async def tools_duplicates_cancel(_: bool = Depends(require_auth)):
    return await cancel_duplicate_check_api()

@app.get("/api/admin/tools/duplicates/status")
async def tools_duplicates_status(_: bool = Depends(require_auth)):
    return await duplicate_check_status_api()

@app.post("/api/admin/tools/duplicates/purge")
async def tools_duplicates_purge(payload: dict | None = None, _: bool = Depends(require_auth)):
    return await purge_duplicates_api(payload)


@app.exception_handler(401)
async def auth_exception_handler(request: Request, exc):
    # API / stream / WebDAV clients must receive a real 401, not an HTML login redirect.
    path = request.url.path or ""
    if path.startswith(("/webdav", "/dl/", "/sub/", "/stremio/", "/api/", "/thumb/")):
        from fastapi.responses import JSONResponse
        detail = getattr(exc, "detail", "Unauthorized")
        headers = {}
        # Preserve WWW-Authenticate for WebDAV Basic auth prompts
        if hasattr(exc, "headers") and exc.headers:
            headers.update(exc.headers)
        return JSONResponse(status_code=401, content={"detail": detail}, headers=headers)
    return RedirectResponse(url="/login", status_code=302)