weebzone commited on
Commit
d3a7f5b
ยท
1 Parent(s): adf3244

`๐Ÿš€ v2.0.0: released`

Browse files

- Added token-based access ๐Ÿ”
- Improved streaming with prefetch + parallelism โšก
- Added DC warming ๐ŸŒ
- Per-token usage limits ๐Ÿ“Š
- Dashboard stream details ๐Ÿงพ
- Minor bug fixes ๐Ÿ› ๏ธ

Backend/__init__.py CHANGED
@@ -11,4 +11,4 @@ StartTime = time()
11
  USE_DEFAULT_ID: str = None
12
  db = Database()
13
 
14
- __version__ = "1.6.0"
 
11
  USE_DEFAULT_ID: str = None
12
  db = Database()
13
 
14
+ __version__ = "2.0.0"
Backend/config.py CHANGED
@@ -12,6 +12,9 @@ class Telegram:
12
  BASE_URL = getenv("BASE_URL", "").rstrip('/')
13
  PORT = int(getenv("PORT", "8000"))
14
 
 
 
 
15
  AUTH_CHANNEL = [channel.strip() for channel in (getenv("AUTH_CHANNEL") or "").split(",") if channel.strip()]
16
  DATABASE = [db.strip() for db in (getenv("DATABASE") or "").split(",") if db.strip()]
17
 
 
12
  BASE_URL = getenv("BASE_URL", "").rstrip('/')
13
  PORT = int(getenv("PORT", "8000"))
14
 
15
+ PARALLEL = int(getenv("PARALLEL", "1"))
16
+ PRE_FETCH = int(getenv("PRE_FETCH", "1"))
17
+
18
  AUTH_CHANNEL = [channel.strip() for channel in (getenv("AUTH_CHANNEL") or "").split(",") if channel.strip()]
19
  DATABASE = [db.strip() for db in (getenv("DATABASE") or "").split(",") if db.strip()]
20
 
Backend/fastapi/main.py CHANGED
@@ -14,7 +14,8 @@ from Backend.fastapi.routes.template_routes import (
14
  from Backend.fastapi.routes.api_routes import (
15
  list_media_api, delete_media_api, update_media_api,
16
  delete_movie_quality_api, delete_tv_quality_api,
17
- delete_tv_episode_api, delete_tv_season_api
 
18
  )
19
 
20
  app = FastAPI(
@@ -129,6 +130,23 @@ async def get_workloads(_: bool = Depends(require_auth)):
129
  except Exception as e:
130
  return {"loads": {}}
131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  @app.exception_handler(401)
133
  async def auth_exception_handler(request: Request, exc):
134
  return RedirectResponse(url="/login", status_code=302)
 
14
  from Backend.fastapi.routes.api_routes import (
15
  list_media_api, delete_media_api, update_media_api,
16
  delete_movie_quality_api, delete_tv_quality_api,
17
+ delete_tv_episode_api, delete_tv_season_api,
18
+ create_token_api, revoke_token_api, update_token_limits_api
19
  )
20
 
21
  app = FastAPI(
 
130
  except Exception as e:
131
  return {"loads": {}}
132
 
133
+ @app.post("/api/tokens")
134
+ async def create_token(payload: dict, _: bool = Depends(require_auth)):
135
+ return await create_token_api(payload)
136
+
137
+ @app.put("/api/tokens/{token}")
138
+ async def update_token(token: str, payload: dict, _: bool = Depends(require_auth)):
139
+ return await update_token_limits_api(token, payload)
140
+
141
+ @app.delete("/api/tokens/{token}")
142
+ async def revoke_token(token: str, _: bool = Depends(require_auth)):
143
+ return await revoke_token_api(token)
144
+
145
+ @app.get("/api/system/stats")
146
+ async def get_system_stats(_: bool = Depends(require_auth)):
147
+ from Backend.fastapi.routes.api_routes import get_system_stats_api
148
+ return await get_system_stats_api()
149
+
150
  @app.exception_handler(401)
151
  async def auth_exception_handler(request: Request, exc):
152
  return RedirectResponse(url="/login", status_code=302)
Backend/fastapi/routes/api_routes.py CHANGED
@@ -1,6 +1,39 @@
1
  from fastapi import Request, Query, HTTPException
2
- from Backend import db
 
 
 
3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  # --- API Routes for Media Management ---
5
 
6
  async def list_media_api(
@@ -162,3 +195,66 @@ async def delete_tv_season_api(tmdb_id: int, db_index: int, season: int):
162
  raise HTTPException(status_code=404, detail="Season not found")
163
  except Exception as e:
164
  raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from fastapi import Request, Query, HTTPException
2
+ from Backend import db, StartTime, __version__
3
+ from Backend.helper.pyro import get_readable_time
4
+ from Backend.pyrofork.bot import multi_clients, StreamBot
5
+ from time import time
6
 
7
+
8
+ # --- API Routes for System Stats ---
9
+
10
+ async def get_system_stats_api():
11
+ try:
12
+ db_stats = await db.get_database_stats()
13
+ total_movies = sum(stat.get("movie_count", 0) for stat in db_stats)
14
+ total_tv_shows = sum(stat.get("tv_count", 0) for stat in db_stats)
15
+ api_tokens = await db.get_all_api_tokens()
16
+
17
+ return {
18
+ "server_status": "running",
19
+ "uptime": get_readable_time(time() - StartTime),
20
+ "telegram_bot": f"@{StreamBot.username}" if StreamBot and StreamBot.username else "@StreamBot",
21
+ "connected_bots": len(multi_clients),
22
+ "version": __version__,
23
+ "movies": total_movies,
24
+ "tv_shows": total_tv_shows,
25
+ "databases": db_stats,
26
+ "total_databases": len(db_stats),
27
+ "current_db_index": db.current_db_index,
28
+ "api_tokens": api_tokens
29
+ }
30
+ except Exception as e:
31
+ print(f"System Stats API Error: {e}")
32
+ return {
33
+ "server_status": "error",
34
+ "error": str(e)
35
+ }
36
+
37
  # --- API Routes for Media Management ---
38
 
39
  async def list_media_api(
 
195
  raise HTTPException(status_code=404, detail="Season not found")
196
  except Exception as e:
197
  raise HTTPException(status_code=500, detail=str(e))
198
+
199
+
200
+ # --- API Routes for Token Management ---
201
+
202
+ async def create_token_api(payload: dict):
203
+ try:
204
+ token_name = payload.get("name")
205
+ daily_limit = payload.get("daily_limit_gb")
206
+ monthly_limit = payload.get("monthly_limit_gb")
207
+
208
+ if not token_name:
209
+ raise HTTPException(status_code=400, detail="Token name is required")
210
+ def parse_limit(val):
211
+ try:
212
+ v = float(val)
213
+ return v if v > 0 else None
214
+ except (ValueError, TypeError):
215
+ return None
216
+
217
+ new_token = await db.add_api_token(
218
+ token_name,
219
+ parse_limit(daily_limit),
220
+ parse_limit(monthly_limit)
221
+ )
222
+ return new_token
223
+ except Exception as e:
224
+ raise HTTPException(status_code=500, detail=str(e))
225
+
226
+ async def update_token_limits_api(token: str, payload: dict):
227
+ try:
228
+ daily_limit = payload.get("daily_limit_gb")
229
+ monthly_limit = payload.get("monthly_limit_gb")
230
+
231
+ def parse_limit(val):
232
+ try:
233
+ v = float(val)
234
+ return v if v > 0 else None
235
+ except (ValueError, TypeError, AttributeError):
236
+ return None
237
+
238
+ result = await db.update_api_token_limits(
239
+ token,
240
+ parse_limit(daily_limit),
241
+ parse_limit(monthly_limit)
242
+ )
243
+
244
+ if result:
245
+ return {"message": "Limits updated successfully"}
246
+ else:
247
+ return {"message": "Limits updated successfully"}
248
+
249
+ except Exception as e:
250
+ raise HTTPException(status_code=500, detail=str(e))
251
+
252
+ async def revoke_token_api(token: str):
253
+ try:
254
+ result = await db.revoke_api_token(token)
255
+ if result:
256
+ return {"message": "Token revoked successfully"}
257
+ else:
258
+ raise HTTPException(status_code=404, detail="Token not found")
259
+ except Exception as e:
260
+ raise HTTPException(status_code=500, detail=str(e))
Backend/fastapi/routes/stream_routes.py CHANGED
@@ -1,97 +1,264 @@
1
  import math
2
  import secrets
3
  import mimetypes
4
- from typing import Tuple
5
- from fastapi import APIRouter, Request, HTTPException
6
- from fastapi.responses import StreamingResponse
7
 
 
 
 
 
 
 
8
  from Backend.helper.encrypt import decode_string
9
  from Backend.helper.exceptions import InvalidHash
10
- from Backend.helper.custom_dl import ByteStreamer
11
- from Backend.pyrofork.bot import StreamBot, work_loads, multi_clients
 
 
 
 
12
 
13
  router = APIRouter(tags=["Streaming"])
14
- class_cache = {}
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- def parse_range_header(range_header: str, file_size: int) -> Tuple[int, int]:
 
18
  if not range_header:
19
  return 0, file_size - 1
 
20
  try:
21
- range_value = range_header.replace("bytes=", "")
22
- from_str, until_str = range_value.split("-")
23
- from_bytes = int(from_str)
24
- until_bytes = int(until_str) if until_str else file_size - 1
25
- except Exception as e:
26
- raise HTTPException(status_code=400, detail=f"Invalid Range header: {e}")
27
-
28
- if (until_bytes > file_size - 1) or (from_bytes < 0) or (until_bytes < from_bytes):
 
 
 
 
29
  raise HTTPException(
30
  status_code=416,
31
  detail="Requested Range Not Satisfiable",
32
  headers={"Content-Range": f"bytes */{file_size}"},
33
  )
34
 
35
- return from_bytes, until_bytes
 
 
 
 
 
 
 
 
36
 
 
 
 
 
 
 
 
 
37
 
38
- @router.get("/dl/{id}/{name}")
39
- @router.head("/dl/{id}/{name}")
40
- async def stream_handler(request: Request, id: str, name: str):
41
- decoded_data = await decode_string(id)
42
- if not decoded_data.get("msg_id"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  raise HTTPException(status_code=400, detail="Missing id")
44
 
45
- chat_id = f"-100{decoded_data['chat_id']}"
46
- message = await StreamBot.get_messages(int(chat_id), int(decoded_data["msg_id"]))
47
  file = message.video or message.document
48
- file_hash = file.file_unique_id[:6]
49
 
50
  return await media_streamer(
51
- request,
52
- chat_id=int(chat_id),
53
- id=int(decoded_data["msg_id"]),
54
- secure_hash=file_hash
 
 
55
  )
56
 
57
-
58
  async def media_streamer(
59
  request: Request,
60
  chat_id: int,
61
- id: int,
62
  secure_hash: str,
63
- ) -> StreamingResponse:
64
- range_header = request.headers.get("Range", "")
65
- index = min(work_loads, key=work_loads.get)
66
- faster_client = multi_clients[index]
 
 
 
 
 
 
 
 
 
67
 
68
- tg_connect = class_cache.get(faster_client)
69
- if not tg_connect:
70
- tg_connect = ByteStreamer(faster_client)
71
- class_cache[faster_client] = tg_connect
72
 
73
- file_id = await tg_connect.get_file_properties(chat_id=chat_id, message_id=id)
74
- if file_id.unique_id[:6] != secure_hash:
75
- raise InvalidHash
 
 
 
76
 
77
  file_size = file_id.file_size
78
- from_bytes, until_bytes = parse_range_header(range_header, file_size)
 
 
79
 
80
- chunk_size = 1024 * 1024
81
- offset = from_bytes - (from_bytes % chunk_size)
82
- first_part_cut = from_bytes - offset
83
- last_part_cut = (until_bytes % chunk_size) + 1
84
- req_length = until_bytes - from_bytes + 1
85
- part_count = math.ceil(until_bytes / chunk_size) - math.floor(offset / chunk_size)
86
 
87
- body = tg_connect.yield_file(
88
- file_id, index, offset, first_part_cut, last_part_cut, part_count, chunk_size
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  )
90
 
91
- file_name = file_id.file_name or f"{secrets.token_hex(2)}.unknown"
 
 
92
  mime_type = file_id.mime_type or mimetypes.guess_type(file_name)[0] or "application/octet-stream"
93
- if not file_id.file_name and "/" in mime_type:
94
- file_name = f"{secrets.token_hex(2)}.{mime_type.split('/')[1]}"
 
95
 
96
  headers = {
97
  "Content-Type": mime_type,
@@ -101,17 +268,89 @@ async def media_streamer(
101
  "Cache-Control": "public, max-age=3600, immutable",
102
  "Access-Control-Allow-Origin": "*",
103
  "Access-Control-Expose-Headers": "Content-Length, Content-Range, Accept-Ranges",
 
104
  }
105
-
106
  if range_header:
107
- headers["Content-Range"] = f"bytes {from_bytes}-{until_bytes}/{file_size}"
108
- status_code = 206
109
  else:
110
- status_code = 200
111
-
112
  return StreamingResponse(
113
- status_code=status_code,
114
- content=body,
115
  headers=headers,
 
116
  media_type=mime_type,
117
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 StreamBot, work_loads, multi_clients, client_dc_map
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
 
24
+ _streamer_by_client: Dict = {}
25
+
26
+
27
+ def make_json_safe(obj):
28
+ if isinstance(obj, deque):
29
+ return list(obj)
30
+ if isinstance(obj, (set, tuple)):
31
+ return list(obj)
32
+ if isinstance(obj, bytes):
33
+ return obj.decode("utf-8", errors="ignore")
34
+ if isinstance(obj, dict):
35
+ return {k: make_json_safe(v) for k, v in obj.items()}
36
+ if isinstance(obj, list):
37
+ return [make_json_safe(v) for v in obj]
38
+ return obj
39
 
40
+
41
+ def parse_range_header(range_header: str, file_size: int):
42
  if not range_header:
43
  return 0, file_size - 1
44
+
45
  try:
46
+ value = range_header.replace("bytes=", "")
47
+ start_str, end_str = value.split("-")
48
+ start = int(start_str)
49
+ end = int(end_str) if end_str else file_size - 1
50
+ except Exception:
51
+ raise HTTPException(
52
+ status_code=416,
53
+ detail="Invalid Range header",
54
+ headers={"Content-Range": f"bytes */{file_size}"},
55
+ )
56
+
57
+ if start < 0 or end >= file_size or end < start:
58
  raise HTTPException(
59
  status_code=416,
60
  detail="Requested Range Not Satisfiable",
61
  headers={"Content-Range": f"bytes */{file_size}"},
62
  )
63
 
64
+ return start, end
65
+
66
+
67
+ def select_best_client(target_dc: int) -> int:
68
+ matching_dc_clients = []
69
+ for client_idx, client_dc in client_dc_map.items():
70
+ if client_dc == target_dc and client_idx in multi_clients:
71
+ matching_dc_clients.append((client_idx, work_loads.get(client_idx, 0)))
72
+
73
 
74
+ # # -------------Don't use part of code at now ----------------------------
75
+ # if matching_dc_clients:
76
+ # selected = min(matching_dc_clients, key=lambda x: x[1])[0]
77
+ # LOGGER.info(
78
+ # f"Selected client {selected} (DC {target_dc} match) with workload {work_loads[selected]}"
79
+ # )
80
+ # return selected
81
+ # # -------------------------------------------------------------------------
82
 
83
+ if multi_clients:
84
+ selected = min(work_loads, key=work_loads.get)
85
+ selected_dc = client_dc_map.get(selected, "unknown")
86
+ LOGGER.debug(
87
+ f"No DC {target_dc} client available. "
88
+ f"Using client {selected} (DC {selected_dc}) with workload {work_loads[selected]}"
89
+ )
90
+ return selected
91
+
92
+ return 0
93
+
94
+
95
+ async def track_usage_from_stats(stream_id: str, token: str, token_data: dict):
96
+ await asyncio.sleep(2)
97
+
98
+ limits = token_data.get("limits", {}) if token_data else {}
99
+ usage = token_data.get("usage", {}) if token_data else {}
100
+
101
+ daily_limit_gb = limits.get("daily_limit_gb")
102
+ monthly_limit_gb = limits.get("monthly_limit_gb")
103
+
104
+ initial_daily_bytes = usage.get("daily", {}).get("bytes", 0)
105
+ initial_monthly_bytes = usage.get("monthly", {}).get("bytes", 0)
106
+
107
+ last_tracked_bytes = 0
108
+ update_interval = 10
109
+
110
+ try:
111
+ while True:
112
+ await asyncio.sleep(update_interval)
113
+ stream_info = ACTIVE_STREAMS.get(stream_id)
114
+ if not stream_info:
115
+ for rec in RECENT_STREAMS:
116
+ if rec.get("stream_id") == stream_id:
117
+ final_bytes = rec.get("total_bytes", 0)
118
+ delta = final_bytes - last_tracked_bytes
119
+ if delta > 0:
120
+ try:
121
+ await db.update_token_usage(token, delta)
122
+ LOGGER.debug(f"Final usage update for {stream_id}: {delta} bytes")
123
+ except Exception as e:
124
+ LOGGER.error(f"Final usage update failed: {e}")
125
+ break
126
+ return
127
+
128
+ current_bytes = stream_info.get("total_bytes", 0)
129
+ delta = current_bytes - last_tracked_bytes
130
+
131
+ if delta > 0:
132
+ try:
133
+ await db.update_token_usage(token, delta)
134
+ last_tracked_bytes = current_bytes
135
+ LOGGER.debug(f"Updated usage for {stream_id}: +{delta} bytes (total: {current_bytes})")
136
+ except Exception as e:
137
+ LOGGER.error(f"Periodic usage update failed: {e}")
138
+
139
+ # Check limits (don't stop stream, just log - client manages connection)
140
+ if daily_limit_gb and daily_limit_gb > 0:
141
+ current_daily_gb = (initial_daily_bytes + current_bytes) / (1024 ** 3)
142
+ if current_daily_gb >= daily_limit_gb:
143
+ LOGGER.debug(f"Daily limit reached for token, stream {stream_id} may be blocked by verify_token")
144
+
145
+ if monthly_limit_gb and monthly_limit_gb > 0:
146
+ current_monthly_gb = (initial_monthly_bytes + current_bytes) / (1024 ** 3)
147
+ if current_monthly_gb >= monthly_limit_gb:
148
+ LOGGER.debug(f"Monthly limit reached for token, stream {stream_id} may be blocked by verify_token")
149
+
150
+ except asyncio.CancelledError:
151
+ stream_info = ACTIVE_STREAMS.get(stream_id)
152
+ if stream_info:
153
+ current_bytes = stream_info.get("total_bytes", 0)
154
+ delta = current_bytes - last_tracked_bytes
155
+ if delta > 0:
156
+ try:
157
+ await db.update_token_usage(token, delta)
158
+ LOGGER.info(f"Cancelled - final update for {stream_id}: {delta} bytes")
159
+ except Exception as e:
160
+ LOGGER.error(f"Cancelled usage update failed: {e}")
161
+
162
+
163
+ @router.get("/dl/{token}/{id}/{name}")
164
+ @router.head("/dl/{token}/{id}/{name}")
165
+ async def stream_handler(
166
+ request: Request,
167
+ token: str,
168
+ id: str,
169
+ name: str,
170
+ token_data: dict = Depends(verify_token),
171
+ ):
172
+ decoded = await decode_string(id)
173
+ msg_id = decoded.get("msg_id")
174
+ if not msg_id:
175
  raise HTTPException(status_code=400, detail="Missing id")
176
 
177
+ chat_id = int(f"-100{decoded['chat_id']}")
178
+ message = await StreamBot.get_messages(chat_id, int(msg_id))
179
  file = message.video or message.document
180
+ secure_hash = file.file_unique_id[:6]
181
 
182
  return await media_streamer(
183
+ request=request,
184
+ chat_id=chat_id,
185
+ msg_id=int(msg_id),
186
+ secure_hash=secure_hash,
187
+ token=token,
188
+ token_data=token_data,
189
  )
190
 
 
191
  async def media_streamer(
192
  request: Request,
193
  chat_id: int,
194
+ msg_id: int,
195
  secure_hash: str,
196
+ token: str,
197
+ token_data: dict = None,
198
+ ):
199
+ temp_client = multi_clients[min(work_loads, key=work_loads.get)]
200
+ if temp_client not in _streamer_by_client:
201
+ _streamer_by_client[temp_client] = ByteStreamer(temp_client)
202
+ temp_streamer = _streamer_by_client[temp_client]
203
+
204
+ file_id = await temp_streamer.get_file_properties(chat_id=chat_id, message_id=msg_id)
205
+
206
+ if secure_hash != "SKIP_HASH_CHECK": # Don't check this it is for my Webdav
207
+ if file_id.unique_id[:6] != secure_hash:
208
+ raise InvalidHash
209
 
210
+ target_dc = file_id.dc_id
211
+ LOGGER.debug(f"File msg_id={msg_id} is in DC {target_dc}")
 
 
212
 
213
+ index = select_best_client(target_dc)
214
+ tg_client = multi_clients[index]
215
+
216
+ if tg_client not in _streamer_by_client:
217
+ _streamer_by_client[tg_client] = ByteStreamer(tg_client)
218
+ streamer: ByteStreamer = _streamer_by_client[tg_client]
219
 
220
  file_size = file_id.file_size
221
+ range_header = request.headers.get("Range", "")
222
+ start, end = parse_range_header(range_header, file_size)
223
+ req_length = end - start + 1
224
 
225
+ chunk_size = streamer.CHUNK_SIZE
226
+ offset = start - (start % chunk_size)
227
+ first_part_cut = start - offset
228
+ last_part_cut = (end % chunk_size) + 1
229
+ part_count = math.ceil(end / chunk_size) - math.floor(offset / chunk_size)
 
230
 
231
+ stream_id = secrets.token_hex(8)
232
+ meta = {
233
+ "request_path": str(request.url.path),
234
+ "client_host": request.client.host if request.client else None,
235
+ }
236
+
237
+ prefetch_count = Telegram.PARALLEL
238
+ parallelism = Telegram.PRE_FETCH
239
+
240
+ body_gen = await streamer.prefetch_stream(
241
+ file_id=file_id,
242
+ client_index=index,
243
+ offset=offset,
244
+ first_part_cut=first_part_cut,
245
+ last_part_cut=last_part_cut,
246
+ part_count=part_count,
247
+ chunk_size=chunk_size,
248
+ prefetch=prefetch_count,
249
+ stream_id=stream_id,
250
+ meta=meta,
251
+ parallelism=parallelism,
252
+ request=request,
253
  )
254
 
255
+ asyncio.create_task(track_usage_from_stats(stream_id, token, token_data))
256
+
257
+ file_name = file_id.file_name or f"{secrets.token_hex(4)}.bin"
258
  mime_type = file_id.mime_type or mimetypes.guess_type(file_name)[0] or "application/octet-stream"
259
+
260
+ if "." not in file_name and "/" in mime_type:
261
+ file_name = f"{file_name}.{mime_type.split('/')[1]}"
262
 
263
  headers = {
264
  "Content-Type": mime_type,
 
268
  "Cache-Control": "public, max-age=3600, immutable",
269
  "Access-Control-Allow-Origin": "*",
270
  "Access-Control-Expose-Headers": "Content-Length, Content-Range, Accept-Ranges",
271
+ "X-Stream-Id": stream_id,
272
  }
273
+
274
  if range_header:
275
+ headers["Content-Range"] = f"bytes {start}-{end}/{file_size}"
276
+ status = 206
277
  else:
278
+ status = 200
 
279
  return StreamingResponse(
280
+ content=body_gen,
 
281
  headers=headers,
282
+ status_code=status,
283
  media_type=mime_type,
284
+ )
285
+
286
+ @router.get("/stream/stats")
287
+ async def get_stream_stats():
288
+ now = time.time()
289
+ PRUNE_SECONDS = 3
290
+
291
+ for sid, info in list(ACTIVE_STREAMS.items()):
292
+ status = info.get("status")
293
+ last_ts = info.get("last_ts", info.get("start_ts", now))
294
+ if status in ("cancelled", "error", "finished"):
295
+ if now - last_ts > PRUNE_SECONDS:
296
+ try:
297
+ RECENT_STREAMS.appendleft(ACTIVE_STREAMS.pop(sid))
298
+ except KeyError:
299
+ pass
300
+
301
+ active = []
302
+ for sid, info in ACTIVE_STREAMS.items():
303
+ active.append(
304
+ {
305
+ "stream_id": sid,
306
+ "msg_id": info.get("msg_id"),
307
+ "chat_id": info.get("chat_id"),
308
+ "client_index": info.get("client_index"),
309
+ "dc_id": info.get("dc_id"),
310
+ "status": info.get("status"),
311
+ "total_bytes": info.get("total_bytes"),
312
+ "instant_mbps": round(info.get("instant_mbps", 0.0), 3),
313
+ "avg_mbps": round(info.get("avg_mbps", 0.0), 3),
314
+ "peak_mbps": round(info.get("peak_mbps", 0.0), 3),
315
+ "start_ts": info.get("start_ts"),
316
+ }
317
+ )
318
+
319
+ recent = []
320
+ for info in RECENT_STREAMS:
321
+ recent.append(
322
+ {
323
+ "stream_id": info.get("stream_id"),
324
+ "msg_id": info.get("msg_id"),
325
+ "chat_id": info.get("chat_id"),
326
+ "client_index": info.get("client_index"),
327
+ "dc_id": info.get("dc_id"),
328
+ "status": info.get("status"),
329
+ "total_bytes": info.get("total_bytes"),
330
+ "duration": info.get("duration"),
331
+ "avg_mbps": round(info.get("avg_mbps", 0.0), 3),
332
+ "start_ts": info.get("start_ts"),
333
+ "end_ts": info.get("end_ts"),
334
+ }
335
+ )
336
+
337
+ return JSONResponse(
338
+ {
339
+ "active_streams": active,
340
+ "recent_streams": recent,
341
+ "client_dc_map": client_dc_map,
342
+ "work_loads": work_loads,
343
+ }
344
+ )
345
+
346
+ @router.get("/stream/stats/{stream_id}")
347
+ async def get_stream_detail(stream_id: str):
348
+ info = ACTIVE_STREAMS.get(stream_id)
349
+ if info:
350
+ return JSONResponse(make_json_safe(info))
351
+
352
+ for rec in RECENT_STREAMS:
353
+ if rec.get("stream_id") == stream_id:
354
+ return JSONResponse(make_json_safe(rec))
355
+
356
+ raise HTTPException(status_code=404, detail="Stream not found")
Backend/fastapi/routes/stremio_routes.py CHANGED
@@ -1,10 +1,11 @@
1
- from fastapi import APIRouter, HTTPException
2
  from typing import Optional
3
  from urllib.parse import unquote
4
  from Backend.config import Telegram
5
  from Backend import db, __version__
6
  import PTN
7
  from datetime import datetime, timezone, timedelta
 
8
 
9
 
10
  # --- Configuration ---
@@ -106,8 +107,8 @@ def get_resolution_priority(stream_name: str) -> int:
106
  return 1
107
 
108
  # --- Routes ---
109
- @router.get("/manifest.json")
110
- async def get_manifest():
111
  if Telegram.HIDE_CATALOG:
112
  resources = ["stream"]
113
  catalogs = []
@@ -175,12 +176,14 @@ async def get_manifest():
175
  }
176
 
177
 
178
- @router.get("/catalog/{media_type}/{id}/{extra:path}.json")
179
- @router.get("/catalog/{media_type}/{id}.json")
180
- async def get_catalog(media_type: str, id: str, extra: Optional[str] = None):
 
 
181
  if Telegram.HIDE_CATALOG:
182
  raise HTTPException(status_code=404, detail="Catalog disabled")
183
-
184
  if media_type not in ["movie", "series"]:
185
  raise HTTPException(status_code=404, detail="Invalid catalog type")
186
 
@@ -230,10 +233,10 @@ async def get_catalog(media_type: str, id: str, extra: Optional[str] = None):
230
  return {"metas": metas}
231
 
232
 
233
- @router.get("/meta/{media_type}/{id}.json")
234
- async def get_meta(media_type: str, id: str):
235
  if Telegram.HIDE_CATALOG:
236
- raise HTTPException(status_code=404, detail="Meta disabled")
237
  try:
238
  imdb_id = id
239
  except (ValueError, IndexError):
@@ -292,14 +295,39 @@ async def get_meta(media_type: str, id: str):
292
  meta_obj["videos"] = videos
293
  return {"meta": meta_obj}
294
 
295
- @router.get("/stream/{media_type}/{id}.json")
296
- async def get_streams(media_type: str, id: str):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297
  try:
298
  parts = id.split(":")
299
  imdb_id = parts[0]
300
  season_num = int(parts[1]) if len(parts) > 1 else None
301
  episode_num = int(parts[2]) if len(parts) > 2 else None
302
-
303
  except (ValueError, IndexError):
304
  raise HTTPException(status_code=400, detail="Invalid Stremio ID format")
305
 
@@ -315,17 +343,22 @@ async def get_streams(media_type: str, id: str):
315
  streams = []
316
  for quality in media_details.get("telegram", []):
317
  if quality.get("id"):
318
- filename = quality.get('name', '')
319
- quality_str = quality.get('quality', 'HD')
320
- size = quality.get('size', '')
321
 
322
- stream_name, stream_title = format_stream_details(filename, quality_str, size)
 
 
323
 
324
  streams.append({
325
  "name": stream_name,
326
  "title": stream_title,
327
- "url": f"{BASE_URL}/dl/{quality.get('id')}/video.mkv"
328
  })
329
 
330
- streams.sort(key=lambda s: get_resolution_priority(s.get("name", "")), reverse=True)
331
- return {"streams": streams}
 
 
 
 
1
+ from fastapi import APIRouter, HTTPException, Depends
2
  from typing import Optional
3
  from urllib.parse import unquote
4
  from Backend.config import Telegram
5
  from Backend import db, __version__
6
  import PTN
7
  from datetime import datetime, timezone, timedelta
8
+ from Backend.fastapi.security.tokens import verify_token
9
 
10
 
11
  # --- Configuration ---
 
107
  return 1
108
 
109
  # --- Routes ---
110
+ @router.get("/{token}/manifest.json")
111
+ async def get_manifest(token: str, token_data: dict = Depends(verify_token)):
112
  if Telegram.HIDE_CATALOG:
113
  resources = ["stream"]
114
  catalogs = []
 
176
  }
177
 
178
 
179
+
180
+
181
+ @router.get("/{token}/catalog/{media_type}/{id}/{extra:path}.json")
182
+ @router.get("/{token}/catalog/{media_type}/{id}.json")
183
+ async def get_catalog(token: str, media_type: str, id: str, extra: Optional[str] = None, token_data: dict = Depends(verify_token)):
184
  if Telegram.HIDE_CATALOG:
185
  raise HTTPException(status_code=404, detail="Catalog disabled")
186
+
187
  if media_type not in ["movie", "series"]:
188
  raise HTTPException(status_code=404, detail="Invalid catalog type")
189
 
 
233
  return {"metas": metas}
234
 
235
 
236
+ @router.get("/{token}/meta/{media_type}/{id}.json")
237
+ async def get_meta(token: str, media_type: str, id: str, token_data: dict = Depends(verify_token)):
238
  if Telegram.HIDE_CATALOG:
239
+ raise HTTPException(status_code=404, detail="Catalog disabled")
240
  try:
241
  imdb_id = id
242
  except (ValueError, IndexError):
 
295
  meta_obj["videos"] = videos
296
  return {"meta": meta_obj}
297
 
298
+ @router.get("/{token}/stream/{media_type}/{id}.json")
299
+ async def get_streams(
300
+ token: str,
301
+ media_type: str,
302
+ id: str,
303
+ token_data: dict = Depends(verify_token)
304
+ ):
305
+
306
+ if token_data.get("limit_exceeded"):
307
+ limit_type = token_data["limit_exceeded"]
308
+
309
+ title = (
310
+ "๐Ÿšซ Daily Limit Reached โ€“ Upgrade Required"
311
+ if limit_type == "daily"
312
+ else "๐Ÿšซ Monthly Limit Reached โ€“ Upgrade Required"
313
+ )
314
+
315
+ return {
316
+ "streams": [
317
+ {
318
+ "name": "Limit Reached",
319
+ "title": title,
320
+ "url": token_data["limit_video"]
321
+ }
322
+ ]
323
+ }
324
+
325
+
326
  try:
327
  parts = id.split(":")
328
  imdb_id = parts[0]
329
  season_num = int(parts[1]) if len(parts) > 1 else None
330
  episode_num = int(parts[2]) if len(parts) > 2 else None
 
331
  except (ValueError, IndexError):
332
  raise HTTPException(status_code=400, detail="Invalid Stremio ID format")
333
 
 
343
  streams = []
344
  for quality in media_details.get("telegram", []):
345
  if quality.get("id"):
346
+ filename = quality.get("name", "")
347
+ quality_str = quality.get("quality", "HD")
348
+ size = quality.get("size", "")
349
 
350
+ stream_name, stream_title = format_stream_details(
351
+ filename, quality_str, size
352
+ )
353
 
354
  streams.append({
355
  "name": stream_name,
356
  "title": stream_title,
357
+ "url": f"{BASE_URL}/dl/{token}/{quality.get('id')}/video.mkv"
358
  })
359
 
360
+ streams.sort(
361
+ key=lambda s: get_resolution_priority(s.get("name", "")),
362
+ reverse=True
363
+ )
364
+ return {"streams": streams}
Backend/fastapi/routes/template_routes.py CHANGED
@@ -7,8 +7,8 @@ from Backend import db
7
  from Backend.pyrofork.bot import work_loads, multi_clients, StreamBot
8
  from Backend.helper.pyro import get_readable_time
9
  from Backend import StartTime, __version__
10
- from time import time
11
-
12
 
13
  templates = Jinja2Templates(directory="Backend/fastapi/templates")
14
 
@@ -60,51 +60,89 @@ async def dashboard_page(request: Request, _: bool = Depends(require_auth)):
60
  db_stats = await db.get_database_stats()
61
  total_movies = sum(stat.get("movie_count", 0) for stat in db_stats)
62
  total_tv_shows = sum(stat.get("tv_count", 0) for stat in db_stats)
63
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  system_stats = {
65
  "server_status": "running",
66
- "uptime": get_readable_time(time() - StartTime),
67
  "telegram_bot": f"@{StreamBot.username}" if StreamBot and StreamBot.username else "@StreamBot",
68
  "connected_bots": len(multi_clients),
69
  "loads": {
70
- f"bot{c + 1}": l
71
- for c, (_, l) in enumerate(
72
- sorted(work_loads.items(), key=lambda x: x[1], reverse=True)
73
- )
74
  } if work_loads else {},
75
  "version": __version__,
76
  "movies": total_movies,
77
  "tv_shows": total_tv_shows,
78
  "databases": db_stats,
79
  "total_databases": len(db_stats),
80
- "current_db_index": db.current_db_index
 
 
81
  }
 
82
  except Exception as e:
83
  print(f"Dashboard error: {e}")
84
  system_stats = {
85
- "server_status": "error",
86
  "error": str(e),
87
  "uptime": "N/A",
88
  "telegram_bot": "@StreamBot",
89
  "connected_bots": 0,
90
  "loads": {},
91
- "version": "1.0.0",
92
  "movies": 0,
93
  "tv_shows": 0,
94
  "databases": [],
95
  "total_databases": 0,
96
- "current_db_index": 1
 
 
97
  }
98
-
 
99
  return templates.TemplateResponse("dashboard.html", {
100
  "request": request,
101
  "theme": theme,
102
  "themes": get_all_themes(),
103
  "current_theme": theme_name,
104
  "current_user": current_user,
105
- "system_stats": system_stats
 
106
  })
107
-
108
 
109
  async def media_management_page(request: Request, media_type: str = "movie", _: bool = Depends(require_auth)):
110
  theme_name = request.session.get("theme", "purple_gradient")
 
7
  from Backend.pyrofork.bot import work_loads, multi_clients, StreamBot
8
  from Backend.helper.pyro import get_readable_time
9
  from Backend import StartTime, __version__
10
+ import time
11
+ from Backend.helper.custom_dl import ACTIVE_STREAMS, RECENT_STREAMS
12
 
13
  templates = Jinja2Templates(directory="Backend/fastapi/templates")
14
 
 
60
  db_stats = await db.get_database_stats()
61
  total_movies = sum(stat.get("movie_count", 0) for stat in db_stats)
62
  total_tv_shows = sum(stat.get("tv_count", 0) for stat in db_stats)
63
+
64
+ now = time.time()
65
+ PRUNE_SECONDS = 3
66
+ for sid, info in list(ACTIVE_STREAMS.items()):
67
+ status = info.get("status")
68
+ last_ts = info.get("last_ts", info.get("start_ts", now))
69
+
70
+ if status in ("cancelled", "error", "finished") and (now - last_ts > PRUNE_SECONDS):
71
+
72
+ info["duration"] = round(now - info.get("start_ts", now), 1)
73
+ info["stream_id"] = sid
74
+ try:
75
+ RECENT_STREAMS.appendleft(info)
76
+ ACTIVE_STREAMS.pop(sid)
77
+ except KeyError:
78
+ pass
79
+
80
+ active_streams_data = []
81
+ for stream_id, info in ACTIVE_STREAMS.items():
82
+ active_streams_data.append({
83
+ "stream_id": stream_id,
84
+ "msg_id": info.get("msg_id"),
85
+ "chat_id": info.get("chat_id"),
86
+ "status": info.get("status", "active"),
87
+ "total_bytes": info.get("total_bytes", 0),
88
+ "avg_mbps": round(info.get("avg_mbps", 0.0), 2),
89
+ "instant_mbps": round(info.get("instant_mbps", 0.0), 2),
90
+ "peak_mbps": round(info.get("peak_mbps", 0.0), 2),
91
+ "client_index": info.get("client_index", 0),
92
+ "dc_id": info.get("dc_id", 0),
93
+ "duration": round(now - info.get("start_ts", now), 1),
94
+ "meta": info.get("meta", {})
95
+ })
96
+
97
  system_stats = {
98
  "server_status": "running",
99
+ "uptime": get_readable_time(now - StartTime),
100
  "telegram_bot": f"@{StreamBot.username}" if StreamBot and StreamBot.username else "@StreamBot",
101
  "connected_bots": len(multi_clients),
102
  "loads": {
103
+ f"bot{c+1}": l
104
+ for c, (_, l) in enumerate(sorted(work_loads.items(), key=lambda x: x[1], reverse=True))
 
 
105
  } if work_loads else {},
106
  "version": __version__,
107
  "movies": total_movies,
108
  "tv_shows": total_tv_shows,
109
  "databases": db_stats,
110
  "total_databases": len(db_stats),
111
+ "current_db_index": db.current_db_index,
112
+ "active_streams": active_streams_data,
113
+ "total_active_streams": len(active_streams_data)
114
  }
115
+
116
  except Exception as e:
117
  print(f"Dashboard error: {e}")
118
  system_stats = {
119
+ "server_status": "error",
120
  "error": str(e),
121
  "uptime": "N/A",
122
  "telegram_bot": "@StreamBot",
123
  "connected_bots": 0,
124
  "loads": {},
125
+ "version": __version__,
126
  "movies": 0,
127
  "tv_shows": 0,
128
  "databases": [],
129
  "total_databases": 0,
130
+ "current_db_index": 1,
131
+ "active_streams": [],
132
+ "total_active_streams": 0
133
  }
134
+
135
+ api_tokens = await db.get_all_api_tokens()
136
  return templates.TemplateResponse("dashboard.html", {
137
  "request": request,
138
  "theme": theme,
139
  "themes": get_all_themes(),
140
  "current_theme": theme_name,
141
  "current_user": current_user,
142
+ "system_stats": system_stats,
143
+ "api_tokens": api_tokens
144
  })
145
+
146
 
147
  async def media_management_page(request: Request, media_type: str = "movie", _: bool = Depends(require_auth)):
148
  theme_name = request.session.get("theme", "purple_gradient")
Backend/fastapi/security/tokens.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import HTTPException
2
+ from Backend import db
3
+
4
+ DAILY_LIMIT_VIDEO = "https://bit.ly/3YZFKT5"
5
+ MONTHLY_LIMIT_VIDEO = "https://bit.ly/4rfjtgd"
6
+
7
+
8
+ async def verify_token(token: str):
9
+ token_data = await db.get_api_token(token)
10
+ if not token_data:
11
+ raise HTTPException(status_code=401, detail="Invalid or expired API token")
12
+
13
+ limits = token_data.get("limits", {})
14
+ usage = token_data.get("usage", {})
15
+
16
+ daily_limit = limits.get("daily_limit_gb")
17
+ monthly_limit = limits.get("monthly_limit_gb")
18
+
19
+ token_data["limit_exceeded"] = None
20
+ token_data["limit_video"] = None
21
+
22
+ if daily_limit and daily_limit > 0:
23
+ current_daily_gb = usage.get("daily", {}).get("bytes", 0) / (1024 ** 3)
24
+ if current_daily_gb >= daily_limit:
25
+ token_data["limit_exceeded"] = "daily"
26
+ token_data["limit_video"] = DAILY_LIMIT_VIDEO
27
+ return token_data
28
+
29
+ if monthly_limit and monthly_limit > 0:
30
+ current_monthly_gb = usage.get("monthly", {}).get("bytes", 0) / (1024 ** 3)
31
+ if current_monthly_gb >= monthly_limit:
32
+ token_data["limit_exceeded"] = "monthly"
33
+ token_data["limit_video"] = MONTHLY_LIMIT_VIDEO
34
+ return token_data
35
+
36
+ return token_data
Backend/fastapi/templates/dashboard.html CHANGED
@@ -9,265 +9,719 @@
9
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
10
  <div class="flex items-center justify-between">
11
  <div class="flex items-center space-x-4">
12
- <h1 class="text-3xl font-bold text-primary">System Overview</h1>
13
  </div>
 
 
 
 
 
 
 
 
 
 
 
14
  </div>
15
  </div>
16
  </header>
17
 
18
  <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-12">
19
  <!-- System Status Section -->
20
- <div class="mb-12">
21
  <div class="grid lg:grid-cols-2 gap-8">
22
  <!-- System Status Card -->
23
  <div class="theme-card rounded-xl p-8 shadow-xl">
24
  <div class="flex items-center mb-6">
25
- <div class="w-12 h-12 theme-primary rounded-lg flex items-center justify-center mr-4 bg-opacity-20 text-primary">
26
- <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="white">
27
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
 
 
 
 
28
  </svg>
29
  </div>
30
  <h3 class="text-2xl font-semibold">System Status</h3>
31
  </div>
32
-
33
  <div class="space-y-4">
34
  <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
35
  <span class="font-medium theme-text-secondary">Uptime</span>
36
- <span class="text-primary font-semibold">{{ system_stats.uptime or 'N/A' }}</span>
 
37
  </div>
38
  <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
39
  <span class="font-medium theme-text-secondary">Telegram Bot</span>
40
- <span class="text-primary font-semibold">{{ system_stats.telegram_bot or '@StreamBot' }}</span>
 
 
41
  </div>
42
  <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
43
  <span class="font-medium theme-text-secondary">Connected Bots</span>
44
- <span class="text-primary font-semibold">{{ system_stats.connected_bots|default(0) }}</span>
 
45
  </div>
46
  <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
47
  <span class="font-medium theme-text-secondary">Backend Version</span>
48
- <span class="text-primary font-semibold">v{{ system_stats.version or '1.0.0' }}</span>
 
49
  </div>
50
  </div>
51
  </div>
52
 
53
- <!-- Bot Workload Accordion (Collapsed by default) -->
54
- <div class="theme-card rounded-xl p-8 shadow-xl">
55
- <div class="flex items-center justify-between cursor-pointer" onclick="toggleAccordion('workload-content')">
56
- <div class="flex items-center">
 
57
  <div class="w-12 h-12 theme-primary rounded-lg flex items-center justify-center mr-4 bg-opacity-20 text-primary">
58
  <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="white">
59
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
 
60
  </svg>
61
  </div>
62
- <h3 class="text-2xl font-semibold">Bot Workloads</h3>
 
 
 
 
 
63
  </div>
64
- <svg id="workload-content-icon" xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 text-primary transition-transform duration-200 transform rotate-0" fill="none" viewBox="0 0 24 24" stroke="white">
65
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
66
- </svg>
67
- </div>
68
-
69
- <div id="workload-content" class="hidden mt-6 space-y-3">
70
- {% if system_stats.loads and system_stats.loads|length > 0 %}
71
- {% for bot_name, load in system_stats.loads.items() %}
72
- <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
73
- <span class="font-medium theme-text-secondary">{{ bot_name }}</span>
74
- <div class="flex items-center space-x-2">
75
- <div class="w-16 bg-gray-200 rounded-full h-2">
76
- {% set max_load = system_stats.loads.values() | max if system_stats.loads.values() | max > 0 else 1 %}
77
- <div class="theme-primary h-2 rounded-full" style="width: {{ (load / max_load * 100) | round }}%"></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  </div>
79
- <span class="text-primary font-semibold text-sm w-8" id="load-{{ loop.index0 }}">{{ load }}</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  </div>
81
- </div>
82
- {% endfor %}
83
- {% else %}
84
- <div class="text-center theme-text-secondary py-4">No workload data available</div>
85
- {% endif %}
 
 
 
 
 
 
 
86
  </div>
87
- </div>
88
  </div>
89
  </div>
90
 
91
  <!-- Database Statistics Section -->
92
- <div class="mb-12">
93
- <h2 class="text-2xl font-bold mb-6">Database Overview</h2>
94
- <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
95
  {% if system_stats.databases %}
96
- {% for db_stat in system_stats.databases %}
97
- <div class="theme-card rounded-xl p-6 shadow-xl">
98
- <div class="flex items-center justify-between mb-4">
99
- <h3 class="text-lg font-semibold">{{ db_stat.db_name.replace("storage_", "Database ") }}</h3>
100
- <div class="w-8 h-8 theme-primary rounded-lg flex items-center justify-center bg-opacity-20 text-primary">
101
- <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="white">
102
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4"></path>
103
- </svg>
104
- </div>
 
 
 
105
  </div>
106
-
107
- <div class="space-y-3">
108
- <div class="flex justify-between text-sm">
109
- <span class="theme-text-secondary">Movies</span>
110
- <span class="text-primary font-semibold">{{ "{:,}".format(db_stat.movie_count) }}</span>
111
- </div>
112
- <div class="flex justify-between text-sm">
113
- <span class="theme-text-secondary">TV Shows</span>
114
- <span class="text-primary font-semibold">{{ "{:,}".format(db_stat.tv_count) }}</span>
 
 
 
 
 
 
 
 
 
 
 
115
  </div>
116
- <div class="mt-4">
117
- <div class="flex justify-between text-sm mb-1">
118
- <span class="theme-text-secondary">Storage Used</span>
119
- <span class="text-xs">{{ "%.1f"|format(db_stat.storageSize / 1024 / 1024) }} MB</span>
120
- </div>
121
- {% set storage_percent = (db_stat.storageSize / (500 * 1024 * 1024) * 100) | round %}
122
- <div class="w-full bg-gray-200 rounded-full h-2">
123
- <div class="theme-primary h-2 rounded-full" style="width: {{ storage_percent }}%"></div>
124
  </div>
125
  </div>
126
  </div>
127
  </div>
128
- {% endfor %}
 
129
  {% else %}
130
- <div class="col-span-full text-center theme-text-secondary py-8">No database statistics available</div>
131
- {% endif %}
132
- </div>
133
  </div>
134
 
 
 
135
  <!-- Media Management Section -->
136
- <div class="mb-12">
137
- <h2 class="text-2xl font-bold mb-6">Media Management</h2>
138
- <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
139
- <a href="/media/manage?media_type=movie" class="block theme-card rounded-xl p-8 shadow-xl hover:shadow-2xl transition-all group">
140
  <div class="flex items-center">
141
- <div class="w-16 h-16 theme-primary rounded-lg flex items-center justify-center mr-6 group-hover:scale-110 transition-transform bg-opacity-20 text-primary">
142
- <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8" fill="none" viewBox="0 0 24 24" stroke="white">
143
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 4V2a1 1 0 011-1h8a1 1 0 011 1v2h4a1 1 0 110 2h-1v12a2 2 0 01-2-2V6H3a1 1 0 110-2h4zM9 6v10h6V6H9z"></path>
 
 
 
 
144
  </svg>
145
  </div>
146
  <div>
147
  <h3 class="text-xl font-semibold mb-2">Manage Movies</h3>
148
  <p class="theme-text-secondary">Edit and organize movie collections</p>
149
- <div class="mt-2 text-primary font-semibold text-sm">{{ system_stats.movies|default(0) }} movies</div>
 
150
  </div>
151
  </div>
152
  </a>
153
 
154
- <a href="/media/manage?media_type=tv" class="block theme-card rounded-xl p-8 shadow-xl hover:shadow-2xl transition-all group">
 
155
  <div class="flex items-center">
156
- <div class="w-16 h-16 theme-primary rounded-lg flex items-center justify-center mr-6 group-hover:scale-110 transition-transform bg-opacity-20 text-primary">
157
- <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8" fill="none" viewBox="0 0 24 24" stroke="white">
158
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
 
 
 
 
159
  </svg>
160
  </div>
161
  <div>
162
  <h3 class="text-xl font-semibold mb-2">Manage TV Shows</h3>
163
  <p class="theme-text-secondary">Edit and organize TV series</p>
164
- <div class="mt-2 text-primary font-semibold text-sm">{{ system_stats.tv_shows|default(0) }} shows</div>
165
- </div>
166
- </div>
167
- </a>
168
-
169
- <a href="/stremio" class="block theme-card rounded-xl p-8 shadow-xl hover:shadow-2xl transition-all group">
170
- <div class="flex items-center">
171
- <div class="w-16 h-16 theme-primary rounded-lg flex items-center justify-center mr-6 group-hover:scale-110 transition-transform bg-opacity-20 text-primary">
172
- <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8" fill="none" viewBox="0 0 24 24" stroke="white">
173
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"></path>
174
- </svg>
175
- </div>
176
- <div>
177
- <h3 class="text-xl font-semibold mb-2">Stremio Setup</h3>
178
- <p class="theme-text-secondary">Configure addon installation</p>
179
  </div>
180
  </div>
181
  </a>
182
  </div>
183
  </div>
184
 
185
- <!-- Stremio Addon Section -->
186
- <div class="theme-card rounded-xl p-8 shadow-xl">
187
  <div class="text-center mb-8">
188
- <div class="w-16 h-16 theme-primary rounded-full flex items-center justify-center mx-auto mb-4 bg-opacity-20 text-primary">
189
- <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8" fill="none" viewBox="0 0 24 24" stroke="white">
190
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"></path>
 
 
 
 
191
  </svg>
192
  </div>
193
- <h3 class="text-2xl font-bold mb-2">Stremio Addon</h3>
194
- <p class="theme-text-secondary">Install the addon to access media content through Stremio</p>
195
  </div>
196
 
197
- <!-- Installation Section -->
198
- <div class="bg-gray-50 rounded-lg p-6 mb-6">
199
- <h4 class="text-lg font-semibold mb-4">Installation Instructions</h4>
200
- <div class="space-y-3 theme-text-secondary">
201
- <div class="flex items-start space-x-3">
202
- <div class="w-6 h-6 theme-primary rounded-full flex items-center justify-center text-white text-sm font-semibold mt-0.5">1</div>
203
- <p>Copy the manifest URL below</p>
204
- </div>
205
- <div class="flex items-start space-x-3">
206
- <div class="w-6 h-6 theme-primary rounded-full flex items-center justify-center text-white text-sm font-semibold mt-0.5">2</div>
207
- <p>Open Stremio and go to Addons section</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
  </div>
209
- <div class="flex items-start space-x-3">
210
- <div class="w-6 h-6 theme-primary rounded-full flex items-center justify-center text-white text-sm font-semibold mt-0.5">3</div>
211
- <p>Paste the URL in "Add Addon" field and install</p>
 
212
  </div>
213
  </div>
214
- </div>
215
 
216
- <!-- Manifest URL -->
217
- <div class="bg-gray-50 rounded-lg p-4">
218
- <label class="block text-sm font-medium theme-text-secondary mb-2">Manifest URL</label>
219
- <div class="flex">
220
- <input
221
- type="text"
222
- value="{{ (request.base_url|string).replace('http:', 'https:') }}stremio/manifest.json"
223
- readonly
224
- id="manifest-url"
225
- class="flex-1 theme-card border border-gray-300 rounded-l-lg px-4 py-3 font-mono text-sm focus:outline-none focus:border-primary"
226
- />
227
- <button
228
- onclick="copyToClipboard()"
229
- class="theme-primary text-white px-6 py-3 rounded-r-lg font-semibold hover:opacity-90 transition-colors duration-200"
230
- >
231
- Copy
232
- </button>
233
  </div>
234
  </div>
235
  </div>
 
 
236
  </main>
237
  </div>
238
 
 
239
  <script>
240
- function copyToClipboard() {
241
- const manifestUrl = document.getElementById('manifest-url').value;
242
- navigator.clipboard.writeText(manifestUrl).then(function() {
243
- showToast('Manifest URL copied to clipboard!');
244
- });
245
- }
246
-
247
- function showToast(message) {
248
- const toast = document.createElement('div');
249
- toast.className = 'fixed top-4 right-4 theme-primary text-white px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-x-full';
250
- toast.textContent = message;
251
- document.body.appendChild(toast);
252
-
253
- setTimeout(() => toast.classList.remove('translate-x-full'), 100);
254
- setTimeout(() => {
255
- toast.classList.add('translate-x-full');
256
- setTimeout(() => document.body.removeChild(toast), 300);
257
- }, 3000);
258
- }
259
-
260
- function toggleAccordion(id) {
261
- const content = document.getElementById(id);
262
- const icon = document.getElementById(id + '-icon');
263
-
264
- if (content.classList.contains('hidden')) {
265
- content.classList.remove('hidden');
266
- icon.classList.add('rotate-180');
267
- } else {
268
- content.classList.add('hidden');
269
- icon.classList.remove('rotate-180');
270
  }
271
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
  </script>
273
  {% endblock %}
 
9
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
10
  <div class="flex items-center justify-between">
11
  <div class="flex items-center space-x-4">
12
+ <h1 class="text-3xl font-bold text-primary">Dashboard</h1>
13
  </div>
14
+ <button onclick="refreshSystemStats()"
15
+ class="flex items-center space-x-2 px-4 py-2 rounded-lg theme-primary text-white hover:opacity-90 transition-all shadow-md active:scale-95 group focus:outline-none"
16
+ title="Refresh System Stats">
17
+ <svg id="refresh-icon" xmlns="http://www.w3.org/2000/svg"
18
+ class="w-5 h-5 group-hover:rotate-180 transition-transform duration-500" fill="none"
19
+ viewBox="0 0 24 24" stroke="currentColor">
20
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
21
+ d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
22
+ </svg>
23
+ <span class="font-medium">Refresh Data</span>
24
+ </button>
25
  </div>
26
  </div>
27
  </header>
28
 
29
  <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-12">
30
  <!-- System Status Section -->
31
+ <div class="mb-8">
32
  <div class="grid lg:grid-cols-2 gap-8">
33
  <!-- System Status Card -->
34
  <div class="theme-card rounded-xl p-8 shadow-xl">
35
  <div class="flex items-center mb-6">
36
+ <div
37
+ class="w-12 h-12 theme-primary rounded-lg flex items-center justify-center mr-4 bg-opacity-20 text-primary">
38
+ <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24"
39
+ stroke="white">
40
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
41
+ d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z">
42
+ </path>
43
  </svg>
44
  </div>
45
  <h3 class="text-2xl font-semibold">System Status</h3>
46
  </div>
47
+
48
  <div class="space-y-4">
49
  <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
50
  <span class="font-medium theme-text-secondary">Uptime</span>
51
+ <span id="sys-uptime" class="text-primary font-semibold">{{ system_stats.uptime or 'N/A'
52
+ }}</span>
53
  </div>
54
  <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
55
  <span class="font-medium theme-text-secondary">Telegram Bot</span>
56
+ <span id="sys-bot-name" class="text-primary font-semibold">{{ system_stats.telegram_bot or
57
+ '@StreamBot'
58
+ }}</span>
59
  </div>
60
  <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
61
  <span class="font-medium theme-text-secondary">Connected Bots</span>
62
+ <span id="sys-bots-count" class="text-primary font-semibold">{{
63
+ system_stats.connected_bots|default(0) }}</span>
64
  </div>
65
  <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
66
  <span class="font-medium theme-text-secondary">Backend Version</span>
67
+ <span id="sys-version" class="text-primary font-semibold">v{{ system_stats.version or
68
+ '1.0.0' }}</span>
69
  </div>
70
  </div>
71
  </div>
72
 
73
+ <!-- Bot Workload Section -->
74
+ <!-- Live Streaming Status Card -->
75
+ <div class="streams-container">
76
+ <div class="theme-card rounded-xl p-8 shadow-xl">
77
+ <div class="flex items-center mb-6">
78
  <div class="w-12 h-12 theme-primary rounded-lg flex items-center justify-center mr-4 bg-opacity-20 text-primary">
79
  <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="white">
80
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"></path>
81
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
82
  </svg>
83
  </div>
84
+ <div class="flex-1">
85
+ <h3 class="text-2xl font-semibold">Live Streaming Status</h3>
86
+ </div>
87
+ <span class="px-3 py-1 bg-red-500 text-white rounded-full text-sm font-semibold">
88
+ {{ system_stats.total_active_streams }} Active
89
+ </span>
90
  </div>
91
+
92
+ <div class="space-y-4">
93
+ {% if system_stats.active_streams and system_stats.active_streams|length > 0 %}
94
+ {% for stream in system_stats.active_streams %}
95
+ <div class="p-4 bg-gray-50 rounded-lg border-l-4 {% if stream.status == 'active' %}border-green-500{% elif stream.status == 'cancelled' %}border-yellow-500{% else %}border-red-500{% endif %}">
96
+ <div class="flex justify-between items-start mb-3">
97
+ <div class="flex items-center gap-2">
98
+ <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-primary" fill="currentColor" viewBox="0 0 24 24">
99
+ <path d="M8 5v14l11-7z"/>
100
+ </svg>
101
+ <span class="font-medium theme-text-secondary">Stream:</span>
102
+ <span class="font-semibold">{{ stream.stream_id[:8] }}...</span>
103
+ </div>
104
+ <span class="px-2 py-1 rounded text-xs font-semibold {% if stream.status == 'active' %}bg-green-100 text-green-800{% elif stream.status == 'cancelled' %}bg-yellow-100 text-yellow-800{% else %}bg-red-100 text-red-800{% endif %}">
105
+ {{ stream.status|upper }}
106
+ </span>
107
+ </div>
108
+
109
+ <div class="grid grid-cols-2 gap-3 mb-3">
110
+ <div class="flex justify-between py-2 px-3 bg-white rounded">
111
+ <span class="text-sm theme-text-secondary">Bot:</span>
112
+ <span class="text-sm font-semibold">Bot{{ stream.client_index + 1 }} </span>
113
+ </div>
114
+ <div class="flex justify-between py-2 px-3 bg-white rounded">
115
+ <span class="text-sm theme-text-secondary">File:</span>
116
+ <span class="text-sm font-semibold">DC{{ stream.dc_id }}</span>
117
+ </div>
118
+ <div class="flex justify-between py-2 px-3 bg-white rounded col-span-2">
119
+ <span class="text-sm theme-text-secondary">Duration:</span>
120
+ <span class="text-sm font-semibold">{{ stream.duration }}s</span>
121
+ </div>
122
+
123
+ <div class="flex justify-between py-2 px-3 bg-white rounded col-span-2">
124
+ <span class="text-sm theme-text-secondary">Data Transferred:</span>
125
+ <span class="text-sm font-semibold">{{ "%.2f"|format(stream.total_bytes / 1024 / 1024) }} MB</span>
126
+ </div>
127
  </div>
128
+
129
+ <div class="grid grid-cols-3 gap-3">
130
+ <div class="text-center py-3 bg-white rounded">
131
+ <div class="text-xs theme-text-secondary mb-1">Instant</div>
132
+ <div class="text-sm font-bold text-primary">{{ stream.instant_mbps }} MB/s</div>
133
+ </div>
134
+ <div class="text-center py-3 bg-white rounded">
135
+ <div class="text-xs theme-text-secondary mb-1">Average</div>
136
+ <div class="text-sm font-bold text-primary">{{ stream.avg_mbps }} MB/s</div>
137
+ </div>
138
+ <div class="text-center py-3 bg-white rounded">
139
+ <div class="text-xs theme-text-secondary mb-1">Peak</div>
140
+ <div class="text-sm font-bold text-primary">{{ stream.peak_mbps }} MB/s</div>
141
+ </div>
142
+ </div>
143
+
144
+ {% if stream.meta and stream.meta.client_host %}
145
+ <div class="mt-3 pt-3 border-t border-gray-200">
146
+ <div class="flex items-center gap-2 text-sm">
147
+ <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 theme-text-secondary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
148
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9"></path>
149
+ </svg>
150
+ <span class="theme-text-secondary">Client:</span>
151
+ <span class="font-mono text-xs">{{ stream.meta.client_host }}</span>
152
+ </div>
153
+ </div>
154
+ {% endif %}
155
  </div>
156
+ {% endfor %}
157
+ {% else %}
158
+ <div class="text-center py-12">
159
+ <svg xmlns="http://www.w3.org/2000/svg" class="w-16 h-16 mx-auto mb-4 text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
160
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"></path>
161
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
162
+ </svg>
163
+ <p class="text-gray-500 font-medium mb-1">No active streams</p>
164
+ <p class="text-gray-400 text-sm">Streams will appear here when users start watching content</p>
165
+ </div>
166
+ {% endif %}
167
+ </div>
168
  </div>
169
+ </div>
170
  </div>
171
  </div>
172
 
173
  <!-- Database Statistics Section -->
174
+ <div class="mb-8 mt-4">
175
+ <h2 class="text-2xl font-bold mb-6 text-center">Database and Commands</h2>
176
+ <div class="grid lg:grid-cols-2 gap-6">
177
  {% if system_stats.databases %}
178
+ {% for db_stat in system_stats.databases %}
179
+ <div class="theme-card rounded-xl p-8 shadow-xl w-full flex flex-col h-full">
180
+ <div class="flex items-center justify-between mb-6">
181
+ <h3 class="text-xl font-semibold">{{ db_stat.db_name.replace("storage_", "Database ") }}</h3>
182
+ <div
183
+ class="w-12 h-12 theme-primary rounded-lg flex items-center justify-center bg-opacity-20 text-primary">
184
+ <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24"
185
+ stroke="white">
186
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
187
+ d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4">
188
+ </path>
189
+ </svg>
190
  </div>
191
+ </div>
192
+
193
+ <div class="space-y-4 flex-grow">
194
+ <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
195
+ <span class="font-medium theme-text-secondary">Movies</span>
196
+ <span id="db-movies-{{ loop.index0 }}" class="text-primary font-semibold">{{
197
+ "{:,}".format(db_stat.movie_count) }}</span>
198
+ </div>
199
+ <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
200
+ <span class="font-medium theme-text-secondary">TV Shows</span>
201
+ <span id="db-tv-{{ loop.index0 }}" class="text-primary font-semibold">{{
202
+ "{:,}".format(db_stat.tv_count) }}</span>
203
+ </div>
204
+
205
+ <div class="py-3 px-4 bg-gray-50 rounded-lg">
206
+ <div class="flex justify-between items-center mb-2">
207
+ <span class="font-medium theme-text-secondary">Storage Used</span>
208
+ <span id="db-storage-{{ loop.index0 }}" class="text-primary font-semibold text-sm">{{
209
+ "%.1f"|format(db_stat.storageSize /
210
+ 1024 / 1024) }} MB</span>
211
  </div>
212
+ {% set storage_percent = (db_stat.storageSize / (500 * 1024 * 1024) * 100) | round %}
213
+ <div class="w-full bg-gray-200 rounded-full h-2.5">
214
+ <div class="theme-primary h-2.5 rounded-full" style="width: {{ storage_percent }}%">
 
 
 
 
 
215
  </div>
216
  </div>
217
  </div>
218
  </div>
219
+ </div>
220
+ {% endfor %}
221
  {% else %}
222
+ <div class="col-span-full text-center theme-text-secondary py-8">No database statistics available</div>
223
+ {% endif %} <!-- Add this closing tag -->
224
+ </div>
225
  </div>
226
 
227
+
228
+
229
  <!-- Media Management Section -->
230
+ <div class="mb-8">
231
+ <div class="grid lg:grid-cols-2 gap-6">
232
+ <a href="/media/manage?media_type=movie"
233
+ class="block theme-card rounded-xl p-8 shadow-xl hover:shadow-2xl transition-all group w-full">
234
  <div class="flex items-center">
235
+ <div
236
+ class="w-16 h-16 theme-primary rounded-lg flex items-center justify-center mr-6 group-hover:scale-110 transition-transform bg-opacity-20 text-primary">
237
+ <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8" fill="none" viewBox="0 0 24 24"
238
+ stroke="white">
239
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
240
+ d="M7 4V2a1 1 0 011-1h8a1 1 0 011 1v2h4a1 1 0 110 2h-1v12a2 2 0 01-2-2V6H3a1 1 0 110-2h4zM9 6v10h6V6H9z">
241
+ </path>
242
  </svg>
243
  </div>
244
  <div>
245
  <h3 class="text-xl font-semibold mb-2">Manage Movies</h3>
246
  <p class="theme-text-secondary">Edit and organize movie collections</p>
247
+ <div class="mt-2 text-primary font-semibold text-sm">{{ system_stats.movies|default(0) }}
248
+ movies</div>
249
  </div>
250
  </div>
251
  </a>
252
 
253
+ <a href="/media/manage?media_type=tv"
254
+ class="block theme-card rounded-xl p-8 shadow-xl hover:shadow-2xl transition-all group w-full">
255
  <div class="flex items-center">
256
+ <div
257
+ class="w-16 h-16 theme-primary rounded-lg flex items-center justify-center mr-6 group-hover:scale-110 transition-transform bg-opacity-20 text-primary">
258
+ <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8" fill="none" viewBox="0 0 24 24"
259
+ stroke="white">
260
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
261
+ d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z">
262
+ </path>
263
  </svg>
264
  </div>
265
  <div>
266
  <h3 class="text-xl font-semibold mb-2">Manage TV Shows</h3>
267
  <p class="theme-text-secondary">Edit and organize TV series</p>
268
+ <div class="mt-2 text-primary font-semibold text-sm">{{ system_stats.tv_shows|default(0) }}
269
+ shows</div>
 
 
 
 
 
 
 
 
 
 
 
 
 
270
  </div>
271
  </div>
272
  </a>
273
  </div>
274
  </div>
275
 
276
+ <!-- Access Management Section -->
277
+ <div class="theme-card rounded-xl p-8 shadow-xl mb-8">
278
  <div class="text-center mb-8">
279
+ <div
280
+ class="w-16 h-16 theme-primary rounded-full flex items-center justify-center mx-auto mb-4 bg-opacity-20 text-primary">
281
+ <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8" fill="none" viewBox="0 0 24 24"
282
+ stroke="white">
283
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
284
+ d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11.536 16.464l-4.786 1.768a3 3 0 01-3.951-3.951l1.768-4.786L14.464 11.536A6 6 0 0121 9z">
285
+ </path>
286
  </svg>
287
  </div>
288
+ <h3 class="text-2xl font-bold mb-2">Access Management</h3>
289
+ <p class="theme-text-secondary">Manage API tokens for Stremio addon access</p>
290
  </div>
291
 
292
+ <!-- Create Token Form -->
293
+ <div class="mb-8">
294
+ <div id="create-btn-container">
295
+ <button onclick="toggleCreateForm()"
296
+ class="theme-primary text-white px-6 py-3 rounded-lg font-semibold hover:opacity-90 transition-colors duration-200 flex items-center shadow-md">
297
+ <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 mr-2" fill="none" viewBox="0 0 24 24"
298
+ stroke="currentColor">
299
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
300
+ d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
301
+ </svg>
302
+ New Token
303
+ </button>
304
+ </div>
305
+
306
+ <div id="create-form-container"
307
+ class="hidden mt-4 bg-gray-50 p-6 rounded-xl border border-gray-200 transition-all duration-300">
308
+ <form onsubmit="createToken(event)" class="flex flex-col md:flex-row gap-4 items-end">
309
+ <div class="flex-1 w-full">
310
+ <label class="block text-sm font-medium theme-text-secondary mb-1">Token Name</label>
311
+ <input type="text" id="token-name" placeholder="E.g., Family iPad" required
312
+ class="w-full theme-card border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:border-primary">
313
+ </div>
314
+
315
+ <div class="w-full md:w-32">
316
+ <label class="block text-sm font-medium theme-text-secondary mb-1">Daily Limit</label>
317
+ <div class="relative">
318
+ <input type="number" id="daily-limit" placeholder="0" step="0.1" min="0"
319
+ class="w-full theme-card border border-gray-300 rounded-lg pl-4 pr-12 py-3 focus:outline-none focus:border-primary">
320
+ <span class="absolute right-4 top-3 text-gray-400 text-sm pointer-events-none">GB</span>
321
+ </div>
322
+ </div>
323
+
324
+ <div class="w-full md:w-32">
325
+ <label class="block text-sm font-medium theme-text-secondary mb-1">Monthly Limit</label>
326
+ <div class="relative">
327
+ <input type="number" id="monthly-limit" placeholder="0" step="0.1" min="0"
328
+ class="w-full theme-card border border-gray-300 rounded-lg pl-4 pr-12 py-3 focus:outline-none focus:border-primary">
329
+ <span class="absolute right-4 top-3 text-gray-400 text-sm pointer-events-none">GB</span>
330
+ </div>
331
+ </div>
332
+
333
+ <div class="flex gap-2 w-full md:w-auto">
334
+ <button type="button" onclick="toggleCreateForm()"
335
+ class="w-full md:w-auto bg-gray-200 text-gray-700 px-6 py-3 rounded-lg font-semibold hover:bg-gray-300 transition-colors duration-200">
336
+ Cancel
337
+ </button>
338
+ <button type="submit"
339
+ class="w-full md:w-auto theme-primary text-white px-6 py-3 rounded-lg font-semibold hover:opacity-90 transition-colors duration-200 flex items-center justify-center">
340
+ Create
341
+ </button>
342
+ </div>
343
+ </form>
344
+ </div>
345
+ </div>
346
+
347
+ <!-- Token List -->
348
+ <div class="overflow-x-auto">
349
+ <table class="w-full text-left border-collapse">
350
+ <thead>
351
+ <tr class="border-b border-gray-200">
352
+ <th class="py-4 px-4 font-semibold theme-text-secondary">Name</th>
353
+ <th class="py-4 px-4 font-semibold theme-text-secondary">Usage (Today / Month)</th>
354
+ <th class="py-4 px-4 font-semibold theme-text-secondary">Limits (GB)</th>
355
+ <th class="py-4 px-4 font-semibold theme-text-secondary">Manifest URL</th>
356
+ <th class="py-4 px-4 font-semibold theme-text-secondary text-right">Actions</th>
357
+ </tr>
358
+ </thead>
359
+ <tbody>
360
+ {% for token in api_tokens %}
361
+ <tr class="border-b border-gray-100 hover:bg-gray-50 transition-colors">
362
+ <td class="py-4 px-4 font-medium">
363
+ {{ token.name }}<br>
364
+ <span class="text-xs theme-text-secondary">{{ token.created_at.strftime('%Y-%m-%d')
365
+ }}</span>
366
+ </td>
367
+ <td class="py-4 px-4 text-sm">
368
+ <span class="block">Today: <span class="font-semibold text-primary"
369
+ data-bytes="{{ token.usage.daily.bytes|default(0) }}"></span></span>
370
+ <span class="block text-gray-500">Month: <span
371
+ data-bytes="{{ token.usage.monthly.bytes|default(0) }}"></span></span>
372
+ </td>
373
+ <td class="py-4 px-4 text-sm">
374
+ <div class="text-gray-600">
375
+ <div class="flex items-center gap-1">
376
+ <span class="w-4 text-gray-400">D:</span>
377
+ {% if token.limits.daily_limit_gb %}
378
+ <span
379
+ data-bytes="{{ (token.limits.daily_limit_gb * 1024 * 1024 * 1024)|int }}"></span>
380
+ {% else %}
381
+ <span>โˆž</span>
382
+ {% endif %}
383
+ </div>
384
+ <div class="flex items-center gap-1">
385
+ <span class="w-4 text-gray-400">M:</span>
386
+ {% if token.limits.monthly_limit_gb %}
387
+ <span
388
+ data-bytes="{{ (token.limits.monthly_limit_gb * 1024 * 1024 * 1024)|int }}"></span>
389
+ {% else %}
390
+ <span>โˆž</span>
391
+ {% endif %}
392
+ </div>
393
+ </div>
394
+ </td>
395
+ <td class="py-4 px-4">
396
+ <div class="flex flex-col items-start space-y-1">
397
+ <code
398
+ class="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded select-all border border-gray-200">
399
+ API={{ token.token[:3] }}.......{{ token.token[-3:] }}
400
+ </code>
401
+ <button
402
+ onclick="copyUrl('{{ (request.base_url|string).replace('http:', 'https:') }}stremio/{{ token.token }}/manifest.json')"
403
+ class="text-primary hover:text-opacity-80 flex items-center space-x-1 text-sm font-medium"
404
+ title="Copy URL">
405
+ <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none"
406
+ viewBox="0 0 24 24" stroke="currentColor">
407
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
408
+ d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
409
+ </svg>
410
+ <span class="underline">Copy Link</span>
411
+ </button>
412
+ </div>
413
+ </td>
414
+ <td class="py-4 px-4 text-right">
415
+ <button
416
+ onclick="openEditModal('{{ token.token }}', '{{ token.limits.daily_limit_gb|default(0) }}', '{{ token.limits.monthly_limit_gb|default(0) }}')"
417
+ class="text-blue-500 hover:text-blue-700 font-medium text-sm px-3 py-1 mr-2 rounded border border-blue-200 hover:bg-blue-50 transition-colors">
418
+ Edit
419
+ </button>
420
+ <button onclick="revokeToken('{{ token.token }}')"
421
+ class="text-red-500 hover:text-red-700 font-medium text-sm px-3 py-1 rounded border border-red-200 hover:bg-red-50 transition-colors">
422
+ Revoke
423
+ </button>
424
+ </td>
425
+ </tr>
426
+ {% else %}
427
+ <tr>
428
+ <td colspan="5" class="py-8 text-center theme-text-secondary">No tokens found. Create one to
429
+ get started.</td>
430
+ </tr>
431
+ {% endfor %}
432
+ </tbody>
433
+ </table>
434
+ </div>
435
+ </div>
436
+
437
+ <!-- Edit Limit Modal -->
438
+ <div id="edit-modal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center z-50">
439
+ <div class="bg-white rounded-lg p-6 w-full max-w-md shadow-xl transform transition-all">
440
+ <h3 class="text-lg font-bold mb-4 theme-text-primary">Edit Token Limits</h3>
441
+ <input type="hidden" id="edit-token-id">
442
+
443
+ <div class="space-y-4">
444
+ <div>
445
+ <label class="block text-sm font-medium theme-text-secondary mb-1">Daily Limit (GB)</label>
446
+ <input type="number" id="edit-daily" placeholder="0 for unlimited" step="0.1" min="0"
447
+ class="w-full theme-card border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:border-primary">
448
  </div>
449
+ <div>
450
+ <label class="block text-sm font-medium theme-text-secondary mb-1">Monthly Limit (GB)</label>
451
+ <input type="number" id="edit-monthly" placeholder="0 for unlimited" step="0.1" min="0"
452
+ class="w-full theme-card border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:border-primary">
453
  </div>
454
  </div>
 
455
 
456
+ <div class="mt-6 flex justify-end space-x-3">
457
+ <button onclick="closeEditModal()"
458
+ class="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">Cancel</button>
459
+ <button onclick="saveTokenLimits()"
460
+ class="px-4 py-2 theme-primary text-white rounded-lg hover:opacity-90 transition-colors">Save
461
+ Changes</button>
 
 
 
 
 
 
 
 
 
 
 
462
  </div>
463
  </div>
464
  </div>
465
+
466
+
467
  </main>
468
  </div>
469
 
470
+ <!-- JS for Workload Updates -->
471
  <script>
472
+ function toggleCreateForm() {
473
+ const formContainer = document.getElementById('create-form-container');
474
+ const btnContainer = document.getElementById('create-btn-container');
475
+
476
+ if (formContainer.classList.contains('hidden')) {
477
+ formContainer.classList.remove('hidden');
478
+ btnContainer.classList.add('hidden');
479
+ } else {
480
+ formContainer.classList.add('hidden');
481
+ btnContainer.classList.remove('hidden');
482
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
483
  }
484
+
485
+ let currentEditToken = null;
486
+
487
+ function openEditModal(token, daily, monthly) {
488
+ currentEditToken = token;
489
+ document.getElementById('edit-token-id').value = token;
490
+ document.getElementById('edit-daily').value = daily == 'None' ? 0 : daily;
491
+ document.getElementById('edit-monthly').value = monthly == 'None' ? 0 : monthly;
492
+
493
+ document.getElementById('edit-modal').classList.remove('hidden');
494
+ }
495
+
496
+ function closeEditModal() {
497
+ document.getElementById('edit-modal').classList.add('hidden');
498
+ currentEditToken = null;
499
+ }
500
+
501
+ async function saveTokenLimits() {
502
+ if (!currentEditToken) return;
503
+
504
+ const daily = document.getElementById('edit-daily').value;
505
+ const monthly = document.getElementById('edit-monthly').value;
506
+
507
+ try {
508
+ const response = await fetch('/api/tokens/' + currentEditToken, {
509
+ method: 'PUT',
510
+ headers: { 'Content-Type': 'application/json' },
511
+ body: JSON.stringify({
512
+ daily_limit_gb: daily,
513
+ monthly_limit_gb: monthly
514
+ })
515
+ });
516
+
517
+ if (response.ok) {
518
+ closeEditModal();
519
+ // Refresh page to show new limits (or update DOM dynamically if we want)
520
+ window.location.reload();
521
+ } else {
522
+ alert("Failed to update limits");
523
+ }
524
+ } catch (error) {
525
+ console.error(error);
526
+ alert("Error updating limits");
527
+ }
528
+ }
529
+ </script>
530
+
531
+ <!-- System Stats Auto-Refresh -->
532
+ <script>
533
+ async function refreshSystemStats() {
534
+ const icon = document.getElementById('refresh-icon');
535
+ if (icon) icon.classList.add('animate-spin'); // Add tailwind spin class
536
+
537
+ try {
538
+ const response = await fetch('/api/system/stats');
539
+ if (response.ok) {
540
+ const stats = await response.json();
541
+
542
+ // Update Static Elements
543
+ const elUptime = document.getElementById('sys-uptime');
544
+ if (elUptime) elUptime.innerText = stats.uptime;
545
+
546
+ const elBotName = document.getElementById('sys-bot-name');
547
+ if (elBotName) elBotName.innerText = stats.telegram_bot;
548
+
549
+ const elBotCount = document.getElementById('sys-bots-count');
550
+ if (elBotCount) elBotCount.innerText = stats.connected_bots;
551
+
552
+ const elVersion = document.getElementById('sys-version');
553
+ if (elVersion) elVersion.innerText = 'v' + stats.version;
554
+
555
+ // Update Database Stats
556
+ if (stats.databases && Array.isArray(stats.databases)) {
557
+ stats.databases.forEach((db, index) => {
558
+ const elMovies = document.getElementById(`db-movies-${index}`);
559
+ if (elMovies) elMovies.innerText = db.movie_count.toLocaleString();
560
+
561
+ const elTv = document.getElementById(`db-tv-${index}`);
562
+ if (elTv) elTv.innerText = db.tv_count.toLocaleString();
563
+
564
+ const elStorage = document.getElementById(`db-storage-${index}`);
565
+ if (elStorage) {
566
+ const mb = db.storageSize / (1024 * 1024);
567
+ elStorage.innerText = mb.toFixed(1) + ' MB';
568
+ }
569
+ });
570
+ }
571
+
572
+ // Update API Token Usage Data
573
+ if (stats.api_tokens && Array.isArray(stats.api_tokens)) {
574
+ stats.api_tokens.forEach((token, index) => {
575
+ // Find all elements with data-bytes attributes for this token
576
+ const tokenRows = document.querySelectorAll('tbody tr');
577
+
578
+ // Get the token's row (skip the "No tokens found" row)
579
+ if (tokenRows.length > index && !tokenRows[index].querySelector('[colspan]')) {
580
+ const row = tokenRows[index];
581
+
582
+ // Update daily usage
583
+ const dailyUsageSpan = row.querySelector('td:nth-child(2) span.font-semibold');
584
+ if (dailyUsageSpan && token.usage && token.usage.daily) {
585
+ const dailyBytes = token.usage.daily.bytes || 0;
586
+ dailyUsageSpan.setAttribute('data-bytes', dailyBytes);
587
+ dailyUsageSpan.textContent = formatBytes(dailyBytes);
588
+ }
589
+
590
+ // Update monthly usage
591
+ const monthlyUsageSpan = row.querySelector('td:nth-child(2) span.text-gray-500 span');
592
+ if (monthlyUsageSpan && token.usage && token.usage.monthly) {
593
+ const monthlyBytes = token.usage.monthly.bytes || 0;
594
+ monthlyUsageSpan.setAttribute('data-bytes', monthlyBytes);
595
+ monthlyUsageSpan.textContent = formatBytes(monthlyBytes);
596
+ }
597
+ }
598
+ });
599
+ }
600
+
601
+ // Update Bot Workloads
602
+ await updateBotWorkloads();
603
+ }
604
+ } catch (error) {
605
+ console.error("Failed to refresh system stats:", error);
606
+ } finally {
607
+ // Remove spin after short delay to make it visible
608
+ setTimeout(() => {
609
+ if (icon) icon.classList.remove('animate-spin');
610
+ }, 500);
611
+ }
612
+ }
613
+
614
+ // Auto-refresh every 2 minutes
615
+ const statsInterval = setInterval(refreshSystemStats, 120000);
616
+ </script>
617
+ <script>
618
+ async function createToken(event) {
619
+ event.preventDefault();
620
+ const nameInput = document.getElementById('token-name');
621
+ const dailyInput = document.getElementById('daily-limit');
622
+ const monthlyInput = document.getElementById('monthly-limit');
623
+
624
+ const payload = {
625
+ name: nameInput.value,
626
+ daily_limit_gb: dailyInput.value,
627
+ monthly_limit_gb: monthlyInput.value
628
+ };
629
+
630
+ try {
631
+ const response = await fetch('/api/tokens', {
632
+ method: 'POST',
633
+ headers: { 'Content-Type': 'application/json' },
634
+ body: JSON.stringify(payload)
635
+ });
636
+
637
+ if (response.ok) {
638
+ showToast('Token created successfully!');
639
+ setTimeout(() => window.location.reload(), 1000);
640
+ } else {
641
+ const data = await response.json();
642
+ showToast('Error: ' + data.detail);
643
+ }
644
+ } catch (error) {
645
+ showToast('Error creating token');
646
+ }
647
+ }
648
+
649
+ async function revokeToken(token) {
650
+ if (!confirm('Are you sure you want to revoke this token? The user will lose access immediately.')) return;
651
+
652
+ try {
653
+ const response = await fetch('/api/tokens/' + token, {
654
+ method: 'DELETE'
655
+ });
656
+
657
+ if (response.ok) {
658
+ showToast('Token revoked successfully!');
659
+ setTimeout(() => window.location.reload(), 1000);
660
+ } else {
661
+ showToast('Error revoking token');
662
+ }
663
+ } catch (error) {
664
+ showToast('Error revoking token');
665
+ }
666
+ }
667
+
668
+ function copyUrl(url) {
669
+ navigator.clipboard.writeText(url).then(function () {
670
+ showToast('Manifest URL copied to clipboard!');
671
+ });
672
+ }
673
+ </script>
674
+ </main>
675
+ </div>
676
+
677
+ <script>
678
+ function copyToClipboard() {
679
+ const manifestUrl = document.getElementById('manifest-url').value;
680
+ navigator.clipboard.writeText(manifestUrl).then(function () {
681
+ showToast('Manifest URL copied to clipboard!');
682
+ });
683
+ }
684
+
685
+ function showToast(message, duration = 3000) {
686
+ const toast = document.createElement('div');
687
+ toast.className = 'fixed top-4 right-4 theme-primary text-white px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-x-full';
688
+ toast.textContent = message;
689
+ document.body.appendChild(toast);
690
+
691
+ setTimeout(() => toast.classList.remove('translate-x-full'), 100);
692
+ setTimeout(() => {
693
+ toast.classList.add('translate-x-full');
694
+ setTimeout(() => document.body.removeChild(toast), 300);
695
+ }, duration);
696
+ }
697
+
698
+ function toggleAccordion(id) {
699
+ const content = document.getElementById(id);
700
+ const icon = document.getElementById(id + '-icon');
701
+
702
+ if (content.classList.contains('hidden')) {
703
+ content.classList.remove('hidden');
704
+ icon.classList.add('rotate-180');
705
+ } else {
706
+ content.classList.add('hidden');
707
+ icon.classList.remove('rotate-180');
708
+ }
709
+ }
710
+
711
+ function formatBytes(bytes, decimals = 2) {
712
+ if (!+bytes) return '0 B';
713
+ const k = 1024;
714
+ const dm = decimals < 0 ? 0 : decimals;
715
+ const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
716
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
717
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
718
+ }
719
+
720
+ // Auto-format bytes on load
721
+ document.addEventListener("DOMContentLoaded", () => {
722
+ document.querySelectorAll('[data-bytes]').forEach(el => {
723
+ el.textContent = formatBytes(el.getAttribute('data-bytes'));
724
+ });
725
+ });
726
  </script>
727
  {% endblock %}
Backend/helper/custom_dl.py CHANGED
@@ -1,146 +1,453 @@
1
  import asyncio
2
- from pyrogram import utils, raw
 
 
 
 
 
 
3
  from pyrogram.errors import AuthBytesInvalid
4
  from pyrogram.file_id import FileId, FileType, ThumbnailSource
5
  from pyrogram.session import Session, Auth
6
- from typing import Dict, Union
7
  from Backend.logger import LOGGER
8
  from Backend.helper.exceptions import FIleNotFound
9
  from Backend.helper.pyro import get_file_ids
10
  from Backend.pyrofork.bot import work_loads
11
- from pyrogram import Client, utils, raw
12
 
 
 
13
 
14
  class ByteStreamer:
 
 
 
15
  def __init__(self, client: Client):
16
- self.clean_timer = 30 * 60
17
- self.client: Client = client
18
- self.__cached_file_ids: Dict[int, FileId] = {}
19
- asyncio.create_task(self.clean_cache())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  async def get_file_properties(self, chat_id: int, message_id: int) -> FileId:
22
- if message_id not in self.__cached_file_ids:
23
  file_id = await get_file_ids(self.client, int(chat_id), int(message_id))
24
  if not file_id:
25
- LOGGER.info('Message with ID %s not found!', message_id)
26
  raise FIleNotFound
27
- self.__cached_file_ids[message_id] = file_id
28
- return self.__cached_file_ids[message_id]
29
-
30
- async def yield_file(self, file_id: FileId, index: int, offset: int, first_part_cut: int, last_part_cut: int, part_count: int, chunk_size: int) -> Union[str, None]: # type: ignore
31
- client = self.client
32
- work_loads[index] += 1
33
- LOGGER.debug(f"Starting to yielding file with client {index}.")
34
- media_session = await self.generate_media_session(client, file_id)
35
- current_part = 1
36
- location = await self.get_location(file_id)
37
- try:
38
- r = await media_session.send(raw.functions.upload.GetFile(location=location, offset=offset, limit=chunk_size))
39
- if isinstance(r, raw.types.upload.File):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  while True:
41
- chunk = r.bytes
42
- if not chunk:
 
 
 
 
 
 
 
 
 
 
 
 
43
  break
44
- elif part_count == 1:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  yield chunk[first_part_cut:last_part_cut]
46
- elif current_part == 1:
47
  yield chunk[first_part_cut:]
48
- elif current_part == part_count:
49
  yield chunk[:last_part_cut]
50
  else:
51
  yield chunk
52
 
53
- current_part += 1
54
- offset += chunk_size
55
 
56
- if current_part > part_count:
57
- break
58
-
59
- r = await media_session.send(
60
- raw.functions.upload.GetFile(
61
- location=location, offset=offset, limit=chunk_size
62
- ),
63
- )
64
- except (TimeoutError, AttributeError):
65
- pass
66
- finally:
67
- LOGGER.debug("Finished yielding file with {current_part} parts.")
68
- work_loads[index] -= 1
69
-
70
- async def generate_media_session(self, client: Client, file_id: FileId) -> Session:
71
- media_session = client.media_sessions.get(file_id.dc_id, None)
72
- if media_session is None:
73
- if file_id.dc_id != await client.storage.dc_id():
74
- media_session = Session(
75
- client,
76
- file_id.dc_id,
77
- await Auth(client, file_id.dc_id, await client.storage.test_mode()).create(),
78
- await client.storage.test_mode(),
79
- is_media=True,
80
- )
81
- await media_session.start()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  for _ in range(6):
83
- exported_auth = await client.invoke(raw.functions.auth.ExportAuthorization(dc_id=file_id.dc_id))
84
  try:
85
-
86
- await media_session.send(raw.functions.auth.ImportAuthorization(id=exported_auth.id, bytes=exported_auth.bytes))
87
  break
88
  except AuthBytesInvalid:
89
- LOGGER.debug(f"Invalid authorization bytes for DC {file_id.dc_id}, retrying...")
 
90
  except OSError:
91
- LOGGER.debug(f"Connection error, retrying...")
92
- await asyncio.sleep(2)
93
- else:
94
- await media_session.stop()
95
- LOGGER.debug(f"Failed to establish media session for DC {file_id.dc_id} after multiple retries")
96
- return None
97
- else:
98
- media_session = Session(
99
- client,
100
- file_id.dc_id,
101
- await client.storage.auth_key(),
102
- await client.storage.test_mode(),
103
- is_media=True,
104
- )
105
- await media_session.start()
106
- LOGGER.debug(f"Created media session for DC {file_id.dc_id}")
107
- client.media_sessions[file_id.dc_id] = media_session
108
- else:
109
- LOGGER.debug(f"Using cached media session for DC {file_id.dc_id}")
110
- return media_session
111
 
 
 
 
112
 
113
  @staticmethod
114
- async def get_location(file_id: FileId) -> Union[raw.types.InputPhotoFileLocation, raw.types.InputDocumentFileLocation, raw.types.InputPeerPhotoFileLocation]:
115
- file_type = file_id.file_type
116
- if file_type == FileType.CHAT_PHOTO:
 
 
 
 
 
117
  if file_id.chat_id > 0:
118
- peer = raw.types.InputPeerUser(
119
- user_id=file_id.chat_id, access_hash=file_id.chat_access_hash)
120
  else:
121
  if file_id.chat_access_hash == 0:
122
  peer = raw.types.InputPeerChat(chat_id=-file_id.chat_id)
123
  else:
124
- peer = raw.types.InputPeerChannel(channel_id=utils.get_channel_id(
125
- file_id.chat_id), access_hash=file_id.chat_access_hash)
126
- location = raw.types.InputPeerPhotoFileLocation(peer=peer,
127
- volume_id=file_id.volume_id,
128
- local_id=file_id.local_id,
129
- big=file_id.thumbnail_source == ThumbnailSource.CHAT_PHOTO_BIG)
130
- elif file_type == FileType.PHOTO:
131
- location = raw.types.InputPhotoFileLocation(id=file_id.media_id,
132
- access_hash=file_id.access_hash,
133
- file_reference=file_id.file_reference,
134
- thumb_size=file_id.thumbnail_size)
135
- else:
136
- location = raw.types.InputDocumentFileLocation(id=file_id.media_id,
137
- access_hash=file_id.access_hash,
138
- file_reference=file_id.file_reference,
139
- thumb_size=file_id.thumbnail_size)
140
- return location
141
-
142
- async def clean_cache(self) -> None:
 
 
 
 
 
 
 
143
  while True:
144
- await asyncio.sleep(self.clean_timer)
145
- self.__cached_file_ids.clear()
146
- LOGGER.debug("Cleaned the cache")
 
1
  import asyncio
2
+ import time
3
+ import secrets
4
+ from collections import deque
5
+ from typing import Dict, Union, Optional, Tuple
6
+ import traceback
7
+ from fastapi import Request
8
+ from pyrogram import Client, raw, utils
9
  from pyrogram.errors import AuthBytesInvalid
10
  from pyrogram.file_id import FileId, FileType, ThumbnailSource
11
  from pyrogram.session import Session, Auth
 
12
  from Backend.logger import LOGGER
13
  from Backend.helper.exceptions import FIleNotFound
14
  from Backend.helper.pyro import get_file_ids
15
  from Backend.pyrofork.bot import work_loads
 
16
 
17
+ ACTIVE_STREAMS: Dict[str, Dict] = {}
18
+ RECENT_STREAMS = deque(maxlen=3)
19
 
20
  class ByteStreamer:
21
+ CHUNK_SIZE = 1024 * 1024 # 1 MB
22
+ CLEAN_INTERVAL = 30 * 60 # 30 minutes
23
+
24
  def __init__(self, client: Client):
25
+ self.client = client
26
+ self._file_id_cache: Dict[int, FileId] = {}
27
+ self._session_lock = asyncio.Lock()
28
+ asyncio.create_task(self._clean_cache())
29
+ asyncio.create_task(self._prewarm_sessions())
30
+
31
+ async def _prewarm_sessions(self):
32
+ common_dcs = [1, 2, 4, 5] # Main Telegram DCs
33
+ LOGGER.debug("Pre-warming media sessions for common DCs...")
34
+
35
+ for dc in common_dcs:
36
+ try:
37
+ if dc in self.client.media_sessions:
38
+ LOGGER.debug(f"Media session for DC {dc} already exists, skipping")
39
+ continue
40
+
41
+ test_mode = await self.client.storage.test_mode()
42
+ current_dc = await self.client.storage.dc_id()
43
+
44
+ if dc == current_dc:
45
+ continue
46
+
47
+ auth_key = await Auth(self.client, dc, test_mode).create()
48
+ session = Session(self.client, dc, auth_key, test_mode, is_media=True)
49
+ session.no_updates = True
50
+ session.timeout = 30
51
+ session.sleep_threshold = 60
52
+
53
+ await session.start()
54
+
55
+ for attempt in range(6):
56
+ try:
57
+ exported = await self.client.invoke(
58
+ raw.functions.auth.ExportAuthorization(dc_id=dc)
59
+ )
60
+ await session.send(
61
+ raw.functions.auth.ImportAuthorization(
62
+ id=exported.id, bytes=exported.bytes
63
+ )
64
+ )
65
+ break
66
+ except AuthBytesInvalid:
67
+ LOGGER.debug(f"AuthBytesInvalid during pre-warm for DC {dc}; retrying...")
68
+ await asyncio.sleep(0.5)
69
+ except OSError:
70
+ LOGGER.debug(f"OSError during pre-warm for DC {dc}; retrying...")
71
+ await asyncio.sleep(1)
72
+ except Exception as e:
73
+ LOGGER.debug(f"Error during pre-warm for DC {dc}: {e}")
74
+ break
75
+
76
+ self.client.media_sessions[dc] = session
77
+ LOGGER.debug(f"Pre-warmed media session for DC {dc}")
78
+
79
+ except Exception as e:
80
+ LOGGER.debug(f"Could not pre-warm DC {dc}: {e}")
81
+ continue
82
 
83
  async def get_file_properties(self, chat_id: int, message_id: int) -> FileId:
84
+ if message_id not in self._file_id_cache:
85
  file_id = await get_file_ids(self.client, int(chat_id), int(message_id))
86
  if not file_id:
87
+ LOGGER.warning("Message %s not found", message_id)
88
  raise FIleNotFound
89
+ self._file_id_cache[message_id] = file_id
90
+ return self._file_id_cache[message_id]
91
+
92
+ async def prefetch_stream(
93
+ self,
94
+ file_id: FileId,
95
+ client_index: int,
96
+ offset: int,
97
+ first_part_cut: int,
98
+ last_part_cut: int,
99
+ part_count: int,
100
+ chunk_size: int,
101
+ prefetch: int = 3,
102
+ stream_id: Optional[str] = None,
103
+ meta: Optional[dict] = None,
104
+ parallelism: int = 2,
105
+ request: Optional[Request] = None,
106
+ ):
107
+ if not stream_id:
108
+ stream_id = secrets.token_hex(8)
109
+
110
+ now = time.time()
111
+ registry_entry = {
112
+ "stream_id": stream_id,
113
+ "msg_id": getattr(file_id, "local_id", None) or None,
114
+ "chat_id": getattr(file_id, "chat_id", None),
115
+ "dc_id": file_id.dc_id,
116
+ "client_index": client_index,
117
+ "start_ts": now,
118
+ "last_ts": now,
119
+ "total_bytes": 0,
120
+ "avg_mbps": 0.0,
121
+ "instant_mbps": 0.0,
122
+ "peak_mbps": 0.0,
123
+ "recent_measurements": deque(maxlen=3),
124
+ "status": "active",
125
+ "part_count": part_count,
126
+ "prefetch": prefetch,
127
+ "meta": meta or {},
128
+ }
129
+
130
+ ACTIVE_STREAMS[stream_id] = registry_entry
131
+ work_loads[client_index] += 1
132
+
133
+ queue_maxsize = max(1, prefetch)
134
+ q: asyncio.Queue = asyncio.Queue(maxsize=queue_maxsize)
135
+ stop_event = asyncio.Event()
136
+
137
+ media_session = await self._get_media_session(file_id)
138
+ location = await self._get_location(file_id)
139
+
140
+ async def fetch_chunk_with_retries(seq_idx: int, off: int) -> Tuple[int, Optional[bytes]]:
141
+ tries = 0
142
+ while tries < 4 and not stop_event.is_set():
143
+ try:
144
+ r = await media_session.send(
145
+ raw.functions.upload.GetFile(location=location, offset=off, limit=chunk_size)
146
+ )
147
+ chunk_bytes = getattr(r, "bytes", None) if r else None
148
+ return seq_idx, chunk_bytes
149
+ except Exception as e:
150
+ tries += 1
151
+ LOGGER.debug(
152
+ "Fetch chunk error seq=%s off=%s try=%s err=%s",
153
+ seq_idx, off, tries, getattr(e, "args", e),
154
+ )
155
+ await asyncio.sleep(0.15 * tries)
156
+
157
+ LOGGER.error("Failed to fetch chunk seq=%s off=%s after retries", seq_idx, off)
158
+ return seq_idx, None
159
+
160
+ async def producer():
161
+ try:
162
+ if part_count <= 0:
163
+ await q.put((None, None))
164
+ return
165
+
166
+ next_to_schedule = 0
167
+ scheduled_tasks = {}
168
+ results_buffer = {}
169
+ next_to_put = 0
170
+ max_parallel = max(1, parallelism)
171
+
172
+ initial = min(part_count, max_parallel)
173
+ for i in range(initial):
174
+ seq = next_to_schedule
175
+ off = offset + seq * chunk_size
176
+ task = asyncio.create_task(fetch_chunk_with_retries(seq, off))
177
+ scheduled_tasks[seq] = task
178
+ next_to_schedule += 1
179
+
180
+ while next_to_put < part_count:
181
+ if stop_event.is_set():
182
+ break
183
+
184
+ if not scheduled_tasks:
185
+ seq = next_to_schedule
186
+ off = offset + seq * chunk_size
187
+ task = asyncio.create_task(fetch_chunk_with_retries(seq, off))
188
+ scheduled_tasks[seq] = task
189
+ next_to_schedule += 1
190
+
191
+ done, _ = await asyncio.wait(scheduled_tasks.values(), return_when=asyncio.FIRST_COMPLETED)
192
+
193
+ for completed in done:
194
+ try:
195
+ completed_seq = None
196
+ for k, t in list(scheduled_tasks.items()):
197
+ if t is completed:
198
+ completed_seq = k
199
+ break
200
+
201
+ if completed_seq is None:
202
+ continue
203
+
204
+ seq_idx, chunk_bytes = completed.result()
205
+ scheduled_tasks.pop(completed_seq, None)
206
+
207
+ if chunk_bytes is None:
208
+ LOGGER.error("Chunk fetch returned empty for stream=%s seq=%s", stream_id, seq_idx)
209
+ await q.put((None, None))
210
+ return
211
+
212
+ results_buffer[seq_idx] = chunk_bytes
213
+
214
+ if next_to_schedule < part_count:
215
+ seq = next_to_schedule
216
+ off = offset + seq * chunk_size
217
+ task = asyncio.create_task(fetch_chunk_with_retries(seq, off))
218
+ scheduled_tasks[seq] = task
219
+ next_to_schedule += 1
220
+
221
+ except asyncio.CancelledError:
222
+ raise
223
+ except Exception as e:
224
+ LOGGER.exception("Error processing completed fetch task: %s%s", e, traceback.format_exc())
225
+ await q.put((None, None))
226
+ return
227
+
228
+ while next_to_put in results_buffer:
229
+ chunk_bytes = results_buffer.pop(next_to_put)
230
+ await q.put((offset + next_to_put * chunk_size, chunk_bytes))
231
+ next_to_put += 1
232
+
233
+ await q.put((None, None))
234
+
235
+ except asyncio.CancelledError:
236
+ LOGGER.debug("Producer cancelled for stream %s", stream_id)
237
+ try:
238
+ await q.put((None, None))
239
+ except Exception:
240
+ pass
241
+ raise
242
+ except Exception as e:
243
+ LOGGER.exception("Producer unexpected error for stream %s: %s", stream_id, e)
244
+ try:
245
+ await q.put((None, None))
246
+ except Exception:
247
+ pass
248
+
249
+ async def consumer_generator():
250
+ producer_task = asyncio.create_task(producer())
251
+ current_part_idx = 1
252
+
253
+ try:
254
  while True:
255
+ try:
256
+ if request and await request.is_disconnected():
257
+ LOGGER.debug("Client disconnected for stream %s; cancelling stream", stream_id)
258
+ ACTIVE_STREAMS[stream_id]["status"] = "cancelled"
259
+ break
260
+ except Exception:
261
+ pass
262
+
263
+ off_chunk = await q.get()
264
+ if off_chunk is None:
265
+ break
266
+
267
+ off, chunk = off_chunk
268
+ if off is None and chunk is None:
269
  break
270
+
271
+ try:
272
+ chunk_len = len(chunk)
273
+ except Exception:
274
+ chunk_len = 0
275
+
276
+ now_ts = time.time()
277
+ elapsed = now_ts - ACTIVE_STREAMS[stream_id]["last_ts"]
278
+ if elapsed <= 0:
279
+ elapsed = 1e-6
280
+
281
+ recent = ACTIVE_STREAMS[stream_id]["recent_measurements"]
282
+ recent.append((chunk_len, elapsed))
283
+
284
+ if len(recent) >= 2:
285
+ total_bytes = sum(b for b, _ in recent)
286
+ total_time = sum(t for _, t in recent)
287
+ instant_mbps = min((total_bytes / (1024 * 1024)) / max(total_time, 0.01), 1000.0)
288
+ else:
289
+ instant_mbps = 0.0
290
+
291
+ ACTIVE_STREAMS[stream_id]["total_bytes"] += chunk_len
292
+ ACTIVE_STREAMS[stream_id]["last_ts"] = now_ts
293
+
294
+ total_time = now_ts - ACTIVE_STREAMS[stream_id]["start_ts"]
295
+ if total_time <= 0:
296
+ total_time = 1e-6
297
+
298
+ ACTIVE_STREAMS[stream_id]["avg_mbps"] = (ACTIVE_STREAMS[stream_id]["total_bytes"] / (1024 * 1024)) / total_time
299
+ ACTIVE_STREAMS[stream_id]["instant_mbps"] = instant_mbps
300
+
301
+ if instant_mbps > ACTIVE_STREAMS[stream_id]["peak_mbps"]:
302
+ ACTIVE_STREAMS[stream_id]["peak_mbps"] = instant_mbps
303
+
304
+ if part_count == 1:
305
  yield chunk[first_part_cut:last_part_cut]
306
+ elif current_part_idx == 1:
307
  yield chunk[first_part_cut:]
308
+ elif current_part_idx == part_count:
309
  yield chunk[:last_part_cut]
310
  else:
311
  yield chunk
312
 
313
+ current_part_idx += 1
 
314
 
315
+ except asyncio.CancelledError:
316
+ LOGGER.debug("Consumer cancelled for stream %s", stream_id)
317
+ if not producer_task.done():
318
+ producer_task.cancel()
319
+ ACTIVE_STREAMS[stream_id]["status"] = "cancelled"
320
+ raise
321
+ except Exception as e:
322
+ LOGGER.exception("Consumer error for stream %s: %s", stream_id, e)
323
+ ACTIVE_STREAMS[stream_id]["status"] = "error"
324
+ if not producer_task.done():
325
+ producer_task.cancel()
326
+ raise
327
+ finally:
328
+ if not producer_task.done():
329
+ try:
330
+ producer_task.cancel()
331
+ await asyncio.wait_for(producer_task, timeout=2.0)
332
+ except Exception:
333
+ pass
334
+
335
+ try:
336
+ end_ts = time.time()
337
+ total_bytes = ACTIVE_STREAMS[stream_id]["total_bytes"]
338
+ start_ts = ACTIVE_STREAMS[stream_id]["start_ts"]
339
+ duration = end_ts - start_ts if end_ts > start_ts else 0.0
340
+ avg_mbps = (total_bytes / (1024 * 1024)) / (duration if duration > 0 else 1e-6)
341
+
342
+ entry = ACTIVE_STREAMS.get(stream_id, {})
343
+ entry.update({
344
+ "end_ts": end_ts,
345
+ "duration": duration,
346
+ "avg_mbps": avg_mbps,
347
+ "status": entry.get("status", "finished"),
348
+ "parallelism": parallelism,
349
+ })
350
+
351
+ try:
352
+ RECENT_STREAMS.appendleft(ACTIVE_STREAMS.pop(stream_id))
353
+ except KeyError:
354
+ pass
355
+ finally:
356
+ try:
357
+ work_loads[client_index] -= 1
358
+ except Exception:
359
+ pass
360
+
361
+ stop_event.set()
362
+
363
+ return consumer_generator()
364
+
365
+ async def _get_media_session(self, file_id: FileId) -> Session:
366
+ dc = file_id.dc_id
367
+ media_session = self.client.media_sessions.get(dc)
368
+
369
+ if media_session:
370
+ return media_session
371
+
372
+ async with self._session_lock:
373
+ media_session = self.client.media_sessions.get(dc)
374
+ if media_session:
375
+ return media_session
376
+
377
+ test_mode = await self.client.storage.test_mode()
378
+ current_dc = await self.client.storage.dc_id()
379
+
380
+ if dc != current_dc:
381
+ auth_key = await Auth(self.client, dc, test_mode).create()
382
+ else:
383
+ auth_key = await self.client.storage.auth_key()
384
+
385
+ session = Session(self.client, dc, auth_key, test_mode, is_media=True)
386
+ session.no_updates = True
387
+ session.timeout = 30
388
+ session.sleep_threshold = 60
389
+
390
+ await session.start()
391
+
392
+ if dc != current_dc:
393
  for _ in range(6):
 
394
  try:
395
+ exported = await self.client.invoke(raw.functions.auth.ExportAuthorization(dc_id=dc))
396
+ await session.send(raw.functions.auth.ImportAuthorization(id=exported.id, bytes=exported.bytes))
397
  break
398
  except AuthBytesInvalid:
399
+ LOGGER.debug("AuthBytesInvalid during media session import; retrying...")
400
+ await asyncio.sleep(0.5)
401
  except OSError:
402
+ LOGGER.debug("OSError during media session import; retrying...")
403
+ await asyncio.sleep(1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
404
 
405
+ self.client.media_sessions[dc] = session
406
+ LOGGER.debug("Created media session for DC %s", dc)
407
+ return session
408
 
409
  @staticmethod
410
+ async def _get_location(file_id: FileId) -> Union[
411
+ raw.types.InputPhotoFileLocation,
412
+ raw.types.InputDocumentFileLocation,
413
+ raw.types.InputPeerPhotoFileLocation,
414
+ ]:
415
+ ftype = file_id.file_type
416
+
417
+ if ftype == FileType.CHAT_PHOTO:
418
  if file_id.chat_id > 0:
419
+ peer = raw.types.InputPeerUser(user_id=file_id.chat_id, access_hash=file_id.chat_access_hash)
 
420
  else:
421
  if file_id.chat_access_hash == 0:
422
  peer = raw.types.InputPeerChat(chat_id=-file_id.chat_id)
423
  else:
424
+ peer = raw.types.InputPeerChannel(channel_id=utils.get_channel_id(file_id.chat_id),
425
+ access_hash=file_id.chat_access_hash)
426
+
427
+ return raw.types.InputPeerPhotoFileLocation(
428
+ peer=peer,
429
+ volume_id=file_id.volume_id,
430
+ local_id=file_id.local_id,
431
+ big=file_id.thumbnail_source == ThumbnailSource.CHAT_PHOTO_BIG,
432
+ )
433
+
434
+ if ftype == FileType.PHOTO:
435
+ return raw.types.InputPhotoFileLocation(
436
+ id=file_id.media_id,
437
+ access_hash=file_id.access_hash,
438
+ file_reference=file_id.file_reference,
439
+ thumb_size=file_id.thumbnail_size,
440
+ )
441
+
442
+ return raw.types.InputDocumentFileLocation(
443
+ id=file_id.media_id,
444
+ access_hash=file_id.access_hash,
445
+ file_reference=file_id.file_reference,
446
+ thumb_size=file_id.thumbnail_size,
447
+ )
448
+
449
+ async def _clean_cache(self) -> None:
450
  while True:
451
+ await asyncio.sleep(self.CLEAN_INTERVAL)
452
+ self._file_id_cache.clear()
453
+ LOGGER.debug("ByteStreamer: cleared file_id cache")
Backend/helper/database.py CHANGED
@@ -1,7 +1,9 @@
 
 
1
  from asyncio import create_task
2
  from bson import ObjectId
3
  import motor.motor_asyncio
4
- from datetime import datetime
5
  from pydantic import ValidationError
6
  from pymongo import ASCENDING, DESCENDING
7
  from typing import Dict, List, Optional, Tuple, Any
@@ -902,3 +904,89 @@ class Database:
902
  "dataSize": db_stats.get("dataSize", 0)
903
  })
904
  return stats
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import secrets
2
+ import string
3
  from asyncio import create_task
4
  from bson import ObjectId
5
  import motor.motor_asyncio
6
+ from datetime import datetime, timezone
7
  from pydantic import ValidationError
8
  from pymongo import ASCENDING, DESCENDING
9
  from typing import Dict, List, Optional, Tuple, Any
 
904
  "dataSize": db_stats.get("dataSize", 0)
905
  })
906
  return stats
907
+
908
+
909
+
910
+ # -------------------------------
911
+ # API Token Methods
912
+ # -------------------------------
913
+
914
+ async def add_api_token(self, name: str, daily_limit_gb: float = None, monthly_limit_gb: float = None) -> dict:
915
+ alphabet = string.ascii_letters + string.digits
916
+ token = ''.join(secrets.choice(alphabet) for _ in range(32))
917
+
918
+ token_doc = {
919
+ "name": name,
920
+ "token": token,
921
+ "created_at": datetime.utcnow(),
922
+ "limits": {
923
+ "daily_limit_gb": daily_limit_gb if daily_limit_gb else 0,
924
+ "monthly_limit_gb": monthly_limit_gb if monthly_limit_gb else 0
925
+ },
926
+ "usage": {
927
+ "total_bytes": 0,
928
+ "daily": {"date": datetime.now(timezone.utc).strftime("%Y-%m-%d"), "bytes": 0},
929
+ "monthly": {"month": datetime.now(timezone.utc).strftime("%Y-%m"), "bytes": 0}
930
+ }
931
+ }
932
+
933
+ await self.dbs["tracking"]["api_tokens"].insert_one(token_doc)
934
+ return convert_objectid_to_str(token_doc)
935
+
936
+ async def get_api_token(self, token: str) -> Optional[dict]:
937
+ doc = await self.dbs["tracking"]["api_tokens"].find_one({"token": token})
938
+ return convert_objectid_to_str(doc) if doc else None
939
+
940
+ async def get_all_api_tokens(self) -> List[dict]:
941
+ cursor = self.dbs["tracking"]["api_tokens"].find().sort("created_at", DESCENDING)
942
+ tokens = await cursor.to_list(None)
943
+ return [convert_objectid_to_str(token) for token in tokens]
944
+
945
+ async def revoke_api_token(self, token: str) -> bool:
946
+ result = await self.dbs["tracking"]["api_tokens"].delete_one({"token": token})
947
+ return result.deleted_count > 0
948
+
949
+ async def update_token_usage(self, token: str, bytes_delta: int):
950
+ today_str = datetime.now(timezone.utc).strftime("%Y-%m-%d")
951
+ month_str = datetime.now(timezone.utc).strftime("%Y-%m")
952
+
953
+ token_doc = await self.dbs["tracking"]["api_tokens"].find_one({"token": token})
954
+ if not token_doc:
955
+ return
956
+
957
+ current_daily = token_doc.get("usage", {}).get("daily", {})
958
+ if current_daily.get("date") != today_str:
959
+ await self.dbs["tracking"]["api_tokens"].update_one(
960
+ {"token": token},
961
+ {"$set": {"usage.daily": {"date": today_str, "bytes": 0}}}
962
+ )
963
+
964
+ current_monthly = token_doc.get("usage", {}).get("monthly", {})
965
+ if current_monthly.get("month") != month_str:
966
+ await self.dbs["tracking"]["api_tokens"].update_one(
967
+ {"token": token},
968
+ {"$set": {"usage.monthly": {"month": month_str, "bytes": 0}}}
969
+ )
970
+
971
+ await self.dbs["tracking"]["api_tokens"].update_one(
972
+ {"token": token},
973
+ {
974
+ "$inc": {
975
+ "usage.total_bytes": bytes_delta,
976
+ "usage.daily.bytes": bytes_delta,
977
+ "usage.monthly.bytes": bytes_delta
978
+ }
979
+ }
980
+ )
981
+
982
+ async def update_api_token_limits(self, token: str, daily_limit_gb: float, monthly_limit_gb: float) -> bool:
983
+ result = await self.dbs["tracking"]["api_tokens"].update_one(
984
+ {"token": token},
985
+ {"$set": {
986
+ "limits": {
987
+ "daily_limit_gb": daily_limit_gb if daily_limit_gb else 0,
988
+ "monthly_limit_gb": monthly_limit_gb if monthly_limit_gb else 0
989
+ }
990
+ }}
991
+ )
992
+ return result.modified_count > 0
Backend/helper/pinger.py CHANGED
@@ -7,7 +7,7 @@ from Backend.logger import LOGGER
7
  async def ping():
8
 
9
  sleep_time = 1200
10
- manifest_url = f"{Telegram.BASE_URL}/stremio/manifest.json"
11
 
12
  while True:
13
  await asyncio.sleep(sleep_time)
 
7
  async def ping():
8
 
9
  sleep_time = 1200
10
+ manifest_url = f"{Telegram.BASE_URL}/api/system/stats"
11
 
12
  while True:
13
  await asyncio.sleep(sleep_time)
README.md CHANGED
@@ -219,6 +219,8 @@ All environment variables for this project are defined in the `config.env` file.
219
  | **`OWNER_ID`** | Your **Telegram user ID**. This ID has full administrative access. |
220
  | **`REPLACE_MODE`** | When `true`, new files replace existing files of the same quality. When `false`, multiple files of the same quality are allowed. |
221
  | **`HIDE_CATALOG`** | When `true`, the default Telegram Stremio Catalog is hidden, and streams only show in the Cinemata catalog (i.e., Cinemata addon is mandatory). Default is `false`. |
 
 
222
 
223
  ### ๐Ÿ—„๏ธ Storage
224
 
 
219
  | **`OWNER_ID`** | Your **Telegram user ID**. This ID has full administrative access. |
220
  | **`REPLACE_MODE`** | When `true`, new files replace existing files of the same quality. When `false`, multiple files of the same quality are allowed. |
221
  | **`HIDE_CATALOG`** | When `true`, the default Telegram Stremio Catalog is hidden, and streams only show in the Cinemata catalog (i.e., Cinemata addon is mandatory). Default is `false`. |
222
+ | **`PARALLEL`** | Controls the number of parallel chunks/connections used during streaming. Higher values can improve download speed and reduce buffering but will increase CPU, memory usage, and Telegram API load. Default is `1` (for this you should have more Multi Tokens). |
223
+ | **`PRE_FETCH`** | Enables prefetching of upcoming stream chunks before they are requested by the player. Higher values allow smoother playback and faster seeking at the cost of extra bandwidth and memory usage. Default is `1` (for this you should have more Multi Tokens). |
224
 
225
  ### ๐Ÿ—„๏ธ Storage
226
 
pyproject.toml CHANGED
@@ -1,6 +1,6 @@
1
  [project]
2
  name = "Telegram-Stremio"
3
- version = "1.6.0"
4
  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."
5
  readme = "README.md"
6
  requires-python = ">=3.11"
 
1
  [project]
2
  name = "Telegram-Stremio"
3
+ version = "2.0.0"
4
  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."
5
  readme = "README.md"
6
  requires-python = ">=3.11"
sample_config.env CHANGED
@@ -6,6 +6,8 @@ HELPER_BOT_TOKEN = ""
6
  OWNER_ID = ""
7
  REPLACE_MODE = "true"
8
  HIDE_CATALOG = "false"
 
 
9
 
10
  # STORAGE
11
  AUTH_CHANNEL = ""
 
6
  OWNER_ID = ""
7
  REPLACE_MODE = "true"
8
  HIDE_CATALOG = "false"
9
+ PARALLEL = "1"
10
+ PRE_FETCH = "1"
11
 
12
  # STORAGE
13
  AUTH_CHANNEL = ""
uv.lock CHANGED
@@ -901,7 +901,7 @@ wheels = [
901
 
902
  [[package]]
903
  name = "telegram-stremio"
904
- version = "1.5.0"
905
  source = { virtual = "." }
906
  dependencies = [
907
  { name = "aiofiles" },
 
901
 
902
  [[package]]
903
  name = "telegram-stremio"
904
+ version = "2.0.0"
905
  source = { virtual = "." }
906
  dependencies = [
907
  { name = "aiofiles" },