Gujjugaming2k commited on
Commit
7787e06
Β·
unverified Β·
1 Parent(s): 21043a1

Addon Proxy Integration and DC-Aware Bot Selection - V2.1.1 (#43)

Browse files
Backend/__init__.py CHANGED
@@ -11,4 +11,4 @@ StartTime = time()
11
  USE_DEFAULT_ID: str = None
12
  db = Database()
13
 
14
- __version__ = "2.1.0"
 
11
  USE_DEFAULT_ID: str = None
12
  db = Database()
13
 
14
+ __version__ = "2.1.1"
Backend/config.py CHANGED
@@ -34,4 +34,9 @@ class Telegram:
34
  SUBSCRIPTION = getenv("SUBSCRIPTION", "false").lower() == "true"
35
  SUBSCRIPTION_GROUP_ID = int(getenv("SUBSCRIPTION_GROUP_ID", "0"))
36
  SUBSCRIPTION_URL = getenv("SUBSCRIPTION_URL", "https://t.me/")
37
- APPROVER_IDS = [int(x.strip()) for x in (getenv("APPROVER_IDS") or "").split(",") if x.strip().isdigit()]
 
 
 
 
 
 
34
  SUBSCRIPTION = getenv("SUBSCRIPTION", "false").lower() == "true"
35
  SUBSCRIPTION_GROUP_ID = int(getenv("SUBSCRIPTION_GROUP_ID", "0"))
36
  SUBSCRIPTION_URL = getenv("SUBSCRIPTION_URL", "https://t.me/")
37
+ APPROVER_IDS = [int(x.strip()) for x in (getenv("APPROVER_IDS") or "").split(",") if x.strip().isdigit()]
38
+
39
+ PROXY = getenv("Proxy", "false").lower() == "true"
40
+ PROXY_TYPE = getenv("ProxyType", "HTTPS")
41
+ HTTP_PROXY_URL = getenv("HTTP_Proxy_URL", "")
42
+ SHOW_PROXY_AND_NON_PROXY_BOTH = getenv("SHOW_ProxyAndNonProxyBoth", "false").lower() == "true"
Backend/fastapi/routes/stream_routes.py CHANGED
@@ -100,15 +100,15 @@ def select_best_client(target_dc: int) -> int:
100
  def _score(idx: int) -> int:
101
  return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
102
 
103
- # --- DC-aware selection (uncomment to enable) ---------------------------
104
- # matching = [
105
- # idx for idx, dc in client_dc_map.items()
106
- # if dc == target_dc and idx in multi_clients
107
- # ]
108
- # if matching:
109
- # selected = min(matching, key=_score)
110
- # LOGGER.debug("DC-match client %s (DC %s) score=%s", selected, target_dc, _score(selected))
111
- # return selected
112
  # ------------------------------------------------------------------------
113
 
114
  if multi_clients:
 
100
  def _score(idx: int) -> int:
101
  return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
102
 
103
+ # --- DC-aware selection (Enabled) ---------------------------------------
104
+ matching = [
105
+ idx for idx, dc in client_dc_map.items()
106
+ if dc == target_dc and idx in multi_clients
107
+ ]
108
+ if matching:
109
+ selected = min(matching, key=_score)
110
+ LOGGER.debug("DC-match client %s (DC %s) score=%s", selected, target_dc, _score(selected))
111
+ return selected
112
  # ------------------------------------------------------------------------
113
 
114
  if multi_clients:
Backend/fastapi/routes/stremio_routes.py CHANGED
@@ -562,11 +562,32 @@ async def get_streams(
562
  filename, quality_str, size
563
  )
564
 
565
- streams.append({
566
- "name": stream_name,
567
- "title": stream_title,
568
- "url": f"{BASE_URL}/dl/{token}/{quality.get('id')}/video.mkv"
569
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
570
 
571
  streams.sort(
572
  key=lambda s: get_resolution_priority(s.get("name", "")),
 
562
  filename, quality_str, size
563
  )
564
 
565
+ original_url = f"{BASE_URL}/dl/{token}/{quality.get('id')}/video.mkv"
566
+ proxy_url = f"{Telegram.HTTP_PROXY_URL}{original_url}" if Telegram.PROXY and Telegram.HTTP_PROXY_URL else None
567
+
568
+ if Telegram.SHOW_PROXY_AND_NON_PROXY_BOTH and proxy_url:
569
+ streams.append({
570
+ "name": f"{stream_name} (Proxy)",
571
+ "title": stream_title,
572
+ "url": proxy_url
573
+ })
574
+ streams.append({
575
+ "name": f"{stream_name} (Direct)",
576
+ "title": stream_title,
577
+ "url": original_url
578
+ })
579
+ elif proxy_url:
580
+ streams.append({
581
+ "name": stream_name,
582
+ "title": stream_title,
583
+ "url": proxy_url
584
+ })
585
+ else:
586
+ streams.append({
587
+ "name": stream_name,
588
+ "title": stream_title,
589
+ "url": original_url
590
+ })
591
 
592
  streams.sort(
593
  key=lambda s: get_resolution_priority(s.get("name", "")),
Backend/helper/custom_dl.py CHANGED
@@ -166,19 +166,19 @@ class ByteStreamer:
166
  async def fetch_chunk_with_retries(seq_idx: int, off: int) -> Tuple[int, Optional[bytes]]:
167
  """Fetch one chunk with timeout, exponential back-off, and bot fallback.
168
 
169
- Retry schedule (max 6 tries):
170
- tries 0-2 β†’ same bot / same session, 15 s timeout each
171
- tries 3-5 β†’ try a healthier fallback bot (if available),
172
  still with 15 s timeout
173
  On every TimeoutError the primary client's failure counter is incremented
174
  so select_best_client will avoid it for future requests.
175
  """
176
  tries = 0
177
- while tries < 6 and not stop_event.is_set():
178
  # --- choose which media session to use this attempt ---
179
  use_session = media_session
180
  use_client_idx = client_index
181
- if tries >= 3 and len(multi_clients) > 1:
182
  # Pick the best *other* client by score = workload + 3Γ—failures
183
  def _score(idx):
184
  return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
@@ -213,6 +213,10 @@ class ByteStreamer:
213
  timeout=15.0,
214
  )
215
  chunk_bytes = getattr(r, "bytes", None) if r else None
 
 
 
 
216
  # If we succeeded via a fallback, mark primary as degraded
217
  if use_client_idx != client_index:
218
  client_failures[client_index] = client_failures.get(client_index, 0) + 1
@@ -236,7 +240,7 @@ class ByteStreamer:
236
  await asyncio.sleep(min(0.5 * (2 ** (tries - 1)), 10.0))
237
 
238
  LOGGER.error(
239
- "Failed to fetch chunk seq=%s off=%s after 6 retries, client=%s",
240
  seq_idx, off, client_index,
241
  )
242
  return seq_idx, None
@@ -289,9 +293,8 @@ class ByteStreamer:
289
  scheduled_tasks.pop(completed_seq, None)
290
 
291
  if chunk_bytes is None:
292
- LOGGER.error("Chunk fetch returned empty for stream=%s seq=%s", stream_id, seq_idx)
293
- await q.put((None, None))
294
- return
295
 
296
  results_buffer[seq_idx] = chunk_bytes
297
 
 
166
  async def fetch_chunk_with_retries(seq_idx: int, off: int) -> Tuple[int, Optional[bytes]]:
167
  """Fetch one chunk with timeout, exponential back-off, and bot fallback.
168
 
169
+ Retry schedule (max 3 tries):
170
+ tries 0 β†’ same bot / same session, 15 s timeout each
171
+ tries 1-2 β†’ try a healthier fallback bot (if available),
172
  still with 15 s timeout
173
  On every TimeoutError the primary client's failure counter is incremented
174
  so select_best_client will avoid it for future requests.
175
  """
176
  tries = 0
177
+ while tries < 3 and not stop_event.is_set():
178
  # --- choose which media session to use this attempt ---
179
  use_session = media_session
180
  use_client_idx = client_index
181
+ if tries >= 1 and len(multi_clients) > 1:
182
  # Pick the best *other* client by score = workload + 3Γ—failures
183
  def _score(idx):
184
  return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
 
213
  timeout=15.0,
214
  )
215
  chunk_bytes = getattr(r, "bytes", None) if r else None
216
+
217
+ if chunk_bytes == b"":
218
+ return seq_idx, None
219
+
220
  # If we succeeded via a fallback, mark primary as degraded
221
  if use_client_idx != client_index:
222
  client_failures[client_index] = client_failures.get(client_index, 0) + 1
 
240
  await asyncio.sleep(min(0.5 * (2 ** (tries - 1)), 10.0))
241
 
242
  LOGGER.error(
243
+ "Failed to fetch chunk seq=%s off=%s after 3 retries, client=%s",
244
  seq_idx, off, client_index,
245
  )
246
  return seq_idx, None
 
293
  scheduled_tasks.pop(completed_seq, None)
294
 
295
  if chunk_bytes is None:
296
+ LOGGER.error("Chunk fetch returned empty for stream=%s seq=%s. Filling with zero bytes.", stream_id, seq_idx)
297
+ chunk_bytes = b"\x00" * chunk_size
 
298
 
299
  results_buffer[seq_idx] = chunk_bytes
300
 
Backend/pyrofork/subscription_plugins/start.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pyrogram import filters, Client, enums
2
+ from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton
3
+ from Backend.config import Telegram
4
+ from Backend import db
5
+ from datetime import datetime
6
+
7
+ print("DEBUG: Subscription Bot start.py PLUGIN LOADED SUCCESSFULLY!")
8
+
9
+ @Client.on_message(filters.command('start'), group=10)
10
+ async def send_start_message(client: Client, message: Message):
11
+ try:
12
+ user_id = (message.from_user.id if message.from_user else None) or (message.sender_chat.id if message.sender_chat else None) or message.chat.id
13
+ print(f"DEBUG: Subscription Bot received /start command from {user_id}")
14
+
15
+ base_url = Telegram.BASE_URL
16
+ addon_url = f"{base_url}/stremio/manifest.json"
17
+
18
+ # If subscriptions are NOT enabled
19
+ if not Telegram.SUBSCRIPTION:
20
+ # Generate or fetch API token for free user
21
+ user_name = (message.from_user.first_name or message.from_user.username or f"User {user_id}") if message.from_user else f"Chat {user_id}"
22
+ try:
23
+ # Ensure user gets a token
24
+ token_doc = await db.add_api_token(name=user_name, user_id=user_id)
25
+ token_str = token_doc.get("token")
26
+ addon_url = f"{base_url}/stremio/{token_str}/manifest.json"
27
+ except Exception as e:
28
+ print(f"DEBUG: Error ensuring token for free user: {e}")
29
+
30
+ await message.reply_text(
31
+ 'πŸŽ‰ <b>Welcome to the Telegram Stremio Media Server!</b>\n\n'
32
+ 'Here is your personal Stremio Addon link:\n\n'
33
+ '🎬 <b>Stremio Addon β€” Install Link:</b>\n'
34
+ f'<code>{addon_url}</code>\n\n'
35
+ 'Tap the link above β†’ <b>Install</b> in Stremio to start watching!',
36
+ quote=True,
37
+ parse_mode=enums.ParseMode.HTML
38
+ )
39
+ return
40
+
41
+ # Subscription logic (When SUBSCRIPTION=True)
42
+ user = await db.get_user(user_id)
43
+ now = datetime.utcnow()
44
+
45
+ # Check if user has an active subscription
46
+ is_active = False
47
+ if user and user.get("subscription_status") == "active":
48
+ if user.get("subscription_expiry") and user.get("subscription_expiry") > now:
49
+ is_active = True
50
+ else:
51
+ await db.mark_user_expired(user_id)
52
+
53
+ if not is_active:
54
+ plans = await db.get_subscription_plans()
55
+ if not plans:
56
+ return await message.reply_text(
57
+ '<b>Welcome to the Telegram Stremio Private Group!</b>\n\n'
58
+ 'Currently, no subscription plans are set up. Please contact the administrator.',
59
+ quote=True,
60
+ parse_mode=enums.ParseMode.HTML
61
+ )
62
+
63
+ keyboard_buttons = []
64
+ for plan in plans:
65
+ keyboard_buttons.append([InlineKeyboardButton(f"{plan['days']} Days - β‚Ή{plan['price']}", callback_data=f"plan_{plan['_id']}")])
66
+
67
+ keyboard = InlineKeyboardMarkup(keyboard_buttons)
68
+
69
+ return await message.reply_text(
70
+ '<b>Welcome to the Telegram Stremio Private Group!</b>\n\n'
71
+ 'Access to the Stremio Addon requires an active subscription.\n'
72
+ 'Please select a subscription plan below to continue:',
73
+ reply_markup=keyboard,
74
+ quote=True,
75
+ parse_mode=enums.ParseMode.HTML
76
+ )
77
+
78
+ # User is active, fetch their token
79
+ all_tokens = await db.get_all_api_tokens()
80
+ token_doc = next((t for t in all_tokens if t.get("user_id") == user_id), None)
81
+
82
+ if token_doc and "token" in token_doc:
83
+ token_str = token_doc["token"]
84
+ addon_url = f"{base_url}/stremio/{token_str}/manifest.json"
85
+
86
+ await message.reply_text(
87
+ 'πŸŽ‰ <b>Welcome back to the Telegram Stremio Subscription Manager!</b>\n\n'
88
+ 'Your subscription is active. Here is your personal addon link:\n\n'
89
+ '🎬 <b>Stremio Addon β€” Install Link:</b>\n'
90
+ f'<code>{addon_url}</code>\n\n'
91
+ 'Tap the link above β†’ <b>Install</b> in Stremio to start watching!',
92
+ quote=True,
93
+ parse_mode=enums.ParseMode.HTML
94
+ )
95
+
96
+ except Exception as e:
97
+ await message.reply_text(f"⚠️ Error: {e}")
98
+ print(f"Error in Subscription Bot /start handler: {e}")
Backend/pyrofork/subscription_plugins/subscription.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pyrogram import Client, filters
2
+ from pyrogram.types import Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
3
+ from Backend.config import Telegram
4
+ from Backend import db
5
+ from datetime import datetime, timedelta
6
+ import asyncio
7
+
8
+ from bson.objectid import ObjectId
9
+
10
+ @Client.on_callback_query(filters.regex(r"^plan_([a-fA-F0-9]{24})$"))
11
+ async def plan_selection(client: Client, callback_query: CallbackQuery):
12
+ if not Telegram.SUBSCRIPTION:
13
+ return await callback_query.answer("Subscriptions are not enabled.", show_alert=True)
14
+
15
+ plan_id = callback_query.matches[0].group(1)
16
+
17
+ plans = await db.get_subscription_plans()
18
+ plan = next((p for p in plans if p["_id"] == plan_id), None)
19
+
20
+ if not plan:
21
+ return await callback_query.answer("Invalid plan.", show_alert=True)
22
+
23
+ duration = plan["days"]
24
+ await callback_query.answer()
25
+
26
+ user_id = callback_query.from_user.id if callback_query.from_user else callback_query.message.chat.id
27
+ first_name = callback_query.from_user.first_name if callback_query.from_user else callback_query.message.chat.title
28
+ username = callback_query.from_user.username if callback_query.from_user else callback_query.message.chat.username
29
+
30
+ # Store initial user interaction if needed
31
+ await db.update_user_interaction(user_id, first_name, username)
32
+
33
+ # Calculate expiry
34
+ user = await db.get_user(user_id)
35
+ now = datetime.utcnow()
36
+ current_expiry = user.get("subscription_expiry") if user else None
37
+
38
+ if current_expiry and current_expiry > now:
39
+ new_expiry = current_expiry + timedelta(days=int(duration))
40
+ else:
41
+ new_expiry = now + timedelta(days=int(duration))
42
+
43
+ expiry_str = new_expiry.strftime("%Y-%m-%d %H:%M UTC")
44
+
45
+ text = (
46
+ f"<b>βœ… Plan Selected: {plan['days']} Days</b>\n\n"
47
+ f"<b>πŸ’° Price:</b> β‚Ή{plan['price']}\n"
48
+ f"<b>πŸ“… Expiry (if approved now):</b> {expiry_str}\n\n"
49
+ f"<b>πŸ“‹ Payment Instructions:</b>\n"
50
+ f"1. Pay β‚Ή{plan['price']} to the admin.\n"
51
+ f"2. <b>Send your payment screenshot directly here (in this chat)</b>.\n"
52
+ f" The admin will review and activate your subscription."
53
+ )
54
+
55
+ # Set pending payment state (price stored for admin display)
56
+ await db.set_pending_payment(user_id, int(duration), 0, price=plan.get("price", 0))
57
+
58
+ # Add cancel button
59
+ keyboard = InlineKeyboardMarkup([
60
+ [InlineKeyboardButton("❌ Cancel", callback_data="cancel_payment")]
61
+ ])
62
+
63
+ dm_sent = False
64
+ try:
65
+ msg = await client.send_message(
66
+ chat_id=user_id,
67
+ text=text,
68
+ reply_markup=keyboard,
69
+ )
70
+ dm_sent = True
71
+
72
+ async def delete_msg(message):
73
+ await asyncio.sleep(120)
74
+ try:
75
+ await message.delete()
76
+ except Exception:
77
+ pass
78
+
79
+ asyncio.create_task(delete_msg(msg))
80
+ except Exception as e:
81
+ print(f"Could not DM user {user_id}: {e}")
82
+
83
+ if dm_sent:
84
+ await callback_query.answer("βœ… Check your DM for payment instructions!", show_alert=True)
85
+ else:
86
+ # Fallback: reply in current chat if DM fails (user hasn't started bot)
87
+ fallback_msg = await callback_query.message.reply_text(
88
+ text + "\n\n⚠️ <i>Please start a DM with the bot first by clicking its username, then send your screenshot there.</i>",
89
+ reply_markup=keyboard,
90
+ quote=True,
91
+ )
92
+ await callback_query.answer()
93
+
94
+ async def delete_msg(message):
95
+ await asyncio.sleep(120)
96
+ try:
97
+ await message.delete()
98
+ except Exception:
99
+ pass
100
+
101
+ asyncio.create_task(delete_msg(fallback_msg))
102
+
103
+ @Client.on_callback_query(filters.regex(r"^cancel_payment$"))
104
+ async def cancel_payment_handler(client: Client, callback_query: CallbackQuery):
105
+ user_id = callback_query.from_user.id if callback_query.from_user else callback_query.message.chat.id
106
+
107
+ # Remove pending payment
108
+ await db.reject_payment(user_id)
109
+
110
+ await callback_query.answer("Payment process cancelled.", show_alert=True)
111
+ try:
112
+ await callback_query.message.delete()
113
+ except Exception:
114
+ pass
115
+
116
+
117
+ @Client.on_message(filters.photo & filters.private)
118
+ async def handle_payment_screenshot(client: Client, message: Message):
119
+ if not Telegram.SUBSCRIPTION:
120
+ return
121
+
122
+ # Safely resolve sender ID
123
+ sender_id = (message.from_user.id if message.from_user else None) \
124
+ or (message.sender_chat.id if message.sender_chat else None) \
125
+ or message.chat.id
126
+
127
+ try:
128
+ print(f"DEBUG: handle_payment_screenshot triggered by {sender_id}")
129
+ # Check if user has a pending payment request
130
+ user = await db.get_user(sender_id)
131
+ print(f"DEBUG: user from DB = {user}")
132
+ if not user or "pending_payment" not in user:
133
+ # No active payment flow - tell the user what to do
134
+ print(f"DEBUG: No pending_payment found for {sender_id}")
135
+ await message.reply_text(
136
+ "ℹ️ We received your photo, but you don't have an active payment request.\n\n"
137
+ "Please use /start to select a subscription plan first, then send your payment screenshot.",
138
+ quote=True
139
+ )
140
+ return
141
+
142
+ pending = user["pending_payment"]
143
+ duration = pending.get("duration", "?")
144
+ price = pending.get("price", "?")
145
+
146
+ # --- Admin notification ---
147
+ keyboard = InlineKeyboardMarkup([
148
+ [
149
+ InlineKeyboardButton("βœ… Approve", callback_data=f"approve_{sender_id}"),
150
+ InlineKeyboardButton("❌ Reject", callback_data=f"reject_{sender_id}")
151
+ ]
152
+ ])
153
+
154
+ user_mention = message.from_user.mention if message.from_user else f"User {sender_id}"
155
+ username_str = f"@{message.from_user.username}" if (message.from_user and message.from_user.username) else "N/A"
156
+
157
+ admin_text = (
158
+ f"<b>πŸ’° New Payment Screenshot Received</b>\n\n"
159
+ f"<b>πŸ‘€ User:</b> {user_mention}\n"
160
+ f"<b>πŸ†” User ID:</b> <code>{sender_id}</code>\n"
161
+ f"<b>πŸ”— Username:</b> {username_str}\n\n"
162
+ f"<b>πŸ“¦ Plan Details:</b>\n"
163
+ f" β€’ Duration: <b>{duration} days</b>\n"
164
+ f" β€’ Price: <b>β‚Ή{price}</b>\n\n"
165
+ f"Please review the screenshot above and approve or reject."
166
+ )
167
+
168
+ approver_ids = Telegram.APPROVER_IDS if Telegram.APPROVER_IDS else [Telegram.OWNER_ID]
169
+ admin_messages = []
170
+ for approver_id in approver_ids:
171
+ try:
172
+ sent = await message.copy(approver_id, caption=admin_text, reply_markup=keyboard)
173
+ admin_messages.append({"chat_id": approver_id, "message_id": sent.id})
174
+ except Exception as e:
175
+ print(f"Failed to forward screenshot to approver {approver_id}: {e}")
176
+
177
+ # Update pending state with screenshot message ID + all admin message IDs
178
+ await db.set_pending_payment(sender_id, duration, message.id, price=price,
179
+ admin_messages=admin_messages)
180
+
181
+ if admin_messages:
182
+ await message.reply_text(
183
+ "βœ… <b>Screenshot Received!</b>\n\n"
184
+ "Your payment screenshot has been forwarded to the admin for review.\n"
185
+ "You will be notified once it's approved. Thank you! πŸ™",
186
+ quote=True
187
+ )
188
+ else:
189
+ await message.reply_text(
190
+ "⚠️ Your screenshot was received but we could not reach the admin. "
191
+ "Please contact the admin directly.",
192
+ quote=True
193
+ )
194
+
195
+ except Exception as e:
196
+ print(f"Error in handle_payment_screenshot: {e}")
197
+ await message.reply_text(
198
+ f"⚠️ Something went wrong while processing your screenshot. Please try again or contact the admin.\n\nError: {e}",
199
+ quote=True
200
+ )
201
+
202
+
203
+ @Client.on_callback_query(filters.regex(r"^(approve|reject)_(\d+)$"))
204
+ async def admin_review(client: Client, callback_query: CallbackQuery):
205
+ approver_ids = Telegram.APPROVER_IDS if Telegram.APPROVER_IDS else [Telegram.OWNER_ID]
206
+ if callback_query.from_user.id not in approver_ids:
207
+ return await callback_query.answer("You are not authorized to perform this action.", show_alert=True)
208
+
209
+ action = callback_query.matches[0].group(1)
210
+ target_user_id = int(callback_query.matches[0].group(2))
211
+ acting_admin = callback_query.from_user
212
+ admin_name = acting_admin.first_name or acting_admin.username or f"Admin {acting_admin.id}"
213
+
214
+ # Fetch admin_messages BEFORE any DB write (approve/reject unsets pending_payment)
215
+ user_pre = await db.get_user(target_user_id)
216
+ if not user_pre or "pending_payment" not in user_pre:
217
+ return await callback_query.answer("This request has already been processed.", show_alert=True)
218
+
219
+ admin_messages = user_pre["pending_payment"].get("admin_messages", [])
220
+
221
+ if action == "approve":
222
+ user_data = await db.approve_payment(target_user_id)
223
+ if user_data:
224
+ # Generate or retrieve existing API token for this user
225
+ try:
226
+ user_obj = await db.get_user(target_user_id)
227
+ user_name = (user_obj.get("first_name") or user_obj.get("username") or str(target_user_id)) if user_obj else str(target_user_id)
228
+ token_doc = await db.add_api_token(name=user_name, user_id=target_user_id)
229
+ token_str = token_doc.get("token")
230
+ addon_url = f"{Telegram.BASE_URL}/stremio/{token_str}/manifest.json"
231
+ except Exception as te:
232
+ token_str = None
233
+ addon_url = None
234
+
235
+ # Generate invite link for the group
236
+ try:
237
+ invite_link = await client.create_chat_invite_link(
238
+ chat_id=Telegram.SUBSCRIPTION_GROUP_ID,
239
+ member_limit=1,
240
+ expire_date=datetime.utcnow() + timedelta(days=1)
241
+ )
242
+ invite_text = f"\n\nπŸ”— <b>Group Invite:</b> {invite_link.invite_link}"
243
+ except Exception:
244
+ invite_text = ""
245
+
246
+ expiry_str = user_data["subscription_expiry"].strftime("%Y-%m-%d")
247
+
248
+ # Build confirmation message for user
249
+ success_text = (
250
+ f"πŸŽ‰ <b>Payment Approved!</b>\n\n"
251
+ f"Your subscription is now active until <b>{expiry_str}</b>."
252
+ f"{invite_text}"
253
+ )
254
+ if addon_url:
255
+ success_text += (
256
+ f"\n\n🎬 <b>Stremio Addon β€” Install Link:</b>\n"
257
+ f"<code>{addon_url}</code>\n\n"
258
+ f"Tap the link above β†’ <b>Install</b> in Stremio to start watching!"
259
+ )
260
+
261
+ await client.send_message(target_user_id, success_text)
262
+
263
+ # Determine how to format the user/payment info
264
+ duration = user_pre["pending_payment"].get("duration", "?")
265
+ price = user_pre["pending_payment"].get("price", "?")
266
+
267
+ try:
268
+ target_user = await client.get_users(target_user_id)
269
+ user_mention = target_user.mention
270
+ username_str = f"@{target_user.username}" if target_user.username else "N/A"
271
+ except Exception:
272
+ user_mention = f"User {target_user_id}"
273
+ username_str = "N/A"
274
+
275
+ info_text = (
276
+ f"πŸ‘€ <b>User:</b> {user_mention}\n"
277
+ f"πŸ†” <b>User ID:</b> <code>{target_user_id}</code>\n"
278
+ f"πŸ”— <b>Username:</b> {username_str}\n\n"
279
+ f"πŸ“¦ <b>Plan:</b> {duration} days (β‚Ή{price})"
280
+ )
281
+
282
+ # Update acting admin's message
283
+ status_caption = f"βœ… <b>Approved by {admin_name}</b>\n\n{info_text}"
284
+ await callback_query.message.edit_caption(status_caption)
285
+
286
+ # Update all OTHER admins' copies
287
+ acting_msg_id = callback_query.message.id
288
+ for am in admin_messages:
289
+ if am["message_id"] == acting_msg_id:
290
+ continue
291
+ try:
292
+ await client.edit_message_caption(
293
+ chat_id=am["chat_id"],
294
+ message_id=am["message_id"],
295
+ caption=status_caption
296
+ )
297
+ except Exception:
298
+ pass
299
+ else:
300
+ await callback_query.answer("Could not approve β€” no pending payment found.", show_alert=True)
301
+
302
+ elif action == "reject":
303
+ success = await db.reject_payment(target_user_id)
304
+ if success:
305
+ await client.send_message(
306
+ target_user_id,
307
+ "❌ <b>Payment Rejected</b>\n\nYour recent payment submission was rejected by the admin. Please contact the admin or try submitting again."
308
+ )
309
+
310
+ # Determine how to format the user/payment info
311
+ duration = user_pre["pending_payment"].get("duration", "?")
312
+ price = user_pre["pending_payment"].get("price", "?")
313
+
314
+ try:
315
+ target_user = await client.get_users(target_user_id)
316
+ user_mention = target_user.mention
317
+ username_str = f"@{target_user.username}" if target_user.username else "N/A"
318
+ except Exception:
319
+ user_mention = f"User {target_user_id}"
320
+ username_str = "N/A"
321
+
322
+ info_text = (
323
+ f"πŸ‘€ <b>User:</b> {user_mention}\n"
324
+ f"πŸ†” <b>User ID:</b> <code>{target_user_id}</code>\n"
325
+ f"πŸ”— <b>Username:</b> {username_str}\n\n"
326
+ f"πŸ“¦ <b>Plan:</b> {duration} days (β‚Ή{price})"
327
+ )
328
+
329
+ # Update acting admin's message
330
+ status_caption = f"❌ <b>Rejected by {admin_name}</b>\n\n{info_text}"
331
+ await callback_query.message.edit_caption(status_caption)
332
+
333
+ # Update all OTHER admins' copies
334
+ acting_msg_id = callback_query.message.id
335
+ for am in admin_messages:
336
+ if am["message_id"] == acting_msg_id:
337
+ continue
338
+ try:
339
+ await client.edit_message_caption(
340
+ chat_id=am["chat_id"],
341
+ message_id=am["message_id"],
342
+ caption=status_caption
343
+ )
344
+ except Exception:
345
+ pass
346
+ else:
347
+ await callback_query.answer("Could not reject β€” no pending payment found.", show_alert=True)
348
+
349
+
350
+ @Client.on_message(filters.command("status"))
351
+ async def check_status(client: Client, message: Message):
352
+ if not Telegram.SUBSCRIPTION:
353
+ return
354
+
355
+ user_id = (message.from_user.id if message.from_user else None) or (message.sender_chat.id if message.sender_chat else None) or message.chat.id
356
+
357
+ user = await db.get_user(user_id)
358
+ if not user or user.get("subscription_status") != "active":
359
+ return await message.reply_text("You do not have an active subscription.")
360
+
361
+ expiry = user.get("subscription_expiry")
362
+ if not expiry:
363
+ return await message.reply_text("Error retrieving expiry date.")
364
+
365
+ now = datetime.utcnow()
366
+ if now > expiry:
367
+ return await message.reply_text("Your subscription has expired.")
368
+
369
+ remaining = expiry - now
370
+ days = remaining.days
371
+ hours = remaining.seconds // 3600
372
+
373
+ await message.reply_text(
374
+ f"<b>Subscription Status:</b> Active βœ…\n"
375
+ f"<b>Expiry Date:</b> {expiry.strftime('%Y-%m-%d %H:%M UTC')}\n"
376
+ f"<b>Time Remaining:</b> {days} days and {hours} hours"
377
+ )
README.md CHANGED
@@ -89,6 +89,9 @@ This project is a **next-generation Telegram Stremio Media Server** that allows
89
  - πŸ†“ **Free Mode Toggle** – Administrators can turn off the `SUBSCRIPTION` requirement in `config.env` to allow all users immediate access via an automatically generated API token.
90
  - πŸ”„ **Automatic Stream Cleanup** – Deleting a source message in the Telegram channel instantly deletes all corresponding streams and qualities from the Stremio Addon Database and Admin Panel, preventing dead links.
91
  - 🏷️ **Manual IMDb/TMDb Override** – Users can instantly update or fix incorrect metadata for a file by simply editing the Telegram channel message caption and pasting the correct IMDb/TMDB URL.
 
 
 
92
 
93
 
94
 
@@ -257,8 +260,8 @@ All environment variables for this project are defined in the `config.env` file.
257
  | **`OWNER_ID`** | Your **Telegram user ID**. This ID has full administrative access. |
258
  | **`REPLACE_MODE`** | When `true`, new files replace existing files of the same quality. When `false`, multiple files of the same quality are allowed. |
259
  | **`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`. |
260
- | **`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). |
261
- | **`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). |
262
 
263
  ### πŸ—„οΈ Storage
264
 
@@ -326,6 +329,12 @@ To avoid this, you can use **MULTI_TOKEN** system:
326
  - Add the tokens in your `config.env` as `MULTI_TOKEN1`, `MULTI_TOKEN2`, `MULTI_TOKEN3`, and so on.
327
  - The system will automatically distribute the load among all these bots!
328
 
 
 
 
 
 
 
329
 
330
  ---
331
 
 
89
  - πŸ†“ **Free Mode Toggle** – Administrators can turn off the `SUBSCRIPTION` requirement in `config.env` to allow all users immediate access via an automatically generated API token.
90
  - πŸ”„ **Automatic Stream Cleanup** – Deleting a source message in the Telegram channel instantly deletes all corresponding streams and qualities from the Stremio Addon Database and Admin Panel, preventing dead links.
91
  - 🏷️ **Manual IMDb/TMDb Override** – Users can instantly update or fix incorrect metadata for a file by simply editing the Telegram channel message caption and pasting the correct IMDb/TMDB URL.
92
+ - πŸ›‘οΈ **Stream Stability & Recovery** – Intelligent `b""` empty-chunk fallback that securely pads video streams with zero bytes, and reduced chunk retry lockups (from 6 to 3) to instantaneously recover from stalled parts without breaking the video player.
93
+ - 🎯 **DC-Aware Bot Selection** – The underlying streaming load-balancer now ensures that a bot located in the exact same Data Center as the media file is prioritized. This substantially minimizes cross-DC round-trips and timeouts.
94
+ - 🌐 **Addon Proxy Integration** – Built-in functionality targeting `config.env` configurations (`Proxy`, `ProxyType`, `HTTP_Proxy_URL`, `SHOW_ProxyAndNonProxyBoth`) allows instant proxying or caching of video streams (such as routing through Cloudflare Workers) natively on Stremio.
95
 
96
 
97
 
 
260
  | **`OWNER_ID`** | Your **Telegram user ID**. This ID has full administrative access. |
261
  | **`REPLACE_MODE`** | When `true`, new files replace existing files of the same quality. When `false`, multiple files of the same quality are allowed. |
262
  | **`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`. |
263
+ | **`PARALLEL`** | Controls the queue size for chunks buffered ahead. Keeps the player buffer full without overloading Telegram. Example: `PARALLEL = 4` means 4 chunks are buffered ahead. Default is `1`. |
264
+ | **`PRE_FETCH`** | Controls the number of workers downloading chunks simultaneously. Example: `PRE_FETCH = 3` means 3 workers download concurrently. Higher values can improve speed but increase API load. Default is `1`. |
265
 
266
  ### πŸ—„οΈ Storage
267
 
 
329
  - Add the tokens in your `config.env` as `MULTI_TOKEN1`, `MULTI_TOKEN2`, `MULTI_TOKEN3`, and so on.
330
  - The system will automatically distribute the load among all these bots!
331
 
332
+ > ⚠️ **Real Limitation:**
333
+ > Even if you configure 10 bots in your system, **a single stream will typically only use 1 bot**. Extra bots do not make a single stream download 10x faster. Their primary purpose is to help handle **multiple users streaming simultaneously** without hitting rate limits:
334
+ > - User 1 β†’ assigned to Bot 1
335
+ > - User 2 β†’ assigned to Bot 2
336
+ > - User 3 β†’ assigned to Bot 3
337
+
338
 
339
  ---
340
 
sample_config.env CHANGED
@@ -22,3 +22,8 @@ SUBSCRIPTION_GROUP_ID= #without ""
22
  APPROVER_IDS= #without ""
23
  SUBSCRIPTION_URL="" #telegram bot url like https://t.me/username
24
  MULTI_TOKEN1=""
 
 
 
 
 
 
22
  APPROVER_IDS= #without ""
23
  SUBSCRIPTION_URL="" #telegram bot url like https://t.me/username
24
  MULTI_TOKEN1=""
25
+ # Proxy Configs
26
+ Proxy=True
27
+ ProxyType=HTTPS
28
+ HTTP_Proxy_URL="" #example https://PROXYURL/?url=
29
+ SHOW_ProxyAndNonProxyBoth=True # this will show both link proxy and non proxy both