AngryBird-22 commited on
Commit
699ee87
·
verified ·
1 Parent(s): 682f65d

Delete mfinder

Browse files
mfinder/__init__.py DELETED
@@ -1,140 +0,0 @@
1
- import os
2
- import re
3
- import logging
4
- import logging.config
5
- import asyncio
6
- from dotenv import load_dotenv
7
- from sqlalchemy import create_engine
8
- from sqlalchemy.orm import sessionmaker, scoped_session
9
- from sqlalchemy.pool import QueuePool, NullPool
10
-
11
- if not os.environ.get("BOT_TOKEN"):
12
- load_dotenv()
13
-
14
- id_pattern = re.compile(r"^.\d+$")
15
-
16
- # vars
17
- APP_ID = os.environ.get("APP_ID", "")
18
- API_HASH = os.environ.get("API_HASH", "")
19
- BOT_TOKEN = os.environ.get("BOT_TOKEN", "")
20
- DB_URL = os.environ.get("DB_URL", "")
21
- OWNER_ID = int(os.environ.get("OWNER_ID", ""))
22
- ADMINS = [
23
- int(user) if id_pattern.search(user) else user
24
- for user in os.environ.get("ADMINS", "").split()
25
- ] + [OWNER_ID]
26
- DB_CHANNELS = [
27
- int(ch) if id_pattern.search(ch) else ch
28
- for ch in os.environ.get("DB_CHANNELS", "").split()
29
- ]
30
-
31
- try:
32
- import const
33
- except Exception:
34
- import sample_const as const
35
-
36
- START_MSG = const.START_MSG
37
- START_KB = const.START_KB
38
- HELP_MSG = const.HELP_MSG
39
- HELP_KB = const.HELP_KB
40
-
41
- # logging Conf
42
- logging.config.fileConfig(fname="config.ini", disable_existing_loggers=False)
43
- LOGGER = logging.getLogger(__name__)
44
- logging.getLogger("pyrogram").setLevel(logging.WARNING)
45
-
46
- # Database connection
47
- def start():
48
- connect_args = {}
49
- if DB_URL and DB_URL.startswith(("postgres://", "postgresql://")):
50
- connect_args["sslmode"] = "require"
51
- engine = create_engine(
52
- DB_URL,
53
- connect_args=connect_args,
54
- poolclass=QueuePool,
55
- pool_size=10,
56
- max_overflow=20,
57
- pool_pre_ping=True,
58
- pool_recycle=1800 # Recycle connections every 1800 seconds (30 minutes)
59
- )
60
- return scoped_session(sessionmaker(bind=engine, autoflush=False))
61
-
62
- SESSION = start()
63
-
64
- def load_dynamic_configs():
65
- global ADMINS, DB_CHANNELS
66
- try:
67
- from mfinder.db import settings_sql
68
- with settings_sql.SESSION() as session:
69
- res = session.query(settings_sql.AdminSettings).first()
70
- if res:
71
- db_admins = res.admins_list
72
- db_channels = res.db_channels_list
73
- if db_admins is not None:
74
- loaded_admins = []
75
- for admin in db_admins.split(','):
76
- admin = admin.strip()
77
- if admin:
78
- if id_pattern.search(admin):
79
- loaded_admins.append(int(admin))
80
- else:
81
- loaded_admins.append(admin)
82
- if OWNER_ID not in loaded_admins:
83
- loaded_admins.append(OWNER_ID)
84
- ADMINS.clear()
85
- ADMINS.extend(loaded_admins)
86
-
87
- if db_channels is not None:
88
- loaded_channels = []
89
- for ch in db_channels.split(','):
90
- ch = ch.strip()
91
- if ch:
92
- if id_pattern.search(ch):
93
- loaded_channels.append(int(ch))
94
- else:
95
- loaded_channels.append(ch)
96
- DB_CHANNELS.clear()
97
- DB_CHANNELS.extend(loaded_channels)
98
- except Exception as e:
99
- print(f"Error loading dynamic configs: {e}")
100
-
101
- load_dynamic_configs()
102
-
103
- import pyrogram.filters as py_filters
104
-
105
- # Store original user filter
106
- original_user_filter = py_filters.user
107
-
108
- def custom_user_filter(users=None):
109
- if users is ADMINS:
110
- async def func(flt, client, update):
111
- user_id = update.from_user.id if update.from_user else None
112
- if not user_id:
113
- return False
114
- return user_id in ADMINS
115
- return py_filters.create(func)
116
- else:
117
- return original_user_filter(users)
118
-
119
- py_filters.user = custom_user_filter
120
-
121
- # Keep-alive task
122
- async def keep_alive():
123
- while True:
124
- try:
125
- # Execute a simple query to keep the connection alive
126
- with SESSION() as session:
127
- session.execute("SELECT 1")
128
- await asyncio.sleep(180) # Sleep for 3 minutes
129
- except Exception as e:
130
- LOGGER.warning(f"Keep-alive error: {e}")
131
- await asyncio.sleep(10) # Wait before retrying
132
-
133
- # Main function
134
- async def main():
135
- # Start the keep-alive task
136
- asyncio.create_task(keep_alive())
137
- # Your existing bot initialization and running code
138
-
139
- if __name__ == "__main__":
140
- asyncio.run(main())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/__main__.py DELETED
@@ -1,140 +0,0 @@
1
- import pyrogram.utils
2
- pyrogram.utils.MIN_CHANNEL_ID = -1002199999999999
3
- pyrogram.utils.MIN_CHAT_ID = -999999999999999
4
-
5
- import os
6
- import asyncio
7
- import logging
8
- from contextlib import asynccontextmanager
9
- from fastapi import FastAPI
10
- import uvicorn
11
- from pyrogram import Client, __version__
12
- from pyrogram.raw.all import layer
13
- from mfinder import APP_ID, API_HASH, BOT_TOKEN
14
-
15
- import warnings
16
- warnings.filterwarnings("ignore", category=DeprecationWarning)
17
-
18
- # Suppress Uvicorn HTTP access log spam (scanner 404s) and Pyrogram deprecation warnings
19
- logging.getLogger("uvicorn.access").setLevel(logging.WARNING)
20
- logging.getLogger("pyrogram.methods.messages").setLevel(logging.ERROR)
21
- logging.getLogger("pyrogram.dispatcher").setLevel(logging.ERROR)
22
-
23
- try:
24
- import uvloop
25
- uvloop.install()
26
- except ImportError:
27
- pass
28
-
29
- app_client = None
30
- stream_client = None
31
-
32
- @asynccontextmanager
33
- async def lifespan(app: FastAPI):
34
- """
35
- Manages high-concurrency dual Pyrogram client lifecycles:
36
- 1. app_client: Handles 100% of Telegram messages, searches, button callbacks (workers=100)
37
- 2. stream_client: Handles 100% of HTTP direct file downloads (workers=100, in_memory=True)
38
- This guarantees zero lag or delays on bot commands even when 50+ users download simultaneously!
39
- """
40
- global app_client, stream_client
41
- plugins = dict(root="mfinder/plugins")
42
-
43
- # 1. Main Bot Gateway (Messaging & Searching)
44
- app_client = Client(
45
- name="mfinder",
46
- api_id=APP_ID,
47
- api_hash=API_HASH,
48
- bot_token=BOT_TOKEN,
49
- plugins=plugins,
50
- workers=100,
51
- )
52
-
53
- # 2. Direct Stream Gateway (HTTP Downloads)
54
- stream_client = Client(
55
- name="stream_worker",
56
- api_id=APP_ID,
57
- api_hash=API_HASH,
58
- bot_token=BOT_TOKEN,
59
- in_memory=True,
60
- workers=100,
61
- )
62
-
63
- await app_client.start()
64
- await stream_client.start()
65
-
66
- app.state.client = app_client
67
- app.state.stream_client = stream_client
68
-
69
- # Warmup dialogs cache / Inject Log & Force Sub Channel Peer Cache rows
70
- try:
71
- from mfinder.db.settings_sql import get_admin_settings_sync
72
- settings = get_admin_settings_sync()
73
-
74
- # 1. Inject Log Channel Peer
75
- if settings and settings.log_channel and settings.log_channel_access_hash:
76
- peer_id = int(settings.log_channel)
77
- access_hash = int(settings.log_channel_access_hash)
78
- await app_client.storage.update_peers([(peer_id, access_hash, "channel", "", "")])
79
- print("Successfully injected log channel peer into Pyrogram storage cache!")
80
-
81
- # 2. Inject Force Sub Channel Peers
82
- if settings:
83
- import json
84
- hashes = {}
85
- if settings.fsub_channels_access_hashes:
86
- try:
87
- hashes = json.loads(settings.fsub_channels_access_hashes)
88
- except Exception:
89
- pass
90
- # Backwards compatibility: add legacy single fsub channel
91
- if settings.fsub_channel and settings.fsub_channel_access_hash:
92
- hashes[str(int(settings.fsub_channel))] = settings.fsub_channel_access_hash
93
-
94
- for peer_str, hash_val in hashes.items():
95
- if peer_str and hash_val is not None:
96
- try:
97
- peer_id = int(peer_str)
98
- access_hash = int(hash_val)
99
- await app_client.storage.update_peers([(peer_id, access_hash, "channel", "", "")])
100
- print(f"Successfully injected force sub channel peer {peer_id} into Pyrogram storage cache!")
101
- except Exception as peer_err:
102
- print(f"Failed to inject force sub channel peer {peer_str}: {peer_err}")
103
- except Exception as e:
104
- print(f"Log/ForceSub channel peer cache warmup exception: {e}")
105
-
106
- me = await app_client.get_me()
107
- safe_first_name = (me.first_name or "").encode("ascii", errors="ignore").decode("ascii")
108
- if not safe_first_name:
109
- safe_first_name = "Bot"
110
- print(
111
- f"{safe_first_name} - @{me.username} - Pyrogram v{__version__} (Layer {layer}) - Dual-Engine High-Concurrency Server Online!"
112
- )
113
-
114
- yield
115
-
116
- await app_client.stop()
117
- await stream_client.stop()
118
- print(f"{safe_first_name} - @{me.username} - Stopped !!!")
119
-
120
- # Initialize web application with docs disabled
121
- web_app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
122
-
123
- @web_app.get("/")
124
- async def home():
125
- """Simple keep-alive health check endpoint."""
126
- return {"status": "ok", "message": "Bot is running with Dual Engine!"}
127
-
128
- # Include the stream server router for direct downloads
129
- from mfinder.plugins.stream_server import router as stream_router
130
- web_app.include_router(stream_router)
131
-
132
- # Catch-all fallback handler for web scanners seeking .env, config, etc. to eliminate 404 log spam
133
- @web_app.api_route("/{path:path}", methods=["GET", "POST", "HEAD"])
134
- async def catch_all_fallback(path: str):
135
- return {"status": "ok", "message": "Bot is running!"}
136
-
137
- PORT = int(os.environ.get("PORT", 7860))
138
-
139
- if __name__ == "__main__":
140
- uvicorn.run(web_app, host="0.0.0.0", port=PORT, access_log=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/db/analytics_sql.py DELETED
@@ -1,186 +0,0 @@
1
- import datetime
2
- from sqlalchemy import Column, Integer, TEXT, DateTime, inspect, func
3
- from mfinder.db.settings_sql import BASE, SESSION
4
- from mfinder.db.files_sql import Files, clean_movie_title, INSERTION_LOCK, reconnect_session, OperationalError
5
-
6
- class SearchAnalytics(BASE):
7
- __tablename__ = "search_analytics"
8
- query = Column(TEXT, primary_key=True)
9
- search_count = Column(Integer, default=1)
10
- last_searched = Column(DateTime, default=datetime.datetime.utcnow)
11
-
12
- def __init__(self, query):
13
- self.query = query.strip().lower()
14
- self.search_count = 1
15
- self.last_searched = datetime.datetime.utcnow()
16
-
17
- # Ensure table exists in DB automatically on module load
18
- try:
19
- session = SESSION()
20
- bind = session.get_bind()
21
- inspector = inspect(bind)
22
- if not inspector.has_table("search_analytics"):
23
- SearchAnalytics.__table__.create(bind=bind, checkfirst=True)
24
- except Exception as _e:
25
- pass
26
-
27
- async def log_search_query(query_text: str):
28
- """Logs or increments search query count in analytics database."""
29
- if not query_text or len(query_text.strip()) < 2:
30
- return
31
-
32
- clean_q = query_text.strip().lower()
33
- session = SESSION()
34
- try:
35
- record = session.query(SearchAnalytics).filter_by(query=clean_q).first()
36
- if record:
37
- record.search_count += 1
38
- record.last_searched = datetime.datetime.utcnow()
39
- else:
40
- record = SearchAnalytics(query=clean_q)
41
- session.add(record)
42
- session.commit()
43
- except Exception as e:
44
- session.rollback()
45
- finally:
46
- try:
47
- SESSION.close()
48
- except Exception:
49
- pass
50
-
51
- async def cleanup_old_search_analytics():
52
- """Deletes search records older than 7 days to maintain a clean weekly trending cycle."""
53
- session = SESSION()
54
- try:
55
- one_week_ago = datetime.datetime.utcnow() - datetime.timedelta(days=7)
56
- session.query(SearchAnalytics).filter(SearchAnalytics.last_searched < one_week_ago).delete()
57
- session.commit()
58
- except Exception:
59
- session.rollback()
60
- finally:
61
- try:
62
- SESSION.close()
63
- except Exception:
64
- pass
65
-
66
- async def get_latest_uploaded_movies(limit: int = 25) -> list:
67
- """
68
- Retrieves the latest distinct uploaded movies from the database files table,
69
- sorted by newest created_at timestamp first.
70
- Returns list of tuples: (cleaned_title, file_count)
71
- """
72
- retries = 3
73
- while retries > 0:
74
- try:
75
- with INSERTION_LOCK:
76
- files = (
77
- SESSION.query(Files.file_name)
78
- .order_by(Files.created_at.desc(), Files.file_name.asc())
79
- .limit(300)
80
- .all()
81
- )
82
-
83
- movie_counts = {}
84
- movie_years = {}
85
- for (f_name,) in files:
86
- title = clean_movie_title(f_name)
87
- if title and len(title) >= 2:
88
- movie_counts[title] = movie_counts.get(title, 0) + 1
89
- if title not in movie_years:
90
- import re
91
- year_match = re.search(r'\b(19\d{2}|20[0-2]\d|2030)\b', f_name)
92
- if year_match:
93
- movie_years[title] = year_match.group(1)
94
-
95
- latest_list = []
96
- for title, count in movie_counts.items():
97
- year = movie_years.get(title)
98
- latest_list.append((title, count, year))
99
- if len(latest_list) >= limit:
100
- break
101
-
102
- return latest_list
103
- except OperationalError:
104
- reconnect_session()
105
- retries -= 1
106
- except Exception as e:
107
- retries -= 1
108
- finally:
109
- try:
110
- SESSION.close()
111
- except Exception:
112
- pass
113
- return []
114
-
115
- async def get_top_trending_movies(limit: int = 10) -> list:
116
- """
117
- Retrieves top searched queries from the 7-day weekly cycle in search_analytics.
118
- Returns list of tuples: (movie_title, file_count)
119
- """
120
- # Trigger weekly cleanup of old search records
121
- await cleanup_old_search_analytics()
122
-
123
- retries = 3
124
- while retries > 0:
125
- try:
126
- with INSERTION_LOCK:
127
- one_week_ago = datetime.datetime.utcnow() - datetime.timedelta(days=7)
128
- top_records = (
129
- SESSION.query(SearchAnalytics)
130
- .filter(SearchAnalytics.last_searched >= one_week_ago)
131
- .order_by(SearchAnalytics.search_count.desc(), SearchAnalytics.last_searched.desc())
132
- .limit(50)
133
- .all()
134
- )
135
-
136
- if not top_records:
137
- return []
138
-
139
- trending_movies = []
140
- seen_titles = set()
141
-
142
- for rec in top_records:
143
- q = rec.query
144
- files = (
145
- SESSION.query(Files.file_name)
146
- .filter(Files.file_name.ilike(f"%{q}%"))
147
- .limit(50)
148
- .all()
149
- )
150
-
151
- if files:
152
- for (f_name,) in files:
153
- title = clean_movie_title(f_name)
154
- if title and len(title) >= 2:
155
- t_key = title.lower()
156
- if t_key not in seen_titles:
157
- seen_titles.add(t_key)
158
- count = SESSION.query(Files).filter(Files.file_name.ilike(f"%{title}%")).count()
159
-
160
- # Extract year from matched files
161
- import re
162
- year = None
163
- for (fn,) in files:
164
- year_match = re.search(r'\b(19\d{2}|20[0-2]\d|2030)\b', fn)
165
- if year_match:
166
- year = year_match.group(1)
167
- break
168
-
169
- trending_movies.append((title, count if count > 0 else len(files), year))
170
- if len(trending_movies) >= limit:
171
- break
172
- if len(trending_movies) >= limit:
173
- break
174
-
175
- return trending_movies
176
- except OperationalError:
177
- reconnect_session()
178
- retries -= 1
179
- except Exception:
180
- retries -= 1
181
- finally:
182
- try:
183
- SESSION.close()
184
- except Exception:
185
- pass
186
- return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/db/ban_sql.py DELETED
@@ -1,106 +0,0 @@
1
- import threading
2
- from sqlalchemy import create_engine, Column, BigInteger
3
- from sqlalchemy.ext.declarative import declarative_base
4
- from sqlalchemy.orm import sessionmaker, scoped_session
5
- from sqlalchemy.orm.exc import NoResultFound
6
- from sqlalchemy.pool import QueuePool
7
- from mfinder import DB_URL
8
- import time
9
- import sqlalchemy
10
-
11
- BASE = declarative_base()
12
-
13
- class BanList(BASE):
14
- __tablename__ = "banlist"
15
- user_id = Column(BigInteger, primary_key=True)
16
-
17
- def __init__(self, user_id):
18
- self.user_id = user_id
19
-
20
- def start() -> scoped_session:
21
- connect_args = {}
22
- if DB_URL and DB_URL.startswith(("postgres://", "postgresql://")):
23
- connect_args["sslmode"] = "require"
24
- engine = create_engine(
25
- DB_URL,
26
- connect_args=connect_args,
27
- poolclass=QueuePool,
28
- pool_size=10,
29
- max_overflow=20,
30
- pool_pre_ping=True,
31
- pool_recycle=1800 # Recycle connections every 1800 seconds (30 minutes)
32
- )
33
- BASE.metadata.bind = engine
34
- BASE.metadata.create_all(engine)
35
- return scoped_session(sessionmaker(bind=engine, autoflush=False))
36
-
37
- SESSION = start()
38
- INSERTION_LOCK = threading.RLock()
39
-
40
- async def ban_user(user_id):
41
- with INSERTION_LOCK:
42
- try:
43
- usr = SESSION.query(BanList).filter_by(user_id=user_id).one()
44
- except NoResultFound:
45
- usr = BanList(user_id=user_id)
46
- SESSION.add(usr)
47
- SESSION.commit()
48
- return True
49
- except sqlalchemy.exc.OperationalError as e:
50
- SESSION.rollback()
51
- raise e
52
- finally:
53
- SESSION.close()
54
-
55
- async def is_banned(user_id, retries=3):
56
- with INSERTION_LOCK:
57
- for attempt in range(retries):
58
- try:
59
- usr = SESSION.query(BanList).filter_by(user_id=user_id).one()
60
- return usr.user_id
61
- except NoResultFound:
62
- return False
63
- except sqlalchemy.exc.OperationalError as e:
64
- try:
65
- SESSION.rollback()
66
- except Exception:
67
- pass
68
- try:
69
- SESSION.remove()
70
- except Exception:
71
- pass
72
- if 'SSL connection has been closed unexpectedly' in str(e):
73
- if attempt < retries - 1:
74
- time.sleep(2) # wait before retrying
75
- continue
76
- raise e
77
- except sqlalchemy.exc.PendingRollbackError:
78
- try:
79
- SESSION.rollback()
80
- except Exception:
81
- pass
82
- try:
83
- SESSION.remove()
84
- except Exception:
85
- pass
86
- if attempt < retries - 1:
87
- time.sleep(2) # wait before retrying
88
- continue
89
- raise
90
- finally:
91
- SESSION.close()
92
-
93
- async def unban_user(user_id):
94
- with INSERTION_LOCK:
95
- try:
96
- usr = SESSION.query(BanList).filter_by(user_id=user_id).one()
97
- SESSION.delete(usr)
98
- SESSION.commit()
99
- return True
100
- except NoResultFound:
101
- return False
102
- except sqlalchemy.exc.OperationalError as e:
103
- SESSION.rollback()
104
- raise e
105
- finally:
106
- SESSION.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/db/broadcast_sql.py DELETED
@@ -1,87 +0,0 @@
1
- import threading
2
- from sqlalchemy import create_engine, Column, TEXT, BigInteger
3
- from sqlalchemy.ext.declarative import declarative_base
4
- from sqlalchemy.orm import sessionmaker, scoped_session
5
- from sqlalchemy.orm.exc import NoResultFound
6
- from sqlalchemy.pool import StaticPool
7
- from mfinder import DB_URL
8
-
9
- BASE = declarative_base()
10
-
11
- class Broadcast(BASE):
12
- __tablename__ = "broadcast"
13
- user_id = Column(BigInteger, primary_key=True)
14
- user_name = Column(TEXT)
15
-
16
- def __init__(self, user_id, user_name):
17
- self.user_id = user_id
18
- self.user_name = user_name
19
-
20
- def start() -> scoped_session:
21
- connect_args = {}
22
- if DB_URL and DB_URL.startswith(("postgres://", "postgresql://")):
23
- connect_args["sslmode"] = "require"
24
- engine = create_engine(
25
- DB_URL,
26
- connect_args=connect_args,
27
- client_encoding="utf8",
28
- poolclass=StaticPool,
29
- pool_pre_ping=True # Added to handle disconnections
30
- )
31
- BASE.metadata.bind = engine
32
- BASE.metadata.create_all(engine)
33
- return scoped_session(sessionmaker(bind=engine, autoflush=False))
34
-
35
- SESSION = start()
36
- INSERTION_LOCK = threading.RLock()
37
-
38
- async def add_user(user_id, user_name):
39
- with INSERTION_LOCK:
40
- try:
41
- usr = SESSION.query(Broadcast).filter_by(user_id=user_id).one()
42
- except NoResultFound:
43
- usr = Broadcast(user_id=user_id, user_name=user_name)
44
- SESSION.add(usr)
45
- SESSION.commit()
46
- except Exception as e:
47
- SESSION.rollback()
48
- raise e
49
- finally:
50
- SESSION.close()
51
-
52
- async def is_user(user_id):
53
- with INSERTION_LOCK:
54
- try:
55
- usr = SESSION.query(Broadcast).filter_by(user_id=user_id).one()
56
- return usr.user_id
57
- except NoResultFound:
58
- return False
59
- except Exception as e:
60
- SESSION.rollback()
61
- raise e
62
- finally:
63
- SESSION.close()
64
-
65
- async def query_msg():
66
- try:
67
- query = SESSION.query(Broadcast.user_id).order_by(Broadcast.user_id)
68
- return query.all()
69
- except Exception as e:
70
- SESSION.rollback()
71
- raise e
72
- finally:
73
- SESSION.close()
74
-
75
- async def del_user(user_id):
76
- with INSERTION_LOCK:
77
- try:
78
- usr = SESSION.query(Broadcast).filter_by(user_id=user_id).one()
79
- SESSION.delete(usr)
80
- SESSION.commit()
81
- except NoResultFound:
82
- pass
83
- except Exception as e:
84
- SESSION.rollback()
85
- raise e
86
- finally:
87
- SESSION.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/db/db_support.py DELETED
@@ -1,28 +0,0 @@
1
- import asyncio
2
- from pyrogram.errors import FloodWait
3
- from pyrogram import enums
4
- from mfinder import LOGGER
5
- from mfinder.db.broadcast_sql import query_msg, del_user
6
-
7
-
8
-
9
- async def users_info(bot):
10
- users = 0
11
- blocked = 0
12
- identity = await query_msg()
13
- for user in identity:
14
- user_id = int(user[0])
15
- name = bool()
16
- try:
17
- name = await bot.send_chat_action(user_id, enums.ChatAction.TYPING)
18
- except FloodWait as e:
19
- await asyncio.sleep(e.value)
20
- except Exception:
21
- pass
22
- if bool(name):
23
- users += 1
24
- else:
25
- await del_user(user_id)
26
- LOGGER.info("Deleted user id %s from broadcast list", user_id)
27
- blocked += 1
28
- return users, blocked
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/db/files_sql.py DELETED
@@ -1,538 +0,0 @@
1
- import threading
2
- import time
3
- import datetime
4
- import re
5
- from sqlalchemy import create_engine, or_, func, and_, text
6
- from sqlalchemy import Column, TEXT, Numeric, DateTime
7
- from sqlalchemy.ext.declarative import declarative_base
8
- from sqlalchemy.orm import sessionmaker, scoped_session
9
- from sqlalchemy.pool import QueuePool
10
- from sqlalchemy.exc import OperationalError, PendingRollbackError, NoResultFound
11
- from mfinder import DB_URL, LOGGER
12
- from mfinder.utils.helpers import unpack_new_file_id
13
- import asyncio
14
-
15
- BASE = declarative_base()
16
-
17
- class Files(BASE):
18
- __tablename__ = "files"
19
- file_name = Column(TEXT, primary_key=True)
20
- file_id = Column(TEXT)
21
- file_ref = Column(TEXT)
22
- file_size = Column(Numeric)
23
- file_type = Column(TEXT)
24
- mime_type = Column(TEXT)
25
- caption = Column(TEXT)
26
- created_at = Column(DateTime, server_default=func.now())
27
-
28
- def __init__(
29
- self, file_name, file_id, file_ref, file_size, file_type, mime_type, caption, created_at=None
30
- ):
31
- self.file_name = file_name
32
- self.file_id = file_id
33
- self.file_ref = file_ref
34
- self.file_size = file_size
35
- self.file_type = file_type
36
- self.mime_type = mime_type
37
- self.caption = caption
38
- self.created_at = created_at or datetime.datetime.utcnow()
39
-
40
- class SearchSuggestionsCache(BASE):
41
- __tablename__ = "search_suggestions_cache"
42
-
43
- original_query = Column(TEXT, primary_key=True)
44
- corrected_query = Column(TEXT, nullable=True)
45
- keywords = Column(TEXT, nullable=True) # Comma separated
46
- suggestions = Column(TEXT, nullable=True) # Comma separated
47
- created_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
48
-
49
- def __init__(self, original_query, corrected_query, keywords, suggestions):
50
- self.original_query = original_query.strip().lower()
51
- self.corrected_query = corrected_query
52
- self.keywords = keywords
53
- self.suggestions = suggestions
54
-
55
- def start() -> scoped_session:
56
- connect_args = {}
57
- if DB_URL and DB_URL.startswith(("postgres://", "postgresql://")):
58
- connect_args["sslmode"] = "require"
59
- engine = create_engine(
60
- DB_URL,
61
- connect_args=connect_args,
62
- poolclass=QueuePool,
63
- pool_size=10,
64
- max_overflow=20,
65
- pool_pre_ping=True,
66
- pool_recycle=1800
67
- )
68
- BASE.metadata.bind = engine
69
- BASE.metadata.create_all(engine)
70
-
71
- # DDL migrations: ensure created_at column on files table and pg_trgm indexes
72
- try:
73
- with engine.connect() as conn:
74
- conn.execute(text("ALTER TABLE files ADD COLUMN IF NOT EXISTS created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP"))
75
- conn.execute(text("CREATE EXTENSION IF NOT EXISTS pg_trgm"))
76
- conn.execute(text("CREATE INDEX IF NOT EXISTS idx_files_file_name_trgm ON files USING gin (file_name gin_trgm_ops)"))
77
- conn.execute(text("CREATE INDEX IF NOT EXISTS idx_files_caption_trgm ON files USING gin (caption gin_trgm_ops)"))
78
- conn.commit()
79
- except Exception as e:
80
- LOGGER.warning(f"Failed to create GIN trigram indexes or extension: {e}")
81
-
82
- return scoped_session(sessionmaker(bind=engine, autoflush=False))
83
-
84
- SESSION = start()
85
- INSERTION_LOCK = threading.RLock()
86
-
87
- import asyncio
88
- import functools
89
- from sqlalchemy.exc import OperationalError, PendingRollbackError
90
-
91
- def db_retry(func):
92
- if asyncio.iscoroutinefunction(func):
93
- @functools.wraps(func)
94
- async def wrapper(*args, **kwargs):
95
- for attempt in range(3):
96
- try:
97
- return await func(*args, **kwargs)
98
- except (OperationalError, PendingRollbackError) as e:
99
- LOGGER.warning("Database connection error in %s (attempt %s): %s. Reconnecting...", func.__name__, attempt + 1, str(e))
100
- try:
101
- SESSION.rollback()
102
- SESSION.remove()
103
- except Exception:
104
- pass
105
- if attempt == 2:
106
- raise
107
- await asyncio.sleep(0.5)
108
- return wrapper
109
- else:
110
- @functools.wraps(func)
111
- def wrapper(*args, **kwargs):
112
- for attempt in range(3):
113
- try:
114
- return func(*args, **kwargs)
115
- except (OperationalError, PendingRollbackError) as e:
116
- LOGGER.warning("Database connection error in %s (attempt %s): %s. Reconnecting...", func.__name__, attempt + 1, str(e))
117
- try:
118
- SESSION.rollback()
119
- SESSION.remove()
120
- except Exception:
121
- pass
122
- if attempt == 2:
123
- raise
124
- import time
125
- time.sleep(0.5)
126
- return wrapper
127
-
128
- def reconnect_session(max_retries=5, delay=5):
129
- """Attempt to reconnect to the database a specified number of times with a delay."""
130
- for attempt in range(max_retries):
131
- try:
132
- global SESSION
133
- SESSION = start()
134
- return SESSION
135
- except OperationalError as e:
136
- LOGGER.warning(f"Database connection failed: {e}. Retrying in {delay} seconds...")
137
- time.sleep(delay)
138
- raise Exception("Failed to reconnect to the database after multiple attempts")
139
-
140
- @db_retry
141
- async def save_file(media):
142
- """Save a media file to the database."""
143
- file_id, file_ref = unpack_new_file_id(media.file_id)
144
- with INSERTION_LOCK:
145
- try:
146
- # Check if file with same file_id exists
147
- file = SESSION.query(Files).filter_by(file_id=file_id).one()
148
- LOGGER.warning("%s is already saved in the database", media.file_name)
149
- except NoResultFound:
150
- try:
151
- # Check if file with same file_name and file_size exists
152
- file = SESSION.query(Files).filter_by(file_name=media.file_name, file_size=media.file_size).one()
153
- LOGGER.warning("%s with size %s is already saved in the database", media.file_name, media.file_size)
154
- except NoResultFound:
155
- # Create a new file record
156
- file = Files(
157
- file_name=media.caption if media.caption else media.file_name,
158
- file_id=file_id,
159
- file_ref=file_ref,
160
- file_size=media.file_size,
161
- file_type=media.file_type,
162
- mime_type=media.mime_type,
163
- caption=media.caption if media.caption else media.file_name,
164
- )
165
- LOGGER.info("%s is saved in the database", media.file_name)
166
- SESSION.add(file)
167
- SESSION.commit()
168
- return True
169
- except Exception as e:
170
- LOGGER.warning("Error occurred while saving file in the database: %s", str(e))
171
- SESSION.rollback()
172
- return False
173
- except Exception as e:
174
- LOGGER.warning("Error occurred while saving file in the database: %s", str(e))
175
- SESSION.rollback()
176
- return False
177
- finally:
178
- try:
179
- SESSION.close()
180
- except Exception as close_error:
181
- LOGGER.error(f"Error closing session: {close_error}")
182
-
183
- async def get_filter_results(query, page=1, per_page=10):
184
- """Get filtered results from the database."""
185
- retries = 3
186
- while retries > 0:
187
- try:
188
- with INSERTION_LOCK:
189
- offset = (page - 1) * per_page
190
- search = query.split()
191
- conditions = []
192
- for word in search:
193
- conditions.append(
194
- or_(
195
- Files.file_name.ilike(f"%{word}%"),
196
- Files.caption.ilike(f"%{word}%"),
197
- )
198
- )
199
- combined_condition = and_(*conditions)
200
- files_query = (
201
- SESSION.query(Files)
202
- .filter(combined_condition)
203
- .order_by(Files.file_name)
204
- )
205
- total_count = files_query.count()
206
- files = files_query.offset(offset).limit(per_page).all()
207
- return files, total_count
208
- except PendingRollbackError:
209
- SESSION.rollback()
210
- retries -= 1
211
- continue
212
- except OperationalError as e:
213
- LOGGER.warning(f"OperationalError: {e}. Retrying...")
214
- reconnect_session()
215
- retries -= 1
216
- except Exception as e:
217
- LOGGER.warning(f"Error occurred while retrieving filter results: {e}")
218
- return [], 0
219
- finally:
220
- try:
221
- SESSION.close()
222
- except Exception as close_error:
223
- LOGGER.error(f"Error closing session: {close_error}")
224
- return [], 0
225
-
226
- async def get_precise_filter_results(query, page=1, per_page=10):
227
- """Get precise filtered results from the database."""
228
- retries = 3
229
- while retries > 0:
230
- try:
231
- with INSERTION_LOCK:
232
- offset = (page - 1) * per_page
233
- search = query.split()
234
- conditions = []
235
- for word in search:
236
- conditions.append(
237
- or_(
238
- func.concat(" ", Files.file_name, " ").ilike(f"% {word} %"),
239
- func.concat(" ", Files.caption, " ").ilike(f"% {word} %"),
240
- )
241
- )
242
- combined_condition = and_(*conditions)
243
- files_query = (
244
- SESSION.query(Files)
245
- .filter(combined_condition)
246
- .order_by(Files.file_name)
247
- )
248
- total_count = files_query.count()
249
- files = files_query.offset(offset).limit(per_page).all()
250
- return files, total_count
251
- except PendingRollbackError:
252
- SESSION.rollback()
253
- retries -= 1
254
- continue
255
- except OperationalError as e:
256
- LOGGER.warning(f"OperationalError: {e}. Retrying...")
257
- reconnect_session()
258
- retries -= 1
259
- except Exception as e:
260
- LOGGER.warning(f"Error occurred while retrieving filter results: {e}")
261
- return [], 0
262
- finally:
263
- try:
264
- SESSION.close()
265
- except Exception as close_error:
266
- LOGGER.error(f"Error closing session: {close_error}")
267
- return [], 0
268
-
269
- GENERIC_KEYWORDS_RE = re.compile(
270
- r'\b(1080p|720p|480p|4k|2k|hdrip|webdl|web-dl|bluray|blu-ray|hdtv|brrip|dvdrip|hevc|x264|x265|h264|h265|aac|dd5\.1|dd\+|ddp5\.1|ddp|dd|dual|multi|esub|esubs|sub|subs|tamil|telugu|hindi|malayalam|kannada|english|bengali|marathi|punjabi|movie|season|s\d+ep\d+|s\d+|ep\d+|combined)\b',
271
- re.IGNORECASE
272
- )
273
-
274
- def clean_movie_title(text: str) -> str:
275
- if not text:
276
- return ""
277
- # Strip channel tag
278
- title = text.replace("@FIREBOLTOFFICIAL", "")
279
- # Split at common delimiters like (, [, -, year
280
- title = re.split(r'\(\d{4}\)', title)[0]
281
- title = title.split('[')[0]
282
- # Remove generic keywords
283
- title = GENERIC_KEYWORDS_RE.sub('', title)
284
- title = re.sub(r'^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$', '', title)
285
- title = re.sub(r'\s+', ' ', title).strip()
286
- return title
287
-
288
- async def get_trigram_filter_results(query, page=1, per_page=10, threshold=0.3):
289
- """Get fuzzy filtered results from the database using trigram similarity and re-ranked in Python."""
290
- import difflib
291
-
292
- retries = 3
293
- while retries > 0:
294
- try:
295
- with INSERTION_LOCK:
296
- offset = (page - 1) * per_page
297
- # Set dynamic trigram word similarity threshold for matching
298
- SESSION.execute(text(f"SET LOCAL pg_trgm.word_similarity_threshold = {threshold}"))
299
-
300
- # Fetch up to 100 candidate fuzzy matches to re-rank
301
- sql_query = text("""
302
- SELECT file_name, file_id, file_ref, file_size, file_type, mime_type, caption
303
- FROM files
304
- WHERE file_name %> :query OR caption %> :query
305
- LIMIT 100
306
- """)
307
-
308
- params = {"query": query}
309
- result = SESSION.execute(sql_query, params).fetchall()
310
-
311
- # Clean the query
312
- q_clean = clean_movie_title(query).lower()
313
- if not q_clean:
314
- q_clean = query.lower()
315
-
316
- candidates = []
317
- for row in result:
318
- title_name = clean_movie_title(row.file_name)
319
- ratio_name = difflib.SequenceMatcher(None, q_clean, title_name.lower()).ratio()
320
-
321
- ratio_caption = 0.0
322
- if row.caption:
323
- title_caption = clean_movie_title(row.caption)
324
- ratio_caption = difflib.SequenceMatcher(None, q_clean, title_caption.lower()).ratio()
325
-
326
- best_ratio = max(ratio_name, ratio_caption)
327
- candidates.append((row, best_ratio))
328
-
329
- # Re-rank candidates by ratio descending, then file_name
330
- candidates.sort(key=lambda x: (-x[1], x[0].file_name))
331
-
332
- total_count = len(candidates)
333
- sliced_candidates = candidates[offset : offset + per_page]
334
-
335
- files = []
336
- for row, ratio in sliced_candidates:
337
- files.append(Files(
338
- file_name=row.file_name,
339
- file_id=row.file_id,
340
- file_ref=row.file_ref,
341
- file_size=row.file_size,
342
- file_type=row.file_type,
343
- mime_type=row.mime_type,
344
- caption=row.caption
345
- ))
346
- return files, total_count
347
- except PendingRollbackError:
348
- SESSION.rollback()
349
- retries -= 1
350
- continue
351
- except OperationalError as e:
352
- LOGGER.warning(f"OperationalError: {e}. Retrying...")
353
- reconnect_session()
354
- retries -= 1
355
- except Exception as e:
356
- LOGGER.warning(f"Error occurred while retrieving trigram results: {e}")
357
- return [], 0
358
- finally:
359
- try:
360
- SESSION.close()
361
- except Exception as close_error:
362
- LOGGER.error(f"Error closing session: {close_error}")
363
- return [], 0
364
-
365
- async def get_file_details(file_id):
366
- """Get file details based on file_id."""
367
- retries = 3
368
- while retries > 0:
369
- try:
370
- with INSERTION_LOCK:
371
- file_details = SESSION.query(Files).filter_by(file_id=file_id).all()
372
- return file_details
373
- except PendingRollbackError:
374
- SESSION.rollback()
375
- retries -= 1
376
- continue
377
- except OperationalError as e:
378
- LOGGER.warning(f"OperationalError: {e}. Retrying...")
379
- reconnect_session()
380
- retries -= 1
381
- except Exception as e:
382
- LOGGER.warning(f"Error occurred while retrieving file details: {e}")
383
- return []
384
- finally:
385
- try:
386
- SESSION.close()
387
- except Exception as close_error:
388
- LOGGER.error(f"Error closing session: {close_error}")
389
- return []
390
-
391
- async def delete_file(media):
392
- """Delete a file record from the database."""
393
- file_id, file_ref = unpack_new_file_id(media.file_id)
394
- retries = 3
395
- while retries > 0:
396
- try:
397
- with INSERTION_LOCK:
398
- file = SESSION.query(Files).filter_by(file_id=file_id).first()
399
- if file:
400
- SESSION.delete(file)
401
- SESSION.commit()
402
- return True
403
- return "Not Found"
404
- LOGGER.warning("File to delete not found: %s", str(file_id))
405
- except PendingRollbackError:
406
- SESSION.rollback()
407
- retries -= 1
408
- continue
409
- except OperationalError as e:
410
- LOGGER.warning(f"OperationalError: {e}. Retrying...")
411
- reconnect_session()
412
- retries -= 1
413
- except Exception as e:
414
- LOGGER.warning(f"Error occurred while deleting file: {e}")
415
- SESSION.rollback()
416
- return False
417
- finally:
418
- try:
419
- SESSION.close()
420
- except Exception as close_error:
421
- LOGGER.error(f"Error closing session: {close_error}")
422
- return False
423
-
424
- @db_retry
425
- async def get_keyword_db_suggestions(query: str, limit: int = 30) -> list:
426
- """
427
- Extracts significant keywords (actor names, franchise words) from query
428
- and finds matching unique movie titles directly from uploaded files in DB.
429
- """
430
- import re
431
- STOP_WORDS = {
432
- 'new', 'movie', 'movies', 'tamil', 'telugu', 'hindi', 'malayalam', 'kannada',
433
- 'english', 'full', 'download', 'hd', 'mp4', 'mkv', '1080p', '720p', '480p',
434
- 'best', 'latest', 'film', 'films', 'cinema', '2023', '2024', '2025', '2026',
435
- 'part', 'all', 'series', 'collection', 'link', 'file', 'files', 'video'
436
- }
437
-
438
- GENERIC_RE = re.compile(
439
- r'\b(1080p|720p|480p|4k|2k|hdrip|webdl|web-dl|bluray|blu-ray|hdtv|brrip|dvdrip|hevc|x264|x265|h264|h265|aac|dd5\.1|dd\+|ddp5\.1|ddp|dd|dual|multi|esub|esubs|sub|subs|tamil|telugu|hindi|malayalam|kannada|english|bengali|marathi|punjabi|movie|season|s\d+ep\d+|s\d+|ep\d+|combined)\b',
440
- re.IGNORECASE
441
- )
442
-
443
- def _extract_clean_title(text: str) -> str:
444
- if not text:
445
- return ""
446
- t = text.replace("@FIREBOLTOFFICIAL", "")
447
- t = re.split(r'\(\d{4}\)', t)[0]
448
- t = t.split('[')[0]
449
- t = GENERIC_RE.sub('', t)
450
- t = re.sub(r'^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$', '', t)
451
- t = re.sub(r'\s+', ' ', t).strip()
452
- return t
453
-
454
- words = [w.strip().lower() for w in re.findall(r'\b\w+\b', query) if len(w) >= 3]
455
- keywords = [w for w in words if w not in STOP_WORDS]
456
-
457
- if not keywords:
458
- return []
459
-
460
- retries = 3
461
- while retries > 0:
462
- try:
463
- with INSERTION_LOCK:
464
- conditions = [Files.file_name.ilike(f"%{kw}%") for kw in keywords]
465
- files = (
466
- SESSION.query(Files.file_name)
467
- .filter(or_(*conditions))
468
- .order_by(Files.file_name.desc())
469
- .limit(150)
470
- .all()
471
- )
472
-
473
- extracted_titles = []
474
- seen = set()
475
- for (f_name,) in files:
476
- title = _extract_clean_title(f_name)
477
- if title and len(title) >= 2:
478
- t_key = title.lower()
479
- if t_key not in seen:
480
- seen.add(t_key)
481
- extracted_titles.append(title)
482
- if len(extracted_titles) >= limit:
483
- break
484
-
485
- return extracted_titles
486
- except Exception as e:
487
- LOGGER.warning(f"Error extracting DB keyword suggestions: {e}")
488
- retries -= 1
489
- await asyncio.sleep(0.2)
490
- finally:
491
- try:
492
- SESSION.close()
493
- except Exception:
494
- pass
495
- return []
496
-
497
- async def count_files():
498
- """Count the total number of files in the database."""
499
- retries = 3
500
- while retries > 0:
501
- try:
502
- with INSERTION_LOCK:
503
- total_count = SESSION.query(Files).count()
504
- return total_count
505
- except PendingRollbackError:
506
- SESSION.rollback()
507
- retries -= 1
508
- continue
509
- except OperationalError as e:
510
- LOGGER.warning(f"OperationalError: {e}. Retrying...")
511
- reconnect_session()
512
- retries -= 1
513
- except Exception as e:
514
- LOGGER.warning(f"Error occurred while counting files: {e}")
515
- return 0
516
- finally:
517
- try:
518
- SESSION.close()
519
- except Exception as close_error:
520
- LOGGER.error(f"Error closing session: {close_error}")
521
- return 0
522
-
523
- async def keep_alive():
524
- """Keep the database connection alive."""
525
- while True:
526
- try:
527
- with SESSION() as session:
528
- session.execute("SELECT 1")
529
- await asyncio.sleep(180)
530
- except Exception as e:
531
- LOGGER.warning(f"Keep-alive error: {e}")
532
- await asyncio.sleep(10)
533
-
534
- async def main():
535
- asyncio.create_task(keep_alive())
536
-
537
- if __name__ == "__main__":
538
- asyncio.run(main())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/db/filters_sql.py DELETED
@@ -1,148 +0,0 @@
1
- import threading
2
- import time
3
- from sqlalchemy import create_engine, Column, TEXT
4
- from sqlalchemy.ext.declarative import declarative_base
5
- from sqlalchemy.orm import sessionmaker, scoped_session
6
- from sqlalchemy.orm.exc import NoResultFound
7
- from sqlalchemy.pool import QueuePool
8
- from sqlalchemy.exc import OperationalError, PendingRollbackError
9
- from mfinder import DB_URL
10
-
11
- BASE = declarative_base()
12
-
13
- class Filters(BASE):
14
- __tablename__ = "filters"
15
- filters = Column(TEXT, primary_key=True)
16
- message = Column(TEXT)
17
-
18
- def __init__(self, filters, message):
19
- self.filters = filters
20
- self.message = message
21
-
22
- def start() -> scoped_session:
23
- connect_args = {}
24
- if DB_URL and DB_URL.startswith(("postgres://", "postgresql://")):
25
- connect_args["sslmode"] = "require"
26
- engine = create_engine(
27
- DB_URL,
28
- connect_args=connect_args,
29
- poolclass=QueuePool,
30
- pool_size=10,
31
- max_overflow=20,
32
- pool_pre_ping=True,
33
- pool_recycle=1800 # Recycle connections every 1800 seconds (30 minutes)
34
- )
35
- BASE.metadata.bind = engine
36
- BASE.metadata.create_all(engine)
37
- return scoped_session(sessionmaker(bind=engine, autoflush=False))
38
-
39
- SESSION = start()
40
- INSERTION_LOCK = threading.RLock()
41
-
42
- def reconnect_session():
43
- global SESSION
44
- SESSION.close()
45
- SESSION = start()
46
-
47
- async def add_filter(filters, message):
48
- with INSERTION_LOCK:
49
- try:
50
- fltr = SESSION.query(Filters).filter(Filters.filters.ilike(filters)).one()
51
- except NoResultFound:
52
- fltr = Filters(filters=filters, message=message)
53
- SESSION.add(fltr)
54
- SESSION.commit()
55
- return True
56
-
57
- async def is_filter(filters):
58
- retries = 3
59
- while retries > 0:
60
- with INSERTION_LOCK:
61
- try:
62
- fltr = SESSION.query(Filters).filter(Filters.filters.ilike(filters)).one()
63
- return fltr
64
- except NoResultFound:
65
- return False
66
- except OperationalError as e:
67
- try:
68
- SESSION.rollback()
69
- except Exception:
70
- pass
71
- try:
72
- SESSION.remove()
73
- except Exception:
74
- pass
75
- if 'SSL connection has been closed unexpectedly' in str(e):
76
- if retries > 1:
77
- time.sleep(2) # wait before retrying
78
- reconnect_session()
79
- retries -= 1
80
- continue
81
- raise e
82
- except PendingRollbackError:
83
- try:
84
- SESSION.rollback()
85
- except Exception:
86
- pass
87
- try:
88
- SESSION.remove()
89
- except Exception:
90
- pass
91
- if retries > 1:
92
- time.sleep(2) # wait before retrying
93
- retries -= 1
94
- continue
95
- raise
96
- finally:
97
- SESSION.close()
98
-
99
- async def rem_filter(filters):
100
- with INSERTION_LOCK:
101
- try:
102
- fltr = SESSION.query(Filters).filter(Filters.filters.ilike(filters)).one()
103
- SESSION.delete(fltr)
104
- SESSION.commit()
105
- return True
106
- except NoResultFound:
107
- return False
108
-
109
- async def list_filters():
110
- retries = 3
111
- while retries > 0:
112
- try:
113
- fltrs = SESSION.query(Filters.filters).all()
114
- return [fltr[0] for fltr in fltrs]
115
- except NoResultFound:
116
- return False
117
- except OperationalError as e:
118
- try:
119
- SESSION.rollback()
120
- except Exception:
121
- pass
122
- try:
123
- SESSION.remove()
124
- except Exception:
125
- pass
126
- if 'SSL connection has been closed unexpectedly' in str(e):
127
- if retries > 1:
128
- time.sleep(2) # wait before retrying
129
- reconnect_session()
130
- retries -= 1
131
- continue
132
- raise e
133
- except PendingRollbackError:
134
- try:
135
- SESSION.rollback()
136
- except Exception:
137
- pass
138
- try:
139
- SESSION.remove()
140
- except Exception:
141
- pass
142
- if retries > 1:
143
- time.sleep(2) # wait before retrying
144
- retries -= 1
145
- continue
146
- raise
147
- finally:
148
- SESSION.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/db/requests_sql.py DELETED
@@ -1,146 +0,0 @@
1
- import datetime
2
- import asyncio
3
- from sqlalchemy import Column, Integer, BigInteger, TEXT, DateTime, inspect
4
- from sqlalchemy.exc import OperationalError, PendingRollbackError
5
- from mfinder.db.settings_sql import BASE, SESSION
6
-
7
- class MovieRequest(BASE):
8
- __tablename__ = "movie_requests"
9
- id = Column(Integer, primary_key=True, autoincrement=True)
10
- user_id = Column(BigInteger, nullable=False)
11
- user_name = Column(TEXT, nullable=True)
12
- query = Column(TEXT, nullable=False)
13
- status = Column(TEXT, default="Pending") # Pending, Uploaded, Rejected
14
- channel_msg_id = Column(Integer, nullable=True)
15
- created_at = Column(DateTime, default=datetime.datetime.utcnow)
16
-
17
- def __init__(self, user_id, user_name, query, status="Pending", channel_msg_id=None):
18
- self.user_id = user_id
19
- self.user_name = user_name
20
- self.query = query
21
- self.status = status
22
- self.channel_msg_id = channel_msg_id
23
- self.created_at = datetime.datetime.utcnow()
24
-
25
- # Ensure table exists in DB automatically on module load
26
- try:
27
- session = SESSION()
28
- bind = session.get_bind()
29
- inspector = inspect(bind)
30
- if not inspector.has_table("movie_requests"):
31
- MovieRequest.__table__.create(bind=bind, checkfirst=True)
32
- except Exception as _e:
33
- pass
34
-
35
- async def add_movie_request(user_id: int, user_name: str, query: str) -> MovieRequest:
36
- """Adds a new movie request to the database."""
37
- session = SESSION()
38
- try:
39
- req = MovieRequest(user_id=user_id, user_name=user_name, query=query)
40
- session.add(req)
41
- session.commit()
42
- session.refresh(req)
43
- return req
44
- except Exception as e:
45
- try:
46
- session.rollback()
47
- except Exception:
48
- pass
49
- try:
50
- SESSION.remove()
51
- except Exception:
52
- pass
53
- raise e
54
- finally:
55
- session.close()
56
-
57
- async def update_request_status(req_id: int, status: str, channel_msg_id: int = None) -> MovieRequest:
58
- """Updates the status and optional channel message ID of a movie request."""
59
- session = SESSION()
60
- try:
61
- req = session.query(MovieRequest).filter_by(id=req_id).first()
62
- if req:
63
- req.status = status
64
- if channel_msg_id is not None:
65
- req.channel_msg_id = channel_msg_id
66
- session.commit()
67
- session.refresh(req)
68
- return req
69
- except Exception as e:
70
- try:
71
- session.rollback()
72
- except Exception:
73
- pass
74
- try:
75
- SESSION.remove()
76
- except Exception:
77
- pass
78
- raise e
79
- finally:
80
- session.close()
81
-
82
- async def get_movie_request(req_id: int) -> MovieRequest:
83
- """Retrieves a movie request by ID."""
84
- for attempt in range(3):
85
- try:
86
- session = SESSION()
87
- return session.query(MovieRequest).filter_by(id=req_id).first()
88
- except (OperationalError, PendingRollbackError) as e:
89
- from mfinder import LOGGER
90
- LOGGER.warning("Database connection error in get_movie_request (attempt %d): %s. Reconnecting...", attempt + 1, str(e))
91
- try:
92
- SESSION.rollback()
93
- except Exception:
94
- pass
95
- try:
96
- SESSION.remove()
97
- except Exception:
98
- pass
99
- if attempt == 2:
100
- return None
101
- await asyncio.sleep(0.5)
102
- except Exception as e:
103
- try:
104
- SESSION.rollback()
105
- except Exception:
106
- pass
107
- try:
108
- SESSION.remove()
109
- except Exception:
110
- pass
111
- return None
112
- finally:
113
- SESSION.close()
114
-
115
- async def get_pending_requests_count() -> int:
116
- """Returns total pending request count."""
117
- for attempt in range(3):
118
- try:
119
- session = SESSION()
120
- return session.query(MovieRequest).filter_by(status="Pending").count()
121
- except (OperationalError, PendingRollbackError) as e:
122
- from mfinder import LOGGER
123
- LOGGER.warning("Database connection error in get_pending_requests_count (attempt %d): %s. Reconnecting...", attempt + 1, str(e))
124
- try:
125
- SESSION.rollback()
126
- except Exception:
127
- pass
128
- try:
129
- SESSION.remove()
130
- except Exception:
131
- pass
132
- if attempt == 2:
133
- return 0
134
- await asyncio.sleep(0.5)
135
- except Exception as e:
136
- try:
137
- SESSION.rollback()
138
- except Exception:
139
- pass
140
- try:
141
- SESSION.remove()
142
- except Exception:
143
- pass
144
- return 0
145
- finally:
146
- SESSION.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/db/settings_sql.py DELETED
@@ -1,1225 +0,0 @@
1
- import threading
2
- from sqlalchemy import create_engine, Column, TEXT, Boolean, Numeric, BigInteger
3
- from sqlalchemy.ext.declarative import declarative_base
4
- from sqlalchemy.orm import sessionmaker, scoped_session
5
- from sqlalchemy.pool import QueuePool
6
- from sqlalchemy.orm.exc import NoResultFound
7
- from mfinder import DB_URL, LOGGER
8
-
9
- BASE = declarative_base()
10
-
11
- class AdminSettings(BASE):
12
- __tablename__ = "admin_settings"
13
- setting_name = Column(TEXT, primary_key=True)
14
- auto_delete = Column(Numeric)
15
- custom_caption = Column(TEXT)
16
- fsub_channel = Column(Numeric)
17
- channel_link = Column(TEXT)
18
- caption_uname = Column(TEXT)
19
- repair_mode = Column(Boolean)
20
- shortener_site = Column(TEXT)
21
- shortener_api = Column(TEXT)
22
- shortener_status = Column(Boolean)
23
- admins_list = Column(TEXT)
24
- db_channels_list = Column(TEXT)
25
- token_shortener_enabled = Column(Boolean)
26
- token_timeout = Column(Numeric)
27
- log_channel = Column(Numeric)
28
- how_to_download = Column(TEXT)
29
- log_channel_access_hash = Column(Numeric)
30
- fsub_channel_access_hash = Column(Numeric)
31
- fsub_channels_list = Column(TEXT)
32
- fsub_channels_access_hashes = Column(TEXT)
33
-
34
- def __init__(self, setting_name="default"):
35
- self.setting_name = setting_name
36
- self.auto_delete = 0
37
- self.custom_caption = None
38
- self.fsub_channel = None
39
- self.channel_link = None
40
- self.caption_uname = None
41
- self.repair_mode = False
42
- self.shortener_site = None
43
- self.shortener_api = None
44
- self.shortener_status = True
45
- self.admins_list = None
46
- self.db_channels_list = None
47
- self.token_shortener_enabled = False
48
- self.token_timeout = 3600
49
- self.log_channel = None
50
- self.how_to_download = None
51
- self.log_channel_access_hash = None
52
- self.fsub_channel_access_hash = None
53
- self.fsub_channels_list = None
54
- self.fsub_channels_access_hashes = "{}"
55
-
56
- class PendingFsubRequests(BASE):
57
- __tablename__ = "pending_fsub_requests"
58
- user_id = Column(Numeric, primary_key=True)
59
- search_query = Column(TEXT)
60
- target_file_id = Column(TEXT)
61
- created_at = Column(Numeric)
62
-
63
- def __init__(self, user_id, search_query=None, target_file_id=None):
64
- self.user_id = user_id
65
- self.search_query = search_query
66
- self.target_file_id = target_file_id
67
- import time
68
- self.created_at = time.time()
69
-
70
- class Settings(BASE):
71
- __tablename__ = "settings"
72
- user_id = Column(BigInteger, primary_key=True)
73
- precise_mode = Column(Boolean)
74
- button_mode = Column(Boolean)
75
- link_mode = Column(Boolean)
76
- list_mode = Column(Boolean)
77
-
78
- def __init__(self, user_id, precise_mode, button_mode, link_mode, list_mode):
79
- self.user_id = user_id
80
- self.precise_mode = precise_mode
81
- self.button_mode = button_mode
82
- self.link_mode = link_mode
83
- self.list_mode = list_mode
84
-
85
- class UserTokens(BASE):
86
- __tablename__ = "user_tokens"
87
- user_id = Column(BigInteger, primary_key=True)
88
- token = Column(TEXT)
89
- created_at = Column(Numeric)
90
- expires_at = Column(Numeric)
91
- status = Column(TEXT)
92
- search_query = Column(TEXT)
93
- target_file_id = Column(TEXT)
94
- req_msg_id = Column(Numeric, nullable=True)
95
-
96
- def __init__(self, user_id, token, created_at, expires_at=0, status="pending", search_query=None, target_file_id=None, req_msg_id=None):
97
- self.user_id = user_id
98
- self.token = token
99
- self.created_at = created_at
100
- self.expires_at = expires_at
101
- self.status = status
102
- self.search_query = search_query
103
- self.target_file_id = target_file_id
104
- self.req_msg_id = req_msg_id
105
-
106
- def start() -> scoped_session:
107
- connect_args = {}
108
- if DB_URL and DB_URL.startswith(("postgres://", "postgresql://")):
109
- connect_args["sslmode"] = "require"
110
- engine = create_engine(
111
- DB_URL,
112
- connect_args=connect_args,
113
- poolclass=QueuePool,
114
- pool_size=10,
115
- max_overflow=20,
116
- pool_pre_ping=True,
117
- pool_recycle=1800 # Recycle connections every 1800 seconds (30 minutes)
118
- )
119
- BASE.metadata.bind = engine
120
- BASE.metadata.create_all(engine)
121
-
122
- from sqlalchemy import text
123
- try:
124
- with engine.connect() as conn:
125
- with conn.begin():
126
- conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS shortener_site TEXT"))
127
- conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS shortener_api TEXT"))
128
- conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS shortener_status BOOLEAN DEFAULT TRUE"))
129
- conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS admins_list TEXT"))
130
- conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS db_channels_list TEXT"))
131
- conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS token_shortener_enabled BOOLEAN DEFAULT FALSE"))
132
- conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS token_timeout NUMERIC DEFAULT 3600"))
133
- conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS log_channel NUMERIC"))
134
- conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS how_to_download TEXT"))
135
- conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS log_channel_access_hash NUMERIC"))
136
- conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS fsub_channel_access_hash NUMERIC"))
137
- conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS fsub_channels_list TEXT"))
138
- conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS fsub_channels_access_hashes TEXT"))
139
- conn.execute(text("ALTER TABLE user_tokens ADD COLUMN IF NOT EXISTS req_msg_id NUMERIC"))
140
- conn.execute(text("""
141
- CREATE TABLE IF NOT EXISTS pending_fsub_requests (
142
- user_id NUMERIC PRIMARY KEY,
143
- search_query TEXT,
144
- target_file_id TEXT,
145
- created_at NUMERIC
146
- )
147
- """))
148
- try:
149
- conn.execute(text("ALTER TABLE pending_fsub_requests ALTER COLUMN user_id TYPE NUMERIC"))
150
- except Exception:
151
- pass
152
- except Exception as e:
153
- LOGGER.warning("Could not execute DDL migrations for admin_settings: %s", str(e))
154
-
155
- return scoped_session(sessionmaker(bind=engine, autoflush=False))
156
-
157
- SESSION = start()
158
-
159
- import asyncio
160
- import time
161
- import functools
162
- from sqlalchemy.exc import OperationalError, PendingRollbackError
163
-
164
- def db_retry(func):
165
- if asyncio.iscoroutinefunction(func):
166
- @functools.wraps(func)
167
- async def wrapper(*args, **kwargs):
168
- for attempt in range(3):
169
- try:
170
- return await func(*args, **kwargs)
171
- except (OperationalError, PendingRollbackError) as e:
172
- LOGGER.warning("Database connection error in %s (attempt %s): %s. Reconnecting...", func.__name__, attempt + 1, str(e))
173
- try:
174
- SESSION.rollback()
175
- SESSION.remove()
176
- except Exception:
177
- pass
178
- if attempt == 2:
179
- raise
180
- await asyncio.sleep(0.5)
181
- return wrapper
182
- else:
183
- @functools.wraps(func)
184
- def wrapper(*args, **kwargs):
185
- for attempt in range(3):
186
- try:
187
- return func(*args, **kwargs)
188
- except (OperationalError, PendingRollbackError) as e:
189
- LOGGER.warning("Database connection error in %s (attempt %s): %s. Reconnecting...", func.__name__, attempt + 1, str(e))
190
- try:
191
- SESSION.rollback()
192
- SESSION.remove()
193
- except Exception:
194
- pass
195
- if attempt == 2:
196
- raise
197
- time.sleep(0.5)
198
- return wrapper
199
-
200
- # ----------------- IN-MEMORY CACHE & MUTEX LOCK -----------------
201
- class CachedAdminSettings:
202
- def __init__(self, admin_settings_db=None):
203
- self.setting_name = "default"
204
- self.auto_delete = 0
205
- self.custom_caption = None
206
- self.fsub_channel = None
207
- self.channel_link = None
208
- self.caption_uname = None
209
- self.repair_mode = False
210
- self.shortener_site = None
211
- self.shortener_api = None
212
- self.shortener_status = True
213
- self.admins_list = None
214
- self.db_channels_list = None
215
- self.token_shortener_enabled = False
216
- self.token_timeout = 3600
217
- self.log_channel = None
218
- self.how_to_download = None
219
- self.log_channel_access_hash = None
220
- self.fsub_channel_access_hash = None
221
- self.fsub_channels_list = None
222
- self.fsub_channels_access_hashes = "{}"
223
-
224
- if admin_settings_db:
225
- def to_numeric(val):
226
- if val is None:
227
- return None
228
- try:
229
- val_str = str(val)
230
- if "." not in val_str:
231
- return int(val)
232
- f_val = float(val)
233
- if f_val.is_integer():
234
- return int(f_val)
235
- return f_val
236
- except (ValueError, TypeError):
237
- return val
238
-
239
- self.setting_name = admin_settings_db.setting_name
240
- self.auto_delete = to_numeric(admin_settings_db.auto_delete) or 0
241
- self.custom_caption = admin_settings_db.custom_caption
242
- self.fsub_channel = to_numeric(admin_settings_db.fsub_channel)
243
- self.channel_link = admin_settings_db.channel_link
244
- self.caption_uname = admin_settings_db.caption_uname
245
- self.repair_mode = bool(admin_settings_db.repair_mode)
246
- self.shortener_site = admin_settings_db.shortener_site
247
- self.shortener_api = admin_settings_db.shortener_api
248
- self.shortener_status = bool(admin_settings_db.shortener_status) if admin_settings_db.shortener_status is not None else True
249
- self.admins_list = admin_settings_db.admins_list
250
- self.db_channels_list = admin_settings_db.db_channels_list
251
- self.token_shortener_enabled = bool(admin_settings_db.token_shortener_enabled) if admin_settings_db.token_shortener_enabled is not None else False
252
- self.token_timeout = to_numeric(admin_settings_db.token_timeout) or 3600
253
- self.log_channel = to_numeric(admin_settings_db.log_channel)
254
- self.how_to_download = admin_settings_db.how_to_download
255
- self.log_channel_access_hash = to_numeric(admin_settings_db.log_channel_access_hash)
256
- self.fsub_channel_access_hash = to_numeric(admin_settings_db.fsub_channel_access_hash)
257
- self.fsub_channels_list = admin_settings_db.fsub_channels_list
258
- self.fsub_channels_access_hashes = admin_settings_db.fsub_channels_access_hashes or "{}"
259
-
260
- _cached_admin_settings = None
261
- _cache_lock = threading.Lock()
262
-
263
- def _update_cache_from_db(admin_setting):
264
- global _cached_admin_settings
265
- with _cache_lock:
266
- _cached_admin_settings = CachedAdminSettings(admin_setting)
267
-
268
- @db_retry
269
- def get_admin_settings_sync():
270
- global _cached_admin_settings
271
- with _cache_lock:
272
- if _cached_admin_settings is not None:
273
- return _cached_admin_settings
274
-
275
- for attempt in range(3):
276
- try:
277
- session = SESSION()
278
- admin_setting = session.query(AdminSettings).first()
279
- if not admin_setting:
280
- admin_setting = AdminSettings(setting_name="default")
281
- session.add(admin_setting)
282
- session.commit()
283
- _cached_admin_settings = CachedAdminSettings(admin_setting)
284
- return _cached_admin_settings
285
- except (OperationalError, PendingRollbackError) as e:
286
- LOGGER.warning("Database connection error in get_admin_settings_sync (attempt %d): %s. Reconnecting...", attempt + 1, str(e))
287
- try:
288
- SESSION.rollback()
289
- except Exception:
290
- pass
291
- try:
292
- SESSION.remove()
293
- except Exception:
294
- pass
295
- if attempt == 2:
296
- return CachedAdminSettings()
297
- time.sleep(0.5)
298
- except Exception as e:
299
- LOGGER.warning("Error in get_admin_settings_sync: %s", str(e))
300
- try:
301
- SESSION.rollback()
302
- except Exception:
303
- pass
304
- try:
305
- SESSION.remove()
306
- except Exception:
307
- pass
308
- return CachedAdminSettings()
309
- finally:
310
- SESSION.close()
311
-
312
- @db_retry
313
- def heal_admin_settings():
314
- import os
315
- try:
316
- session = SESSION()
317
- admin_setting = session.query(AdminSettings).first()
318
-
319
- env_admins = os.environ.get("ADMINS", "")
320
- owner_id = os.environ.get("OWNER_ID", "")
321
- admins_set = set()
322
- for x in env_admins.split():
323
- x = x.strip()
324
- if x:
325
- admins_set.add(x)
326
- if owner_id:
327
- admins_set.add(owner_id.strip())
328
- default_admins = ",".join(sorted(list(admins_set))) if admins_set else None
329
-
330
- env_channels = os.environ.get("DB_CHANNELS", "")
331
- channels_list = []
332
- for x in env_channels.split():
333
- x = x.strip()
334
- if x:
335
- channels_list.append(x)
336
- default_channels = ",".join(channels_list) if channels_list else None
337
-
338
- # Parse helpers
339
- def parse_bool(env_val, default=None):
340
- if env_val is None:
341
- return default
342
- val = env_val.strip().lower()
343
- if val in ("true", "yes", "on", "1"):
344
- return True
345
- if val in ("false", "no", "off", "0"):
346
- return False
347
- return default
348
-
349
- def parse_int(env_val, default=None):
350
- if env_val is None:
351
- return default
352
- try:
353
- return int(env_val.strip())
354
- except ValueError:
355
- return default
356
-
357
- def parse_time(env_val, default=None):
358
- if env_val is None:
359
- return default
360
- val = env_val.strip().lower()
361
- if val.endswith("h"):
362
- try:
363
- return int(float(val[:-1]) * 3600)
364
- except ValueError:
365
- pass
366
- elif val.endswith("m"):
367
- try:
368
- return int(float(val[:-1]) * 60)
369
- except ValueError:
370
- pass
371
- elif val.endswith("d"):
372
- try:
373
- return int(float(val[:-1]) * 86400)
374
- except ValueError:
375
- pass
376
- elif val.endswith("s"):
377
- try:
378
- return int(float(val[:-1]))
379
- except ValueError:
380
- pass
381
- else:
382
- try:
383
- return int(val)
384
- except ValueError:
385
- pass
386
- return default
387
-
388
- env_auto_delete = os.environ.get("AUTO_DELETE")
389
- env_custom_caption = os.environ.get("CUSTOM_CAPTION")
390
- env_fsub_channel = os.environ.get("FSUB_CHANNEL")
391
- env_channel_link = os.environ.get("CHANNEL_LINK")
392
- env_caption_uname = os.environ.get("CAPTION_UNAME")
393
- env_repair_mode = os.environ.get("REPAIR_MODE")
394
- env_shortener_site = os.environ.get("SHORTENER_SITE")
395
- env_shortener_api = os.environ.get("SHORTENER_API")
396
- env_shortener_status = os.environ.get("SHORTENER_STATUS")
397
- env_token_shortener_enabled = os.environ.get("TOKEN_SHORTENER_ENABLED")
398
- env_token_timeout = os.environ.get("TOKEN_TIMEOUT")
399
- env_log_channel = os.environ.get("LOG_CHANNEL")
400
- env_how_to_download = os.environ.get("HOW_TO_DOWNLOAD")
401
-
402
- if not admin_setting:
403
- admin_setting = AdminSettings(setting_name="default")
404
- admin_setting.admins_list = default_admins
405
- admin_setting.db_channels_list = default_channels
406
-
407
- if env_auto_delete is not None:
408
- admin_setting.auto_delete = parse_int(env_auto_delete, 0)
409
- if env_custom_caption is not None:
410
- cc = env_custom_caption.strip()
411
- admin_setting.custom_caption = None if cc.lower() in ("off", "disable", "disabled", "none") else cc
412
- if env_fsub_channel is not None:
413
- admin_setting.fsub_channel = parse_int(env_fsub_channel)
414
- if env_channel_link is not None:
415
- cl = env_channel_link.strip()
416
- admin_setting.channel_link = None if cl.lower() in ("off", "disable", "disabled", "none") else cl
417
- if env_caption_uname is not None:
418
- cu = env_caption_uname.strip()
419
- admin_setting.caption_uname = None if cu.lower() in ("off", "disable", "disabled", "none") else cu
420
- if env_repair_mode is not None:
421
- admin_setting.repair_mode = parse_bool(env_repair_mode, False)
422
- if env_shortener_site is not None:
423
- ss = env_shortener_site.strip()
424
- admin_setting.shortener_site = None if ss.lower() in ("off", "disable", "disabled", "none") else ss
425
- if env_shortener_api is not None:
426
- sa = env_shortener_api.strip()
427
- admin_setting.shortener_api = None if sa.lower() in ("off", "disable", "disabled", "none") else sa
428
- if env_shortener_status is not None:
429
- admin_setting.shortener_status = parse_bool(env_shortener_status, True)
430
- if env_token_shortener_enabled is not None:
431
- admin_setting.token_shortener_enabled = parse_bool(env_token_shortener_enabled, False)
432
- if env_token_timeout is not None:
433
- admin_setting.token_timeout = parse_time(env_token_timeout, 3600)
434
- if env_log_channel is not None:
435
- admin_setting.log_channel = parse_int(env_log_channel)
436
- if env_how_to_download is not None:
437
- hd = env_how_to_download.strip()
438
- admin_setting.how_to_download = None if hd.lower() in ("off", "disable", "disabled", "none") else hd
439
-
440
- # Enforce mutual exclusion
441
- if admin_setting.token_shortener_enabled and admin_setting.shortener_status:
442
- admin_setting.shortener_status = False
443
-
444
- session.add(admin_setting)
445
- session.commit()
446
- LOGGER.info("Created default AdminSettings with env values.")
447
- else:
448
- updated = False
449
- # Check if admins_list is None, empty, or has the test dummy values
450
- if (not admin_setting.admins_list or
451
- admin_setting.admins_list == "12345,67890" or
452
- (owner_id and owner_id.strip() not in admin_setting.admins_list.split(','))):
453
- admin_setting.admins_list = default_admins
454
- updated = True
455
-
456
- # Check if db_channels_list is None, empty, or has the test dummy values
457
- if (not admin_setting.db_channels_list or
458
- admin_setting.db_channels_list == "-100123,-100456"):
459
- admin_setting.db_channels_list = default_channels
460
- updated = True
461
-
462
- # Heal other environment variables
463
- if env_auto_delete is not None:
464
- parsed_auto_delete = parse_int(env_auto_delete)
465
- if parsed_auto_delete is not None and admin_setting.auto_delete != parsed_auto_delete:
466
- admin_setting.auto_delete = parsed_auto_delete
467
- updated = True
468
-
469
- if env_custom_caption is not None:
470
- parsed_custom_caption = env_custom_caption.strip()
471
- if parsed_custom_caption.lower() in ("off", "disable", "disabled", "none"):
472
- parsed_custom_caption = None
473
- if admin_setting.custom_caption != parsed_custom_caption:
474
- admin_setting.custom_caption = parsed_custom_caption
475
- updated = True
476
-
477
- if env_fsub_channel is not None:
478
- parsed_fsub_channel = parse_int(env_fsub_channel)
479
- if parsed_fsub_channel is not None and admin_setting.fsub_channel != parsed_fsub_channel:
480
- admin_setting.fsub_channel = parsed_fsub_channel
481
- updated = True
482
-
483
- if env_channel_link is not None:
484
- parsed_channel_link = env_channel_link.strip()
485
- if parsed_channel_link.lower() in ("off", "disable", "disabled", "none"):
486
- parsed_channel_link = None
487
- if admin_setting.channel_link != parsed_channel_link:
488
- admin_setting.channel_link = parsed_channel_link
489
- updated = True
490
-
491
- if env_caption_uname is not None:
492
- parsed_caption_uname = env_caption_uname.strip()
493
- if parsed_caption_uname.lower() in ("off", "disable", "disabled", "none"):
494
- parsed_caption_uname = None
495
- if admin_setting.caption_uname != parsed_caption_uname:
496
- admin_setting.caption_uname = parsed_caption_uname
497
- updated = True
498
-
499
- if env_repair_mode is not None:
500
- parsed_repair_mode = parse_bool(env_repair_mode)
501
- if parsed_repair_mode is not None and admin_setting.repair_mode != parsed_repair_mode:
502
- admin_setting.repair_mode = parsed_repair_mode
503
- updated = True
504
-
505
- if env_shortener_site is not None:
506
- parsed_shortener_site = env_shortener_site.strip()
507
- if parsed_shortener_site.lower() in ("off", "disable", "disabled", "none"):
508
- parsed_shortener_site = None
509
- if admin_setting.shortener_site != parsed_shortener_site:
510
- admin_setting.shortener_site = parsed_shortener_site
511
- updated = True
512
-
513
- if env_shortener_api is not None:
514
- parsed_shortener_api = env_shortener_api.strip()
515
- if parsed_shortener_api.lower() in ("off", "disable", "disabled", "none"):
516
- parsed_shortener_api = None
517
- if admin_setting.shortener_api != parsed_shortener_api:
518
- admin_setting.shortener_api = parsed_shortener_api
519
- updated = True
520
-
521
- if env_shortener_status is not None:
522
- parsed_shortener_status = parse_bool(env_shortener_status)
523
- if parsed_shortener_status is not None and admin_setting.shortener_status != parsed_shortener_status:
524
- admin_setting.shortener_status = parsed_shortener_status
525
- updated = True
526
-
527
- if env_token_shortener_enabled is not None:
528
- parsed_token_shortener_enabled = parse_bool(env_token_shortener_enabled)
529
- if parsed_token_shortener_enabled is not None and admin_setting.token_shortener_enabled != parsed_token_shortener_enabled:
530
- admin_setting.token_shortener_enabled = parsed_token_shortener_enabled
531
- updated = True
532
-
533
- if env_token_timeout is not None:
534
- parsed_token_timeout = parse_time(env_token_timeout)
535
- if parsed_token_timeout is not None and admin_setting.token_timeout != parsed_token_timeout:
536
- admin_setting.token_timeout = parsed_token_timeout
537
- updated = True
538
-
539
- if env_log_channel is not None:
540
- parsed_log_channel = parse_int(env_log_channel)
541
- if parsed_log_channel is not None and admin_setting.log_channel != parsed_log_channel:
542
- admin_setting.log_channel = parsed_log_channel
543
- updated = True
544
-
545
- if env_how_to_download is not None:
546
- parsed_hd = env_how_to_download.strip()
547
- if parsed_hd.lower() in ("off", "disable", "disabled", "none"):
548
- parsed_hd = None
549
- if admin_setting.how_to_download != parsed_hd:
550
- admin_setting.how_to_download = parsed_hd
551
- updated = True
552
-
553
- # Enforce mutual exclusion
554
- if admin_setting.token_shortener_enabled and admin_setting.shortener_status:
555
- admin_setting.shortener_status = False
556
- updated = True
557
-
558
- if updated:
559
- session.commit()
560
- LOGGER.info("Healed/restored AdminSettings from env values.")
561
-
562
- # Prime the cache on boot
563
- _update_cache_from_db(admin_setting)
564
- except Exception as e:
565
- LOGGER.warning("Could not heal admin settings: %s", str(e))
566
- finally:
567
- SESSION.close()
568
-
569
- heal_admin_settings()
570
-
571
- INSERTION_LOCK = threading.RLock()
572
-
573
- @db_retry
574
- async def get_search_settings(user_id):
575
- for attempt in range(3):
576
- try:
577
- with INSERTION_LOCK:
578
- settings = SESSION.query(Settings).filter_by(user_id=user_id).first()
579
- return settings
580
- except (OperationalError, PendingRollbackError) as e:
581
- LOGGER.warning("Database connection error in get_search_settings (attempt %d): %s. Reconnecting...", attempt + 1, str(e))
582
- try:
583
- SESSION.rollback()
584
- except Exception:
585
- pass
586
- try:
587
- SESSION.remove()
588
- except Exception:
589
- pass
590
- if attempt == 2:
591
- return None
592
- await asyncio.sleep(0.5)
593
- except Exception as e:
594
- LOGGER.warning("Error getting search settings: %s", str(e))
595
- try:
596
- SESSION.rollback()
597
- except Exception:
598
- pass
599
- try:
600
- SESSION.remove()
601
- except Exception:
602
- pass
603
- return None
604
- finally:
605
- SESSION.close()
606
-
607
- @db_retry
608
- async def change_search_settings(user_id, precise_mode=None, button_mode=None, link_mode=None, list_mode=None):
609
- try:
610
- with INSERTION_LOCK:
611
- settings = SESSION.query(Settings).filter_by(user_id=user_id).first()
612
- if settings:
613
- if precise_mode is not None:
614
- settings.precise_mode = precise_mode
615
- if button_mode is not None:
616
- settings.button_mode = button_mode
617
- if link_mode is not None:
618
- settings.link_mode = link_mode
619
- if list_mode is not None:
620
- settings.list_mode = list_mode
621
- else:
622
- new_settings = Settings(
623
- user_id=user_id,
624
- precise_mode=precise_mode if precise_mode is not None else False,
625
- button_mode=button_mode if button_mode is not None else False,
626
- link_mode=link_mode if link_mode is not None else True,
627
- list_mode=list_mode if list_mode is not None else False
628
- )
629
- SESSION.add(new_settings)
630
- SESSION.commit()
631
- return True
632
- except Exception as e:
633
- LOGGER.warning("Error changing search settings: %s", str(e))
634
- try:
635
- SESSION.rollback()
636
- except Exception:
637
- pass
638
- try:
639
- SESSION.remove()
640
- except Exception:
641
- pass
642
- return False
643
- finally:
644
- SESSION.close()
645
-
646
- @db_retry
647
- async def set_repair_mode(repair_mode):
648
- try:
649
- with INSERTION_LOCK:
650
- session = SESSION()
651
- admin_setting = session.query(AdminSettings).first()
652
- if not admin_setting:
653
- admin_setting = AdminSettings(setting_name="default")
654
- session.add(admin_setting)
655
- session.commit()
656
-
657
- admin_setting.repair_mode = repair_mode
658
- session.commit()
659
- _update_cache_from_db(admin_setting)
660
- except Exception as e:
661
- LOGGER.warning("Error setting repair mode: %s", str(e))
662
- SESSION.rollback()
663
- finally:
664
- SESSION.close()
665
-
666
- @db_retry
667
- async def set_auto_delete(dur):
668
- try:
669
- with INSERTION_LOCK:
670
- session = SESSION()
671
- admin_setting = session.query(AdminSettings).first()
672
- if not admin_setting:
673
- admin_setting = AdminSettings(setting_name="default")
674
- session.add(admin_setting)
675
- session.commit()
676
-
677
- admin_setting.auto_delete = dur
678
- session.commit()
679
- _update_cache_from_db(admin_setting)
680
- except Exception as e:
681
- LOGGER.warning("Error setting auto delete: %s", str(e))
682
- SESSION.rollback()
683
- finally:
684
- SESSION.close()
685
-
686
- @db_retry
687
- async def get_admin_settings():
688
- return get_admin_settings_sync()
689
-
690
- @db_retry
691
- async def set_custom_caption(caption):
692
- try:
693
- with INSERTION_LOCK:
694
- session = SESSION()
695
- admin_setting = session.query(AdminSettings).first()
696
- if not admin_setting:
697
- admin_setting = AdminSettings(setting_name="default")
698
- session.add(admin_setting)
699
- session.commit()
700
-
701
- admin_setting.custom_caption = caption
702
- session.commit()
703
- _update_cache_from_db(admin_setting)
704
- except Exception as e:
705
- LOGGER.warning("Error setting custom caption: %s", str(e))
706
- SESSION.rollback()
707
- finally:
708
- SESSION.close()
709
-
710
- @db_retry
711
- async def set_force_sub(channel, access_hash=None):
712
- try:
713
- with INSERTION_LOCK:
714
- session = SESSION()
715
- admin_setting = session.query(AdminSettings).first()
716
- if not admin_setting:
717
- admin_setting = AdminSettings(setting_name="default")
718
- session.add(admin_setting)
719
- session.commit()
720
-
721
- admin_setting.fsub_channel = channel
722
- if access_hash is not None:
723
- admin_setting.fsub_channel_access_hash = access_hash
724
-
725
- # Keep fsub_channels_list in sync for backwards compatibility
726
- if channel:
727
- admin_setting.fsub_channels_list = str(channel)
728
- if access_hash is not None:
729
- import json
730
- admin_setting.fsub_channels_access_hashes = json.dumps({str(channel): access_hash})
731
- else:
732
- admin_setting.fsub_channels_list = None
733
- admin_setting.fsub_channels_access_hashes = "{}"
734
-
735
- session.commit()
736
- _update_cache_from_db(admin_setting)
737
- except Exception as e:
738
- LOGGER.warning("Error setting Force Sub channel: %s", str(e))
739
- SESSION.rollback()
740
- finally:
741
- SESSION.close()
742
-
743
- @db_retry
744
- async def set_force_sub_channels(channels_list, hashes_map):
745
- try:
746
- with INSERTION_LOCK:
747
- session = SESSION()
748
- admin_setting = session.query(AdminSettings).first()
749
- if not admin_setting:
750
- admin_setting = AdminSettings(setting_name="default")
751
- session.add(admin_setting)
752
- session.commit()
753
-
754
- admin_setting.fsub_channels_list = channels_list
755
- import json
756
- admin_setting.fsub_channels_access_hashes = json.dumps(hashes_map)
757
-
758
- # Sync first channel to fsub_channel legacy columns for safety
759
- if channels_list:
760
- first_ch = channels_list.split(',')[0].strip()
761
- try:
762
- admin_setting.fsub_channel = int(first_ch)
763
- except ValueError:
764
- admin_setting.fsub_channel = None
765
- admin_setting.fsub_channel_access_hash = hashes_map.get(first_ch)
766
- else:
767
- admin_setting.fsub_channel = None
768
- admin_setting.fsub_channel_access_hash = None
769
-
770
- session.commit()
771
- _update_cache_from_db(admin_setting)
772
- except Exception as e:
773
- LOGGER.warning("Error setting Force Sub channels list: %s", str(e))
774
- SESSION.rollback()
775
- finally:
776
- SESSION.close()
777
-
778
- @db_retry
779
- async def save_pending_fsub_request(user_id, search_query=None, target_file_id=None):
780
- import time
781
- try:
782
- with INSERTION_LOCK:
783
- session = SESSION()
784
- req = session.query(PendingFsubRequests).filter(PendingFsubRequests.user_id == user_id).first()
785
- if req:
786
- req.search_query = search_query
787
- req.target_file_id = target_file_id
788
- req.created_at = time.time()
789
- else:
790
- req = PendingFsubRequests(user_id=user_id, search_query=search_query, target_file_id=target_file_id)
791
- req.created_at = time.time()
792
- session.add(req)
793
- session.commit()
794
- except Exception as e:
795
- LOGGER.warning("Error saving pending fsub request: %s", str(e))
796
- SESSION.rollback()
797
- finally:
798
- SESSION.close()
799
-
800
- @db_retry
801
- async def get_pending_fsub_request(user_id):
802
- for attempt in range(3):
803
- try:
804
- session = SESSION()
805
- req = session.query(PendingFsubRequests).filter(PendingFsubRequests.user_id == user_id).first()
806
- return req
807
- except (OperationalError, PendingRollbackError) as e:
808
- LOGGER.warning("Database connection error in get_pending_fsub_request (attempt %d): %s. Reconnecting...", attempt + 1, str(e))
809
- try:
810
- SESSION.rollback()
811
- except Exception:
812
- pass
813
- try:
814
- SESSION.remove()
815
- except Exception:
816
- pass
817
- if attempt == 2:
818
- return None
819
- await asyncio.sleep(0.5)
820
- except Exception as e:
821
- LOGGER.warning("Error getting pending fsub request: %s", str(e))
822
- try:
823
- SESSION.rollback()
824
- except Exception:
825
- pass
826
- try:
827
- SESSION.remove()
828
- except Exception:
829
- pass
830
- return None
831
- finally:
832
- session.close()
833
-
834
- @db_retry
835
- async def delete_pending_fsub_request(user_id):
836
- try:
837
- with INSERTION_LOCK:
838
- session = SESSION()
839
- session.query(PendingFsubRequests).filter(PendingFsubRequests.user_id == user_id).delete()
840
- session.commit()
841
- except Exception as e:
842
- LOGGER.warning("Error deleting pending fsub request: %s", str(e))
843
- SESSION.rollback()
844
- finally:
845
- SESSION.close()
846
-
847
- @db_retry
848
- async def set_channel_link(link):
849
- try:
850
- with INSERTION_LOCK:
851
- session = SESSION()
852
- admin_setting = session.query(AdminSettings).first()
853
- if not admin_setting:
854
- admin_setting = AdminSettings(setting_name="default")
855
- session.add(admin_setting)
856
- session.commit()
857
-
858
- admin_setting.channel_link = link
859
- session.commit()
860
- _update_cache_from_db(admin_setting)
861
- except Exception as e:
862
- LOGGER.warning("Error adding Force Sub channel link: %s", str(e))
863
- SESSION.rollback()
864
- finally:
865
- SESSION.close()
866
-
867
- @db_retry
868
- async def get_channel():
869
- settings = get_admin_settings_sync()
870
- return settings.fsub_channel if settings.fsub_channel else False
871
-
872
- @db_retry
873
- async def get_link():
874
- settings = get_admin_settings_sync()
875
- return settings.channel_link if settings.channel_link else False
876
-
877
- @db_retry
878
- async def set_username(username):
879
- try:
880
- with INSERTION_LOCK:
881
- session = SESSION()
882
- admin_setting = session.query(AdminSettings).first()
883
- if not admin_setting:
884
- admin_setting = AdminSettings(setting_name="default")
885
- session.add(admin_setting)
886
- session.commit()
887
-
888
- admin_setting.caption_uname = username
889
- session.commit()
890
- _update_cache_from_db(admin_setting)
891
- except Exception as e:
892
- LOGGER.warning("Error adding username: %s", str(e))
893
- SESSION.rollback()
894
- finally:
895
- SESSION.close()
896
-
897
- @db_retry
898
- async def set_shortener_settings(site=None, api=None, status=None):
899
- try:
900
- with INSERTION_LOCK:
901
- session = SESSION()
902
- admin_setting = session.query(AdminSettings).first()
903
- if not admin_setting:
904
- admin_setting = AdminSettings(setting_name="default")
905
- session.add(admin_setting)
906
- session.commit()
907
-
908
- if site is not None:
909
- admin_setting.shortener_site = site
910
- if api is not None:
911
- admin_setting.shortener_api = api
912
- if status is not None:
913
- admin_setting.shortener_status = status
914
- if status:
915
- admin_setting.token_shortener_enabled = False
916
- session.commit()
917
- _update_cache_from_db(admin_setting)
918
- except Exception as e:
919
- LOGGER.warning("Error setting shortener settings: %s", str(e))
920
- SESSION.rollback()
921
- finally:
922
- SESSION.close()
923
-
924
- @db_retry
925
- async def delete_shortener_settings():
926
- try:
927
- with INSERTION_LOCK:
928
- session = SESSION()
929
- admin_setting = session.query(AdminSettings).first()
930
- if admin_setting:
931
- admin_setting.shortener_site = None
932
- admin_setting.shortener_api = None
933
- admin_setting.shortener_status = False
934
- session.commit()
935
- _update_cache_from_db(admin_setting)
936
- except Exception as e:
937
- LOGGER.warning("Error deleting shortener settings: %s", str(e))
938
- SESSION.rollback()
939
- finally:
940
- SESSION.close()
941
-
942
- @db_retry
943
- async def update_admins_list(admins_str):
944
- try:
945
- with INSERTION_LOCK:
946
- session = SESSION()
947
- admin_setting = session.query(AdminSettings).first()
948
- if not admin_setting:
949
- admin_setting = AdminSettings(setting_name="default")
950
- session.add(admin_setting)
951
- session.commit()
952
-
953
- admin_setting.admins_list = admins_str
954
- session.commit()
955
- _update_cache_from_db(admin_setting)
956
- except Exception as e:
957
- LOGGER.warning("Error updating admins list: %s", str(e))
958
- SESSION.rollback()
959
- finally:
960
- SESSION.close()
961
-
962
- @db_retry
963
- async def update_db_channels_list(channels_str):
964
- try:
965
- with INSERTION_LOCK:
966
- session = SESSION()
967
- admin_setting = session.query(AdminSettings).first()
968
- if not admin_setting:
969
- admin_setting = AdminSettings(setting_name="default")
970
- session.add(admin_setting)
971
- session.commit()
972
-
973
- admin_setting.db_channels_list = channels_str
974
- session.commit()
975
- _update_cache_from_db(admin_setting)
976
- except Exception as e:
977
- LOGGER.warning("Error updating db channels list: %s", str(e))
978
- SESSION.rollback()
979
- finally:
980
- SESSION.close()
981
-
982
- @db_retry
983
- async def get_user_token(user_id):
984
- for attempt in range(3):
985
- try:
986
- with INSERTION_LOCK:
987
- session = SESSION()
988
- return session.query(UserTokens).filter_by(user_id=user_id).first()
989
- except (OperationalError, PendingRollbackError) as e:
990
- LOGGER.warning("Database connection error in get_user_token (attempt %d): %s. Reconnecting...", attempt + 1, str(e))
991
- try:
992
- SESSION.rollback()
993
- except Exception:
994
- pass
995
- try:
996
- SESSION.remove()
997
- except Exception:
998
- pass
999
- if attempt == 2:
1000
- return None
1001
- await asyncio.sleep(0.5)
1002
- except Exception as e:
1003
- LOGGER.warning("Error getting user token: %s", str(e))
1004
- try:
1005
- SESSION.rollback()
1006
- except Exception:
1007
- pass
1008
- try:
1009
- SESSION.remove()
1010
- except Exception:
1011
- pass
1012
- return None
1013
- finally:
1014
- SESSION.close()
1015
-
1016
- @db_retry
1017
- async def create_user_token(user_id, token, search_query=None, target_file_id=None):
1018
- import time
1019
- try:
1020
- await prune_all_expired_tokens()
1021
- with INSERTION_LOCK:
1022
- session = SESSION()
1023
- tok_rec = session.query(UserTokens).filter_by(user_id=user_id).first()
1024
- if tok_rec:
1025
- tok_rec.token = token
1026
- tok_rec.created_at = time.time()
1027
- tok_rec.expires_at = 0
1028
- tok_rec.status = "pending"
1029
- tok_rec.search_query = search_query
1030
- tok_rec.target_file_id = target_file_id
1031
- else:
1032
- tok_rec = UserTokens(
1033
- user_id=user_id,
1034
- token=token,
1035
- created_at=time.time(),
1036
- search_query=search_query,
1037
- target_file_id=target_file_id
1038
- )
1039
- session.add(tok_rec)
1040
- session.commit()
1041
- return tok_rec
1042
- except Exception as e:
1043
- LOGGER.warning("Error creating user token: %s", str(e))
1044
- SESSION.rollback()
1045
- return None
1046
- finally:
1047
- SESSION.close()
1048
-
1049
- @db_retry
1050
- async def activate_user_token(user_id, expires_at):
1051
- try:
1052
- with INSERTION_LOCK:
1053
- session = SESSION()
1054
- tok_rec = session.query(UserTokens).filter_by(user_id=user_id).first()
1055
- if tok_rec:
1056
- tok_rec.status = "active"
1057
- tok_rec.expires_at = expires_at
1058
- session.commit()
1059
- return True
1060
- return False
1061
- except Exception as e:
1062
- LOGGER.warning("Error activating user token: %s", str(e))
1063
- SESSION.rollback()
1064
- return False
1065
- finally:
1066
- SESSION.close()
1067
-
1068
- @db_retry
1069
- async def delete_user_token(user_id):
1070
- try:
1071
- with INSERTION_LOCK:
1072
- session = SESSION()
1073
- tok_rec = session.query(UserTokens).filter_by(user_id=user_id).first()
1074
- if tok_rec:
1075
- session.delete(tok_rec)
1076
- session.commit()
1077
- return True
1078
- return False
1079
- except Exception as e:
1080
- LOGGER.warning("Error deleting user token: %s", str(e))
1081
- SESSION.rollback()
1082
- return False
1083
- finally:
1084
- SESSION.close()
1085
-
1086
- @db_retry
1087
- async def prune_all_expired_tokens():
1088
- import time
1089
- try:
1090
- with INSERTION_LOCK:
1091
- session = SESSION()
1092
- current_time = time.time()
1093
-
1094
- # Delete active tokens that have expired
1095
- expired_active = session.query(UserTokens).filter(
1096
- UserTokens.status == "active",
1097
- UserTokens.expires_at < current_time
1098
- )
1099
-
1100
- # Delete pending tokens that are older than 30 minutes (1800 seconds)
1101
- stale_pending = session.query(UserTokens).filter(
1102
- UserTokens.status == "pending",
1103
- (current_time - UserTokens.created_at) > 1800
1104
- )
1105
-
1106
- deleted_active = expired_active.delete(synchronize_session=False)
1107
- deleted_pending = stale_pending.delete(synchronize_session=False)
1108
-
1109
- if deleted_active or deleted_pending:
1110
- session.commit()
1111
- LOGGER.info("Database row protection: Pruned %d expired active and %d stale pending tokens.", deleted_active, deleted_pending)
1112
- return True
1113
- except Exception as e:
1114
- LOGGER.warning("Error pruning expired tokens from database: %s", str(e))
1115
- SESSION.rollback()
1116
- return False
1117
- finally:
1118
- SESSION.close()
1119
-
1120
- @db_retry
1121
- async def set_token_shortener_state(enabled):
1122
- try:
1123
- with INSERTION_LOCK:
1124
- session = SESSION()
1125
- admin_setting = session.query(AdminSettings).first()
1126
- if not admin_setting:
1127
- admin_setting = AdminSettings(setting_name="default")
1128
- session.add(admin_setting)
1129
- admin_setting.token_shortener_enabled = enabled
1130
- if enabled:
1131
- admin_setting.shortener_status = False
1132
- session.commit()
1133
- _update_cache_from_db(admin_setting)
1134
- return True
1135
- except Exception as e:
1136
- LOGGER.warning("Error setting token shortener state: %s", str(e))
1137
- SESSION.rollback()
1138
- return False
1139
- finally:
1140
- SESSION.close()
1141
-
1142
- @db_retry
1143
- async def set_token_timeout(seconds):
1144
- try:
1145
- with INSERTION_LOCK:
1146
- session = SESSION()
1147
- admin_setting = session.query(AdminSettings).first()
1148
- if not admin_setting:
1149
- admin_setting = AdminSettings(setting_name="default")
1150
- session.add(admin_setting)
1151
- admin_setting.token_timeout = seconds
1152
- session.commit()
1153
- _update_cache_from_db(admin_setting)
1154
- return True
1155
- except Exception as e:
1156
- LOGGER.warning("Error setting token timeout: %s", str(e))
1157
- SESSION.rollback()
1158
- return False
1159
- finally:
1160
- SESSION.close()
1161
-
1162
- @db_retry
1163
- async def set_log_channel(channel, access_hash=None):
1164
- try:
1165
- with INSERTION_LOCK:
1166
- session = SESSION()
1167
- admin_setting = session.query(AdminSettings).first()
1168
- if not admin_setting:
1169
- admin_setting = AdminSettings(setting_name="default")
1170
- session.add(admin_setting)
1171
- admin_setting.log_channel = channel
1172
- if access_hash is not None:
1173
- admin_setting.log_channel_access_hash = access_hash
1174
- session.commit()
1175
- _update_cache_from_db(admin_setting)
1176
- return True
1177
- except Exception as e:
1178
- LOGGER.warning("Error setting log channel: %s", str(e))
1179
- SESSION.rollback()
1180
- return False
1181
- finally:
1182
- SESSION.close()
1183
-
1184
- @db_retry
1185
- async def get_log_channel():
1186
- settings = get_admin_settings_sync()
1187
- return settings.log_channel if settings.log_channel else False
1188
-
1189
- @db_retry
1190
- async def set_how_to_download(url):
1191
- try:
1192
- with INSERTION_LOCK:
1193
- session = SESSION()
1194
- admin_setting = session.query(AdminSettings).first()
1195
- if not admin_setting:
1196
- admin_setting = AdminSettings(setting_name="default")
1197
- session.add(admin_setting)
1198
- admin_setting.how_to_download = url
1199
- session.commit()
1200
- _update_cache_from_db(admin_setting)
1201
- return True
1202
- except Exception as e:
1203
- LOGGER.warning("Error setting how to download URL: %s", str(e))
1204
- SESSION.rollback()
1205
- return False
1206
- finally:
1207
- SESSION.close()
1208
-
1209
- @db_retry
1210
- async def update_user_token_msg_id(user_id, msg_id):
1211
- try:
1212
- with INSERTION_LOCK:
1213
- session = SESSION()
1214
- tok_rec = session.query(UserTokens).filter_by(user_id=user_id).first()
1215
- if tok_rec:
1216
- tok_rec.req_msg_id = msg_id
1217
- session.commit()
1218
- return True
1219
- return False
1220
- except Exception as e:
1221
- LOGGER.warning("Error updating user token message ID: %s", str(e))
1222
- SESSION.rollback()
1223
- return False
1224
- finally:
1225
- SESSION.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/db/suggestion_cache.py DELETED
@@ -1,103 +0,0 @@
1
- import logging
2
- from sqlalchemy import func
3
- from sqlalchemy.exc import PendingRollbackError
4
- from mfinder.db.files_sql import SESSION, INSERTION_LOCK, SearchSuggestionsCache
5
-
6
- LOGGER = logging.getLogger(__name__)
7
-
8
- async def get_cached_suggestion(original_query: str):
9
- """Retrieve cached suggestion for a query if it exists."""
10
- original_query = original_query.strip().lower()
11
- retries = 3
12
- while retries > 0:
13
- try:
14
- with INSERTION_LOCK:
15
- entry = SESSION.query(SearchSuggestionsCache).filter_by(original_query=original_query).first()
16
- if entry:
17
- return {
18
- "corrected_query": entry.corrected_query,
19
- "keywords": [k.strip() for k in entry.keywords.split(",") if k.strip()] if entry.keywords else [],
20
- "suggestions": [s.strip() for s in entry.suggestions.split(",") if s.strip()] if entry.suggestions else []
21
- }
22
- return None
23
- except PendingRollbackError:
24
- try:
25
- SESSION.rollback()
26
- except Exception:
27
- pass
28
- try:
29
- SESSION.remove()
30
- except Exception:
31
- pass
32
- retries -= 1
33
- except Exception as e:
34
- LOGGER.warning(f"Error reading suggestion cache: {e}")
35
- try:
36
- SESSION.rollback()
37
- except Exception:
38
- pass
39
- try:
40
- SESSION.remove()
41
- except Exception:
42
- pass
43
- return None
44
- finally:
45
- try:
46
- SESSION.close()
47
- except Exception:
48
- pass
49
- return None
50
-
51
- async def set_cached_suggestion(original_query: str, corrected_query: str, keywords: list, suggestions: list):
52
- """Save/update a suggestion in the cache."""
53
- original_query = original_query.strip().lower()
54
- keywords_str = ",".join(keywords) if keywords else ""
55
- suggestions_str = ",".join(suggestions) if suggestions else ""
56
-
57
- retries = 3
58
- while retries > 0:
59
- try:
60
- with INSERTION_LOCK:
61
- entry = SESSION.query(SearchSuggestionsCache).filter_by(original_query=original_query).first()
62
- if entry:
63
- entry.corrected_query = corrected_query
64
- entry.keywords = keywords_str
65
- entry.suggestions = suggestions_str
66
- entry.created_at = func.now()
67
- else:
68
- new_entry = SearchSuggestionsCache(
69
- original_query=original_query,
70
- corrected_query=corrected_query,
71
- keywords=keywords_str,
72
- suggestions=suggestions_str
73
- )
74
- SESSION.add(new_entry)
75
- SESSION.commit()
76
- return True
77
- except PendingRollbackError:
78
- try:
79
- SESSION.rollback()
80
- except Exception:
81
- pass
82
- try:
83
- SESSION.remove()
84
- except Exception:
85
- pass
86
- retries -= 1
87
- except Exception as e:
88
- LOGGER.warning(f"Error saving suggestion cache: {e}")
89
- try:
90
- SESSION.rollback()
91
- except Exception:
92
- pass
93
- try:
94
- SESSION.remove()
95
- except Exception:
96
- pass
97
- return False
98
- finally:
99
- try:
100
- SESSION.close()
101
- except Exception:
102
- pass
103
- return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/plugins/admin_settings.py DELETED
@@ -1,1079 +0,0 @@
1
- import shlex
2
- from pyrogram import Client, filters
3
- from mfinder.db.settings_sql import (
4
- get_admin_settings,
5
- set_repair_mode,
6
- set_auto_delete,
7
- set_custom_caption,
8
- set_force_sub,
9
- set_channel_link,
10
- get_link,
11
- set_username,
12
- set_log_channel,
13
- get_log_channel,
14
- set_how_to_download
15
- )
16
- from mfinder.db.ban_sql import is_banned, ban_user, unban_user
17
- from mfinder.db.filters_sql import add_filter, rem_filter, list_filters
18
- from mfinder.db.files_sql import count_files
19
- from mfinder import ADMINS, DB_CHANNELS
20
-
21
- @Client.on_message(filters.command(["autodelete"]) & filters.user(ADMINS))
22
- async def auto_delete_(bot, update):
23
- data = update.text.split()
24
- if len(data) == 2:
25
- dur = data[-1]
26
- if dur.lower() == "off":
27
- dur = 0
28
-
29
- await set_auto_delete(int(dur))
30
-
31
- if dur:
32
- await update.reply_text(f"File auto delete set to `{dur}` seconds")
33
- else:
34
- await update.reply_text("File auto delete disabled")
35
-
36
- else:
37
- await update.reply_text("Please send in proper format `/autodelete seconds`")
38
-
39
-
40
- @Client.on_message(filters.command(["repairmode"]) & filters.user(ADMINS))
41
- async def repair_mode_(bot, update):
42
- data = update.text.split()
43
- if len(data) == 2:
44
- toggle = data[-1]
45
- if toggle.lower() == "off":
46
- mode = False
47
- elif toggle.lower() == "on":
48
- mode = True
49
- else:
50
- await update.reply_text(
51
- "Please send in proper format `/repairmode <on/off>`"
52
- )
53
- return
54
-
55
- await set_repair_mode(mode)
56
- await update.reply_text(f"Repair mode set to `{toggle.upper()}`")
57
-
58
- else:
59
- await update.reply_text("Please send in proper format `/repairmode on/off`")
60
- return
61
-
62
-
63
- @Client.on_message(filters.command(["customcaption"]) & filters.user(ADMINS))
64
- async def custom_caption_(bot, update):
65
- data = update.text.split()
66
- caption = " ".join(data[1:])
67
- if len(data) >= 2:
68
- if caption.lower() == "off":
69
- caption = None
70
-
71
- await set_custom_caption(caption)
72
-
73
- if caption:
74
- await update.reply_text(f"Custom caption set to `{caption}`")
75
- else:
76
- await update.reply_text("Custom caption disabled")
77
-
78
- else:
79
- await update.reply_text(
80
- "Please send in proper format `/customcaption caption/off`"
81
- )
82
- return
83
-
84
-
85
- ADMIN_INPUT_STATE = {}
86
-
87
- async def get_settings_screen(cat: str):
88
- from mfinder.db.settings_sql import get_admin_settings
89
- from mfinder import ADMINS, DB_CHANNELS
90
-
91
- admin_settings = await get_admin_settings()
92
- auto_delete = admin_settings.auto_delete
93
- custom_caption = admin_settings.custom_caption
94
- fsub_channel = admin_settings.fsub_channel
95
- fsub_channels_list = admin_settings.fsub_channels_list
96
- caption_uname = admin_settings.caption_uname
97
- invite_link = admin_settings.channel_link
98
- repair_mode = admin_settings.repair_mode
99
- shortener_site = admin_settings.shortener_site
100
- shortener_api = admin_settings.shortener_api
101
- shortener_status = admin_settings.shortener_status
102
- if shortener_status is None:
103
- shortener_status = True
104
- token_shortener_enabled = admin_settings.token_shortener_enabled
105
- if token_shortener_enabled is None:
106
- token_shortener_enabled = False
107
- token_timeout = admin_settings.token_timeout
108
- if token_timeout is None:
109
- token_timeout = 3600
110
- log_channel = admin_settings.log_channel
111
-
112
- from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
113
-
114
- if cat == "main":
115
- text = "🛠️ **Admin Settings**\n\nSelect a category to configure:"
116
- keyboard = InlineKeyboardMarkup([
117
- [
118
- InlineKeyboardButton("⚙️ General Settings", callback_data="adm_cat:gen"),
119
- InlineKeyboardButton("🔗 Shortener Settings", callback_data="adm_cat:sho")
120
- ],
121
- [
122
- InlineKeyboardButton("📢 Channel Settings", callback_data="adm_cat:cha"),
123
- InlineKeyboardButton("📝 Caption Settings", callback_data="adm_cat:cap")
124
- ],
125
- [
126
- InlineKeyboardButton("❌ Close Menu", callback_data="adm_close")
127
- ]
128
- ])
129
- return text, keyboard
130
-
131
- elif cat == "gen":
132
- repair_status_label = "🟢 Enabled" if repair_mode else "🔴 Disabled"
133
- repair_btn_label = "🔴 Disable Repair Mode" if repair_mode else "🟢 Enable Repair Mode"
134
- auto_del_label = f"{auto_delete} seconds" if auto_delete else "Disabled"
135
-
136
- how_to_download = admin_settings.how_to_download
137
- how_to_download_label = how_to_download if how_to_download else "Default (https://telegram.me/FIREBOLTTutorial/23)"
138
-
139
- text = (
140
- "⚙️ **General Settings**\n\n"
141
- f"• **Repair Mode**: `{repair_status_label}`\n"
142
- " _When enabled, the bot will ignore all search queries._\n\n"
143
- f"• **Auto Delete**: `{auto_del_label}`\n"
144
- " _Duration in seconds before sent files are deleted from the chat._\n\n"
145
- f"• **How to Download URL**: `{how_to_download_label}`\n"
146
- " _URL used for 'How to Download' and 'How to Verify' buttons._"
147
- )
148
- keyboard = InlineKeyboardMarkup([
149
- [InlineKeyboardButton(repair_btn_label, callback_data="adm_toggle:repair")],
150
- [InlineKeyboardButton("⏱️ Set Auto Delete Duration", callback_data="adm_ask:auto_delete")],
151
- [InlineKeyboardButton("❓ Set How to Download URL", callback_data="adm_ask:how_to_download")],
152
- [InlineKeyboardButton("🔙 Back to Main Settings", callback_data="adm_cat:main")]
153
- ])
154
- return text, keyboard
155
-
156
- elif cat == "sho":
157
- status_label = "🟢 ON" if shortener_status else "🔴 OFF"
158
- toggle_label = "🔴 Turn OFF Shortener" if shortener_status else "🟢 Turn ON Shortener"
159
- site_label = shortener_site if shortener_site else "Not set"
160
- if shortener_api:
161
- api_label = shortener_api[:4] + "*" * (len(shortener_api) - 4) if len(shortener_api) > 4 else "Set"
162
- else:
163
- api_label = "Not set"
164
-
165
- token_status_label = "🟢 ON" if token_shortener_enabled else "🔴 OFF"
166
- token_toggle_label = "🔴 Turn OFF Token Shortener" if token_shortener_enabled else "🟢 Turn ON Token Shortener"
167
-
168
- parsed_seconds = int(token_timeout)
169
- if parsed_seconds >= 3600:
170
- hours = parsed_seconds / 3600
171
- time_desc = f"{hours:.1f} hours" if hours % 1 != 0 else f"{int(hours)} hours"
172
- elif parsed_seconds >= 60:
173
- mins = parsed_seconds / 60
174
- time_desc = f"{mins:.1f} minutes" if mins % 1 != 0 else f"{int(mins)} minutes"
175
- else:
176
- time_desc = f"{parsed_seconds} seconds"
177
-
178
- text = (
179
- "🔗 **Shortener Settings**\n\n"
180
- f"• **Shortener Status (Standard)**: `{status_label}`\n"
181
- " _If ON, standard file-level shortening is applied._\n\n"
182
- f"• **Shortener Site**: `{site_label}`\n"
183
- f"• **Shortener API**: `{api_label}`\n\n"
184
- f"• **Token Shortener**: `{token_status_label}`\n"
185
- f"• **Token Timeout**: `{time_desc}`\n"
186
- " _If ON, users complete ONE link for direct access for the duration above._"
187
- )
188
- keyboard = InlineKeyboardMarkup([
189
- [InlineKeyboardButton(toggle_label, callback_data="adm_toggle:shortener")],
190
- [InlineKeyboardButton(token_toggle_label, callback_data="adm_toggle:token_shortener")],
191
- [
192
- InlineKeyboardButton("🌐 Set Site Name", callback_data="adm_ask:shortener_site"),
193
- InlineKeyboardButton("🔑 Set API Key", callback_data="adm_ask:shortener_api")
194
- ],
195
- [
196
- InlineKeyboardButton("⏱️ Set Token Timeout", callback_data="adm_ask:token_timeout"),
197
- InlineKeyboardButton("🗑️ Clear Settings", callback_data="adm_del_shortener")
198
- ],
199
- [InlineKeyboardButton("🔙 Back to Main Settings", callback_data="adm_cat:main")]
200
- ])
201
- return text, keyboard
202
-
203
- elif cat == "cha":
204
- admins_str = "\n".join(f"• `{adm}`" for adm in ADMINS)
205
- db_channels_str = "\n".join(f"• `{ch}`" for ch in DB_CHANNELS) if DB_CHANNELS else "• None"
206
- fsub_label = fsub_channels_list if fsub_channels_list else (fsub_channel if fsub_channel else "Disabled")
207
- link_label = invite_link if invite_link else "Disabled"
208
- log_label = log_channel if log_channel else "Disabled"
209
-
210
- text = (
211
- "📢 **Channel Settings**\n\n"
212
- f"👤 **Admins**:\n{admins_str}\n\n"
213
- f"📦 **Database Channels**:\n{db_channels_str}\n\n"
214
- f"• **Force Sub Channel**: `{fsub_label}`\n"
215
- f"• **Channel Link**: `{link_label}`\n"
216
- f"• **User Logs Channel**: `{log_label}`"
217
- )
218
- keyboard = InlineKeyboardMarkup([
219
- [
220
- InlineKeyboardButton("👤 Set Admins List", callback_data="adm_ask:admins"),
221
- InlineKeyboardButton("📦 Set DB Channels", callback_data="adm_ask:db_channels")
222
- ],
223
- [
224
- InlineKeyboardButton("⚡ Set Force Sub ID", callback_data="adm_ask:force_sub"),
225
- InlineKeyboardButton("🔗 Set Channel Link", callback_data="adm_ask:channel_link")
226
- ],
227
- [
228
- InlineKeyboardButton("📊 Set Log Channel ID", callback_data="adm_ask:log_channel")
229
- ],
230
- [InlineKeyboardButton("🔙 Back to Main Settings", callback_data="adm_cat:main")]
231
- ])
232
- return text, keyboard
233
-
234
- elif cat == "cap":
235
- caption_label = custom_caption if custom_caption else "Disabled"
236
- uname_label = caption_uname if caption_uname else "Disabled"
237
-
238
- text = (
239
- "📝 **Caption Settings**\n\n"
240
- f"• **Custom Caption**:\n`{caption_label}`\n\n"
241
- f"• **Caption Username**: `{uname_label}`"
242
- )
243
- keyboard = InlineKeyboardMarkup([
244
- [InlineKeyboardButton("✏️ Set Custom Caption", callback_data="adm_ask:custom_caption")],
245
- [InlineKeyboardButton("🏷️ Set Caption Username", callback_data="adm_ask:caption_uname")],
246
- [InlineKeyboardButton("🔙 Back to Main Settings", callback_data="adm_cat:main")]
247
- ])
248
- return text, keyboard
249
-
250
- @Client.on_message(filters.command(["adminsettings"]) & filters.user(ADMINS))
251
- async def admin_settings_(bot, update):
252
- text, keyboard = await get_settings_screen("main")
253
- await update.reply_text(
254
- text=text,
255
- reply_markup=keyboard,
256
- quote=True
257
- )
258
-
259
- @Client.on_callback_query(filters.regex(r"^adm_cat:(main|gen|sho|cha|cap)$") & filters.user(ADMINS))
260
- async def admin_category_callback(bot, query):
261
- cat = query.data.split(":")[1]
262
- ADMIN_INPUT_STATE.pop(query.from_user.id, None)
263
-
264
- text, keyboard = await get_settings_screen(cat)
265
- try:
266
- await query.message.edit_text(
267
- text=text,
268
- reply_markup=keyboard
269
- )
270
- except Exception:
271
- pass
272
- await query.answer()
273
-
274
- @Client.on_callback_query(filters.regex(r"^adm_toggle:(repair|shortener|token_shortener)$") & filters.user(ADMINS))
275
- async def admin_toggle_callback(bot, query):
276
- setting = query.data.split(":")[1]
277
- from mfinder.db.settings_sql import (
278
- get_admin_settings,
279
- set_repair_mode,
280
- set_shortener_settings,
281
- set_token_shortener_state
282
- )
283
-
284
- admin_settings = await get_admin_settings()
285
-
286
- if setting == "repair":
287
- new_val = not admin_settings.repair_mode
288
- await set_repair_mode(new_val)
289
- await query.answer(f"Repair mode {'Enabled' if new_val else 'Disabled'}")
290
- text, keyboard = await get_settings_screen("gen")
291
- elif setting == "shortener":
292
- current_status = admin_settings.shortener_status
293
- if current_status is None:
294
- current_status = True
295
- new_val = not current_status
296
- await set_shortener_settings(status=new_val)
297
- if new_val:
298
- await set_token_shortener_state(False)
299
- await query.answer(f"Shortener {'ON' if new_val else 'OFF'}")
300
- text, keyboard = await get_settings_screen("sho")
301
- elif setting == "token_shortener":
302
- current_status = admin_settings.token_shortener_enabled
303
- if current_status is None:
304
- current_status = False
305
- new_val = not current_status
306
- await set_token_shortener_state(new_val)
307
- if new_val:
308
- await set_shortener_settings(status=False)
309
- await query.answer(f"Token shortener {'Enabled' if new_val else 'Disabled'}")
310
- text, keyboard = await get_settings_screen("sho")
311
- else:
312
- await query.answer("Unknown toggle.")
313
- return
314
-
315
- try:
316
- await query.message.edit_text(
317
- text=text,
318
- reply_markup=keyboard
319
- )
320
- except Exception:
321
- pass
322
-
323
- @Client.on_callback_query(filters.regex(r"^adm_del_shortener$") & filters.user(ADMINS))
324
- async def admin_del_shortener_callback(bot, query):
325
- from mfinder.db.settings_sql import delete_shortener_settings
326
- await delete_shortener_settings()
327
- await query.answer("Shortener settings cleared.")
328
- text, keyboard = await get_settings_screen("sho")
329
- try:
330
- await query.message.edit_text(
331
- text=text,
332
- reply_markup=keyboard
333
- )
334
- except Exception:
335
- pass
336
-
337
- @Client.on_callback_query(filters.regex(r"^adm_close$") & filters.user(ADMINS))
338
- async def admin_close_callback(bot, query):
339
- ADMIN_INPUT_STATE.pop(query.from_user.id, None)
340
- try:
341
- await query.message.delete()
342
- except Exception:
343
- pass
344
- await query.answer("Settings menu closed.")
345
-
346
- @Client.on_callback_query(filters.regex(r"^adm_ask:(\w+)$") & filters.user(ADMINS))
347
- async def admin_ask_callback(bot, query):
348
- action = query.data.split(":")[1]
349
- user_id = query.from_user.id
350
- ADMIN_INPUT_STATE[user_id] = {"action": f"set_{action}", "message_id": query.message.id}
351
- prompt_map = {
352
- "auto_delete": "Send the new Auto Delete duration in seconds (or 'off' to disable):",
353
- "custom_caption": "Send the new Custom Caption text (or 'off' to disable):",
354
- "caption_uname": "Send the new Caption Username starting with '@' (or 'off' to disable):",
355
- "shortener_site": "Send the new Site name (e.g. shortxlinks.com):",
356
- "shortener_api": "Send the new Shortener API Key:",
357
- "token_timeout": "Send the new Token validity time (e.g., '1h' for 1 hour, '30m' for 30 mins, or raw seconds):",
358
- "force_sub": "Send the new Force Subscription Channel ID (or 'off' to disable):",
359
- "channel_link": "Send the new Force Subscription Channel Link (or 'off' to disable):",
360
- "admins": "Send a comma-separated list of Admin User IDs (e.g. 12345, 67890):",
361
- "db_channels": "Send a comma-separated list of DB Channel IDs (e.g. -100123, -100456):",
362
- "log_channel": "Send the new User Search Logs Channel ID or username (or 'off' to disable):",
363
- "how_to_download": "Send the new How to Download/Verify URL (or 'off' to disable):"
364
- }
365
- prompt = prompt_map.get(action, "Send the new parameter value:")
366
- from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
367
- category_map = {
368
- "auto_delete": "gen",
369
- "custom_caption": "cap",
370
- "caption_uname": "cap",
371
- "shortener_site": "sho",
372
- "shortener_api": "sho",
373
- "token_timeout": "sho",
374
- "force_sub": "cha",
375
- "channel_link": "cha",
376
- "admins": "cha",
377
- "db_channels": "cha",
378
- "log_channel": "cha",
379
- "how_to_download": "gen"
380
- }
381
- cat = category_map.get(action, "main")
382
- keyboard = InlineKeyboardMarkup([[InlineKeyboardButton("❌ Cancel Configuration", callback_data=f"adm_cat:{cat}")]])
383
- await query.message.edit_text(text=f"⌨️ **{prompt}**", reply_markup=keyboard)
384
- await query.answer()
385
-
386
- async def handle_admin_input(bot, message):
387
- user_id = message.from_user.id
388
- state = ADMIN_INPUT_STATE.get(user_id)
389
- if not state:
390
- return
391
- action = state.get("action")
392
- menu_message_id = state.get("message_id")
393
- input_text = message.text.strip()
394
- try:
395
- await message.delete()
396
- except Exception:
397
- pass
398
- from mfinder.db.settings_sql import (
399
- set_auto_delete, set_custom_caption, set_force_sub, set_username, set_channel_link,
400
- set_shortener_settings, update_admins_list, update_db_channels_list, get_link,
401
- set_token_timeout, set_log_channel, set_how_to_download
402
- )
403
- from mfinder import ADMINS, DB_CHANNELS
404
- success = True
405
- err_msg = ""
406
- success_msg = ""
407
-
408
- if action == "set_auto_delete":
409
- if input_text.lower() in ("off", "disable", "disabled"):
410
- dur = 0
411
- await set_auto_delete(dur)
412
- success_msg = "Auto delete duration has been disabled."
413
- else:
414
- try:
415
- dur = int(input_text)
416
- if dur < 0:
417
- raise ValueError()
418
- await set_auto_delete(dur)
419
- success_msg = f"Auto delete duration set to `{dur}` seconds."
420
- except ValueError:
421
- success = False
422
- err_msg = "Must be a non-negative integer or 'off'."
423
-
424
- elif action == "set_custom_caption":
425
- if input_text.lower() in ("off", "disable", "disabled"):
426
- caption = None
427
- success_msg = "Custom caption has been disabled."
428
- else:
429
- caption = input_text
430
- success_msg = "Custom caption updated successfully."
431
- await set_custom_caption(caption)
432
-
433
- elif action == "set_caption_uname":
434
- if input_text.lower() in ("off", "disable", "disabled"):
435
- uname = None
436
- success_msg = "Caption username has been disabled."
437
- await set_username(uname)
438
- elif input_text.startswith("@"):
439
- uname = input_text
440
- success_msg = f"Caption username set to `{uname}`."
441
- await set_username(uname)
442
- else:
443
- success = False
444
- err_msg = "Must start with '@' (e.g. @mychannel) or 'off' to disable."
445
-
446
- elif action == "set_shortener_site":
447
- if input_text.lower() in ("off", "disable", "disabled"):
448
- site = None
449
- success_msg = "Shortener site has been cleared/disabled."
450
- await set_shortener_settings(site=site)
451
- elif " " in input_text or "." not in input_text:
452
- success = False
453
- err_msg = "Invalid domain name. It should not contain spaces and must contain at least one dot (e.g., shortxlinks.com)."
454
- else:
455
- site = input_text
456
- success_msg = f"Shortener site updated successfully to `{site}`."
457
- await set_shortener_settings(site=site)
458
-
459
- elif action == "set_shortener_api":
460
- if input_text.lower() in ("off", "disable", "disabled"):
461
- api = None
462
- success_msg = "Shortener API key has been cleared/disabled."
463
- await set_shortener_settings(api=api)
464
- elif not input_text:
465
- success = False
466
- err_msg = "API key cannot be empty."
467
- else:
468
- api = input_text
469
- success_msg = "Shortener API key updated successfully."
470
- await set_shortener_settings(api=api)
471
-
472
- elif action == "set_force_sub":
473
- if input_text.lower() in ("off", "disable", "disabled", "0"):
474
- await set_channel_link(None)
475
- await set_force_sub(0)
476
- success_msg = "Force subscription channel has been disabled."
477
- else:
478
- try:
479
- resolved_ids, links_list = await parse_and_set_forcesub(bot, input_text)
480
- success_msg = f"Force subscription channels set to: `{', '.join(resolved_ids)}`. Links: {', '.join(links_list)}"
481
- except Exception as e:
482
- success = False
483
- err_msg = f"Could not find or access channels: {str(e)}. Make sure the channels exist and the bot is added as an administrator."
484
-
485
- elif action == "set_channel_link":
486
- if input_text.lower() in ("off", "disable", "disabled"):
487
- await set_channel_link(None)
488
- success_msg = "Channel invite link has been removed."
489
- elif not (input_text.startswith("http://") or input_text.startswith("https://")):
490
- success = False
491
- err_msg = "Invalid URL. The link must start with 'http://' or 'https://'."
492
- else:
493
- await set_channel_link(input_text)
494
- success_msg = f"Channel invite link set to `{input_text}`."
495
-
496
- elif action == "set_admins":
497
- try:
498
- raw_ids = input_text.split(",")
499
- parsed_ids = []
500
- is_list_valid = True
501
- invalid_val = ""
502
- from mfinder import id_pattern
503
- for r_id in raw_ids:
504
- r_id = r_id.strip()
505
- if not r_id:
506
- continue
507
- if id_pattern.search(r_id):
508
- parsed_ids.append(int(r_id))
509
- else:
510
- is_list_valid = False
511
- invalid_val = r_id
512
- break
513
-
514
- if not is_list_valid:
515
- success = False
516
- err_msg = f"Invalid Admin ID `{invalid_val}`. Admins list must contain only comma-separated integer IDs."
517
- elif not parsed_ids:
518
- success = False
519
- err_msg = "Admins list cannot be empty."
520
- else:
521
- from mfinder import OWNER_ID
522
- if OWNER_ID not in parsed_ids:
523
- parsed_ids.append(OWNER_ID)
524
-
525
- admins_str = ",".join(str(i) for i in parsed_ids)
526
- await update_admins_list(admins_str)
527
-
528
- ADMINS.clear()
529
- ADMINS.extend(parsed_ids)
530
- success_msg = f"Admins list updated successfully with {len(parsed_ids)} admins."
531
- except Exception as e:
532
- success = False
533
- err_msg = f"Error parsing admins: {e}"
534
-
535
- elif action == "set_db_channels":
536
- try:
537
- raw_ids = input_text.split(",")
538
- parsed_ids = []
539
- is_list_valid = True
540
- invalid_val = ""
541
- from mfinder import id_pattern
542
- for r_id in raw_ids:
543
- r_id = r_id.strip()
544
- if not r_id:
545
- continue
546
- if id_pattern.search(r_id):
547
- parsed_ids.append(int(r_id))
548
- else:
549
- is_list_valid = False
550
- invalid_val = r_id
551
- break
552
-
553
- if not is_list_valid:
554
- success = False
555
- err_msg = f"Invalid Channel ID `{invalid_val}`. DB Channels list must contain only comma-separated integer IDs."
556
- else:
557
- channels_str = ",".join(str(i) for i in parsed_ids)
558
- await update_db_channels_list(channels_str)
559
-
560
- DB_CHANNELS.clear()
561
- DB_CHANNELS.extend(parsed_ids)
562
- success_msg = f"Database channels list updated successfully with {len(parsed_ids)} channels."
563
- except Exception as e:
564
- success = False
565
- err_msg = f"Error parsing DB channels: {e}"
566
-
567
- elif action == "set_token_timeout":
568
- val = input_text.lower().strip()
569
- parsed_seconds = None
570
-
571
- if val.endswith("h"):
572
- try:
573
- parsed_seconds = int(float(val[:-1]) * 3600)
574
- except ValueError:
575
- pass
576
- elif val.endswith("m"):
577
- try:
578
- parsed_seconds = int(float(val[:-1]) * 60)
579
- except ValueError:
580
- pass
581
- elif val.endswith("d"):
582
- try:
583
- parsed_seconds = int(float(val[:-1]) * 86400)
584
- except ValueError:
585
- pass
586
- elif val.endswith("s"):
587
- try:
588
- parsed_seconds = int(float(val[:-1]))
589
- except ValueError:
590
- pass
591
- else:
592
- try:
593
- parsed_seconds = int(val)
594
- except ValueError:
595
- pass
596
-
597
- if parsed_seconds is None or parsed_seconds <= 0:
598
- success = False
599
- err_msg = "Invalid format. Use e.g. '1h' (1 hour), '30m' (30 minutes), or a positive number of seconds."
600
- else:
601
- await set_token_timeout(parsed_seconds)
602
- if parsed_seconds >= 3600:
603
- hours = parsed_seconds / 3600
604
- time_desc = f"{hours:.1f} hours" if hours % 1 != 0 else f"{int(hours)} hours"
605
- elif parsed_seconds >= 60:
606
- mins = parsed_seconds / 60
607
- time_desc = f"{mins:.1f} minutes" if mins % 1 != 0 else f"{int(mins)} minutes"
608
- else:
609
- time_desc = f"{parsed_seconds} seconds"
610
-
611
- success_msg = f"Token validity duration set to `{parsed_seconds}` seconds ({time_desc})."
612
-
613
- elif action == "set_log_channel":
614
- if input_text.lower() in ("off", "disable", "disabled", "0"):
615
- await set_log_channel(None)
616
- success_msg = "User search logging channel has been disabled."
617
- else:
618
- channel_str = input_text
619
- is_valid_id = False
620
- if channel_str.startswith("@") and len(channel_str) > 1:
621
- is_valid_id = True
622
- channel_param = channel_str
623
- else:
624
- try:
625
- channel_param = int(channel_str)
626
- is_valid_id = True
627
- except ValueError:
628
- pass
629
-
630
- if not is_valid_id:
631
- success = False
632
- err_msg = "Must be a valid integer ID (e.g., -100123456789) or username starting with '@'."
633
- else:
634
- try:
635
- chat = await bot.get_chat(channel_param)
636
- access_hash = None
637
- try:
638
- resolved = await bot.resolve_peer(chat.id)
639
- if getattr(resolved, "access_hash", None):
640
- access_hash = resolved.access_hash
641
- except Exception:
642
- pass
643
- await set_log_channel(chat.id, access_hash=access_hash)
644
- success_msg = f"User search logging channel set to `{chat.id}` ({chat.title or 'Channel'})."
645
- except Exception as e:
646
- success = False
647
- err_msg = f"Could not find or access the channel: {str(e)}. Make sure the channel exists and the bot is added as an administrator."
648
-
649
- elif action == "set_how_to_download":
650
- if input_text.lower() in ("off", "disable", "disabled"):
651
- await set_how_to_download(None)
652
- success_msg = "How to Download/Verify URL has been disabled/removed."
653
- elif not (input_text.startswith("http://") or input_text.startswith("https://")):
654
- success = False
655
- err_msg = "Invalid URL. The link must start with 'http://' or 'https://'."
656
- else:
657
- await set_how_to_download(input_text)
658
- success_msg = f"How to Download URL set to `{input_text}`."
659
-
660
- else:
661
- success = False
662
- err_msg = "Unknown action."
663
-
664
- from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
665
- category_map = {
666
- "set_auto_delete": "gen",
667
- "set_custom_caption": "cap",
668
- "set_caption_uname": "cap",
669
- "set_shortener_site": "sho",
670
- "set_shortener_api": "sho",
671
- "set_token_timeout": "sho",
672
- "set_force_sub": "cha",
673
- "set_channel_link": "cha",
674
- "set_admins": "cha",
675
- "set_db_channels": "cha",
676
- "set_log_channel": "cha",
677
- "set_how_to_download": "gen"
678
- }
679
- cat = category_map.get(action, "main")
680
-
681
- if success:
682
- ADMIN_INPUT_STATE.pop(user_id, None)
683
- keyboard = InlineKeyboardMarkup([
684
- [InlineKeyboardButton("⬅️ Back", callback_data=f"adm_cat:{cat}")]
685
- ])
686
- text_to_send = f"✅ {success_msg}\n\nClick back to configure other settings."
687
- else:
688
- keyboard = InlineKeyboardMarkup([
689
- [InlineKeyboardButton("❌ Cancel Configuration", callback_data=f"adm_cat:{cat}")]
690
- ])
691
- prompt_map = {
692
- "set_auto_delete": "Send the new Auto Delete duration in seconds (or 'off' to disable):",
693
- "set_custom_caption": "Send the new Custom Caption text (or 'off' to disable):",
694
- "set_caption_uname": "Send the new Caption Username starting with '@' (or 'off' to disable):",
695
- "set_shortener_site": "Send the new Site name (e.g. shortxlinks.com):",
696
- "set_shortener_api": "Send the new Shortener API Key:",
697
- "set_token_timeout": "Send the new Token validity time (e.g., '1h' for 1 hour, '30m' for 30 mins, or raw seconds):",
698
- "set_force_sub": "Send the new Force Subscription Channel ID (or 'off' to disable):",
699
- "set_channel_link": "Send the new Force Subscription Channel Link (or 'off' to disable):",
700
- "set_admins": "Send a comma-separated list of Admin User IDs (e.g. 12345, 67890):",
701
- "set_db_channels": "Send a comma-separated list of DB Channel IDs (e.g. -100123, -100456):",
702
- "set_log_channel": "Send the new User Search Logs Channel ID or username (or 'off' to disable):",
703
- "set_how_to_download": "Send the new How to Download/Verify URL (or 'off' to disable):"
704
- }
705
- original_prompt = prompt_map.get(action, "Send the new parameter value:")
706
- text_to_send = f"⚠️ **Invalid input:** `{err_msg}`\n\n⌨️ **{original_prompt}**"
707
-
708
- try:
709
- await bot.edit_message_text(
710
- chat_id=user_id,
711
- message_id=menu_message_id,
712
- text=text_to_send,
713
- reply_markup=keyboard
714
- )
715
- except Exception:
716
- try:
717
- await bot.send_message(user_id, text_to_send, reply_markup=keyboard)
718
- except Exception:
719
- pass
720
-
721
-
722
- @Client.on_message(filters.command(["ban"]) & filters.user(ADMINS))
723
- async def banuser(bot, update):
724
- data = update.text.split()
725
- if len(data) == 2:
726
- user_id = data[-1]
727
- banned = await is_banned(int(user_id))
728
- if not banned:
729
- await ban_user(int(user_id))
730
- await update.reply_text(f"User {user_id} banned")
731
- else:
732
- await update.reply_text(f"User {user_id} is already banned")
733
-
734
- else:
735
- await update.reply_text("Please send in proper format `/ban user_id`")
736
-
737
-
738
- @Client.on_message(filters.command(["unban"]) & filters.user(ADMINS))
739
- async def unbanuser(bot, update):
740
- data = update.text.split()
741
- if len(data) == 2:
742
- user_id = data[-1]
743
- banned = await is_banned(int(user_id))
744
- if banned:
745
- await unban_user(int(user_id))
746
- await update.reply_text(f"User {user_id} unbanned")
747
- else:
748
- await update.reply_text(f"User {user_id} is not in ban list")
749
- else:
750
- await update.reply_text("Please send in proper format `/unban user_id`")
751
-
752
-
753
- @Client.on_message(filters.command(["addfilter"]) & filters.user(ADMINS))
754
- async def addfilter(bot, update):
755
- data = shlex.split(update.text)
756
- if len(data) >= 3:
757
- fltr = data[1].strip('"').lower()
758
- message = " ".join(data[2:])
759
- add = await add_filter(fltr, message)
760
- if add:
761
- await update.reply_text(f"Filter `{fltr}` added")
762
- else:
763
- await update.reply_text(f"Filter `{fltr}` already exists")
764
- else:
765
- await update.reply_text(
766
- "Please send in proper format `/addfilter filter message`"
767
- )
768
-
769
-
770
- @Client.on_message(filters.command(["delfilter"]) & filters.user(ADMINS))
771
- async def delfilter(bot, update):
772
- data = update.text.split()
773
- if len(data) >= 2:
774
- fltr = " ".join(data[1:])
775
- rem = await rem_filter(fltr)
776
- if rem:
777
- await update.reply_text(f"Filter `{fltr}` removed")
778
- else:
779
- await update.reply_text(f"Filter `{fltr}` not found")
780
- else:
781
- await update.reply_text("Please send in proper format `/delfilter filter`")
782
-
783
-
784
- @Client.on_message(filters.command(["listfilters"]) & filters.user(ADMINS))
785
- async def list_filter(bot, update):
786
- fltr = await list_filters()
787
- fltr_msg = ""
788
- if fltr:
789
- for fltrs in fltr:
790
- fltr_msg += "\n" + "`" + fltrs + "`"
791
- await update.reply_text(f"**Available Filters:** {fltr_msg}")
792
- else:
793
- await update.reply_text("No filters found")
794
-
795
-
796
- @Client.on_message(filters.command(["forcesub"]) & filters.user(ADMINS))
797
- async def force_sub(bot, update):
798
- data = update.text.split()
799
- if len(data) == 2:
800
- channel_str = data[-1]
801
- if channel_str.lower() == "off":
802
- await set_channel_link(None)
803
- await set_force_sub(0)
804
- await update.reply_text("Force Subscription disabled")
805
- return
806
-
807
- try:
808
- resolved_ids, links_list = await parse_and_set_forcesub(bot, channel_str)
809
- await update.reply_text(f"Force subscription channels set to: `{', '.join(resolved_ids)}`. Links: {', '.join(links_list)}")
810
- except Exception as e:
811
- await update.reply_text(
812
- f"❌ Error setting force subscription: {str(e)}. Make sure the channels exist and the bot is added as an administrator."
813
- )
814
-
815
- else:
816
- await update.reply_text(
817
- "Please send in proper format `/forcesub channel_id/off`"
818
- )
819
-
820
-
821
- @Client.on_message(filters.command(["logchannel"]) & filters.user(ADMINS))
822
- async def log_channel_(bot, update):
823
- data = update.text.split()
824
- if len(data) == 2:
825
- channel_str = data[-1]
826
- if channel_str.lower() == "off":
827
- await set_log_channel(None)
828
- await update.reply_text("User search logging disabled.")
829
- return
830
-
831
- try:
832
- if channel_str.startswith("@"):
833
- channel_param = channel_str
834
- else:
835
- channel_param = int(channel_str)
836
-
837
- chat = await bot.get_chat(channel_param)
838
- access_hash = None
839
- try:
840
- resolved = await bot.resolve_peer(chat.id)
841
- if getattr(resolved, "access_hash", None):
842
- access_hash = resolved.access_hash
843
- except Exception:
844
- pass
845
- await set_log_channel(chat.id, access_hash=access_hash)
846
- await update.reply_text(f"User search logging channel set to `{chat.id}` ({chat.title or 'Channel'}).")
847
- except Exception as e:
848
- await update.reply_text(
849
- f"❌ Error setting log channel: {str(e)}. Make sure the channel exists and the bot is added as an administrator."
850
- )
851
- else:
852
- await update.reply_text(
853
- "Please send in proper format `/logchannel channel_id/off`"
854
- )
855
-
856
-
857
- @Client.on_message(filters.command(["checklink"]) & filters.user(ADMINS))
858
- async def testlink(bot, update):
859
- link = await get_link()
860
- if link:
861
- await update.reply_text(f"Invite link for force subscription channel: {link}")
862
- else:
863
- await update.reply_text(
864
- "Force Subscription is disabled, please enable it first"
865
- )
866
-
867
-
868
- @Client.on_message(filters.command(["setusername"]) & filters.user(ADMINS))
869
- async def caption_username(bot, update):
870
- data = update.text.split()
871
- if len(data) == 2:
872
- username = data[-1]
873
- if username.lower() == "off":
874
- username = 0
875
- elif username.startswith("@"):
876
- username = username
877
- else:
878
- await update.reply_text("This is not a username, please check.")
879
- return
880
-
881
- await set_username(username)
882
-
883
- if username:
884
- await update.reply_text(f"File caption username set to `{username}`")
885
- else:
886
- await update.reply_text("File caption username disabled")
887
-
888
- else:
889
- await update.reply_text(
890
- "Please send in proper format `/setusername username/off`"
891
- )
892
-
893
-
894
- @Client.on_message(filters.command(["total"]) & filters.user(ADMINS))
895
- async def count_f(bot, update):
896
- count = await count_files()
897
- await update.reply_text(f"**Total no. of files in DB:** `{count}`")
898
-
899
- async def parse_and_set_forcesub(bot, channel_str):
900
- channels = [ch.strip() for ch in channel_str.split(',') if ch.strip()]
901
- resolved_ids = []
902
- hashes_map = {}
903
- links_list = []
904
-
905
- for ch in channels:
906
- try:
907
- ch_param = int(ch)
908
- except ValueError:
909
- ch_param = ch if ch.startswith("@") else f"@{ch}"
910
- chat = await bot.get_chat(ch_param)
911
- resolved_ids.append(str(chat.id))
912
-
913
- # Resolve access hash
914
- access_hash = None
915
- try:
916
- resolved = await bot.resolve_peer(chat.id)
917
- if getattr(resolved, "access_hash", None):
918
- access_hash = resolved.access_hash
919
- except Exception:
920
- pass
921
- if access_hash is not None:
922
- hashes_map[str(chat.id)] = access_hash
923
-
924
- # Link resolving
925
- link = None
926
- try:
927
- link_obj = await bot.create_chat_invite_link(chat.id)
928
- link = link_obj.invite_link
929
- except Exception:
930
- if chat.username:
931
- link = f"https://t.me/{chat.username}"
932
- if link:
933
- links_list.append(link)
934
-
935
- if not resolved_ids:
936
- raise ValueError("No valid channels could be resolved.")
937
-
938
- from mfinder.db.settings_sql import set_force_sub_channels, set_channel_link
939
- await set_force_sub_channels(",".join(resolved_ids), hashes_map)
940
- if links_list:
941
- await set_channel_link(links_list[0])
942
-
943
- return resolved_ids, links_list
944
-
945
-
946
- async def verify_user_token(bot, update, param):
947
- import time
948
- import asyncio
949
- from mfinder import LOGGER
950
- from mfinder.db.settings_sql import get_user_token, activate_user_token, get_admin_settings, prune_all_expired_tokens
951
-
952
- # Clean up any other expired or stale tokens
953
- await prune_all_expired_tokens()
954
-
955
- user_id = update.from_user.id
956
- token_str = param
957
-
958
- tok_rec = await get_user_token(user_id)
959
-
960
- if not tok_rec or tok_rec.token != token_str:
961
- if tok_rec and tok_rec.req_msg_id:
962
- try:
963
- await bot.delete_messages(chat_id=user_id, message_ids=int(tok_rec.req_msg_id))
964
- except Exception as e:
965
- LOGGER.warning(f"Failed to delete original token request message: {e}")
966
- err_msg = await update.reply_text(
967
- "❌ **Invalid token link!**\n\nPlease search for a movie again to generate a new verification link.",
968
- quote=True
969
- )
970
- async def delete_after_delay(b, u_id, err_msg_id, incoming_msg_id):
971
- await asyncio.sleep(10)
972
- try:
973
- await b.delete_messages(chat_id=u_id, message_ids=[err_msg_id, incoming_msg_id])
974
- except Exception:
975
- pass
976
- asyncio.create_task(delete_after_delay(bot, user_id, err_msg.id, update.id))
977
- return
978
-
979
- # Check if the token has already been claimed/activated
980
- if tok_rec.status == "active":
981
- if tok_rec.target_file_id:
982
- update.text = f"/start {tok_rec.target_file_id}"
983
- from mfinder.plugins.serve import get_files
984
- await get_files(bot, update)
985
- return
986
- elif tok_rec.search_query:
987
- from mfinder.plugins.serve import filter_
988
- update.text = tok_rec.search_query
989
- await filter_(bot, update)
990
- return
991
- else:
992
- await update.reply_text(
993
- "✅ **Token Verified Successfully!**\n\nYou already have direct, ad-free access to all movies and files.",
994
- quote=True
995
- )
996
- return
997
-
998
- current_time = time.time()
999
- if tok_rec.status == "pending" and (current_time - float(tok_rec.created_at)) > 1800:
1000
- if tok_rec.req_msg_id:
1001
- try:
1002
- await bot.delete_messages(chat_id=user_id, message_ids=int(tok_rec.req_msg_id))
1003
- except Exception as e:
1004
- LOGGER.warning(f"Failed to delete original token request message: {e}")
1005
- from mfinder.db.settings_sql import delete_user_token
1006
- await delete_user_token(user_id)
1007
- err_msg = await update.reply_text(
1008
- "❌ **Verification link has expired!**\n\nThe link is only valid to be claimed within 30 minutes of generation. Please search for a movie again to get a new link.",
1009
- quote=True
1010
- )
1011
- async def delete_after_delay(b, u_id, err_msg_id, incoming_msg_id):
1012
- await asyncio.sleep(10)
1013
- try:
1014
- await b.delete_messages(chat_id=u_id, message_ids=[err_msg_id, incoming_msg_id])
1015
- except Exception:
1016
- pass
1017
- asyncio.create_task(delete_after_delay(bot, user_id, err_msg.id, update.id))
1018
- return
1019
-
1020
- admin_settings = await get_admin_settings()
1021
- timeout = float(admin_settings.token_timeout) if admin_settings and admin_settings.token_timeout else 3600
1022
- expires_at = current_time + timeout
1023
-
1024
- success = await activate_user_token(user_id, expires_at)
1025
- if not success:
1026
- await update.reply_text(
1027
- "❌ **Verification failed due to database error!** Please try again later.",
1028
- quote=True
1029
- )
1030
- return
1031
-
1032
- if timeout >= 3600:
1033
- hours = timeout / 3600
1034
- time_desc = f"{hours:.1f} hours" if hours % 1 != 0 else f"{int(hours)} hours"
1035
- elif timeout >= 60:
1036
- mins = timeout / 60
1037
- time_desc = f"{mins:.1f} minutes" if mins % 1 != 0 else f"{int(mins)} minutes"
1038
- else:
1039
- time_desc = f"{timeout} seconds"
1040
-
1041
- if tok_rec.req_msg_id:
1042
- try:
1043
- await bot.delete_messages(chat_id=user_id, message_ids=int(tok_rec.req_msg_id))
1044
- except Exception as e:
1045
- LOGGER.warning(f"Failed to delete original token request message: {e}")
1046
-
1047
- verified_msg = await update.reply_text(
1048
- f"✅ **Token Verified Successfully!**\n\nYou now have direct, ad-free access to all movies and files for the next **{time_desc}**.\n\nEnjoy!",
1049
- quote=True
1050
- )
1051
-
1052
- async def delete_after_delay(b, u_id, success_msg_id, incoming_msg_id):
1053
- await asyncio.sleep(10)
1054
- try:
1055
- await b.delete_messages(chat_id=u_id, message_ids=[success_msg_id, incoming_msg_id])
1056
- except Exception as e:
1057
- LOGGER.warning(f"Failed to auto-delete verification messages: {e}")
1058
-
1059
- asyncio.create_task(delete_after_delay(bot, user_id, verified_msg.id, update.id))
1060
-
1061
- search_q = tok_rec.search_query
1062
- target_f_id = tok_rec.target_file_id
1063
-
1064
- if search_q:
1065
- try:
1066
- from mfinder.plugins.serve import filter_
1067
- update.text = search_q
1068
- await asyncio.sleep(0.5)
1069
- await filter_(bot, update)
1070
- except Exception as e:
1071
- LOGGER.warning(f"Error auto-resuming search query '{search_q}': {e}")
1072
- elif target_f_id:
1073
- try:
1074
- from mfinder.plugins.serve import get_files
1075
- update.text = f"/start {target_f_id}"
1076
- await asyncio.sleep(0.5)
1077
- await get_files(bot, update)
1078
- except Exception as e:
1079
- LOGGER.warning(f"Error auto-resuming file download for '{target_f_id}': {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/plugins/broadcast.py DELETED
@@ -1,75 +0,0 @@
1
- import asyncio
2
- import time
3
- import datetime
4
- from pyrogram.types import Message
5
- from pyrogram import Client, filters
6
- from pyrogram.errors import FloodWait
7
- from mfinder import LOGGER
8
- from mfinder.db.db_support import users_info
9
- from mfinder.db.broadcast_sql import query_msg
10
- from mfinder import ADMINS, OWNER_ID
11
-
12
-
13
- @Client.on_message(
14
- filters.private & filters.command("stats") & filters.user(ADMINS)
15
- )
16
- async def get_subscribers_count(bot: Client, message: Message):
17
- wait_msg = "__Calculating, please wait...__"
18
- msg = await message.reply_text(wait_msg)
19
- active, blocked = await users_info(bot)
20
- stats_msg = f"**Stats**\nSubscribers: `{active}`\nBlocked / Deleted: `{blocked}`"
21
- await msg.edit(stats_msg)
22
-
23
-
24
- @Client.on_message(
25
- filters.private & filters.command("broadcast") & filters.user(OWNER_ID)
26
- )
27
- async def send_text(bot, message: Message):
28
- user_id = message.from_user.id
29
- if "broadcast" in message.text and message.reply_to_message is not None:
30
- start_time = time.time()
31
- await message.reply_text("Starting broadcast, content below...")
32
- await bot.copy_message(
33
- chat_id=user_id,
34
- from_chat_id=message.chat.id,
35
- message_id=message.reply_to_message_id,
36
- # caption=message.reply_to_message.caption,
37
- reply_markup=message.reply_to_message.reply_markup,
38
- )
39
- query = await query_msg()
40
- success = 0
41
- failed = 0
42
- for row in query:
43
- chat_id = int(row[0])
44
- br_msg = bool()
45
- try:
46
- br_msg = await bot.copy_message(
47
- chat_id=chat_id,
48
- from_chat_id=message.chat.id,
49
- message_id=message.reply_to_message_id,
50
- # caption=message.reply_to_message.caption,
51
- reply_markup=message.reply_to_message.reply_markup,
52
- )
53
- LOGGER.info("Broadcast sent to %s", chat_id)
54
- except FloodWait as e:
55
- LOGGER.warning("Floodwait while broadcasting, sleeping for %s", e.value)
56
- await asyncio.sleep(e.value)
57
- except Exception:
58
- pass
59
-
60
- if bool(br_msg):
61
- success += 1
62
- else:
63
- failed += 1
64
- time_taken = datetime.timedelta(seconds=int(time.time() - start_time))
65
- await message.reply_text(
66
- f"**Broadcast Completed**\nSent to: `{success}`\nBlocked / Deleted: `{failed}`\nCompleted in `{time_taken}` HH:MM:SS"
67
- )
68
-
69
- else:
70
- reply_error = (
71
- "`Use this command as a reply to any telegram message without any spaces.`"
72
- )
73
- msg = await message.reply_text(reply_error, message.id)
74
- await asyncio.sleep(8)
75
- await msg.delete()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/plugins/commands.py DELETED
@@ -1,254 +0,0 @@
1
- import os
2
- import sys
3
- import asyncio
4
- import time
5
- import shutil
6
- from psutil import cpu_percent, virtual_memory, disk_usage
7
- from pyrogram import Client, filters
8
- from mfinder.db.broadcast_sql import add_user
9
- from mfinder.db.settings_sql import get_search_settings, change_search_settings
10
- from mfinder.utils.constants import STARTMSG, HELPMSG
11
- from mfinder import LOGGER, ADMINS, START_MSG, HELP_MSG, START_KB, HELP_KB
12
- from mfinder.utils.util_support import humanbytes, get_db_size
13
- from mfinder.plugins.serve import get_files
14
-
15
-
16
- def get_dynamic_start_kb():
17
- from mfinder.db.settings_sql import get_admin_settings_sync
18
- from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
19
- admin_settings = get_admin_settings_sync()
20
- how_to_download_url = admin_settings.how_to_download if admin_settings and admin_settings.how_to_download else "https://telegram.me/FIREBOLTTutorial/23"
21
- return InlineKeyboardMarkup(
22
- [
23
- [
24
- InlineKeyboardButton("🔥 Trending", callback_data="trnd_list"),
25
- InlineKeyboardButton("🆕 New Uploads", callback_data="new_up_list"),
26
- ],
27
- [
28
- InlineKeyboardButton("🆘 Help", callback_data="help_cb"),
29
- InlineKeyboardButton(
30
- "📞 Contact", url="https://telegram.me/ANGRY_BIRD22_bot"
31
- )
32
- ],
33
- [
34
- InlineKeyboardButton(
35
- "❓ How To Download ❓", url=how_to_download_url
36
- )
37
- ],
38
- ]
39
- )
40
-
41
-
42
- @Client.on_message(filters.command(["start"]))
43
- async def start(bot, update):
44
- if len(update.command) == 1:
45
- user_id = update.from_user.id
46
- name = update.from_user.first_name if update.from_user.first_name else " "
47
- user_name = (
48
- "@" + update.from_user.username if update.from_user.username else None
49
- )
50
- await add_user(user_id, user_name)
51
-
52
- try:
53
- start_msg = START_MSG.format(name, user_id)
54
- except Exception as e:
55
- LOGGER.warning(e)
56
- start_msg = STARTMSG.format(name, user_id)
57
-
58
- await bot.send_message(
59
- chat_id=update.chat.id,
60
- text=start_msg,
61
- reply_to_message_id=update.reply_to_message_id,
62
- reply_markup=get_dynamic_start_kb(),
63
- )
64
- search_settings = await get_search_settings(user_id)
65
- if not search_settings:
66
- await change_search_settings(user_id, link_mode=True)
67
- elif len(update.command) == 2:
68
- param = update.command[1]
69
- from mfinder.plugins.serve import verify_force_sub
70
- if param.startswith("tok_"):
71
- if not await verify_force_sub(bot, update):
72
- return
73
- from mfinder.plugins.admin_settings import verify_user_token
74
- await verify_user_token(bot, update, param)
75
- else:
76
- if not await verify_force_sub(bot, update, pending_file_id=param):
77
- return
78
- user_id = update.from_user.id
79
- from mfinder.db.settings_sql import get_admin_settings
80
- admin_settings = await get_admin_settings()
81
- if admin_settings and admin_settings.token_shortener_enabled:
82
- from mfinder import ADMINS
83
- if user_id not in ADMINS:
84
- from mfinder.plugins.serve import is_token_valid, create_and_send_token_link
85
- if not await is_token_valid(user_id):
86
- await create_and_send_token_link(bot, update, admin_settings, target_file_id=param)
87
- return
88
- await get_files(bot, update)
89
-
90
-
91
- @Client.on_message(filters.command(["help"]))
92
- async def help_m(bot, update):
93
- from mfinder.plugins.serve import verify_force_sub
94
- if not await verify_force_sub(bot, update):
95
- return
96
- try:
97
- help_msg = HELP_MSG
98
- except Exception as e:
99
- LOGGER.warning(e)
100
- help_msg = HELPMSG
101
-
102
- await bot.send_message(
103
- chat_id=update.chat.id,
104
- text=help_msg,
105
- reply_to_message_id=update.reply_to_message_id,
106
- reply_markup=HELP_KB,
107
- )
108
-
109
-
110
- @Client.on_callback_query(filters.regex(r"^back_m$"))
111
- async def back(bot, query):
112
- from mfinder.plugins.serve import verify_force_sub
113
- if not await verify_force_sub(bot, query):
114
- return
115
- user_id = query.from_user.id
116
- name = query.from_user.first_name if query.from_user.first_name else " "
117
- try:
118
- start_msg = START_MSG.format(name, user_id)
119
- except Exception as e:
120
- LOGGER.warning(e)
121
- start_msg = STARTMSG
122
- await query.message.edit_text(start_msg, reply_markup=get_dynamic_start_kb())
123
-
124
-
125
- @Client.on_callback_query(filters.regex(r"^help_cb$"))
126
- async def help_cb(bot, query):
127
- from mfinder.plugins.serve import verify_force_sub
128
- if not await verify_force_sub(bot, query):
129
- return
130
- try:
131
- help_msg = HELP_MSG
132
- except Exception as e:
133
- LOGGER.warning(e)
134
- help_msg = HELPMSG
135
- await query.message.edit_text(help_msg, reply_markup=HELP_KB)
136
-
137
-
138
- @Client.on_callback_query(filters.regex(r"^verify_fsub$"))
139
- async def verify_fsub_cb(bot, query):
140
- user_id = query.from_user.id
141
- from mfinder.plugins.serve import verify_force_sub
142
- if not await verify_force_sub(bot, query):
143
- return
144
-
145
- try:
146
- await query.message.edit_reply_markup(reply_markup=None)
147
- except Exception:
148
- pass
149
-
150
- from mfinder.db.settings_sql import get_pending_fsub_request, delete_pending_fsub_request
151
- pending = await get_pending_fsub_request(user_id)
152
- if not pending:
153
- await query.answer("✅ Verification successful! You can now use the bot.", show_alert=True)
154
- try:
155
- await query.message.delete()
156
- except Exception:
157
- pass
158
- return
159
-
160
- try:
161
- await query.message.delete()
162
- except Exception:
163
- pass
164
-
165
- search_q = pending.search_query
166
- target_f_id = pending.target_file_id
167
-
168
- await delete_pending_fsub_request(user_id)
169
-
170
- if search_q:
171
- try:
172
- from pyrogram.types import Message
173
- mock_msg = Message(
174
- id=query.message.id,
175
- chat=query.message.chat,
176
- from_user=query.from_user,
177
- text=search_q,
178
- date=query.message.date
179
- )
180
- mock_msg._client = bot
181
- if search_q.startswith("/"):
182
- if search_q == "/trending":
183
- from mfinder.plugins.trending import trending_command
184
- await trending_command(bot, mock_msg)
185
- elif search_q == "/newuploads":
186
- from mfinder.plugins.trending import new_uploads_command
187
- await new_uploads_command(bot, mock_msg)
188
- else:
189
- from mfinder.plugins.serve import filter_
190
- await filter_(bot, mock_msg)
191
- except Exception as e:
192
- LOGGER.warning(f"Error auto-resuming pending search '{search_q}': {e}")
193
- elif target_f_id:
194
- try:
195
- from mfinder.plugins.serve import get_files
196
- from pyrogram.types import Message
197
- mock_msg = Message(
198
- id=query.message.id,
199
- chat=query.message.chat,
200
- from_user=query.from_user,
201
- text=f"/start {target_f_id}",
202
- date=query.message.date
203
- )
204
- mock_msg._client = bot
205
- await get_files(bot, mock_msg)
206
- except Exception as e:
207
- LOGGER.warning(f"Error auto-resuming pending download for '{target_f_id}': {e}")
208
-
209
-
210
- @Client.on_message(filters.command(["restart"]) & filters.user(ADMINS))
211
- async def restart(bot, update):
212
- LOGGER.warning("Restarting bot using /restart command")
213
- msg = await update.reply_text(text="__Restarting.....__")
214
- await asyncio.sleep(5)
215
- await msg.edit("__Bot restarted !__")
216
- os.execv(sys.executable, ["python3", "-m", "mfinder"] + sys.argv)
217
-
218
-
219
- @Client.on_message(filters.command(["logs"]) & filters.user(ADMINS))
220
- async def log_file(bot, update):
221
- logs_msg = await update.reply("__Sending logs, please wait...__")
222
- try:
223
- await update.reply_document("logs.txt")
224
- except Exception as e:
225
- await update.reply(str(e))
226
- await logs_msg.delete()
227
-
228
-
229
- @Client.on_message(filters.command(["server"]) & filters.user(ADMINS))
230
- async def server_stats(bot, update):
231
- sts = await update.reply_text("__Calculating, please wait...__")
232
- total, used, free = shutil.disk_usage(".")
233
- ram = virtual_memory()
234
- start_t = time.time()
235
- end_t = time.time()
236
- time_taken_s = (end_t - start_t) * 1000
237
-
238
- ping = f"{time_taken_s:.3f} ms"
239
- total = humanbytes(total)
240
- used = humanbytes(used)
241
- free = humanbytes(free)
242
- t_ram = humanbytes(ram.total)
243
- u_ram = humanbytes(ram.used)
244
- f_ram = humanbytes(ram.available)
245
- cpu_usage = cpu_percent()
246
- ram_usage = virtual_memory().percent
247
- used_disk = disk_usage("/").percent
248
- db_size = get_db_size()
249
-
250
- stats_msg = f"--**BOT STATS**--\n`Ping: {ping}`\n\n--**SERVER DETAILS**--\n`Disk Total/Used/Free: {total}/{used}/{free}\nDisk usage: {used_disk}%\nRAM Total/Used/Free: {t_ram}/{u_ram}/{f_ram}\nRAM Usage: {ram_usage}%\nCPU Usage: {cpu_usage}%`\n\n--**DATABASE DETAILS**--\n`Size: {db_size} MB`"
251
- try:
252
- await sts.edit(stats_msg)
253
- except Exception as e:
254
- await update.reply_text(str(e))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/plugins/index.py DELETED
@@ -1,145 +0,0 @@
1
- import asyncio
2
- from pyrogram import Client, filters
3
- from pyrogram.errors import FloodWait
4
- from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
5
- from mfinder import ADMINS, LOGGER
6
- from mfinder.db.files_sql import save_file, delete_file
7
- from mfinder.utils.helpers import edit_caption
8
-
9
- lock = asyncio.Lock()
10
- media_filter = filters.document | filters.video | filters.audio
11
- DELETING_USERS = set()
12
-
13
- @Client.on_message(filters.private & filters.user(ADMINS) & media_filter)
14
- async def index_files(bot, message):
15
- user_id = message.from_user.id
16
- if user_id in DELETING_USERS:
17
- try:
18
- for file_type in ("document", "video", "audio"):
19
- media = getattr(message, file_type, None)
20
- if not media:
21
- continue
22
- del_file = await delete_file(media)
23
- if del_file == "Not Found":
24
- await message.reply(f"❌ `{media.file_name}` not found in database.")
25
- elif del_file == True:
26
- await message.reply(f"🗑️ `{media.file_name}` deleted from database successfully!")
27
- else:
28
- await message.reply(f"⚠️ Error occurred while deleting `{media.file_name}`.")
29
- except Exception as e:
30
- LOGGER.warning("Error occurred during bulk delete: %s", str(e))
31
- return
32
-
33
- if lock.locked():
34
- await message.reply("Wait until previous process complete.")
35
- else:
36
- try:
37
- last_msg_id = message.forward_from_message_id
38
- chat_id = message.forward_from_chat.username or message.forward_from_chat.id
39
- await bot.get_messages(chat_id, last_msg_id)
40
-
41
- kb = InlineKeyboardMarkup(
42
- [
43
- [InlineKeyboardButton("Proceed", callback_data=f"index {chat_id} {last_msg_id}")],
44
- [InlineKeyboardButton("Cancel", callback_data="can-index")],
45
- ]
46
- )
47
- await bot.send_message(user_id, "Please confirm if you want to start indexing", reply_markup=kb)
48
- except Exception as e:
49
- await message.reply_text(f"Unable to start indexing. Error: <code>{e}</code>")
50
-
51
- @Client.on_callback_query(filters.regex(r"^index -?\d+ \d+"))
52
- async def index(bot, query):
53
- user_id = query.from_user.id
54
- chat_id, last_msg_id = map(int, query.data.split()[1:])
55
- await query.message.delete()
56
- msg = await bot.send_message(user_id, "Processing Index...⏳")
57
- total_files = 0
58
- async with lock:
59
- try:
60
- total = last_msg_id + 1
61
- current = 2
62
- counter = 0
63
- while True:
64
- try:
65
- message = await bot.get_messages(chat_id=chat_id, message_ids=current, replies=0)
66
- except FloodWait as e:
67
- LOGGER.warning("FloodWait while indexing, Error: %s", str(e))
68
- await asyncio.sleep(e.value)
69
- except Exception as e:
70
- LOGGER.warning("Error occurred while fetching message: %s", str(e))
71
- try:
72
- for file_type in ("document", "video", "audio"):
73
- media = getattr(message, file_type, None)
74
- if not media:
75
- break
76
- file_name = media.file_name
77
- file_name = edit_caption(file_name)
78
- media.file_type = file_type
79
- media.caption = message.caption if message.caption else file_name
80
- await save_file(media)
81
- total_files += 1
82
- except Exception as e:
83
- LOGGER.warning("Error occurred while saving file: %s", str(e))
84
-
85
- current += 1
86
- counter += 1
87
- if counter == 50:
88
- try:
89
- await msg.edit(f"Total messages fetched: {current}\nTotal messages saved: {total_files}")
90
- except FloodWait as e:
91
- LOGGER.warning("FloodWait while indexing, sleeping for: %s", str(e.value))
92
- await asyncio.sleep(e.value)
93
- counter -= 50
94
- if current == total:
95
- break
96
- except Exception as e:
97
- LOGGER.exception(e)
98
- await msg.edit(f"Error: {e}")
99
- else:
100
- await msg.edit(f"Total {total_files} Saved To DataBase!")
101
-
102
- @Client.on_message(filters.command(["index"]) & filters.user(ADMINS))
103
- async def index_comm(bot, update):
104
- await update.reply("Now please forward the last message of the channel you want to index & follow the steps. Bot must be admin of the channel if the channel is private.")
105
-
106
- @Client.on_message(filters.command(["delete"]) & filters.user(ADMINS))
107
- async def delete_files(bot, message):
108
- if message.reply_to_message:
109
- org_msg = message.reply_to_message
110
- try:
111
- for file_type in ("document", "video", "audio"):
112
- media = getattr(org_msg, file_type, None)
113
- if not media:
114
- break
115
- del_file = await delete_file(media)
116
- if del_file == "Not Found":
117
- await message.reply(f"❌ `{media.file_name}` not found in database")
118
- elif del_file == True:
119
- await message.reply(f"🗑️ `{media.file_name}` deleted from database")
120
- else:
121
- await message.reply(f"⚠️ Error occurred while deleting `{media.file_name}`")
122
- except Exception as e:
123
- LOGGER.warning("Error occurred while deleting file: %s", str(e))
124
- else:
125
- user_id = message.from_user.id
126
- DELETING_USERS.add(user_id)
127
- await message.reply(
128
- "🧹 **Bulk Delete Mode Activated!**\n\n"
129
- "Please send or forward all the files you want to delete from the database. "
130
- "I will delete them one-by-one automatically.\n\n"
131
- "When you are finished, type `/done` to turn off this mode."
132
- )
133
-
134
- @Client.on_message(filters.command(["done"]) & filters.user(ADMINS))
135
- async def done_deleting(bot, message):
136
- user_id = message.from_user.id
137
- if user_id in DELETING_USERS:
138
- DELETING_USERS.remove(user_id)
139
- await message.reply("🧹 **Bulk Delete Mode Deactivated!**")
140
- else:
141
- await message.reply("❌ You are not currently in bulk delete mode.")
142
-
143
- @Client.on_callback_query(filters.regex(r"^can-index$"))
144
- async def cancel_index(bot, query):
145
- await query.message.delete()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/plugins/live_index.py DELETED
@@ -1,23 +0,0 @@
1
- from pyrogram import Client, filters
2
- from mfinder import DB_CHANNELS, LOGGER
3
- from mfinder.db.files_sql import save_file
4
- from mfinder.utils.helpers import edit_caption
5
-
6
- media_filter = filters.document | filters.video | filters.audio
7
-
8
- @Client.on_message(filters.chat(DB_CHANNELS) & media_filter)
9
- async def live_index(bot, message):
10
- try:
11
- for file_type in ("document", "video", "audio"):
12
- media = getattr(message, file_type, None)
13
-
14
- if not media:
15
- break
16
- file_name = media.file_name
17
- file_name = edit_caption(file_name)
18
- media.file_type = file_type
19
- media.caption = message.caption if message.caption else file_name
20
- await save_file(media)
21
-
22
- except Exception as e:
23
- LOGGER.warning("Error occurred while saving file: %s", str(e))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/plugins/requests.py DELETED
@@ -1,313 +0,0 @@
1
- import re
2
- import hashlib
3
- import logging
4
- import asyncio
5
- from pyrogram import Client, filters
6
- from pyrogram.enums import ParseMode
7
- from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
8
- from pyrogram.errors import MessageNotModified
9
- from mfinder import ADMINS, LOGGER
10
- from mfinder.plugins.admin_settings import get_log_channel
11
- from mfinder.db.requests_sql import (
12
- add_movie_request,
13
- update_request_status,
14
- get_movie_request,
15
- get_pending_requests_count,
16
- )
17
-
18
- # In-memory LRU-style cache mapping 12-char hashes to search queries to keep callback data < 64 bytes
19
- class SimpleCache:
20
- def __init__(self, maxsize=500):
21
- self.cache = {}
22
- self.maxsize = maxsize
23
-
24
- def get(self, key):
25
- return self.cache.get(key)
26
-
27
- def set(self, key, value):
28
- if len(self.cache) >= self.maxsize:
29
- first_key = next(iter(self.cache))
30
- del self.cache[first_key]
31
- self.cache[key] = value
32
-
33
- REQUEST_QUERY_CACHE = SimpleCache()
34
-
35
- async def send_request_to_channel(bot, user, query_text: str, req_id: int):
36
- """Sends a formatted movie request card with Admin action buttons to the Log Channel."""
37
- try:
38
- log_channel_id = await get_log_channel()
39
- if not log_channel_id:
40
- return None
41
-
42
- user_id = user.id
43
- first_name = user.first_name or ""
44
- last_name = user.last_name or ""
45
- full_name = f"{first_name} {last_name}".strip()
46
- username = f"@{user.username}" if user.username else "N/A"
47
-
48
- def escape_html(text):
49
- if not text:
50
- return ""
51
- return str(text).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
52
-
53
- full_name_esc = escape_html(full_name)
54
- first_name_esc = escape_html(first_name)
55
- username_esc = escape_html(username)
56
- query_esc = escape_html(query_text)
57
-
58
- log_msg = (
59
- f"📩 <b>New Movie Request!</b>\n\n"
60
- f"👤 <b>User Details:</b>\n"
61
- f"• <b>User ID:</b> <code>{user_id}</code>\n"
62
- f"• <b>Name:</b> {full_name_esc}\n"
63
- f"• <b>Username:</b> {username_esc}\n"
64
- f"• <b>Mention:</b> <a href=\"tg://user?id={user_id}\">{first_name_esc}</a>\n\n"
65
- f"🎬 <b>Requested Movie:</b> <code>{query_esc}</code>\n"
66
- f"🆔 <b>Request ID:</b> <code>#{req_id}</code>\n"
67
- f"📊 <b>Status:</b> ⏳ <code>Pending</code>"
68
- )
69
-
70
- buttons = InlineKeyboardMarkup([
71
- [
72
- InlineKeyboardButton("✅ Mark Uploaded & Notify", callback_data=f"req_appr {req_id}"),
73
- InlineKeyboardButton("❌ Reject", callback_data=f"req_rejc {req_id}")
74
- ]
75
- ])
76
-
77
- target_chat_id = int(log_channel_id)
78
- sent_msg = None
79
- try:
80
- sent_msg = await bot.send_message(
81
- chat_id=target_chat_id,
82
- text=log_msg,
83
- reply_markup=buttons,
84
- parse_mode=ParseMode.HTML
85
- )
86
- except Exception as send_err:
87
- # If peer resolution fails (e.g. after container restart), refresh dialogs & retry
88
- try:
89
- async for _ in bot.get_dialogs(limit=100):
90
- pass
91
- sent_msg = await bot.send_message(
92
- chat_id=target_chat_id,
93
- text=log_msg,
94
- reply_markup=buttons,
95
- parse_mode=ParseMode.HTML
96
- )
97
- except Exception as retry_err:
98
- LOGGER.warning(f"Failed to send request card to channel ({log_channel_id}): {retry_err}")
99
-
100
- if sent_msg:
101
- await update_request_status(req_id, "Pending", channel_msg_id=sent_msg.id)
102
- return sent_msg.id
103
- except Exception as e:
104
- LOGGER.warning(f"Error sending request card to log channel: {e}")
105
- return None
106
-
107
- @Client.on_message(filters.command(["request"]))
108
- async def request_command(bot, message):
109
- from mfinder.plugins.serve import verify_force_sub
110
- if not await verify_force_sub(bot, message, pending_query=message.text):
111
- return
112
- user = message.from_user
113
- if len(message.command) < 2:
114
- await message.reply_text(
115
- "⚠️ **Please provide a movie name to request!**\n\n"
116
- "**Example:** `/request Kantara Chapter 1`",
117
- quote=True,
118
- parse_mode=ParseMode.MARKDOWN
119
- )
120
- return
121
-
122
- query_text = message.text.split(None, 1)[1].strip()
123
- if len(query_text) < 2:
124
- await message.reply_text("⚠️ Movie title is too short.", quote=True)
125
- return
126
-
127
- user_name = f"{user.first_name or ''} {user.last_name or ''}".strip()
128
- req = await add_movie_request(user.id, user_name, query_text)
129
-
130
- asyncio.create_task(send_request_to_channel(bot, user, query_text, req.id))
131
-
132
- reply_msg = await message.reply_text(
133
- f"✅ **Your request for** `{query_text}` **has been submitted to admins!**\n\n"
134
- f"🎉 You will receive an automatic private DM as soon as it is uploaded.",
135
- quote=True,
136
- parse_mode=ParseMode.MARKDOWN
137
- )
138
-
139
- # Auto-delete response message after 15 minutes to match normal message auto-delete
140
- async def auto_delete_msg(msg):
141
- await asyncio.sleep(900)
142
- try:
143
- await msg.delete()
144
- except Exception:
145
- pass
146
- asyncio.create_task(auto_delete_msg(reply_msg))
147
-
148
- @Client.on_callback_query(filters.regex(r"^req_send (\w+)$"))
149
- async def request_callback(bot, query):
150
- """Handles clicking the '📩 Request Movie' button in search UI."""
151
- from mfinder.plugins.serve import verify_force_sub
152
- if not await verify_force_sub(bot, query):
153
- return
154
- user = query.from_user
155
- short_hash = query.data.split()[1]
156
-
157
- movie_title = REQUEST_QUERY_CACHE.get(short_hash)
158
- if not movie_title:
159
- await query.answer("⚠️ Session expired. Please search for the movie again to request it!", show_alert=True)
160
- return
161
-
162
- # Immediately answer callback query
163
- await query.answer("✅ Request submitted to admins!", show_alert=True)
164
-
165
- user_name = f"{user.first_name or ''} {user.last_name or ''}".strip()
166
- req = await add_movie_request(user.id, user_name, movie_title)
167
- asyncio.create_task(send_request_to_channel(bot, user, movie_title, req.id))
168
-
169
- confirm_text = (
170
- f"✅ **Your request for** `{movie_title}` **has been submitted to admins!**\n\n"
171
- f"🎉 You will receive an automatic private DM as soon as it is uploaded."
172
- )
173
-
174
- # Helper function to auto delete message after 15 minutes
175
- async def auto_delete_msg(msg):
176
- await asyncio.sleep(900)
177
- try:
178
- await msg.delete()
179
- except Exception:
180
- pass
181
-
182
- # Immediately edit message/remove button to prevent duplicate clicks/spam
183
- try:
184
- if query.message and query.message.reply_markup:
185
- new_rows = []
186
- for row in query.message.reply_markup.inline_keyboard:
187
- filtered_row = [b for b in row if not (b.callback_data and b.callback_data.startswith("req_send"))]
188
- if filtered_row:
189
- new_rows.append(filtered_row)
190
-
191
- if new_rows:
192
- # Other buttons (suggestion buttons) exist: update reply_markup to remove request button
193
- await query.message.edit_reply_markup(reply_markup=InlineKeyboardMarkup(new_rows))
194
- reply_msg = await query.message.reply_text(
195
- text=confirm_text,
196
- quote=True,
197
- parse_mode=ParseMode.MARKDOWN
198
- )
199
- asyncio.create_task(auto_delete_msg(reply_msg))
200
- else:
201
- # Standalone request button: replace message content directly into confirmation text
202
- await query.message.edit_text(
203
- text=confirm_text,
204
- reply_markup=None,
205
- parse_mode=ParseMode.MARKDOWN
206
- )
207
- asyncio.create_task(auto_delete_msg(query.message))
208
- else:
209
- await query.message.edit_text(
210
- text=confirm_text,
211
- reply_markup=None,
212
- parse_mode=ParseMode.MARKDOWN
213
- )
214
- asyncio.create_task(auto_delete_msg(query.message))
215
- except Exception as e:
216
- LOGGER.warning(f"Notice updating request callback UI: {e}")
217
-
218
- @Client.on_callback_query(filters.regex(r"^req_(appr|rejc) (\d+)$"))
219
- async def admin_request_action(bot, query):
220
- """Handles Admin clicking '✅ Mark Uploaded' or '❌ Reject' in the Log/Request Channel."""
221
- user = query.from_user
222
- action = query.data.split()[0].split("_")[1]
223
- req_id = int(query.data.split()[1])
224
-
225
- admin_name = user.first_name or "Admin"
226
-
227
- req = await get_movie_request(req_id)
228
- if not req:
229
- await query.answer("⚠️ Request record not found in database.", show_alert=True)
230
- return
231
-
232
- def escape_html(text):
233
- if not text:
234
- return ""
235
- return str(text).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
236
-
237
- full_name_esc = escape_html(req.user_name or f"User {req.user_id}")
238
- query_esc = escape_html(req.query)
239
- admin_esc = escape_html(admin_name)
240
-
241
- if action == "appr":
242
- await update_request_status(req_id, "Uploaded")
243
- status_text = f"✅ <b>Uploaded</b> (by {admin_esc})"
244
-
245
- # 1. Update Channel Message
246
- card_msg = (
247
- f"📩 <b>Movie Request Updated</b>\n\n"
248
- f"👤 <b>User Details:</b>\n"
249
- f"• <b>User ID:</b> <code>{req.user_id}</code>\n"
250
- f"• <b>Name:</b> {full_name_esc}\n\n"
251
- f"🎬 <b>Requested Movie:</b> <code>{query_esc}</code>\n"
252
- f"🆔 <b>Request ID:</b> <code>#{req_id}</code>\n"
253
- f"📊 <b>Status:</b> {status_text}"
254
- )
255
- try:
256
- await query.message.edit_text(card_msg, parse_mode=ParseMode.HTML, reply_markup=None)
257
- except MessageNotModified:
258
- pass
259
-
260
- await query.answer("✅ Marked as Uploaded! Notifying user via DM...", show_alert=True)
261
-
262
- # 2. Automatically notify user in private DM
263
- dm_text = (
264
- f"🎉 <b>Great news, {full_name_esc}!</b>\n\n"
265
- f"The movie you requested (<b>{query_esc}</b>) has been <b>uploaded</b>! 🍿\n\n"
266
- f"Search for <code>{query_esc}</code> now to download."
267
- )
268
- try:
269
- await bot.send_message(chat_id=req.user_id, text=dm_text, parse_mode=ParseMode.HTML)
270
- except Exception as dm_err:
271
- LOGGER.warning(f"Could not send DM to user {req.user_id} for request #{req_id}: {dm_err}")
272
-
273
- elif action == "rejc":
274
- await update_request_status(req_id, "Rejected")
275
- status_text = f"❌ <b>Rejected</b> (by {admin_esc})"
276
-
277
- # 1. Update Channel Message
278
- card_msg = (
279
- f"📩 <b>Movie Request Updated</b>\n\n"
280
- f"👤 <b>User Details:</b>\n"
281
- f"• <b>User ID:</b> <code>{req.user_id}</code>\n"
282
- f"• <b>Name:</b> {full_name_esc}\n\n"
283
- f"🎬 <b>Requested Movie:</b> <code>{query_esc}</code>\n"
284
- f"🆔 <b>Request ID:</b> <code>#{req_id}</code>\n"
285
- f"📊 <b>Status:</b> {status_text}"
286
- )
287
- try:
288
- await query.message.edit_text(card_msg, parse_mode=ParseMode.HTML, reply_markup=None)
289
- except MessageNotModified:
290
- pass
291
-
292
- await query.answer("❌ Request marked as Rejected.", show_alert=True)
293
-
294
- # 2. Automatically notify user in private DM
295
- dm_text = (
296
- f"ℹ️ <b>Hello {full_name_esc},</b>\n\n"
297
- f"Regarding your request for <b>{query_esc}</b>: Sorry, this movie is currently unavailable."
298
- )
299
- try:
300
- await bot.send_message(chat_id=req.user_id, text=dm_text, parse_mode=ParseMode.HTML)
301
- except Exception as dm_err:
302
- LOGGER.warning(f"Could not send rejection DM to user {req.user_id} for request #{req_id}: {dm_err}")
303
-
304
- @Client.on_message(filters.command(["requests"]) & filters.user(ADMINS))
305
- async def requests_admin_command(bot, message):
306
- """Admin command to check pending request count."""
307
- count = await get_pending_requests_count()
308
- await message.reply_text(
309
- f"📊 **Movie Requests Summary**\n\n"
310
- f"⏳ **Pending Requests:** `{count}`",
311
- quote=True,
312
- parse_mode=ParseMode.MARKDOWN
313
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/plugins/serve.py DELETED
@@ -1,1133 +0,0 @@
1
- import os
2
- import re
3
- import asyncio
4
- import hashlib
5
- from pyrogram import Client, filters
6
-
7
- GENERIC_KEYWORDS_RE = re.compile(
8
- r'\b(1080p|720p|480p|4k|2k|hdrip|webdl|web-dl|bluray|blu-ray|hdtv|brrip|dvdrip|hevc|x264|x265|h264|h265|aac|dd5\.1|dd\+|ddp5\.1|ddp|dd|dual|multi|esub|esubs|sub|subs|tamil|telugu|hindi|malayalam|kannada|english|bengali|marathi|punjabi|season|s\d+ep\d+|s\d+|ep\d+|combined)\b',
9
- re.IGNORECASE
10
- )
11
-
12
- def clean_movie_title(text: str) -> str:
13
- if not text:
14
- return ""
15
- # Strip common channel tags (e.g. starting with @)
16
- title = re.sub(r'@[a-zA-Z0-9_]+', '', text)
17
- # Strip leading non-alphanumeric characters like - or space
18
- title = re.sub(r'^[^a-zA-Z0-9]+', '', title)
19
-
20
- # Try to extract the title including the year in parentheses, e.g. "Movie Name (2024)"
21
- year_match = re.search(r'^(.*?)\s*\((\d{4})\)', title)
22
- if year_match:
23
- prefix = year_match.group(1)
24
- year = year_match.group(2)
25
- # Clean prefix from common separators like [, -, etc.
26
- prefix = re.split(r'[\[\-]', prefix)[0]
27
- prefix = re.sub(r'\s+', ' ', prefix).strip()
28
- return f"{prefix} ({year})"
29
-
30
- # Otherwise, split at [ or - or (
31
- title = re.split(r'[\[\-\()]', title)[0]
32
- # Remove generic keywords
33
- title = GENERIC_KEYWORDS_RE.sub('', title)
34
- title = re.sub(r'\s+', ' ', title).strip()
35
- return title
36
-
37
- class SimpleLRUCache:
38
- def __init__(self, maxsize=5000):
39
- self.maxsize = maxsize
40
- self.cache = {}
41
-
42
- def get(self, key):
43
- if key in self.cache:
44
- # Move key to end to mark as recently used
45
- val = self.cache.pop(key)
46
- self.cache[key] = val
47
- return val
48
- return None
49
-
50
- def set(self, key, value):
51
- if key in self.cache:
52
- self.cache.pop(key)
53
- elif len(self.cache) >= self.maxsize:
54
- # Pop the oldest item (first key)
55
- first_key = next(iter(self.cache))
56
- self.cache.pop(first_key)
57
- self.cache[key] = value
58
-
59
- MOVIE_CALLBACK_CACHE = SimpleLRUCache(maxsize=5000)
60
- SEARCH_QUERY_CACHE = SimpleLRUCache(maxsize=5000)
61
- from pyrogram.types import (
62
- InlineKeyboardButton,
63
- InlineKeyboardMarkup,
64
- Message,
65
- CallbackQuery,
66
- )
67
- from pyrogram.enums import ParseMode, ChatMemberStatus
68
- from pyrogram.errors import UserNotParticipant
69
- from pyrogram.errors.exceptions.bad_request_400 import MessageNotModified
70
- from mfinder.db.files_sql import (
71
- get_filter_results,
72
- get_file_details,
73
- get_precise_filter_results,
74
- get_trigram_filter_results,
75
- )
76
- from mfinder.db.settings_sql import (
77
- get_search_settings,
78
- get_admin_settings,
79
- get_link,
80
- get_channel,
81
- get_log_channel,
82
- )
83
- from mfinder.db.ban_sql import is_banned
84
- from mfinder.db.filters_sql import is_filter
85
- from mfinder import LOGGER, ADMINS
86
-
87
- async def verify_force_sub(bot, event, pending_query=None, pending_file_id=None):
88
- from mfinder import ADMINS, LOGGER
89
- from mfinder.db.settings_sql import get_admin_settings, save_pending_fsub_request
90
- from pyrogram.types import Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
91
- from pyrogram.enums import ChatMemberStatus, ParseMode
92
- from pyrogram.errors import UserNotParticipant
93
-
94
- user_id = event.from_user.id
95
- if user_id in ADMINS:
96
- return True
97
-
98
- admin_settings = await get_admin_settings()
99
- fsub_channels = []
100
- if admin_settings:
101
- if admin_settings.fsub_channels_list:
102
- fsub_channels = [ch.strip() for ch in admin_settings.fsub_channels_list.split(',') if ch.strip()]
103
- elif admin_settings.fsub_channel:
104
- fsub_channels = [str(int(admin_settings.fsub_channel))]
105
-
106
- if not fsub_channels:
107
- return True
108
-
109
- not_joined = []
110
- for ch in fsub_channels:
111
- try:
112
- ch_param = int(ch) if (ch.startswith('-') or ch.isdigit()) else ch
113
- member = await bot.get_chat_member(ch_param, user_id)
114
- if member.status == ChatMemberStatus.BANNED:
115
- if isinstance(event, CallbackQuery):
116
- await event.answer("Sorry, you are Banned to use me.", show_alert=True)
117
- else:
118
- await event.reply_text("Sorry, you are Banned to use me.", quote=True)
119
- return False
120
- except UserNotParticipant:
121
- not_joined.append(ch)
122
- except Exception as e:
123
- LOGGER.warning(f"Error checking chat member for channel {ch}: {e}")
124
- not_joined.append(ch)
125
-
126
- if not not_joined:
127
- return True
128
-
129
- # Save user's pending request details so we can auto-execute on joining
130
- await save_pending_fsub_request(user_id, search_query=pending_query, target_file_id=pending_file_id)
131
-
132
- # Build buttons for channels they must join
133
- buttons = []
134
- for ch in fsub_channels:
135
- try:
136
- ch_param = int(ch) if (ch.startswith('-') or ch.isdigit()) else ch
137
- chat = await bot.get_chat(ch_param)
138
- title = chat.title or "Join Channel"
139
- if chat.username:
140
- url = f"https://t.me/{chat.username}"
141
- else:
142
- url = chat.invite_link or (await bot.create_chat_invite_link(ch_param)).invite_link
143
- except Exception:
144
- url = admin_settings.channel_link if (admin_settings and admin_settings.channel_link) else "https://t.me/FIREBOLT_File_Bot"
145
- title = "Update Channel"
146
- buttons.append([InlineKeyboardButton(f"🤖 Join: {title}", url=url)])
147
-
148
- # Add the Try Again / Verification button
149
- buttons.append([InlineKeyboardButton("🔄 Try Again / Verified", callback_data="verify_fsub")])
150
-
151
- text = "**Please join my Update Channel(s) to use this Bot!**"
152
- if len(not_joined) > 1:
153
- text = "**Please join the required Update Channels below to use this Bot!**"
154
-
155
- if isinstance(event, CallbackQuery):
156
- await event.answer("⚠️ Please join the required channels to proceed!", show_alert=True)
157
- try:
158
- from pyrogram.errors import MessageNotModified
159
- await event.message.edit_text(
160
- text=text,
161
- reply_markup=InlineKeyboardMarkup(buttons),
162
- parse_mode=ParseMode.MARKDOWN,
163
- )
164
- except MessageNotModified:
165
- pass
166
- except Exception:
167
- pass
168
- else:
169
- await event.reply_text(
170
- text=text,
171
- reply_markup=InlineKeyboardMarkup(buttons),
172
- parse_mode=ParseMode.MARKDOWN,
173
- quote=True,
174
- )
175
-
176
- return False
177
- from mfinder.utils.helpers import shorten_url
178
-
179
- async def is_token_valid(user_id: int) -> bool:
180
- import time
181
- from mfinder import ADMINS
182
- if user_id in ADMINS:
183
- return True
184
- from mfinder.db.settings_sql import get_user_token, delete_user_token
185
- tok_rec = await get_user_token(user_id)
186
- if tok_rec:
187
- if tok_rec.status == "active":
188
- if float(tok_rec.expires_at) > time.time():
189
- return True
190
- else:
191
- # Active token has expired, delete it to save space!
192
- await delete_user_token(user_id)
193
- elif tok_rec.status == "pending":
194
- # Preserve pending tokens within the 30-minute verification window
195
- if (time.time() - float(tok_rec.created_at)) > 1800:
196
- await delete_user_token(user_id)
197
- return False
198
-
199
- async def log_search_attempt(bot, user, query, token_status, result_status, suggestions=None):
200
- try:
201
- log_channel_id = await get_log_channel()
202
- if not log_channel_id:
203
- return # Logging is disabled or channel not configured
204
-
205
- user_id = user.id
206
- first_name = user.first_name or ""
207
- last_name = user.last_name or ""
208
- full_name = f"{first_name} {last_name}".strip()
209
- username = f"@{user.username}" if user.username else "N/A"
210
-
211
- # HTML escape helper
212
- def escape_html(text):
213
- if not text:
214
- return ""
215
- return str(text).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
216
-
217
- full_name_esc = escape_html(full_name)
218
- first_name_esc = escape_html(first_name)
219
- username_esc = escape_html(username)
220
- query_esc = escape_html(query)
221
- token_status_esc = escape_html(token_status)
222
- result_status_esc = escape_html(result_status)
223
-
224
- sug_block = ""
225
- if suggestions:
226
- if isinstance(suggestions, list) and len(suggestions) > 0:
227
- formatted_sugs = ", ".join([f"<code>{escape_html(s)}</code>" for s in suggestions[:8]])
228
- sug_block = f"\n💡 <b>Suggestions Offered:</b> {formatted_sugs}"
229
- elif isinstance(suggestions, str) and suggestions.strip():
230
- sug_block = f"\n💡 <b>Suggestions Offered:</b> <code>{escape_html(suggestions)}</code>"
231
-
232
- log_msg = (
233
- f"🔍 <b>New Movie Search Log</b>\n\n"
234
- f"👤 <b>User Details:</b>\n"
235
- f"• <b>User ID:</b> <code>{user_id}</code>\n"
236
- f"• <b>Name:</b> {full_name_esc}\n"
237
- f"• <b>Username:</b> {username_esc}\n"
238
- f"• <b>Mention:</b> <a href=\"tg://user?id={user_id}\">{first_name_esc}</a>\n\n"
239
- f"📝 <b>Search Query:</b> <code>{query_esc}</code>\n"
240
- f"🔑 <b>Token Status:</b> <code>{token_status_esc}</code>\n"
241
- f"📊 <b>Search Result:</b> {result_status_esc}"
242
- f"{sug_block}"
243
- )
244
-
245
- target_chat_id = int(log_channel_id)
246
- try:
247
- await bot.send_message(
248
- chat_id=target_chat_id,
249
- text=log_msg,
250
- parse_mode=ParseMode.HTML
251
- )
252
- except Exception as send_err:
253
- LOGGER.warning(f"Log channel send_message failed: {send_err}")
254
- except Exception as e:
255
- LOGGER.warning(f"Failed to send search log to channel: {e}")
256
-
257
- async def log_file_delivery(bot, user, file_name, file_size, file_id):
258
- try:
259
- log_channel_id = await get_log_channel()
260
- if not log_channel_id:
261
- return # Logging disabled
262
-
263
- user_id = user.id
264
- first_name = user.first_name or ""
265
- last_name = user.last_name or ""
266
- full_name = f"{first_name} {last_name}".strip()
267
- username = f"@{user.username}" if user.username else "N/A"
268
-
269
- def escape_html(text):
270
- if not text:
271
- return ""
272
- return str(text).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
273
-
274
- full_name_esc = escape_html(full_name)
275
- first_name_esc = escape_html(first_name)
276
- username_esc = escape_html(username)
277
- file_name_esc = escape_html(file_name)
278
-
279
- log_msg = (
280
- f"📥 <b>File Delivered Log</b>\n\n"
281
- f"👤 <b>User Details:</b>\n"
282
- f"• <b>User ID:</b> <code>{user_id}</code>\n"
283
- f"• <b>Name:</b> {full_name_esc}\n"
284
- f"• <b>Username:</b> {username_esc}\n"
285
- f"• <b>Mention:</b> <a href=\"tg://user?id={user_id}\">{first_name_esc}</a>\n\n"
286
- f"📄 <b>File Name:</b> <code>{file_name_esc}</code>\n"
287
- f"📦 <b>File Size:</b> <code>{file_size}</code>\n"
288
- f"🆔 <b>File ID:</b> <code>{file_id}</code>"
289
- )
290
-
291
- target_chat_id = int(log_channel_id)
292
- try:
293
- await bot.send_message(
294
- chat_id=target_chat_id,
295
- text=log_msg,
296
- parse_mode=ParseMode.HTML
297
- )
298
- except Exception as send_err:
299
- LOGGER.warning(f"File delivery log channel send_message failed: {send_err}")
300
- except Exception as e:
301
- LOGGER.warning(f"Failed to send file delivery log to channel: {e}")
302
-
303
- async def create_and_send_token_link(bot, update, admin_settings, search_query=None, target_file_id=None):
304
- import uuid
305
- from mfinder.db.settings_sql import create_user_token
306
- from mfinder.utils.helpers import shorten_url
307
-
308
- from pyrogram.types import CallbackQuery, Message
309
- from pyrogram.enums import ChatType
310
-
311
- if isinstance(update, CallbackQuery):
312
- user_id = update.from_user.id
313
- elif isinstance(update, Message):
314
- if update.chat and update.chat.type == ChatType.PRIVATE:
315
- user_id = update.chat.id
316
- else:
317
- user_id = update.from_user.id if update.from_user else None
318
- else:
319
- user_id = getattr(update, "from_user", None)
320
- user_id = user_id.id if user_id else None
321
-
322
- if not user_id:
323
- user_id = update.from_user.id
324
-
325
- # Delete any previous token request message to prevent chat clutter
326
- try:
327
- from mfinder.db.settings_sql import get_user_token
328
- old_tok = await get_user_token(user_id)
329
- if old_tok and old_tok.req_msg_id:
330
- await bot.delete_messages(chat_id=user_id, message_ids=int(old_tok.req_msg_id))
331
- except Exception as e:
332
- LOGGER.warning(f"Error deleting old token request message: {e}")
333
-
334
- token = f"tok_{uuid.uuid4().hex}"
335
-
336
- # Save token as pending
337
- await create_user_token(user_id, token, search_query=search_query, target_file_id=target_file_id)
338
-
339
- me = bot.me
340
- username = me.username
341
-
342
- # Generate redirect link
343
- redirect_url = f"https://telegram.me/{username}?start={token}"
344
- short_url = await shorten_url(redirect_url, force=True)
345
-
346
- text = (
347
- "⚠️ **Access Token Required!**\n\n"
348
- "To access search results and download files directly without ads, you need to generate a direct access token.\n\n"
349
- "1. Click the button below to generate your token.\n"
350
- "2. Complete the shortening link.\n"
351
- "3. You will be redirected back with direct access for a dynamically set duration!\n\n"
352
- "⏱️ **Note:** Standard per-file shortening is completely bypassed once verified!"
353
- )
354
-
355
- how_to_download_url = admin_settings.how_to_download if admin_settings and admin_settings.how_to_download else "https://telegram.me/FIREBOLTTutorial/23"
356
-
357
- markup = InlineKeyboardMarkup([
358
- [InlineKeyboardButton("🎫 Generate Access Token", url=short_url)],
359
- [InlineKeyboardButton("❓ How to Verify ❓", url=how_to_download_url)]
360
- ])
361
-
362
- sent_msg = await update.reply_text(
363
- text=text,
364
- reply_markup=markup,
365
- quote=True
366
- )
367
-
368
- try:
369
- from mfinder.db.settings_sql import update_user_token_msg_id
370
- await update_user_token_msg_id(user_id, sent_msg.id)
371
- except Exception as e:
372
- LOGGER.warning(f"Error saving req_msg_id to database: {e}")
373
-
374
- @Client.on_message(
375
- ~filters.regex(r"^\/") & filters.text & filters.private & filters.incoming
376
- )
377
- async def filter_(bot, message):
378
- from mfinder import ADMINS
379
- user_id = message.from_user.id
380
-
381
- try:
382
- from mfinder.plugins.admin_settings import ADMIN_INPUT_STATE, handle_admin_input
383
- if user_id in ADMIN_INPUT_STATE:
384
- await handle_admin_input(bot, message)
385
- return
386
- except Exception as e:
387
- LOGGER.warning(f"Error checking ADMIN_INPUT_STATE: {e}")
388
-
389
- if re.findall(r"((^\/|^,|^!|^\.|^[\U0001F600-\U000E007F]).*)", message.text):
390
- return
391
-
392
- if await is_banned(user_id):
393
- await message.reply_text("You are banned. You can't use this bot.", quote=True)
394
- return
395
-
396
- if not await verify_force_sub(bot, message, pending_query=message.text):
397
- return
398
-
399
- admin_settings = await get_admin_settings()
400
- if admin_settings:
401
- if admin_settings.repair_mode and user_id not in ADMINS:
402
- await message.reply_text(
403
- "⚙️ **Bot Under Maintenance!**\n\nThe bot is currently undergoing scheduled maintenance or repair. Please try again later.",
404
- quote=True
405
- )
406
- return
407
- if admin_settings.token_shortener_enabled and user_id not in ADMINS:
408
- if not await is_token_valid(user_id):
409
- asyncio.create_task(
410
- log_search_attempt(
411
- bot=bot,
412
- user=message.from_user,
413
- query=message.text,
414
- token_status="Expired / Verification Required",
415
- result_status="Blocked (Token Verification Required)"
416
- )
417
- )
418
- await create_and_send_token_link(bot, message, admin_settings, search_query=message.text)
419
- return
420
-
421
- fltr = await is_filter(message.text)
422
- if fltr:
423
- await message.reply_text(
424
- text=fltr.message,
425
- quote=True,
426
- )
427
- return
428
-
429
- if 2 < len(message.text) < 100:
430
- search = message.text
431
- page_no = 1
432
- me = bot.me
433
- username = me.username
434
-
435
- # Send "Searching Files 🔎" message
436
- search_msg = await message.reply_text("Searching Files 🔎", quote=True)
437
-
438
- result, btn, suggestions = await get_result(search, page_no, user_id, username)
439
-
440
- # Delete the "Searching Files 🔎" message
441
- await search_msg.delete()
442
-
443
- # Determine token status
444
- token_status = "N/A (Token Shortener Disabled)"
445
- if admin_settings and admin_settings.token_shortener_enabled:
446
- if user_id in ADMINS:
447
- token_status = "Bypassed (Admin)"
448
- else:
449
- token_status = "Active / Valid"
450
-
451
- # Parse result status
452
- result_status = "Not Found"
453
- if result:
454
- match = re.search(r"Total Results.*`(\d+)`", result or "")
455
- if match:
456
- total_count = match.group(1)
457
- result_status = f"Found ({total_count} results)"
458
- else:
459
- if "m_s " in str(btn) or "Did you mean" in (result or "") or "No exact match" in (result or ""):
460
- result_status = "Not Found (Suggestions Offered)"
461
- else:
462
- result_status = "Found"
463
- else:
464
- result_status = "Not Found (No Suggestions)"
465
-
466
- # Safe logging run in background
467
- from mfinder.db.analytics_sql import log_search_query
468
- asyncio.create_task(log_search_query(search))
469
- asyncio.create_task(
470
- log_search_attempt(
471
- bot=bot,
472
- user=message.from_user,
473
- query=search,
474
- token_status=token_status,
475
- result_status=result_status,
476
- suggestions=suggestions
477
- )
478
- )
479
-
480
- if result:
481
- if btn:
482
- msg = await message.reply_text(
483
- f"{result}",
484
- reply_markup=InlineKeyboardMarkup(btn),
485
- disable_web_page_preview=True,
486
- quote=True,
487
- )
488
- else:
489
- msg = await message.reply_text(
490
- f"{result}",
491
- disable_web_page_preview=True,
492
- quote=True,
493
- )
494
- # Delete the message after 15 minutes
495
- await asyncio.sleep(900)
496
- await msg.delete()
497
- else:
498
- await message.reply_text(
499
- text="No results found.\nOr retry with the correct spelling 🤐",
500
- quote=True,
501
- )
502
-
503
- @Client.on_callback_query(filters.regex(r"^(nxt_pg|prev_pg) \d+ \d+ \w+$"))
504
- async def pages(bot, query):
505
- user_id = query.from_user.id
506
- if not await verify_force_sub(bot, query):
507
- return
508
- admin_settings = await get_admin_settings()
509
- if admin_settings and admin_settings.repair_mode and user_id not in ADMINS:
510
- await query.answer("⚙️ Bot is under maintenance. Please try again later.", show_alert=True)
511
- return
512
- data_parts = query.data.split()
513
- action = data_parts[0]
514
- org_user_id = int(data_parts[1])
515
- page_no = int(data_parts[2])
516
- query_hash = data_parts[3]
517
-
518
- search = SEARCH_QUERY_CACHE.get(query_hash)
519
- if not search:
520
- await query.answer("⚠️ This search session has expired. Please search again!", show_alert=True)
521
- return
522
-
523
- me = bot.me
524
- username = me.username
525
-
526
- result, btn, suggestions = await get_result(search, page_no, user_id, username)
527
-
528
- if result:
529
- try:
530
- if btn:
531
- if query.message.text != result:
532
- await query.message.edit(
533
- f"{result}",
534
- reply_markup=InlineKeyboardMarkup(btn),
535
- disable_web_page_preview=True,
536
- )
537
- else:
538
- if query.message.text != result:
539
- await query.message.edit(
540
- f"{result}",
541
- disable_web_page_preview=True,
542
- )
543
- except MessageNotModified:
544
- pass
545
- else:
546
- await query.answer("No more results found.", show_alert=True)
547
-
548
- @Client.on_callback_query(filters.regex(r"^m_s (\w+)$"))
549
- async def movie_selection(bot, query):
550
- user_id = query.from_user.id
551
- admin_settings = await get_admin_settings()
552
- if admin_settings and admin_settings.repair_mode and user_id not in ADMINS:
553
- await query.answer("⚙️ Bot is under maintenance. Please try again later.", show_alert=True)
554
- return
555
- short_hash = query.data.split()[1]
556
-
557
- cached_val = MOVIE_CALLBACK_CACHE.get(short_hash)
558
- if not cached_val:
559
- await query.answer("⚠️ This suggestion session has expired. Please search again!", show_alert=True)
560
- return
561
-
562
- if isinstance(cached_val, tuple):
563
- movie_title, source = cached_val
564
- else:
565
- movie_title = cached_val
566
- source = "AI Suggestion"
567
-
568
- if not await verify_force_sub(bot, query, pending_query=movie_title):
569
- return
570
-
571
- if admin_settings and admin_settings.token_shortener_enabled and user_id not in ADMINS:
572
- if not await is_token_valid(user_id):
573
- await query.answer("⚠️ Access token required. Generating token link...", show_alert=True)
574
- # Log the blocked attempt with correct verification status
575
- asyncio.create_task(
576
- log_search_attempt(
577
- bot=bot,
578
- user=query.from_user,
579
- query=f"Selected Movie: {movie_title} (from {source})",
580
- token_status="Expired / Verification Required",
581
- result_status="Blocked (Token Verification Required)"
582
- )
583
- )
584
- await create_and_send_token_link(bot, query.message, admin_settings, search_query=movie_title)
585
- return
586
-
587
- await query.answer(f"Fetching files for {movie_title}...", cache_time=5)
588
-
589
- me = bot.me
590
- username = me.username
591
-
592
- # We perform a direct exact search on the movie_title, starting on page_no = 1
593
- result, btn, suggestions = await get_result(movie_title, 1, user_id, username)
594
-
595
- # Determine token status
596
- token_status = "N/A (Token Shortener Disabled)"
597
- if admin_settings and admin_settings.token_shortener_enabled:
598
- if user_id in ADMINS:
599
- token_status = "Bypassed (Admin)"
600
- else:
601
- is_valid = await is_token_valid(user_id)
602
- token_status = "Active / Valid" if is_valid else "Expired / Verification Required"
603
-
604
- # Parse result status
605
- result_status = "Not Found"
606
- if result:
607
- match = re.search(r"Total Results.*`(\d+)`", result or "")
608
- if match:
609
- total_count = match.group(1)
610
- result_status = f"Found ({total_count} results) via Suggestion Selection"
611
- else:
612
- result_status = "Found via Suggestion Selection"
613
- else:
614
- result_status = "Not Found via Suggestion Selection"
615
-
616
- # Safe logging run in background
617
- asyncio.create_task(
618
- log_search_attempt(
619
- bot=bot,
620
- user=query.from_user,
621
- query=f"Selected Movie: {movie_title} (from {source})",
622
- token_status=token_status,
623
- result_status=result_status,
624
- suggestions=suggestions
625
- )
626
- )
627
-
628
- if result:
629
- try:
630
- if btn:
631
- await query.message.edit(
632
- f"{result}",
633
- reply_markup=InlineKeyboardMarkup(btn),
634
- disable_web_page_preview=True,
635
- )
636
- else:
637
- await query.message.edit(
638
- f"{result}",
639
- disable_web_page_preview=True,
640
- )
641
- except MessageNotModified:
642
- pass
643
- else:
644
- await query.message.edit(
645
- f"No files found for **{movie_title}**.",
646
- disable_web_page_preview=True,
647
- )
648
-
649
- async def get_result(search, page_no, user_id, username):
650
- from mfinder import ADMINS
651
- admin_settings = await get_admin_settings()
652
- bypass_shortening = False
653
- if admin_settings and admin_settings.token_shortener_enabled:
654
- bypass_shortening = True
655
- if user_id in ADMINS:
656
- bypass_shortening = True
657
-
658
- search_settings = await get_search_settings(user_id)
659
- if search_settings:
660
- if search_settings.precise_mode:
661
- files, count = await get_precise_filter_results(query=search, page=page_no)
662
- precise_search = "Enabled"
663
- else:
664
- files, count = await get_filter_results(query=search, page=page_no)
665
- precise_search = "Disabled"
666
- else:
667
- files, count = await get_filter_results(query=search, page=page_no)
668
- precise_search = "Disabled"
669
-
670
- search_type = "Direct"
671
- original_search = search
672
-
673
- # If direct search returned no files and page_no == 1, run spelling corrections and group by movie title
674
- if not files and page_no == 1:
675
- corrected_query = None
676
- keywords = []
677
- suggestions = []
678
- ai_model = None
679
-
680
- try:
681
- from mfinder.db.suggestion_cache import get_cached_suggestion, set_cached_suggestion
682
- from mfinder.utils.gemini_client import get_ai_suggestions
683
-
684
- cached = await get_cached_suggestion(search)
685
- if cached:
686
- corrected_query = cached.get("corrected_query")
687
- keywords = cached.get("keywords") or []
688
- suggestions = cached.get("suggestions") or []
689
- ai_model = cached.get("model") or "gemini-3.1-flash-lite"
690
- else:
691
- ai_res = await get_ai_suggestions(search)
692
- if ai_res:
693
- corrected_query = ai_res.get("corrected")
694
- keywords = ai_res.get("keywords") or []
695
- suggestions = ai_res.get("suggestions") or []
696
- ai_model = ai_res.get("model")
697
- await set_cached_suggestion(search, corrected_query, keywords, suggestions)
698
- except Exception as e:
699
- LOGGER.warning(f"Error in Gemini search: {e}")
700
-
701
- # Collect candidate files from DB
702
- candidate_files = []
703
- seen_file_ids = set()
704
-
705
- def add_unique_files(new_files):
706
- for f in new_files:
707
- if f.file_id not in seen_file_ids:
708
- seen_file_ids.add(f.file_id)
709
- candidate_files.append(f)
710
-
711
- # A. Query fuzzy trigram search for original search
712
- orig_fuzzy_files, _ = await get_trigram_filter_results(query=search, page=1, per_page=100, threshold=0.2)
713
- add_unique_files(orig_fuzzy_files)
714
-
715
- # B. Query direct and fuzzy matching for corrections/suggestions
716
- candidates = []
717
- if corrected_query and corrected_query.strip().lower() != search.strip().lower():
718
- candidates.append(corrected_query.strip())
719
- for sug in suggestions:
720
- if sug and sug.strip().lower() != search.strip().lower() and sug.strip() not in candidates:
721
- candidates.append(sug.strip())
722
- for kw in keywords:
723
- if kw and kw.strip().lower() != search.strip().lower() and len(kw.strip()) > 3 and kw.strip() not in candidates:
724
- candidates.append(kw.strip())
725
-
726
- # C. Query database keyword titles directly (extracting actor/recent movie names from DB files)
727
- from mfinder.db.files_sql import get_keyword_db_suggestions
728
- db_kw_suggestions = await get_keyword_db_suggestions(search, limit=25)
729
- for db_sug in db_kw_suggestions:
730
- if db_sug and db_sug.strip() not in candidates:
731
- candidates.append(db_sug.strip())
732
- if db_sug not in suggestions:
733
- suggestions.append(db_sug)
734
-
735
- for cand in candidates:
736
- cand_direct_files, _ = await get_filter_results(query=cand, page=1, per_page=50)
737
- add_unique_files(cand_direct_files)
738
-
739
- cand_fuzzy_files, _ = await get_trigram_filter_results(query=cand, page=1, per_page=50, threshold=0.2)
740
- add_unique_files(cand_fuzzy_files)
741
-
742
- # Clean and group candidate files by cleaned movie title
743
- import difflib
744
- movie_groups = {} # {cleaned_title: [file1, file2, ...]}
745
- for f in candidate_files:
746
- cl_title = clean_movie_title(f.file_name)
747
- if not cl_title:
748
- cl_title = clean_movie_title(f.caption)
749
- if not cl_title:
750
- continue
751
-
752
- norm_key = cl_title.lower().strip()
753
- found_key = None
754
- for existing_title in movie_groups:
755
- if existing_title.lower().strip() == norm_key:
756
- found_key = existing_title
757
- break
758
-
759
- if found_key:
760
- movie_groups[found_key].append(f)
761
- else:
762
- movie_groups[cl_title] = [f]
763
-
764
- # Score and rank movie groups
765
- q_clean = clean_movie_title(search).lower()
766
- if not q_clean:
767
- q_clean = search.lower()
768
-
769
- corr_clean = None
770
- if corrected_query:
771
- corr_clean = clean_movie_title(corrected_query).lower()
772
- if not corr_clean:
773
- corr_clean = corrected_query.lower()
774
-
775
- sugs_clean = []
776
- for s in suggestions:
777
- if s:
778
- sc = clean_movie_title(s).lower()
779
- if not sc:
780
- sc = s.lower()
781
- if sc not in sugs_clean:
782
- sugs_clean.append(sc)
783
-
784
- scored_groups = []
785
- for cl_title, group_files in movie_groups.items():
786
- t_clean = cl_title.lower()
787
- t_clean_no_year = re.sub(r'\s*\(\d{4}\)', '', t_clean).strip()
788
-
789
- q_clean_no_year = re.sub(r'\s*\(\d{4}\)', '', q_clean).strip()
790
- corr_clean_no_year = re.sub(r'\s*\(\d{4}\)', '', corr_clean).strip() if corr_clean else ""
791
- sugs_clean_no_year = [re.sub(r'\s*\(\d{4}\)', '', s).strip() for s in sugs_clean if s]
792
-
793
- # Match 1: Exact matches (ignoring year)
794
- is_exact = False
795
- if t_clean_no_year == q_clean_no_year:
796
- is_exact = True
797
- elif corr_clean_no_year and t_clean_no_year == corr_clean_no_year:
798
- is_exact = True
799
- elif t_clean_no_year in sugs_clean_no_year:
800
- is_exact = True
801
-
802
- if is_exact:
803
- best_score = 1.0
804
- else:
805
- # Match 2: Prefix / Word boundary containment matches
806
- best_sub = 0.0
807
- for match_cand in [q_clean_no_year, corr_clean_no_year] + sugs_clean_no_year:
808
- if not match_cand:
809
- continue
810
- if t_clean_no_year.startswith(match_cand) or match_cand.startswith(t_clean_no_year):
811
- best_sub = max(best_sub, 0.90)
812
- elif f" {match_cand} " in f" {t_clean_no_year} " or f" {t_clean_no_year} " in f" {match_cand} ":
813
- best_sub = max(best_sub, 0.85)
814
-
815
- # Match 3: Fuzzy SequenceMatcher ratio
816
- score_orig = difflib.SequenceMatcher(None, q_clean_no_year, t_clean_no_year).ratio()
817
- score_corr = difflib.SequenceMatcher(None, corr_clean_no_year, t_clean_no_year).ratio() if corr_clean else 0.0
818
- best_fuzzy = max(score_orig, score_corr)
819
-
820
- best_score = max(best_sub, best_fuzzy)
821
-
822
- scored_groups.append((cl_title, group_files, best_score))
823
-
824
- # Apply strict score threshold of 0.55 to completely filter out unrelated suggestion buttons
825
- scored_groups = [g for g in scored_groups if g[2] >= 0.55]
826
- scored_groups.sort(key=lambda x: (-x[2], -len(x[1]), x[0].lower()))
827
-
828
- # If we have groups, present the Movie Suggestion UI
829
- if scored_groups:
830
- btn = []
831
- for cl_title, group_files, score in scored_groups[:10]:
832
- count_files = len(group_files)
833
- h = hashlib.md5(cl_title.encode('utf-8')).hexdigest()[:12]
834
- MOVIE_CALLBACK_CACHE.set(h, (cl_title, "AI Suggestion"))
835
-
836
- btn.append([
837
- InlineKeyboardButton(
838
- text=f"🎬 {cl_title} — {count_files} file{'s' if count_files > 1 else ''}",
839
- callback_data=f"m_s {h}"
840
- )
841
- ])
842
-
843
- original_search_esc = original_search.replace("[", "\\[").replace("]", "\\]")
844
- if corrected_query and corrected_query.strip().lower() != original_search.strip().lower():
845
- corrected_query_esc = corrected_query.replace("[", "\\[").replace("]", "\\]")
846
- model_display = ai_model or "gemini-3.1-flash-lite"
847
- confidence = int(scored_groups[0][2] * 100) if scored_groups else 95
848
- if confidence < 50:
849
- confidence = 90
850
- result = (
851
- f"❌ **No exact match for** `{original_search_esc}`\n\n"
852
- f"✨ **AI suggests (confidence: {confidence}%):**\n"
853
- f"🎯 **Corrected:** `{corrected_query_esc}`\n"
854
- f"🤖 **Model:** `{model_display}`\n\n"
855
- f"👇 **Select the movie you meant:**"
856
- )
857
- else:
858
- result = (
859
- f"❌ **No exact match for** `{original_search_esc}`\n\n"
860
- f"💡 **Did you mean one of these?**"
861
- )
862
-
863
- req_hash = hashlib.md5(original_search.encode('utf-8')).hexdigest()[:12]
864
- from mfinder.plugins.requests import REQUEST_QUERY_CACHE
865
- REQUEST_QUERY_CACHE.set(req_hash, original_search)
866
-
867
- btn.append([
868
- InlineKeyboardButton(
869
- text=f"📩 Request Movie: \"{original_search}\"",
870
- callback_data=f"req_send {req_hash}"
871
- )
872
- ])
873
-
874
- shown_titles = [cl_title for cl_title, group_files, score in scored_groups[:10]]
875
- raw_count = len(suggestions) if suggestions else 0
876
- LOGGER.info(f"Displaying {len(shown_titles)} movie suggestion button(s) in DB for search '{original_search}' (out of {raw_count} AI raw suggestions)")
877
- return result, btn, shown_titles
878
-
879
- if search_settings:
880
- if search_settings.button_mode:
881
- button_mode = "ON"
882
- else:
883
- button_mode = "OFF"
884
- else:
885
- button_mode = "OFF"
886
-
887
- if search_settings:
888
- if search_settings.link_mode:
889
- link_mode = "ON"
890
- else:
891
- link_mode = "OFF"
892
- else:
893
- link_mode = "ON"
894
-
895
- if button_mode == "ON" and link_mode == "OFF":
896
- search_md = "Button"
897
- elif link_mode == "ON":
898
- search_md = "Link"
899
- else:
900
- search_md = "Text Button"
901
-
902
- if files:
903
- btn = []
904
- index = (page_no - 1) * 10
905
- crnt_pg = index // 10 + 1
906
- tot_pg = (count + 10 - 1) // 10
907
- btn_count = 0
908
- header_prefix = ""
909
- if search_type == "Fuzzy Match":
910
- header_prefix = f"⚠️ **No exact matches for** `{original_search}`.\n💡 **Showing close fuzzy matches:**\n\n"
911
- elif search_type == "AI Corrected":
912
- header_prefix = f"🤖 **AI corrected query:** `{original_search}` ➔ `{search}`\n🍿 **Showing suggested results:**\n\n"
913
-
914
- # Shorten URLs concurrently in parallel to avoid sequential network delays
915
- async def get_short_url(f):
916
- long_url = f"https://telegram.me/{username}?start={f.file_id}"
917
- if bypass_shortening:
918
- return long_url
919
- try:
920
- return await shorten_url(long_url)
921
- except Exception as e:
922
- print(f"Error shortening URL for {f.file_name}: {e}")
923
- return long_url
924
-
925
- short_urls = await asyncio.gather(*(get_short_url(f) for f in files))
926
-
927
- result = header_prefix + f"**Search Query:** `{search}`\n**Total Results:** `{count}`\n**Page:** `{crnt_pg}/{tot_pg}`\n**Precise Search: **`{precise_search}`\n**Result Mode:** `{search_md}`\n"
928
- page = page_no
929
- for idx, file in enumerate(files):
930
- file_id = file.file_id
931
- filename = f"[{get_size(file.file_size)}]{file.file_name}"
932
- short_url = short_urls[idx]
933
-
934
- if button_mode == "ON":
935
- btn_kb = InlineKeyboardButton(
936
- text=f"{filename}", url=short_url
937
- )
938
- btn.append([btn_kb])
939
- elif link_mode == "ON":
940
- index += 1
941
- btn_count += 1
942
- filename = f"**{index}.** [{file.file_name}]({short_url}) - `[{get_size(file.file_size)}]`"
943
- result += "\n" + filename
944
- else:
945
- index += 1
946
- btn_count += 1
947
- filename = (
948
- f"**{index}.** `{file.file_name}` - `[{get_size(file.file_size)}]`"
949
- )
950
- result += "\n" + filename
951
-
952
- btn_kb = InlineKeyboardButton(
953
- text=f"{index}", url=short_url
954
- )
955
-
956
- if btn_count == 1 or btn_count == 6:
957
- btn.append([btn_kb])
958
- elif 6 > btn_count > 1:
959
- btn[0].append(btn_kb)
960
- else:
961
- btn[1].append(btn_kb)
962
-
963
- # Generate a unique hash for the search query to stay within 64 bytes
964
- h = hashlib.md5(search.encode('utf-8')).hexdigest()[:12]
965
- SEARCH_QUERY_CACHE.set(h, search)
966
-
967
- nxt_kb = InlineKeyboardButton(
968
- text="Next >>",
969
- callback_data=f"nxt_pg {user_id} {page + 1} {h}",
970
- )
971
- prev_kb = InlineKeyboardButton(
972
- text="<< Previous",
973
- callback_data=f"prev_pg {user_id} {page - 1} {h}",
974
- )
975
-
976
- kb = []
977
- if crnt_pg == 1 and tot_pg > 1:
978
- kb = [nxt_kb]
979
- elif crnt_pg > 1 and crnt_pg < tot_pg:
980
- kb = [prev_kb, nxt_kb]
981
- elif tot_pg > 1:
982
- kb = [prev_kb]
983
-
984
- if kb:
985
- btn.append(kb)
986
-
987
- if button_mode and link_mode == "OFF":
988
- result = (
989
- result
990
- + "\n\n"
991
- + "🔻 __Tap on below corresponding file number to download.__ 🔻"
992
- )
993
- elif link_mode == "ON":
994
- result = result + "\n\n" + " __Tap on file name & then start to download.__"
995
-
996
- return result, btn, []
997
-
998
- req_hash = hashlib.md5(original_search.encode('utf-8')).hexdigest()[:12]
999
- from mfinder.plugins.requests import REQUEST_QUERY_CACHE
1000
- REQUEST_QUERY_CACHE.set(req_hash, original_search)
1001
-
1002
- original_search_esc = original_search.replace("[", "\\[").replace("]", "\\]")
1003
- no_res_text = (
1004
- f"❌ **No results found for** `{original_search_esc}`\n\n"
1005
- f"💡 If this movie is missing, tap below to submit a request to our admins!"
1006
- )
1007
- no_res_btn = [[
1008
- InlineKeyboardButton(
1009
- text=f"📩 Request Movie: \"{original_search}\"",
1010
- callback_data=f"req_send {req_hash}"
1011
- )
1012
- ]]
1013
- return no_res_text, no_res_btn, []
1014
-
1015
- @Client.on_callback_query(filters.regex(r"^file (.+)$"))
1016
- async def get_files(bot, query):
1017
- user_id = query.from_user.id
1018
-
1019
- file_id = None
1020
- if isinstance(query, CallbackQuery):
1021
- file_id = query.data.split()[1]
1022
- elif isinstance(query, Message):
1023
- file_id = query.text.split()[1]
1024
-
1025
- if not await verify_force_sub(bot, query, pending_file_id=file_id):
1026
- return
1027
-
1028
- admin_settings = await get_admin_settings()
1029
-
1030
- if admin_settings and admin_settings.repair_mode and user_id not in ADMINS:
1031
- if isinstance(query, CallbackQuery):
1032
- await query.answer("⚙️ Bot is under maintenance. Please try again later.", show_alert=True)
1033
- elif isinstance(query, Message):
1034
- await query.reply_text(
1035
- "⚙️ **Bot Under Maintenance!**\n\nThe bot is currently undergoing scheduled maintenance or repair. Please try again later.",
1036
- quote=True
1037
- )
1038
- return
1039
-
1040
- if admin_settings and admin_settings.token_shortener_enabled and user_id not in ADMINS:
1041
- if not await is_token_valid(user_id):
1042
- if isinstance(query, CallbackQuery):
1043
- file_id = query.data.split()[1]
1044
- await query.answer("⚠️ Access token expired. Generating a new link...", show_alert=True)
1045
- await create_and_send_token_link(bot, query.message, admin_settings, target_file_id=file_id)
1046
- elif isinstance(query, Message):
1047
- file_id = query.text.split()[1]
1048
- await create_and_send_token_link(bot, query, admin_settings, target_file_id=file_id)
1049
- return
1050
-
1051
- if isinstance(query, CallbackQuery):
1052
- file_id = query.data.split()[1]
1053
- await query.answer("Sending file...", cache_time=60)
1054
- cbq = True
1055
- elif isinstance(query, Message):
1056
- file_id = query.text.split()[1]
1057
- cbq = False
1058
- filedetails = await get_file_details(file_id)
1059
- for files in filedetails:
1060
- f_caption = files.caption
1061
- if admin_settings.custom_caption:
1062
- f_caption = f"**{admin_settings.custom_caption}**"
1063
- elif f_caption is None:
1064
- f_caption = f"**{files.file_name}**"
1065
- else:
1066
- f_caption = f"**{f_caption}**"
1067
-
1068
- if admin_settings.caption_uname:
1069
- f_caption = f_caption + "\n" + admin_settings.caption_uname
1070
-
1071
- # Appends the "🌐 Direct Browser Download 🌐" inline button under the media if STREAM_URL is set
1072
- stream_url = os.environ.get("STREAM_URL")
1073
- reply_markup = None
1074
- if stream_url:
1075
- import urllib.parse
1076
- stream_url = stream_url.rstrip("/")
1077
- quoted_filename = urllib.parse.quote(files.file_name)
1078
- download_url = f"{stream_url}/dl/{quoted_filename}"
1079
- reply_markup = InlineKeyboardMarkup([
1080
- [InlineKeyboardButton("🌐 Direct Browser Download 🌐", url=download_url)]
1081
- ])
1082
-
1083
- if cbq:
1084
- msg = await query.message.reply_cached_media(
1085
- file_id=file_id,
1086
- caption=f_caption,
1087
- parse_mode=ParseMode.MARKDOWN,
1088
- reply_markup=reply_markup,
1089
- quote=True,
1090
- )
1091
- else:
1092
- msg = await query.reply_cached_media(
1093
- file_id=file_id,
1094
- caption=f_caption,
1095
- parse_mode=ParseMode.MARKDOWN,
1096
- reply_markup=reply_markup,
1097
- quote=True,
1098
- )
1099
-
1100
- user_target = query.from_user if hasattr(query, "from_user") and query.from_user else None
1101
- if user_target:
1102
- asyncio.create_task(
1103
- log_file_delivery(
1104
- bot=bot,
1105
- user=user_target,
1106
- file_name=files.file_name,
1107
- file_size=get_size(files.file_size),
1108
- file_id=files.file_id
1109
- )
1110
- )
1111
-
1112
- if admin_settings.auto_delete:
1113
- delay_dur = float(admin_settings.auto_delete)
1114
- delay = delay_dur / 60 if delay_dur > 60 else delay_dur
1115
- delay = round(delay, 2)
1116
- minsec = str(delay) + " mins" if delay_dur > 60 else str(delay) + " secs"
1117
- disc = await bot.send_message(
1118
- user_id,
1119
- f"Please save the file to your saved messages, it will be deleted in {minsec}",
1120
- )
1121
- await asyncio.sleep(delay_dur)
1122
- await disc.delete()
1123
- await msg.delete()
1124
- await bot.send_message(user_id, "File has been deleted")
1125
-
1126
- def get_size(size):
1127
- units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"]
1128
- size = float(size)
1129
- i = 0
1130
- while size >= 1024.0 and i < len(units):
1131
- i += 1
1132
- size /= 1024.0
1133
- return f"{size:.2f} {units[i]}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/plugins/stream_server.py DELETED
@@ -1,98 +0,0 @@
1
- import urllib.parse
2
- import re
3
- from fastapi import APIRouter, Request, HTTPException, Header
4
- from fastapi.responses import StreamingResponse, Response
5
- from mfinder.db.files_sql import SESSION, Files
6
-
7
- router = APIRouter()
8
-
9
- def get_file_by_name(file_name: str) -> Files:
10
- """Safely retrieves file details from the SQL database without session leaking."""
11
- try:
12
- session = SESSION()
13
- return session.query(Files).filter_by(file_name=file_name).first()
14
- except Exception as e:
15
- print(f"Error querying file details for download: {e}")
16
- return None
17
- finally:
18
- try:
19
- SESSION.close()
20
- except Exception:
21
- pass
22
-
23
- @router.get("/dl/{file_name}")
24
- async def download_file(request: Request, file_name: str, range: str = Header(None)):
25
- """
26
- Asynchronously streams a Telegram file directly to the browser chunk-by-chunk.
27
- Supports HTTP Range requests (206 Partial Content) for accelerated multi-thread downloads (IDM/ADM/Chrome).
28
- Uses a dedicated stream_client to keep main bot commands 100% fast and responsive for 50+ concurrent users.
29
- """
30
- decoded_file_name = urllib.parse.unquote(file_name)
31
-
32
- file_details = get_file_by_name(decoded_file_name)
33
- if not file_details:
34
- raise HTTPException(status_code=404, detail="File not found in database.")
35
-
36
- file_id = file_details.file_id
37
- file_size = int(file_details.file_size)
38
- mime_type = file_details.mime_type or "application/octet-stream"
39
-
40
- # Use dedicated stream_client if available to isolate file streaming from bot commands
41
- stream_client = getattr(request.app.state, "stream_client", None) or getattr(request.app.state, "client", None)
42
- if not stream_client:
43
- raise HTTPException(status_code=503, detail="Telegram client gateway not initialized.")
44
-
45
- start_bytes = 0
46
- end_bytes = file_size - 1
47
-
48
- if range:
49
- range_match = re.match(r"bytes=(\d+)-(\d+)?", range)
50
- if range_match:
51
- start_bytes = int(range_match.group(1))
52
- if range_match.group(2):
53
- end_bytes = int(range_match.group(2))
54
-
55
- if start_bytes >= file_size or end_bytes >= file_size or start_bytes > end_bytes:
56
- headers = {"Content-Range": f"bytes */{file_size}"}
57
- return Response(status_code=416, headers=headers)
58
-
59
- content_length = (end_bytes - start_bytes) + 1
60
-
61
- chunk_offset = start_bytes // (1024 * 1024)
62
- skip_bytes = start_bytes % (1024 * 1024)
63
-
64
- async def media_generator():
65
- bytes_sent = 0
66
- try:
67
- first = True
68
- async for chunk in stream_client.stream_media(file_id, offset=chunk_offset):
69
- if first:
70
- first = False
71
- if skip_bytes > 0:
72
- chunk = chunk[skip_bytes:]
73
-
74
- if bytes_sent + len(chunk) > content_length:
75
- chunk = chunk[:content_length - bytes_sent]
76
-
77
- if not chunk:
78
- break
79
-
80
- yield chunk
81
- bytes_sent += len(chunk)
82
-
83
- if bytes_sent >= content_length:
84
- break
85
- except Exception as e:
86
- print(f"Error occurred while streaming file '{decoded_file_name}': {e}")
87
-
88
- headers = {
89
- "Content-Disposition": f"attachment; filename=\"{decoded_file_name}\"; filename*=UTF-8''{urllib.parse.quote(decoded_file_name)}",
90
- "Content-Length": str(content_length),
91
- "Accept-Ranges": "bytes"
92
- }
93
-
94
- if range:
95
- headers["Content-Range"] = f"bytes {start_bytes}-{end_bytes}/{file_size}"
96
- return StreamingResponse(media_generator(), status_code=206, media_type=mime_type, headers=headers)
97
- else:
98
- return StreamingResponse(media_generator(), status_code=200, media_type=mime_type, headers=headers)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/plugins/trending.py DELETED
@@ -1,191 +0,0 @@
1
- import hashlib
2
- import asyncio
3
- from pyrogram import Client, filters
4
- from pyrogram.enums import ParseMode
5
- from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
6
- from mfinder.db.analytics_sql import get_top_trending_movies, get_latest_uploaded_movies
7
- from mfinder.plugins.serve import MOVIE_CALLBACK_CACHE, verify_force_sub
8
-
9
- @Client.on_message(filters.command(["trending"]) & filters.private)
10
- async def trending_command(bot, message):
11
- """Displays top 10 trending searched movies from the 7-day weekly cycle."""
12
- if not await verify_force_sub(bot, message, pending_query="/trending"):
13
- return
14
- trending_list = await get_top_trending_movies(limit=10)
15
-
16
- if not trending_list:
17
- await message.reply_text(
18
- "ℹ️ **No trending movies data available for this week yet.**\n\n"
19
- "Search for movies to build the trending list!",
20
- quote=True,
21
- parse_mode=ParseMode.MARKDOWN
22
- )
23
- return
24
-
25
- buttons = []
26
- for item in trending_list:
27
- if len(item) == 3:
28
- cl_title, count_files, year = item
29
- else:
30
- cl_title, count_files = item
31
- year = None
32
-
33
- h = hashlib.md5(cl_title.encode('utf-8')).hexdigest()[:12]
34
- MOVIE_CALLBACK_CACHE.set(h, (cl_title, "Trending List"))
35
- display_title = f"{cl_title} ({year})" if year else cl_title
36
- buttons.append([
37
- InlineKeyboardButton(
38
- text=f"🎬 {display_title} — {count_files} file{'s' if count_files > 1 else ''}",
39
- callback_data=f"m_s {h}"
40
- )
41
- ])
42
-
43
- text = "🔥 **Top Trending Movies This Week**\n\n👇 Select a movie below to view files:"
44
- reply_msg = await message.reply_text(
45
- text=text,
46
- reply_markup=InlineKeyboardMarkup(buttons),
47
- parse_mode=ParseMode.MARKDOWN,
48
- quote=True
49
- )
50
-
51
- # Auto-delete message after 15 minutes
52
- async def auto_delete_msg(msg):
53
- await asyncio.sleep(900)
54
- try:
55
- await msg.delete()
56
- except Exception:
57
- pass
58
- asyncio.create_task(auto_delete_msg(reply_msg))
59
-
60
- @Client.on_message(filters.command(["newuploads"]) & filters.private)
61
- async def new_uploads_command(bot, message):
62
- """Displays latest 25 newly uploaded movies in descending order."""
63
- if not await verify_force_sub(bot, message, pending_query="/newuploads"):
64
- return
65
- latest_list = await get_latest_uploaded_movies(limit=25)
66
-
67
- if not latest_list:
68
- await message.reply_text("ℹ️ **No newly uploaded movies available.**", quote=True)
69
- return
70
-
71
- buttons = []
72
- for item in latest_list:
73
- if len(item) == 3:
74
- cl_title, count_files, year = item
75
- else:
76
- cl_title, count_files = item
77
- year = None
78
-
79
- h = hashlib.md5(cl_title.encode('utf-8')).hexdigest()[:12]
80
- MOVIE_CALLBACK_CACHE.set(h, (cl_title, "New Uploads List"))
81
- display_title = f"{cl_title} ({year})" if year else cl_title
82
- buttons.append([
83
- InlineKeyboardButton(
84
- text=f"🎬 {display_title} — {count_files} file{'s' if count_files > 1 else ''}",
85
- callback_data=f"m_s {h}"
86
- )
87
- ])
88
-
89
- text = f"🆕 **Newly Uploaded Movies (Top 25)**\n\n👇 Select a movie below to view files:"
90
- reply_msg = await message.reply_text(
91
- text=text,
92
- reply_markup=InlineKeyboardMarkup(buttons),
93
- parse_mode=ParseMode.MARKDOWN,
94
- quote=True
95
- )
96
-
97
- # Auto-delete message after 15 minutes
98
- async def auto_delete_msg(msg):
99
- await asyncio.sleep(900)
100
- try:
101
- await msg.delete()
102
- except Exception:
103
- pass
104
- asyncio.create_task(auto_delete_msg(reply_msg))
105
-
106
- @Client.on_callback_query(filters.regex(r"^(trnd_list|new_up_list)$"))
107
- async def trending_newuploads_callback(bot, query):
108
- """Handles callback buttons for Trending and New Uploads by editing message in-place."""
109
- action = query.data
110
- pending = "/trending" if action == "trnd_list" else "/newuploads"
111
- if not await verify_force_sub(bot, query, pending_query=pending):
112
- return
113
- action = query.data
114
- if action == "trnd_list":
115
- trending_list = await get_top_trending_movies(limit=10)
116
-
117
- if not trending_list:
118
- await query.answer("ℹ️ No trending movies data available for this week yet.", show_alert=True)
119
- return
120
-
121
- buttons = []
122
- for item in trending_list:
123
- if len(item) == 3:
124
- cl_title, count_files, year = item
125
- else:
126
- cl_title, count_files = item
127
- year = None
128
-
129
- h = hashlib.md5(cl_title.encode('utf-8')).hexdigest()[:12]
130
- MOVIE_CALLBACK_CACHE.set(h, (cl_title, "Trending List"))
131
- display_title = f"{cl_title} ({year})" if year else cl_title
132
- buttons.append([
133
- InlineKeyboardButton(
134
- text=f"🎬 {display_title} — {count_files} file{'s' if count_files > 1 else ''}",
135
- callback_data=f"m_s {h}"
136
- )
137
- ])
138
-
139
- buttons.append([
140
- InlineKeyboardButton("🔙 Back to Menu", callback_data="back_m")
141
- ])
142
-
143
- text = "🔥 **Top Trending Movies This Week**\n\n👇 Select a movie below to view files:"
144
- await query.answer()
145
- try:
146
- await query.message.edit_text(
147
- text=text,
148
- reply_markup=InlineKeyboardMarkup(buttons),
149
- parse_mode=ParseMode.MARKDOWN
150
- )
151
- except Exception:
152
- pass
153
-
154
- elif action == "new_up_list":
155
- latest_list = await get_latest_uploaded_movies(limit=25)
156
- if not latest_list:
157
- await query.answer("ℹ️ No newly uploaded movies available.", show_alert=True)
158
- return
159
-
160
- buttons = []
161
- for item in latest_list:
162
- if len(item) == 3:
163
- cl_title, count_files, year = item
164
- else:
165
- cl_title, count_files = item
166
- year = None
167
-
168
- h = hashlib.md5(cl_title.encode('utf-8')).hexdigest()[:12]
169
- MOVIE_CALLBACK_CACHE.set(h, (cl_title, "New Uploads List"))
170
- display_title = f"{cl_title} ({year})" if year else cl_title
171
- buttons.append([
172
- InlineKeyboardButton(
173
- text=f"🎬 {display_title} — {count_files} file{'s' if count_files > 1 else ''}",
174
- callback_data=f"m_s {h}"
175
- )
176
- ])
177
-
178
- buttons.append([
179
- InlineKeyboardButton("🔙 Back to Menu", callback_data="back_m")
180
- ])
181
-
182
- text = f"🆕 **Newly Uploaded Movies (Top 25)**\n\n👇 Select a movie below to view files:"
183
- await query.answer()
184
- try:
185
- await query.message.edit_text(
186
- text=text,
187
- reply_markup=InlineKeyboardMarkup(buttons),
188
- parse_mode=ParseMode.MARKDOWN
189
- )
190
- except Exception:
191
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/plugins/user_settings.py DELETED
@@ -1,125 +0,0 @@
1
- from pyrogram import Client, filters
2
- from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
3
- from mfinder.db.settings_sql import get_search_settings, change_search_settings
4
- from mfinder.utils.constants import SET_MSG
5
-
6
-
7
- @Client.on_message(filters.command(["settings"]))
8
- async def user_settings(bot, update):
9
- from mfinder.plugins.serve import verify_force_sub
10
- if not await verify_force_sub(bot, update):
11
- return
12
- user_id = update.from_user.id
13
- set_kb = await find_search_settings(user_id)
14
- await bot.send_message(
15
- chat_id=user_id,
16
- text=SET_MSG,
17
- reply_markup=set_kb,
18
- )
19
-
20
-
21
- @Client.on_callback_query(filters.regex(r"^prec (.+)$"))
22
- async def set_precise_mode(bot, query):
23
- from mfinder.plugins.serve import verify_force_sub
24
- if not await verify_force_sub(bot, query):
25
- return
26
- user_id = query.from_user.id
27
- prsc_mode = query.data.split()[1]
28
- if prsc_mode == "on":
29
- await change_search_settings(user_id, precise_mode=True)
30
- if prsc_mode == "off":
31
- await change_search_settings(user_id, precise_mode=False)
32
- if prsc_mode == "md":
33
- await query.answer(text="Toggle Precise Search ON/OFF", show_alert=False)
34
- return
35
-
36
- set_kb = await find_search_settings(user_id)
37
-
38
- await query.message.edit(
39
- text=SET_MSG,
40
- reply_markup=set_kb,
41
- )
42
-
43
-
44
- @Client.on_callback_query(filters.regex(r"^res (.+)$"))
45
- async def set_list_mode(bot, query):
46
- from mfinder.plugins.serve import verify_force_sub
47
- if not await verify_force_sub(bot, query):
48
- return
49
- user_id = query.from_user.id
50
- result_mode = query.data.split()[1]
51
- if result_mode == "btnn":
52
- await change_search_settings(
53
- user_id, button_mode=True, link_mode=False, list_mode=False
54
- )
55
- if result_mode == "link":
56
- await change_search_settings(
57
- user_id, button_mode=False, link_mode=True, list_mode=False
58
- )
59
- if result_mode == "list":
60
- await change_search_settings(
61
- user_id, button_mode=False, link_mode=False, list_mode=True
62
- )
63
- if result_mode == "mode":
64
- await query.answer(text="Toggle Button/Link/List Mode", show_alert=False)
65
- return
66
-
67
- set_kb = await find_search_settings(user_id)
68
-
69
- await query.message.edit(
70
- text=SET_MSG,
71
- reply_markup=set_kb,
72
- )
73
-
74
-
75
- async def find_search_settings(user_id):
76
- search_settings = await get_search_settings(user_id)
77
-
78
- kb = [
79
- InlineKeyboardButton("[Precise Mode]:", callback_data="prec md"),
80
- ]
81
-
82
- on_kb = InlineKeyboardButton("❌ Disabled", callback_data="prec on")
83
- off_kb = InlineKeyboardButton("✅ Enabled", callback_data="prec off")
84
-
85
- if search_settings:
86
- precise_mode = search_settings.precise_mode
87
- if precise_mode:
88
- precise_mode = "Enabled"
89
- kb.append(off_kb)
90
- else:
91
- precise_mode = "Disabled"
92
- kb.append(on_kb)
93
- else:
94
- await change_search_settings(user_id)
95
- precise_mode = "Disabled"
96
- kb.append(on_kb)
97
-
98
- bkb = [
99
- InlineKeyboardButton("[Result Mode]:", callback_data="res mode"),
100
- ]
101
-
102
- btn_kb = InlineKeyboardButton("📃 List", callback_data="res btnn")
103
- link_kb = InlineKeyboardButton("🔳 Button", callback_data="res link")
104
- list_kb = InlineKeyboardButton("🔗 HyperLink", callback_data="res list")
105
-
106
- if search_settings:
107
- button_mode = search_settings.button_mode
108
- link_mode = search_settings.link_mode
109
- list_mode = search_settings.list_mode
110
- if button_mode:
111
- bkb.append(link_kb)
112
- elif link_mode:
113
- bkb.append(list_kb)
114
- elif list_mode:
115
- bkb.append(btn_kb)
116
- else:
117
- await change_search_settings(user_id, link_mode=True)
118
- bkb.append(list_kb)
119
- else:
120
- await change_search_settings(user_id, link_mode=True)
121
- bkb.append(list_kb)
122
-
123
- set_kb = InlineKeyboardMarkup([kb, bkb])
124
-
125
- return set_kb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/utils/constants.py DELETED
@@ -1,98 +0,0 @@
1
- from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
2
-
3
-
4
- START_KB = InlineKeyboardMarkup(
5
- [
6
- [
7
- InlineKeyboardButton("🆘 Help", callback_data="help_cb"),
8
- ]
9
- ]
10
- )
11
-
12
- HELP_KB = InlineKeyboardMarkup(
13
- [
14
- [
15
- InlineKeyboardButton("🔙 Back", callback_data="back_m"),
16
- ],
17
- ]
18
- )
19
-
20
-
21
- STARTMSG = "Hi **[{}](tg://user?id={})**, I am a FIRE⚡BOLT bot which finds media from my database channel. Just send query to find the media.\nSend /help for more or you can toggle your settings by sending /settings."
22
-
23
-
24
- HELPMSG = """
25
- REQUEST FORMAT :- *MOVIE NAME WITH YEAR (LANGUAGE OPTIONAL)
26
-
27
- REQUEST LIKE THIS :-
28
- =>IRON MAN✅
29
- =>IRON MAN 2008✅
30
- =>IRON MAN 2008 TAMIL✅
31
-
32
- DON'T REQUEST LIKE THIS :-
33
- =>IRON MAN MOVIE ❌
34
- =>IRON MAN 2008 GIVE ❌
35
- =>IRON MAN 2008 ANAPUGA ❌
36
-
37
- [🙅Don't use this words while searching: HD, MOVIES, SEND, PREDVD, WEB-DL, ANAPUGA, SEND PANNUGA, HDrip, VENUM]
38
-
39
- If Any Movies Not Available Send Your MOVIE NAMES Via `/request <Movie Name>` or REPORT HERE 👉 @ANGRY_BIRD22_bot
40
-
41
- ━━━━━━━━━━━━━━━━━━━━━━
42
- **You can find the bot commands here.**
43
-
44
- **User Commands:-**
45
- /start - Start the bot and view main menu
46
- /help - Show this help message
47
- /trending - View top 10 trending movies this week
48
- /newuploads - View latest 25 newly uploaded movies
49
- /request - Request a missing movie from admins (`/request Movie Name`)
50
- /settings - Toggle settings of Precise Mode and Button Mode
51
-
52
- **Precise Mode:**
53
- - If Enabled, bot will match the word & return results with only the exact match
54
- - If Disabled, bot will match the word & return all the results containing the word
55
-
56
- **Result Mode:**
57
- - If Button, bot will return results in button format
58
- - If List, bot will return results in list format
59
- - If HyperLink, bot will return results in hyperlink format
60
-
61
- **Admin Commands:-**
62
- /requests - View pending movie requests summary
63
- /logs - Get logs as a file
64
- /server - Get server stats
65
- /restart - Restart the bot
66
- /stats - Get bot user stats
67
- /broadcast - Reply to a message to send that to all bot users
68
- /index - Start indexing a database channel (bot must be admin of the channel if that is private channel)
69
- *(You can just forward the message from database channel for starting indexing, no need to use the /index command)*
70
- /delete - Reply to a file to delete it from database
71
- /autodelete - Set file auto delete time in seconds
72
- /repairmode - Enable or disable repair mode - If on, bot will not send any files
73
- /customcaption - Set custom caption for files
74
- /adminsettings - Get current admin settings
75
- /ban - Ban a user from bot - `/ban user_id`
76
- /unban - Unban a user from bot - `/unban user_id`
77
- /addfilter - Add a text filter - `/addfilter filter message` or `/addfilter "filter multiple words" message` *(If a filter is there, bot will send the filter rather than file)*
78
- /delfilter - Delete a text filter - `/delfilter filter`
79
- /listfilters - List all filters currently added in the bot
80
- /forcesub - Set force subscribe channel - `/forcesub channel_id` *(Bot must be admin of that channel)*
81
- /checklink - Check invite link for force subscribe channel
82
- /total - Get count of total files in DB
83
- """
84
-
85
- SET_MSG = """
86
- **Below are your current settings:**
87
-
88
- `Info`
89
- **Precise Mode:**
90
- - If Enabled, bot will match the word & return results with only the exact match
91
- - If Disabled, bot will match the word & return all the results containing the word
92
-
93
- **Result Mode:**
94
- - If HyperLink, bot will return results in hyperlink format
95
- - If Button, bot will return results in button format
96
- - If List, bot will return results in list format
97
-
98
- You can toggle options using the buttons below:"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/utils/gemini_client.py DELETED
@@ -1,151 +0,0 @@
1
- import os
2
- import time
3
- import logging
4
- import requests
5
- import json
6
- import asyncio
7
-
8
- LOGGER = logging.getLogger(__name__)
9
-
10
- # Models ordered by highest free-tier daily quota (RPD) first, then by RPM.
11
- # This maximizes availability by burning through high-quota models before low-quota ones.
12
- # Models with 0/0 free-tier limits (gemini-2.0-flash, gemini-2.0-flash-lite, gemini-1.5-flash) are excluded.
13
- MODEL_PRIORITY_LIST = [
14
- "gemini-3.1-flash-lite", # 15 RPM, 500 RPD — Best free tier model
15
- "gemini-3.5-flash-lite", # 15 RPM, 500 RPD — Equal best
16
- "gemini-3.5-flash", # 5 RPM, 20 RPD
17
- "gemini-3.6-flash", # 5 RPM, 20 RPD
18
- "gemini-2.5-flash-lite", # 10 RPM, 20 RPD
19
- "gemini-2.5-flash", # 5 RPM, 20 RPD
20
- ]
21
-
22
- # Track cooldown end timestamps per model. Cooldown durations vary by error type.
23
- MODEL_COOLDOWNS = {}
24
-
25
- def get_api_key():
26
- """Retrieve Gemini API Key from environment variables."""
27
- return (
28
- os.environ.get("GEMINI_API_KEY")
29
- or os.environ.get("API_KEY")
30
- )
31
-
32
- def _call_gemini_sync(model_name: str, api_key: str, user_query: str) -> dict:
33
- """Synchronous HTTP call to Gemini API. Executed in a separate thread."""
34
- url = f"https://generativelanguage.googleapis.com/v1beta/models/{model_name}:generateContent?key={api_key}"
35
-
36
- headers = {
37
- "Content-Type": "application/json"
38
- }
39
-
40
- system_instruction = (
41
- "You are an expert movie query and franchise parser for global, Indian (Tamil, Telugu, Hindi, Malayalam, Kannada), and international cinema. "
42
- "Your task is to correct any spelling mistakes, extract clean keywords, and discover ALL parts, sequels, prequels, spin-offs, and RECENT/UPCOMING releases for that actor, director, or franchise. "
43
- "If the query mentions an actor name (e.g., 'vijay', 'thalapathy', 'rajini', 'prabhas', 'srk', 'kamal', 'ajith') or phrases like 'new movie', 'latest movie', '2024 movie', '2025 movie': "
44
- "1. Identify the actor/franchise. "
45
- "2. Include their latest/recent 2024-2026 released films, upcoming projects, tentative working titles (e.g. 'Jananayagan', 'The Greatest of All Time', 'GOAT', 'Leo', 'Varisu', 'Beast', 'Master') as well as classic popular hits. "
46
- "Include both short titles and full titles in the 'suggestions' list. Limit to top 15 most relevant entries. "
47
- "You MUST respond ONLY in valid JSON matching this schema: "
48
- "{\"corrected\": \"Corrected Movie Title\", \"keywords\": [\"keyword1\", \"keyword2\"], \"suggestions\": [\"Franchise Part 1\", \"Franchise Part 2\"]}. "
49
- "Do not include markdown blocks or any text other than the JSON."
50
- )
51
-
52
- payload = {
53
- "contents": [
54
- {
55
- "parts": [
56
- {"text": f"User query: '{user_query}'"}
57
- ]
58
- }
59
- ],
60
- "systemInstruction": {
61
- "parts": [
62
- {"text": system_instruction}
63
- ]
64
- },
65
- "generationConfig": {
66
- "responseMimeType": "application/json",
67
- "temperature": 0.1,
68
- "maxOutputTokens": 1024
69
- }
70
- }
71
-
72
- response = requests.post(url, headers=headers, json=payload, timeout=10)
73
-
74
- # Return status code info along with response for smart cooldown handling
75
- if response.status_code != 200:
76
- response.raise_for_status()
77
-
78
- data = response.json()
79
- try:
80
- text_response = data["candidates"][0]["content"]["parts"][0]["text"]
81
- return json.loads(text_response)
82
- except (KeyError, IndexError, json.JSONDecodeError) as e:
83
- LOGGER.error(f"Failed to parse response from model {model_name}: {e}. Raw response: {data}")
84
- raise ValueError("Invalid response format from Gemini API")
85
-
86
- async def get_ai_suggestions(user_query: str) -> dict:
87
- """
88
- Get movie spelling correction and keywords from Gemini.
89
- Iterates through the model fallback chain with smart cooldowns:
90
- - 429 (Rate Limit): 60s cooldown per model
91
- - 403 (Forbidden/Quota): 1 hour cooldown (daily quota likely exhausted)
92
- - 404 (Not Found): 24 hour cooldown (model endpoint doesn't exist)
93
- """
94
- api_key = get_api_key()
95
- if not api_key:
96
- LOGGER.error("No Gemini API Key found in environment variables.")
97
- return None
98
-
99
- # Filter out models currently on cooldown
100
- now = time.time()
101
- active_models = [m for m in MODEL_PRIORITY_LIST if MODEL_COOLDOWNS.get(m, 0) < now]
102
-
103
- if not active_models:
104
- # Find the model with the shortest remaining cooldown
105
- soonest_model = min(MODEL_COOLDOWNS, key=MODEL_COOLDOWNS.get)
106
- remaining = int(MODEL_COOLDOWNS[soonest_model] - now)
107
- LOGGER.warning(f"All Gemini models on cooldown. Next available: {soonest_model} in {remaining}s. Skipping AI query.")
108
- return None
109
-
110
- for model in active_models:
111
- try:
112
- LOGGER.info(f"Querying Gemini model: {model}")
113
- result = await asyncio.to_thread(_call_gemini_sync, model, api_key, user_query)
114
-
115
- # Simple validation of results
116
- if result and isinstance(result, dict) and "corrected" in result:
117
- result["model"] = model
118
- LOGGER.info(f"Gemini model {model} returned response. Corrected: '{result.get('corrected', '')}', Raw AI Suggestions: {len(result.get('suggestions', []))}")
119
- return result
120
-
121
- except requests.exceptions.HTTPError as e:
122
- status_code = e.response.status_code if e.response is not None else 0
123
-
124
- if status_code == 429:
125
- # Rate limit hit — short cooldown (60 seconds)
126
- MODEL_COOLDOWNS[model] = now + 60
127
- LOGGER.info(f"Model {model}: rate limited (429). Cooldown 60s.")
128
- continue
129
- elif status_code == 403:
130
- # Forbidden — likely daily quota (RPD) exhausted. Cooldown 1 hour.
131
- MODEL_COOLDOWNS[model] = now + 3600
132
- LOGGER.info(f"Model {model}: forbidden/quota exhausted (403). Cooldown 1h.")
133
- continue
134
- elif status_code == 404:
135
- # Model endpoint doesn't exist — cooldown 24 hours.
136
- MODEL_COOLDOWNS[model] = now + 86400
137
- LOGGER.info(f"Model {model}: not found (404). Cooldown 24h.")
138
- continue
139
- else:
140
- LOGGER.warning(f"HTTP error using Gemini model {model}: {e}")
141
- continue
142
-
143
- except requests.exceptions.Timeout:
144
- LOGGER.warning(f"Timeout querying Gemini model {model}. Trying next.")
145
- continue
146
- except Exception as e:
147
- LOGGER.warning(f"Unexpected error using Gemini model {model}: {e}")
148
- continue
149
-
150
- # All active models failed
151
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/utils/helpers.py DELETED
@@ -1,189 +0,0 @@
1
- from typing import Union
2
- import base64
3
- from struct import pack
4
- from pyrogram import raw
5
- from pyrogram.file_id import FileId, FileType, PHOTO_TYPES, DOCUMENT_TYPES
6
- import os
7
- from dotenv import load_dotenv
8
- import requests
9
-
10
- load_dotenv()
11
-
12
- def get_input_file_from_file_id(
13
- file_id: str,
14
- expected_file_type: FileType = None,
15
- ) -> Union["raw.types.InputPhoto", "raw.types.InputDocument"]:
16
- try:
17
- decoded = FileId.decode(file_id)
18
- except Exception:
19
- raise ValueError(
20
- f'Failed to decode "{file_id}". The value does not represent an existing local file, '
21
- f"HTTP URL, or valid file id."
22
- )
23
-
24
- file_type = decoded.file_type
25
-
26
- if expected_file_type is not None and file_type != expected_file_type:
27
- raise ValueError(
28
- f'Expected: "{expected_file_type}", got "{file_type}" file_id instead'
29
- )
30
-
31
- if file_type in (FileType.THUMBNAIL, FileType.CHAT_PHOTO):
32
- raise ValueError(f"This file_id can only be used for download: {file_id}")
33
-
34
- if file_type in PHOTO_TYPES:
35
- return raw.types.InputPhoto(
36
- id=decoded.media_id,
37
- access_hash=decoded.access_hash,
38
- file_reference=decoded.file_reference,
39
- )
40
-
41
- if file_type in DOCUMENT_TYPES:
42
- return raw.types.InputDocument(
43
- id=decoded.media_id,
44
- access_hash=decoded.access_hash,
45
- file_reference=decoded.file_reference,
46
- )
47
-
48
- raise ValueError(f"Unknown file id: {file_id}")
49
-
50
- def encode_file_id(s: bytes) -> str:
51
- r = b""
52
- n = 0
53
-
54
- for i in s + bytes([22]) + bytes([4]):
55
- if i == 0:
56
- n += 1
57
- else:
58
- if n:
59
- r += b"\x00" + bytes([n])
60
- n = 0
61
-
62
- r += bytes([i])
63
-
64
- return base64.urlsafe_b64encode(r).decode().rstrip("=")
65
-
66
- def encode_file_ref(file_ref: bytes) -> str:
67
- return base64.urlsafe_b64encode(file_ref).decode().rstrip("=")
68
-
69
- def unpack_new_file_id(new_file_id):
70
- """Return file_id, file_ref"""
71
- decoded = FileId.decode(new_file_id)
72
- file_id = encode_file_id(
73
- pack(
74
- "<iiqq",
75
- int(decoded.file_type),
76
- decoded.dc_id,
77
- decoded.media_id,
78
- decoded.access_hash,
79
- )
80
- )
81
- file_ref = encode_file_ref(decoded.file_reference)
82
- return file_id, file_ref
83
-
84
- def edit_caption(c_caption):
85
- return c_caption
86
-
87
- import os
88
- import requests
89
-
90
- import asyncio
91
- import time
92
-
93
- SHORT_URL_CACHE = {}
94
- SHORTEN_COOLDOWN_UNTIL = 0.0
95
- SHORTEN_CONSECUTIVE_FAILURES = 0
96
-
97
- HTTP_SESSION = requests.Session()
98
-
99
- def _shorten_url_sync(api_url, params):
100
- try:
101
- headers = {
102
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
103
- }
104
- response = HTTP_SESSION.get(api_url, params=params, headers=headers, verify=True, timeout=10)
105
- if response.status_code == 200:
106
- try:
107
- data = response.json()
108
- if isinstance(data, dict):
109
- short_link = (
110
- data.get('shortenedUrl') or
111
- data.get('shorturl') or
112
- data.get('short_url') or
113
- data.get('url') or
114
- data.get('link') or
115
- data.get('shortened_url')
116
- )
117
- if short_link:
118
- return str(short_link).strip()
119
- except Exception:
120
- pass
121
-
122
- text_resp = response.text.strip()
123
- if text_resp.startswith("http://") or text_resp.startswith("https://"):
124
- return text_resp
125
- else:
126
- print(f"Shortener API HTTP error {response.status_code}: {response.text[:200]}")
127
- except Exception as e:
128
- print(f"An error occurred in shortener request: {e}")
129
- return None
130
-
131
- async def shorten_url(long_url, force=False):
132
- """
133
- Shortens a given URL using the configured dynamic shortener site and API key.
134
- If the shortener is turned off or not configured, it returns the long URL directly.
135
- Runs asynchronously using a thread pool to avoid blocking the event loop.
136
- Caches shortened URLs in memory.
137
- """
138
- global SHORTEN_COOLDOWN_UNTIL, SHORTEN_CONSECUTIVE_FAILURES
139
-
140
- if long_url in SHORT_URL_CACHE:
141
- return SHORT_URL_CACHE[long_url]
142
-
143
- from mfinder.db.settings_sql import get_admin_settings_sync
144
-
145
- settings = get_admin_settings_sync()
146
- if not settings:
147
- return long_url
148
-
149
- site = settings.shortener_site
150
- api = settings.shortener_api
151
- status = settings.shortener_status
152
-
153
- if (not status and not force) or not site or not api:
154
- return long_url
155
-
156
- current_time = time.time()
157
- if current_time < SHORTEN_COOLDOWN_UNTIL:
158
- return long_url
159
-
160
- site_clean = site.strip().rstrip("/")
161
- if not site_clean.startswith("http://") and not site_clean.startswith("https://"):
162
- api_url = f"https://{site_clean}"
163
- else:
164
- api_url = site_clean
165
-
166
- if not api_url.endswith("/api"):
167
- api_url = f"{api_url}/api"
168
-
169
- params = {
170
- 'url': long_url,
171
- 'api': api.strip(),
172
- 'format': 'json'
173
- }
174
-
175
- try:
176
- shortened = await asyncio.to_thread(_shorten_url_sync, api_url, params)
177
- if shortened:
178
- SHORT_URL_CACHE[long_url] = shortened
179
- SHORTEN_CONSECUTIVE_FAILURES = 0
180
- return shortened
181
- except Exception as e:
182
- print(f"An error occurred while shortening the URL: {e}")
183
-
184
- SHORTEN_CONSECUTIVE_FAILURES += 1
185
- if SHORTEN_CONSECUTIVE_FAILURES >= 5:
186
- SHORTEN_COOLDOWN_UNTIL = current_time + 30.0
187
- print("Shortener API failing or timing out. Placed on short 30-second cooldown.")
188
-
189
- return long_url
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mfinder/utils/util_support.py DELETED
@@ -1,65 +0,0 @@
1
- import psycopg2
2
- from psycopg2 import pool
3
- from mfinder import ADMINS, DB_URL
4
- import time
5
-
6
- def is_admin(user_id):
7
- return user_id in ADMINS
8
-
9
- def humanbytes(B):
10
- 'Return the given bytes as a human-friendly KB, MB, GB, or TB string'
11
- B = float(B)
12
- KB = float(1024)
13
- MB = float(KB ** 2) # 1,048,576
14
- GB = float(KB ** 3) # 1,073,741,824
15
- TB = float(KB ** 4) # 1,099,511,627,776
16
-
17
- if B < KB:
18
- return f'{B} {"Bytes" if 0 == B > 1 else "Byte"}'
19
- elif KB <= B < MB:
20
- return f'{B/KB:.2f} KB'
21
- elif MB <= B < GB:
22
- return f'{B/MB:.2f} MB'
23
- elif GB <= B < TB:
24
- return f'{B/GB:.2f} GB'
25
- elif TB <= B:
26
- return f'{B/TB:.2f} TB'
27
-
28
- def get_db_size():
29
- conn = psycopg2.connect(DB_URL)
30
- cursor = conn.cursor()
31
- query = "SELECT pg_database_size(current_database()) / (1024.0 * 1024.0)::numeric;"
32
- cursor.execute(query)
33
- database_size_mb = cursor.fetchone()[0]
34
- database_size_mb = float(
35
- database_size_mb) if database_size_mb is not None else 0.0
36
- db_size = round(database_size_mb, 2)
37
- cursor.close()
38
- conn.close()
39
- return db_size
40
-
41
- # Connection Pooling
42
- connection_pool = pool.SimpleConnectionPool(
43
- 1, 10, DB_URL
44
- )
45
-
46
- def get_connection_with_retry(retries=5, delay=5):
47
- for attempt in range(retries):
48
- try:
49
- conn = connection_pool.getconn()
50
- if conn:
51
- return conn
52
- except psycopg2.OperationalError:
53
- if attempt < retries - 1:
54
- time.sleep(delay)
55
- continue
56
- else:
57
- raise
58
- raise Exception("Failed to get connection after multiple retries")
59
-
60
- def release_connection(conn):
61
- if conn:
62
- connection_pool.putconn(conn)
63
-
64
- def close_all_connections():
65
- connection_pool.closeall()