Karan Adhikari commited on
Commit
c9c32f6
·
unverified ·
1 Parent(s): 20fd956

Update stremio_routes.py

Browse files
Backend/fastapi/routes/stremio_routes.py CHANGED
@@ -1,12 +1,14 @@
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 ---
12
  BASE_URL = Telegram.BASE_URL
@@ -14,8 +16,6 @@ ADDON_NAME = "Telegram"
14
  ADDON_VERSION = __version__
15
  PAGE_SIZE = 15
16
 
17
- router = APIRouter(prefix="/stremio", tags=["Stremio Addon"])
18
-
19
  # Define available genres
20
  GENRES = [
21
  "Action", "Adventure", "Animation", "Biography", "Comedy",
@@ -24,18 +24,8 @@ GENRES = [
24
  "Sci-Fi", "Sport", "Thriller", "War", "Western"
25
  ]
26
 
 
27
 
28
- def format_released_date(media):
29
- year = media.get("release_year")
30
- if year:
31
- try:
32
- return datetime(int(year), 1, 1).isoformat() + "Z"
33
- except:
34
- return None
35
-
36
- return None
37
-
38
- # --- Helper Functions ---
39
  def convert_to_stremio_meta(item: dict) -> dict:
40
  media_type = "series" if item.get("media_type") == "tv" else "movie"
41
 
@@ -56,10 +46,18 @@ def convert_to_stremio_meta(item: dict) -> dict:
56
  "cast": item.get("cast") or [],
57
  "runtime": item.get("runtime") or "",
58
  }
59
-
60
  return meta
61
 
62
 
 
 
 
 
 
 
 
 
 
63
  def format_stream_details(filename: str, quality: str, size: str) -> tuple[str, str]:
64
  try:
65
  parsed = PTN.parse(filename)
@@ -106,7 +104,8 @@ def get_resolution_priority(stream_name: str) -> int:
106
  return res_value
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:
@@ -159,10 +158,6 @@ async def get_manifest(token: str, token_data: dict = Depends(verify_token)):
159
  }
160
  ]
161
 
162
- # Add visible custom catalogs to the Stremio home screen.
163
- # Each custom catalog is exposed once for movies and once for series because
164
- # Stremio catalogs are type-specific. Hidden catalogs remain manageable in the
165
- # web panel, but are not included in the manifest.
166
  try:
167
  custom_catalogs = await db.get_custom_catalogs(visible_only=True)
168
  for catalog in custom_catalogs:
@@ -186,7 +181,6 @@ async def get_manifest(token: str, token_data: dict = Depends(verify_token)):
186
  pass
187
 
188
 
189
- # Build dynamic name/description/version with subscription info
190
  addon_name = ADDON_NAME
191
  addon_desc = "Streams movies and series from your Telegram."
192
  addon_version = ADDON_VERSION
@@ -195,9 +189,8 @@ async def get_manifest(token: str, token_data: dict = Depends(verify_token)):
195
  if Telegram.SUBSCRIPTION:
196
  user_id = token_data.get("user_id")
197
  if user_id:
198
- from Backend import db as _db
199
  try:
200
- user = await _db.get_user(int(user_id))
201
  if user and user.get("subscription_status") == "active":
202
  expiry_obj = user.get("subscription_expiry")
203
  if expiry_obj:
@@ -207,21 +200,18 @@ async def get_manifest(token: str, token_data: dict = Depends(verify_token)):
207
  f"📅 Subscription active until {expiry_str}.\n"
208
  f"Streams movies and series from your Telegram."
209
  )
210
- # Encode expiry epoch (low 16 bits, hex) into version so
211
- # Stremio detects a change when subscription is updated.
212
  epoch_tag = format(int(expiry_obj.timestamp()) & 0xFFFF, "x")
213
  addon_version = f"{ADDON_VERSION}-{epoch_tag}"
214
  else:
215
  addon_name = f"{ADDON_NAME} — Active"
216
  addon_desc = "✅ Subscription active.\nStreams movies and series from your Telegram."
217
  except Exception:
218
- pass # Fallback to defaults on error
219
 
220
- # Configure URL — opening this reinstalls the addon with latest manifest
221
  configure_url = f"{Telegram.BASE_URL}/stremio/{token}/configure"
222
 
223
  return {
224
- "id": f"telegram.media.{token[:8]}", # per-user ID so each token is independent
225
  "version": addon_version,
226
  "name": addon_name,
227
  "logo": "https://i.postimg.cc/XqWnmDXr/Picsart-25-10-09-08-09-45-867.png",
@@ -352,16 +342,11 @@ async def get_meta(token: str, media_type: str, id: str, token_data: dict = Depe
352
 
353
  # --- Add Episodes ---
354
  if media_type == "series" and "seasons" in media:
355
-
356
  yesterday = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat()
357
-
358
  videos = []
359
-
360
  for season in sorted(media.get("seasons", []), key=lambda s: s.get("season_number")):
361
  for episode in sorted(season.get("episodes", []), key=lambda e: e.get("episode_number")):
362
-
363
  episode_id = f"{id}:{season['season_number']}:{episode['episode_number']}"
364
-
365
  videos.append({
366
  "id": episode_id,
367
  "title": episode.get("title", f"Episode {episode['episode_number']}"),
@@ -372,7 +357,6 @@ async def get_meta(token: str, media_type: str, id: str, token_data: dict = Depe
372
  "thumbnail": episode.get("episode_backdrop") or "https://raw.githubusercontent.com/weebzone/Colab-Tools/refs/heads/main/no_episode_backdrop.png",
373
  "imdb_id": episode.get("imdb_id") or media.get("imdb_id"),
374
  })
375
-
376
  meta_obj["videos"] = videos
377
  return {"meta": meta_obj}
378
 
@@ -385,13 +369,12 @@ async def get_streams(
385
  ):
386
 
387
  if token_data.get("subscription_expired"):
388
- from Backend.config import Telegram as _TG
389
  return {
390
  "streams": [
391
  {
392
  "name": "🚫 Subscription Expired",
393
  "title": "Your subscription has expired.\nRenew via the bot to continue watching.",
394
- "url": _TG.SUBSCRIPTION_URL
395
  }
396
  ]
397
  }
@@ -410,7 +393,7 @@ async def get_streams(
410
  {
411
  "name": "Limit Reached",
412
  "title": title,
413
- "url": token_data["limit_video"]
414
  }
415
  ]
416
  }
@@ -475,9 +458,6 @@ async def get_streams(
475
  key=lambda s: get_resolution_priority(s.get("name", "")),
476
  reverse=True
477
  )
478
-
479
- # Deduplicate stream names — Stremio collapses streams with identical names,
480
- # so when two files share the same caption we append (1), (2) ... to each duplicate.
481
  name_count: dict = {}
482
  for s in streams:
483
  name_count[s["name"]] = name_count.get(s["name"], 0) + 1
@@ -487,31 +467,15 @@ async def get_streams(
487
  if name_count[s["name"]] > 1:
488
  seen[s["name"]] = seen.get(s["name"], 0) + 1
489
  s["name"] = f"{s['name']} ({seen[s['name']]})"
490
-
491
  return {"streams": streams}
492
 
493
-
494
-
495
-
496
-
497
-
498
  @router.get("/{token}/configure")
499
  async def configure_addon(token: str):
500
- """
501
- Configure/update page for the Stremio addon.
502
- Uses the correct stremio://addon_install?manifest= deep-link so Stremio
503
- actually shows the Install/Update dialog when the button is clicked.
504
- """
505
- from urllib.parse import quote
506
- from fastapi.responses import HTMLResponse
507
- from Backend import db as _db
508
-
509
  manifest_url = f"{Telegram.BASE_URL}/stremio/{token}/manifest.json"
510
- # Universal Stremio web install — works on desktop and mobile
511
  web_install_url = f"https://web.stremio.com/#/?addon_manifest={quote(manifest_url, safe='')}"
512
 
513
  # Fetch user info for display
514
- token_doc = await _db.get_api_token(token)
515
  user_name = "Unknown"
516
  expiry_str = "N/A"
517
  status_color = "#ef4444"
@@ -521,7 +485,7 @@ async def configure_addon(token: str):
521
  uid = token_doc.get("user_id")
522
  if uid:
523
  try:
524
- user = await _db.get_user(int(uid))
525
  if user:
526
  user_name = user.get("first_name") or user.get("username") or f"User {uid}"
527
  sub_status = user.get("subscription_status", "")
 
1
  from fastapi import APIRouter, HTTPException, Depends
2
  from typing import Optional
3
+ from urllib.parse import unquote, quote
4
  from Backend.config import Telegram
5
  from Backend import db, __version__
6
  import PTN
7
+ from fastapi.responses import HTMLResponse
8
  from datetime import datetime, timezone, timedelta
9
  from Backend.fastapi.security.tokens import verify_token
10
 
11
+ router = APIRouter(prefix="/stremio", tags=["Stremio Addon"])
12
 
13
  # --- Configuration ---
14
  BASE_URL = Telegram.BASE_URL
 
16
  ADDON_VERSION = __version__
17
  PAGE_SIZE = 15
18
 
 
 
19
  # Define available genres
20
  GENRES = [
21
  "Action", "Adventure", "Animation", "Biography", "Comedy",
 
24
  "Sci-Fi", "Sport", "Thriller", "War", "Western"
25
  ]
26
 
27
+ # --------------- Helper Functions -----------------
28
 
 
 
 
 
 
 
 
 
 
 
 
29
  def convert_to_stremio_meta(item: dict) -> dict:
30
  media_type = "series" if item.get("media_type") == "tv" else "movie"
31
 
 
46
  "cast": item.get("cast") or [],
47
  "runtime": item.get("runtime") or "",
48
  }
 
49
  return meta
50
 
51
 
52
+ def format_released_date(media):
53
+ year = media.get("release_year")
54
+ if year:
55
+ try:
56
+ return datetime(int(year), 1, 1).isoformat() + "Z"
57
+ except:
58
+ return None
59
+ return None
60
+
61
  def format_stream_details(filename: str, quality: str, size: str) -> tuple[str, str]:
62
  try:
63
  parsed = PTN.parse(filename)
 
104
  return res_value
105
  return 1
106
 
107
+ # ------------------ Routes -----------------------
108
+
109
  @router.get("/{token}/manifest.json")
110
  async def get_manifest(token: str, token_data: dict = Depends(verify_token)):
111
  if Telegram.HIDE_CATALOG:
 
158
  }
159
  ]
160
 
 
 
 
 
161
  try:
162
  custom_catalogs = await db.get_custom_catalogs(visible_only=True)
163
  for catalog in custom_catalogs:
 
181
  pass
182
 
183
 
 
184
  addon_name = ADDON_NAME
185
  addon_desc = "Streams movies and series from your Telegram."
186
  addon_version = ADDON_VERSION
 
189
  if Telegram.SUBSCRIPTION:
190
  user_id = token_data.get("user_id")
191
  if user_id:
 
192
  try:
193
+ user = await db.get_user(int(user_id))
194
  if user and user.get("subscription_status") == "active":
195
  expiry_obj = user.get("subscription_expiry")
196
  if expiry_obj:
 
200
  f"📅 Subscription active until {expiry_str}.\n"
201
  f"Streams movies and series from your Telegram."
202
  )
 
 
203
  epoch_tag = format(int(expiry_obj.timestamp()) & 0xFFFF, "x")
204
  addon_version = f"{ADDON_VERSION}-{epoch_tag}"
205
  else:
206
  addon_name = f"{ADDON_NAME} — Active"
207
  addon_desc = "✅ Subscription active.\nStreams movies and series from your Telegram."
208
  except Exception:
209
+ pass
210
 
 
211
  configure_url = f"{Telegram.BASE_URL}/stremio/{token}/configure"
212
 
213
  return {
214
+ "id": f"telegram.media.{token[:8]}",
215
  "version": addon_version,
216
  "name": addon_name,
217
  "logo": "https://i.postimg.cc/XqWnmDXr/Picsart-25-10-09-08-09-45-867.png",
 
342
 
343
  # --- Add Episodes ---
344
  if media_type == "series" and "seasons" in media:
 
345
  yesterday = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat()
 
346
  videos = []
 
347
  for season in sorted(media.get("seasons", []), key=lambda s: s.get("season_number")):
348
  for episode in sorted(season.get("episodes", []), key=lambda e: e.get("episode_number")):
 
349
  episode_id = f"{id}:{season['season_number']}:{episode['episode_number']}"
 
350
  videos.append({
351
  "id": episode_id,
352
  "title": episode.get("title", f"Episode {episode['episode_number']}"),
 
357
  "thumbnail": episode.get("episode_backdrop") or "https://raw.githubusercontent.com/weebzone/Colab-Tools/refs/heads/main/no_episode_backdrop.png",
358
  "imdb_id": episode.get("imdb_id") or media.get("imdb_id"),
359
  })
 
360
  meta_obj["videos"] = videos
361
  return {"meta": meta_obj}
362
 
 
369
  ):
370
 
371
  if token_data.get("subscription_expired"):
 
372
  return {
373
  "streams": [
374
  {
375
  "name": "🚫 Subscription Expired",
376
  "title": "Your subscription has expired.\nRenew via the bot to continue watching.",
377
+ "url": Telegram.SUBSCRIPTION_URL
378
  }
379
  ]
380
  }
 
393
  {
394
  "name": "Limit Reached",
395
  "title": title,
396
+ "url": f"tg://user?id={Telegram.OWNER_ID}"
397
  }
398
  ]
399
  }
 
458
  key=lambda s: get_resolution_priority(s.get("name", "")),
459
  reverse=True
460
  )
 
 
 
461
  name_count: dict = {}
462
  for s in streams:
463
  name_count[s["name"]] = name_count.get(s["name"], 0) + 1
 
467
  if name_count[s["name"]] > 1:
468
  seen[s["name"]] = seen.get(s["name"], 0) + 1
469
  s["name"] = f"{s['name']} ({seen[s['name']]})"
 
470
  return {"streams": streams}
471
 
 
 
 
 
 
472
  @router.get("/{token}/configure")
473
  async def configure_addon(token: str):
 
 
 
 
 
 
 
 
 
474
  manifest_url = f"{Telegram.BASE_URL}/stremio/{token}/manifest.json"
 
475
  web_install_url = f"https://web.stremio.com/#/?addon_manifest={quote(manifest_url, safe='')}"
476
 
477
  # Fetch user info for display
478
+ token_doc = await db.get_api_token(token)
479
  user_name = "Unknown"
480
  expiry_str = "N/A"
481
  status_color = "#ef4444"
 
485
  uid = token_doc.get("user_id")
486
  if uid:
487
  try:
488
+ user = await db.get_user(int(uid))
489
  if user:
490
  user_name = user.get("first_name") or user.get("username") or f"User {uid}"
491
  sub_status = user.get("subscription_status", "")