File size: 31,384 Bytes
34637d4
36dde81
1404692
36dde81
 
d3a7f5b
36dde81
 
 
 
 
 
 
 
 
d3a7f5b
36dde81
 
 
 
 
 
 
 
 
7bb00b9
238a311
36dde81
 
 
 
 
 
 
 
 
 
1404692
 
 
d3a7f5b
39a000d
36dde81
39a000d
36dde81
39a000d
d3a7f5b
36dde81
 
d3a7f5b
 
 
 
 
 
 
 
 
 
 
 
1404692
d3a7f5b
36dde81
d3a7f5b
1404692
 
 
8732974
d3a7f5b
8732974
 
 
 
 
 
 
 
 
 
d3a7f5b
36dde81
8732974
 
 
 
 
36dde81
d3a7f5b
 
 
36dde81
 
 
 
 
d3a7f5b
39a000d
36dde81
 
f697c3b
 
36dde81
39a000d
36dde81
39a000d
 
 
36dde81
39a000d
 
 
 
 
36dde81
39a000d
d3a7f5b
 
36dde81
f697c3b
 
34637d4
f697c3b
 
 
 
36dde81
 
34637d4
36dde81
34637d4
f697c3b
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3a7f5b
 
36dde81
d3a7f5b
238a311
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c12bb0b
36dde81
 
 
 
 
 
 
 
 
 
c12bb0b
 
 
 
 
238a311
36dde81
 
 
 
 
238a311
 
 
 
 
d3a7f5b
 
1404692
d3a7f5b
36dde81
 
34637d4
1404692
 
36dde81
 
 
 
1404692
d3a7f5b
 
 
1bcc59c
d3a7f5b
 
 
 
 
f697c3b
36dde81
 
d3a7f5b
 
 
36dde81
 
 
 
d3a7f5b
 
36dde81
39a000d
36dde81
 
 
 
39a000d
36dde81
 
39a000d
 
 
 
 
 
36dde81
 
39a000d
d3a7f5b
 
 
 
 
 
 
 
 
 
 
 
 
 
39a000d
 
 
1404692
 
2211049
d3a7f5b
36dde81
d3a7f5b
f697c3b
36dde81
 
8732974
238a311
36dde81
 
 
238a311
 
 
 
 
 
 
 
 
36dde81
 
238a311
 
 
 
36dde81
 
238a311
36dde81
238a311
 
 
36dde81
238a311
 
 
36dde81
238a311
 
 
 
 
 
 
 
 
36dde81
238a311
c12bb0b
 
 
 
36dde81
c12bb0b
 
36dde81
c12bb0b
36dde81
 
c12bb0b
 
 
36dde81
 
c12bb0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
c12bb0b
 
 
36dde81
 
c12bb0b
36dde81
c12bb0b
 
 
 
 
36dde81
c12bb0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
c12bb0b
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3a7f5b
 
 
 
34637d4
d3a7f5b
f97130e
 
 
 
 
 
 
 
34637d4
f97130e
 
 
f07c3a4
36dde81
f97130e
 
d3a7f5b
 
 
 
 
36dde81
 
d3a7f5b
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
d3a7f5b
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3a7f5b
36dde81
d3a7f5b
 
 
 
 
 
 
 
7110524
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
import asyncio
import math
import mimetypes
import secrets
import time
from collections import deque
from contextvars import ContextVar
from typing import Dict
from urllib.parse import quote, unquote

from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi.responses import Response as PlainResponse
from fastapi.responses import StreamingResponse

from Backend import db
from Backend.fastapi.security.tokens import verify_token
from Backend.helper.bounded import BoundedDict
from Backend.helper.analytics import client_ip_from, record_stream_start
from Backend.helper import own_bots
from Backend.helper.cf_stream import cf_stream_url
from Backend.helper.custom_dl import ACTIVE_STREAMS, RECENT_STREAMS, ByteStreamer
from Backend.helper.encrypt import decode_string, encode_string
from Backend.helper.pyro import get_thumb_download_target
from Backend.helper.settings_manager import SettingsManager
from Backend.helper.utils import track_usage
from Backend.helper.virtual_dl import resolve_virtual_parts, virtual_stream_generator
from Backend.helper.zip_stream import resolve_zip_entry
from Backend.logger import LOGGER
import Backend.pyrofork.bot as botmod
from Backend.pyrofork.bot import (
    USERBOT_CLIENT_INDEX,
    client_dc_map,
    client_failures,
    multi_clients,
    work_loads,
)

router = APIRouter(tags=["Streaming"])

_streamer_by_client: Dict = {}
_rr_counter: int = 0
_pool: ContextVar = ContextVar("pool", default=None)

_title_cache = BoundedDict(2000)
_TITLE_CACHE_TTL = 300


#----- Recursively convert non-JSON-native containers to serializable forms
def make_json_safe(obj):
    if isinstance(obj, deque):
        return list(obj)
    if isinstance(obj, (set, tuple)):
        return list(obj)
    if isinstance(obj, bytes):
        return obj.decode("utf-8", errors="ignore")
    if isinstance(obj, dict):
        return {k: make_json_safe(v) for k, v in obj.items()}
    if isinstance(obj, list):
        return [make_json_safe(v) for v in obj]
    return obj


#----- Parse an HTTP Range header into (start, end) bounds
def parse_range_header(range_header: str, file_size: int):
    if not range_header:
        return 0, file_size - 1
    try:
        value = range_header.replace("bytes=", "").strip()
        start_str, end_str = value.split("-")
        if start_str == "":
            length = int(end_str)
            start = file_size - length
            end = file_size - 1
        elif end_str == "":
            start = int(start_str)
            end = file_size - 1
        else:
            start = int(start_str)
            end = int(end_str)
    except Exception:
        raise HTTPException(status_code=416, detail="Invalid Range header", headers={"Content-Range": f"bytes */{file_size}"})
    if start < 0:
        start = 0
    if end >= file_size:
        end = file_size - 1
    if end < start:
        raise HTTPException(status_code=416, detail="Requested Range Not Satisfiable", headers={"Content-Range": f"bytes */{file_size}"})
    return start, end


def _clients() -> dict:
    return _pool.get() or multi_clients


#----- Pick the least-loaded client, preferring the target DC, round-robin on ties
def select_best_client(target_dc: int) -> int:
    global _rr_counter
    clients = _clients()

    def _score(idx: int) -> int:
        return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)

    if target_dc > 0:
        matching = [idx for idx, dc in client_dc_map.items() if dc == target_dc and idx in clients]
    else:
        matching = []
    if not matching:
        matching = list(clients.keys())
    if not matching:
        return 0
    min_score = min(_score(i) for i in matching)
    tied = sorted(i for i in matching if _score(i) == min_score)
    selected = tied[_rr_counter % len(tied)]
    _rr_counter = (_rr_counter + 1) % max(len(clients), 1)
    return selected


#----- Periodically decay recorded client failure counters
async def decay_client_failures() -> None:
    while True:
        await asyncio.sleep(300)
        for k in list(client_failures):
            if client_failures.get(k, 0) > 0:
                client_failures[k] = max(0, client_failures[k] - 1)


#----- Parallelism/prefetch factor scaled by the number of clients
def get_parallel_prefetch(client_count: int) -> tuple[int, int]:
    value = min(max(math.ceil(client_count / 5), 1), 5)
    return value, value


#----- Reuse (or lazily create) the cached ByteStreamer for a client index
def _get_streamer(tg_client, index: int) -> ByteStreamer:
    if tg_client not in _streamer_by_client:
        _streamer_by_client[tg_client] = ByteStreamer(tg_client, index)
    return _streamer_by_client[tg_client]


def warm_streamers() -> None:
    for index, client in list(multi_clients.items()):
        _get_streamer(client, index)


def _prefetch_for(index: int) -> tuple[int, int]:
    return (1, 1) if index == USERBOT_CLIENT_INDEX else get_parallel_prefetch(len(_clients()) - 1)


#----- Run fetch(streamer) on the Userbot when it is the default streamer, else (or on failure) on the bot pool
async def _db_client(fetch):
    if not _pool.get() and SettingsManager.current().default_streaming == "userbot" and (ub := _get_userbot_streamer()):
        try:
            return USERBOT_CLIENT_INDEX, ub, await fetch(ub)
        except Exception as e:
            LOGGER.warning(f"[USERBOT] Falling back to bots: {e}")
    index = select_best_client(0)
    streamer = _get_streamer(_clients()[index], index)
    return index, streamer, await fetch(streamer)


#----- Resolve a stream title from the TTL cache, DB, or the decoded URL name
async def _lookup_title(stream_id_hash: str, decoded_name: str):
    if not stream_id_hash:
        return decoded_name
    now = time.time()
    cached = _title_cache.get(stream_id_hash)
    if cached and now < cached[1]:
        return cached[0] or decoded_name
    db_title = await db.get_title_by_stream_id(stream_id_hash)
    _title_cache[stream_id_hash] = (db_title, now + _TITLE_CACHE_TTL)
    return db_title or decoded_name


#----- Derive a display file name and mime type from file properties
def _resolve_filename_mime(file_id):
    file_name = file_id.file_name or f"{secrets.token_hex(4)}.bin"
    mime_type = file_id.mime_type or mimetypes.guess_type(file_name)[0] or "application/octet-stream"
    if "." not in file_name and "/" in mime_type:
        file_name = f"{file_name}.{mime_type.split('/')[1]}"
    return file_name, mime_type


def _content_disposition(file_name, disposition="inline"):
    ascii_fallback = file_name.encode("ascii", "ignore").decode("ascii").replace('"', "").strip() or "file"
    return f"{disposition}; filename=\"{ascii_fallback}\"; filename*=UTF-8''{quote(file_name, safe='')}"


#----- Build the shared streaming response headers and status code
def _build_stream_headers(mime_type, file_name, req_length, range_header, start, end, file_size):
    headers = {
        "Content-Type": mime_type,
        "Content-Disposition": _content_disposition(file_name),
        "Accept-Ranges": "bytes",
        "Content-Length": str(req_length),
        "Cache-Control": "public, max-age=3600",
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Expose-Headers": "Content-Length, Content-Range, Accept-Ranges",
    }
    status = 200
    if range_header:
        headers["Content-Range"] = f"bytes {start}-{end}/{file_size}"
        status = 206
    return headers, status


_thumb_cache = BoundedDict(200)
_THUMB_CACHE_TTL = 3600


#----- Serve a Telegram video/document thumbnail (public, used as artwork)
@router.get("/thumb/{id}")
async def thumb_handler(id: str):
    now = time.time()
    cached = _thumb_cache.get(id)
    if cached and now < cached[1]:
        data = cached[0]
    else:
        try:
            decoded = await decode_string(id)
            chat_id = int(f"-100{decoded['chat_id']}")
            msg_id = int(decoded["msg_id"])
        except Exception:
            raise HTTPException(status_code=400, detail="Invalid thumbnail id")
        if not multi_clients:
            raise HTTPException(status_code=503, detail="No client available")
        client = multi_clients[select_best_client(0)]
        try:
            message = await client.get_messages(chat_id, msg_id)
            target = get_thumb_download_target(message)
            if not target:
                raise HTTPException(status_code=404, detail="No thumbnail")
            file_id = getattr(target, "file_id", None) or target
            buf = await client.download_media(file_id, in_memory=True)
            data = buf.getvalue()
        except HTTPException:
            raise
        except Exception as e:
            LOGGER.warning(f"[THUMB] fetch failed for {id}: {e}")
            raise HTTPException(status_code=404, detail="Thumbnail unavailable")
        _thumb_cache[id] = (data, now + _THUMB_CACHE_TTL)

    return PlainResponse(
        content=data,
        media_type="image/jpeg",
        headers={"Cache-Control": "public, max-age=86400", "Access-Control-Allow-Origin": "*"},
    )


_SUBTITLE_MIME = {
    ".srt": "application/x-subrip",
    ".vtt": "text/vtt",
    ".ass": "text/x-ssa",
    ".ssa": "text/x-ssa",
    ".sub": "text/plain",
}


#----- Serve a subtitle file fully in-memory (files are small)
@router.get("/sub/{token}/{id}/{name}")
async def subtitle_handler(token: str, id: str, name: str, token_data: dict = Depends(verify_token)):
    try:
        decoded = await decode_string(id)
        chat_id = int(f"-100{decoded['chat_id']}")
        msg_id = int(decoded["msg_id"])
    except Exception:
        raise HTTPException(status_code=400, detail="Invalid subtitle id")

    if not multi_clients:
        raise HTTPException(status_code=503, detail="No client available")

    client = multi_clients[select_best_client(0)]
    try:
        message = await client.get_messages(chat_id, msg_id)
        buf = await client.download_media(message, in_memory=True)
        data = buf.getvalue()
    except Exception as e:
        LOGGER.warning(f"[SUBTITLE] fetch failed for {id}: {e}")
        raise HTTPException(status_code=404, detail="Subtitle unavailable")

    ext = "." + name.rsplit(".", 1)[-1].lower() if "." in name else ".srt"
    return PlainResponse(
        content=data,
        media_type=_SUBTITLE_MIME.get(ext, "application/octet-stream"),
        headers={"Cache-Control": "public, max-age=86400", "Access-Control-Allow-Origin": "*"},
    )


#----- Entry point: decode the id and dispatch to the matching streamer
@router.get("/dl/{token}/{id}/{name}")
@router.head("/dl/{token}/{id}/{name}")
async def stream_handler(request: Request, token: str, id: str, name: str, token_data: dict = Depends(verify_token)):
    decoded = await decode_string(id)

    if not decoded.get("global") and own_bots.active(token_data):
        try:
            moved = await own_bots.remap(token_data, decoded)
            cf = own_bots.worker(token_data)
            if cf and request.query_params.get("via") == "cf":
                return RedirectResponse(cf_stream_url(token, await encode_string(moved), quote(name), cf["url"], cf["secret"]), status_code=302)
            pool = await own_bots.pool_for(token_data)
            if pool:
                decoded = moved
                _pool.set(pool)
        except Exception as e:
            LOGGER.warning(f"[OWN BOTS] Falling back to owner bots: {e}")

    if request.method != "HEAD":
        asyncio.create_task(record_stream_start(
            token,
            token_data.get("name") if token_data else None,
            client_ip_from(request),
            request.headers.get("user-agent", ""),
        ))

    if decoded.get("global"):
        if decoded.get("zip"):
            return await global_zip_media_streamer(
                request=request, parts_payload=decoded["parts"],
                token=token, token_data=token_data, stream_id_hash=id,
            )
        if "parts" in decoded:
            return await global_virtual_media_streamer(
                request=request, parts_payload=decoded["parts"],
                token=token, token_data=token_data, stream_id_hash=id,
            )
        return await global_media_streamer(
            request=request, chat_id=int(decoded["chat_id"]), msg_id=int(decoded["msg_id"]),
            token=token, token_data=token_data, stream_id_hash=id,
        )

    if "parts" in decoded:
        if decoded.get("zip"):
            return await db_zip_media_streamer(
                request=request, parts_payload=decoded["parts"],
                token=token, token_data=token_data, stream_id_hash=id,
            )
        return await virtual_media_streamer(
            request=request, parts_payload=decoded["parts"],
            token=token, token_data=token_data, stream_id_hash=id,
        )

    msg_id = decoded.get("msg_id")
    if not msg_id:
        raise HTTPException(status_code=400, detail="Missing id")
    chat_id = int(f"-100{decoded['chat_id']}")
    return await media_streamer(
        request=request, chat_id=chat_id, msg_id=int(msg_id),
        token=token, token_data=token_data, stream_id_hash=id,
    )


#----- Stream a single Telegram file, with optional multi-client parallelism
async def media_streamer(request: Request, chat_id: int, msg_id: int, token: str, token_data: dict = None, stream_id_hash: str = None):
    index, streamer, file_id = await _db_client(lambda s: s.get_file_properties(chat_id=chat_id, message_id=msg_id))
    file_size = file_id.file_size
    range_header = request.headers.get("Range", "")
    start, end = parse_range_header(range_header, file_size)
    req_length = end - start + 1
    chunk_size = 1024 * 1024
    offset = start - (start % chunk_size)
    first_part_cut = start - offset
    last_part_cut = (end % chunk_size) + 1
    part_count = math.ceil(end / chunk_size) - math.floor(offset / chunk_size)
    stream_id = secrets.token_hex(8)
    decoded_name = unquote(request.path_params.get("name", ""))
    final_title = await _lookup_title(stream_id_hash, decoded_name)
    file_name, mime_type = _resolve_filename_mime(file_id)
    meta = {
        "request_path": str(request.url.path),
        "client_host": request.client.host if request.client else None,
        "title": final_title or file_name,
        "file_name": file_name,
        "user_name": token_data.get("name", "Unknown") if token_data else "Unknown",
        "token": token,
    }

    parallelism, prefetch_count = _prefetch_for(index)
    extra_clients_for_stream = []
    clients = _clients()
    if parallelism > 1 and len(clients) > 1:
        other_indices = sorted((i for i in clients if i != index), key=lambda i: work_loads.get(i, 0))

        async def _get_extra_file_id(ec_idx: int):
            ec_client = clients[ec_idx]
            ec_streamer = _get_streamer(ec_client, ec_idx)
            try:
                ec_fid = await ec_streamer.get_file_properties(chat_id=chat_id, message_id=msg_id)
                return (ec_idx, ec_streamer, ec_fid)
            except Exception as e:
                LOGGER.warning("Extra client %s file_id fetch failed: %s", ec_idx, e)
                return None

        results = await asyncio.gather(*[_get_extra_file_id(i) for i in other_indices[:parallelism - 1]])
        extra_clients_for_stream = [r for r in results if r is not None]

    body_gen = await streamer.prefetch_stream(
        file_id=file_id,
        client_index=index,
        offset=offset,
        first_part_cut=first_part_cut,
        last_part_cut=last_part_cut,
        part_count=part_count,
        chunk_size=chunk_size,
        prefetch=prefetch_count,
        stream_id=stream_id,
        meta=meta,
        parallelism=parallelism,
        request=request,
        chat_id=chat_id,
        message_id=msg_id,
        extra_clients=extra_clients_for_stream,
    )

    asyncio.create_task(track_usage(stream_id, token, token_data))

    headers, status = _build_stream_headers(mime_type, file_name, req_length, range_header, start, end, file_size)

    if request.method == "HEAD":
        return PlainResponse(status_code=status, headers=headers)
    return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type)


#----- Stream media reconstructed from multiple split parts
async def virtual_media_streamer(request: Request, parts_payload: list, token: str, token_data: dict = None, stream_id_hash: str = None):
    index, streamer, (parts, file_size) = await _db_client(lambda s: resolve_virtual_parts(parts_payload, s))
    if not parts or file_size <= 0:
        raise HTTPException(status_code=404, detail="Split media parts not found")

    range_header = request.headers.get("Range", "")
    start, end = parse_range_header(range_header, file_size)
    req_length = end - start + 1
    chunk_size = 1024 * 1024
    stream_id = secrets.token_hex(8)
    decoded_name = unquote(request.path_params.get("name", ""))
    final_title = await _lookup_title(stream_id_hash, decoded_name)
    file_name, mime_type = _resolve_filename_mime(parts[0]["file_id"])

    meta = {
        "request_path": str(request.url.path),
        "client_host": request.client.host if request.client else None,
        "title": final_title or file_name,
        "file_name": file_name,
        "user_name": token_data.get("name", "Unknown") if token_data else "Unknown",
        "token": token,
        "split_parts": len(parts),
    }

    parallelism, prefetch_count = _prefetch_for(index)

    asyncio.create_task(track_usage(stream_id, token, token_data))

    common_headers, status = _build_stream_headers(mime_type, file_name, req_length, range_header, start, end, file_size)

    if request.method == "HEAD":
        return PlainResponse(status_code=status, headers=common_headers)

    body_gen = virtual_stream_generator(
        parts=parts, start=start, end=end, chunk_size=chunk_size,
        streamer=streamer, client_index=index, request=request, meta=meta,
        stream_id=stream_id, parallelism=parallelism, prefetch_count=prefetch_count,
    )
    return StreamingResponse(body_gen, headers=common_headers, status_code=status, media_type=mime_type)


_userbot_streamer: ByteStreamer = None


#----- Lazily build and cache the ByteStreamer for the Userbot (None if unconfigured)
def _get_userbot_streamer() -> ByteStreamer:
    global _userbot_streamer
    if botmod.Userbot is None:
        return None
    if _userbot_streamer is None or _userbot_streamer.client is not botmod.Userbot:
        _userbot_streamer = ByteStreamer(botmod.Userbot, USERBOT_CLIENT_INDEX)
    return _userbot_streamer


#----- Stream a Global Search file through the Userbot session directly
async def global_media_streamer(request: Request, chat_id: int, msg_id: int, token: str, token_data: dict = None, stream_id_hash: str = None):
    streamer = _get_userbot_streamer()
    if streamer is None:
        raise HTTPException(status_code=503, detail="Global Search streaming is unavailable (no Userbot configured)")

    LOGGER.info(f"[USERBOT] Stream request: chat={chat_id} msg={msg_id}")
    try:
        file_id = await streamer.get_file_properties(chat_id=chat_id, message_id=msg_id)
    except Exception as e:
        LOGGER.error(f"[USERBOT] File not accessible: chat={chat_id} msg={msg_id}: {e}")
        raise HTTPException(status_code=404, detail="File not accessible via Global Search")

    file_size = file_id.file_size
    range_header = request.headers.get("Range", "")
    start, end = parse_range_header(range_header, file_size)
    req_length = end - start + 1
    chunk_size = 1024 * 1024
    offset = start - (start % chunk_size)
    first_part_cut = start - offset
    last_part_cut = (end % chunk_size) + 1
    part_count = math.ceil(end / chunk_size) - math.floor(offset / chunk_size)
    stream_id = secrets.token_hex(8)

    file_name, mime_type = _resolve_filename_mime(file_id)
    meta = {
        "request_path": str(request.url.path),
        "client_host": request.client.host if request.client else None,
        "title": file_name or "global-stream",
        "file_name": file_name,
        "user_name": token_data.get("name", "Unknown") if token_data else "Unknown",
        "token": token,
        "global_search": True,
    }

    asyncio.create_task(track_usage(stream_id, token, token_data))

    headers, status = _build_stream_headers(mime_type, file_name, req_length, range_header, start, end, file_size)

    if request.method == "HEAD":
        return PlainResponse(status_code=status, headers=headers)

    body_gen = await streamer.prefetch_stream(
        file_id=file_id,
        client_index=USERBOT_CLIENT_INDEX,
        offset=offset,
        first_part_cut=first_part_cut,
        last_part_cut=last_part_cut,
        part_count=part_count,
        chunk_size=chunk_size,
        prefetch=1,
        stream_id=stream_id,
        meta=meta,
        parallelism=1,
        request=request,
        chat_id=chat_id,
        message_id=msg_id,
    )
    return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type)


#----- Stream a split Global Search file (multiple parts) through the Userbot session
async def global_virtual_media_streamer(request: Request, parts_payload: list, token: str, token_data: dict = None, stream_id_hash: str = None):
    streamer = _get_userbot_streamer()
    if streamer is None:
        raise HTTPException(status_code=503, detail="Global Search streaming is unavailable (no Userbot connected)")

    parts, file_size = await resolve_virtual_parts(parts_payload, streamer, prefix_100=False)
    if not parts or file_size <= 0:
        raise HTTPException(status_code=404, detail="Split media parts not accessible via Global Search")

    range_header = request.headers.get("Range", "")
    start, end = parse_range_header(range_header, file_size)
    req_length = end - start + 1
    chunk_size = 1024 * 1024
    stream_id = secrets.token_hex(8)
    decoded_name = unquote(request.path_params.get("name", ""))
    final_title = await _lookup_title(stream_id_hash, decoded_name)
    file_name, mime_type = _resolve_filename_mime(parts[0]["file_id"])

    meta = {
        "request_path": str(request.url.path),
        "client_host": request.client.host if request.client else None,
        "title": final_title or file_name,
        "file_name": file_name,
        "user_name": token_data.get("name", "Unknown") if token_data else "Unknown",
        "token": token,
        "global_search": True,
        "split_parts": len(parts),
    }

    asyncio.create_task(track_usage(stream_id, token, token_data))

    headers, status = _build_stream_headers(mime_type, file_name, req_length, range_header, start, end, file_size)

    if request.method == "HEAD":
        return PlainResponse(status_code=status, headers=headers)

    body_gen = virtual_stream_generator(
        parts=parts, start=start, end=end, chunk_size=chunk_size,
        streamer=streamer, client_index=USERBOT_CLIENT_INDEX, request=request, meta=meta,
        stream_id=stream_id, parallelism=1, prefetch_count=1,
    )
    return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type)


#----- Read a byte range from the concatenated virtual parts into memory
async def _read_virtual_range(parts, start, length, streamer, request, client_index=USERBOT_CLIENT_INDEX, parallelism=1, prefetch_count=1):
    buf = bytearray()
    gen = virtual_stream_generator(
        parts=parts, start=start, end=start + length - 1, chunk_size=1024 * 1024,
        streamer=streamer, client_index=client_index, request=request,
        meta={"title": "zip-index", "user_name": "system", "token": ""},
        stream_id=secrets.token_hex(6), parallelism=parallelism, prefetch_count=prefetch_count,
    )
    try:
        async for chunk in gen:
            buf.extend(chunk)
            if len(buf) >= length:
                break
    finally:
        await gen.aclose()
    return bytes(buf[:length])


#----- Stream a split ZIP archive (.zip.001/.002 ...) as its inner video, with seeking.
#----- Only STORED (uncompressed) archives are seekable; the inner file bytes are served
#----- directly at their offset inside the concatenated zip (no stream-unzip needed).
async def _zip_media_streamer(request, parts_payload, token, token_data, stream_id_hash, streamer, client_index, prefix_100, parallelism, prefetch_count):
    if streamer is None:
        raise HTTPException(status_code=503, detail="ZIP streaming is unavailable (no client/session)")

    parts, zip_size = await resolve_virtual_parts(parts_payload, streamer, prefix_100=prefix_100)
    if not parts or zip_size <= 0:
        raise HTTPException(status_code=404, detail="Split archive parts not accessible")

    async def _read(off, length):
        return await _read_virtual_range(parts, off, length, streamer, request, client_index, parallelism, prefetch_count)

    entry = await resolve_zip_entry(_read, zip_size)
    if not entry:
        raise HTTPException(status_code=415, detail="Unreadable or incomplete split archive")
    if entry["method"] != 0:
        raise HTTPException(
            status_code=415,
            detail="This archive is compressed; only stored (uncompressed) ZIP archives can be seek-streamed.",
        )

    inner_size = entry["size"]
    data_offset = entry["data_offset"]
    if inner_size <= 0 or data_offset + inner_size > zip_size:
        raise HTTPException(status_code=415, detail="Split archive has an unexpected layout")

    range_header = request.headers.get("Range", "")
    start, end = parse_range_header(range_header, inner_size)
    req_length = end - start + 1
    stream_id = secrets.token_hex(8)
    inner_name = (entry.get("name") or "").split("/")[-1] or unquote(request.path_params.get("name", "")) or "video.mkv"
    mime_type = mimetypes.guess_type(inner_name)[0] or "video/x-matroska"

    meta = {
        "request_path": str(request.url.path),
        "client_host": request.client.host if request.client else None,
        "title": (await _lookup_title(stream_id_hash, inner_name)) or inner_name,
        "file_name": inner_name,
        "user_name": token_data.get("name", "Unknown") if token_data else "Unknown",
        "token": token,
        "zip_parts": len(parts),
    }
    asyncio.create_task(track_usage(stream_id, token, token_data))

    headers, status = _build_stream_headers(mime_type, inner_name, req_length, range_header, start, end, inner_size)
    if request.method == "HEAD":
        return PlainResponse(status_code=status, headers=headers)

    body_gen = virtual_stream_generator(
        parts=parts, start=data_offset + start, end=data_offset + end, chunk_size=1024 * 1024,
        streamer=streamer, client_index=client_index, request=request, meta=meta,
        stream_id=stream_id, parallelism=parallelism, prefetch_count=prefetch_count,
    )
    return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type)


#----- ZIP split from Global Search (streamed via the Userbot session)
async def global_zip_media_streamer(request: Request, parts_payload: list, token: str, token_data: dict = None, stream_id_hash: str = None):
    return await _zip_media_streamer(
        request, parts_payload, token, token_data, stream_id_hash,
        _get_userbot_streamer(), USERBOT_CLIENT_INDEX, False, 1, 1,
    )


#----- ZIP split from the indexed library (streamed via the multi-bot pool)
async def db_zip_media_streamer(request: Request, parts_payload: list, token: str, token_data: dict = None, stream_id_hash: str = None):
    index, streamer, _ = await _db_client(lambda s: resolve_virtual_parts(parts_payload[:1], s))
    parallelism, prefetch_count = _prefetch_for(index)
    return await _zip_media_streamer(
        request, parts_payload, token, token_data, stream_id_hash,
        streamer, index, True, parallelism, prefetch_count,
    )


#----- Live and recent stream telemetry, pruning stale active entries
@router.get("/stream/stats")
async def get_stream_stats():
    now = time.time()
    PRUNE_SECONDS = 3
    INACTIVE_TIMEOUT = 15
    for sid, info in list(ACTIVE_STREAMS.items()):
        status = info.get("status", "active")
        current_bytes = info.get("total_bytes", 0)
        if "last_bytes" not in info:
            info["last_bytes"] = current_bytes
            info["last_activity_ts"] = now
        if current_bytes > info["last_bytes"]:
            info["last_bytes"] = current_bytes
            info["last_activity_ts"] = now
            info["status"] = "active"
        else:
            if now - info["last_activity_ts"] > INACTIVE_TIMEOUT:
                if status == "active":
                    info["status"] = "cancelled"
                    info["end_ts"] = now
        if info.get("status") in ("cancelled", "error", "finished", "inactive"):
            last_ts = info.get("end_ts", info.get("last_activity_ts", now))
            if now - last_ts > PRUNE_SECONDS:
                try:
                    RECENT_STREAMS.appendleft(ACTIVE_STREAMS.pop(sid))
                except KeyError:
                    pass

    active = [
        {
            "stream_id": sid,
            "msg_id": info.get("msg_id"),
            "chat_id": info.get("chat_id"),
            "title": info.get("meta", {}).get("title") or info.get("meta", {}).get("file_name"),
            "file_name": info.get("meta", {}).get("file_name"),
            "client_index": info.get("client_index"),
            "dc_id": info.get("dc_id"),
            "status": info.get("status"),
            "total_bytes": info.get("total_bytes"),
            "instant_mbps": round(info.get("instant_mbps", 0.0), 3),
            "avg_mbps": round(info.get("avg_mbps", 0.0), 3),
            "peak_mbps": round(info.get("peak_mbps", 0.0), 3),
            "start_ts": info.get("start_ts"),
        }
        for sid, info in ACTIVE_STREAMS.items()
    ]
    recent = [
        {
            "stream_id": info.get("stream_id"),
            "msg_id": info.get("msg_id"),
            "chat_id": info.get("chat_id"),
            "title": info.get("meta", {}).get("title") or info.get("meta", {}).get("file_name"),
            "file_name": info.get("meta", {}).get("file_name"),
            "client_index": info.get("client_index"),
            "dc_id": info.get("dc_id"),
            "status": info.get("status"),
            "total_bytes": info.get("total_bytes"),
            "duration": info.get("duration"),
            "avg_mbps": round(info.get("avg_mbps", 0.0), 3),
            "start_ts": info.get("start_ts"),
            "end_ts": info.get("end_ts"),
        }
        for info in RECENT_STREAMS
    ]
    return JSONResponse({
        "active_streams": active,
        "recent_streams": recent,
        "client_dc_map": client_dc_map,
        "work_loads": work_loads,
    })


#----- Detailed telemetry for a single stream id
@router.get("/stream/stats/{stream_id}")
async def get_stream_detail(stream_id: str):
    info = ACTIVE_STREAMS.get(stream_id)
    if info:
        return JSONResponse(make_json_safe(info))
    for rec in RECENT_STREAMS:
        if rec.get("stream_id") == stream_id:
            return JSONResponse(make_json_safe(rec))
    raise HTTPException(status_code=404, detail="Stream not found")