Karan Adhikari commited on
Update stream_routes.py
Browse files
Backend/fastapi/routes/stream_routes.py
CHANGED
|
@@ -1,23 +1,21 @@
|
|
| 1 |
import math
|
|
|
|
|
|
|
| 2 |
import secrets
|
| 3 |
import mimetypes
|
| 4 |
-
import time
|
| 5 |
from typing import Dict
|
| 6 |
-
|
|
|
|
| 7 |
from fastapi import APIRouter, Request, HTTPException, Depends
|
| 8 |
-
from fastapi.responses import StreamingResponse, JSONResponse
|
| 9 |
-
|
| 10 |
from collections import deque
|
| 11 |
-
|
| 12 |
from Backend import db
|
|
|
|
|
|
|
| 13 |
from Backend.helper.encrypt import decode_string
|
| 14 |
-
from Backend.helper.exceptions import InvalidHash
|
| 15 |
from Backend.helper.custom_dl import ByteStreamer, ACTIVE_STREAMS, RECENT_STREAMS
|
| 16 |
from Backend.pyrofork.bot import work_loads, multi_clients, client_dc_map, client_failures, client_avg_mbps
|
| 17 |
-
from Backend.config import Telegram
|
| 18 |
-
from Backend.logger import LOGGER
|
| 19 |
from Backend.fastapi.security.tokens import verify_token
|
| 20 |
-
import asyncio
|
| 21 |
|
| 22 |
router = APIRouter(tags=["Streaming"])
|
| 23 |
|
|
@@ -27,7 +25,6 @@ _rr_counter: int = 0
|
|
| 27 |
_title_cache: Dict[str, tuple] = {}
|
| 28 |
_TITLE_CACHE_TTL = 300
|
| 29 |
|
| 30 |
-
|
| 31 |
def make_json_safe(obj):
|
| 32 |
if isinstance(obj, deque):
|
| 33 |
return list(obj)
|
|
@@ -43,21 +40,11 @@ def make_json_safe(obj):
|
|
| 43 |
|
| 44 |
|
| 45 |
def parse_range_header(range_header: str, file_size: int):
|
| 46 |
-
"""
|
| 47 |
-
Parse HTTP Range header.
|
| 48 |
-
|
| 49 |
-
Supports:
|
| 50 |
-
bytes=1000-2000
|
| 51 |
-
bytes=1000-
|
| 52 |
-
bytes=-2000
|
| 53 |
-
"""
|
| 54 |
if not range_header:
|
| 55 |
return 0, file_size - 1
|
| 56 |
-
|
| 57 |
try:
|
| 58 |
value = range_header.replace("bytes=", "").strip()
|
| 59 |
start_str, end_str = value.split("-")
|
| 60 |
-
|
| 61 |
if start_str == "":
|
| 62 |
length = int(end_str)
|
| 63 |
start = file_size - length
|
|
@@ -68,47 +55,21 @@ def parse_range_header(range_header: str, file_size: int):
|
|
| 68 |
else:
|
| 69 |
start = int(start_str)
|
| 70 |
end = int(end_str)
|
| 71 |
-
|
| 72 |
except Exception:
|
| 73 |
-
raise HTTPException(
|
| 74 |
-
status_code=416,
|
| 75 |
-
detail="Invalid Range header",
|
| 76 |
-
headers={"Content-Range": f"bytes */{file_size}"},
|
| 77 |
-
)
|
| 78 |
-
|
| 79 |
if start < 0:
|
| 80 |
start = 0
|
| 81 |
-
|
| 82 |
if end >= file_size:
|
| 83 |
end = file_size - 1
|
| 84 |
-
|
| 85 |
if end < start:
|
| 86 |
-
raise HTTPException(
|
| 87 |
-
status_code=416,
|
| 88 |
-
detail="Requested Range Not Satisfiable",
|
| 89 |
-
headers={"Content-Range": f"bytes */{file_size}"},
|
| 90 |
-
)
|
| 91 |
-
|
| 92 |
return start, end
|
| 93 |
|
| 94 |
|
| 95 |
def select_best_client(target_dc: int) -> int:
|
| 96 |
-
"""Pick the best available client with round-robin tie-breaking.
|
| 97 |
-
|
| 98 |
-
Score = work_loads + 3 × client_failures.
|
| 99 |
-
When multiple clients share the minimum score (typical at startup and
|
| 100 |
-
between short seeks) Python's min() always returns the first key — i.e.
|
| 101 |
-
client 0 for every request. The round-robin counter breaks that tie so
|
| 102 |
-
all 16 bots share the load and no single bot hits Telegram FLOOD_WAIT.
|
| 103 |
-
|
| 104 |
-
target_dc > 0 → prefer same-DC clients; fall back to all if none match.
|
| 105 |
-
target_dc == 0 → no DC preference; pool is all available clients.
|
| 106 |
-
"""
|
| 107 |
global _rr_counter
|
| 108 |
-
|
| 109 |
def _score(idx: int) -> int:
|
| 110 |
return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
|
| 111 |
-
|
| 112 |
if target_dc > 0:
|
| 113 |
matching = [
|
| 114 |
idx for idx, dc in client_dc_map.items()
|
|
@@ -116,57 +77,38 @@ def select_best_client(target_dc: int) -> int:
|
|
| 116 |
]
|
| 117 |
else:
|
| 118 |
matching = []
|
| 119 |
-
|
| 120 |
if not matching:
|
| 121 |
matching = list(multi_clients.keys())
|
| 122 |
if not matching:
|
| 123 |
return 0
|
| 124 |
-
|
| 125 |
min_score = min(_score(i) for i in matching)
|
| 126 |
tied = sorted(i for i in matching if _score(i) == min_score)
|
| 127 |
-
|
| 128 |
-
# Round-robin among equally-scored candidates so every bot gets used.
|
| 129 |
selected = tied[_rr_counter % len(tied)]
|
| 130 |
_rr_counter = (_rr_counter + 1) % max(len(multi_clients), 1)
|
| 131 |
-
|
| 132 |
-
LOGGER.debug(
|
| 133 |
-
"select_best_client DC=%s → client=%s (score=%s, pool=%s)",
|
| 134 |
-
target_dc, selected, min_score, len(tied),
|
| 135 |
-
)
|
| 136 |
return selected
|
| 137 |
|
| 138 |
|
| 139 |
async def decay_client_failures() -> None:
|
| 140 |
-
"""Every 5 minutes reduce each client's failure count by 1 (floor 0).
|
| 141 |
-
|
| 142 |
-
This lets bots self-recover after a temporary DC issue without manual
|
| 143 |
-
intervention. The coroutine is started once as a background task on
|
| 144 |
-
first import.
|
| 145 |
-
"""
|
| 146 |
while True:
|
| 147 |
-
await asyncio.sleep(300)
|
| 148 |
for k in list(client_failures):
|
| 149 |
if client_failures.get(k, 0) > 0:
|
| 150 |
client_failures[k] = max(0, client_failures[k] - 1)
|
| 151 |
-
LOGGER.debug("Failure decay: client %s failures → %s", k, client_failures[k])
|
| 152 |
-
|
| 153 |
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
async def track_usage_from_stats(stream_id: str, token: str, token_data: dict):
|
| 156 |
await asyncio.sleep(2)
|
| 157 |
-
|
| 158 |
limits = token_data.get("limits", {}) if token_data else {}
|
| 159 |
usage = token_data.get("usage", {}) if token_data else {}
|
| 160 |
-
|
| 161 |
daily_limit_gb = limits.get("daily_limit_gb")
|
| 162 |
monthly_limit_gb = limits.get("monthly_limit_gb")
|
| 163 |
-
|
| 164 |
initial_daily_bytes = usage.get("daily", {}).get("bytes", 0)
|
| 165 |
initial_monthly_bytes = usage.get("monthly", {}).get("bytes", 0)
|
| 166 |
-
|
| 167 |
last_tracked_bytes = 0
|
| 168 |
-
update_interval = 10
|
| 169 |
-
|
| 170 |
try:
|
| 171 |
while True:
|
| 172 |
await asyncio.sleep(update_interval)
|
|
@@ -179,34 +121,26 @@ async def track_usage_from_stats(stream_id: str, token: str, token_data: dict):
|
|
| 179 |
if delta > 0:
|
| 180 |
try:
|
| 181 |
await db.update_token_usage(token, delta)
|
| 182 |
-
LOGGER.debug(f"Final usage update for {stream_id}: {delta} bytes")
|
| 183 |
except Exception as e:
|
| 184 |
LOGGER.error(f"Final usage update failed: {e}")
|
| 185 |
break
|
| 186 |
return
|
| 187 |
-
|
| 188 |
current_bytes = stream_info.get("total_bytes", 0)
|
| 189 |
delta = current_bytes - last_tracked_bytes
|
| 190 |
-
|
| 191 |
if delta > 0:
|
| 192 |
try:
|
| 193 |
await db.update_token_usage(token, delta)
|
| 194 |
last_tracked_bytes = current_bytes
|
| 195 |
-
LOGGER.debug(f"Updated usage for {stream_id}: +{delta} bytes (total: {current_bytes})")
|
| 196 |
except Exception as e:
|
| 197 |
LOGGER.error(f"Periodic usage update failed: {e}")
|
| 198 |
-
|
| 199 |
-
# Check limits (don't stop stream, just log - client manages connection)
|
| 200 |
if daily_limit_gb and daily_limit_gb > 0:
|
| 201 |
current_daily_gb = (initial_daily_bytes + current_bytes) / (1024 ** 3)
|
| 202 |
if current_daily_gb >= daily_limit_gb:
|
| 203 |
LOGGER.debug(f"Daily limit reached for token, stream {stream_id} may be blocked by verify_token")
|
| 204 |
-
|
| 205 |
if monthly_limit_gb and monthly_limit_gb > 0:
|
| 206 |
current_monthly_gb = (initial_monthly_bytes + current_bytes) / (1024 ** 3)
|
| 207 |
if current_monthly_gb >= monthly_limit_gb:
|
| 208 |
-
LOGGER.debug(f"Monthly limit reached for token, stream {stream_id} may be blocked by verify_token")
|
| 209 |
-
|
| 210 |
except asyncio.CancelledError:
|
| 211 |
stream_info = ACTIVE_STREAMS.get(stream_id)
|
| 212 |
if stream_info:
|
|
@@ -219,79 +153,37 @@ async def track_usage_from_stats(stream_id: str, token: str, token_data: dict):
|
|
| 219 |
except Exception as e:
|
| 220 |
LOGGER.error(f"Cancelled usage update failed: {e}")
|
| 221 |
|
| 222 |
-
|
| 223 |
@router.get("/dl/{token}/{id}/{name}")
|
| 224 |
@router.head("/dl/{token}/{id}/{name}")
|
| 225 |
-
async def stream_handler(
|
| 226 |
-
request: Request,
|
| 227 |
-
token: str,
|
| 228 |
-
id: str,
|
| 229 |
-
name: str,
|
| 230 |
-
token_data: dict = Depends(verify_token),
|
| 231 |
-
):
|
| 232 |
decoded = await decode_string(id)
|
| 233 |
msg_id = decoded.get("msg_id")
|
| 234 |
if not msg_id:
|
| 235 |
raise HTTPException(status_code=400, detail="Missing id")
|
| 236 |
-
|
| 237 |
chat_id = int(f"-100{decoded['chat_id']}")
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
# on every seek. File identity is verified by the streaming client.
|
| 241 |
-
return await media_streamer(
|
| 242 |
-
request=request,
|
| 243 |
-
chat_id=chat_id,
|
| 244 |
-
msg_id=int(msg_id),
|
| 245 |
-
secure_hash="SKIP_HASH_CHECK",
|
| 246 |
-
token=token,
|
| 247 |
-
token_data=token_data,
|
| 248 |
-
stream_id_hash=id,
|
| 249 |
)
|
| 250 |
|
| 251 |
-
async def media_streamer(
|
| 252 |
-
request: Request,
|
| 253 |
-
chat_id: int,
|
| 254 |
-
msg_id: int,
|
| 255 |
-
secure_hash: str,
|
| 256 |
-
token: str,
|
| 257 |
-
token_data: dict = None,
|
| 258 |
-
stream_id_hash: str = None,
|
| 259 |
-
):
|
| 260 |
-
# Pick the primary client and fetch file metadata.
|
| 261 |
index = select_best_client(0)
|
| 262 |
tg_client = multi_clients[index]
|
| 263 |
if tg_client not in _streamer_by_client:
|
| 264 |
_streamer_by_client[tg_client] = ByteStreamer(tg_client, index)
|
| 265 |
streamer: ByteStreamer = _streamer_by_client[tg_client]
|
| 266 |
-
|
| 267 |
file_id = await streamer.get_file_properties(chat_id=chat_id, message_id=msg_id)
|
| 268 |
target_dc = file_id.dc_id
|
| 269 |
-
|
| 270 |
-
if secure_hash != "SKIP_HASH_CHECK":
|
| 271 |
-
if file_id.unique_id[:6] != secure_hash:
|
| 272 |
-
raise InvalidHash
|
| 273 |
-
|
| 274 |
-
LOGGER.debug("Stream msg_id=%s DC=%s via client=%s", msg_id, target_dc, index)
|
| 275 |
-
|
| 276 |
file_size = file_id.file_size
|
| 277 |
range_header = request.headers.get("Range", "")
|
| 278 |
start, end = parse_range_header(range_header, file_size)
|
| 279 |
req_length = end - start + 1
|
| 280 |
-
|
| 281 |
chunk_size = 1024 * 1024
|
| 282 |
offset = start - (start % chunk_size)
|
| 283 |
first_part_cut = start - offset
|
| 284 |
last_part_cut = (end % chunk_size) + 1
|
| 285 |
part_count = math.ceil(end / chunk_size) - math.floor(offset / chunk_size)
|
| 286 |
-
|
| 287 |
-
from urllib.parse import unquote
|
| 288 |
-
|
| 289 |
stream_id = secrets.token_hex(8)
|
| 290 |
-
|
| 291 |
-
# Extract original title from the URL path name, fallback to raw name
|
| 292 |
decoded_name = unquote(request.path_params.get("name", ""))
|
| 293 |
-
|
| 294 |
-
# Look up the real title — cached to avoid a DB hit on every seek.
|
| 295 |
db_title = None
|
| 296 |
if stream_id_hash:
|
| 297 |
_now = time.time()
|
|
@@ -301,10 +193,7 @@ async def media_streamer(
|
|
| 301 |
else:
|
| 302 |
db_title = await db.get_title_by_stream_id(stream_id_hash)
|
| 303 |
_title_cache[stream_id_hash] = (db_title, _now + _TITLE_CACHE_TTL)
|
| 304 |
-
LOGGER.info(f"Stream lookup for hash '{stream_id_hash}' returned title: {db_title}")
|
| 305 |
-
|
| 306 |
final_title = db_title if db_title else decoded_name
|
| 307 |
-
|
| 308 |
meta = {
|
| 309 |
"request_path": str(request.url.path),
|
| 310 |
"client_host": request.client.host if request.client else None,
|
|
@@ -312,18 +201,14 @@ async def media_streamer(
|
|
| 312 |
"user_name": token_data.get("name", "Unknown") if token_data else "Unknown"
|
| 313 |
}
|
| 314 |
|
| 315 |
-
|
| 316 |
-
prefetch_count =
|
| 317 |
-
|
| 318 |
-
# Gather extra bot clients so each parallel GetFile slot uses a different
|
| 319 |
-
# Telegram account — different rate-limit buckets, no per-session FloodWait.
|
| 320 |
extra_clients_for_stream = []
|
| 321 |
if parallelism > 1 and len(multi_clients) > 1:
|
| 322 |
other_indices = sorted(
|
| 323 |
(i for i in multi_clients if i != index),
|
| 324 |
key=lambda i: work_loads.get(i, 0),
|
| 325 |
)
|
| 326 |
-
|
| 327 |
async def _get_extra_file_id(ec_idx: int):
|
| 328 |
ec_client = multi_clients[ec_idx]
|
| 329 |
if ec_client not in _streamer_by_client:
|
|
@@ -335,7 +220,6 @@ async def media_streamer(
|
|
| 335 |
except Exception as e:
|
| 336 |
LOGGER.warning("Extra client %s file_id fetch failed: %s", ec_idx, e)
|
| 337 |
return None
|
| 338 |
-
|
| 339 |
results = await asyncio.gather(*[
|
| 340 |
_get_extra_file_id(i) for i in other_indices[:parallelism - 1]
|
| 341 |
])
|
|
@@ -366,10 +250,7 @@ async def media_streamer(
|
|
| 366 |
|
| 367 |
if "." not in file_name and "/" in mime_type:
|
| 368 |
file_name = f"{file_name}.{mime_type.split('/')[1]}"
|
| 369 |
-
|
| 370 |
-
# HEAD request support
|
| 371 |
-
from fastapi.responses import Response as PlainResponse
|
| 372 |
-
|
| 373 |
if request.method == "HEAD":
|
| 374 |
headers = {
|
| 375 |
"Content-Type": mime_type,
|
|
@@ -405,43 +286,28 @@ async def media_streamer(
|
|
| 405 |
else:
|
| 406 |
status = 200
|
| 407 |
|
| 408 |
-
return StreamingResponse(
|
| 409 |
-
body_gen,
|
| 410 |
-
headers=headers,
|
| 411 |
-
status_code=status,
|
| 412 |
-
media_type=mime_type,
|
| 413 |
-
)
|
| 414 |
-
|
| 415 |
|
| 416 |
@router.get("/stream/stats")
|
| 417 |
async def get_stream_stats():
|
| 418 |
now = time.time()
|
| 419 |
-
|
| 420 |
PRUNE_SECONDS = 3
|
| 421 |
-
INACTIVE_TIMEOUT = 15
|
| 422 |
-
|
| 423 |
for sid, info in list(ACTIVE_STREAMS.items()):
|
| 424 |
status = info.get("status", "active")
|
| 425 |
-
|
| 426 |
current_bytes = info.get("total_bytes", 0)
|
| 427 |
-
|
| 428 |
if "last_bytes" not in info:
|
| 429 |
info["last_bytes"] = current_bytes
|
| 430 |
info["last_activity_ts"] = now
|
| 431 |
-
|
| 432 |
-
|
| 433 |
if current_bytes > info["last_bytes"]:
|
| 434 |
-
# Data is flowing → update activity timestamp
|
| 435 |
info["last_bytes"] = current_bytes
|
| 436 |
info["last_activity_ts"] = now
|
| 437 |
-
info["status"] = "active"
|
| 438 |
else:
|
| 439 |
-
# No data flow → check inactivity timeout
|
| 440 |
if now - info["last_activity_ts"] > INACTIVE_TIMEOUT:
|
| 441 |
if status == "active":
|
| 442 |
info["status"] = "cancelled"
|
| 443 |
-
info["end_ts"] = now
|
| 444 |
-
|
| 445 |
if info.get("status") in ("cancelled", "error", "finished", "inactive"):
|
| 446 |
last_ts = info.get("end_ts", info.get("last_activity_ts", now))
|
| 447 |
if now - last_ts > PRUNE_SECONDS:
|
|
@@ -449,7 +315,6 @@ async def get_stream_stats():
|
|
| 449 |
RECENT_STREAMS.appendleft(ACTIVE_STREAMS.pop(sid))
|
| 450 |
except KeyError:
|
| 451 |
pass
|
| 452 |
-
|
| 453 |
active = []
|
| 454 |
for sid, info in ACTIVE_STREAMS.items():
|
| 455 |
active.append(
|
|
@@ -468,7 +333,6 @@ async def get_stream_stats():
|
|
| 468 |
"start_ts": info.get("start_ts"),
|
| 469 |
}
|
| 470 |
)
|
| 471 |
-
|
| 472 |
recent = []
|
| 473 |
for info in RECENT_STREAMS:
|
| 474 |
recent.append(
|
|
@@ -487,7 +351,6 @@ async def get_stream_stats():
|
|
| 487 |
"end_ts": info.get("end_ts"),
|
| 488 |
}
|
| 489 |
)
|
| 490 |
-
|
| 491 |
return JSONResponse(
|
| 492 |
{
|
| 493 |
"active_streams": active,
|
|
@@ -502,9 +365,7 @@ async def get_stream_detail(stream_id: str):
|
|
| 502 |
info = ACTIVE_STREAMS.get(stream_id)
|
| 503 |
if info:
|
| 504 |
return JSONResponse(make_json_safe(info))
|
| 505 |
-
|
| 506 |
for rec in RECENT_STREAMS:
|
| 507 |
if rec.get("stream_id") == stream_id:
|
| 508 |
return JSONResponse(make_json_safe(rec))
|
| 509 |
-
|
| 510 |
raise HTTPException(status_code=404, detail="Stream not found")
|
|
|
|
| 1 |
import math
|
| 2 |
+
import time
|
| 3 |
+
import asyncio
|
| 4 |
import secrets
|
| 5 |
import mimetypes
|
|
|
|
| 6 |
from typing import Dict
|
| 7 |
+
from urllib.parse import unquote
|
| 8 |
+
from math import ceil
|
| 9 |
from fastapi import APIRouter, Request, HTTPException, Depends
|
| 10 |
+
from fastapi.responses import Response as PlainResponse, StreamingResponse, JSONResponse
|
|
|
|
| 11 |
from collections import deque
|
|
|
|
| 12 |
from Backend import db
|
| 13 |
+
from Backend.config import Telegram
|
| 14 |
+
from Backend.logger import LOGGER
|
| 15 |
from Backend.helper.encrypt import decode_string
|
|
|
|
| 16 |
from Backend.helper.custom_dl import ByteStreamer, ACTIVE_STREAMS, RECENT_STREAMS
|
| 17 |
from Backend.pyrofork.bot import work_loads, multi_clients, client_dc_map, client_failures, client_avg_mbps
|
|
|
|
|
|
|
| 18 |
from Backend.fastapi.security.tokens import verify_token
|
|
|
|
| 19 |
|
| 20 |
router = APIRouter(tags=["Streaming"])
|
| 21 |
|
|
|
|
| 25 |
_title_cache: Dict[str, tuple] = {}
|
| 26 |
_TITLE_CACHE_TTL = 300
|
| 27 |
|
|
|
|
| 28 |
def make_json_safe(obj):
|
| 29 |
if isinstance(obj, deque):
|
| 30 |
return list(obj)
|
|
|
|
| 40 |
|
| 41 |
|
| 42 |
def parse_range_header(range_header: str, file_size: int):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
if not range_header:
|
| 44 |
return 0, file_size - 1
|
|
|
|
| 45 |
try:
|
| 46 |
value = range_header.replace("bytes=", "").strip()
|
| 47 |
start_str, end_str = value.split("-")
|
|
|
|
| 48 |
if start_str == "":
|
| 49 |
length = int(end_str)
|
| 50 |
start = file_size - length
|
|
|
|
| 55 |
else:
|
| 56 |
start = int(start_str)
|
| 57 |
end = int(end_str)
|
|
|
|
| 58 |
except Exception:
|
| 59 |
+
raise HTTPException(status_code=416, detail="Invalid Range header", headers={"Content-Range": f"bytes */{file_size}"}, )
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
if start < 0:
|
| 61 |
start = 0
|
|
|
|
| 62 |
if end >= file_size:
|
| 63 |
end = file_size - 1
|
|
|
|
| 64 |
if end < start:
|
| 65 |
+
raise HTTPException(status_code=416, detail="Requested Range Not Satisfiable", headers={"Content-Range": f"bytes */{file_size}"},)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
return start, end
|
| 67 |
|
| 68 |
|
| 69 |
def select_best_client(target_dc: int) -> int:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
global _rr_counter
|
|
|
|
| 71 |
def _score(idx: int) -> int:
|
| 72 |
return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
|
|
|
|
| 73 |
if target_dc > 0:
|
| 74 |
matching = [
|
| 75 |
idx for idx, dc in client_dc_map.items()
|
|
|
|
| 77 |
]
|
| 78 |
else:
|
| 79 |
matching = []
|
|
|
|
| 80 |
if not matching:
|
| 81 |
matching = list(multi_clients.keys())
|
| 82 |
if not matching:
|
| 83 |
return 0
|
|
|
|
| 84 |
min_score = min(_score(i) for i in matching)
|
| 85 |
tied = sorted(i for i in matching if _score(i) == min_score)
|
|
|
|
|
|
|
| 86 |
selected = tied[_rr_counter % len(tied)]
|
| 87 |
_rr_counter = (_rr_counter + 1) % max(len(multi_clients), 1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
return selected
|
| 89 |
|
| 90 |
|
| 91 |
async def decay_client_failures() -> None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
while True:
|
| 93 |
+
await asyncio.sleep(300)
|
| 94 |
for k in list(client_failures):
|
| 95 |
if client_failures.get(k, 0) > 0:
|
| 96 |
client_failures[k] = max(0, client_failures[k] - 1)
|
|
|
|
|
|
|
| 97 |
|
| 98 |
+
def get_parallel_prefetch(client_count: int) -> tuple[int, int]:
|
| 99 |
+
value = min(max(ceil(client_count / 5), 1), 5)
|
| 100 |
+
return value, value
|
| 101 |
|
| 102 |
async def track_usage_from_stats(stream_id: str, token: str, token_data: dict):
|
| 103 |
await asyncio.sleep(2)
|
|
|
|
| 104 |
limits = token_data.get("limits", {}) if token_data else {}
|
| 105 |
usage = token_data.get("usage", {}) if token_data else {}
|
|
|
|
| 106 |
daily_limit_gb = limits.get("daily_limit_gb")
|
| 107 |
monthly_limit_gb = limits.get("monthly_limit_gb")
|
|
|
|
| 108 |
initial_daily_bytes = usage.get("daily", {}).get("bytes", 0)
|
| 109 |
initial_monthly_bytes = usage.get("monthly", {}).get("bytes", 0)
|
|
|
|
| 110 |
last_tracked_bytes = 0
|
| 111 |
+
update_interval = 10
|
|
|
|
| 112 |
try:
|
| 113 |
while True:
|
| 114 |
await asyncio.sleep(update_interval)
|
|
|
|
| 121 |
if delta > 0:
|
| 122 |
try:
|
| 123 |
await db.update_token_usage(token, delta)
|
|
|
|
| 124 |
except Exception as e:
|
| 125 |
LOGGER.error(f"Final usage update failed: {e}")
|
| 126 |
break
|
| 127 |
return
|
|
|
|
| 128 |
current_bytes = stream_info.get("total_bytes", 0)
|
| 129 |
delta = current_bytes - last_tracked_bytes
|
|
|
|
| 130 |
if delta > 0:
|
| 131 |
try:
|
| 132 |
await db.update_token_usage(token, delta)
|
| 133 |
last_tracked_bytes = current_bytes
|
|
|
|
| 134 |
except Exception as e:
|
| 135 |
LOGGER.error(f"Periodic usage update failed: {e}")
|
|
|
|
|
|
|
| 136 |
if daily_limit_gb and daily_limit_gb > 0:
|
| 137 |
current_daily_gb = (initial_daily_bytes + current_bytes) / (1024 ** 3)
|
| 138 |
if current_daily_gb >= daily_limit_gb:
|
| 139 |
LOGGER.debug(f"Daily limit reached for token, stream {stream_id} may be blocked by verify_token")
|
|
|
|
| 140 |
if monthly_limit_gb and monthly_limit_gb > 0:
|
| 141 |
current_monthly_gb = (initial_monthly_bytes + current_bytes) / (1024 ** 3)
|
| 142 |
if current_monthly_gb >= monthly_limit_gb:
|
| 143 |
+
LOGGER.debug(f"Monthly limit reached for token, stream {stream_id} may be blocked by verify_token")
|
|
|
|
| 144 |
except asyncio.CancelledError:
|
| 145 |
stream_info = ACTIVE_STREAMS.get(stream_id)
|
| 146 |
if stream_info:
|
|
|
|
| 153 |
except Exception as e:
|
| 154 |
LOGGER.error(f"Cancelled usage update failed: {e}")
|
| 155 |
|
|
|
|
| 156 |
@router.get("/dl/{token}/{id}/{name}")
|
| 157 |
@router.head("/dl/{token}/{id}/{name}")
|
| 158 |
+
async def stream_handler(request: Request, token: str, id: str, name: str, token_data: dict = Depends(verify_token),):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
decoded = await decode_string(id)
|
| 160 |
msg_id = decoded.get("msg_id")
|
| 161 |
if not msg_id:
|
| 162 |
raise HTTPException(status_code=400, detail="Missing id")
|
|
|
|
| 163 |
chat_id = int(f"-100{decoded['chat_id']}")
|
| 164 |
+
return await media_streamer(request=request, chat_id=chat_id, msg_id=int(msg_id),
|
| 165 |
+
token=token, token_data=token_data, stream_id_hash=id,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
)
|
| 167 |
|
| 168 |
+
async def media_streamer(request: Request, chat_id: int, msg_id: int, token: str, token_data: dict = None, stream_id_hash: str = None,):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
index = select_best_client(0)
|
| 170 |
tg_client = multi_clients[index]
|
| 171 |
if tg_client not in _streamer_by_client:
|
| 172 |
_streamer_by_client[tg_client] = ByteStreamer(tg_client, index)
|
| 173 |
streamer: ByteStreamer = _streamer_by_client[tg_client]
|
|
|
|
| 174 |
file_id = await streamer.get_file_properties(chat_id=chat_id, message_id=msg_id)
|
| 175 |
target_dc = file_id.dc_id
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
file_size = file_id.file_size
|
| 177 |
range_header = request.headers.get("Range", "")
|
| 178 |
start, end = parse_range_header(range_header, file_size)
|
| 179 |
req_length = end - start + 1
|
|
|
|
| 180 |
chunk_size = 1024 * 1024
|
| 181 |
offset = start - (start % chunk_size)
|
| 182 |
first_part_cut = start - offset
|
| 183 |
last_part_cut = (end % chunk_size) + 1
|
| 184 |
part_count = math.ceil(end / chunk_size) - math.floor(offset / chunk_size)
|
|
|
|
|
|
|
|
|
|
| 185 |
stream_id = secrets.token_hex(8)
|
|
|
|
|
|
|
| 186 |
decoded_name = unquote(request.path_params.get("name", ""))
|
|
|
|
|
|
|
| 187 |
db_title = None
|
| 188 |
if stream_id_hash:
|
| 189 |
_now = time.time()
|
|
|
|
| 193 |
else:
|
| 194 |
db_title = await db.get_title_by_stream_id(stream_id_hash)
|
| 195 |
_title_cache[stream_id_hash] = (db_title, _now + _TITLE_CACHE_TTL)
|
|
|
|
|
|
|
| 196 |
final_title = db_title if db_title else decoded_name
|
|
|
|
| 197 |
meta = {
|
| 198 |
"request_path": str(request.url.path),
|
| 199 |
"client_host": request.client.host if request.client else None,
|
|
|
|
| 201 |
"user_name": token_data.get("name", "Unknown") if token_data else "Unknown"
|
| 202 |
}
|
| 203 |
|
| 204 |
+
token_count = len(multi_clients) - 1
|
| 205 |
+
parallelism, prefetch_count = get_parallel_prefetch(token_count)
|
|
|
|
|
|
|
|
|
|
| 206 |
extra_clients_for_stream = []
|
| 207 |
if parallelism > 1 and len(multi_clients) > 1:
|
| 208 |
other_indices = sorted(
|
| 209 |
(i for i in multi_clients if i != index),
|
| 210 |
key=lambda i: work_loads.get(i, 0),
|
| 211 |
)
|
|
|
|
| 212 |
async def _get_extra_file_id(ec_idx: int):
|
| 213 |
ec_client = multi_clients[ec_idx]
|
| 214 |
if ec_client not in _streamer_by_client:
|
|
|
|
| 220 |
except Exception as e:
|
| 221 |
LOGGER.warning("Extra client %s file_id fetch failed: %s", ec_idx, e)
|
| 222 |
return None
|
|
|
|
| 223 |
results = await asyncio.gather(*[
|
| 224 |
_get_extra_file_id(i) for i in other_indices[:parallelism - 1]
|
| 225 |
])
|
|
|
|
| 250 |
|
| 251 |
if "." not in file_name and "/" in mime_type:
|
| 252 |
file_name = f"{file_name}.{mime_type.split('/')[1]}"
|
| 253 |
+
|
|
|
|
|
|
|
|
|
|
| 254 |
if request.method == "HEAD":
|
| 255 |
headers = {
|
| 256 |
"Content-Type": mime_type,
|
|
|
|
| 286 |
else:
|
| 287 |
status = 200
|
| 288 |
|
| 289 |
+
return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type, )
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
|
| 291 |
@router.get("/stream/stats")
|
| 292 |
async def get_stream_stats():
|
| 293 |
now = time.time()
|
|
|
|
| 294 |
PRUNE_SECONDS = 3
|
| 295 |
+
INACTIVE_TIMEOUT = 15
|
|
|
|
| 296 |
for sid, info in list(ACTIVE_STREAMS.items()):
|
| 297 |
status = info.get("status", "active")
|
|
|
|
| 298 |
current_bytes = info.get("total_bytes", 0)
|
|
|
|
| 299 |
if "last_bytes" not in info:
|
| 300 |
info["last_bytes"] = current_bytes
|
| 301 |
info["last_activity_ts"] = now
|
|
|
|
|
|
|
| 302 |
if current_bytes > info["last_bytes"]:
|
|
|
|
| 303 |
info["last_bytes"] = current_bytes
|
| 304 |
info["last_activity_ts"] = now
|
| 305 |
+
info["status"] = "active"
|
| 306 |
else:
|
|
|
|
| 307 |
if now - info["last_activity_ts"] > INACTIVE_TIMEOUT:
|
| 308 |
if status == "active":
|
| 309 |
info["status"] = "cancelled"
|
| 310 |
+
info["end_ts"] = now
|
|
|
|
| 311 |
if info.get("status") in ("cancelled", "error", "finished", "inactive"):
|
| 312 |
last_ts = info.get("end_ts", info.get("last_activity_ts", now))
|
| 313 |
if now - last_ts > PRUNE_SECONDS:
|
|
|
|
| 315 |
RECENT_STREAMS.appendleft(ACTIVE_STREAMS.pop(sid))
|
| 316 |
except KeyError:
|
| 317 |
pass
|
|
|
|
| 318 |
active = []
|
| 319 |
for sid, info in ACTIVE_STREAMS.items():
|
| 320 |
active.append(
|
|
|
|
| 333 |
"start_ts": info.get("start_ts"),
|
| 334 |
}
|
| 335 |
)
|
|
|
|
| 336 |
recent = []
|
| 337 |
for info in RECENT_STREAMS:
|
| 338 |
recent.append(
|
|
|
|
| 351 |
"end_ts": info.get("end_ts"),
|
| 352 |
}
|
| 353 |
)
|
|
|
|
| 354 |
return JSONResponse(
|
| 355 |
{
|
| 356 |
"active_streams": active,
|
|
|
|
| 365 |
info = ACTIVE_STREAMS.get(stream_id)
|
| 366 |
if info:
|
| 367 |
return JSONResponse(make_json_safe(info))
|
|
|
|
| 368 |
for rec in RECENT_STREAMS:
|
| 369 |
if rec.get("stream_id") == stream_id:
|
| 370 |
return JSONResponse(make_json_safe(rec))
|
|
|
|
| 371 |
raise HTTPException(status_code=404, detail="Stream not found")
|