Karan Adhikari commited on
Fix Subscription system
Browse files- Backend/config.py +0 -1
- Backend/fastapi/routes/api_routes.py +24 -2
- Backend/fastapi/routes/stremio_routes.py +67 -11
- Backend/fastapi/templates/access_manage.html +12 -12
- Backend/fastapi/templates/settings.html +8 -15
- Backend/fastapi/templates/subscriptions_manage.html +9 -9
- Backend/helper/database.py +29 -25
- Backend/helper/settings_manager.py +1 -7
- Backend/helper/subscription_checker.py +4 -8
- Backend/pyrofork/bot.py +13 -0
- README.md +19 -7
Backend/config.py
CHANGED
|
@@ -33,7 +33,6 @@ class Telegram:
|
|
| 33 |
ADMIN_PASSWORD = getenv("ADMIN_PASSWORD", "admin")
|
| 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 |
HTTP_PROXY_URL = getenv("HTTP_Proxy_URL", "")
|
| 39 |
SHOW_PROXY_AND_NON_PROXY_BOTH = getenv("SHOW_ProxyAndNonProxyBoth", "false").lower() == "true"
|
|
|
|
| 33 |
ADMIN_PASSWORD = getenv("ADMIN_PASSWORD", "admin")
|
| 34 |
SUBSCRIPTION = getenv("SUBSCRIPTION", "false").lower() == "true"
|
| 35 |
SUBSCRIPTION_GROUP_ID = int(getenv("SUBSCRIPTION_GROUP_ID", "0"))
|
|
|
|
| 36 |
APPROVER_IDS = [int(x.strip()) for x in (getenv("APPROVER_IDS") or "").split(",") if x.strip().isdigit()]
|
| 37 |
HTTP_PROXY_URL = getenv("HTTP_Proxy_URL", "")
|
| 38 |
SHOW_PROXY_AND_NON_PROXY_BOTH = getenv("SHOW_ProxyAndNonProxyBoth", "false").lower() == "true"
|
Backend/fastapi/routes/api_routes.py
CHANGED
|
@@ -580,8 +580,30 @@ async def manage_subscriber_api(user_id: int, payload: dict) -> dict:
|
|
| 580 |
raise HTTPException(status_code=400, detail="Invalid action")
|
| 581 |
|
| 582 |
success = await db.manage_subscriber(user_id, action, days)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 583 |
if success:
|
| 584 |
-
|
|
|
|
| 585 |
else:
|
| 586 |
raise HTTPException(status_code=404, detail="User not found or update failed")
|
| 587 |
except HTTPException:
|
|
@@ -1049,7 +1071,7 @@ async def update_settings_api(payload: dict) -> dict:
|
|
| 1049 |
|
| 1050 |
# Strip whitespace from string fields
|
| 1051 |
for key in ("tmdb_api", "base_url", "upstream_repo", "upstream_branch",
|
| 1052 |
-
"admin_username", "admin_password", "http_proxy_url",
|
| 1053 |
"payment_instructions", "payment_qr_url"):
|
| 1054 |
if key in payload and isinstance(payload[key], str):
|
| 1055 |
payload[key] = payload[key].strip()
|
|
|
|
| 580 |
raise HTTPException(status_code=400, detail="Invalid action")
|
| 581 |
|
| 582 |
success = await db.manage_subscriber(user_id, action, days)
|
| 583 |
+
|
| 584 |
+
# On revoke, also remove the user from the subscription group so the
|
| 585 |
+
# action takes effect immediately instead of waiting for the checker.
|
| 586 |
+
if success and action == "delete" and SettingsManager.current().subscription:
|
| 587 |
+
group_id = SettingsManager.current().subscription_group_id
|
| 588 |
+
if group_id:
|
| 589 |
+
try:
|
| 590 |
+
# ban + unban kicks without permanently blocking re-join
|
| 591 |
+
await StreamBot.ban_chat_member(group_id, user_id)
|
| 592 |
+
await StreamBot.unban_chat_member(group_id, user_id)
|
| 593 |
+
except Exception as exc:
|
| 594 |
+
LOGGER.warning(f"Revoke: could not remove user {user_id} from group: {exc}")
|
| 595 |
+
|
| 596 |
+
# Reflect the change immediately in the stremio membership cache.
|
| 597 |
+
if success:
|
| 598 |
+
try:
|
| 599 |
+
from Backend.fastapi.routes.stremio_routes import invalidate_membership_cache
|
| 600 |
+
invalidate_membership_cache(user_id)
|
| 601 |
+
except Exception:
|
| 602 |
+
pass
|
| 603 |
+
|
| 604 |
if success:
|
| 605 |
+
verb = {"extend": "extended", "reduce": "reduced", "delete": "revoked"}.get(action, "updated")
|
| 606 |
+
return {"status": "success", "message": f"User subscription {verb} successfully"}
|
| 607 |
else:
|
| 608 |
raise HTTPException(status_code=404, detail="User not found or update failed")
|
| 609 |
except HTTPException:
|
|
|
|
| 1071 |
|
| 1072 |
# Strip whitespace from string fields
|
| 1073 |
for key in ("tmdb_api", "base_url", "upstream_repo", "upstream_branch",
|
| 1074 |
+
"admin_username", "admin_password", "http_proxy_url",
|
| 1075 |
"payment_instructions", "payment_qr_url"):
|
| 1076 |
if key in payload and isinstance(payload[key], str):
|
| 1077 |
payload[key] = payload[key].strip()
|
Backend/fastapi/routes/stremio_routes.py
CHANGED
|
@@ -10,6 +10,7 @@ from datetime import datetime, timezone, timedelta
|
|
| 10 |
from Backend.fastapi.security.tokens import verify_token
|
| 11 |
from Backend.logger import LOGGER
|
| 12 |
from Backend.helper.global_search import global_search, is_global_search_enabled
|
|
|
|
| 13 |
|
| 14 |
router = APIRouter(prefix="/stremio", tags=["Stremio Addon"])
|
| 15 |
|
|
@@ -18,6 +19,18 @@ ADDON_NAME = "Telegram"
|
|
| 18 |
ADDON_VERSION = __version__
|
| 19 |
PAGE_SIZE = 15
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
# Define available genres
|
| 22 |
GENRES = [
|
| 23 |
"Action", "Adventure", "Animation", "Biography", "Comedy",
|
|
@@ -365,11 +378,6 @@ async def get_meta(token: str, media_type: str, id: str, token_data: dict = Depe
|
|
| 365 |
return {"meta": meta_obj}
|
| 366 |
|
| 367 |
async def _global_streams_for(token: str, imdb_id: str, media_type: str, season_num: Optional[int], episode_num: Optional[int]) -> list:
|
| 368 |
-
"""Builds Global Search stream entries for a catalog item that has no
|
| 369 |
-
local DB row at all. Since there's no local title to read, the
|
| 370 |
-
canonical title (and, for a specific episode, confirmation it exists)
|
| 371 |
-
is resolved from Cinemeta via Backend.helper.imdb β the same source
|
| 372 |
-
used everywhere else in this codebase for metadata."""
|
| 373 |
from Backend.helper.imdb import get_detail, get_season
|
| 374 |
|
| 375 |
imdb_media_type = "tvSeries" if media_type == "series" else "movie"
|
|
@@ -409,6 +417,42 @@ async def _global_streams_for(token: str, imdb_id: str, media_type: str, season_
|
|
| 409 |
return streams
|
| 410 |
|
| 411 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 412 |
@router.get("/{token}/stream/{media_type}/{id}.json")
|
| 413 |
async def get_streams(
|
| 414 |
token: str,
|
|
@@ -421,13 +465,28 @@ async def get_streams(
|
|
| 421 |
return {
|
| 422 |
"streams": [
|
| 423 |
{
|
| 424 |
-
"name": "π«
|
| 425 |
-
"title": "Your
|
| 426 |
-
"url":
|
| 427 |
}
|
| 428 |
]
|
| 429 |
}
|
| 430 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 431 |
if token_data.get("limit_exceeded"):
|
| 432 |
limit_type = token_data["limit_exceeded"]
|
| 433 |
|
|
@@ -501,9 +560,6 @@ async def get_streams(
|
|
| 501 |
"url": original_url
|
| 502 |
})
|
| 503 |
elif is_global_search_enabled():
|
| 504 |
-
# Not in the local catalog at all β resolve the real title via
|
| 505 |
-
# Cinemeta (we have no local DB row to read a title from) and
|
| 506 |
-
# search for it across the Userbot's channels instead.
|
| 507 |
try:
|
| 508 |
streams.extend(
|
| 509 |
await _global_streams_for(token, imdb_id, media_type, season_num, episode_num)
|
|
|
|
| 10 |
from Backend.fastapi.security.tokens import verify_token
|
| 11 |
from Backend.logger import LOGGER
|
| 12 |
from Backend.helper.global_search import global_search, is_global_search_enabled
|
| 13 |
+
from Backend.pyrofork.bot import get_streambot_url
|
| 14 |
|
| 15 |
router = APIRouter(prefix="/stremio", tags=["Stremio Addon"])
|
| 16 |
|
|
|
|
| 19 |
ADDON_VERSION = __version__
|
| 20 |
PAGE_SIZE = 15
|
| 21 |
|
| 22 |
+
_membership_cache: dict = {}
|
| 23 |
+
_MEMBERSHIP_TTL = 60 # seconds
|
| 24 |
+
_MEMBERSHIP_CACHE_MAX = 5000
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def invalidate_membership_cache(user_id: int | None = None) -> None:
|
| 28 |
+
if user_id is None:
|
| 29 |
+
_membership_cache.clear()
|
| 30 |
+
return
|
| 31 |
+
for key in [k for k in _membership_cache if k[1] == user_id]:
|
| 32 |
+
_membership_cache.pop(key, None)
|
| 33 |
+
|
| 34 |
# Define available genres
|
| 35 |
GENRES = [
|
| 36 |
"Action", "Adventure", "Animation", "Biography", "Comedy",
|
|
|
|
| 378 |
return {"meta": meta_obj}
|
| 379 |
|
| 380 |
async def _global_streams_for(token: str, imdb_id: str, media_type: str, season_num: Optional[int], episode_num: Optional[int]) -> list:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
from Backend.helper.imdb import get_detail, get_season
|
| 382 |
|
| 383 |
imdb_media_type = "tvSeries" if media_type == "series" else "movie"
|
|
|
|
| 417 |
return streams
|
| 418 |
|
| 419 |
|
| 420 |
+
async def _is_subscription_member(user_id: int) -> bool:
|
| 421 |
+
import time
|
| 422 |
+
from Backend.pyrofork.bot import StreamBot
|
| 423 |
+
from pyrogram.enums import ChatMemberStatus
|
| 424 |
+
from pyrogram.errors import UserNotParticipant
|
| 425 |
+
|
| 426 |
+
group_id = SettingsManager.current().subscription_group_id
|
| 427 |
+
if not group_id:
|
| 428 |
+
return True
|
| 429 |
+
|
| 430 |
+
cache_key = (group_id, user_id)
|
| 431 |
+
cached = _membership_cache.get(cache_key)
|
| 432 |
+
now_ts = time.monotonic()
|
| 433 |
+
if cached and (now_ts - cached[0]) < _MEMBERSHIP_TTL:
|
| 434 |
+
return cached[1]
|
| 435 |
+
|
| 436 |
+
try:
|
| 437 |
+
member = await StreamBot.get_chat_member(group_id, user_id)
|
| 438 |
+
result = member.status not in (ChatMemberStatus.LEFT, ChatMemberStatus.BANNED)
|
| 439 |
+
except UserNotParticipant:
|
| 440 |
+
result = False
|
| 441 |
+
except Exception as e:
|
| 442 |
+
# Fail open and do NOT cache, so the next request retries.
|
| 443 |
+
LOGGER.warning(f"[SUBSCRIPTION] Membership check failed for user {user_id}: {e}")
|
| 444 |
+
return True
|
| 445 |
+
|
| 446 |
+
if len(_membership_cache) >= _MEMBERSHIP_CACHE_MAX:
|
| 447 |
+
for k in [k for k, v in _membership_cache.items() if (now_ts - v[0]) >= _MEMBERSHIP_TTL]:
|
| 448 |
+
_membership_cache.pop(k, None)
|
| 449 |
+
if len(_membership_cache) >= _MEMBERSHIP_CACHE_MAX:
|
| 450 |
+
_membership_cache.clear()
|
| 451 |
+
|
| 452 |
+
_membership_cache[cache_key] = (now_ts, result)
|
| 453 |
+
return result
|
| 454 |
+
|
| 455 |
+
|
| 456 |
@router.get("/{token}/stream/{media_type}/{id}.json")
|
| 457 |
async def get_streams(
|
| 458 |
token: str,
|
|
|
|
| 465 |
return {
|
| 466 |
"streams": [
|
| 467 |
{
|
| 468 |
+
"name": "π« Plan Expired",
|
| 469 |
+
"title": "Your plan is expired.\nRenew it from the bot to continue watching.",
|
| 470 |
+
"url": get_streambot_url()
|
| 471 |
}
|
| 472 |
]
|
| 473 |
}
|
| 474 |
|
| 475 |
+
# When the subscription feature is on, the user must be a current member of
|
| 476 |
+
# the configured subscription group/channel to stream anything.
|
| 477 |
+
if SettingsManager.current().subscription:
|
| 478 |
+
user_id = token_data.get("user_id")
|
| 479 |
+
if user_id and not await _is_subscription_member(int(user_id)):
|
| 480 |
+
return {
|
| 481 |
+
"streams": [
|
| 482 |
+
{
|
| 483 |
+
"name": "π’ Join Required",
|
| 484 |
+
"title": "First join the channel to stream it.\nThen wait for 2 min for verification",
|
| 485 |
+
"url": get_streambot_url()
|
| 486 |
+
}
|
| 487 |
+
]
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
if token_data.get("limit_exceeded"):
|
| 491 |
limit_type = token_data["limit_exceeded"]
|
| 492 |
|
|
|
|
| 560 |
"url": original_url
|
| 561 |
})
|
| 562 |
elif is_global_search_enabled():
|
|
|
|
|
|
|
|
|
|
| 563 |
try:
|
| 564 |
streams.extend(
|
| 565 |
await _global_streams_for(token, imdb_id, media_type, season_num, episode_num)
|
Backend/fastapi/templates/access_manage.html
CHANGED
|
@@ -100,27 +100,27 @@
|
|
| 100 |
}
|
| 101 |
|
| 102 |
.glass-btn-success {
|
| 103 |
-
background:
|
| 104 |
-
color: #
|
| 105 |
-
border-color:
|
| 106 |
}
|
| 107 |
|
| 108 |
.glass-btn-warning {
|
| 109 |
-
background:
|
| 110 |
-
color: #
|
| 111 |
-
border-color:
|
| 112 |
}
|
| 113 |
|
| 114 |
.glass-btn-danger {
|
| 115 |
-
background:
|
| 116 |
-
color: #
|
| 117 |
-
border-color:
|
| 118 |
}
|
| 119 |
|
| 120 |
.glass-btn-purple {
|
| 121 |
-
background:
|
| 122 |
-
color: #
|
| 123 |
-
border-color:
|
| 124 |
}
|
| 125 |
|
| 126 |
.glass-input,
|
|
|
|
| 100 |
}
|
| 101 |
|
| 102 |
.glass-btn-success {
|
| 103 |
+
background: linear-gradient(135deg, #22c55e, #16a34a);
|
| 104 |
+
color: #ffffff;
|
| 105 |
+
border-color: transparent;
|
| 106 |
}
|
| 107 |
|
| 108 |
.glass-btn-warning {
|
| 109 |
+
background: linear-gradient(135deg, #f59e0b, #d97706);
|
| 110 |
+
color: #ffffff;
|
| 111 |
+
border-color: transparent;
|
| 112 |
}
|
| 113 |
|
| 114 |
.glass-btn-danger {
|
| 115 |
+
background: linear-gradient(135deg, #ef4444, #dc2626);
|
| 116 |
+
color: #ffffff;
|
| 117 |
+
border-color: transparent;
|
| 118 |
}
|
| 119 |
|
| 120 |
.glass-btn-purple {
|
| 121 |
+
background: linear-gradient(135deg, #a855f7, #9333ea);
|
| 122 |
+
color: #ffffff;
|
| 123 |
+
border-color: transparent;
|
| 124 |
}
|
| 125 |
|
| 126 |
.glass-input,
|
Backend/fastapi/templates/settings.html
CHANGED
|
@@ -243,19 +243,14 @@
|
|
| 243 |
</label>
|
| 244 |
|
| 245 |
<div id="sub-fields" style="{% if not settings.subscription %}display:none{% endif %}">
|
| 246 |
-
<div
|
| 247 |
-
<
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
<
|
| 254 |
-
<label class="s-label" for="subscription_url">Subscription URL</label>
|
| 255 |
-
<input type="url" id="subscription_url" class="s-input"
|
| 256 |
-
value="{{ settings.subscription_url }}"
|
| 257 |
-
placeholder="https://t.me/your_group">
|
| 258 |
-
</div>
|
| 259 |
</div>
|
| 260 |
|
| 261 |
<!-- Payment method -->
|
|
@@ -603,7 +598,6 @@ async function saveSettings() {
|
|
| 603 |
auth_channels: collectList('auth_channels'),
|
| 604 |
subscription: document.getElementById('subscription').checked,
|
| 605 |
subscription_group_id: parseInt(document.getElementById('subscription_group_id').value || '0', 10),
|
| 606 |
-
subscription_url: document.getElementById('subscription_url').value.trim(),
|
| 607 |
payment_instructions: document.getElementById('payment_instructions').value.trim(),
|
| 608 |
payment_qr_url: document.getElementById('payment_qr_url').value.trim(),
|
| 609 |
approver_ids: collectList('approver_ids').map(Number),
|
|
@@ -693,7 +687,6 @@ function renderSettings(s) {
|
|
| 693 |
document.getElementById('upstream_repo').value = s.upstream_repo || '';
|
| 694 |
document.getElementById('upstream_branch').value = s.upstream_branch || '';
|
| 695 |
document.getElementById('subscription_group_id').value = s.subscription_group_id || 0;
|
| 696 |
-
document.getElementById('subscription_url').value = s.subscription_url || '';
|
| 697 |
document.getElementById('http_proxy_url').value = s.http_proxy_url || '';
|
| 698 |
|
| 699 |
// Simple multi-value lists
|
|
|
|
| 243 |
</label>
|
| 244 |
|
| 245 |
<div id="sub-fields" style="{% if not settings.subscription %}display:none{% endif %}">
|
| 246 |
+
<div style="margin-bottom:1rem">
|
| 247 |
+
<label class="s-label" for="subscription_group_id">Subscription Group ID</label>
|
| 248 |
+
<input type="number" id="subscription_group_id" class="s-input"
|
| 249 |
+
value="{{ settings.subscription_group_id }}"
|
| 250 |
+
placeholder="-100xxxxxxxx">
|
| 251 |
+
<span style="color:var(--text-sec);font-size:0.78rem;display:block;margin-top:0.4rem">
|
| 252 |
+
Users are pointed back to your bot automatically for renewals and joining.
|
| 253 |
+
</span>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
</div>
|
| 255 |
|
| 256 |
<!-- Payment method -->
|
|
|
|
| 598 |
auth_channels: collectList('auth_channels'),
|
| 599 |
subscription: document.getElementById('subscription').checked,
|
| 600 |
subscription_group_id: parseInt(document.getElementById('subscription_group_id').value || '0', 10),
|
|
|
|
| 601 |
payment_instructions: document.getElementById('payment_instructions').value.trim(),
|
| 602 |
payment_qr_url: document.getElementById('payment_qr_url').value.trim(),
|
| 603 |
approver_ids: collectList('approver_ids').map(Number),
|
|
|
|
| 687 |
document.getElementById('upstream_repo').value = s.upstream_repo || '';
|
| 688 |
document.getElementById('upstream_branch').value = s.upstream_branch || '';
|
| 689 |
document.getElementById('subscription_group_id').value = s.subscription_group_id || 0;
|
|
|
|
| 690 |
document.getElementById('http_proxy_url').value = s.http_proxy_url || '';
|
| 691 |
|
| 692 |
// Simple multi-value lists
|
Backend/fastapi/templates/subscriptions_manage.html
CHANGED
|
@@ -103,21 +103,21 @@
|
|
| 103 |
}
|
| 104 |
|
| 105 |
.glass-btn-danger {
|
| 106 |
-
background:
|
| 107 |
-
color: #
|
| 108 |
-
border-color:
|
| 109 |
}
|
| 110 |
|
| 111 |
.glass-btn-warning {
|
| 112 |
-
background:
|
| 113 |
-
color: #
|
| 114 |
-
border-color:
|
| 115 |
}
|
| 116 |
|
| 117 |
.glass-btn-success {
|
| 118 |
-
background:
|
| 119 |
-
color: #
|
| 120 |
-
border-color:
|
| 121 |
}
|
| 122 |
|
| 123 |
.glass-input,
|
|
|
|
| 103 |
}
|
| 104 |
|
| 105 |
.glass-btn-danger {
|
| 106 |
+
background: linear-gradient(135deg, #ef4444, #dc2626);
|
| 107 |
+
color: #ffffff;
|
| 108 |
+
border-color: transparent;
|
| 109 |
}
|
| 110 |
|
| 111 |
.glass-btn-warning {
|
| 112 |
+
background: linear-gradient(135deg, #f59e0b, #d97706);
|
| 113 |
+
color: #ffffff;
|
| 114 |
+
border-color: transparent;
|
| 115 |
}
|
| 116 |
|
| 117 |
.glass-btn-success {
|
| 118 |
+
background: linear-gradient(135deg, #22c55e, #16a34a);
|
| 119 |
+
color: #ffffff;
|
| 120 |
+
border-color: transparent;
|
| 121 |
}
|
| 122 |
|
| 123 |
.glass-input,
|
Backend/helper/database.py
CHANGED
|
@@ -318,43 +318,47 @@ class Database:
|
|
| 318 |
return [convert_objectid_to_str(u) for u in users]
|
| 319 |
|
| 320 |
async def manage_subscriber(self, user_id: int, action: str, days: int = 0) -> bool:
|
| 321 |
-
|
| 322 |
-
if not user:
|
| 323 |
-
return False
|
| 324 |
-
|
| 325 |
now = datetime.utcnow()
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
|
|
|
| 330 |
if action == "extend":
|
| 331 |
-
if current_expiry and current_expiry > now
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
new_expiry = now + timedelta(days=days)
|
| 335 |
-
else: # reduce
|
| 336 |
if current_expiry:
|
| 337 |
new_expiry = current_expiry - timedelta(days=days)
|
| 338 |
if new_expiry < now:
|
| 339 |
-
new_expiry = now
|
| 340 |
else:
|
| 341 |
-
new_expiry = now
|
| 342 |
-
|
| 343 |
status = "active" if new_expiry > now else "expired"
|
| 344 |
-
|
| 345 |
-
|
| 346 |
{"_id": user_id},
|
| 347 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
)
|
| 349 |
-
return
|
| 350 |
-
|
| 351 |
elif action == "delete":
|
| 352 |
-
|
| 353 |
{"_id": user_id},
|
| 354 |
-
{"$
|
| 355 |
)
|
| 356 |
-
return
|
| 357 |
-
|
| 358 |
return False
|
| 359 |
|
| 360 |
async def assign_subscription(self, user_id: int, days: int) -> dict:
|
|
|
|
| 318 |
return [convert_objectid_to_str(u) for u in users]
|
| 319 |
|
| 320 |
async def manage_subscriber(self, user_id: int, action: str, days: int = 0) -> bool:
|
| 321 |
+
from datetime import timedelta
|
|
|
|
|
|
|
|
|
|
| 322 |
now = datetime.utcnow()
|
| 323 |
+
user = await self.get_user(user_id)
|
| 324 |
+
|
| 325 |
+
if action in ("extend", "reduce"):
|
| 326 |
+
current_expiry = user.get("subscription_expiry") if user else None
|
| 327 |
+
|
| 328 |
if action == "extend":
|
| 329 |
+
base = current_expiry if (current_expiry and current_expiry > now) else now
|
| 330 |
+
new_expiry = base + timedelta(days=days)
|
| 331 |
+
else:
|
|
|
|
|
|
|
| 332 |
if current_expiry:
|
| 333 |
new_expiry = current_expiry - timedelta(days=days)
|
| 334 |
if new_expiry < now:
|
| 335 |
+
new_expiry = now
|
| 336 |
else:
|
| 337 |
+
new_expiry = now
|
| 338 |
+
|
| 339 |
status = "active" if new_expiry > now else "expired"
|
| 340 |
+
|
| 341 |
+
await self.dbs["tracking"]["users"].update_one(
|
| 342 |
{"_id": user_id},
|
| 343 |
+
{
|
| 344 |
+
"$set": {"subscription_expiry": new_expiry, "subscription_status": status},
|
| 345 |
+
"$setOnInsert": {
|
| 346 |
+
"first_name": f"User {user_id}",
|
| 347 |
+
"username": None,
|
| 348 |
+
"created_at": now,
|
| 349 |
+
},
|
| 350 |
+
},
|
| 351 |
+
upsert=True
|
| 352 |
)
|
| 353 |
+
return True
|
| 354 |
+
|
| 355 |
elif action == "delete":
|
| 356 |
+
await self.dbs["tracking"]["users"].update_one(
|
| 357 |
{"_id": user_id},
|
| 358 |
+
{"$set": {"subscription_status": "expired", "subscription_expiry": now}}
|
| 359 |
)
|
| 360 |
+
return True
|
| 361 |
+
|
| 362 |
return False
|
| 363 |
|
| 364 |
async def assign_subscription(self, user_id: int, days: int) -> dict:
|
Backend/helper/settings_manager.py
CHANGED
|
@@ -17,7 +17,6 @@ _DEFAULTS: Dict[str, Any] = {
|
|
| 17 |
"admin_password": "admin",
|
| 18 |
"subscription": False,
|
| 19 |
"subscription_group_id": 0,
|
| 20 |
-
"subscription_url": "https://t.me/",
|
| 21 |
"approver_ids": [],
|
| 22 |
"payment_instructions": "",
|
| 23 |
"payment_qr_url": "",
|
|
@@ -47,7 +46,6 @@ def _seed_from_env() -> Dict[str, Any]:
|
|
| 47 |
"admin_password": Telegram.ADMIN_PASSWORD,
|
| 48 |
"subscription": Telegram.SUBSCRIPTION,
|
| 49 |
"subscription_group_id": Telegram.SUBSCRIPTION_GROUP_ID,
|
| 50 |
-
"subscription_url": Telegram.SUBSCRIPTION_URL,
|
| 51 |
"approver_ids": list(Telegram.APPROVER_IDS),
|
| 52 |
"global_search_channels": [],
|
| 53 |
"http_proxy_url": Telegram.HTTP_PROXY_URL,
|
|
@@ -123,10 +121,6 @@ class Settings:
|
|
| 123 |
def http_proxy_url(self) -> str:
|
| 124 |
return str(self._d.get("http_proxy_url") or "")
|
| 125 |
|
| 126 |
-
@property
|
| 127 |
-
def subscription_url(self) -> str:
|
| 128 |
-
return str(self._d.get("subscription_url") or "https://t.me/")
|
| 129 |
-
|
| 130 |
@property
|
| 131 |
def payment_instructions(self) -> str:
|
| 132 |
return str(self._d.get("payment_instructions") or "")
|
|
@@ -279,7 +273,7 @@ class SettingsManager:
|
|
| 279 |
LOGGER.error(f"SettingsManager reinit subscription: {exc}")
|
| 280 |
results["subscription"] = f"error: {exc}"
|
| 281 |
else:
|
| 282 |
-
sub_keys = {"subscription_group_id", "approver_ids",
|
| 283 |
"payment_instructions", "payment_qr_url"}
|
| 284 |
if any(old.get(k) != new.get(k) for k in sub_keys):
|
| 285 |
results["subscription"] = "settings reloaded in-memory"
|
|
|
|
| 17 |
"admin_password": "admin",
|
| 18 |
"subscription": False,
|
| 19 |
"subscription_group_id": 0,
|
|
|
|
| 20 |
"approver_ids": [],
|
| 21 |
"payment_instructions": "",
|
| 22 |
"payment_qr_url": "",
|
|
|
|
| 46 |
"admin_password": Telegram.ADMIN_PASSWORD,
|
| 47 |
"subscription": Telegram.SUBSCRIPTION,
|
| 48 |
"subscription_group_id": Telegram.SUBSCRIPTION_GROUP_ID,
|
|
|
|
| 49 |
"approver_ids": list(Telegram.APPROVER_IDS),
|
| 50 |
"global_search_channels": [],
|
| 51 |
"http_proxy_url": Telegram.HTTP_PROXY_URL,
|
|
|
|
| 121 |
def http_proxy_url(self) -> str:
|
| 122 |
return str(self._d.get("http_proxy_url") or "")
|
| 123 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
@property
|
| 125 |
def payment_instructions(self) -> str:
|
| 126 |
return str(self._d.get("payment_instructions") or "")
|
|
|
|
| 273 |
LOGGER.error(f"SettingsManager reinit subscription: {exc}")
|
| 274 |
results["subscription"] = f"error: {exc}"
|
| 275 |
else:
|
| 276 |
+
sub_keys = {"subscription_group_id", "approver_ids",
|
| 277 |
"payment_instructions", "payment_qr_url"}
|
| 278 |
if any(old.get(k) != new.get(k) for k in sub_keys):
|
| 279 |
results["subscription"] = "settings reloaded in-memory"
|
Backend/helper/subscription_checker.py
CHANGED
|
@@ -1,13 +1,11 @@
|
|
| 1 |
import asyncio
|
| 2 |
from pyrogram import Client
|
| 3 |
from Backend.helper.settings_manager import SettingsManager
|
|
|
|
| 4 |
from Backend import db
|
| 5 |
from datetime import datetime
|
| 6 |
from Backend.logger import LOGGER
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
async def subscription_checker_loop(bot: Client):
|
| 12 |
while True:
|
| 13 |
try:
|
|
@@ -34,7 +32,7 @@ async def subscription_checker_loop(bot: Client):
|
|
| 34 |
user_id,
|
| 35 |
"β <b>Subscription Expired</b>\n\n"
|
| 36 |
"Your subscription has expired, and you have been removed from the private group.\n"
|
| 37 |
-
f"Please
|
| 38 |
)
|
| 39 |
LOGGER.info(f"Kicked expired user {user_id}")
|
| 40 |
except Exception as e:
|
|
@@ -50,7 +48,7 @@ async def subscription_checker_loop(bot: Client):
|
|
| 50 |
user_id,
|
| 51 |
f"β οΈ <b>Subscription Expiring Soon</b>\n\n"
|
| 52 |
f"Your subscription will expire on <b>{expiry.strftime('%Y-%m-%d %H:%M UTC')}</b>.\n"
|
| 53 |
-
f"Please
|
| 54 |
)
|
| 55 |
await db.mark_reminder_sent(user_id)
|
| 56 |
LOGGER.info(f"Sent expiry reminder to user {user_id}")
|
|
@@ -60,10 +58,8 @@ async def subscription_checker_loop(bot: Client):
|
|
| 60 |
await asyncio.sleep(3600)
|
| 61 |
|
| 62 |
except asyncio.CancelledError:
|
| 63 |
-
# Raised by subscription_task_manager.stop() β exit cleanly,
|
| 64 |
-
# don't swallow it as a generic error.
|
| 65 |
LOGGER.info("Subscription checker loop cancelled.")
|
| 66 |
raise
|
| 67 |
except Exception as e:
|
| 68 |
LOGGER.error(f"Error in subscription checker loop: {e}")
|
| 69 |
-
await asyncio.sleep(300)
|
|
|
|
| 1 |
import asyncio
|
| 2 |
from pyrogram import Client
|
| 3 |
from Backend.helper.settings_manager import SettingsManager
|
| 4 |
+
from Backend.pyrofork.bot import get_streambot_url
|
| 5 |
from Backend import db
|
| 6 |
from datetime import datetime
|
| 7 |
from Backend.logger import LOGGER
|
| 8 |
|
|
|
|
|
|
|
|
|
|
| 9 |
async def subscription_checker_loop(bot: Client):
|
| 10 |
while True:
|
| 11 |
try:
|
|
|
|
| 32 |
user_id,
|
| 33 |
"β <b>Subscription Expired</b>\n\n"
|
| 34 |
"Your subscription has expired, and you have been removed from the private group.\n"
|
| 35 |
+
f"Please open the bot {get_streambot_url()} and send /start to renew your subscription and regain access."
|
| 36 |
)
|
| 37 |
LOGGER.info(f"Kicked expired user {user_id}")
|
| 38 |
except Exception as e:
|
|
|
|
| 48 |
user_id,
|
| 49 |
f"β οΈ <b>Subscription Expiring Soon</b>\n\n"
|
| 50 |
f"Your subscription will expire on <b>{expiry.strftime('%Y-%m-%d %H:%M UTC')}</b>.\n"
|
| 51 |
+
f"Please open the bot {get_streambot_url()} and send /start to renew your plan before you lose access to the group!"
|
| 52 |
)
|
| 53 |
await db.mark_reminder_sent(user_id)
|
| 54 |
LOGGER.info(f"Sent expiry reminder to user {user_id}")
|
|
|
|
| 58 |
await asyncio.sleep(3600)
|
| 59 |
|
| 60 |
except asyncio.CancelledError:
|
|
|
|
|
|
|
| 61 |
LOGGER.info("Subscription checker loop cancelled.")
|
| 62 |
raise
|
| 63 |
except Exception as e:
|
| 64 |
LOGGER.error(f"Error in subscription checker loop: {e}")
|
| 65 |
+
await asyncio.sleep(300)
|
Backend/pyrofork/bot.py
CHANGED
|
@@ -33,6 +33,19 @@ client_dc_map = {}
|
|
| 33 |
client_failures = {}
|
| 34 |
client_avg_mbps = {}
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
if Userbot is not None:
|
| 37 |
work_loads[USERBOT_CLIENT_INDEX] = 0
|
| 38 |
client_failures[USERBOT_CLIENT_INDEX] = 0
|
|
|
|
| 33 |
client_failures = {}
|
| 34 |
client_avg_mbps = {}
|
| 35 |
|
| 36 |
+
|
| 37 |
+
def get_streambot_url() -> str:
|
| 38 |
+
try:
|
| 39 |
+
username = getattr(StreamBot, "username", None)
|
| 40 |
+
if not username:
|
| 41 |
+
me = getattr(StreamBot, "me", None)
|
| 42 |
+
username = getattr(me, "username", None) if me else None
|
| 43 |
+
if username:
|
| 44 |
+
return f"https://t.me/{username}"
|
| 45 |
+
except Exception:
|
| 46 |
+
pass
|
| 47 |
+
return "https://t.me/"
|
| 48 |
+
|
| 49 |
if Userbot is not None:
|
| 50 |
work_loads[USERBOT_CLIENT_INDEX] = 0
|
| 51 |
client_failures[USERBOT_CLIENT_INDEX] = 0
|
README.md
CHANGED
|
@@ -436,7 +436,7 @@ Everything below is stored in the database and applied **instantly β no restar
|
|
| 436 |
| **Upstream Repo / Branch** | Optional β used by `/restart` to auto-update (e.g. repo `weebzone/Telegram-Stremio`, branch `master`). |
|
| 437 |
|
| 438 |
### π³ Subscription (optional)
|
| 439 |
-
Turn this on to monetise access. Set the **Subscription Group ID**, **
|
| 440 |
|
| 441 |
### π Global Search (optional)
|
| 442 |
Requires `USER_SESSION_STRING` in `config.env` plus one app restart to unlock. Then enable the toggle and add the **channel IDs** to search. Results that arenβt in your local catalog are tagged **π GLOBAL** in Stremio.
|
|
@@ -552,19 +552,31 @@ The addon manifest updates dynamically per user:
|
|
| 552 |
|
| 553 |
The manifest `version` encodes the expiry date β when an admin extends or revokes a subscription, the version changes and Stremio detects an update.
|
| 554 |
|
| 555 |
-
###
|
| 556 |
|
| 557 |
-
When
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 558 |
|
| 559 |
```json
|
| 560 |
{
|
| 561 |
-
"name": "
|
| 562 |
-
"title": "
|
| 563 |
-
"url": "https://t.me/your_bot"
|
| 564 |
}
|
| 565 |
```
|
| 566 |
|
| 567 |
-
Clicking the stream name opens the bot directly
|
| 568 |
|
| 569 |
### Configure & Reinstall Page
|
| 570 |
|
|
|
|
| 436 |
| **Upstream Repo / Branch** | Optional β used by `/restart` to auto-update (e.g. repo `weebzone/Telegram-Stremio`, branch `master`). |
|
| 437 |
|
| 438 |
### π³ Subscription (optional)
|
| 439 |
+
Turn this on to monetise access. Set the **Subscription Group ID**, **Payment Instructions** (your UPI / bank / PayPal text), an optional **Payment QR image URL**, and the **Approver IDs** (who can approve requests). Renewal and "join the channel" prompts shown in Stremio point users back to **your bot automatically** β no separate URL to configure. The full flow is described in [Subscription Management](#-subscription-management).
|
| 440 |
|
| 441 |
### π Global Search (optional)
|
| 442 |
Requires `USER_SESSION_STRING` in `config.env` plus one app restart to unlock. Then enable the toggle and add the **channel IDs** to search. Results that arenβt in your local catalog are tagged **π GLOBAL** in Stremio.
|
|
|
|
| 552 |
|
| 553 |
The manifest `version` encodes the expiry date β when an admin extends or revokes a subscription, the version changes and Stremio detects an update.
|
| 554 |
|
| 555 |
+
### Subscription Stream Gating
|
| 556 |
|
| 557 |
+
When the subscription feature is enabled, the addon checks every stream request and shows a single actionable entry instead of the streams when the user isn't eligible. In both cases the stream link opens **your bot** (derived automatically from the bot's username β there is no URL to configure).
|
| 558 |
+
|
| 559 |
+
**Plan expired** β the user's subscription has lapsed:
|
| 560 |
+
|
| 561 |
+
```json
|
| 562 |
+
{
|
| 563 |
+
"name": "π« Plan Expired",
|
| 564 |
+
"title": "Your plan is expired.\nRenew it from the bot to continue watching.",
|
| 565 |
+
"url": "https://t.me/your_bot"
|
| 566 |
+
}
|
| 567 |
+
```
|
| 568 |
+
|
| 569 |
+
**Not joined** β the user is active but has left / never joined the subscription channel (the `Subscription Group ID`):
|
| 570 |
|
| 571 |
```json
|
| 572 |
{
|
| 573 |
+
"name": "π’ Join Required",
|
| 574 |
+
"title": "First join the channel to stream it.\nTap here to open the bot and join.",
|
| 575 |
+
"url": "https://t.me/your_bot"
|
| 576 |
}
|
| 577 |
```
|
| 578 |
|
| 579 |
+
Clicking the stream name opens the bot directly so the user can renew or rejoin. The membership check fails open β if Telegram is briefly unreachable or the bot can't read the group, legitimate users are never blocked.
|
| 580 |
|
| 581 |
### Configure & Reinstall Page
|
| 582 |
|