Spaces:
Running
Running
Upload 35 files
Browse files- Dockerfile +20 -0
- LICENSE +13 -0
- README.md +87 -0
- config.ini +38 -0
- const.py +100 -0
- mfinder/__init__.py +164 -0
- mfinder/__main__.py +161 -0
- mfinder/db/analytics_sql.py +313 -0
- mfinder/db/ban_sql.py +106 -0
- mfinder/db/broadcast_sql.py +92 -0
- mfinder/db/db_support.py +32 -0
- mfinder/db/files_sql.py +538 -0
- mfinder/db/filters_sql.py +148 -0
- mfinder/db/newsletter_sql.py +145 -0
- mfinder/db/requests_sql.py +160 -0
- mfinder/db/settings_sql.py +1689 -0
- mfinder/db/suggestion_cache.py +103 -0
- mfinder/plugins/admin_settings.py +1617 -0
- mfinder/plugins/announcement.py +141 -0
- mfinder/plugins/broadcast.py +149 -0
- mfinder/plugins/commands.py +522 -0
- mfinder/plugins/index.py +168 -0
- mfinder/plugins/live_index.py +46 -0
- mfinder/plugins/newsletter.py +183 -0
- mfinder/plugins/requests.py +588 -0
- mfinder/plugins/serve.py +1756 -0
- mfinder/plugins/stream_server.py +123 -0
- mfinder/plugins/trending.py +205 -0
- mfinder/plugins/user_settings.py +125 -0
- mfinder/utils/constants.py +98 -0
- mfinder/utils/gemini_client.py +151 -0
- mfinder/utils/helpers.py +386 -0
- mfinder/utils/util_support.py +65 -0
- requirements.txt +21 -0
- sample_const.py +92 -0
Dockerfile
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim-bookworm
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
# Install system dependencies required for compiling Python packages and libmediainfo
|
| 6 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 7 |
+
gcc \
|
| 8 |
+
python3-dev \
|
| 9 |
+
libmediainfo-dev \
|
| 10 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 11 |
+
|
| 12 |
+
# Install python requirements
|
| 13 |
+
COPY requirements.txt .
|
| 14 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 15 |
+
|
| 16 |
+
# Copy all codebase files to working directory
|
| 17 |
+
COPY . .
|
| 18 |
+
|
| 19 |
+
# Run the app
|
| 20 |
+
CMD ["python", "-m", "mfinder"]
|
LICENSE
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2026 Angry Bird & Team FireBolt. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Proprietary License - Fully Owned and Licensed by Angry Bird & Team FireBolt.
|
| 4 |
+
|
| 5 |
+
This software, its source code, assets, and implementations (hereinafter referred to as the "Software") are the sole property of Angry Bird (telegram.me/ANGRY_BIRD22_bot) and Team FireBolt.
|
| 6 |
+
|
| 7 |
+
Permission is hereby granted, free of charge, to the authorized users of Team FireBolt to run and deploy this Software for personal or educational use.
|
| 8 |
+
|
| 9 |
+
Subject to the following conditions:
|
| 10 |
+
|
| 11 |
+
1. Redirection of credit, modification of copyright notices, or claiming of this Software as one's own work is strictly prohibited.
|
| 12 |
+
2. Distribution, licensing, or commercial selling of copies of this Software without the express prior written consent of Angry Bird is strictly prohibited.
|
| 13 |
+
3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the authors or copyright holders be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
|
README.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: testbot
|
| 3 |
+
emoji: 🎬
|
| 4 |
+
colorFrom: red
|
| 5 |
+
colorTo: yellow
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
+
pinned: false
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# 🔥 ANGRY BIRD File Serve Bot (Premium Edition) 🔥
|
| 12 |
+
|
| 13 |
+
A premium, high-speed **Telegram File Search and Direct Browser Download** bot powered by **FastAPI**, **Pyrogram**, and **Neon PostgreSQL**. Designed for seamless 24/7 deployment on **HuggingFace Spaces** (Docker) and **Render**.
|
| 14 |
+
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
## 🌟 Core & Premium Features
|
| 18 |
+
|
| 19 |
+
### 💎 Premium High-Speed Streaming Gateway
|
| 20 |
+
* **🌐 Direct Browser Streaming**: High-speed browser file downloading directly from Telegram CDNs using custom-engineered asynchronous chunk streaming.
|
| 21 |
+
* **⚡ Concurrency Optimized (100 Slots)**: Supports up to **100 simultaneous parallel downloads/streams** without any queuing or delay bottlenecks, utilizing `workers=100` parallel client connections.
|
| 22 |
+
* **🚀 Practically 0 MB Server Overhead**: Streams block-by-block using Pyrogram's `client.stream_media(...)` async generator, avoiding local file caching and RAM out-of-memory (OOM) failures entirely.
|
| 23 |
+
* **🗑️ Auto-Clean Token Verification**: Automatically cleans up authorization alerts, expiry errors, and incoming user query messages after a 10-second delay, ensuring clean private chats.
|
| 24 |
+
* **❓ Dynamic Help & Guide Integrations**: Renders a dynamic administrative control setting button (`how_to_download` guide URL) across `/start` keyboards.
|
| 25 |
+
|
| 26 |
+
### 🔍 Advanced Database Search Engine
|
| 27 |
+
* **🔥 Weekly Trending Tracker (`/trending`)**: Automatically monitors and tracks movie search query frequencies over a 7-day rolling cycle, presenting the top 10 most popular movies directly to users on start keyboards or inline buttons.
|
| 28 |
+
* **🆕 Newly Uploaded Monitor (`/newuploads`)**: Displays a real-time list of the 25 most recently indexed movies/files, making it easy for users to check recent releases instantly.
|
| 29 |
+
* **📈 Trigram pg_trgm Fuzzy Search**: Implements fuzzy title-matching leveraging PostgreSQL GIN trigram indexes to suggest and correct spelling mistakes.
|
| 30 |
+
* **🎯 Precise Mode Search Option**: Toggleable precise-matching mode to target exact word hits or perform general query containing searches.
|
| 31 |
+
* **📁 Multiple File Formats Supported**: Fully indexes and handles Documents, Video files, and Audio file formats with complete metadata logging.
|
| 32 |
+
* **🔀 Multi-Format Result Output**: Dynamically outputs search query results in button layouts, list structures, or hyperlink lists.
|
| 33 |
+
|
| 34 |
+
### ⚙️ Channel Indexing & Operations
|
| 35 |
+
* **🔄 Automated Live Indexing**: Real-time listening and automatic indexing of files uploaded directly to DB channels.
|
| 36 |
+
* **📦 Manual Indexing (`/index`)**: Forward-based administrative channel scanning to easily batch-import files into database records. Works based on original file captions to prevent duplicate quality skip issues!
|
| 37 |
+
* **🗑️ Dynamic Database Deletion**: Quick inline administrative file deletions (`/delete`) directly inside chat threads.
|
| 38 |
+
* **⏳ Auto-Delete Schedule**: Automatic scheduled file purge settings to clear files after configured time thresholds.
|
| 39 |
+
|
| 40 |
+
### 🧹 Bulk Delete Mode
|
| 41 |
+
* **Smart Bulk Deleting**: Standalone `/delete` command turns on a powerful state-based bulk delete mode. Forward multiple files at once, and the bot will automatically delete them all from the database, deactivated with `/done`.
|
| 42 |
+
|
| 43 |
+
### 🛡️ Administration & Controls
|
| 44 |
+
* **🛡️ Multi-Channel Force Subscribe**: Blocks all search queries, keyboard commands, and downloads until users join all configured update channels. Supports a comma-separated list of public/private channels in settings.
|
| 45 |
+
* **🔗 Dynamic Invite Link Generation**: Automatically resolves usernames (even without `@` prefix) or creates private invite links for each configured channel dynamically.
|
| 46 |
+
* * **🔄 Instant Resumption Handshake**: Saves blocked queries in the database and automatically executes them once the user joins and clicks "Try Again". If a token shortener is enabled, the query is passed seamlessly to the token system and executed automatically upon returning from the browser via `/start tok_xxxx`.
|
| 47 |
+
* * **🎛️ Spam & Double-Click Protection**: Instantly removes verification buttons when clicked to prevent duplicate execution, and edits prompt messages in-place with popup alerts to prevent user chat spam.
|
| 48 |
+
* * **📅 Filename Release Years**: Automatically extracts movie release years from filenames (e.g. `1900-2030`) and appends them to search list buttons (e.g., `Odyssey (2026)`) for a cleaner UX.
|
| 49 |
+
* **🏷️ Custom File Captioning**: Setup custom headers/captions (like adding usernames or watermarks) to all dispatched files.
|
| 50 |
+
* **⛔ Member Ban/Unban System**: Block unwanted users instantly using `/ban` and `/unban` command strings.
|
| 51 |
+
* **📢 Massive Broadcast system**: Send custom formatted alerts or messages globally to all registered bot users concurrently.
|
| 52 |
+
* **📊 Live Server Stats & Logs**: Get real-time stats and runtime log dumps directly inside the administrator's chat.
|
| 53 |
+
|
| 54 |
+
---
|
| 55 |
+
|
| 56 |
+
## 📂 Codebase & Setup
|
| 57 |
+
|
| 58 |
+
For full instructions, file structures, and advanced procedures:
|
| 59 |
+
* 📖 Refer to the comprehensive deployment manuals at:
|
| 60 |
+
* [documentation/render_deployment_guide.md](file:///d:/Work/AngryBird-main/documentation/render_deployment_guide.md) (For Render and Local setups)
|
| 61 |
+
|
| 62 |
+
### Quick Local Run
|
| 63 |
+
|
| 64 |
+
1. **Activate environment & install dependencies**:
|
| 65 |
+
```bash
|
| 66 |
+
python -m venv .venv
|
| 67 |
+
.venv\Scripts\Activate.ps1 # Windows
|
| 68 |
+
source .venv/bin/activate # Linux/macOS
|
| 69 |
+
pip install -r requirements.txt
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
2. **Add environment variables** to a local `.env` file (API_ID, API_HASH, BOT_TOKEN, DB_URL, OWNER_ID, DB_CHANNELS, etc.).
|
| 73 |
+
|
| 74 |
+
3. **Launch the bot**:
|
| 75 |
+
```bash
|
| 76 |
+
python -m mfinder
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
---
|
| 80 |
+
|
| 81 |
+
## 📜 License & Ownership
|
| 82 |
+
|
| 83 |
+
This software, codebase, and its implementations are **fully owned, managed, and licensed** by:
|
| 84 |
+
* 👤 **Angry Bird** (Primary Maintainer: [@ANGRY_BIRD22_bot](https://t.me/ANGRY_BIRD22_bot))
|
| 85 |
+
* ⚡ **Team FireBolt**
|
| 86 |
+
|
| 87 |
+
All rights reserved. Unauthorized redistribution or copying of these custom features is strictly prohibited.
|
config.ini
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[loggers]
|
| 2 |
+
keys=root,Logger
|
| 3 |
+
|
| 4 |
+
[handlers]
|
| 5 |
+
keys=consoleHandler, file_handler
|
| 6 |
+
|
| 7 |
+
[formatters]
|
| 8 |
+
keys=Formatter
|
| 9 |
+
|
| 10 |
+
[logger_root]
|
| 11 |
+
level=INFO
|
| 12 |
+
handlers=consoleHandler, file_handler
|
| 13 |
+
|
| 14 |
+
[logger_Logger]
|
| 15 |
+
level=INFO
|
| 16 |
+
handlers=consoleHandler, file_handler
|
| 17 |
+
qualname=Logger
|
| 18 |
+
propagate=0
|
| 19 |
+
|
| 20 |
+
[handler_consoleHandler]
|
| 21 |
+
class=StreamHandler
|
| 22 |
+
level=INFO
|
| 23 |
+
formatter=Formatter
|
| 24 |
+
args=(sys.stdout,)
|
| 25 |
+
|
| 26 |
+
[handler_file_handler]
|
| 27 |
+
class=FileHandler
|
| 28 |
+
level=INFO
|
| 29 |
+
formatter=Formatter
|
| 30 |
+
args=('logs.txt','a',)
|
| 31 |
+
|
| 32 |
+
[formatter_Formatter]
|
| 33 |
+
format= [%(asctime)s][%(name)s][%(module)s][%(lineno)d][%(levelname)s] -> %(message)s
|
| 34 |
+
datefmt= %d/%m/%Y %H:%M:%S
|
| 35 |
+
|
| 36 |
+
[ssl]
|
| 37 |
+
cert_file=path/to/certificate.crt
|
| 38 |
+
key_file=path/to/private.key
|
const.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Do not edit this file, copy this file & rename it to const.py. Any format error will result in not getting start or help message.
|
| 2 |
+
|
| 3 |
+
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
#use the same format for name & user_id placeholders
|
| 7 |
+
START_MSG = """
|
| 8 |
+
Hi **[{}](tg://user?id={})**,𝐈’𝐦 𝐭𝐡𝐞 𝐀𝐍𝐆𝐑𝐘 😡 𝐁𝐈𝐑𝐃 𝐅𝐢𝐥𝐞 𝐒𝐞𝐫𝐯𝐞 𝐁𝐨𝐭 𝐟𝐫𝐨𝐦 𝐓𝐞𝐚𝐦 𝐅𝐢𝐫𝐞⚡𝐁𝐨𝐥𝐭 !
|
| 9 |
+
𝐍𝐞𝐞𝐝 𝐚 𝐌𝐎𝐕𝐈𝐄 𝐨𝐫 𝐒𝐄𝐑𝐈𝐄𝐒 ? 𝐉𝐮𝐬𝐭 𝐬𝐞𝐧𝐝 𝐭𝐡𝐞 𝐧𝐚𝐦𝐞, 𝐚𝐧𝐝 𝐈’𝐥𝐥 𝐟𝐢𝐧𝐝 𝐢𝐭 𝐟𝐨𝐫 𝐲𝐨𝐮 𝐢𝐧𝐬𝐭𝐚𝐧𝐭𝐥𝐲! 🍿🎥
|
| 10 |
+
|
| 11 |
+
𝐖𝐚𝐧𝐭 𝐭𝐨 𝐤𝐧𝐨𝐰 𝐦𝐨𝐫𝐞? 𝐓𝐲𝐩𝐞 /help 𝐟𝐨𝐫 𝐚𝐥𝐥 𝐜𝐨𝐦𝐦𝐚𝐧𝐝𝐬.
|
| 12 |
+
𝐋𝐞𝐭’𝐬 𝐡𝐮𝐧𝐭 𝐝𝐨𝐰𝐧 𝐬𝐨𝐦𝐞 𝐠𝐫𝐞𝐚𝐭 𝐜𝐨𝐧𝐭𝐞𝐧𝐭!
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
HELP_MSG = """
|
| 16 |
+
REQUEST FORMAT :- *MOVIE NAME WITH YEAR (LANGUAGE OPTIONAL)
|
| 17 |
+
|
| 18 |
+
REQUEST LIKE THIS :-
|
| 19 |
+
=>IRON MAN✅
|
| 20 |
+
=>IRON MAN 2008✅
|
| 21 |
+
=>IRON MAN 2008 TAMIL✅
|
| 22 |
+
|
| 23 |
+
DON'T REQUEST LIKE THIS :-
|
| 24 |
+
=>IRON MAN MOVIE ❌
|
| 25 |
+
=>IRON MAN 2008 GIVE ❌
|
| 26 |
+
=>IRON MAN 2008 ANAPUGA ❌
|
| 27 |
+
|
| 28 |
+
[🙅Don't use this words while searching: HD, MOVIES, SEND, PREDVD, WEB-DL, ANAPUGA, SEND PANNUGA, HDrip, VENUM]
|
| 29 |
+
|
| 30 |
+
If Any Movies Not Available Send Your MOVIE NAMES Via `/request <Movie Name>` or REPORT HERE 👉 @ANGRY_BIRD22_bot
|
| 31 |
+
|
| 32 |
+
━━━━━━━━━━━━━━━━━━━━━━
|
| 33 |
+
**You can find the bot commands here.**
|
| 34 |
+
|
| 35 |
+
**User Commands:-**
|
| 36 |
+
/start - Start the bot and view main menu
|
| 37 |
+
/help - Show this help message
|
| 38 |
+
/trending - View top 10 trending movies this week
|
| 39 |
+
/newuploads - View latest 25 newly uploaded movies
|
| 40 |
+
/request - Request a missing movie from admins (`/request Movie Name`)
|
| 41 |
+
/settings - Toggle settings of Precise Mode and Button Mode
|
| 42 |
+
|
| 43 |
+
**Precise Mode:**
|
| 44 |
+
- If Enabled, bot will match the word & return results with only the exact match
|
| 45 |
+
- If Disabled, bot will match the word & return all the results containing the word
|
| 46 |
+
|
| 47 |
+
**Result Mode:**
|
| 48 |
+
- If Button, bot will return results in button format
|
| 49 |
+
- If List, bot will return results in list format
|
| 50 |
+
- If HyperLink, bot will return results in hyperlink format
|
| 51 |
+
|
| 52 |
+
**Admin Commands:-**
|
| 53 |
+
/requests - View pending movie requests summary
|
| 54 |
+
/message - Send message to user's PM - `/message <user_id/username> [optional text]`
|
| 55 |
+
/logs - Get logs as a file
|
| 56 |
+
/server - Get server stats
|
| 57 |
+
/restart - Restart the bot
|
| 58 |
+
/stats - Get bot user stats
|
| 59 |
+
/broadcast - Reply to a message to send that to all bot users
|
| 60 |
+
/index - Start indexing a database channel (bot must be admin of the channel if that is private channel)
|
| 61 |
+
*(You can just forward the message from database channel for starting indexing, no need to use the /index command)*
|
| 62 |
+
/delete - Reply to a file to delete it from database
|
| 63 |
+
/autodelete - Set file auto delete time in seconds
|
| 64 |
+
/repairmode - Enable or disable repair mode - If on, bot will not send any files
|
| 65 |
+
/customcaption - Set custom caption for files
|
| 66 |
+
/adminsettings - Get current admin settings
|
| 67 |
+
/ban - Ban a user from bot - `/ban user_id`
|
| 68 |
+
/unban - Unban a user from bot - `/unban user_id`
|
| 69 |
+
/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)*
|
| 70 |
+
/delfilter - Delete a text filter - `/delfilter filter`
|
| 71 |
+
/listfilters - List all filters currently added in the bot
|
| 72 |
+
/forcesub - Set force subscribe channel - `/forcesub channel_id` *(Bot must be admin of that channel)*
|
| 73 |
+
/checklink - Check invite link for force subscribe channel
|
| 74 |
+
/total - Get count of total files in DB
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
START_KB = InlineKeyboardMarkup(
|
| 79 |
+
[
|
| 80 |
+
[
|
| 81 |
+
InlineKeyboardButton("🆘 Help", callback_data="help_cb"),
|
| 82 |
+
InlineKeyboardButton(
|
| 83 |
+
"📞 Contact", url="https://telegram.me/ANGRY_BIRD22_bot"
|
| 84 |
+
)
|
| 85 |
+
],
|
| 86 |
+
[
|
| 87 |
+
InlineKeyboardButton(
|
| 88 |
+
"❓ How To Download ❓", url="https://telegram.me/FIREBOLTTutorial/23"
|
| 89 |
+
)
|
| 90 |
+
],
|
| 91 |
+
]
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
HELP_KB = InlineKeyboardMarkup(
|
| 95 |
+
[
|
| 96 |
+
[
|
| 97 |
+
InlineKeyboardButton("🔙 Back", callback_data="back_m"),
|
| 98 |
+
],
|
| 99 |
+
]
|
| 100 |
+
)
|
mfinder/__init__.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_val = os.environ.get("OWNER_ID", "").strip()
|
| 22 |
+
if not owner_id_val:
|
| 23 |
+
raise ValueError("OWNER_ID environment variable is missing or empty! Please rename your Render Secret File to '.env' and verify you used '=' instead of '-' (e.g. OWNER_ID=123456).")
|
| 24 |
+
OWNER_ID = int(owner_id_val)
|
| 25 |
+
ADMINS = [
|
| 26 |
+
int(user) if id_pattern.search(user) else user
|
| 27 |
+
for user in os.environ.get("ADMINS", "").split()
|
| 28 |
+
] + [OWNER_ID]
|
| 29 |
+
DB_CHANNELS = [
|
| 30 |
+
int(ch) if id_pattern.search(ch) else ch
|
| 31 |
+
for ch in os.environ.get("DB_CHANNELS", "").split()
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
try:
|
| 35 |
+
import const
|
| 36 |
+
except Exception:
|
| 37 |
+
import sample_const as const
|
| 38 |
+
|
| 39 |
+
START_MSG = const.START_MSG
|
| 40 |
+
START_KB = const.START_KB
|
| 41 |
+
HELP_MSG = const.HELP_MSG
|
| 42 |
+
HELP_KB = const.HELP_KB
|
| 43 |
+
|
| 44 |
+
# logging Conf
|
| 45 |
+
logging.config.fileConfig(fname="config.ini", disable_existing_loggers=False)
|
| 46 |
+
LOGGER = logging.getLogger(__name__)
|
| 47 |
+
logging.getLogger("pyrogram").setLevel(logging.WARNING)
|
| 48 |
+
logging.getLogger("pyrogram.dispatcher").setLevel(logging.CRITICAL)
|
| 49 |
+
logging.getLogger("pyrogram.connection.transport").setLevel(logging.CRITICAL)
|
| 50 |
+
logging.getLogger("pyrogram.connection.connection").setLevel(logging.CRITICAL)
|
| 51 |
+
logging.getLogger("pyrogram.session.session").setLevel(logging.CRITICAL)
|
| 52 |
+
|
| 53 |
+
# Database connection
|
| 54 |
+
def start():
|
| 55 |
+
connect_args = {}
|
| 56 |
+
if DB_URL and DB_URL.startswith(("postgres://", "postgresql://")):
|
| 57 |
+
connect_args["sslmode"] = "require"
|
| 58 |
+
engine = create_engine(
|
| 59 |
+
DB_URL,
|
| 60 |
+
connect_args=connect_args,
|
| 61 |
+
poolclass=QueuePool,
|
| 62 |
+
pool_size=10,
|
| 63 |
+
max_overflow=20,
|
| 64 |
+
pool_pre_ping=True,
|
| 65 |
+
pool_recycle=1800 # Recycle connections every 1800 seconds (30 minutes)
|
| 66 |
+
)
|
| 67 |
+
return scoped_session(sessionmaker(bind=engine, autoflush=False))
|
| 68 |
+
|
| 69 |
+
SESSION = start()
|
| 70 |
+
|
| 71 |
+
def load_dynamic_configs():
|
| 72 |
+
global ADMINS, DB_CHANNELS
|
| 73 |
+
try:
|
| 74 |
+
from mfinder.db import settings_sql
|
| 75 |
+
with settings_sql.SESSION() as session:
|
| 76 |
+
res = session.query(settings_sql.AdminSettings).first()
|
| 77 |
+
if res:
|
| 78 |
+
db_admins = res.admins_list
|
| 79 |
+
db_channels = res.db_channels_list
|
| 80 |
+
if db_admins is not None:
|
| 81 |
+
loaded_admins = []
|
| 82 |
+
for admin in db_admins.split(','):
|
| 83 |
+
admin = admin.strip()
|
| 84 |
+
if admin:
|
| 85 |
+
if id_pattern.search(admin):
|
| 86 |
+
loaded_admins.append(int(admin))
|
| 87 |
+
else:
|
| 88 |
+
loaded_admins.append(admin)
|
| 89 |
+
if OWNER_ID not in loaded_admins:
|
| 90 |
+
loaded_admins.append(OWNER_ID)
|
| 91 |
+
ADMINS.clear()
|
| 92 |
+
ADMINS.extend(loaded_admins)
|
| 93 |
+
|
| 94 |
+
if db_channels is not None:
|
| 95 |
+
loaded_channels = []
|
| 96 |
+
for ch in db_channels.split(','):
|
| 97 |
+
ch = ch.strip()
|
| 98 |
+
if ch:
|
| 99 |
+
if id_pattern.search(ch):
|
| 100 |
+
loaded_channels.append(int(ch))
|
| 101 |
+
else:
|
| 102 |
+
loaded_channels.append(ch)
|
| 103 |
+
DB_CHANNELS.clear()
|
| 104 |
+
DB_CHANNELS.extend(loaded_channels)
|
| 105 |
+
except Exception as e:
|
| 106 |
+
print(f"Error loading dynamic configs: {e}")
|
| 107 |
+
|
| 108 |
+
load_dynamic_configs()
|
| 109 |
+
|
| 110 |
+
import pyrogram.filters as py_filters
|
| 111 |
+
|
| 112 |
+
# Store original user filter
|
| 113 |
+
original_user_filter = py_filters.user
|
| 114 |
+
|
| 115 |
+
def custom_user_filter(users=None):
|
| 116 |
+
if users is ADMINS:
|
| 117 |
+
async def func(flt, client, update):
|
| 118 |
+
user_id = update.from_user.id if update.from_user else None
|
| 119 |
+
if not user_id:
|
| 120 |
+
return False
|
| 121 |
+
return user_id in ADMINS
|
| 122 |
+
return py_filters.create(func)
|
| 123 |
+
else:
|
| 124 |
+
return original_user_filter(users)
|
| 125 |
+
|
| 126 |
+
py_filters.user = custom_user_filter
|
| 127 |
+
|
| 128 |
+
# Keep-alive task
|
| 129 |
+
async def keep_alive():
|
| 130 |
+
while True:
|
| 131 |
+
try:
|
| 132 |
+
# Execute a simple query to keep the connection alive
|
| 133 |
+
with SESSION() as session:
|
| 134 |
+
session.execute("SELECT 1")
|
| 135 |
+
await asyncio.sleep(180) # Sleep for 3 minutes
|
| 136 |
+
except Exception as e:
|
| 137 |
+
LOGGER.warning(f"Keep-alive error: {e}")
|
| 138 |
+
await asyncio.sleep(10) # Wait before retrying
|
| 139 |
+
|
| 140 |
+
# Main function
|
| 141 |
+
async def main():
|
| 142 |
+
# Start the keep-alive task
|
| 143 |
+
asyncio.create_task(keep_alive())
|
| 144 |
+
# Your existing bot initialization and running code
|
| 145 |
+
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
asyncio.run(main())
|
| 148 |
+
|
| 149 |
+
# Monkey patch CallbackQuery.answer to silently ignore QueryIdInvalid and connection errors
|
| 150 |
+
from pyrogram.types import CallbackQuery
|
| 151 |
+
|
| 152 |
+
original_answer = CallbackQuery.answer
|
| 153 |
+
|
| 154 |
+
async def safe_answer(self, *args, **kwargs):
|
| 155 |
+
try:
|
| 156 |
+
return await original_answer(self, *args, **kwargs)
|
| 157 |
+
except Exception as e:
|
| 158 |
+
import logging
|
| 159 |
+
logging.getLogger("pyrogram.types.bots_and_keyboards.callback_query").warning(
|
| 160 |
+
f"Failed to answer callback query: {e}"
|
| 161 |
+
)
|
| 162 |
+
return False
|
| 163 |
+
|
| 164 |
+
CallbackQuery.answer = safe_answer
|
mfinder/__main__.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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: Dedicated persistent client handling HTTP downloads (workers=100, max_concurrent_transmissions=100)
|
| 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 |
+
max_concurrent_transmissions=100,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
# 2. Direct Stream Gateway (HTTP Downloads, persistent on disk to cache auth keys/sessions)
|
| 55 |
+
stream_client = Client(
|
| 56 |
+
name="stream_worker",
|
| 57 |
+
api_id=APP_ID,
|
| 58 |
+
api_hash=API_HASH,
|
| 59 |
+
bot_token=BOT_TOKEN,
|
| 60 |
+
in_memory=False,
|
| 61 |
+
workers=100,
|
| 62 |
+
max_concurrent_transmissions=100,
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
await app_client.start()
|
| 66 |
+
|
| 67 |
+
# Start Newsletter background loop task
|
| 68 |
+
from mfinder.plugins.newsletter import start_newsletter_loop
|
| 69 |
+
asyncio.create_task(start_newsletter_loop(app_client))
|
| 70 |
+
|
| 71 |
+
from mfinder.plugins.serve import start_auto_delete_loop
|
| 72 |
+
asyncio.create_task(start_auto_delete_loop(app_client))
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
await stream_client.start()
|
| 76 |
+
app.state.stream_client = stream_client
|
| 77 |
+
except Exception as stream_err:
|
| 78 |
+
print(f"WARNING: Failed to start stream_client (FloodWait/Auth issue): {stream_err}. Using main app_client as fallback.")
|
| 79 |
+
app.state.stream_client = app_client
|
| 80 |
+
|
| 81 |
+
app.state.client = app_client
|
| 82 |
+
|
| 83 |
+
# Warmup dialogs cache / Inject Log & Force Sub Channel Peer Cache rows
|
| 84 |
+
try:
|
| 85 |
+
from mfinder.db.settings_sql import get_admin_settings_sync
|
| 86 |
+
settings = get_admin_settings_sync()
|
| 87 |
+
|
| 88 |
+
# 1. Inject Log Channel Peer
|
| 89 |
+
if settings and settings.log_channel and settings.log_channel_access_hash:
|
| 90 |
+
peer_id = int(settings.log_channel)
|
| 91 |
+
access_hash = int(settings.log_channel_access_hash)
|
| 92 |
+
await app_client.storage.update_peers([(peer_id, access_hash, "channel", "", "")])
|
| 93 |
+
print("Successfully injected log channel peer into Pyrogram storage cache!")
|
| 94 |
+
|
| 95 |
+
# 3. Inject Announcement Channel Peer
|
| 96 |
+
if settings and getattr(settings, "announcement_channel", None) and getattr(settings, "announcement_channel_access_hash", None):
|
| 97 |
+
peer_id = int(settings.announcement_channel)
|
| 98 |
+
access_hash = int(settings.announcement_channel_access_hash)
|
| 99 |
+
await app_client.storage.update_peers([(peer_id, access_hash, "channel", "", "")])
|
| 100 |
+
print("Successfully injected announcement channel peer into Pyrogram storage cache!")
|
| 101 |
+
|
| 102 |
+
# 2. Inject Force Sub Channel Peers
|
| 103 |
+
if settings:
|
| 104 |
+
import json
|
| 105 |
+
hashes = {}
|
| 106 |
+
if settings.fsub_channels_access_hashes:
|
| 107 |
+
try:
|
| 108 |
+
hashes = json.loads(settings.fsub_channels_access_hashes)
|
| 109 |
+
except Exception:
|
| 110 |
+
pass
|
| 111 |
+
# Backwards compatibility: add legacy single fsub channel
|
| 112 |
+
if settings.fsub_channel and settings.fsub_channel_access_hash:
|
| 113 |
+
hashes[str(int(settings.fsub_channel))] = settings.fsub_channel_access_hash
|
| 114 |
+
|
| 115 |
+
for peer_str, hash_val in hashes.items():
|
| 116 |
+
if peer_str and hash_val is not None:
|
| 117 |
+
try:
|
| 118 |
+
peer_id = int(peer_str)
|
| 119 |
+
access_hash = int(hash_val)
|
| 120 |
+
await app_client.storage.update_peers([(peer_id, access_hash, "channel", "", "")])
|
| 121 |
+
print(f"Successfully injected force sub channel peer {peer_id} into Pyrogram storage cache!")
|
| 122 |
+
except Exception as peer_err:
|
| 123 |
+
print(f"Failed to inject force sub channel peer {peer_str}: {peer_err}")
|
| 124 |
+
except Exception as e:
|
| 125 |
+
print(f"Log/ForceSub channel peer cache warmup exception: {e}")
|
| 126 |
+
|
| 127 |
+
me = await app_client.get_me()
|
| 128 |
+
safe_first_name = (me.first_name or "").encode("ascii", errors="ignore").decode("ascii")
|
| 129 |
+
if not safe_first_name:
|
| 130 |
+
safe_first_name = "Bot"
|
| 131 |
+
print(
|
| 132 |
+
f"{safe_first_name} - @{me.username} - Pyrogram v{__version__} (Layer {layer}) - Dual-Engine High-Concurrency Server Online!"
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
yield
|
| 136 |
+
|
| 137 |
+
await app_client.stop()
|
| 138 |
+
await stream_client.stop()
|
| 139 |
+
print(f"{safe_first_name} - @{me.username} - Stopped !!!")
|
| 140 |
+
|
| 141 |
+
# Initialize web application with docs disabled
|
| 142 |
+
web_app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
|
| 143 |
+
|
| 144 |
+
@web_app.get("/")
|
| 145 |
+
async def home():
|
| 146 |
+
"""Simple keep-alive health check endpoint."""
|
| 147 |
+
return {"status": "ok", "message": "Bot is running with Dual Engine!"}
|
| 148 |
+
|
| 149 |
+
# Include the stream server router for direct downloads
|
| 150 |
+
from mfinder.plugins.stream_server import router as stream_router
|
| 151 |
+
web_app.include_router(stream_router)
|
| 152 |
+
|
| 153 |
+
# Catch-all fallback handler for web scanners seeking .env, config, etc. to eliminate 404 log spam
|
| 154 |
+
@web_app.api_route("/{path:path}", methods=["GET", "POST", "HEAD"])
|
| 155 |
+
async def catch_all_fallback(path: str):
|
| 156 |
+
return {"status": "ok", "message": "Bot is running!"}
|
| 157 |
+
|
| 158 |
+
PORT = int(os.environ.get("PORT", 7860))
|
| 159 |
+
|
| 160 |
+
if __name__ == "__main__":
|
| 161 |
+
uvicorn.run(web_app, host="0.0.0.0", port=PORT, access_log=False)
|
mfinder/db/analytics_sql.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
def extract_season(text: str) -> str:
|
| 67 |
+
if not text:
|
| 68 |
+
return None
|
| 69 |
+
import re
|
| 70 |
+
# Match S02, s2, S-2, s_2, S(2), Season 2, Season-02, s02e03, etc.
|
| 71 |
+
match = re.search(r'\b[sS](?:eason)?[\s_.-]*\(?(\d+)\)?(?:\b|[eE])', text)
|
| 72 |
+
if match:
|
| 73 |
+
season_num = int(match.group(1))
|
| 74 |
+
return f"S{season_num}"
|
| 75 |
+
return None
|
| 76 |
+
|
| 77 |
+
async def get_latest_uploaded_movies(limit: int = 25) -> list:
|
| 78 |
+
"""
|
| 79 |
+
Retrieves the latest distinct uploaded movies from the database files table,
|
| 80 |
+
sorted by newest created_at timestamp first.
|
| 81 |
+
Returns list of tuples: (cleaned_title, file_count, year, season_str)
|
| 82 |
+
"""
|
| 83 |
+
retries = 3
|
| 84 |
+
while retries > 0:
|
| 85 |
+
try:
|
| 86 |
+
with INSERTION_LOCK:
|
| 87 |
+
files = (
|
| 88 |
+
SESSION.query(Files.file_name, Files.caption)
|
| 89 |
+
.order_by(Files.created_at.desc(), Files.file_name.asc())
|
| 90 |
+
.limit(300)
|
| 91 |
+
.all()
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
movie_counts = {}
|
| 95 |
+
movie_years = {}
|
| 96 |
+
movie_seasons = {}
|
| 97 |
+
for f_name, caption in files:
|
| 98 |
+
title = clean_movie_title(f_name)
|
| 99 |
+
if title and len(title) >= 2:
|
| 100 |
+
movie_counts[title] = movie_counts.get(title, 0) + 1
|
| 101 |
+
if title not in movie_years:
|
| 102 |
+
import re
|
| 103 |
+
year_match = re.search(r'\b(19\d{2}|20[0-2]\d|2030)\b', f_name)
|
| 104 |
+
if year_match:
|
| 105 |
+
movie_years[title] = year_match.group(1)
|
| 106 |
+
|
| 107 |
+
# Extract season
|
| 108 |
+
season = extract_season(f_name)
|
| 109 |
+
if not season and caption:
|
| 110 |
+
season = extract_season(caption)
|
| 111 |
+
if season:
|
| 112 |
+
if title not in movie_seasons:
|
| 113 |
+
movie_seasons[title] = set()
|
| 114 |
+
movie_seasons[title].add(season)
|
| 115 |
+
|
| 116 |
+
latest_list = []
|
| 117 |
+
for title, count in movie_counts.items():
|
| 118 |
+
year = movie_years.get(title)
|
| 119 |
+
seasons = movie_seasons.get(title)
|
| 120 |
+
season_str = None
|
| 121 |
+
if seasons:
|
| 122 |
+
sorted_seasons = sorted(list(seasons), key=lambda s: int(s[1:]))
|
| 123 |
+
if len(sorted_seasons) > 1:
|
| 124 |
+
season_str = " & ".join(sorted_seasons)
|
| 125 |
+
else:
|
| 126 |
+
season_str = sorted_seasons[0]
|
| 127 |
+
|
| 128 |
+
latest_list.append((title, count, year, season_str))
|
| 129 |
+
if len(latest_list) >= limit:
|
| 130 |
+
break
|
| 131 |
+
|
| 132 |
+
return latest_list
|
| 133 |
+
except OperationalError:
|
| 134 |
+
reconnect_session()
|
| 135 |
+
retries -= 1
|
| 136 |
+
except Exception as e:
|
| 137 |
+
retries -= 1
|
| 138 |
+
finally:
|
| 139 |
+
try:
|
| 140 |
+
SESSION.close()
|
| 141 |
+
except Exception:
|
| 142 |
+
pass
|
| 143 |
+
return []
|
| 144 |
+
|
| 145 |
+
async def get_top_trending_movies(limit: int = 10) -> list:
|
| 146 |
+
"""
|
| 147 |
+
Retrieves top searched queries from the 7-day weekly cycle in search_analytics.
|
| 148 |
+
Returns list of tuples: (movie_title, file_count)
|
| 149 |
+
"""
|
| 150 |
+
# Trigger weekly cleanup of old search records
|
| 151 |
+
await cleanup_old_search_analytics()
|
| 152 |
+
|
| 153 |
+
retries = 3
|
| 154 |
+
while retries > 0:
|
| 155 |
+
try:
|
| 156 |
+
with INSERTION_LOCK:
|
| 157 |
+
one_week_ago = datetime.datetime.utcnow() - datetime.timedelta(days=7)
|
| 158 |
+
top_records = (
|
| 159 |
+
SESSION.query(SearchAnalytics)
|
| 160 |
+
.filter(SearchAnalytics.last_searched >= one_week_ago)
|
| 161 |
+
.order_by(SearchAnalytics.search_count.desc(), SearchAnalytics.last_searched.desc())
|
| 162 |
+
.limit(50)
|
| 163 |
+
.all()
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
if not top_records:
|
| 167 |
+
return []
|
| 168 |
+
|
| 169 |
+
trending_movies = []
|
| 170 |
+
seen_titles = set()
|
| 171 |
+
|
| 172 |
+
for rec in top_records:
|
| 173 |
+
q = rec.query
|
| 174 |
+
files = (
|
| 175 |
+
SESSION.query(Files.file_name, Files.caption)
|
| 176 |
+
.filter(Files.file_name.ilike(f"%{q}%"))
|
| 177 |
+
.limit(50)
|
| 178 |
+
.all()
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
if files:
|
| 182 |
+
for f_name, caption in files:
|
| 183 |
+
title = clean_movie_title(f_name)
|
| 184 |
+
if title and len(title) >= 2:
|
| 185 |
+
t_key = title.lower()
|
| 186 |
+
if t_key not in seen_titles:
|
| 187 |
+
seen_titles.add(t_key)
|
| 188 |
+
count = SESSION.query(Files).filter(Files.file_name.ilike(f"%{title}%")).count()
|
| 189 |
+
|
| 190 |
+
# Extract year and seasons from matched files
|
| 191 |
+
import re
|
| 192 |
+
year = None
|
| 193 |
+
seasons = set()
|
| 194 |
+
for fn, cap in files:
|
| 195 |
+
year_match = re.search(r'\b(19\d{2}|20[0-2]\d|2030)\b', fn)
|
| 196 |
+
if year_match:
|
| 197 |
+
year = year_match.group(1)
|
| 198 |
+
season = extract_season(fn)
|
| 199 |
+
if not season and cap:
|
| 200 |
+
season = extract_season(cap)
|
| 201 |
+
if season:
|
| 202 |
+
seasons.add(season)
|
| 203 |
+
|
| 204 |
+
season_str = None
|
| 205 |
+
if seasons:
|
| 206 |
+
sorted_seasons = sorted(list(seasons), key=lambda s: int(s[1:]))
|
| 207 |
+
if len(sorted_seasons) > 1:
|
| 208 |
+
season_str = " & ".join(sorted_seasons)
|
| 209 |
+
else:
|
| 210 |
+
season_str = sorted_seasons[0]
|
| 211 |
+
|
| 212 |
+
trending_movies.append((title, count if count > 0 else len(files), year, season_str))
|
| 213 |
+
if len(trending_movies) >= limit:
|
| 214 |
+
break
|
| 215 |
+
if len(trending_movies) >= limit:
|
| 216 |
+
break
|
| 217 |
+
|
| 218 |
+
return trending_movies
|
| 219 |
+
except OperationalError:
|
| 220 |
+
reconnect_session()
|
| 221 |
+
retries -= 1
|
| 222 |
+
except Exception:
|
| 223 |
+
retries -= 1
|
| 224 |
+
finally:
|
| 225 |
+
try:
|
| 226 |
+
SESSION.close()
|
| 227 |
+
except Exception:
|
| 228 |
+
pass
|
| 229 |
+
return []
|
| 230 |
+
|
| 231 |
+
from sqlalchemy import BigInteger
|
| 232 |
+
|
| 233 |
+
class UserInteraction(BASE):
|
| 234 |
+
__tablename__ = "user_interactions"
|
| 235 |
+
user_id = Column(BigInteger, primary_key=True)
|
| 236 |
+
last_active = Column(DateTime, default=datetime.datetime.utcnow)
|
| 237 |
+
|
| 238 |
+
def __init__(self, user_id):
|
| 239 |
+
self.user_id = user_id
|
| 240 |
+
self.last_active = datetime.datetime.utcnow()
|
| 241 |
+
|
| 242 |
+
# Ensure table exists in DB automatically on module load
|
| 243 |
+
try:
|
| 244 |
+
session = SESSION()
|
| 245 |
+
bind = session.get_bind()
|
| 246 |
+
inspector = inspect(bind)
|
| 247 |
+
if not inspector.has_table("user_interactions"):
|
| 248 |
+
UserInteraction.__table__.create(bind=bind, checkfirst=True)
|
| 249 |
+
except Exception as _e:
|
| 250 |
+
pass
|
| 251 |
+
|
| 252 |
+
async def log_user_interaction(user_id: int):
|
| 253 |
+
if not user_id:
|
| 254 |
+
return
|
| 255 |
+
session = SESSION()
|
| 256 |
+
try:
|
| 257 |
+
record = session.query(UserInteraction).filter_by(user_id=user_id).first()
|
| 258 |
+
if record:
|
| 259 |
+
record.last_active = datetime.datetime.utcnow()
|
| 260 |
+
else:
|
| 261 |
+
record = UserInteraction(user_id=user_id)
|
| 262 |
+
session.add(record)
|
| 263 |
+
session.commit()
|
| 264 |
+
except Exception as e:
|
| 265 |
+
session.rollback()
|
| 266 |
+
finally:
|
| 267 |
+
try:
|
| 268 |
+
SESSION.close()
|
| 269 |
+
except Exception:
|
| 270 |
+
pass
|
| 271 |
+
|
| 272 |
+
async def get_today_active_users_count() -> int:
|
| 273 |
+
session = SESSION()
|
| 274 |
+
try:
|
| 275 |
+
now = datetime.datetime.utcnow()
|
| 276 |
+
local_now = now + datetime.timedelta(hours=5, minutes=30)
|
| 277 |
+
local_today_start = datetime.datetime(local_now.year, local_now.month, local_now.day)
|
| 278 |
+
utc_today_start = local_today_start - datetime.timedelta(hours=5, minutes=30)
|
| 279 |
+
count = session.query(UserInteraction).filter(UserInteraction.last_active >= utc_today_start).count()
|
| 280 |
+
return count
|
| 281 |
+
except Exception:
|
| 282 |
+
return 0
|
| 283 |
+
finally:
|
| 284 |
+
try:
|
| 285 |
+
SESSION.close()
|
| 286 |
+
except Exception:
|
| 287 |
+
pass
|
| 288 |
+
|
| 289 |
+
def get_movie_quality_sync(title: str) -> str:
|
| 290 |
+
from mfinder.db.files_sql import Files
|
| 291 |
+
from mfinder.utils.helpers import detect_file_quality
|
| 292 |
+
session = SESSION()
|
| 293 |
+
try:
|
| 294 |
+
files = (
|
| 295 |
+
session.query(Files.file_name)
|
| 296 |
+
.filter(Files.file_name.ilike(f"%{title}%"))
|
| 297 |
+
.order_by(Files.created_at.desc())
|
| 298 |
+
.limit(10)
|
| 299 |
+
.all()
|
| 300 |
+
)
|
| 301 |
+
if not files:
|
| 302 |
+
return "HD"
|
| 303 |
+
for (f_name,) in files:
|
| 304 |
+
if detect_file_quality(f_name) == "Theatre Print [Clear Audio]":
|
| 305 |
+
return "Theatre Print [Clear Audio]"
|
| 306 |
+
return "HD"
|
| 307 |
+
except Exception:
|
| 308 |
+
return "HD"
|
| 309 |
+
finally:
|
| 310 |
+
try:
|
| 311 |
+
session.close()
|
| 312 |
+
except Exception:
|
| 313 |
+
pass
|
mfinder/db/ban_sql.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.pool import StaticPool
|
| 6 |
+
from sqlalchemy.exc import IntegrityError
|
| 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
|
| 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).first()
|
| 42 |
+
if usr:
|
| 43 |
+
if usr.user_name != user_name:
|
| 44 |
+
usr.user_name = user_name
|
| 45 |
+
SESSION.commit()
|
| 46 |
+
return
|
| 47 |
+
|
| 48 |
+
usr = Broadcast(user_id=user_id, user_name=user_name)
|
| 49 |
+
SESSION.add(usr)
|
| 50 |
+
SESSION.commit()
|
| 51 |
+
except Exception as e:
|
| 52 |
+
SESSION.rollback()
|
| 53 |
+
if isinstance(e, IntegrityError) or "UniqueViolation" in str(e):
|
| 54 |
+
pass
|
| 55 |
+
else:
|
| 56 |
+
raise e
|
| 57 |
+
finally:
|
| 58 |
+
SESSION.close()
|
| 59 |
+
|
| 60 |
+
async def is_user(user_id):
|
| 61 |
+
with INSERTION_LOCK:
|
| 62 |
+
try:
|
| 63 |
+
usr = SESSION.query(Broadcast).filter_by(user_id=user_id).first()
|
| 64 |
+
return usr.user_id if usr else False
|
| 65 |
+
except Exception as e:
|
| 66 |
+
SESSION.rollback()
|
| 67 |
+
raise e
|
| 68 |
+
finally:
|
| 69 |
+
SESSION.close()
|
| 70 |
+
|
| 71 |
+
async def query_msg():
|
| 72 |
+
try:
|
| 73 |
+
query = SESSION.query(Broadcast.user_id).order_by(Broadcast.user_id)
|
| 74 |
+
return query.all()
|
| 75 |
+
except Exception as e:
|
| 76 |
+
SESSION.rollback()
|
| 77 |
+
raise e
|
| 78 |
+
finally:
|
| 79 |
+
SESSION.close()
|
| 80 |
+
|
| 81 |
+
async def del_user(user_id):
|
| 82 |
+
with INSERTION_LOCK:
|
| 83 |
+
try:
|
| 84 |
+
usr = SESSION.query(Broadcast).filter_by(user_id=user_id).first()
|
| 85 |
+
if usr:
|
| 86 |
+
SESSION.delete(usr)
|
| 87 |
+
SESSION.commit()
|
| 88 |
+
except Exception as e:
|
| 89 |
+
SESSION.rollback()
|
| 90 |
+
raise e
|
| 91 |
+
finally:
|
| 92 |
+
SESSION.close()
|
mfinder/db/db_support.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
async def users_info(bot):
|
| 8 |
+
users = 0
|
| 9 |
+
blocked = 0
|
| 10 |
+
try:
|
| 11 |
+
identity = await query_msg()
|
| 12 |
+
if not identity:
|
| 13 |
+
return 0, 0
|
| 14 |
+
for user in identity:
|
| 15 |
+
user_id = int(user[0])
|
| 16 |
+
name = bool()
|
| 17 |
+
try:
|
| 18 |
+
name = await bot.send_chat_action(user_id, enums.ChatAction.TYPING)
|
| 19 |
+
except FloodWait as e:
|
| 20 |
+
await asyncio.sleep(e.value)
|
| 21 |
+
except Exception:
|
| 22 |
+
pass
|
| 23 |
+
if bool(name):
|
| 24 |
+
users += 1
|
| 25 |
+
else:
|
| 26 |
+
await del_user(user_id)
|
| 27 |
+
LOGGER.info("Deleted user id %s from broadcast list", user_id)
|
| 28 |
+
blocked += 1
|
| 29 |
+
return users, blocked
|
| 30 |
+
except Exception as e:
|
| 31 |
+
LOGGER.error(f"Error fetching users count: {e}")
|
| 32 |
+
return 0, 0
|
mfinder/db/files_sql.py
ADDED
|
@@ -0,0 +1,538 @@
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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(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|
|
|
|
|
|
|
|
|
| 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/newsletter_sql.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import threading
|
| 2 |
+
from sqlalchemy import create_engine, Column, BigInteger, Numeric
|
| 3 |
+
from sqlalchemy.ext.declarative import declarative_base
|
| 4 |
+
from sqlalchemy.orm import sessionmaker, scoped_session
|
| 5 |
+
from sqlalchemy.pool import QueuePool
|
| 6 |
+
from mfinder import DB_URL, LOGGER
|
| 7 |
+
|
| 8 |
+
BASE = declarative_base()
|
| 9 |
+
|
| 10 |
+
class NewsletterSubscribers(BASE):
|
| 11 |
+
__tablename__ = "newsletter_subscribers"
|
| 12 |
+
user_id = Column(BigInteger, primary_key=True)
|
| 13 |
+
created_at = Column(Numeric)
|
| 14 |
+
|
| 15 |
+
def __init__(self, user_id):
|
| 16 |
+
self.user_id = user_id
|
| 17 |
+
import time
|
| 18 |
+
self.created_at = time.time()
|
| 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
|
| 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 |
+
def db_retry(func):
|
| 41 |
+
import asyncio
|
| 42 |
+
import functools
|
| 43 |
+
from sqlalchemy.exc import OperationalError, PendingRollbackError
|
| 44 |
+
if asyncio.iscoroutinefunction(func):
|
| 45 |
+
@functools.wraps(func)
|
| 46 |
+
async def wrapper(*args, **kwargs):
|
| 47 |
+
for attempt in range(3):
|
| 48 |
+
try:
|
| 49 |
+
return await func(*args, **kwargs)
|
| 50 |
+
except (OperationalError, PendingRollbackError) as e:
|
| 51 |
+
LOGGER.warning("Database connection error in %s (attempt %s): %s. Reconnecting...", func.__name__, attempt + 1, str(e))
|
| 52 |
+
try:
|
| 53 |
+
SESSION.rollback()
|
| 54 |
+
except Exception:
|
| 55 |
+
pass
|
| 56 |
+
try:
|
| 57 |
+
SESSION.remove()
|
| 58 |
+
except Exception:
|
| 59 |
+
pass
|
| 60 |
+
if attempt == 2:
|
| 61 |
+
raise
|
| 62 |
+
await asyncio.sleep(0.5)
|
| 63 |
+
return wrapper
|
| 64 |
+
else:
|
| 65 |
+
@functools.wraps(func)
|
| 66 |
+
def wrapper(*args, **kwargs):
|
| 67 |
+
for attempt in range(3):
|
| 68 |
+
try:
|
| 69 |
+
return func(*args, **kwargs)
|
| 70 |
+
except (OperationalError, PendingRollbackError) as e:
|
| 71 |
+
LOGGER.warning("Database connection error in %s (attempt %s): %s. Reconnecting...", func.__name__, attempt + 1, str(e))
|
| 72 |
+
try:
|
| 73 |
+
SESSION.rollback()
|
| 74 |
+
except Exception:
|
| 75 |
+
pass
|
| 76 |
+
try:
|
| 77 |
+
SESSION.remove()
|
| 78 |
+
except Exception:
|
| 79 |
+
pass
|
| 80 |
+
if attempt == 2:
|
| 81 |
+
raise
|
| 82 |
+
import time
|
| 83 |
+
time.sleep(0.5)
|
| 84 |
+
return wrapper
|
| 85 |
+
|
| 86 |
+
@db_retry
|
| 87 |
+
async def is_subscribed(user_id: int) -> bool:
|
| 88 |
+
try:
|
| 89 |
+
with INSERTION_LOCK:
|
| 90 |
+
session = SESSION()
|
| 91 |
+
res = session.query(NewsletterSubscribers).filter_by(user_id=user_id).first()
|
| 92 |
+
return res is not None
|
| 93 |
+
except Exception as e:
|
| 94 |
+
LOGGER.warning("Error checking subscription: %s", str(e))
|
| 95 |
+
return False
|
| 96 |
+
finally:
|
| 97 |
+
SESSION.close()
|
| 98 |
+
|
| 99 |
+
@db_retry
|
| 100 |
+
async def subscribe_user(user_id: int) -> bool:
|
| 101 |
+
try:
|
| 102 |
+
with INSERTION_LOCK:
|
| 103 |
+
session = SESSION()
|
| 104 |
+
res = session.query(NewsletterSubscribers).filter_by(user_id=user_id).first()
|
| 105 |
+
if not res:
|
| 106 |
+
sub = NewsletterSubscribers(user_id)
|
| 107 |
+
session.add(sub)
|
| 108 |
+
session.commit()
|
| 109 |
+
return True
|
| 110 |
+
except Exception as e:
|
| 111 |
+
LOGGER.warning("Error subscribing user: %s", str(e))
|
| 112 |
+
SESSION.rollback()
|
| 113 |
+
return False
|
| 114 |
+
finally:
|
| 115 |
+
SESSION.close()
|
| 116 |
+
|
| 117 |
+
@db_retry
|
| 118 |
+
async def unsubscribe_user(user_id: int) -> bool:
|
| 119 |
+
try:
|
| 120 |
+
with INSERTION_LOCK:
|
| 121 |
+
session = SESSION()
|
| 122 |
+
res = session.query(NewsletterSubscribers).filter_by(user_id=user_id).first()
|
| 123 |
+
if res:
|
| 124 |
+
session.delete(res)
|
| 125 |
+
session.commit()
|
| 126 |
+
return True
|
| 127 |
+
except Exception as e:
|
| 128 |
+
LOGGER.warning("Error unsubscribing user: %s", str(e))
|
| 129 |
+
SESSION.rollback()
|
| 130 |
+
return False
|
| 131 |
+
finally:
|
| 132 |
+
SESSION.close()
|
| 133 |
+
|
| 134 |
+
@db_retry
|
| 135 |
+
async def get_all_subscribers() -> list:
|
| 136 |
+
try:
|
| 137 |
+
with INSERTION_LOCK:
|
| 138 |
+
session = SESSION()
|
| 139 |
+
res = session.query(NewsletterSubscribers.user_id).all()
|
| 140 |
+
return [r[0] for r in res]
|
| 141 |
+
except Exception as e:
|
| 142 |
+
LOGGER.warning("Error getting subscribers: %s", str(e))
|
| 143 |
+
return []
|
| 144 |
+
finally:
|
| 145 |
+
SESSION.close()
|
mfinder/db/requests_sql.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|
| 147 |
+
|
| 148 |
+
async def get_all_pending_requests() -> list:
|
| 149 |
+
"""Retrieves all pending movie requests."""
|
| 150 |
+
session = SESSION()
|
| 151 |
+
try:
|
| 152 |
+
return session.query(MovieRequest).filter_by(status="Pending").all()
|
| 153 |
+
except Exception as e:
|
| 154 |
+
try:
|
| 155 |
+
session.rollback()
|
| 156 |
+
except Exception:
|
| 157 |
+
pass
|
| 158 |
+
return []
|
| 159 |
+
finally:
|
| 160 |
+
session.close()
|
mfinder/db/settings_sql.py
ADDED
|
@@ -0,0 +1,1689 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import threading
|
| 2 |
+
from sqlalchemy import create_engine, Column, TEXT, Boolean, Numeric, BigInteger, Integer
|
| 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 |
+
|
| 12 |
+
def merge_env_shortener_into_list(shorteners_json, env_site, env_api, env_download):
|
| 13 |
+
import json
|
| 14 |
+
try:
|
| 15 |
+
shorteners = json.loads(shorteners_json) if shorteners_json else []
|
| 16 |
+
except Exception:
|
| 17 |
+
shorteners = []
|
| 18 |
+
|
| 19 |
+
parsed_site = None
|
| 20 |
+
if env_site:
|
| 21 |
+
ss = env_site.strip()
|
| 22 |
+
parsed_site = None if ss.lower() in ("off", "disable", "disabled", "none") else ss
|
| 23 |
+
|
| 24 |
+
parsed_api = env_api.strip() if env_api else None
|
| 25 |
+
|
| 26 |
+
parsed_hd = None
|
| 27 |
+
if env_download:
|
| 28 |
+
hd = env_download.strip()
|
| 29 |
+
parsed_hd = None if hd.lower() in ("off", "disable", "disabled", "none") else hd
|
| 30 |
+
|
| 31 |
+
if not parsed_site or not parsed_api:
|
| 32 |
+
return shorteners_json, False
|
| 33 |
+
|
| 34 |
+
exists = False
|
| 35 |
+
updated = False
|
| 36 |
+
for s in shorteners:
|
| 37 |
+
if s.get("site") == parsed_site:
|
| 38 |
+
if s.get("api") != parsed_api:
|
| 39 |
+
s["api"] = parsed_api
|
| 40 |
+
updated = True
|
| 41 |
+
if parsed_hd is not None and s.get("how_to_download") != parsed_hd:
|
| 42 |
+
s["how_to_download"] = parsed_hd
|
| 43 |
+
updated = True
|
| 44 |
+
exists = True
|
| 45 |
+
break
|
| 46 |
+
|
| 47 |
+
if not exists:
|
| 48 |
+
shorteners.append({
|
| 49 |
+
"site": parsed_site,
|
| 50 |
+
"api": parsed_api,
|
| 51 |
+
"how_to_download": parsed_hd,
|
| 52 |
+
"status": True
|
| 53 |
+
})
|
| 54 |
+
updated = True
|
| 55 |
+
|
| 56 |
+
return json.dumps(shorteners), updated
|
| 57 |
+
|
| 58 |
+
class AdminSettings(BASE):
|
| 59 |
+
__tablename__ = "admin_settings"
|
| 60 |
+
setting_name = Column(TEXT, primary_key=True)
|
| 61 |
+
auto_delete = Column(Numeric)
|
| 62 |
+
custom_caption = Column(TEXT)
|
| 63 |
+
fsub_channel = Column(Numeric)
|
| 64 |
+
channel_link = Column(TEXT)
|
| 65 |
+
caption_uname = Column(TEXT)
|
| 66 |
+
repair_mode = Column(Boolean)
|
| 67 |
+
shortener_status = Column(Boolean)
|
| 68 |
+
admins_list = Column(TEXT)
|
| 69 |
+
db_channels_list = Column(TEXT)
|
| 70 |
+
token_shortener_enabled = Column(Boolean)
|
| 71 |
+
token_timeout = Column(Numeric)
|
| 72 |
+
log_channel = Column(Numeric)
|
| 73 |
+
log_channel_access_hash = Column(Numeric)
|
| 74 |
+
fsub_channel_access_hash = Column(Numeric)
|
| 75 |
+
fsub_channels_list = Column(TEXT)
|
| 76 |
+
fsub_channels_access_hashes = Column(TEXT)
|
| 77 |
+
shorteners_list = Column(TEXT)
|
| 78 |
+
smart_rotator = Column(Boolean, default=False)
|
| 79 |
+
newsletter_days = Column(TEXT)
|
| 80 |
+
newsletter_time = Column(TEXT)
|
| 81 |
+
newsletter_count = Column(Integer)
|
| 82 |
+
newsletter_enabled = Column(Boolean, default=False)
|
| 83 |
+
newsletter_target = Column(TEXT)
|
| 84 |
+
announcement_enabled = Column(Boolean, default=False)
|
| 85 |
+
announcement_channel = Column(Numeric)
|
| 86 |
+
announcement_channel_access_hash = Column(Numeric)
|
| 87 |
+
|
| 88 |
+
def __init__(self, setting_name="default"):
|
| 89 |
+
self.setting_name = setting_name
|
| 90 |
+
self.auto_delete = 0
|
| 91 |
+
self.custom_caption = None
|
| 92 |
+
self.fsub_channel = None
|
| 93 |
+
self.channel_link = None
|
| 94 |
+
self.caption_uname = None
|
| 95 |
+
self.repair_mode = False
|
| 96 |
+
self.shortener_site = None
|
| 97 |
+
self.shortener_api = None
|
| 98 |
+
self.shortener_status = True
|
| 99 |
+
self.admins_list = None
|
| 100 |
+
self.db_channels_list = None
|
| 101 |
+
self.token_shortener_enabled = False
|
| 102 |
+
self.token_timeout = 3600
|
| 103 |
+
self.log_channel = None
|
| 104 |
+
self.how_to_download = None
|
| 105 |
+
self.log_channel_access_hash = None
|
| 106 |
+
self.fsub_channel_access_hash = None
|
| 107 |
+
self.fsub_channels_list = None
|
| 108 |
+
self.fsub_channels_access_hashes = "{}"
|
| 109 |
+
self.shorteners_list = "[]"
|
| 110 |
+
self.smart_rotator = False
|
| 111 |
+
self.newsletter_days = "Friday"
|
| 112 |
+
self.newsletter_time = "20:00"
|
| 113 |
+
self.newsletter_count = 10
|
| 114 |
+
self.newsletter_enabled = False
|
| 115 |
+
self.newsletter_target = "subscribed"
|
| 116 |
+
self.newsletter_days = "Friday"
|
| 117 |
+
self.newsletter_time = "20:00"
|
| 118 |
+
self.newsletter_count = 10
|
| 119 |
+
self.newsletter_enabled = False
|
| 120 |
+
|
| 121 |
+
class PendingFsubRequests(BASE):
|
| 122 |
+
__tablename__ = "pending_fsub_requests"
|
| 123 |
+
user_id = Column(Numeric, primary_key=True)
|
| 124 |
+
search_query = Column(TEXT)
|
| 125 |
+
target_file_id = Column(TEXT)
|
| 126 |
+
created_at = Column(Numeric)
|
| 127 |
+
|
| 128 |
+
def __init__(self, user_id, search_query=None, target_file_id=None):
|
| 129 |
+
self.user_id = user_id
|
| 130 |
+
self.search_query = search_query
|
| 131 |
+
self.target_file_id = target_file_id
|
| 132 |
+
import time
|
| 133 |
+
self.created_at = time.time()
|
| 134 |
+
|
| 135 |
+
class Settings(BASE):
|
| 136 |
+
__tablename__ = "settings"
|
| 137 |
+
user_id = Column(BigInteger, primary_key=True)
|
| 138 |
+
precise_mode = Column(Boolean)
|
| 139 |
+
button_mode = Column(Boolean)
|
| 140 |
+
link_mode = Column(Boolean)
|
| 141 |
+
list_mode = Column(Boolean)
|
| 142 |
+
|
| 143 |
+
def __init__(self, user_id, precise_mode, button_mode, link_mode, list_mode):
|
| 144 |
+
self.user_id = user_id
|
| 145 |
+
self.precise_mode = precise_mode
|
| 146 |
+
self.button_mode = button_mode
|
| 147 |
+
self.link_mode = link_mode
|
| 148 |
+
self.list_mode = list_mode
|
| 149 |
+
|
| 150 |
+
class UserTokens(BASE):
|
| 151 |
+
__tablename__ = "user_tokens"
|
| 152 |
+
user_id = Column(BigInteger, primary_key=True)
|
| 153 |
+
token = Column(TEXT)
|
| 154 |
+
created_at = Column(Numeric)
|
| 155 |
+
expires_at = Column(Numeric)
|
| 156 |
+
status = Column(TEXT)
|
| 157 |
+
search_query = Column(TEXT)
|
| 158 |
+
target_file_id = Column(TEXT)
|
| 159 |
+
req_msg_id = Column(Numeric, nullable=True)
|
| 160 |
+
|
| 161 |
+
def __init__(self, user_id, token, created_at, expires_at=0, status="pending", search_query=None, target_file_id=None, req_msg_id=None):
|
| 162 |
+
self.user_id = user_id
|
| 163 |
+
self.token = token
|
| 164 |
+
self.created_at = created_at
|
| 165 |
+
self.expires_at = expires_at
|
| 166 |
+
self.status = status
|
| 167 |
+
self.search_query = search_query
|
| 168 |
+
self.target_file_id = target_file_id
|
| 169 |
+
self.req_msg_id = req_msg_id
|
| 170 |
+
|
| 171 |
+
class UserShortenerUsage(BASE):
|
| 172 |
+
__tablename__ = "user_shortener_usage"
|
| 173 |
+
user_id = Column(BigInteger, primary_key=True)
|
| 174 |
+
last_index = Column(Integer, default=0)
|
| 175 |
+
last_date = Column(TEXT) # Format: YYYY-MM-DD
|
| 176 |
+
|
| 177 |
+
def __init__(self, user_id, last_index=0, last_date=""):
|
| 178 |
+
self.user_id = user_id
|
| 179 |
+
self.last_index = last_index
|
| 180 |
+
self.last_date = last_date
|
| 181 |
+
|
| 182 |
+
# SQLite configuration for auto-delete queue to save Neon compute hours
|
| 183 |
+
SQLITE_DB_URL = "sqlite:///mfinder_autodelete.db"
|
| 184 |
+
sqlite_engine = create_engine(SQLITE_DB_URL, pool_pre_ping=True)
|
| 185 |
+
sqlite_session_maker = sessionmaker(bind=sqlite_engine, autoflush=False)
|
| 186 |
+
SQLITE_SESSION = scoped_session(sqlite_session_maker)
|
| 187 |
+
SQLITE_BASE = declarative_base()
|
| 188 |
+
|
| 189 |
+
class AutoDeleteMessage(SQLITE_BASE):
|
| 190 |
+
__tablename__ = "auto_delete_messages"
|
| 191 |
+
id = Column(Integer, primary_key=True, autoincrement=True)
|
| 192 |
+
chat_id = Column(Numeric)
|
| 193 |
+
message_id = Column(Integer)
|
| 194 |
+
delete_at = Column(Numeric) # Unix timestamp
|
| 195 |
+
|
| 196 |
+
def __init__(self, chat_id, message_id, delete_at):
|
| 197 |
+
self.chat_id = chat_id
|
| 198 |
+
self.message_id = message_id
|
| 199 |
+
self.delete_at = delete_at
|
| 200 |
+
|
| 201 |
+
def start() -> scoped_session:
|
| 202 |
+
connect_args = {}
|
| 203 |
+
if DB_URL and DB_URL.startswith(("postgres://", "postgresql://")):
|
| 204 |
+
connect_args["sslmode"] = "require"
|
| 205 |
+
engine = create_engine(
|
| 206 |
+
DB_URL,
|
| 207 |
+
connect_args=connect_args,
|
| 208 |
+
poolclass=QueuePool,
|
| 209 |
+
pool_size=10,
|
| 210 |
+
max_overflow=20,
|
| 211 |
+
pool_pre_ping=True,
|
| 212 |
+
pool_recycle=1800 # Recycle connections every 1800 seconds (30 minutes)
|
| 213 |
+
)
|
| 214 |
+
BASE.metadata.bind = engine
|
| 215 |
+
BASE.metadata.create_all(engine)
|
| 216 |
+
SQLITE_BASE.metadata.bind = sqlite_engine
|
| 217 |
+
SQLITE_BASE.metadata.create_all(sqlite_engine)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
# Migrate and drop legacy columns
|
| 222 |
+
from sqlalchemy import text
|
| 223 |
+
try:
|
| 224 |
+
from sqlalchemy import inspect
|
| 225 |
+
inspector = inspect(engine)
|
| 226 |
+
columns = [col["name"] for col in inspector.get_columns("admin_settings")]
|
| 227 |
+
|
| 228 |
+
# Only migrate and drop if obsolete columns actually exist in the table
|
| 229 |
+
has_obsolete = any(c in columns for c in ["shortener_site", "shortener_api", "how_to_download"])
|
| 230 |
+
|
| 231 |
+
if has_obsolete:
|
| 232 |
+
|
| 233 |
+
# 1. Attempt to migrate old settings
|
| 234 |
+
old_site = None
|
| 235 |
+
old_api = None
|
| 236 |
+
old_download = None
|
| 237 |
+
shorteners_list_json = None
|
| 238 |
+
|
| 239 |
+
col_selectors = []
|
| 240 |
+
if "shortener_site" in columns:
|
| 241 |
+
col_selectors.append("shortener_site")
|
| 242 |
+
if "shortener_api" in columns:
|
| 243 |
+
col_selectors.append("shortener_api")
|
| 244 |
+
if "how_to_download" in columns:
|
| 245 |
+
col_selectors.append("how_to_download")
|
| 246 |
+
|
| 247 |
+
if len(col_selectors) > 0 and "shorteners_list" in columns:
|
| 248 |
+
col_selectors.append("shorteners_list")
|
| 249 |
+
try:
|
| 250 |
+
with engine.connect() as conn:
|
| 251 |
+
query_str = f"SELECT {', '.join(col_selectors)} FROM admin_settings LIMIT 1"
|
| 252 |
+
res = conn.execute(text(query_str)).fetchone()
|
| 253 |
+
if res:
|
| 254 |
+
val_map = dict(zip(col_selectors, res))
|
| 255 |
+
old_site = val_map.get("shortener_site")
|
| 256 |
+
old_api = val_map.get("shortener_api")
|
| 257 |
+
old_download = val_map.get("how_to_download")
|
| 258 |
+
shorteners_list_json = val_map.get("shorteners_list")
|
| 259 |
+
|
| 260 |
+
if old_site and old_api:
|
| 261 |
+
import json
|
| 262 |
+
try:
|
| 263 |
+
shorteners = json.loads(shorteners_list_json) if shorteners_list_json else []
|
| 264 |
+
except Exception:
|
| 265 |
+
shorteners = []
|
| 266 |
+
exists = any(s.get("site") == old_site and s.get("api") == old_api for s in shorteners)
|
| 267 |
+
if not exists:
|
| 268 |
+
shorteners.append({
|
| 269 |
+
"site": old_site,
|
| 270 |
+
"api": old_api,
|
| 271 |
+
"how_to_download": old_download,
|
| 272 |
+
"status": True
|
| 273 |
+
})
|
| 274 |
+
with engine.begin() as t_conn:
|
| 275 |
+
t_conn.execute(
|
| 276 |
+
text("UPDATE admin_settings SET shorteners_list = :sl"),
|
| 277 |
+
{"sl": json.dumps(shorteners)}
|
| 278 |
+
)
|
| 279 |
+
LOGGER.info(f"Successfully migrated old shortener {old_site} to shorteners_list.")
|
| 280 |
+
except Exception as e:
|
| 281 |
+
LOGGER.warning(f"Error migrating old settings: {e}")
|
| 282 |
+
|
| 283 |
+
# 2. Drop the obsolete columns since they exist (each column drop in its own transaction block)
|
| 284 |
+
for col_to_drop in ["shortener_site", "shortener_api", "how_to_download"]:
|
| 285 |
+
if col_to_drop in columns:
|
| 286 |
+
try:
|
| 287 |
+
with engine.begin() as t_conn:
|
| 288 |
+
t_conn.execute(text(f"ALTER TABLE admin_settings DROP COLUMN IF EXISTS {col_to_drop}"))
|
| 289 |
+
LOGGER.info(f"Obsolete column {col_to_drop} successfully dropped from admin_settings table.")
|
| 290 |
+
except Exception as e:
|
| 291 |
+
LOGGER.warning(f"Error dropping column {col_to_drop}: {e}")
|
| 292 |
+
except Exception as e:
|
| 293 |
+
LOGGER.warning(f"Error checking/dropping obsolete columns: {e}")
|
| 294 |
+
|
| 295 |
+
from sqlalchemy import text
|
| 296 |
+
try:
|
| 297 |
+
with engine.connect() as conn:
|
| 298 |
+
with conn.begin():
|
| 299 |
+
# conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS shortener_site TEXT"))
|
| 300 |
+
# conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS shortener_api TEXT"))
|
| 301 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS shortener_status BOOLEAN DEFAULT TRUE"))
|
| 302 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS admins_list TEXT"))
|
| 303 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS db_channels_list TEXT"))
|
| 304 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS token_shortener_enabled BOOLEAN DEFAULT FALSE"))
|
| 305 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS token_timeout NUMERIC DEFAULT 3600"))
|
| 306 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS log_channel NUMERIC"))
|
| 307 |
+
# conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS how_to_download TEXT"))
|
| 308 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS log_channel_access_hash NUMERIC"))
|
| 309 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS fsub_channel_access_hash NUMERIC"))
|
| 310 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS fsub_channels_list TEXT"))
|
| 311 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS fsub_channels_access_hashes TEXT"))
|
| 312 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS shorteners_list TEXT"))
|
| 313 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS smart_rotator BOOLEAN DEFAULT FALSE"))
|
| 314 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS newsletter_days TEXT DEFAULT 'Friday'"))
|
| 315 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS newsletter_time TEXT DEFAULT '20:00'"))
|
| 316 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS newsletter_count INTEGER DEFAULT 10"))
|
| 317 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS newsletter_enabled BOOLEAN DEFAULT FALSE"))
|
| 318 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS newsletter_target TEXT DEFAULT 'subscribed'"))
|
| 319 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS announcement_enabled BOOLEAN DEFAULT FALSE"))
|
| 320 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS announcement_channel NUMERIC"))
|
| 321 |
+
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN IF NOT EXISTS announcement_channel_access_hash NUMERIC"))
|
| 322 |
+
conn.execute(text("""
|
| 323 |
+
CREATE TABLE IF NOT EXISTS user_shortener_usage (
|
| 324 |
+
user_id BIGINT PRIMARY KEY,
|
| 325 |
+
last_index INTEGER DEFAULT 0,
|
| 326 |
+
last_date TEXT
|
| 327 |
+
)
|
| 328 |
+
"""))
|
| 329 |
+
conn.execute(text("ALTER TABLE user_tokens ADD COLUMN IF NOT EXISTS req_msg_id NUMERIC"))
|
| 330 |
+
conn.execute(text("""
|
| 331 |
+
CREATE TABLE IF NOT EXISTS pending_fsub_requests (
|
| 332 |
+
user_id NUMERIC PRIMARY KEY,
|
| 333 |
+
search_query TEXT,
|
| 334 |
+
target_file_id TEXT,
|
| 335 |
+
created_at NUMERIC
|
| 336 |
+
)
|
| 337 |
+
"""))
|
| 338 |
+
try:
|
| 339 |
+
conn.execute(text("ALTER TABLE pending_fsub_requests ALTER COLUMN user_id TYPE NUMERIC"))
|
| 340 |
+
except Exception:
|
| 341 |
+
pass
|
| 342 |
+
except Exception as e:
|
| 343 |
+
LOGGER.warning("Could not execute DDL migrations for admin_settings: %s", str(e))
|
| 344 |
+
|
| 345 |
+
return scoped_session(sessionmaker(bind=engine, autoflush=False))
|
| 346 |
+
|
| 347 |
+
SESSION = start()
|
| 348 |
+
|
| 349 |
+
import asyncio
|
| 350 |
+
import time
|
| 351 |
+
import functools
|
| 352 |
+
from sqlalchemy.exc import OperationalError, PendingRollbackError
|
| 353 |
+
|
| 354 |
+
def db_retry(func):
|
| 355 |
+
if asyncio.iscoroutinefunction(func):
|
| 356 |
+
@functools.wraps(func)
|
| 357 |
+
async def wrapper(*args, **kwargs):
|
| 358 |
+
for attempt in range(3):
|
| 359 |
+
try:
|
| 360 |
+
return await func(*args, **kwargs)
|
| 361 |
+
except (OperationalError, PendingRollbackError) as e:
|
| 362 |
+
LOGGER.warning("Database connection error in %s (attempt %s): %s. Reconnecting...", func.__name__, attempt + 1, str(e))
|
| 363 |
+
try:
|
| 364 |
+
SESSION.rollback()
|
| 365 |
+
SESSION.remove()
|
| 366 |
+
except Exception:
|
| 367 |
+
pass
|
| 368 |
+
if attempt == 2:
|
| 369 |
+
raise
|
| 370 |
+
await asyncio.sleep(0.5)
|
| 371 |
+
return wrapper
|
| 372 |
+
else:
|
| 373 |
+
@functools.wraps(func)
|
| 374 |
+
def wrapper(*args, **kwargs):
|
| 375 |
+
for attempt in range(3):
|
| 376 |
+
try:
|
| 377 |
+
return func(*args, **kwargs)
|
| 378 |
+
except (OperationalError, PendingRollbackError) as e:
|
| 379 |
+
LOGGER.warning("Database connection error in %s (attempt %s): %s. Reconnecting...", func.__name__, attempt + 1, str(e))
|
| 380 |
+
try:
|
| 381 |
+
SESSION.rollback()
|
| 382 |
+
SESSION.remove()
|
| 383 |
+
except Exception:
|
| 384 |
+
pass
|
| 385 |
+
if attempt == 2:
|
| 386 |
+
raise
|
| 387 |
+
time.sleep(0.5)
|
| 388 |
+
return wrapper
|
| 389 |
+
|
| 390 |
+
# ----------------- IN-MEMORY CACHE & MUTEX LOCK -----------------
|
| 391 |
+
class CachedAdminSettings:
|
| 392 |
+
def __init__(self, admin_settings_db=None):
|
| 393 |
+
self.setting_name = "default"
|
| 394 |
+
self.auto_delete = 0
|
| 395 |
+
self.custom_caption = None
|
| 396 |
+
self.fsub_channel = None
|
| 397 |
+
self.channel_link = None
|
| 398 |
+
self.caption_uname = None
|
| 399 |
+
self.repair_mode = False
|
| 400 |
+
self.shortener_status = True
|
| 401 |
+
self.admins_list = None
|
| 402 |
+
self.db_channels_list = None
|
| 403 |
+
self.token_shortener_enabled = False
|
| 404 |
+
self.token_timeout = 3600
|
| 405 |
+
self.log_channel = None
|
| 406 |
+
self.log_channel_access_hash = None
|
| 407 |
+
self.fsub_channel_access_hash = None
|
| 408 |
+
self.fsub_channels_list = None
|
| 409 |
+
self.fsub_channels_access_hashes = "{}"
|
| 410 |
+
self.shorteners_list = "[]"
|
| 411 |
+
self.smart_rotator = False
|
| 412 |
+
self.newsletter_days = "Friday"
|
| 413 |
+
self.newsletter_time = "20:00"
|
| 414 |
+
self.newsletter_count = 10
|
| 415 |
+
self.newsletter_enabled = False
|
| 416 |
+
self.newsletter_target = "subscribed"
|
| 417 |
+
self.announcement_enabled = False
|
| 418 |
+
self.announcement_channel = None
|
| 419 |
+
self.announcement_channel_access_hash = None
|
| 420 |
+
self.shortener_site = None
|
| 421 |
+
self.shortener_api = None
|
| 422 |
+
self.how_to_download = None
|
| 423 |
+
|
| 424 |
+
if admin_settings_db:
|
| 425 |
+
def to_numeric(val):
|
| 426 |
+
if val is None:
|
| 427 |
+
return None
|
| 428 |
+
try:
|
| 429 |
+
val_str = str(val)
|
| 430 |
+
if "." not in val_str:
|
| 431 |
+
return int(val)
|
| 432 |
+
f_val = float(val)
|
| 433 |
+
if f_val.is_integer():
|
| 434 |
+
return int(f_val)
|
| 435 |
+
return f_val
|
| 436 |
+
except (ValueError, TypeError):
|
| 437 |
+
return val
|
| 438 |
+
|
| 439 |
+
self.setting_name = admin_settings_db.setting_name
|
| 440 |
+
self.auto_delete = to_numeric(admin_settings_db.auto_delete) or 0
|
| 441 |
+
self.custom_caption = admin_settings_db.custom_caption
|
| 442 |
+
self.fsub_channel = to_numeric(admin_settings_db.fsub_channel)
|
| 443 |
+
self.channel_link = admin_settings_db.channel_link
|
| 444 |
+
self.caption_uname = admin_settings_db.caption_uname
|
| 445 |
+
self.repair_mode = bool(admin_settings_db.repair_mode)
|
| 446 |
+
self.shortener_status = bool(admin_settings_db.shortener_status) if admin_settings_db.shortener_status is not None else True
|
| 447 |
+
self.admins_list = admin_settings_db.admins_list
|
| 448 |
+
self.db_channels_list = admin_settings_db.db_channels_list
|
| 449 |
+
self.token_shortener_enabled = bool(admin_settings_db.token_shortener_enabled) if admin_settings_db.token_shortener_enabled is not None else False
|
| 450 |
+
self.token_timeout = to_numeric(admin_settings_db.token_timeout) or 3600
|
| 451 |
+
self.log_channel = to_numeric(admin_settings_db.log_channel)
|
| 452 |
+
self.log_channel_access_hash = to_numeric(admin_settings_db.log_channel_access_hash)
|
| 453 |
+
self.fsub_channel_access_hash = to_numeric(admin_settings_db.fsub_channel_access_hash)
|
| 454 |
+
self.fsub_channels_list = admin_settings_db.fsub_channels_list
|
| 455 |
+
self.fsub_channels_access_hashes = admin_settings_db.fsub_channels_access_hashes or "{}"
|
| 456 |
+
self.shorteners_list = admin_settings_db.shorteners_list or "[]"
|
| 457 |
+
self.smart_rotator = bool(admin_settings_db.smart_rotator) if admin_settings_db.smart_rotator is not None else False
|
| 458 |
+
self.newsletter_days = admin_settings_db.newsletter_days or "Friday"
|
| 459 |
+
self.newsletter_time = admin_settings_db.newsletter_time or "20:00"
|
| 460 |
+
self.newsletter_count = to_numeric(admin_settings_db.newsletter_count) or 10
|
| 461 |
+
self.newsletter_enabled = bool(admin_settings_db.newsletter_enabled) if admin_settings_db.newsletter_enabled is not None else False
|
| 462 |
+
self.newsletter_target = admin_settings_db.newsletter_target or "subscribed"
|
| 463 |
+
self.announcement_enabled = bool(admin_settings_db.announcement_enabled) if admin_settings_db.announcement_enabled is not None else False
|
| 464 |
+
self.announcement_channel = to_numeric(admin_settings_db.announcement_channel)
|
| 465 |
+
self.announcement_channel_access_hash = to_numeric(admin_settings_db.announcement_channel_access_hash)
|
| 466 |
+
|
| 467 |
+
# Dynamically resolve legacy columns from shorteners_list JSON
|
| 468 |
+
import json
|
| 469 |
+
try:
|
| 470 |
+
sh_list = json.loads(self.shorteners_list)
|
| 471 |
+
except Exception:
|
| 472 |
+
sh_list = []
|
| 473 |
+
if sh_list:
|
| 474 |
+
first_sh = sh_list[0]
|
| 475 |
+
self.shortener_site = first_sh.get("site")
|
| 476 |
+
self.shortener_api = first_sh.get("api")
|
| 477 |
+
self.how_to_download = first_sh.get("how_to_download")
|
| 478 |
+
else:
|
| 479 |
+
self.shortener_site = None
|
| 480 |
+
self.shortener_api = None
|
| 481 |
+
self.how_to_download = None
|
| 482 |
+
|
| 483 |
+
_cached_admin_settings = None
|
| 484 |
+
_cache_lock = threading.Lock()
|
| 485 |
+
|
| 486 |
+
def _update_cache_from_db(admin_setting):
|
| 487 |
+
global _cached_admin_settings
|
| 488 |
+
with _cache_lock:
|
| 489 |
+
_cached_admin_settings = CachedAdminSettings(admin_setting)
|
| 490 |
+
|
| 491 |
+
@db_retry
|
| 492 |
+
def get_admin_settings_sync():
|
| 493 |
+
global _cached_admin_settings
|
| 494 |
+
with _cache_lock:
|
| 495 |
+
if _cached_admin_settings is not None:
|
| 496 |
+
return _cached_admin_settings
|
| 497 |
+
|
| 498 |
+
for attempt in range(3):
|
| 499 |
+
try:
|
| 500 |
+
session = SESSION()
|
| 501 |
+
admin_setting = session.query(AdminSettings).first()
|
| 502 |
+
if not admin_setting:
|
| 503 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 504 |
+
session.add(admin_setting)
|
| 505 |
+
session.commit()
|
| 506 |
+
_cached_admin_settings = CachedAdminSettings(admin_setting)
|
| 507 |
+
return _cached_admin_settings
|
| 508 |
+
except (OperationalError, PendingRollbackError) as e:
|
| 509 |
+
LOGGER.warning("Database connection error in get_admin_settings_sync (attempt %d): %s. Reconnecting...", attempt + 1, str(e))
|
| 510 |
+
try:
|
| 511 |
+
SESSION.rollback()
|
| 512 |
+
except Exception:
|
| 513 |
+
pass
|
| 514 |
+
try:
|
| 515 |
+
SESSION.remove()
|
| 516 |
+
except Exception:
|
| 517 |
+
pass
|
| 518 |
+
if attempt == 2:
|
| 519 |
+
return CachedAdminSettings()
|
| 520 |
+
time.sleep(0.5)
|
| 521 |
+
except Exception as e:
|
| 522 |
+
LOGGER.warning("Error in get_admin_settings_sync: %s", str(e))
|
| 523 |
+
try:
|
| 524 |
+
SESSION.rollback()
|
| 525 |
+
except Exception:
|
| 526 |
+
pass
|
| 527 |
+
try:
|
| 528 |
+
SESSION.remove()
|
| 529 |
+
except Exception:
|
| 530 |
+
pass
|
| 531 |
+
return CachedAdminSettings()
|
| 532 |
+
finally:
|
| 533 |
+
SESSION.close()
|
| 534 |
+
|
| 535 |
+
@db_retry
|
| 536 |
+
def heal_admin_settings():
|
| 537 |
+
import os
|
| 538 |
+
try:
|
| 539 |
+
session = SESSION()
|
| 540 |
+
admin_setting = session.query(AdminSettings).first()
|
| 541 |
+
|
| 542 |
+
env_admins = os.environ.get("ADMINS", "")
|
| 543 |
+
owner_id = os.environ.get("OWNER_ID", "")
|
| 544 |
+
admins_set = set()
|
| 545 |
+
for x in env_admins.split():
|
| 546 |
+
x = x.strip()
|
| 547 |
+
if x:
|
| 548 |
+
admins_set.add(x)
|
| 549 |
+
if owner_id:
|
| 550 |
+
admins_set.add(owner_id.strip())
|
| 551 |
+
default_admins = ",".join(sorted(list(admins_set))) if admins_set else None
|
| 552 |
+
|
| 553 |
+
env_channels = os.environ.get("DB_CHANNELS", "")
|
| 554 |
+
channels_list = []
|
| 555 |
+
for x in env_channels.split():
|
| 556 |
+
x = x.strip()
|
| 557 |
+
if x:
|
| 558 |
+
channels_list.append(x)
|
| 559 |
+
default_channels = ",".join(channels_list) if channels_list else None
|
| 560 |
+
|
| 561 |
+
# Parse helpers
|
| 562 |
+
def parse_bool(env_val, default=None):
|
| 563 |
+
if env_val is None:
|
| 564 |
+
return default
|
| 565 |
+
val = env_val.strip().lower()
|
| 566 |
+
if val in ("true", "yes", "on", "1"):
|
| 567 |
+
return True
|
| 568 |
+
if val in ("false", "no", "off", "0"):
|
| 569 |
+
return False
|
| 570 |
+
return default
|
| 571 |
+
|
| 572 |
+
def parse_int(env_val, default=None):
|
| 573 |
+
if env_val is None:
|
| 574 |
+
return default
|
| 575 |
+
try:
|
| 576 |
+
return int(env_val.strip())
|
| 577 |
+
except ValueError:
|
| 578 |
+
return default
|
| 579 |
+
|
| 580 |
+
def parse_time(env_val, default=None):
|
| 581 |
+
if env_val is None:
|
| 582 |
+
return default
|
| 583 |
+
val = env_val.strip().lower()
|
| 584 |
+
if val.endswith("h"):
|
| 585 |
+
try:
|
| 586 |
+
return int(float(val[:-1]) * 3600)
|
| 587 |
+
except ValueError:
|
| 588 |
+
pass
|
| 589 |
+
elif val.endswith("m"):
|
| 590 |
+
try:
|
| 591 |
+
return int(float(val[:-1]) * 60)
|
| 592 |
+
except ValueError:
|
| 593 |
+
pass
|
| 594 |
+
elif val.endswith("d"):
|
| 595 |
+
try:
|
| 596 |
+
return int(float(val[:-1]) * 86400)
|
| 597 |
+
except ValueError:
|
| 598 |
+
pass
|
| 599 |
+
elif val.endswith("s"):
|
| 600 |
+
try:
|
| 601 |
+
return int(float(val[:-1]))
|
| 602 |
+
except ValueError:
|
| 603 |
+
pass
|
| 604 |
+
else:
|
| 605 |
+
try:
|
| 606 |
+
return int(val)
|
| 607 |
+
except ValueError:
|
| 608 |
+
pass
|
| 609 |
+
return default
|
| 610 |
+
|
| 611 |
+
env_auto_delete = os.environ.get("AUTO_DELETE")
|
| 612 |
+
env_custom_caption = os.environ.get("CUSTOM_CAPTION")
|
| 613 |
+
env_fsub_channel = os.environ.get("FSUB_CHANNEL")
|
| 614 |
+
env_channel_link = os.environ.get("CHANNEL_LINK")
|
| 615 |
+
env_caption_uname = os.environ.get("CAPTION_UNAME")
|
| 616 |
+
env_repair_mode = os.environ.get("REPAIR_MODE")
|
| 617 |
+
env_shortener_site = os.environ.get("SHORTENER_SITE")
|
| 618 |
+
env_shortener_api = os.environ.get("SHORTENER_API")
|
| 619 |
+
env_shortener_status = os.environ.get("SHORTENER_STATUS")
|
| 620 |
+
env_token_shortener_enabled = os.environ.get("TOKEN_SHORTENER_ENABLED")
|
| 621 |
+
env_token_timeout = os.environ.get("TOKEN_TIMEOUT")
|
| 622 |
+
env_log_channel = os.environ.get("LOG_CHANNEL")
|
| 623 |
+
env_how_to_download = os.environ.get("HOW_TO_DOWNLOAD")
|
| 624 |
+
|
| 625 |
+
if not admin_setting:
|
| 626 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 627 |
+
admin_setting.admins_list = default_admins
|
| 628 |
+
admin_setting.db_channels_list = default_channels
|
| 629 |
+
|
| 630 |
+
if env_auto_delete is not None:
|
| 631 |
+
admin_setting.auto_delete = parse_int(env_auto_delete, 0)
|
| 632 |
+
if env_custom_caption is not None:
|
| 633 |
+
cc = env_custom_caption.strip()
|
| 634 |
+
admin_setting.custom_caption = None if cc.lower() in ("off", "disable", "disabled", "none") else cc
|
| 635 |
+
if env_fsub_channel is not None:
|
| 636 |
+
admin_setting.fsub_channel = parse_int(env_fsub_channel)
|
| 637 |
+
if env_channel_link is not None:
|
| 638 |
+
cl = env_channel_link.strip()
|
| 639 |
+
admin_setting.channel_link = None if cl.lower() in ("off", "disable", "disabled", "none") else cl
|
| 640 |
+
if env_caption_uname is not None:
|
| 641 |
+
cu = env_caption_uname.strip()
|
| 642 |
+
admin_setting.caption_uname = None if cu.lower() in ("off", "disable", "disabled", "none") else cu
|
| 643 |
+
if env_repair_mode is not None:
|
| 644 |
+
admin_setting.repair_mode = parse_bool(env_repair_mode, False)
|
| 645 |
+
if env_shortener_site and env_shortener_api:
|
| 646 |
+
new_list, _ = merge_env_shortener_into_list(
|
| 647 |
+
admin_setting.shorteners_list,
|
| 648 |
+
env_shortener_site,
|
| 649 |
+
env_shortener_api,
|
| 650 |
+
env_how_to_download
|
| 651 |
+
)
|
| 652 |
+
admin_setting.shorteners_list = new_list
|
| 653 |
+
if env_shortener_status is not None:
|
| 654 |
+
admin_setting.shortener_status = parse_bool(env_shortener_status, True)
|
| 655 |
+
if env_token_shortener_enabled is not None:
|
| 656 |
+
admin_setting.token_shortener_enabled = parse_bool(env_token_shortener_enabled, False)
|
| 657 |
+
if env_token_timeout is not None:
|
| 658 |
+
admin_setting.token_timeout = parse_time(env_token_timeout, 3600)
|
| 659 |
+
if env_log_channel is not None:
|
| 660 |
+
admin_setting.log_channel = parse_int(env_log_channel)
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
# Enforce mutual exclusion
|
| 664 |
+
if admin_setting.token_shortener_enabled and admin_setting.shortener_status:
|
| 665 |
+
admin_setting.shortener_status = False
|
| 666 |
+
|
| 667 |
+
session.add(admin_setting)
|
| 668 |
+
session.commit()
|
| 669 |
+
LOGGER.info("Created default AdminSettings with env values.")
|
| 670 |
+
else:
|
| 671 |
+
updated = False
|
| 672 |
+
# Check if admins_list is None, empty, or has the test dummy values
|
| 673 |
+
if (not admin_setting.admins_list or
|
| 674 |
+
admin_setting.admins_list == "12345,67890" or
|
| 675 |
+
(owner_id and owner_id.strip() not in admin_setting.admins_list.split(','))):
|
| 676 |
+
admin_setting.admins_list = default_admins
|
| 677 |
+
updated = True
|
| 678 |
+
|
| 679 |
+
# Check if db_channels_list is None, empty, or has the test dummy values
|
| 680 |
+
if (not admin_setting.db_channels_list or
|
| 681 |
+
admin_setting.db_channels_list == "-100123,-100456"):
|
| 682 |
+
admin_setting.db_channels_list = default_channels
|
| 683 |
+
updated = True
|
| 684 |
+
|
| 685 |
+
# Heal other environment variables
|
| 686 |
+
if env_auto_delete is not None:
|
| 687 |
+
parsed_auto_delete = parse_int(env_auto_delete)
|
| 688 |
+
if parsed_auto_delete is not None and admin_setting.auto_delete != parsed_auto_delete:
|
| 689 |
+
admin_setting.auto_delete = parsed_auto_delete
|
| 690 |
+
updated = True
|
| 691 |
+
|
| 692 |
+
if env_custom_caption is not None:
|
| 693 |
+
parsed_custom_caption = env_custom_caption.strip()
|
| 694 |
+
if parsed_custom_caption.lower() in ("off", "disable", "disabled", "none"):
|
| 695 |
+
parsed_custom_caption = None
|
| 696 |
+
if admin_setting.custom_caption != parsed_custom_caption:
|
| 697 |
+
admin_setting.custom_caption = parsed_custom_caption
|
| 698 |
+
updated = True
|
| 699 |
+
|
| 700 |
+
if env_fsub_channel is not None:
|
| 701 |
+
parsed_fsub_channel = parse_int(env_fsub_channel)
|
| 702 |
+
if parsed_fsub_channel is not None and admin_setting.fsub_channel != parsed_fsub_channel:
|
| 703 |
+
admin_setting.fsub_channel = parsed_fsub_channel
|
| 704 |
+
updated = True
|
| 705 |
+
|
| 706 |
+
if env_channel_link is not None:
|
| 707 |
+
parsed_channel_link = env_channel_link.strip()
|
| 708 |
+
if parsed_channel_link.lower() in ("off", "disable", "disabled", "none"):
|
| 709 |
+
parsed_channel_link = None
|
| 710 |
+
if admin_setting.channel_link != parsed_channel_link:
|
| 711 |
+
admin_setting.channel_link = parsed_channel_link
|
| 712 |
+
updated = True
|
| 713 |
+
|
| 714 |
+
if env_caption_uname is not None:
|
| 715 |
+
parsed_caption_uname = env_caption_uname.strip()
|
| 716 |
+
if parsed_caption_uname.lower() in ("off", "disable", "disabled", "none"):
|
| 717 |
+
parsed_caption_uname = None
|
| 718 |
+
if admin_setting.caption_uname != parsed_caption_uname:
|
| 719 |
+
admin_setting.caption_uname = parsed_caption_uname
|
| 720 |
+
updated = True
|
| 721 |
+
|
| 722 |
+
if env_repair_mode is not None:
|
| 723 |
+
parsed_repair_mode = parse_bool(env_repair_mode)
|
| 724 |
+
if parsed_repair_mode is not None and admin_setting.repair_mode != parsed_repair_mode:
|
| 725 |
+
admin_setting.repair_mode = parsed_repair_mode
|
| 726 |
+
updated = True
|
| 727 |
+
|
| 728 |
+
if env_shortener_site and env_shortener_api:
|
| 729 |
+
new_list, list_updated = merge_env_shortener_into_list(
|
| 730 |
+
admin_setting.shorteners_list,
|
| 731 |
+
env_shortener_site,
|
| 732 |
+
env_shortener_api,
|
| 733 |
+
env_how_to_download
|
| 734 |
+
)
|
| 735 |
+
if list_updated:
|
| 736 |
+
admin_setting.shorteners_list = new_list
|
| 737 |
+
updated = True
|
| 738 |
+
|
| 739 |
+
if env_shortener_status is not None:
|
| 740 |
+
parsed_shortener_status = parse_bool(env_shortener_status)
|
| 741 |
+
if parsed_shortener_status is not None and admin_setting.shortener_status != parsed_shortener_status:
|
| 742 |
+
admin_setting.shortener_status = parsed_shortener_status
|
| 743 |
+
updated = True
|
| 744 |
+
|
| 745 |
+
if env_token_shortener_enabled is not None:
|
| 746 |
+
parsed_token_shortener_enabled = parse_bool(env_token_shortener_enabled)
|
| 747 |
+
if parsed_token_shortener_enabled is not None and admin_setting.token_shortener_enabled != parsed_token_shortener_enabled:
|
| 748 |
+
admin_setting.token_shortener_enabled = parsed_token_shortener_enabled
|
| 749 |
+
updated = True
|
| 750 |
+
|
| 751 |
+
if env_token_timeout is not None:
|
| 752 |
+
parsed_token_timeout = parse_time(env_token_timeout)
|
| 753 |
+
if parsed_token_timeout is not None and admin_setting.token_timeout != parsed_token_timeout:
|
| 754 |
+
admin_setting.token_timeout = parsed_token_timeout
|
| 755 |
+
updated = True
|
| 756 |
+
|
| 757 |
+
if env_log_channel is not None:
|
| 758 |
+
parsed_log_channel = parse_int(env_log_channel)
|
| 759 |
+
if parsed_log_channel is not None and admin_setting.log_channel != parsed_log_channel:
|
| 760 |
+
admin_setting.log_channel = parsed_log_channel
|
| 761 |
+
updated = True
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
|
| 765 |
+
# Enforce mutual exclusion
|
| 766 |
+
if admin_setting.token_shortener_enabled and admin_setting.shortener_status:
|
| 767 |
+
admin_setting.shortener_status = False
|
| 768 |
+
updated = True
|
| 769 |
+
|
| 770 |
+
if updated:
|
| 771 |
+
session.commit()
|
| 772 |
+
LOGGER.info("Healed/restored AdminSettings from env values.")
|
| 773 |
+
|
| 774 |
+
# Prime the cache on boot
|
| 775 |
+
_update_cache_from_db(admin_setting)
|
| 776 |
+
except Exception as e:
|
| 777 |
+
LOGGER.warning("Could not heal admin settings: %s", str(e))
|
| 778 |
+
finally:
|
| 779 |
+
SESSION.close()
|
| 780 |
+
|
| 781 |
+
heal_admin_settings()
|
| 782 |
+
|
| 783 |
+
INSERTION_LOCK = threading.RLock()
|
| 784 |
+
|
| 785 |
+
@db_retry
|
| 786 |
+
async def get_search_settings(user_id):
|
| 787 |
+
for attempt in range(3):
|
| 788 |
+
try:
|
| 789 |
+
with INSERTION_LOCK:
|
| 790 |
+
settings = SESSION.query(Settings).filter_by(user_id=user_id).first()
|
| 791 |
+
return settings
|
| 792 |
+
except (OperationalError, PendingRollbackError) as e:
|
| 793 |
+
LOGGER.warning("Database connection error in get_search_settings (attempt %d): %s. Reconnecting...", attempt + 1, str(e))
|
| 794 |
+
try:
|
| 795 |
+
SESSION.rollback()
|
| 796 |
+
except Exception:
|
| 797 |
+
pass
|
| 798 |
+
try:
|
| 799 |
+
SESSION.remove()
|
| 800 |
+
except Exception:
|
| 801 |
+
pass
|
| 802 |
+
if attempt == 2:
|
| 803 |
+
return None
|
| 804 |
+
await asyncio.sleep(0.5)
|
| 805 |
+
except Exception as e:
|
| 806 |
+
LOGGER.warning("Error getting search settings: %s", str(e))
|
| 807 |
+
try:
|
| 808 |
+
SESSION.rollback()
|
| 809 |
+
except Exception:
|
| 810 |
+
pass
|
| 811 |
+
try:
|
| 812 |
+
SESSION.remove()
|
| 813 |
+
except Exception:
|
| 814 |
+
pass
|
| 815 |
+
return None
|
| 816 |
+
finally:
|
| 817 |
+
SESSION.close()
|
| 818 |
+
|
| 819 |
+
@db_retry
|
| 820 |
+
async def change_search_settings(user_id, precise_mode=None, button_mode=None, link_mode=None, list_mode=None):
|
| 821 |
+
try:
|
| 822 |
+
with INSERTION_LOCK:
|
| 823 |
+
settings = SESSION.query(Settings).filter_by(user_id=user_id).first()
|
| 824 |
+
if settings:
|
| 825 |
+
if precise_mode is not None:
|
| 826 |
+
settings.precise_mode = precise_mode
|
| 827 |
+
if button_mode is not None:
|
| 828 |
+
settings.button_mode = button_mode
|
| 829 |
+
if link_mode is not None:
|
| 830 |
+
settings.link_mode = link_mode
|
| 831 |
+
if list_mode is not None:
|
| 832 |
+
settings.list_mode = list_mode
|
| 833 |
+
else:
|
| 834 |
+
new_settings = Settings(
|
| 835 |
+
user_id=user_id,
|
| 836 |
+
precise_mode=precise_mode if precise_mode is not None else False,
|
| 837 |
+
button_mode=button_mode if button_mode is not None else False,
|
| 838 |
+
link_mode=link_mode if link_mode is not None else True,
|
| 839 |
+
list_mode=list_mode if list_mode is not None else False
|
| 840 |
+
)
|
| 841 |
+
SESSION.add(new_settings)
|
| 842 |
+
SESSION.commit()
|
| 843 |
+
return True
|
| 844 |
+
except Exception as e:
|
| 845 |
+
LOGGER.warning("Error changing search settings: %s", str(e))
|
| 846 |
+
try:
|
| 847 |
+
SESSION.rollback()
|
| 848 |
+
except Exception:
|
| 849 |
+
pass
|
| 850 |
+
try:
|
| 851 |
+
SESSION.remove()
|
| 852 |
+
except Exception:
|
| 853 |
+
pass
|
| 854 |
+
return False
|
| 855 |
+
finally:
|
| 856 |
+
SESSION.close()
|
| 857 |
+
|
| 858 |
+
@db_retry
|
| 859 |
+
async def set_repair_mode(repair_mode):
|
| 860 |
+
try:
|
| 861 |
+
with INSERTION_LOCK:
|
| 862 |
+
session = SESSION()
|
| 863 |
+
admin_setting = session.query(AdminSettings).first()
|
| 864 |
+
if not admin_setting:
|
| 865 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 866 |
+
session.add(admin_setting)
|
| 867 |
+
session.commit()
|
| 868 |
+
|
| 869 |
+
admin_setting.repair_mode = repair_mode
|
| 870 |
+
session.commit()
|
| 871 |
+
_update_cache_from_db(admin_setting)
|
| 872 |
+
except Exception as e:
|
| 873 |
+
LOGGER.warning("Error setting repair mode: %s", str(e))
|
| 874 |
+
SESSION.rollback()
|
| 875 |
+
finally:
|
| 876 |
+
SESSION.close()
|
| 877 |
+
|
| 878 |
+
@db_retry
|
| 879 |
+
async def set_auto_delete(dur):
|
| 880 |
+
try:
|
| 881 |
+
with INSERTION_LOCK:
|
| 882 |
+
session = SESSION()
|
| 883 |
+
admin_setting = session.query(AdminSettings).first()
|
| 884 |
+
if not admin_setting:
|
| 885 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 886 |
+
session.add(admin_setting)
|
| 887 |
+
session.commit()
|
| 888 |
+
|
| 889 |
+
admin_setting.auto_delete = dur
|
| 890 |
+
session.commit()
|
| 891 |
+
_update_cache_from_db(admin_setting)
|
| 892 |
+
except Exception as e:
|
| 893 |
+
LOGGER.warning("Error setting auto delete: %s", str(e))
|
| 894 |
+
SESSION.rollback()
|
| 895 |
+
finally:
|
| 896 |
+
SESSION.close()
|
| 897 |
+
|
| 898 |
+
@db_retry
|
| 899 |
+
async def get_admin_settings():
|
| 900 |
+
return get_admin_settings_sync()
|
| 901 |
+
|
| 902 |
+
@db_retry
|
| 903 |
+
async def set_custom_caption(caption):
|
| 904 |
+
try:
|
| 905 |
+
with INSERTION_LOCK:
|
| 906 |
+
session = SESSION()
|
| 907 |
+
admin_setting = session.query(AdminSettings).first()
|
| 908 |
+
if not admin_setting:
|
| 909 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 910 |
+
session.add(admin_setting)
|
| 911 |
+
session.commit()
|
| 912 |
+
|
| 913 |
+
admin_setting.custom_caption = caption
|
| 914 |
+
session.commit()
|
| 915 |
+
_update_cache_from_db(admin_setting)
|
| 916 |
+
except Exception as e:
|
| 917 |
+
LOGGER.warning("Error setting custom caption: %s", str(e))
|
| 918 |
+
SESSION.rollback()
|
| 919 |
+
finally:
|
| 920 |
+
SESSION.close()
|
| 921 |
+
|
| 922 |
+
@db_retry
|
| 923 |
+
async def set_force_sub(channel, access_hash=None):
|
| 924 |
+
try:
|
| 925 |
+
with INSERTION_LOCK:
|
| 926 |
+
session = SESSION()
|
| 927 |
+
admin_setting = session.query(AdminSettings).first()
|
| 928 |
+
if not admin_setting:
|
| 929 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 930 |
+
session.add(admin_setting)
|
| 931 |
+
session.commit()
|
| 932 |
+
|
| 933 |
+
admin_setting.fsub_channel = channel
|
| 934 |
+
if access_hash is not None:
|
| 935 |
+
admin_setting.fsub_channel_access_hash = access_hash
|
| 936 |
+
|
| 937 |
+
# Keep fsub_channels_list in sync for backwards compatibility
|
| 938 |
+
if channel:
|
| 939 |
+
admin_setting.fsub_channels_list = str(channel)
|
| 940 |
+
if access_hash is not None:
|
| 941 |
+
import json
|
| 942 |
+
admin_setting.fsub_channels_access_hashes = json.dumps({str(channel): access_hash})
|
| 943 |
+
else:
|
| 944 |
+
admin_setting.fsub_channels_list = None
|
| 945 |
+
admin_setting.fsub_channels_access_hashes = "{}"
|
| 946 |
+
|
| 947 |
+
session.commit()
|
| 948 |
+
_update_cache_from_db(admin_setting)
|
| 949 |
+
except Exception as e:
|
| 950 |
+
LOGGER.warning("Error setting Force Sub channel: %s", str(e))
|
| 951 |
+
SESSION.rollback()
|
| 952 |
+
finally:
|
| 953 |
+
SESSION.close()
|
| 954 |
+
|
| 955 |
+
@db_retry
|
| 956 |
+
async def set_force_sub_channels(channels_list, hashes_map):
|
| 957 |
+
try:
|
| 958 |
+
with INSERTION_LOCK:
|
| 959 |
+
session = SESSION()
|
| 960 |
+
admin_setting = session.query(AdminSettings).first()
|
| 961 |
+
if not admin_setting:
|
| 962 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 963 |
+
session.add(admin_setting)
|
| 964 |
+
session.commit()
|
| 965 |
+
|
| 966 |
+
admin_setting.fsub_channels_list = channels_list
|
| 967 |
+
import json
|
| 968 |
+
admin_setting.fsub_channels_access_hashes = json.dumps(hashes_map)
|
| 969 |
+
|
| 970 |
+
# Sync first channel to fsub_channel legacy columns for safety
|
| 971 |
+
if channels_list:
|
| 972 |
+
first_ch = channels_list.split(',')[0].strip()
|
| 973 |
+
try:
|
| 974 |
+
admin_setting.fsub_channel = int(first_ch)
|
| 975 |
+
except ValueError:
|
| 976 |
+
admin_setting.fsub_channel = None
|
| 977 |
+
admin_setting.fsub_channel_access_hash = hashes_map.get(first_ch)
|
| 978 |
+
else:
|
| 979 |
+
admin_setting.fsub_channel = None
|
| 980 |
+
admin_setting.fsub_channel_access_hash = None
|
| 981 |
+
|
| 982 |
+
session.commit()
|
| 983 |
+
_update_cache_from_db(admin_setting)
|
| 984 |
+
except Exception as e:
|
| 985 |
+
LOGGER.warning("Error setting Force Sub channels list: %s", str(e))
|
| 986 |
+
SESSION.rollback()
|
| 987 |
+
finally:
|
| 988 |
+
SESSION.close()
|
| 989 |
+
|
| 990 |
+
@db_retry
|
| 991 |
+
async def save_pending_fsub_request(user_id, search_query=None, target_file_id=None):
|
| 992 |
+
import time
|
| 993 |
+
try:
|
| 994 |
+
with INSERTION_LOCK:
|
| 995 |
+
session = SESSION()
|
| 996 |
+
req = session.query(PendingFsubRequests).filter(PendingFsubRequests.user_id == user_id).first()
|
| 997 |
+
if req:
|
| 998 |
+
req.search_query = search_query
|
| 999 |
+
req.target_file_id = target_file_id
|
| 1000 |
+
req.created_at = time.time()
|
| 1001 |
+
else:
|
| 1002 |
+
req = PendingFsubRequests(user_id=user_id, search_query=search_query, target_file_id=target_file_id)
|
| 1003 |
+
req.created_at = time.time()
|
| 1004 |
+
session.add(req)
|
| 1005 |
+
session.commit()
|
| 1006 |
+
except Exception as e:
|
| 1007 |
+
LOGGER.warning("Error saving pending fsub request: %s", str(e))
|
| 1008 |
+
SESSION.rollback()
|
| 1009 |
+
finally:
|
| 1010 |
+
SESSION.close()
|
| 1011 |
+
|
| 1012 |
+
@db_retry
|
| 1013 |
+
async def get_pending_fsub_request(user_id):
|
| 1014 |
+
for attempt in range(3):
|
| 1015 |
+
try:
|
| 1016 |
+
session = SESSION()
|
| 1017 |
+
req = session.query(PendingFsubRequests).filter(PendingFsubRequests.user_id == user_id).first()
|
| 1018 |
+
return req
|
| 1019 |
+
except (OperationalError, PendingRollbackError) as e:
|
| 1020 |
+
LOGGER.warning("Database connection error in get_pending_fsub_request (attempt %d): %s. Reconnecting...", attempt + 1, str(e))
|
| 1021 |
+
try:
|
| 1022 |
+
SESSION.rollback()
|
| 1023 |
+
except Exception:
|
| 1024 |
+
pass
|
| 1025 |
+
try:
|
| 1026 |
+
SESSION.remove()
|
| 1027 |
+
except Exception:
|
| 1028 |
+
pass
|
| 1029 |
+
if attempt == 2:
|
| 1030 |
+
return None
|
| 1031 |
+
await asyncio.sleep(0.5)
|
| 1032 |
+
except Exception as e:
|
| 1033 |
+
LOGGER.warning("Error getting pending fsub request: %s", str(e))
|
| 1034 |
+
try:
|
| 1035 |
+
SESSION.rollback()
|
| 1036 |
+
except Exception:
|
| 1037 |
+
pass
|
| 1038 |
+
try:
|
| 1039 |
+
SESSION.remove()
|
| 1040 |
+
except Exception:
|
| 1041 |
+
pass
|
| 1042 |
+
return None
|
| 1043 |
+
finally:
|
| 1044 |
+
session.close()
|
| 1045 |
+
|
| 1046 |
+
@db_retry
|
| 1047 |
+
async def delete_pending_fsub_request(user_id):
|
| 1048 |
+
try:
|
| 1049 |
+
with INSERTION_LOCK:
|
| 1050 |
+
session = SESSION()
|
| 1051 |
+
session.query(PendingFsubRequests).filter(PendingFsubRequests.user_id == user_id).delete()
|
| 1052 |
+
session.commit()
|
| 1053 |
+
except Exception as e:
|
| 1054 |
+
LOGGER.warning("Error deleting pending fsub request: %s", str(e))
|
| 1055 |
+
SESSION.rollback()
|
| 1056 |
+
finally:
|
| 1057 |
+
SESSION.close()
|
| 1058 |
+
|
| 1059 |
+
@db_retry
|
| 1060 |
+
async def set_channel_link(link):
|
| 1061 |
+
try:
|
| 1062 |
+
with INSERTION_LOCK:
|
| 1063 |
+
session = SESSION()
|
| 1064 |
+
admin_setting = session.query(AdminSettings).first()
|
| 1065 |
+
if not admin_setting:
|
| 1066 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 1067 |
+
session.add(admin_setting)
|
| 1068 |
+
session.commit()
|
| 1069 |
+
|
| 1070 |
+
admin_setting.channel_link = link
|
| 1071 |
+
session.commit()
|
| 1072 |
+
_update_cache_from_db(admin_setting)
|
| 1073 |
+
except Exception as e:
|
| 1074 |
+
LOGGER.warning("Error adding Force Sub channel link: %s", str(e))
|
| 1075 |
+
SESSION.rollback()
|
| 1076 |
+
finally:
|
| 1077 |
+
SESSION.close()
|
| 1078 |
+
|
| 1079 |
+
@db_retry
|
| 1080 |
+
async def get_channel():
|
| 1081 |
+
settings = get_admin_settings_sync()
|
| 1082 |
+
return settings.fsub_channel if settings.fsub_channel else False
|
| 1083 |
+
|
| 1084 |
+
@db_retry
|
| 1085 |
+
async def get_link():
|
| 1086 |
+
settings = get_admin_settings_sync()
|
| 1087 |
+
return settings.channel_link if settings.channel_link else False
|
| 1088 |
+
|
| 1089 |
+
@db_retry
|
| 1090 |
+
async def set_username(username):
|
| 1091 |
+
try:
|
| 1092 |
+
with INSERTION_LOCK:
|
| 1093 |
+
session = SESSION()
|
| 1094 |
+
admin_setting = session.query(AdminSettings).first()
|
| 1095 |
+
if not admin_setting:
|
| 1096 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 1097 |
+
session.add(admin_setting)
|
| 1098 |
+
session.commit()
|
| 1099 |
+
|
| 1100 |
+
admin_setting.caption_uname = username
|
| 1101 |
+
session.commit()
|
| 1102 |
+
_update_cache_from_db(admin_setting)
|
| 1103 |
+
except Exception as e:
|
| 1104 |
+
LOGGER.warning("Error adding username: %s", str(e))
|
| 1105 |
+
SESSION.rollback()
|
| 1106 |
+
finally:
|
| 1107 |
+
SESSION.close()
|
| 1108 |
+
|
| 1109 |
+
@db_retry
|
| 1110 |
+
async def set_shortener_settings(site=None, api=None, status=None):
|
| 1111 |
+
try:
|
| 1112 |
+
with INSERTION_LOCK:
|
| 1113 |
+
session = SESSION()
|
| 1114 |
+
admin_setting = session.query(AdminSettings).first()
|
| 1115 |
+
if not admin_setting:
|
| 1116 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 1117 |
+
session.add(admin_setting)
|
| 1118 |
+
session.commit()
|
| 1119 |
+
|
| 1120 |
+
import json
|
| 1121 |
+
try:
|
| 1122 |
+
shorteners = json.loads(admin_setting.shorteners_list) if admin_setting.shorteners_list else []
|
| 1123 |
+
except Exception:
|
| 1124 |
+
shorteners = []
|
| 1125 |
+
|
| 1126 |
+
if site is not None or api is not None:
|
| 1127 |
+
if shorteners:
|
| 1128 |
+
if site is not None:
|
| 1129 |
+
shorteners[0]["site"] = site
|
| 1130 |
+
if api is not None:
|
| 1131 |
+
shorteners[0]["api"] = api
|
| 1132 |
+
else:
|
| 1133 |
+
shorteners.append({
|
| 1134 |
+
"site": site or "",
|
| 1135 |
+
"api": api or "",
|
| 1136 |
+
"how_to_download": None,
|
| 1137 |
+
"status": True
|
| 1138 |
+
})
|
| 1139 |
+
admin_setting.shorteners_list = json.dumps(shorteners)
|
| 1140 |
+
|
| 1141 |
+
if status is not None:
|
| 1142 |
+
admin_setting.shortener_status = status
|
| 1143 |
+
if status:
|
| 1144 |
+
admin_setting.token_shortener_enabled = False
|
| 1145 |
+
session.commit()
|
| 1146 |
+
_update_cache_from_db(admin_setting)
|
| 1147 |
+
except Exception as e:
|
| 1148 |
+
LOGGER.warning("Error setting shortener settings: %s", str(e))
|
| 1149 |
+
SESSION.rollback()
|
| 1150 |
+
finally:
|
| 1151 |
+
SESSION.close()
|
| 1152 |
+
|
| 1153 |
+
@db_retry
|
| 1154 |
+
async def delete_shortener_settings():
|
| 1155 |
+
try:
|
| 1156 |
+
with INSERTION_LOCK:
|
| 1157 |
+
session = SESSION()
|
| 1158 |
+
admin_setting = session.query(AdminSettings).first()
|
| 1159 |
+
if admin_setting:
|
| 1160 |
+
import json
|
| 1161 |
+
try:
|
| 1162 |
+
shorteners = json.loads(admin_setting.shorteners_list) if admin_setting.shorteners_list else []
|
| 1163 |
+
except Exception:
|
| 1164 |
+
shorteners = []
|
| 1165 |
+
if shorteners:
|
| 1166 |
+
shorteners.pop(0)
|
| 1167 |
+
admin_setting.shorteners_list = json.dumps(shorteners)
|
| 1168 |
+
admin_setting.shortener_status = False
|
| 1169 |
+
session.commit()
|
| 1170 |
+
_update_cache_from_db(admin_setting)
|
| 1171 |
+
except Exception as e:
|
| 1172 |
+
LOGGER.warning("Error deleting shortener settings: %s", str(e))
|
| 1173 |
+
SESSION.rollback()
|
| 1174 |
+
finally:
|
| 1175 |
+
SESSION.close()
|
| 1176 |
+
|
| 1177 |
+
@db_retry
|
| 1178 |
+
async def update_admins_list(admins_str):
|
| 1179 |
+
try:
|
| 1180 |
+
with INSERTION_LOCK:
|
| 1181 |
+
session = SESSION()
|
| 1182 |
+
admin_setting = session.query(AdminSettings).first()
|
| 1183 |
+
if not admin_setting:
|
| 1184 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 1185 |
+
session.add(admin_setting)
|
| 1186 |
+
session.commit()
|
| 1187 |
+
|
| 1188 |
+
admin_setting.admins_list = admins_str
|
| 1189 |
+
session.commit()
|
| 1190 |
+
_update_cache_from_db(admin_setting)
|
| 1191 |
+
except Exception as e:
|
| 1192 |
+
LOGGER.warning("Error updating admins list: %s", str(e))
|
| 1193 |
+
SESSION.rollback()
|
| 1194 |
+
finally:
|
| 1195 |
+
SESSION.close()
|
| 1196 |
+
|
| 1197 |
+
@db_retry
|
| 1198 |
+
async def update_db_channels_list(channels_str):
|
| 1199 |
+
try:
|
| 1200 |
+
with INSERTION_LOCK:
|
| 1201 |
+
session = SESSION()
|
| 1202 |
+
admin_setting = session.query(AdminSettings).first()
|
| 1203 |
+
if not admin_setting:
|
| 1204 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 1205 |
+
session.add(admin_setting)
|
| 1206 |
+
session.commit()
|
| 1207 |
+
|
| 1208 |
+
admin_setting.db_channels_list = channels_str
|
| 1209 |
+
session.commit()
|
| 1210 |
+
_update_cache_from_db(admin_setting)
|
| 1211 |
+
except Exception as e:
|
| 1212 |
+
LOGGER.warning("Error updating db channels list: %s", str(e))
|
| 1213 |
+
SESSION.rollback()
|
| 1214 |
+
finally:
|
| 1215 |
+
SESSION.close()
|
| 1216 |
+
|
| 1217 |
+
@db_retry
|
| 1218 |
+
async def get_user_token(user_id):
|
| 1219 |
+
for attempt in range(3):
|
| 1220 |
+
try:
|
| 1221 |
+
with INSERTION_LOCK:
|
| 1222 |
+
session = SESSION()
|
| 1223 |
+
return session.query(UserTokens).filter_by(user_id=user_id).first()
|
| 1224 |
+
except (OperationalError, PendingRollbackError) as e:
|
| 1225 |
+
LOGGER.warning("Database connection error in get_user_token (attempt %d): %s. Reconnecting...", attempt + 1, str(e))
|
| 1226 |
+
try:
|
| 1227 |
+
SESSION.rollback()
|
| 1228 |
+
except Exception:
|
| 1229 |
+
pass
|
| 1230 |
+
try:
|
| 1231 |
+
SESSION.remove()
|
| 1232 |
+
except Exception:
|
| 1233 |
+
pass
|
| 1234 |
+
if attempt == 2:
|
| 1235 |
+
return None
|
| 1236 |
+
await asyncio.sleep(0.5)
|
| 1237 |
+
except Exception as e:
|
| 1238 |
+
LOGGER.warning("Error getting user token: %s", str(e))
|
| 1239 |
+
try:
|
| 1240 |
+
SESSION.rollback()
|
| 1241 |
+
except Exception:
|
| 1242 |
+
pass
|
| 1243 |
+
try:
|
| 1244 |
+
SESSION.remove()
|
| 1245 |
+
except Exception:
|
| 1246 |
+
pass
|
| 1247 |
+
return None
|
| 1248 |
+
finally:
|
| 1249 |
+
SESSION.close()
|
| 1250 |
+
|
| 1251 |
+
@db_retry
|
| 1252 |
+
async def create_user_token(user_id, token, search_query=None, target_file_id=None):
|
| 1253 |
+
import time
|
| 1254 |
+
try:
|
| 1255 |
+
await prune_all_expired_tokens()
|
| 1256 |
+
with INSERTION_LOCK:
|
| 1257 |
+
session = SESSION()
|
| 1258 |
+
tok_rec = session.query(UserTokens).filter_by(user_id=user_id).first()
|
| 1259 |
+
if tok_rec:
|
| 1260 |
+
tok_rec.token = token
|
| 1261 |
+
tok_rec.created_at = time.time()
|
| 1262 |
+
tok_rec.expires_at = 0
|
| 1263 |
+
tok_rec.status = "pending"
|
| 1264 |
+
tok_rec.search_query = search_query
|
| 1265 |
+
tok_rec.target_file_id = target_file_id
|
| 1266 |
+
else:
|
| 1267 |
+
tok_rec = UserTokens(
|
| 1268 |
+
user_id=user_id,
|
| 1269 |
+
token=token,
|
| 1270 |
+
created_at=time.time(),
|
| 1271 |
+
search_query=search_query,
|
| 1272 |
+
target_file_id=target_file_id
|
| 1273 |
+
)
|
| 1274 |
+
session.add(tok_rec)
|
| 1275 |
+
session.commit()
|
| 1276 |
+
return tok_rec
|
| 1277 |
+
except Exception as e:
|
| 1278 |
+
LOGGER.warning("Error creating user token: %s", str(e))
|
| 1279 |
+
SESSION.rollback()
|
| 1280 |
+
return None
|
| 1281 |
+
finally:
|
| 1282 |
+
SESSION.close()
|
| 1283 |
+
|
| 1284 |
+
@db_retry
|
| 1285 |
+
async def activate_user_token(user_id, expires_at):
|
| 1286 |
+
try:
|
| 1287 |
+
with INSERTION_LOCK:
|
| 1288 |
+
session = SESSION()
|
| 1289 |
+
tok_rec = session.query(UserTokens).filter_by(user_id=user_id).first()
|
| 1290 |
+
if tok_rec:
|
| 1291 |
+
tok_rec.status = "active"
|
| 1292 |
+
tok_rec.expires_at = expires_at
|
| 1293 |
+
session.commit()
|
| 1294 |
+
return True
|
| 1295 |
+
return False
|
| 1296 |
+
except Exception as e:
|
| 1297 |
+
LOGGER.warning("Error activating user token: %s", str(e))
|
| 1298 |
+
SESSION.rollback()
|
| 1299 |
+
return False
|
| 1300 |
+
finally:
|
| 1301 |
+
SESSION.close()
|
| 1302 |
+
|
| 1303 |
+
@db_retry
|
| 1304 |
+
async def delete_user_token(user_id):
|
| 1305 |
+
try:
|
| 1306 |
+
with INSERTION_LOCK:
|
| 1307 |
+
session = SESSION()
|
| 1308 |
+
tok_rec = session.query(UserTokens).filter_by(user_id=user_id).first()
|
| 1309 |
+
if tok_rec:
|
| 1310 |
+
session.delete(tok_rec)
|
| 1311 |
+
session.commit()
|
| 1312 |
+
return True
|
| 1313 |
+
return False
|
| 1314 |
+
except Exception as e:
|
| 1315 |
+
LOGGER.warning("Error deleting user token: %s", str(e))
|
| 1316 |
+
SESSION.rollback()
|
| 1317 |
+
return False
|
| 1318 |
+
finally:
|
| 1319 |
+
SESSION.close()
|
| 1320 |
+
|
| 1321 |
+
@db_retry
|
| 1322 |
+
async def prune_all_expired_tokens():
|
| 1323 |
+
import time
|
| 1324 |
+
try:
|
| 1325 |
+
with INSERTION_LOCK:
|
| 1326 |
+
session = SESSION()
|
| 1327 |
+
current_time = time.time()
|
| 1328 |
+
|
| 1329 |
+
# Delete active tokens that have expired
|
| 1330 |
+
expired_active = session.query(UserTokens).filter(
|
| 1331 |
+
UserTokens.status == "active",
|
| 1332 |
+
UserTokens.expires_at < current_time
|
| 1333 |
+
)
|
| 1334 |
+
|
| 1335 |
+
# Delete pending tokens that are older than 30 minutes (1800 seconds)
|
| 1336 |
+
stale_pending = session.query(UserTokens).filter(
|
| 1337 |
+
UserTokens.status == "pending",
|
| 1338 |
+
(current_time - UserTokens.created_at) > 1800
|
| 1339 |
+
)
|
| 1340 |
+
|
| 1341 |
+
deleted_active = expired_active.delete(synchronize_session=False)
|
| 1342 |
+
deleted_pending = stale_pending.delete(synchronize_session=False)
|
| 1343 |
+
|
| 1344 |
+
if deleted_active or deleted_pending:
|
| 1345 |
+
session.commit()
|
| 1346 |
+
LOGGER.info("Database row protection: Pruned %d expired active and %d stale pending tokens.", deleted_active, deleted_pending)
|
| 1347 |
+
return True
|
| 1348 |
+
except Exception as e:
|
| 1349 |
+
LOGGER.warning("Error pruning expired tokens from database: %s", str(e))
|
| 1350 |
+
SESSION.rollback()
|
| 1351 |
+
return False
|
| 1352 |
+
finally:
|
| 1353 |
+
SESSION.close()
|
| 1354 |
+
|
| 1355 |
+
@db_retry
|
| 1356 |
+
async def set_token_shortener_state(enabled):
|
| 1357 |
+
try:
|
| 1358 |
+
with INSERTION_LOCK:
|
| 1359 |
+
session = SESSION()
|
| 1360 |
+
admin_setting = session.query(AdminSettings).first()
|
| 1361 |
+
if not admin_setting:
|
| 1362 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 1363 |
+
session.add(admin_setting)
|
| 1364 |
+
admin_setting.token_shortener_enabled = enabled
|
| 1365 |
+
if enabled:
|
| 1366 |
+
admin_setting.shortener_status = False
|
| 1367 |
+
session.commit()
|
| 1368 |
+
_update_cache_from_db(admin_setting)
|
| 1369 |
+
return True
|
| 1370 |
+
except Exception as e:
|
| 1371 |
+
LOGGER.warning("Error setting token shortener state: %s", str(e))
|
| 1372 |
+
SESSION.rollback()
|
| 1373 |
+
return False
|
| 1374 |
+
finally:
|
| 1375 |
+
SESSION.close()
|
| 1376 |
+
|
| 1377 |
+
@db_retry
|
| 1378 |
+
async def set_token_timeout(seconds):
|
| 1379 |
+
try:
|
| 1380 |
+
with INSERTION_LOCK:
|
| 1381 |
+
session = SESSION()
|
| 1382 |
+
admin_setting = session.query(AdminSettings).first()
|
| 1383 |
+
if not admin_setting:
|
| 1384 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 1385 |
+
session.add(admin_setting)
|
| 1386 |
+
admin_setting.token_timeout = seconds
|
| 1387 |
+
session.commit()
|
| 1388 |
+
_update_cache_from_db(admin_setting)
|
| 1389 |
+
return True
|
| 1390 |
+
except Exception as e:
|
| 1391 |
+
LOGGER.warning("Error setting token timeout: %s", str(e))
|
| 1392 |
+
SESSION.rollback()
|
| 1393 |
+
return False
|
| 1394 |
+
finally:
|
| 1395 |
+
SESSION.close()
|
| 1396 |
+
|
| 1397 |
+
@db_retry
|
| 1398 |
+
async def set_log_channel(channel, access_hash=None):
|
| 1399 |
+
try:
|
| 1400 |
+
with INSERTION_LOCK:
|
| 1401 |
+
session = SESSION()
|
| 1402 |
+
admin_setting = session.query(AdminSettings).first()
|
| 1403 |
+
if not admin_setting:
|
| 1404 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 1405 |
+
session.add(admin_setting)
|
| 1406 |
+
admin_setting.log_channel = channel
|
| 1407 |
+
if access_hash is not None:
|
| 1408 |
+
admin_setting.log_channel_access_hash = access_hash
|
| 1409 |
+
session.commit()
|
| 1410 |
+
_update_cache_from_db(admin_setting)
|
| 1411 |
+
return True
|
| 1412 |
+
except Exception as e:
|
| 1413 |
+
LOGGER.warning("Error setting log channel: %s", str(e))
|
| 1414 |
+
SESSION.rollback()
|
| 1415 |
+
return False
|
| 1416 |
+
finally:
|
| 1417 |
+
SESSION.close()
|
| 1418 |
+
|
| 1419 |
+
@db_retry
|
| 1420 |
+
async def get_log_channel():
|
| 1421 |
+
settings = get_admin_settings_sync()
|
| 1422 |
+
return settings.log_channel if settings.log_channel else False
|
| 1423 |
+
|
| 1424 |
+
@db_retry
|
| 1425 |
+
async def set_how_to_download(url):
|
| 1426 |
+
try:
|
| 1427 |
+
with INSERTION_LOCK:
|
| 1428 |
+
session = SESSION()
|
| 1429 |
+
admin_setting = session.query(AdminSettings).first()
|
| 1430 |
+
if not admin_setting:
|
| 1431 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 1432 |
+
session.add(admin_setting)
|
| 1433 |
+
admin_setting.how_to_download = url
|
| 1434 |
+
session.commit()
|
| 1435 |
+
_update_cache_from_db(admin_setting)
|
| 1436 |
+
return True
|
| 1437 |
+
except Exception as e:
|
| 1438 |
+
LOGGER.warning("Error setting how to download URL: %s", str(e))
|
| 1439 |
+
SESSION.rollback()
|
| 1440 |
+
return False
|
| 1441 |
+
finally:
|
| 1442 |
+
SESSION.close()
|
| 1443 |
+
|
| 1444 |
+
@db_retry
|
| 1445 |
+
async def update_user_token_msg_id(user_id, msg_id):
|
| 1446 |
+
try:
|
| 1447 |
+
with INSERTION_LOCK:
|
| 1448 |
+
session = SESSION()
|
| 1449 |
+
tok_rec = session.query(UserTokens).filter_by(user_id=user_id).first()
|
| 1450 |
+
if tok_rec:
|
| 1451 |
+
tok_rec.req_msg_id = msg_id
|
| 1452 |
+
session.commit()
|
| 1453 |
+
return True
|
| 1454 |
+
return False
|
| 1455 |
+
except Exception as e:
|
| 1456 |
+
LOGGER.warning("Error updating user token message ID: %s", str(e))
|
| 1457 |
+
SESSION.rollback()
|
| 1458 |
+
return False
|
| 1459 |
+
finally:
|
| 1460 |
+
SESSION.close()
|
| 1461 |
+
|
| 1462 |
+
@db_retry
|
| 1463 |
+
async def set_smart_rotator_state(state: bool):
|
| 1464 |
+
try:
|
| 1465 |
+
with INSERTION_LOCK:
|
| 1466 |
+
session = SESSION()
|
| 1467 |
+
admin_setting = session.query(AdminSettings).first()
|
| 1468 |
+
if not admin_setting:
|
| 1469 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 1470 |
+
session.add(admin_setting)
|
| 1471 |
+
session.commit()
|
| 1472 |
+
|
| 1473 |
+
admin_setting.smart_rotator = state
|
| 1474 |
+
session.commit()
|
| 1475 |
+
_update_cache_from_db(admin_setting)
|
| 1476 |
+
except Exception as e:
|
| 1477 |
+
LOGGER.warning("Error setting smart rotator state: %s", str(e))
|
| 1478 |
+
SESSION.rollback()
|
| 1479 |
+
finally:
|
| 1480 |
+
SESSION.close()
|
| 1481 |
+
|
| 1482 |
+
@db_retry
|
| 1483 |
+
async def update_shorteners_list(shorteners_json_str):
|
| 1484 |
+
try:
|
| 1485 |
+
with INSERTION_LOCK:
|
| 1486 |
+
session = SESSION()
|
| 1487 |
+
admin_setting = session.query(AdminSettings).first()
|
| 1488 |
+
if not admin_setting:
|
| 1489 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 1490 |
+
session.add(admin_setting)
|
| 1491 |
+
session.commit()
|
| 1492 |
+
|
| 1493 |
+
admin_setting.shorteners_list = shorteners_json_str
|
| 1494 |
+
session.commit()
|
| 1495 |
+
_update_cache_from_db(admin_setting)
|
| 1496 |
+
except Exception as e:
|
| 1497 |
+
LOGGER.warning("Error updating shorteners list: %s", str(e))
|
| 1498 |
+
SESSION.rollback()
|
| 1499 |
+
finally:
|
| 1500 |
+
SESSION.close()
|
| 1501 |
+
|
| 1502 |
+
@db_retry
|
| 1503 |
+
async def get_user_shortener_index(user_id: int, today_str: str) -> int:
|
| 1504 |
+
for attempt in range(3):
|
| 1505 |
+
try:
|
| 1506 |
+
session = SESSION()
|
| 1507 |
+
record = session.query(UserShortenerUsage).filter_by(user_id=user_id).first()
|
| 1508 |
+
if record and record.last_date == today_str:
|
| 1509 |
+
return record.last_index or 0
|
| 1510 |
+
return 0
|
| 1511 |
+
except (OperationalError, PendingRollbackError) as e:
|
| 1512 |
+
LOGGER.warning("Database connection error in get_user_shortener_index: %s. Reconnecting...", str(e))
|
| 1513 |
+
try:
|
| 1514 |
+
SESSION.rollback()
|
| 1515 |
+
except Exception:
|
| 1516 |
+
pass
|
| 1517 |
+
try:
|
| 1518 |
+
SESSION.remove()
|
| 1519 |
+
except Exception:
|
| 1520 |
+
pass
|
| 1521 |
+
if attempt == 2:
|
| 1522 |
+
return -1
|
| 1523 |
+
await asyncio.sleep(0.5)
|
| 1524 |
+
except Exception as e:
|
| 1525 |
+
LOGGER.warning("Error in get_user_shortener_index: %s", str(e))
|
| 1526 |
+
return -1
|
| 1527 |
+
finally:
|
| 1528 |
+
SESSION.close()
|
| 1529 |
+
|
| 1530 |
+
@db_retry
|
| 1531 |
+
async def update_user_shortener_index(user_id: int, index: int, today_str: str):
|
| 1532 |
+
try:
|
| 1533 |
+
with INSERTION_LOCK:
|
| 1534 |
+
session = SESSION()
|
| 1535 |
+
record = session.query(UserShortenerUsage).filter_by(user_id=user_id).first()
|
| 1536 |
+
if record:
|
| 1537 |
+
record.last_index = index
|
| 1538 |
+
record.last_date = today_str
|
| 1539 |
+
else:
|
| 1540 |
+
record = UserShortenerUsage(user_id=user_id, last_index=index, last_date=today_str)
|
| 1541 |
+
session.add(record)
|
| 1542 |
+
session.commit()
|
| 1543 |
+
except Exception as e:
|
| 1544 |
+
LOGGER.warning("Error in update_user_shortener_index: %s", str(e))
|
| 1545 |
+
SESSION.rollback()
|
| 1546 |
+
finally:
|
| 1547 |
+
SESSION.close()
|
| 1548 |
+
|
| 1549 |
+
@db_retry
|
| 1550 |
+
async def advance_user_shortener_index(user_id: int):
|
| 1551 |
+
try:
|
| 1552 |
+
import datetime
|
| 1553 |
+
local_now = datetime.datetime.utcnow() + datetime.timedelta(hours=5, minutes=30)
|
| 1554 |
+
today_str = local_now.strftime("%Y-%m-%d")
|
| 1555 |
+
with INSERTION_LOCK:
|
| 1556 |
+
session = SESSION()
|
| 1557 |
+
record = session.query(UserShortenerUsage).filter_by(user_id=user_id).first()
|
| 1558 |
+
if record:
|
| 1559 |
+
if record.last_date == today_str:
|
| 1560 |
+
record.last_index = (record.last_index or 0) + 1
|
| 1561 |
+
else:
|
| 1562 |
+
record.last_index = 1
|
| 1563 |
+
record.last_date = today_str
|
| 1564 |
+
else:
|
| 1565 |
+
record = UserShortenerUsage(user_id=user_id, last_index=1, last_date=today_str)
|
| 1566 |
+
session.add(record)
|
| 1567 |
+
session.commit()
|
| 1568 |
+
except Exception as e:
|
| 1569 |
+
LOGGER.warning("Error in advance_user_shortener_index: %s", str(e))
|
| 1570 |
+
SESSION.rollback()
|
| 1571 |
+
finally:
|
| 1572 |
+
SESSION.close()
|
| 1573 |
+
|
| 1574 |
+
@db_retry
|
| 1575 |
+
async def clear_all_user_shortener_usages():
|
| 1576 |
+
try:
|
| 1577 |
+
with INSERTION_LOCK:
|
| 1578 |
+
session = SESSION()
|
| 1579 |
+
session.query(UserShortenerUsage).delete()
|
| 1580 |
+
session.commit()
|
| 1581 |
+
except Exception as e:
|
| 1582 |
+
LOGGER.warning("Error clearing UserShortenerUsage: %s", str(e))
|
| 1583 |
+
SESSION.rollback()
|
| 1584 |
+
finally:
|
| 1585 |
+
SESSION.close()
|
| 1586 |
+
|
| 1587 |
+
|
| 1588 |
+
@db_retry
|
| 1589 |
+
async def set_newsletter_settings(enabled=None, days=None, time_str=None, count=None, target=None):
|
| 1590 |
+
try:
|
| 1591 |
+
with INSERTION_LOCK:
|
| 1592 |
+
session = SESSION()
|
| 1593 |
+
admin_setting = session.query(AdminSettings).first()
|
| 1594 |
+
if not admin_setting:
|
| 1595 |
+
admin_setting = AdminSettings(setting_name="default")
|
| 1596 |
+
session.add(admin_setting)
|
| 1597 |
+
session.commit()
|
| 1598 |
+
|
| 1599 |
+
if enabled is not None:
|
| 1600 |
+
admin_setting.newsletter_enabled = enabled
|
| 1601 |
+
if days is not None:
|
| 1602 |
+
admin_setting.newsletter_days = days
|
| 1603 |
+
if time_str is not None:
|
| 1604 |
+
admin_setting.newsletter_time = time_str
|
| 1605 |
+
if count is not None:
|
| 1606 |
+
admin_setting.newsletter_count = count
|
| 1607 |
+
if target is not None:
|
| 1608 |
+
admin_setting.newsletter_target = target
|
| 1609 |
+
session.commit()
|
| 1610 |
+
_update_cache_from_db(admin_setting)
|
| 1611 |
+
except Exception as e:
|
| 1612 |
+
LOGGER.warning("Error setting newsletter settings: %s", str(e))
|
| 1613 |
+
SESSION.rollback()
|
| 1614 |
+
finally:
|
| 1615 |
+
SESSION.close()
|
| 1616 |
+
|
| 1617 |
+
|
| 1618 |
+
def add_auto_delete_msg_sync(chat_id, message_id, delay):
|
| 1619 |
+
delete_at = time.time() + delay
|
| 1620 |
+
session = SQLITE_SESSION()
|
| 1621 |
+
try:
|
| 1622 |
+
msg = AutoDeleteMessage(chat_id=chat_id, message_id=message_id, delete_at=delete_at)
|
| 1623 |
+
session.add(msg)
|
| 1624 |
+
session.commit()
|
| 1625 |
+
except Exception as e:
|
| 1626 |
+
session.rollback()
|
| 1627 |
+
LOGGER.warning(f"Error in add_auto_delete_msg_sync: {e}")
|
| 1628 |
+
finally:
|
| 1629 |
+
SQLITE_SESSION.remove()
|
| 1630 |
+
|
| 1631 |
+
def remove_auto_delete_msg_sync(chat_id, message_id):
|
| 1632 |
+
session = SQLITE_SESSION()
|
| 1633 |
+
try:
|
| 1634 |
+
session.query(AutoDeleteMessage).filter_by(chat_id=chat_id, message_id=message_id).delete()
|
| 1635 |
+
session.commit()
|
| 1636 |
+
except Exception as e:
|
| 1637 |
+
session.rollback()
|
| 1638 |
+
LOGGER.warning(f"Error in remove_auto_delete_msg_sync: {e}")
|
| 1639 |
+
finally:
|
| 1640 |
+
SQLITE_SESSION.remove()
|
| 1641 |
+
|
| 1642 |
+
def get_all_auto_delete_msgs_sync():
|
| 1643 |
+
session = SQLITE_SESSION()
|
| 1644 |
+
try:
|
| 1645 |
+
all_msgs = session.query(AutoDeleteMessage).all()
|
| 1646 |
+
return [(msg.chat_id, msg.message_id, msg.delete_at) for msg in all_msgs]
|
| 1647 |
+
except Exception as e:
|
| 1648 |
+
LOGGER.warning(f"Error in get_all_auto_delete_msgs_sync: {e}")
|
| 1649 |
+
return []
|
| 1650 |
+
finally:
|
| 1651 |
+
SQLITE_SESSION.remove()
|
| 1652 |
+
|
| 1653 |
+
async def set_announcement_settings(enabled: bool = None, channel = None, access_hash = None) -> None:
|
| 1654 |
+
retries = 3
|
| 1655 |
+
while retries > 0:
|
| 1656 |
+
try:
|
| 1657 |
+
with INSERTION_LOCK:
|
| 1658 |
+
session = SESSION()
|
| 1659 |
+
settings = session.query(AdminSettings).first()
|
| 1660 |
+
if not settings:
|
| 1661 |
+
settings = AdminSettings(setting_name="default")
|
| 1662 |
+
session.add(settings)
|
| 1663 |
+
|
| 1664 |
+
if enabled is not None:
|
| 1665 |
+
settings.announcement_enabled = enabled
|
| 1666 |
+
if channel is not None:
|
| 1667 |
+
if str(channel).lower() == "off":
|
| 1668 |
+
settings.announcement_channel = None
|
| 1669 |
+
settings.announcement_channel_access_hash = None
|
| 1670 |
+
else:
|
| 1671 |
+
settings.announcement_channel = int(channel)
|
| 1672 |
+
if access_hash is not None:
|
| 1673 |
+
settings.announcement_channel_access_hash = int(access_hash)
|
| 1674 |
+
session.commit()
|
| 1675 |
+
_update_cache_from_db(settings)
|
| 1676 |
+
return True
|
| 1677 |
+
except OperationalError:
|
| 1678 |
+
reconnect_session()
|
| 1679 |
+
retries -= 1
|
| 1680 |
+
except Exception as e:
|
| 1681 |
+
LOGGER.warning(f"Error setting announcement settings: {e}")
|
| 1682 |
+
session.rollback()
|
| 1683 |
+
retries -= 1
|
| 1684 |
+
finally:
|
| 1685 |
+
try:
|
| 1686 |
+
session.close()
|
| 1687 |
+
except Exception:
|
| 1688 |
+
pass
|
| 1689 |
+
return False
|
mfinder/db/suggestion_cache.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
ADDED
|
@@ -0,0 +1,1617 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import datetime
|
| 3 |
+
|
| 4 |
+
def get_all_shorteners(admin_settings):
|
| 5 |
+
import json
|
| 6 |
+
shorteners = []
|
| 7 |
+
if hasattr(admin_settings, "shorteners_list") and admin_settings.shorteners_list:
|
| 8 |
+
try:
|
| 9 |
+
shorteners = json.loads(admin_settings.shorteners_list)
|
| 10 |
+
except Exception:
|
| 11 |
+
pass
|
| 12 |
+
if not shorteners and getattr(admin_settings, "shortener_api", None):
|
| 13 |
+
default_site = admin_settings.shortener_site or "gplinks.in"
|
| 14 |
+
default_api = admin_settings.shortener_api
|
| 15 |
+
default_how = admin_settings.how_to_download or "https://telegram.me/FIREBOLTTutorial/23"
|
| 16 |
+
default_status = getattr(admin_settings, "shortener_status", True)
|
| 17 |
+
if default_status is None: default_status = True
|
| 18 |
+
shorteners = [{
|
| 19 |
+
"site": default_site,
|
| 20 |
+
"api": default_api,
|
| 21 |
+
"how_to_download": default_how,
|
| 22 |
+
"status": default_status
|
| 23 |
+
}]
|
| 24 |
+
return shorteners
|
| 25 |
+
|
| 26 |
+
def parse_duration_to_seconds(val: str):
|
| 27 |
+
if not val:
|
| 28 |
+
return None
|
| 29 |
+
val = val.strip().lower()
|
| 30 |
+
if val == "off":
|
| 31 |
+
return 0
|
| 32 |
+
if val.endswith("d"):
|
| 33 |
+
try:
|
| 34 |
+
return int(float(val[:-1]) * 86400)
|
| 35 |
+
except ValueError:
|
| 36 |
+
return None
|
| 37 |
+
elif val.endswith("h"):
|
| 38 |
+
try:
|
| 39 |
+
return int(float(val[:-1]) * 3600)
|
| 40 |
+
except ValueError:
|
| 41 |
+
return None
|
| 42 |
+
elif val.endswith("m"):
|
| 43 |
+
try:
|
| 44 |
+
return int(float(val[:-1]) * 60)
|
| 45 |
+
except ValueError:
|
| 46 |
+
return None
|
| 47 |
+
elif val.endswith("s"):
|
| 48 |
+
try:
|
| 49 |
+
return int(float(val[:-1]))
|
| 50 |
+
except ValueError:
|
| 51 |
+
return None
|
| 52 |
+
else:
|
| 53 |
+
try:
|
| 54 |
+
return int(val)
|
| 55 |
+
except ValueError:
|
| 56 |
+
return None
|
| 57 |
+
|
| 58 |
+
import shlex
|
| 59 |
+
from pyrogram import Client, filters
|
| 60 |
+
from mfinder.db.settings_sql import (
|
| 61 |
+
get_admin_settings,
|
| 62 |
+
set_repair_mode,
|
| 63 |
+
set_auto_delete,
|
| 64 |
+
set_custom_caption,
|
| 65 |
+
set_force_sub,
|
| 66 |
+
set_channel_link,
|
| 67 |
+
get_link,
|
| 68 |
+
set_username,
|
| 69 |
+
set_log_channel,
|
| 70 |
+
get_log_channel,
|
| 71 |
+
set_how_to_download
|
| 72 |
+
)
|
| 73 |
+
from mfinder.db.ban_sql import is_banned, ban_user, unban_user
|
| 74 |
+
from mfinder.db.filters_sql import add_filter, rem_filter, list_filters
|
| 75 |
+
from mfinder.db.files_sql import count_files
|
| 76 |
+
from mfinder import ADMINS, DB_CHANNELS
|
| 77 |
+
|
| 78 |
+
@Client.on_message(filters.command(["autodelete"]) & filters.user(ADMINS))
|
| 79 |
+
async def auto_delete_(bot, update):
|
| 80 |
+
data = update.text.split()
|
| 81 |
+
if len(data) == 2:
|
| 82 |
+
dur_str = data[-1]
|
| 83 |
+
dur = parse_duration_to_seconds(dur_str)
|
| 84 |
+
if dur is None or dur < 0:
|
| 85 |
+
await update.reply_text("❌ **Invalid format!** Please use e.g. `2m` (2 minutes), `5h` (5 hours), `3600` (seconds), or `off`.")
|
| 86 |
+
return
|
| 87 |
+
|
| 88 |
+
await set_auto_delete(dur)
|
| 89 |
+
|
| 90 |
+
if dur:
|
| 91 |
+
if dur >= 86400:
|
| 92 |
+
desc = f"{dur / 86400:.1f} days" if (dur / 86400) % 1 != 0 else f"{int(dur / 86400)} days"
|
| 93 |
+
elif dur >= 3600:
|
| 94 |
+
desc = f"{dur / 3600:.1f} hours" if (dur / 3600) % 1 != 0 else f"{int(dur / 3600)} hours"
|
| 95 |
+
elif dur >= 60:
|
| 96 |
+
desc = f"{dur / 60:.1f} minutes" if (dur / 60) % 1 != 0 else f"{int(dur / 60)} minutes"
|
| 97 |
+
else:
|
| 98 |
+
desc = f"{dur} seconds"
|
| 99 |
+
await update.reply_text(f"✅ File auto delete set to `{dur}` seconds ({desc}).")
|
| 100 |
+
else:
|
| 101 |
+
await update.reply_text("✅ File auto delete disabled.")
|
| 102 |
+
else:
|
| 103 |
+
await update.reply_text("Please send in proper format `/autodelete <duration>` (e.g. `/autodelete 2m`, `/autodelete 5h` or `/autodelete off`)")
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
@Client.on_message(filters.command(["repairmode"]) & filters.user(ADMINS))
|
| 107 |
+
async def repair_mode_(bot, update):
|
| 108 |
+
data = update.text.split()
|
| 109 |
+
if len(data) == 2:
|
| 110 |
+
toggle = data[-1]
|
| 111 |
+
if toggle.lower() == "off":
|
| 112 |
+
mode = False
|
| 113 |
+
elif toggle.lower() == "on":
|
| 114 |
+
mode = True
|
| 115 |
+
else:
|
| 116 |
+
await update.reply_text(
|
| 117 |
+
"Please send in proper format `/repairmode <on/off>`"
|
| 118 |
+
)
|
| 119 |
+
return
|
| 120 |
+
|
| 121 |
+
await set_repair_mode(mode)
|
| 122 |
+
await update.reply_text(f"Repair mode set to `{toggle.upper()}`")
|
| 123 |
+
|
| 124 |
+
else:
|
| 125 |
+
await update.reply_text("Please send in proper format `/repairmode on/off`")
|
| 126 |
+
return
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
@Client.on_message(filters.command(["customcaption"]) & filters.user(ADMINS))
|
| 130 |
+
async def custom_caption_(bot, update):
|
| 131 |
+
data = update.text.split()
|
| 132 |
+
caption = " ".join(data[1:])
|
| 133 |
+
if len(data) >= 2:
|
| 134 |
+
if caption.lower() == "off":
|
| 135 |
+
caption = None
|
| 136 |
+
|
| 137 |
+
await set_custom_caption(caption)
|
| 138 |
+
|
| 139 |
+
if caption:
|
| 140 |
+
await update.reply_text(f"Custom caption set to `{caption}`")
|
| 141 |
+
else:
|
| 142 |
+
await update.reply_text("Custom caption disabled")
|
| 143 |
+
|
| 144 |
+
else:
|
| 145 |
+
await update.reply_text(
|
| 146 |
+
"Please send in proper format `/customcaption caption/off`"
|
| 147 |
+
)
|
| 148 |
+
return
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
ADMIN_INPUT_STATE = {}
|
| 152 |
+
|
| 153 |
+
async def get_settings_screen(cat: str):
|
| 154 |
+
from mfinder.db.settings_sql import get_admin_settings
|
| 155 |
+
from mfinder import ADMINS, DB_CHANNELS
|
| 156 |
+
|
| 157 |
+
admin_settings = await get_admin_settings()
|
| 158 |
+
auto_delete = admin_settings.auto_delete
|
| 159 |
+
custom_caption = admin_settings.custom_caption
|
| 160 |
+
fsub_channel = admin_settings.fsub_channel
|
| 161 |
+
fsub_channels_list = admin_settings.fsub_channels_list
|
| 162 |
+
caption_uname = admin_settings.caption_uname
|
| 163 |
+
invite_link = admin_settings.channel_link
|
| 164 |
+
repair_mode = admin_settings.repair_mode
|
| 165 |
+
shortener_site = admin_settings.shortener_site
|
| 166 |
+
shortener_api = admin_settings.shortener_api
|
| 167 |
+
shortener_status = admin_settings.shortener_status
|
| 168 |
+
if shortener_status is None:
|
| 169 |
+
shortener_status = True
|
| 170 |
+
token_shortener_enabled = admin_settings.token_shortener_enabled
|
| 171 |
+
if token_shortener_enabled is None:
|
| 172 |
+
token_shortener_enabled = False
|
| 173 |
+
token_timeout = admin_settings.token_timeout
|
| 174 |
+
if token_timeout is None:
|
| 175 |
+
token_timeout = 3600
|
| 176 |
+
log_channel = admin_settings.log_channel
|
| 177 |
+
|
| 178 |
+
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
| 179 |
+
|
| 180 |
+
if cat == "main":
|
| 181 |
+
text = "🛠️ **Admin Settings**\n\nSelect a category to configure:"
|
| 182 |
+
keyboard = InlineKeyboardMarkup([
|
| 183 |
+
[
|
| 184 |
+
InlineKeyboardButton("⚙️ General Settings", callback_data="adm_cat:gen"),
|
| 185 |
+
InlineKeyboardButton("🔗 Shortener Settings", callback_data="adm_cat:sho")
|
| 186 |
+
],
|
| 187 |
+
[
|
| 188 |
+
InlineKeyboardButton("📢 Channel Settings", callback_data="adm_cat:cha"),
|
| 189 |
+
InlineKeyboardButton("📝 Caption Settings", callback_data="adm_cat:cap")
|
| 190 |
+
],
|
| 191 |
+
[
|
| 192 |
+
InlineKeyboardButton("📰 Newsletter Settings", callback_data="adm_cat:newsl"),
|
| 193 |
+
InlineKeyboardButton("❌ Close Menu", callback_data="adm_close")
|
| 194 |
+
]
|
| 195 |
+
])
|
| 196 |
+
return text, keyboard
|
| 197 |
+
|
| 198 |
+
elif cat == "gen":
|
| 199 |
+
repair_status_label = "🟢 Enabled" if repair_mode else "🔴 Disabled"
|
| 200 |
+
repair_btn_label = "🔴 Disable Repair Mode" if repair_mode else "🟢 Enable Repair Mode"
|
| 201 |
+
if auto_delete:
|
| 202 |
+
parsed_auto_del = int(auto_delete)
|
| 203 |
+
if parsed_auto_del >= 86400:
|
| 204 |
+
days = parsed_auto_del / 86400
|
| 205 |
+
auto_del_label = f"{days:.1f} days" if days % 1 != 0 else f"{int(days)} days"
|
| 206 |
+
elif parsed_auto_del >= 3600:
|
| 207 |
+
hours = parsed_auto_del / 3600
|
| 208 |
+
auto_del_label = f"{hours:.1f} hours" if hours % 1 != 0 else f"{int(hours)} hours"
|
| 209 |
+
elif parsed_auto_del >= 60:
|
| 210 |
+
mins = parsed_auto_del / 60
|
| 211 |
+
auto_del_label = f"{mins:.1f} minutes" if mins % 1 != 0 else f"{int(mins)} minutes"
|
| 212 |
+
else:
|
| 213 |
+
auto_del_label = f"{parsed_auto_del} seconds"
|
| 214 |
+
else:
|
| 215 |
+
auto_del_label = "Disabled"
|
| 216 |
+
|
| 217 |
+
text = (
|
| 218 |
+
"⚙️ **General Settings**\n\n"
|
| 219 |
+
f"🛠️ **Repair Mode:** `{repair_status_label}`\n"
|
| 220 |
+
"↳ When enabled, the bot ignores all incoming search queries.\n\n"
|
| 221 |
+
f"⏱️ **Auto Delete:** `{auto_del_label}`\n"
|
| 222 |
+
"↳ Duration before sent files are deleted from the chat."
|
| 223 |
+
)
|
| 224 |
+
keyboard = InlineKeyboardMarkup([
|
| 225 |
+
[InlineKeyboardButton(repair_btn_label, callback_data="adm_toggle:repair")],
|
| 226 |
+
[InlineKeyboardButton("⏱️ Set Auto Delete Duration", callback_data="adm_ask:auto_delete")],
|
| 227 |
+
[InlineKeyboardButton("🔙 Back to Main Settings", callback_data="adm_cat:main")]
|
| 228 |
+
])
|
| 229 |
+
return text, keyboard
|
| 230 |
+
|
| 231 |
+
elif cat == "sho":
|
| 232 |
+
status_label = "🟢 ON" if shortener_status else "🔴 OFF"
|
| 233 |
+
toggle_label = "🔴 Turn OFF Shortener" if shortener_status else "🟢 Turn ON Shortener"
|
| 234 |
+
|
| 235 |
+
smart_label = "🟢 ON" if getattr(admin_settings, "smart_rotator", False) else "🔴 OFF"
|
| 236 |
+
smart_toggle_btn = "🔴 Turn OFF Smart Rotator" if getattr(admin_settings, "smart_rotator", False) else "🟢 Turn ON Smart Rotator"
|
| 237 |
+
|
| 238 |
+
token_status_label = "🟢 ON" if token_shortener_enabled else "🔴 OFF"
|
| 239 |
+
token_toggle_label = "🔴 Turn OFF Token Shortener" if token_shortener_enabled else "🟢 Turn ON Token Shortener"
|
| 240 |
+
|
| 241 |
+
parsed_seconds = int(token_timeout)
|
| 242 |
+
if parsed_seconds >= 3600:
|
| 243 |
+
hours = parsed_seconds / 3600
|
| 244 |
+
time_desc = f"{hours:.1f} hours" if hours % 1 != 0 else f"{int(hours)} hours"
|
| 245 |
+
elif parsed_seconds >= 60:
|
| 246 |
+
mins = parsed_seconds / 60
|
| 247 |
+
time_desc = f"{mins:.1f} minutes" if mins % 1 != 0 else f"{int(mins)} minutes"
|
| 248 |
+
else:
|
| 249 |
+
time_desc = f"{parsed_seconds} seconds"
|
| 250 |
+
|
| 251 |
+
text = (
|
| 252 |
+
"🔗 **Shortener Settings**\n\n"
|
| 253 |
+
f"📄 **Standard Shortener:** `{status_label}`\n"
|
| 254 |
+
"↳ If ON, standard file-level shortening is applied.\n\n"
|
| 255 |
+
f"🔄 **Smart Rotator:** `{smart_label}`\n"
|
| 256 |
+
"↳ Rotates active shorteners per user per day to maximize revenue.\n\n"
|
| 257 |
+
f"🎟️ **Token Shortener:** `{token_status_label}`\n"
|
| 258 |
+
f"⏱️ **Token Timeout:** `{time_desc}`\n"
|
| 259 |
+
"↳ If ON, users complete ONE link for direct access for the duration above."
|
| 260 |
+
)
|
| 261 |
+
keyboard = InlineKeyboardMarkup([
|
| 262 |
+
[InlineKeyboardButton(toggle_label, callback_data="adm_toggle:shortener")],
|
| 263 |
+
[InlineKeyboardButton(smart_toggle_btn, callback_data="adm_rot_toggle_smart")],
|
| 264 |
+
[InlineKeyboardButton(token_toggle_label, callback_data="adm_toggle:token_shortener")],
|
| 265 |
+
[InlineKeyboardButton("⏱️ Set Token Timeout", callback_data="adm_ask:token_timeout")],
|
| 266 |
+
[InlineKeyboardButton("📋 Shortener List", callback_data="adm_cat:rot")],
|
| 267 |
+
[InlineKeyboardButton("🔙 Back to Main Settings", callback_data="adm_cat:main")]
|
| 268 |
+
])
|
| 269 |
+
return text, keyboard
|
| 270 |
+
|
| 271 |
+
elif cat == "cha":
|
| 272 |
+
admins_str = "\n".join(f"• `{adm}`" for adm in ADMINS)
|
| 273 |
+
db_channels_str = "\n".join(f"• `{ch}`" for ch in DB_CHANNELS) if DB_CHANNELS else "• None"
|
| 274 |
+
fsub_label = fsub_channels_list if fsub_channels_list else (fsub_channel if fsub_channel else "Disabled")
|
| 275 |
+
link_label = invite_link if invite_link else "Disabled"
|
| 276 |
+
log_label = log_channel if log_channel else "Disabled"
|
| 277 |
+
|
| 278 |
+
ann_enabled = bool(getattr(admin_settings, "announcement_enabled", False))
|
| 279 |
+
ann_status_label = "🟢 Enabled" if ann_enabled else "🔴 Disabled"
|
| 280 |
+
ann_channel = getattr(admin_settings, "announcement_channel", None)
|
| 281 |
+
ann_channel_label = f"`{ann_channel}`" if ann_channel else "`Disabled`"
|
| 282 |
+
|
| 283 |
+
text = (
|
| 284 |
+
"📢 **Channel Settings**\n\n"
|
| 285 |
+
f"👤 **Admins**:\n{admins_str}\n\n"
|
| 286 |
+
f"📦 **Database Channels**:\n{db_channels_str}\n\n"
|
| 287 |
+
f"• **Force Sub Channel**: `{fsub_label}`\n"
|
| 288 |
+
f"• **Channel Link**: `{link_label}`\n"
|
| 289 |
+
f"• **User Logs Channel**: `{log_label}`\n"
|
| 290 |
+
f"• **Upload Announcements**: {ann_status_label}\n"
|
| 291 |
+
f"• **Announcement Channel**: {ann_channel_label}"
|
| 292 |
+
)
|
| 293 |
+
keyboard = InlineKeyboardMarkup([
|
| 294 |
+
[
|
| 295 |
+
InlineKeyboardButton("👤 Set Admins List", callback_data="adm_ask:admins"),
|
| 296 |
+
InlineKeyboardButton("📦 Set DB Channels", callback_data="adm_ask:db_channels")
|
| 297 |
+
],
|
| 298 |
+
[
|
| 299 |
+
InlineKeyboardButton("⚡ Set Force Sub ID", callback_data="adm_ask:force_sub"),
|
| 300 |
+
InlineKeyboardButton("🔗 Set Channel Link", callback_data="adm_ask:channel_link")
|
| 301 |
+
],
|
| 302 |
+
[
|
| 303 |
+
InlineKeyboardButton("📊 Set Log Channel ID", callback_data="adm_ask:log_channel")
|
| 304 |
+
],
|
| 305 |
+
[
|
| 306 |
+
InlineKeyboardButton("📢 Toggle Announcements", callback_data="adm_toggle:announcement_enabled"),
|
| 307 |
+
InlineKeyboardButton("📢 Set Ann Channel ID", callback_data="adm_ask:announcement_channel")
|
| 308 |
+
],
|
| 309 |
+
[InlineKeyboardButton("🔙 Back to Main Settings", callback_data="adm_cat:main")]
|
| 310 |
+
])
|
| 311 |
+
return text, keyboard
|
| 312 |
+
|
| 313 |
+
elif cat == "cap":
|
| 314 |
+
caption_label = custom_caption if custom_caption else "Disabled"
|
| 315 |
+
uname_label = caption_uname if caption_uname else "Disabled"
|
| 316 |
+
|
| 317 |
+
text = (
|
| 318 |
+
"📝 **Caption Settings**\n\n"
|
| 319 |
+
f"• **Custom Caption**:\n`{caption_label}`\n\n"
|
| 320 |
+
f"• **Caption Username**: `{uname_label}`"
|
| 321 |
+
)
|
| 322 |
+
keyboard = InlineKeyboardMarkup([
|
| 323 |
+
[InlineKeyboardButton("✏️ Set Custom Caption", callback_data="adm_ask:custom_caption")],
|
| 324 |
+
[InlineKeyboardButton("🏷️ Set Caption Username", callback_data="adm_ask:caption_uname")],
|
| 325 |
+
[InlineKeyboardButton("🔙 Back to Main Settings", callback_data="adm_cat:main")]
|
| 326 |
+
])
|
| 327 |
+
return text, keyboard
|
| 328 |
+
|
| 329 |
+
elif cat == "newsl":
|
| 330 |
+
ns_enabled = bool(getattr(admin_settings, "newsletter_enabled", False))
|
| 331 |
+
ns_status_label = "🟢 Enabled" if ns_enabled else "🔴 Disabled"
|
| 332 |
+
ns_toggle_label = "🔴 Disable Newsletter" if ns_enabled else "🟢 Enable Newsletter"
|
| 333 |
+
|
| 334 |
+
ns_days = getattr(admin_settings, "newsletter_days", "Friday")
|
| 335 |
+
ns_time = getattr(admin_settings, "newsletter_time", "20:00")
|
| 336 |
+
ns_count = getattr(admin_settings, "newsletter_count", 10)
|
| 337 |
+
|
| 338 |
+
ns_target = getattr(admin_settings, "newsletter_target", "subscribed")
|
| 339 |
+
target_label = "👥 All Users" if ns_target == "all" else "🔔 Subscribed Users Only"
|
| 340 |
+
target_toggle_label = "🔔 Set Target to Subscribed" if ns_target == "all" else "👥 Set Target to All Users"
|
| 341 |
+
|
| 342 |
+
text = (
|
| 343 |
+
"📰 **Newsletter Settings**\n\n"
|
| 344 |
+
f"🔄 **Newsletter Status:** `{ns_status_label}`\n"
|
| 345 |
+
"↳ Toggle automated weekly broadcast feature.\n\n"
|
| 346 |
+
f"📅 **Send Weekdays:** `{ns_days}`\n"
|
| 347 |
+
"↳ Weekday(s) to broadcast the newsletter (comma separated).\n\n"
|
| 348 |
+
f"🕒 **Send Time (24h):** `{ns_time}`\n"
|
| 349 |
+
"↳ Time of day to broadcast the newsletter.\n\n"
|
| 350 |
+
f"🍿 **Max Movies Count:** `{ns_count}`\n"
|
| 351 |
+
"↳ Max newly uploaded movies to include in newsletter.\n\n"
|
| 352 |
+
f"🎯 **Target Audience:** `{target_label}`\n"
|
| 353 |
+
"↳ Who will receive the auto-broadcast."
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
keyboard = InlineKeyboardMarkup([
|
| 357 |
+
[InlineKeyboardButton(ns_toggle_label, callback_data="adm_toggle:newsletter_enabled")],
|
| 358 |
+
[InlineKeyboardButton(target_toggle_label, callback_data="adm_toggle:newsletter_target")],
|
| 359 |
+
[
|
| 360 |
+
InlineKeyboardButton("📅 Set Send Days", callback_data="adm_ask:newsletter_days"),
|
| 361 |
+
InlineKeyboardButton("🕒 Set Send Time", callback_data="adm_ask:newsletter_time")
|
| 362 |
+
],
|
| 363 |
+
[
|
| 364 |
+
InlineKeyboardButton("🍿 Set Max Movie Count", callback_data="adm_ask:newsletter_count")
|
| 365 |
+
],
|
| 366 |
+
[InlineKeyboardButton("🔙 Back to Main Settings", callback_data="adm_cat:main")]
|
| 367 |
+
])
|
| 368 |
+
return text, keyboard
|
| 369 |
+
|
| 370 |
+
elif cat == "rot":
|
| 371 |
+
shorteners = get_all_shorteners(admin_settings)
|
| 372 |
+
|
| 373 |
+
# Sync it back to database if list is migrated in memory
|
| 374 |
+
if hasattr(admin_settings, "shorteners_list") and not admin_settings.shorteners_list:
|
| 375 |
+
from mfinder.db.settings_sql import update_shorteners_list
|
| 376 |
+
asyncio.create_task(update_shorteners_list(json.dumps(shorteners)))
|
| 377 |
+
|
| 378 |
+
text = (
|
| 379 |
+
"📋 **Shortener List Settings**\n\n"
|
| 380 |
+
"📂 **Configured Shorteners List (Priority Order):**\n\n"
|
| 381 |
+
)
|
| 382 |
+
for i, sh in enumerate(shorteners):
|
| 383 |
+
status_icon = "🟢 ON" if sh.get("status", True) else "🔴 OFF"
|
| 384 |
+
site_url = sh.get("site")
|
| 385 |
+
api_key = sh.get("api")
|
| 386 |
+
how_to = sh.get("how_to_download") or "https://telegram.me/FIREBOLTTutorial/23"
|
| 387 |
+
api_masked = api_key[:4] + "*"*(len(api_key)-4) if len(api_key) > 4 else "Set"
|
| 388 |
+
text += f"**{i+1}.** `{site_url}`\n↳ Key: `{api_masked}`\n↳ Tutorial: `{how_to}`\n↳ Status: `{status_icon}`\n\n"
|
| 389 |
+
keyboard_buttons = []
|
| 390 |
+
for i, sh in enumerate(shorteners):
|
| 391 |
+
site_url = sh.get("site")
|
| 392 |
+
keyboard_buttons.append([
|
| 393 |
+
InlineKeyboardButton(f"⚙️ {i+1}. {site_url}", callback_data=f"adm_rot_manage:{i}"),
|
| 394 |
+
])
|
| 395 |
+
keyboard_buttons.append([InlineKeyboardButton("➕ Add New Shortener", callback_data="adm_rot_add")])
|
| 396 |
+
if len(shorteners) > 0:
|
| 397 |
+
keyboard_buttons.append([InlineKeyboardButton("🗑️ Clear All Rotators", callback_data="adm_rot_clear")])
|
| 398 |
+
keyboard_buttons.append([InlineKeyboardButton("🔙 Back to Shortener Settings", callback_data="adm_cat:sho")])
|
| 399 |
+
keyboard = InlineKeyboardMarkup(keyboard_buttons)
|
| 400 |
+
return text, keyboard
|
| 401 |
+
|
| 402 |
+
elif cat.startswith("rot_manage:"):
|
| 403 |
+
idx = int(cat.split(":")[1])
|
| 404 |
+
shorteners = get_all_shorteners(admin_settings)
|
| 405 |
+
if idx >= len(shorteners):
|
| 406 |
+
return "⚠️ Shortener not found.", InlineKeyboardMarkup([[InlineKeyboardButton("🔙 Back", callback_data="adm_cat:rot")]])
|
| 407 |
+
sh = shorteners[idx]
|
| 408 |
+
site_url = sh.get("site")
|
| 409 |
+
status_label = "🟢 ON" if sh.get("status", True) else "🔴 OFF"
|
| 410 |
+
toggle_label = "🔴 Turn OFF" if sh.get("status", True) else "🟢 Turn ON"
|
| 411 |
+
text = (
|
| 412 |
+
f"⚙️ **Manage Shortener #{idx+1}:** `{site_url}`\n\n"
|
| 413 |
+
f"🔘 **Status:** `{status_label}`\n"
|
| 414 |
+
f"🔑 **API Key:** `{sh.get('api')}`\n"
|
| 415 |
+
f"📖 **Download Tutorial:** `{sh.get('how_to_download', 'Not set')}`"
|
| 416 |
+
)
|
| 417 |
+
keyboard = InlineKeyboardMarkup([
|
| 418 |
+
[InlineKeyboardButton(toggle_label, callback_data=f"adm_rot_toggle:{idx}")],
|
| 419 |
+
[InlineKeyboardButton("✏️ Edit Shortener", callback_data=f"adm_rot_edit:{idx}")],
|
| 420 |
+
[InlineKeyboardButton("🗑️ Delete Shortener", callback_data=f"adm_rot_delete:{idx}")],
|
| 421 |
+
[InlineKeyboardButton("🔙 Back to List", callback_data="adm_cat:rot")]
|
| 422 |
+
])
|
| 423 |
+
return text, keyboard
|
| 424 |
+
|
| 425 |
+
@Client.on_message(filters.command(["adminsettings"]) & filters.user(ADMINS))
|
| 426 |
+
async def admin_settings_(bot, update):
|
| 427 |
+
text, keyboard = await get_settings_screen("main")
|
| 428 |
+
await update.reply_text(
|
| 429 |
+
text=text,
|
| 430 |
+
reply_markup=keyboard,
|
| 431 |
+
quote=True
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
@Client.on_callback_query(filters.regex(r"^adm_cat:(main|gen|sho|cha|cap|rot|newsl)$") & filters.user(ADMINS))
|
| 435 |
+
async def admin_category_callback(bot, query):
|
| 436 |
+
cat = query.data.split(":")[1]
|
| 437 |
+
ADMIN_INPUT_STATE.pop(query.from_user.id, None)
|
| 438 |
+
|
| 439 |
+
text, keyboard = await get_settings_screen(cat)
|
| 440 |
+
try:
|
| 441 |
+
await query.message.edit_text(
|
| 442 |
+
text=text,
|
| 443 |
+
reply_markup=keyboard
|
| 444 |
+
)
|
| 445 |
+
except Exception:
|
| 446 |
+
pass
|
| 447 |
+
await query.answer()
|
| 448 |
+
|
| 449 |
+
@Client.on_callback_query(filters.regex(r"^adm_toggle:(repair|shortener|token_shortener|newsletter_enabled|newsletter_target|announcement_enabled)$") & filters.user(ADMINS))
|
| 450 |
+
async def admin_toggle_callback(bot, query):
|
| 451 |
+
setting = query.data.split(":")[1]
|
| 452 |
+
from mfinder.db.settings_sql import (
|
| 453 |
+
get_admin_settings,
|
| 454 |
+
set_repair_mode,
|
| 455 |
+
set_shortener_settings,
|
| 456 |
+
set_token_shortener_state
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
admin_settings = await get_admin_settings()
|
| 460 |
+
|
| 461 |
+
if setting == "repair":
|
| 462 |
+
new_val = not admin_settings.repair_mode
|
| 463 |
+
await set_repair_mode(new_val)
|
| 464 |
+
await query.answer(f"Repair mode {'Enabled' if new_val else 'Disabled'}")
|
| 465 |
+
text, keyboard = await get_settings_screen("gen")
|
| 466 |
+
elif setting == "shortener":
|
| 467 |
+
current_status = admin_settings.shortener_status
|
| 468 |
+
if current_status is None:
|
| 469 |
+
current_status = True
|
| 470 |
+
new_val = not current_status
|
| 471 |
+
await set_shortener_settings(status=new_val)
|
| 472 |
+
from mfinder.utils.helpers import clear_short_url_cache
|
| 473 |
+
clear_short_url_cache()
|
| 474 |
+
try:
|
| 475 |
+
from mfinder.db.settings_sql import clear_all_user_shortener_usages
|
| 476 |
+
await clear_all_user_shortener_usages()
|
| 477 |
+
except Exception:
|
| 478 |
+
pass
|
| 479 |
+
if new_val:
|
| 480 |
+
await set_token_shortener_state(False)
|
| 481 |
+
await query.answer(f"Shortener {'ON' if new_val else 'OFF'}")
|
| 482 |
+
text, keyboard = await get_settings_screen("sho")
|
| 483 |
+
elif setting == "token_shortener":
|
| 484 |
+
current_status = admin_settings.token_shortener_enabled
|
| 485 |
+
if current_status is None:
|
| 486 |
+
current_status = False
|
| 487 |
+
new_val = not current_status
|
| 488 |
+
await set_token_shortener_state(new_val)
|
| 489 |
+
try:
|
| 490 |
+
from mfinder.db.settings_sql import clear_all_user_shortener_usages
|
| 491 |
+
await clear_all_user_shortener_usages()
|
| 492 |
+
except Exception:
|
| 493 |
+
pass
|
| 494 |
+
if new_val:
|
| 495 |
+
await set_shortener_settings(status=False)
|
| 496 |
+
await query.answer(f"Token shortener {'Enabled' if new_val else 'Disabled'}")
|
| 497 |
+
text, keyboard = await get_settings_screen("sho")
|
| 498 |
+
elif setting == "newsletter_enabled":
|
| 499 |
+
current_status = bool(getattr(admin_settings, "newsletter_enabled", False))
|
| 500 |
+
new_val = not current_status
|
| 501 |
+
from mfinder.db.settings_sql import set_newsletter_settings
|
| 502 |
+
await set_newsletter_settings(enabled=new_val)
|
| 503 |
+
await query.answer(f"Newsletter {'Enabled' if new_val else 'Disabled'}")
|
| 504 |
+
text, keyboard = await get_settings_screen("newsl")
|
| 505 |
+
elif setting == "newsletter_target":
|
| 506 |
+
current_target = getattr(admin_settings, "newsletter_target", "subscribed")
|
| 507 |
+
new_target = "all" if current_target == "subscribed" else "subscribed"
|
| 508 |
+
from mfinder.db.settings_sql import set_newsletter_settings
|
| 509 |
+
await set_newsletter_settings(target=new_target)
|
| 510 |
+
await query.answer(f"Target audience set to {'All Users' if new_target == 'all' else 'Subscribed Users'}")
|
| 511 |
+
text, keyboard = await get_settings_screen("newsl")
|
| 512 |
+
elif setting == "announcement_enabled":
|
| 513 |
+
current_status = bool(getattr(admin_settings, "announcement_enabled", False))
|
| 514 |
+
new_val = not current_status
|
| 515 |
+
from mfinder.db.settings_sql import set_announcement_settings
|
| 516 |
+
await set_announcement_settings(enabled=new_val)
|
| 517 |
+
await query.answer(f"Upload Announcements {'Enabled' if new_val else 'Disabled'}")
|
| 518 |
+
text, keyboard = await get_settings_screen("cha")
|
| 519 |
+
else:
|
| 520 |
+
await query.answer("Unknown toggle.")
|
| 521 |
+
return
|
| 522 |
+
|
| 523 |
+
try:
|
| 524 |
+
await query.message.edit_text(
|
| 525 |
+
text=text,
|
| 526 |
+
reply_markup=keyboard
|
| 527 |
+
)
|
| 528 |
+
except Exception:
|
| 529 |
+
pass
|
| 530 |
+
|
| 531 |
+
@Client.on_callback_query(filters.regex(r"^adm_del_shortener$") & filters.user(ADMINS))
|
| 532 |
+
async def admin_del_shortener_callback(bot, query):
|
| 533 |
+
from mfinder.db.settings_sql import delete_shortener_settings
|
| 534 |
+
await delete_shortener_settings()
|
| 535 |
+
await query.answer("Shortener settings cleared.")
|
| 536 |
+
text, keyboard = await get_settings_screen("sho")
|
| 537 |
+
try:
|
| 538 |
+
await query.message.edit_text(
|
| 539 |
+
text=text,
|
| 540 |
+
reply_markup=keyboard
|
| 541 |
+
)
|
| 542 |
+
except Exception:
|
| 543 |
+
pass
|
| 544 |
+
|
| 545 |
+
@Client.on_callback_query(filters.regex(r"^adm_close$") & filters.user(ADMINS))
|
| 546 |
+
async def admin_close_callback(bot, query):
|
| 547 |
+
ADMIN_INPUT_STATE.pop(query.from_user.id, None)
|
| 548 |
+
try:
|
| 549 |
+
await query.message.delete()
|
| 550 |
+
except Exception:
|
| 551 |
+
pass
|
| 552 |
+
await query.answer("Settings menu closed.")
|
| 553 |
+
|
| 554 |
+
@Client.on_callback_query(filters.regex(r"^adm_ask:(\w+)$") & filters.user(ADMINS))
|
| 555 |
+
async def admin_ask_callback(bot, query):
|
| 556 |
+
action = query.data.split(":")[1]
|
| 557 |
+
user_id = query.from_user.id
|
| 558 |
+
import time
|
| 559 |
+
ADMIN_INPUT_STATE[user_id] = {"action": f"set_{action}", "message_id": query.message.id, "timestamp": time.time()}
|
| 560 |
+
prompt_map = {
|
| 561 |
+
"add_rotator_shortener": "Send the new shortener site and API key separated by a space (e.g. gplinks.in API_KEY):",
|
| 562 |
+
"auto_delete": "Send the new Auto Delete duration in seconds (or 'off' to disable):",
|
| 563 |
+
"custom_caption": "Send the new Custom Caption text (or 'off' to disable):",
|
| 564 |
+
"caption_uname": "Send the new Caption Username starting with '@' (or 'off' to disable):",
|
| 565 |
+
"shortener_site": "Send the new Site name (e.g. shortxlinks.com):",
|
| 566 |
+
"shortener_api": "Send the new Shortener API Key:",
|
| 567 |
+
"token_timeout": "Send the new Token validity time (e.g., '1h' for 1 hour, '30m' for 30 mins, or raw seconds):",
|
| 568 |
+
"force_sub": "Send the new Force Subscription Channel ID (or 'off' to disable):",
|
| 569 |
+
"channel_link": "Send the new Force Subscription Channel Link (or 'off' to disable):",
|
| 570 |
+
"admins": "Send a comma-separated list of Admin User IDs (e.g. 12345, 67890):",
|
| 571 |
+
"db_channels": "Send a comma-separated list of DB Channel IDs (e.g. -100123, -100456):",
|
| 572 |
+
"log_channel": "Send the new User Search Logs Channel ID or username (or 'off' to disable):",
|
| 573 |
+
"how_to_download": "Send the new How to Download/Verify URL (or 'off' to disable):",
|
| 574 |
+
"announcement_channel": "Send the new Upload Announcements Channel ID (e.g. -100123456) or 'off' to disable:",
|
| 575 |
+
"newsletter_days": "Send the days of week separated by comma (e.g. Friday,Sunday):",
|
| 576 |
+
"newsletter_time": "Send the new Send Time in 24-hour HH:MM format (e.g. 20:00):",
|
| 577 |
+
"newsletter_count": "Send the maximum number of new uploads to include in the newsletter (e.g. 10):"
|
| 578 |
+
}
|
| 579 |
+
prompt = "Send the new details (format: `domain api_key tutorial_url`):" if action.startswith("edit_rotator_shortener") or action == "add_rotator_shortener" else prompt_map.get(action, "Send the new parameter value:")
|
| 580 |
+
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
| 581 |
+
category_map = {
|
| 582 |
+
"add_rotator_shortener": "rot",
|
| 583 |
+
"auto_delete": "gen",
|
| 584 |
+
"custom_caption": "cap",
|
| 585 |
+
"caption_uname": "cap",
|
| 586 |
+
"shortener_site": "sho",
|
| 587 |
+
"shortener_api": "sho",
|
| 588 |
+
"token_timeout": "sho",
|
| 589 |
+
"force_sub": "cha",
|
| 590 |
+
"channel_link": "cha",
|
| 591 |
+
"admins": "cha",
|
| 592 |
+
"db_channels": "cha",
|
| 593 |
+
"log_channel": "cha",
|
| 594 |
+
"announcement_channel": "cha",
|
| 595 |
+
"how_to_download": "gen",
|
| 596 |
+
"newsletter_days": "newsl",
|
| 597 |
+
"newsletter_time": "newsl",
|
| 598 |
+
"newsletter_count": "newsl"
|
| 599 |
+
}
|
| 600 |
+
cat = "rot" if action.startswith("edit_rotator_shortener") else category_map.get(action, "main")
|
| 601 |
+
keyboard = InlineKeyboardMarkup([[InlineKeyboardButton("❌ Cancel Configuration", callback_data=f"adm_cat:{cat}")]])
|
| 602 |
+
await query.message.edit_text(text=f"⌨️ **{prompt}**", reply_markup=keyboard)
|
| 603 |
+
await query.answer()
|
| 604 |
+
|
| 605 |
+
# Schedule the auto-cancel background task
|
| 606 |
+
async def cancel_after_timeout(b, u_id, msg_id, cat_name):
|
| 607 |
+
await asyncio.sleep(90) # 1.30 minutes
|
| 608 |
+
state = ADMIN_INPUT_STATE.get(u_id)
|
| 609 |
+
if state and state.get("message_id") == msg_id:
|
| 610 |
+
import time
|
| 611 |
+
elapsed = time.time() - state.get("timestamp", 0)
|
| 612 |
+
if elapsed >= 90:
|
| 613 |
+
ADMIN_INPUT_STATE.pop(u_id, None)
|
| 614 |
+
try:
|
| 615 |
+
text, keyboard = await get_settings_screen(cat_name)
|
| 616 |
+
alert_text = "⚠️ **Operation cancelled due to timeout (1.30 min)!**\n\n" + text
|
| 617 |
+
await b.edit_message_text(
|
| 618 |
+
chat_id=u_id,
|
| 619 |
+
message_id=msg_id,
|
| 620 |
+
text=alert_text,
|
| 621 |
+
reply_markup=keyboard
|
| 622 |
+
)
|
| 623 |
+
except Exception:
|
| 624 |
+
pass
|
| 625 |
+
else:
|
| 626 |
+
asyncio.create_task(cancel_after_timeout_loop(b, u_id, msg_id, cat_name))
|
| 627 |
+
|
| 628 |
+
async def cancel_after_timeout_loop(b, u_id, msg_id, cat_name):
|
| 629 |
+
state = ADMIN_INPUT_STATE.get(u_id)
|
| 630 |
+
if state and state.get("message_id") == msg_id:
|
| 631 |
+
import time
|
| 632 |
+
elapsed = time.time() - state.get("timestamp", 0)
|
| 633 |
+
remaining = 90 - elapsed
|
| 634 |
+
if remaining > 0:
|
| 635 |
+
await asyncio.sleep(remaining)
|
| 636 |
+
state = ADMIN_INPUT_STATE.get(u_id)
|
| 637 |
+
if state and state.get("message_id") == msg_id:
|
| 638 |
+
elapsed = time.time() - state.get("timestamp", 0)
|
| 639 |
+
if elapsed >= 90:
|
| 640 |
+
ADMIN_INPUT_STATE.pop(u_id, None)
|
| 641 |
+
try:
|
| 642 |
+
text, keyboard = await get_settings_screen(cat_name)
|
| 643 |
+
alert_text = "⚠️ **Operation cancelled due to timeout (1.30 min)!**\n\n" + text
|
| 644 |
+
await b.edit_message_text(
|
| 645 |
+
chat_id=u_id,
|
| 646 |
+
message_id=msg_id,
|
| 647 |
+
text=alert_text,
|
| 648 |
+
reply_markup=keyboard
|
| 649 |
+
)
|
| 650 |
+
except Exception:
|
| 651 |
+
pass
|
| 652 |
+
|
| 653 |
+
asyncio.create_task(cancel_after_timeout(bot, user_id, query.message.id, cat))
|
| 654 |
+
|
| 655 |
+
async def handle_admin_input(bot, message):
|
| 656 |
+
user_id = message.from_user.id
|
| 657 |
+
state = ADMIN_INPUT_STATE.get(user_id)
|
| 658 |
+
if not state:
|
| 659 |
+
return
|
| 660 |
+
action = state.get("action")
|
| 661 |
+
menu_message_id = state.get("message_id")
|
| 662 |
+
input_text = message.text.strip()
|
| 663 |
+
try:
|
| 664 |
+
await message.delete()
|
| 665 |
+
except Exception:
|
| 666 |
+
pass
|
| 667 |
+
from mfinder.db.settings_sql import (
|
| 668 |
+
set_auto_delete, set_custom_caption, set_force_sub, set_username, set_channel_link,
|
| 669 |
+
set_shortener_settings, update_admins_list, update_db_channels_list, get_link,
|
| 670 |
+
set_token_timeout, set_log_channel, set_how_to_download
|
| 671 |
+
)
|
| 672 |
+
from mfinder import ADMINS, DB_CHANNELS
|
| 673 |
+
success = True
|
| 674 |
+
err_msg = ""
|
| 675 |
+
success_msg = ""
|
| 676 |
+
|
| 677 |
+
if action == "add_rotator_shortener":
|
| 678 |
+
parts = input_text.split(None, 2)
|
| 679 |
+
if len(parts) != 3:
|
| 680 |
+
success = False
|
| 681 |
+
err_msg = "Please send domain name, API key, and How to Download URL separated by spaces (e.g. `gplinks.in API_KEY TUTORIAL_URL`)."
|
| 682 |
+
else:
|
| 683 |
+
site = parts[0].strip()
|
| 684 |
+
api = parts[1].strip()
|
| 685 |
+
how_to_download = parts[2].strip()
|
| 686 |
+
if " " in site or "." not in site:
|
| 687 |
+
success = False
|
| 688 |
+
err_msg = "Invalid domain name. It should not contain spaces and must contain at least one dot (e.g. gplinks.in)."
|
| 689 |
+
elif not how_to_download.startswith("http://") and not how_to_download.startswith("https://") and not how_to_download.startswith("t.me/") and not how_to_download.startswith("telegram.me/"):
|
| 690 |
+
success = False
|
| 691 |
+
err_msg = "Invalid How to Download URL. It must start with http://, https://, t.me/, or telegram.me/."
|
| 692 |
+
else:
|
| 693 |
+
import json
|
| 694 |
+
admin_settings = await get_admin_settings()
|
| 695 |
+
shorteners = []
|
| 696 |
+
if hasattr(admin_settings, "shorteners_list") and admin_settings.shorteners_list:
|
| 697 |
+
try:
|
| 698 |
+
shorteners = json.loads(admin_settings.shorteners_list)
|
| 699 |
+
except Exception:
|
| 700 |
+
pass
|
| 701 |
+
# Check if already exists
|
| 702 |
+
exists = False
|
| 703 |
+
for sh in shorteners:
|
| 704 |
+
if sh.get("site").lower() == site.lower():
|
| 705 |
+
sh["api"] = api
|
| 706 |
+
sh["how_to_download"] = how_to_download
|
| 707 |
+
sh["status"] = True
|
| 708 |
+
exists = True
|
| 709 |
+
break
|
| 710 |
+
if not exists:
|
| 711 |
+
shorteners.append({"site": site, "api": api, "how_to_download": how_to_download, "status": True})
|
| 712 |
+
from mfinder.db.settings_sql import update_shorteners_list
|
| 713 |
+
await update_shorteners_list(json.dumps(shorteners))
|
| 714 |
+
try:
|
| 715 |
+
from mfinder.db.settings_sql import clear_all_user_shortener_usages
|
| 716 |
+
await clear_all_user_shortener_usages()
|
| 717 |
+
except Exception:
|
| 718 |
+
pass
|
| 719 |
+
from mfinder.utils.helpers import clear_short_url_cache
|
| 720 |
+
clear_short_url_cache()
|
| 721 |
+
success_msg = f"Added shortener `{site}` to the rotator list."
|
| 722 |
+
|
| 723 |
+
elif action.startswith("edit_rotator_shortener:"):
|
| 724 |
+
idx = int(action.split(":")[1])
|
| 725 |
+
parts = input_text.split(None, 2)
|
| 726 |
+
if len(parts) != 3:
|
| 727 |
+
success = False
|
| 728 |
+
err_msg = "Please send domain name, API key, and How to Download URL separated by spaces (e.g. `gplinks.in API_KEY TUTORIAL_URL`)."
|
| 729 |
+
else:
|
| 730 |
+
site = parts[0].strip()
|
| 731 |
+
api = parts[1].strip()
|
| 732 |
+
how_to_download = parts[2].strip()
|
| 733 |
+
if " " in site or "." not in site:
|
| 734 |
+
success = False
|
| 735 |
+
err_msg = "Invalid domain name. It should not contain spaces and must contain at least one dot (e.g. gplinks.in)."
|
| 736 |
+
elif not how_to_download.startswith("http://") and not how_to_download.startswith("https://") and not how_to_download.startswith("t.me/") and not how_to_download.startswith("telegram.me/"):
|
| 737 |
+
success = False
|
| 738 |
+
err_msg = "Invalid How to Download URL. It must start with http://, https://, t.me/, or telegram.me/."
|
| 739 |
+
else:
|
| 740 |
+
import json
|
| 741 |
+
admin_settings = await get_admin_settings()
|
| 742 |
+
shorteners = get_all_shorteners(admin_settings)
|
| 743 |
+
if idx < len(shorteners):
|
| 744 |
+
shorteners[idx] = {
|
| 745 |
+
"site": site,
|
| 746 |
+
"api": api,
|
| 747 |
+
"how_to_download": how_to_download,
|
| 748 |
+
"status": shorteners[idx].get("status", True)
|
| 749 |
+
}
|
| 750 |
+
from mfinder.db.settings_sql import update_shorteners_list
|
| 751 |
+
await update_shorteners_list(json.dumps(shorteners))
|
| 752 |
+
try:
|
| 753 |
+
from mfinder.db.settings_sql import clear_all_user_shortener_usages
|
| 754 |
+
await clear_all_user_shortener_usages()
|
| 755 |
+
except Exception:
|
| 756 |
+
pass
|
| 757 |
+
from mfinder.utils.helpers import clear_short_url_cache
|
| 758 |
+
clear_short_url_cache()
|
| 759 |
+
success_msg = f"Updated shortener #{idx+1} (`{site}`) successfully."
|
| 760 |
+
else:
|
| 761 |
+
success = False
|
| 762 |
+
err_msg = "Shortener not found."
|
| 763 |
+
|
| 764 |
+
elif action == "set_auto_delete":
|
| 765 |
+
dur = parse_duration_to_seconds(input_text)
|
| 766 |
+
if dur is None or dur < 0:
|
| 767 |
+
success = False
|
| 768 |
+
err_msg = "Invalid format. Use e.g. '1h' (1 hour), '2m' (2 minutes), '30s' (30 seconds), or 'off'."
|
| 769 |
+
else:
|
| 770 |
+
await set_auto_delete(dur)
|
| 771 |
+
if dur:
|
| 772 |
+
if dur >= 86400:
|
| 773 |
+
desc = f"{dur / 86400:.1f} days" if (dur / 86400) % 1 != 0 else f"{int(dur / 86400)} days"
|
| 774 |
+
elif dur >= 3600:
|
| 775 |
+
desc = f"{dur / 3600:.1f} hours" if (dur / 3600) % 1 != 0 else f"{int(dur / 3600)} hours"
|
| 776 |
+
elif dur >= 60:
|
| 777 |
+
desc = f"{dur / 60:.1f} minutes" if (dur / 60) % 1 != 0 else f"{int(dur / 60)} minutes"
|
| 778 |
+
else:
|
| 779 |
+
desc = f"{dur} seconds"
|
| 780 |
+
success_msg = f"Auto delete duration set to `{dur}` seconds ({desc})."
|
| 781 |
+
else:
|
| 782 |
+
success_msg = "Auto delete duration has been disabled."
|
| 783 |
+
|
| 784 |
+
elif action == "set_custom_caption":
|
| 785 |
+
if input_text.lower() in ("off", "disable", "disabled"):
|
| 786 |
+
caption = None
|
| 787 |
+
success_msg = "Custom caption has been disabled."
|
| 788 |
+
else:
|
| 789 |
+
caption = input_text
|
| 790 |
+
success_msg = "Custom caption updated successfully."
|
| 791 |
+
await set_custom_caption(caption)
|
| 792 |
+
|
| 793 |
+
elif action == "set_caption_uname":
|
| 794 |
+
if input_text.lower() in ("off", "disable", "disabled"):
|
| 795 |
+
uname = None
|
| 796 |
+
success_msg = "Caption username has been disabled."
|
| 797 |
+
await set_username(uname)
|
| 798 |
+
elif input_text.startswith("@"):
|
| 799 |
+
uname = input_text
|
| 800 |
+
success_msg = f"Caption username set to `{uname}`."
|
| 801 |
+
await set_username(uname)
|
| 802 |
+
else:
|
| 803 |
+
success = False
|
| 804 |
+
err_msg = "Must start with '@' (e.g. @mychannel) or 'off' to disable."
|
| 805 |
+
|
| 806 |
+
elif action == "set_shortener_site":
|
| 807 |
+
if input_text.lower() in ("off", "disable", "disabled"):
|
| 808 |
+
site = None
|
| 809 |
+
success_msg = "Shortener site has been cleared/disabled."
|
| 810 |
+
await set_shortener_settings(site=site)
|
| 811 |
+
elif " " in input_text or "." not in input_text:
|
| 812 |
+
success = False
|
| 813 |
+
err_msg = "Invalid domain name. It should not contain spaces and must contain at least one dot (e.g., shortxlinks.com)."
|
| 814 |
+
else:
|
| 815 |
+
site = input_text
|
| 816 |
+
success_msg = f"Shortener site updated successfully to `{site}`."
|
| 817 |
+
await set_shortener_settings(site=site)
|
| 818 |
+
|
| 819 |
+
elif action == "set_shortener_api":
|
| 820 |
+
if input_text.lower() in ("off", "disable", "disabled"):
|
| 821 |
+
api = None
|
| 822 |
+
success_msg = "Shortener API key has been cleared/disabled."
|
| 823 |
+
await set_shortener_settings(api=api)
|
| 824 |
+
elif not input_text:
|
| 825 |
+
success = False
|
| 826 |
+
err_msg = "API key cannot be empty."
|
| 827 |
+
else:
|
| 828 |
+
api = input_text
|
| 829 |
+
success_msg = "Shortener API key updated successfully."
|
| 830 |
+
await set_shortener_settings(api=api)
|
| 831 |
+
|
| 832 |
+
elif action == "set_force_sub":
|
| 833 |
+
if input_text.lower() in ("off", "disable", "disabled", "0"):
|
| 834 |
+
await set_channel_link(None)
|
| 835 |
+
await set_force_sub(0)
|
| 836 |
+
success_msg = "Force subscription channel has been disabled."
|
| 837 |
+
else:
|
| 838 |
+
try:
|
| 839 |
+
resolved_ids, links_list = await parse_and_set_forcesub(bot, input_text)
|
| 840 |
+
success_msg = f"Force subscription channels set to: `{', '.join(resolved_ids)}`. Links: {', '.join(links_list)}"
|
| 841 |
+
except Exception as e:
|
| 842 |
+
success = False
|
| 843 |
+
err_msg = f"Could not find or access channels: {str(e)}. Make sure the channels exist and the bot is added as an administrator."
|
| 844 |
+
|
| 845 |
+
elif action == "set_channel_link":
|
| 846 |
+
if input_text.lower() in ("off", "disable", "disabled"):
|
| 847 |
+
await set_channel_link(None)
|
| 848 |
+
success_msg = "Channel invite link has been removed."
|
| 849 |
+
elif not (input_text.startswith("http://") or input_text.startswith("https://")):
|
| 850 |
+
success = False
|
| 851 |
+
err_msg = "Invalid URL. The link must start with 'http://' or 'https://'."
|
| 852 |
+
else:
|
| 853 |
+
await set_channel_link(input_text)
|
| 854 |
+
success_msg = f"Channel invite link set to `{input_text}`."
|
| 855 |
+
|
| 856 |
+
elif action == "set_admins":
|
| 857 |
+
try:
|
| 858 |
+
raw_ids = input_text.split(",")
|
| 859 |
+
parsed_ids = []
|
| 860 |
+
is_list_valid = True
|
| 861 |
+
invalid_val = ""
|
| 862 |
+
from mfinder import id_pattern
|
| 863 |
+
for r_id in raw_ids:
|
| 864 |
+
r_id = r_id.strip()
|
| 865 |
+
if not r_id:
|
| 866 |
+
continue
|
| 867 |
+
if id_pattern.search(r_id):
|
| 868 |
+
parsed_ids.append(int(r_id))
|
| 869 |
+
else:
|
| 870 |
+
is_list_valid = False
|
| 871 |
+
invalid_val = r_id
|
| 872 |
+
break
|
| 873 |
+
|
| 874 |
+
if not is_list_valid:
|
| 875 |
+
success = False
|
| 876 |
+
err_msg = f"Invalid Admin ID `{invalid_val}`. Admins list must contain only comma-separated integer IDs."
|
| 877 |
+
elif not parsed_ids:
|
| 878 |
+
success = False
|
| 879 |
+
err_msg = "Admins list cannot be empty."
|
| 880 |
+
else:
|
| 881 |
+
from mfinder import OWNER_ID
|
| 882 |
+
if OWNER_ID not in parsed_ids:
|
| 883 |
+
parsed_ids.append(OWNER_ID)
|
| 884 |
+
|
| 885 |
+
admins_str = ",".join(str(i) for i in parsed_ids)
|
| 886 |
+
await update_admins_list(admins_str)
|
| 887 |
+
|
| 888 |
+
ADMINS.clear()
|
| 889 |
+
ADMINS.extend(parsed_ids)
|
| 890 |
+
success_msg = f"Admins list updated successfully with {len(parsed_ids)} admins."
|
| 891 |
+
except Exception as e:
|
| 892 |
+
success = False
|
| 893 |
+
err_msg = f"Error parsing admins: {e}"
|
| 894 |
+
|
| 895 |
+
elif action == "set_db_channels":
|
| 896 |
+
try:
|
| 897 |
+
raw_ids = input_text.split(",")
|
| 898 |
+
parsed_ids = []
|
| 899 |
+
is_list_valid = True
|
| 900 |
+
invalid_val = ""
|
| 901 |
+
from mfinder import id_pattern
|
| 902 |
+
for r_id in raw_ids:
|
| 903 |
+
r_id = r_id.strip()
|
| 904 |
+
if not r_id:
|
| 905 |
+
continue
|
| 906 |
+
if id_pattern.search(r_id):
|
| 907 |
+
parsed_ids.append(int(r_id))
|
| 908 |
+
else:
|
| 909 |
+
is_list_valid = False
|
| 910 |
+
invalid_val = r_id
|
| 911 |
+
break
|
| 912 |
+
|
| 913 |
+
if not is_list_valid:
|
| 914 |
+
success = False
|
| 915 |
+
err_msg = f"Invalid Channel ID `{invalid_val}`. DB Channels list must contain only comma-separated integer IDs."
|
| 916 |
+
else:
|
| 917 |
+
channels_str = ",".join(str(i) for i in parsed_ids)
|
| 918 |
+
await update_db_channels_list(channels_str)
|
| 919 |
+
|
| 920 |
+
DB_CHANNELS.clear()
|
| 921 |
+
DB_CHANNELS.extend(parsed_ids)
|
| 922 |
+
success_msg = f"Database channels list updated successfully with {len(parsed_ids)} channels."
|
| 923 |
+
except Exception as e:
|
| 924 |
+
success = False
|
| 925 |
+
err_msg = f"Error parsing DB channels: {e}"
|
| 926 |
+
|
| 927 |
+
elif action == "set_token_timeout":
|
| 928 |
+
val = input_text.lower().strip()
|
| 929 |
+
parsed_seconds = parse_duration_to_seconds(val)
|
| 930 |
+
|
| 931 |
+
if parsed_seconds is None or parsed_seconds <= 0:
|
| 932 |
+
success = False
|
| 933 |
+
err_msg = "Invalid format. Use e.g. '1h' (1 hour), '30m' (30 minutes), or a positive number of seconds."
|
| 934 |
+
else:
|
| 935 |
+
await set_token_timeout(parsed_seconds)
|
| 936 |
+
if parsed_seconds >= 86400:
|
| 937 |
+
days = parsed_seconds / 86400
|
| 938 |
+
time_desc = f"{days:.1f} days" if days % 1 != 0 else f"{int(days)} days"
|
| 939 |
+
elif parsed_seconds >= 3600:
|
| 940 |
+
hours = parsed_seconds / 3600
|
| 941 |
+
time_desc = f"{hours:.1f} hours" if hours % 1 != 0 else f"{int(hours)} hours"
|
| 942 |
+
elif parsed_seconds >= 60:
|
| 943 |
+
mins = parsed_seconds / 60
|
| 944 |
+
time_desc = f"{mins:.1f} minutes" if mins % 1 != 0 else f"{int(mins)} minutes"
|
| 945 |
+
else:
|
| 946 |
+
time_desc = f"{parsed_seconds} seconds"
|
| 947 |
+
|
| 948 |
+
success_msg = f"Token validity duration set to `{parsed_seconds}` seconds ({time_desc})."
|
| 949 |
+
|
| 950 |
+
elif action == "set_log_channel":
|
| 951 |
+
if input_text.lower() in ("off", "disable", "disabled", "0"):
|
| 952 |
+
await set_log_channel(None)
|
| 953 |
+
success_msg = "User search logging channel has been disabled."
|
| 954 |
+
else:
|
| 955 |
+
channel_str = input_text
|
| 956 |
+
is_valid_id = False
|
| 957 |
+
if channel_str.startswith("@") and len(channel_str) > 1:
|
| 958 |
+
is_valid_id = True
|
| 959 |
+
channel_param = channel_str
|
| 960 |
+
else:
|
| 961 |
+
try:
|
| 962 |
+
channel_param = int(channel_str)
|
| 963 |
+
is_valid_id = True
|
| 964 |
+
except ValueError:
|
| 965 |
+
pass
|
| 966 |
+
|
| 967 |
+
if not is_valid_id:
|
| 968 |
+
success = False
|
| 969 |
+
err_msg = "Must be a valid integer ID (e.g., -100123456789) or username starting with '@'."
|
| 970 |
+
else:
|
| 971 |
+
try:
|
| 972 |
+
chat = await bot.get_chat(channel_param)
|
| 973 |
+
access_hash = None
|
| 974 |
+
try:
|
| 975 |
+
resolved = await bot.resolve_peer(chat.id)
|
| 976 |
+
if getattr(resolved, "access_hash", None):
|
| 977 |
+
access_hash = resolved.access_hash
|
| 978 |
+
except Exception:
|
| 979 |
+
pass
|
| 980 |
+
await set_log_channel(chat.id, access_hash=access_hash)
|
| 981 |
+
success_msg = f"User search logging channel set to `{chat.id}` ({chat.title or 'Channel'})."
|
| 982 |
+
except Exception as e:
|
| 983 |
+
success = False
|
| 984 |
+
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."
|
| 985 |
+
|
| 986 |
+
elif action == "set_how_to_download":
|
| 987 |
+
if input_text.lower() in ("off", "disable", "disabled"):
|
| 988 |
+
await set_how_to_download(None)
|
| 989 |
+
success_msg = "How to Download/Verify URL has been disabled/removed."
|
| 990 |
+
elif not (input_text.startswith("http://") or input_text.startswith("https://")):
|
| 991 |
+
success = False
|
| 992 |
+
err_msg = "Invalid URL. The link must start with 'http://' or 'https://'."
|
| 993 |
+
else:
|
| 994 |
+
await set_how_to_download(input_text)
|
| 995 |
+
success_msg = f"How to Download URL set to `{input_text}`."
|
| 996 |
+
|
| 997 |
+
elif action == "set_newsletter_days":
|
| 998 |
+
valid_days = {"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}
|
| 999 |
+
input_days = [d.strip().lower() for d in input_text.split(",") if d.strip()]
|
| 1000 |
+
if not input_days or any(d not in valid_days for d in input_days):
|
| 1001 |
+
success = False
|
| 1002 |
+
err_msg = "Must be a comma-separated list of valid weekdays (e.g. Friday,Sunday)."
|
| 1003 |
+
else:
|
| 1004 |
+
days_str = ",".join(d.capitalize() for d in input_days)
|
| 1005 |
+
from mfinder.db.settings_sql import set_newsletter_settings
|
| 1006 |
+
await set_newsletter_settings(days=days_str)
|
| 1007 |
+
success_msg = f"Newsletter days updated to `{days_str}`."
|
| 1008 |
+
elif action == "set_newsletter_time":
|
| 1009 |
+
import re
|
| 1010 |
+
if not re.match(r"^(0\d|1\d|2[0-3]):[0-5]\d$", input_text.strip()):
|
| 1011 |
+
success = False
|
| 1012 |
+
err_msg = "Must be in valid 24-hour HH:MM format (e.g. 20:00 or 08:30)."
|
| 1013 |
+
else:
|
| 1014 |
+
time_str = input_text.strip()
|
| 1015 |
+
from mfinder.db.settings_sql import set_newsletter_settings
|
| 1016 |
+
await set_newsletter_settings(time_str=time_str)
|
| 1017 |
+
success_msg = f"Newsletter send time set to `{time_str}`."
|
| 1018 |
+
elif action == "set_newsletter_count":
|
| 1019 |
+
try:
|
| 1020 |
+
val = int(input_text.strip())
|
| 1021 |
+
if val <= 0 or val > 100:
|
| 1022 |
+
raise ValueError
|
| 1023 |
+
from mfinder.db.settings_sql import set_newsletter_settings
|
| 1024 |
+
await set_newsletter_settings(count=val)
|
| 1025 |
+
success_msg = f"Newsletter max movie count set to `{val}`."
|
| 1026 |
+
except ValueError:
|
| 1027 |
+
success = False
|
| 1028 |
+
err_msg = "Must be a positive integer between 1 and 100."
|
| 1029 |
+
elif action == "set_announcement_channel":
|
| 1030 |
+
if input_text.lower() == "off":
|
| 1031 |
+
from mfinder.db.settings_sql import set_announcement_settings
|
| 1032 |
+
await set_announcement_settings(channel="off")
|
| 1033 |
+
success_msg = "Upload Announcements Channel disabled."
|
| 1034 |
+
else:
|
| 1035 |
+
try:
|
| 1036 |
+
chat = await bot.get_chat(input_text)
|
| 1037 |
+
if chat.type.value not in ("channel", "supergroup"):
|
| 1038 |
+
success = False
|
| 1039 |
+
err_msg = "Target must be a channel or supergroup."
|
| 1040 |
+
else:
|
| 1041 |
+
access_hash = getattr(chat, "access_hash", None)
|
| 1042 |
+
from mfinder.db.settings_sql import set_announcement_settings
|
| 1043 |
+
await set_announcement_settings(channel=chat.id, access_hash=access_hash)
|
| 1044 |
+
success_msg = f"Upload Announcements Channel set to `{chat.title}` ({chat.id}) with access hash resolved!"
|
| 1045 |
+
except Exception as e:
|
| 1046 |
+
success = False
|
| 1047 |
+
err_msg = f"Failed to resolve channel '{input_text}': {e}. Make sure the bot is an admin/member in the channel."
|
| 1048 |
+
else:
|
| 1049 |
+
success = False
|
| 1050 |
+
err_msg = "Unknown action."
|
| 1051 |
+
|
| 1052 |
+
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
| 1053 |
+
category_map = {
|
| 1054 |
+
"set_auto_delete": "gen",
|
| 1055 |
+
"set_custom_caption": "cap",
|
| 1056 |
+
"set_caption_uname": "cap",
|
| 1057 |
+
"set_shortener_site": "sho",
|
| 1058 |
+
"set_shortener_api": "sho",
|
| 1059 |
+
"set_token_timeout": "sho",
|
| 1060 |
+
"set_force_sub": "cha",
|
| 1061 |
+
"set_channel_link": "cha",
|
| 1062 |
+
"set_admins": "cha",
|
| 1063 |
+
"set_db_channels": "cha",
|
| 1064 |
+
"set_log_channel": "cha",
|
| 1065 |
+
"set_announcement_channel": "cha",
|
| 1066 |
+
"set_how_to_download": "gen",
|
| 1067 |
+
"set_newsletter_days": "newsl",
|
| 1068 |
+
"set_newsletter_time": "newsl",
|
| 1069 |
+
"set_newsletter_count": "newsl"
|
| 1070 |
+
}
|
| 1071 |
+
cat = "rot" if action.startswith("edit_rotator_shortener") or action == "add_rotator_shortener" else category_map.get(action, "main")
|
| 1072 |
+
|
| 1073 |
+
if success:
|
| 1074 |
+
ADMIN_INPUT_STATE.pop(user_id, None)
|
| 1075 |
+
keyboard = InlineKeyboardMarkup([
|
| 1076 |
+
[InlineKeyboardButton("⬅️ Back", callback_data=f"adm_cat:{cat}")]
|
| 1077 |
+
])
|
| 1078 |
+
text_to_send = f"✅ {success_msg}\n\nClick back to configure other settings."
|
| 1079 |
+
else:
|
| 1080 |
+
keyboard = InlineKeyboardMarkup([
|
| 1081 |
+
[InlineKeyboardButton("❌ Cancel Configuration", callback_data=f"adm_cat:{cat}")]
|
| 1082 |
+
])
|
| 1083 |
+
prompt_map = {
|
| 1084 |
+
"edit_rotator_shortener": "Send the new details (format: `domain api_key tutorial_url`):",
|
| 1085 |
+
|
| 1086 |
+
"set_auto_delete": "Send the new Auto Delete duration in seconds (or 'off' to disable):",
|
| 1087 |
+
"set_custom_caption": "Send the new Custom Caption text (or 'off' to disable):",
|
| 1088 |
+
"set_caption_uname": "Send the new Caption Username starting with '@' (or 'off' to disable):",
|
| 1089 |
+
"set_shortener_site": "Send the new Site name (e.g. shortxlinks.com):",
|
| 1090 |
+
"set_shortener_api": "Send the new Shortener API Key:",
|
| 1091 |
+
"set_token_timeout": "Send the new Token validity time (e.g., '1h' for 1 hour, '30m' for 30 mins, or raw seconds):",
|
| 1092 |
+
"set_force_sub": "Send the new Force Subscription Channel ID (or 'off' to disable):",
|
| 1093 |
+
"set_channel_link": "Send the new Force Subscription Channel Link (or 'off' to disable):",
|
| 1094 |
+
"set_admins": "Send a comma-separated list of Admin User IDs (e.g. 12345, 67890):",
|
| 1095 |
+
"set_db_channels": "Send a comma-separated list of DB Channel IDs (e.g. -100123, -100456):",
|
| 1096 |
+
"set_log_channel": "Send the new User Search Logs Channel ID or username (or 'off' to disable):",
|
| 1097 |
+
"set_how_to_download": "Send the new How to Download/Verify URL (or 'off' to disable):",
|
| 1098 |
+
"set_announcement_channel": "Send the new Upload Announcements Channel ID (e.g. -100123456) or 'off' to disable:",
|
| 1099 |
+
"set_newsletter_days": "Send the days of week separated by comma (e.g. Friday,Sunday):",
|
| 1100 |
+
"set_newsletter_time": "Send the new Send Time in 24-hour HH:MM format (e.g. 20:00):",
|
| 1101 |
+
"set_newsletter_count": "Send the maximum number of new uploads to include in the newsletter (e.g. 10):"
|
| 1102 |
+
}
|
| 1103 |
+
if action.startswith("edit_rotator_shortener") or action == "add_rotator_shortener":
|
| 1104 |
+
original_prompt = "Send the details (format: `domain api_key tutorial_url`):"
|
| 1105 |
+
else:
|
| 1106 |
+
original_prompt = prompt_map.get(action, "Send the new parameter value:")
|
| 1107 |
+
import time
|
| 1108 |
+
text_to_send = f"⚠️ **Invalid input:** `{err_msg}`\n\n⌨️ **{original_prompt}**" + ("\u200b" * int(time.time() % 5))
|
| 1109 |
+
|
| 1110 |
+
from pyrogram.errors import MessageNotModified
|
| 1111 |
+
try:
|
| 1112 |
+
await bot.edit_message_text(
|
| 1113 |
+
chat_id=user_id,
|
| 1114 |
+
message_id=menu_message_id,
|
| 1115 |
+
text=text_to_send,
|
| 1116 |
+
reply_markup=keyboard
|
| 1117 |
+
)
|
| 1118 |
+
except MessageNotModified:
|
| 1119 |
+
pass
|
| 1120 |
+
except Exception:
|
| 1121 |
+
try:
|
| 1122 |
+
sent_msg = await bot.send_message(user_id, text_to_send, reply_markup=keyboard)
|
| 1123 |
+
if not success and state:
|
| 1124 |
+
state["message_id"] = sent_msg.id
|
| 1125 |
+
import time
|
| 1126 |
+
state["timestamp"] = time.time()
|
| 1127 |
+
except Exception:
|
| 1128 |
+
pass
|
| 1129 |
+
|
| 1130 |
+
|
| 1131 |
+
@Client.on_message(filters.command(["ban"]) & filters.user(ADMINS))
|
| 1132 |
+
async def banuser(bot, update):
|
| 1133 |
+
data = update.text.split()
|
| 1134 |
+
if len(data) == 2:
|
| 1135 |
+
user_id = data[-1]
|
| 1136 |
+
banned = await is_banned(int(user_id))
|
| 1137 |
+
if not banned:
|
| 1138 |
+
await ban_user(int(user_id))
|
| 1139 |
+
await update.reply_text(f"User {user_id} banned")
|
| 1140 |
+
else:
|
| 1141 |
+
await update.reply_text(f"User {user_id} is already banned")
|
| 1142 |
+
|
| 1143 |
+
else:
|
| 1144 |
+
await update.reply_text("Please send in proper format `/ban user_id`")
|
| 1145 |
+
|
| 1146 |
+
|
| 1147 |
+
@Client.on_message(filters.command(["unban"]) & filters.user(ADMINS))
|
| 1148 |
+
async def unbanuser(bot, update):
|
| 1149 |
+
data = update.text.split()
|
| 1150 |
+
if len(data) == 2:
|
| 1151 |
+
user_id = data[-1]
|
| 1152 |
+
banned = await is_banned(int(user_id))
|
| 1153 |
+
if banned:
|
| 1154 |
+
await unban_user(int(user_id))
|
| 1155 |
+
await update.reply_text(f"User {user_id} unbanned")
|
| 1156 |
+
else:
|
| 1157 |
+
await update.reply_text(f"User {user_id} is not in ban list")
|
| 1158 |
+
else:
|
| 1159 |
+
await update.reply_text("Please send in proper format `/unban user_id`")
|
| 1160 |
+
|
| 1161 |
+
|
| 1162 |
+
@Client.on_message(filters.command(["addfilter"]) & filters.user(ADMINS))
|
| 1163 |
+
async def addfilter(bot, update):
|
| 1164 |
+
data = shlex.split(update.text)
|
| 1165 |
+
if len(data) >= 3:
|
| 1166 |
+
fltr = data[1].strip('"').lower()
|
| 1167 |
+
message = " ".join(data[2:])
|
| 1168 |
+
add = await add_filter(fltr, message)
|
| 1169 |
+
if add:
|
| 1170 |
+
await update.reply_text(f"Filter `{fltr}` added")
|
| 1171 |
+
else:
|
| 1172 |
+
await update.reply_text(f"Filter `{fltr}` already exists")
|
| 1173 |
+
else:
|
| 1174 |
+
await update.reply_text(
|
| 1175 |
+
"Please send in proper format `/addfilter filter message`"
|
| 1176 |
+
)
|
| 1177 |
+
|
| 1178 |
+
|
| 1179 |
+
@Client.on_message(filters.command(["delfilter"]) & filters.user(ADMINS))
|
| 1180 |
+
async def delfilter(bot, update):
|
| 1181 |
+
data = update.text.split()
|
| 1182 |
+
if len(data) >= 2:
|
| 1183 |
+
fltr = " ".join(data[1:])
|
| 1184 |
+
rem = await rem_filter(fltr)
|
| 1185 |
+
if rem:
|
| 1186 |
+
await update.reply_text(f"Filter `{fltr}` removed")
|
| 1187 |
+
else:
|
| 1188 |
+
await update.reply_text(f"Filter `{fltr}` not found")
|
| 1189 |
+
else:
|
| 1190 |
+
await update.reply_text("Please send in proper format `/delfilter filter`")
|
| 1191 |
+
|
| 1192 |
+
|
| 1193 |
+
@Client.on_message(filters.command(["listfilters"]) & filters.user(ADMINS))
|
| 1194 |
+
async def list_filter(bot, update):
|
| 1195 |
+
fltr = await list_filters()
|
| 1196 |
+
fltr_msg = ""
|
| 1197 |
+
if fltr:
|
| 1198 |
+
for fltrs in fltr:
|
| 1199 |
+
fltr_msg += "\n" + "`" + fltrs + "`"
|
| 1200 |
+
await update.reply_text(f"**Available Filters:** {fltr_msg}")
|
| 1201 |
+
else:
|
| 1202 |
+
await update.reply_text("No filters found")
|
| 1203 |
+
|
| 1204 |
+
|
| 1205 |
+
@Client.on_message(filters.command(["forcesub"]) & filters.user(ADMINS))
|
| 1206 |
+
async def force_sub(bot, update):
|
| 1207 |
+
data = update.text.split()
|
| 1208 |
+
if len(data) == 2:
|
| 1209 |
+
channel_str = data[-1]
|
| 1210 |
+
if channel_str.lower() == "off":
|
| 1211 |
+
await set_channel_link(None)
|
| 1212 |
+
await set_force_sub(0)
|
| 1213 |
+
await update.reply_text("Force Subscription disabled")
|
| 1214 |
+
return
|
| 1215 |
+
|
| 1216 |
+
try:
|
| 1217 |
+
resolved_ids, links_list = await parse_and_set_forcesub(bot, channel_str)
|
| 1218 |
+
await update.reply_text(f"Force subscription channels set to: `{', '.join(resolved_ids)}`. Links: {', '.join(links_list)}")
|
| 1219 |
+
except Exception as e:
|
| 1220 |
+
await update.reply_text(
|
| 1221 |
+
f"❌ Error setting force subscription: {str(e)}. Make sure the channels exist and the bot is added as an administrator."
|
| 1222 |
+
)
|
| 1223 |
+
|
| 1224 |
+
else:
|
| 1225 |
+
await update.reply_text(
|
| 1226 |
+
"Please send in proper format `/forcesub channel_id/off`"
|
| 1227 |
+
)
|
| 1228 |
+
|
| 1229 |
+
|
| 1230 |
+
@Client.on_message(filters.command(["logchannel"]) & filters.user(ADMINS))
|
| 1231 |
+
async def log_channel_(bot, update):
|
| 1232 |
+
data = update.text.split()
|
| 1233 |
+
if len(data) == 2:
|
| 1234 |
+
channel_str = data[-1]
|
| 1235 |
+
if channel_str.lower() == "off":
|
| 1236 |
+
await set_log_channel(None)
|
| 1237 |
+
await update.reply_text("User search logging disabled.")
|
| 1238 |
+
return
|
| 1239 |
+
|
| 1240 |
+
try:
|
| 1241 |
+
if channel_str.startswith("@"):
|
| 1242 |
+
channel_param = channel_str
|
| 1243 |
+
else:
|
| 1244 |
+
channel_param = int(channel_str)
|
| 1245 |
+
|
| 1246 |
+
chat = await bot.get_chat(channel_param)
|
| 1247 |
+
access_hash = None
|
| 1248 |
+
try:
|
| 1249 |
+
resolved = await bot.resolve_peer(chat.id)
|
| 1250 |
+
if getattr(resolved, "access_hash", None):
|
| 1251 |
+
access_hash = resolved.access_hash
|
| 1252 |
+
except Exception:
|
| 1253 |
+
pass
|
| 1254 |
+
await set_log_channel(chat.id, access_hash=access_hash)
|
| 1255 |
+
await update.reply_text(f"User search logging channel set to `{chat.id}` ({chat.title or 'Channel'}).")
|
| 1256 |
+
except Exception as e:
|
| 1257 |
+
await update.reply_text(
|
| 1258 |
+
f"❌ Error setting log channel: {str(e)}. Make sure the channel exists and the bot is added as an administrator."
|
| 1259 |
+
)
|
| 1260 |
+
else:
|
| 1261 |
+
await update.reply_text(
|
| 1262 |
+
"Please send in proper format `/logchannel channel_id/off`"
|
| 1263 |
+
)
|
| 1264 |
+
|
| 1265 |
+
|
| 1266 |
+
@Client.on_message(filters.command(["checklink"]) & filters.user(ADMINS))
|
| 1267 |
+
async def testlink(bot, update):
|
| 1268 |
+
link = await get_link()
|
| 1269 |
+
if link:
|
| 1270 |
+
await update.reply_text(f"Invite link for force subscription channel: {link}")
|
| 1271 |
+
else:
|
| 1272 |
+
await update.reply_text(
|
| 1273 |
+
"Force Subscription is disabled, please enable it first"
|
| 1274 |
+
)
|
| 1275 |
+
|
| 1276 |
+
|
| 1277 |
+
@Client.on_message(filters.command(["setusername"]) & filters.user(ADMINS))
|
| 1278 |
+
async def caption_username(bot, update):
|
| 1279 |
+
data = update.text.split()
|
| 1280 |
+
if len(data) == 2:
|
| 1281 |
+
username = data[-1]
|
| 1282 |
+
if username.lower() == "off":
|
| 1283 |
+
username = 0
|
| 1284 |
+
elif username.startswith("@"):
|
| 1285 |
+
username = username
|
| 1286 |
+
else:
|
| 1287 |
+
await update.reply_text("This is not a username, please check.")
|
| 1288 |
+
return
|
| 1289 |
+
|
| 1290 |
+
await set_username(username)
|
| 1291 |
+
|
| 1292 |
+
if username:
|
| 1293 |
+
await update.reply_text(f"File caption username set to `{username}`")
|
| 1294 |
+
else:
|
| 1295 |
+
await update.reply_text("File caption username disabled")
|
| 1296 |
+
|
| 1297 |
+
else:
|
| 1298 |
+
await update.reply_text(
|
| 1299 |
+
"Please send in proper format `/setusername username/off`"
|
| 1300 |
+
)
|
| 1301 |
+
|
| 1302 |
+
|
| 1303 |
+
@Client.on_message(filters.command(["total"]) & filters.user(ADMINS))
|
| 1304 |
+
async def count_f(bot, update):
|
| 1305 |
+
count = await count_files()
|
| 1306 |
+
await update.reply_text(f"**Total no. of files in DB:** `{count}`")
|
| 1307 |
+
|
| 1308 |
+
async def parse_and_set_forcesub(bot, channel_str):
|
| 1309 |
+
channels = [ch.strip() for ch in channel_str.split(',') if ch.strip()]
|
| 1310 |
+
resolved_ids = []
|
| 1311 |
+
hashes_map = {}
|
| 1312 |
+
links_list = []
|
| 1313 |
+
|
| 1314 |
+
for ch in channels:
|
| 1315 |
+
try:
|
| 1316 |
+
ch_param = int(ch)
|
| 1317 |
+
except ValueError:
|
| 1318 |
+
ch_param = ch if ch.startswith("@") else f"@{ch}"
|
| 1319 |
+
chat = await bot.get_chat(ch_param)
|
| 1320 |
+
resolved_ids.append(str(chat.id))
|
| 1321 |
+
|
| 1322 |
+
# Resolve access hash
|
| 1323 |
+
access_hash = None
|
| 1324 |
+
try:
|
| 1325 |
+
resolved = await bot.resolve_peer(chat.id)
|
| 1326 |
+
if getattr(resolved, "access_hash", None):
|
| 1327 |
+
access_hash = resolved.access_hash
|
| 1328 |
+
except Exception:
|
| 1329 |
+
pass
|
| 1330 |
+
if access_hash is not None:
|
| 1331 |
+
hashes_map[str(chat.id)] = access_hash
|
| 1332 |
+
|
| 1333 |
+
# Link resolving
|
| 1334 |
+
link = None
|
| 1335 |
+
try:
|
| 1336 |
+
link_obj = await bot.create_chat_invite_link(chat.id)
|
| 1337 |
+
link = link_obj.invite_link
|
| 1338 |
+
except Exception:
|
| 1339 |
+
if chat.username:
|
| 1340 |
+
link = f"https://t.me/{chat.username}"
|
| 1341 |
+
if link:
|
| 1342 |
+
links_list.append(link)
|
| 1343 |
+
|
| 1344 |
+
if not resolved_ids:
|
| 1345 |
+
raise ValueError("No valid channels could be resolved.")
|
| 1346 |
+
|
| 1347 |
+
from mfinder.db.settings_sql import set_force_sub_channels, set_channel_link
|
| 1348 |
+
await set_force_sub_channels(",".join(resolved_ids), hashes_map)
|
| 1349 |
+
if links_list:
|
| 1350 |
+
await set_channel_link(links_list[0])
|
| 1351 |
+
|
| 1352 |
+
return resolved_ids, links_list
|
| 1353 |
+
|
| 1354 |
+
|
| 1355 |
+
async def verify_user_token(bot, update, param):
|
| 1356 |
+
import time
|
| 1357 |
+
import asyncio
|
| 1358 |
+
|
| 1359 |
+
from mfinder import LOGGER
|
| 1360 |
+
from mfinder.db.settings_sql import get_user_token, activate_user_token, get_admin_settings, prune_all_expired_tokens
|
| 1361 |
+
|
| 1362 |
+
# Clean up any other expired or stale tokens
|
| 1363 |
+
await prune_all_expired_tokens()
|
| 1364 |
+
|
| 1365 |
+
user_id = update.from_user.id
|
| 1366 |
+
token_str = param
|
| 1367 |
+
|
| 1368 |
+
tok_rec = await get_user_token(user_id)
|
| 1369 |
+
|
| 1370 |
+
if not tok_rec or tok_rec.token != token_str:
|
| 1371 |
+
if tok_rec and tok_rec.req_msg_id:
|
| 1372 |
+
try:
|
| 1373 |
+
await bot.delete_messages(chat_id=user_id, message_ids=int(tok_rec.req_msg_id))
|
| 1374 |
+
except Exception as e:
|
| 1375 |
+
LOGGER.warning(f"Failed to delete original token request message: {e}")
|
| 1376 |
+
err_msg = await update.reply_text(
|
| 1377 |
+
"❌ **Invalid token link!**\n\nPlease search for a movie again to generate a new verification link.",
|
| 1378 |
+
quote=True
|
| 1379 |
+
)
|
| 1380 |
+
async def delete_after_delay(b, u_id, err_msg_id, incoming_msg_id):
|
| 1381 |
+
await asyncio.sleep(10)
|
| 1382 |
+
try:
|
| 1383 |
+
await b.delete_messages(chat_id=u_id, message_ids=[err_msg_id, incoming_msg_id])
|
| 1384 |
+
except Exception:
|
| 1385 |
+
pass
|
| 1386 |
+
asyncio.create_task(delete_after_delay(bot, user_id, err_msg.id, update.id))
|
| 1387 |
+
return
|
| 1388 |
+
|
| 1389 |
+
# Check if the token has already been claimed/activated
|
| 1390 |
+
if tok_rec.status == "active":
|
| 1391 |
+
if tok_rec.target_file_id:
|
| 1392 |
+
update.text = f"/start {tok_rec.target_file_id}"
|
| 1393 |
+
from mfinder.plugins.serve import get_files
|
| 1394 |
+
await get_files(bot, update)
|
| 1395 |
+
return
|
| 1396 |
+
elif tok_rec.search_query:
|
| 1397 |
+
from mfinder.plugins.serve import filter_
|
| 1398 |
+
update.text = tok_rec.search_query
|
| 1399 |
+
await filter_(bot, update)
|
| 1400 |
+
return
|
| 1401 |
+
else:
|
| 1402 |
+
await update.reply_text(
|
| 1403 |
+
"✅ **Token Verified Successfully!**\n\nYou already have direct, ad-free access to all movies and files.",
|
| 1404 |
+
quote=True
|
| 1405 |
+
)
|
| 1406 |
+
return
|
| 1407 |
+
|
| 1408 |
+
current_time = time.time()
|
| 1409 |
+
if tok_rec.status == "pending" and (current_time - float(tok_rec.created_at)) > 1800:
|
| 1410 |
+
if tok_rec.req_msg_id:
|
| 1411 |
+
try:
|
| 1412 |
+
await bot.delete_messages(chat_id=user_id, message_ids=int(tok_rec.req_msg_id))
|
| 1413 |
+
except Exception as e:
|
| 1414 |
+
LOGGER.warning(f"Failed to delete original token request message: {e}")
|
| 1415 |
+
from mfinder.db.settings_sql import delete_user_token
|
| 1416 |
+
await delete_user_token(user_id)
|
| 1417 |
+
err_msg = await update.reply_text(
|
| 1418 |
+
"❌ **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.",
|
| 1419 |
+
quote=True
|
| 1420 |
+
)
|
| 1421 |
+
async def delete_after_delay(b, u_id, err_msg_id, incoming_msg_id):
|
| 1422 |
+
await asyncio.sleep(10)
|
| 1423 |
+
try:
|
| 1424 |
+
await b.delete_messages(chat_id=u_id, message_ids=[err_msg_id, incoming_msg_id])
|
| 1425 |
+
except Exception:
|
| 1426 |
+
pass
|
| 1427 |
+
asyncio.create_task(delete_after_delay(bot, user_id, err_msg.id, update.id))
|
| 1428 |
+
return
|
| 1429 |
+
|
| 1430 |
+
admin_settings = await get_admin_settings()
|
| 1431 |
+
timeout = float(admin_settings.token_timeout) if admin_settings and admin_settings.token_timeout else 3600
|
| 1432 |
+
expires_at = current_time + timeout
|
| 1433 |
+
|
| 1434 |
+
success = await activate_user_token(user_id, expires_at)
|
| 1435 |
+
if success:
|
| 1436 |
+
try:
|
| 1437 |
+
from mfinder.db.settings_sql import advance_user_shortener_index
|
| 1438 |
+
await advance_user_shortener_index(user_id)
|
| 1439 |
+
except Exception as rot_err:
|
| 1440 |
+
LOGGER.warning(f"Error advancing smart rotator index: {rot_err}")
|
| 1441 |
+
if not success:
|
| 1442 |
+
await update.reply_text(
|
| 1443 |
+
"❌ **Verification failed due to database error!** Please try again later.",
|
| 1444 |
+
quote=True
|
| 1445 |
+
)
|
| 1446 |
+
return
|
| 1447 |
+
|
| 1448 |
+
if timeout >= 3600:
|
| 1449 |
+
hours = timeout / 3600
|
| 1450 |
+
time_desc = f"{hours:.1f} hours" if hours % 1 != 0 else f"{int(hours)} hours"
|
| 1451 |
+
elif timeout >= 60:
|
| 1452 |
+
mins = timeout / 60
|
| 1453 |
+
time_desc = f"{mins:.1f} minutes" if mins % 1 != 0 else f"{int(mins)} minutes"
|
| 1454 |
+
else:
|
| 1455 |
+
time_desc = f"{timeout} seconds"
|
| 1456 |
+
|
| 1457 |
+
if tok_rec.req_msg_id:
|
| 1458 |
+
try:
|
| 1459 |
+
await bot.delete_messages(chat_id=user_id, message_ids=int(tok_rec.req_msg_id))
|
| 1460 |
+
except Exception as e:
|
| 1461 |
+
LOGGER.warning(f"Failed to delete original token request message: {e}")
|
| 1462 |
+
|
| 1463 |
+
verified_msg = await update.reply_text(
|
| 1464 |
+
f"✅ **Token Verified Successfully!**\n\nYou now have direct, ad-free access to all movies and files for the next **{time_desc}**.\n\nEnjoy!",
|
| 1465 |
+
quote=True
|
| 1466 |
+
)
|
| 1467 |
+
|
| 1468 |
+
|
| 1469 |
+
async def delete_after_delay(b, u_id, success_msg_id, incoming_msg_id):
|
| 1470 |
+
await asyncio.sleep(10)
|
| 1471 |
+
try:
|
| 1472 |
+
await b.delete_messages(chat_id=u_id, message_ids=[success_msg_id, incoming_msg_id])
|
| 1473 |
+
except Exception as e:
|
| 1474 |
+
LOGGER.warning(f"Failed to auto-delete verification messages: {e}")
|
| 1475 |
+
|
| 1476 |
+
asyncio.create_task(delete_after_delay(bot, user_id, verified_msg.id, update.id))
|
| 1477 |
+
|
| 1478 |
+
search_q = tok_rec.search_query
|
| 1479 |
+
target_f_id = tok_rec.target_file_id
|
| 1480 |
+
|
| 1481 |
+
if search_q:
|
| 1482 |
+
try:
|
| 1483 |
+
from mfinder.plugins.serve import filter_
|
| 1484 |
+
update.text = search_q
|
| 1485 |
+
await asyncio.sleep(0.5)
|
| 1486 |
+
await filter_(bot, update)
|
| 1487 |
+
except Exception as e:
|
| 1488 |
+
LOGGER.warning(f"Error auto-resuming search query '{search_q}': {e}")
|
| 1489 |
+
elif target_f_id:
|
| 1490 |
+
try:
|
| 1491 |
+
from mfinder.plugins.serve import get_files
|
| 1492 |
+
update.text = f"/start {target_f_id}"
|
| 1493 |
+
await asyncio.sleep(0.5)
|
| 1494 |
+
await get_files(bot, update)
|
| 1495 |
+
except Exception as e:
|
| 1496 |
+
LOGGER.warning(f"Error auto-resuming file download for '{target_f_id}': {e}")
|
| 1497 |
+
|
| 1498 |
+
@Client.on_callback_query(filters.regex(r"^adm_rot_toggle_smart$") & filters.user(ADMINS))
|
| 1499 |
+
async def admin_rot_toggle_smart_callback(bot, query):
|
| 1500 |
+
from mfinder.db.settings_sql import get_admin_settings, set_smart_rotator_state, clear_all_user_shortener_usages
|
| 1501 |
+
admin_settings = await get_admin_settings()
|
| 1502 |
+
new_state = not getattr(admin_settings, "smart_rotator", False)
|
| 1503 |
+
await set_smart_rotator_state(new_state)
|
| 1504 |
+
try:
|
| 1505 |
+
from mfinder.db.settings_sql import clear_all_user_shortener_usages
|
| 1506 |
+
await clear_all_user_shortener_usages()
|
| 1507 |
+
except Exception:
|
| 1508 |
+
pass
|
| 1509 |
+
from mfinder.utils.helpers import clear_short_url_cache
|
| 1510 |
+
clear_short_url_cache()
|
| 1511 |
+
await query.answer(f"Smart Rotator {'ON' if new_state else 'OFF'}")
|
| 1512 |
+
text, keyboard = await get_settings_screen("sho")
|
| 1513 |
+
try:
|
| 1514 |
+
await query.message.edit_text(text=text, reply_markup=keyboard)
|
| 1515 |
+
except Exception:
|
| 1516 |
+
pass
|
| 1517 |
+
|
| 1518 |
+
@Client.on_callback_query(filters.regex(r"^adm_rot_manage:\d+$") & filters.user(ADMINS))
|
| 1519 |
+
async def admin_rot_manage_callback(bot, query):
|
| 1520 |
+
idx = int(query.data.split(":")[1])
|
| 1521 |
+
text, keyboard = await get_settings_screen(f"rot_manage:{idx}")
|
| 1522 |
+
try:
|
| 1523 |
+
await query.message.edit_text(text=text, reply_markup=keyboard)
|
| 1524 |
+
except Exception:
|
| 1525 |
+
pass
|
| 1526 |
+
await query.answer()
|
| 1527 |
+
|
| 1528 |
+
@Client.on_callback_query(filters.regex(r"^adm_rot_toggle:\d+$") & filters.user(ADMINS))
|
| 1529 |
+
async def admin_rot_toggle_callback(bot, query):
|
| 1530 |
+
idx = int(query.data.split(":")[1])
|
| 1531 |
+
import json
|
| 1532 |
+
from mfinder.db.settings_sql import get_admin_settings, update_shorteners_list
|
| 1533 |
+
admin_settings = await get_admin_settings()
|
| 1534 |
+
shorteners = get_all_shorteners(admin_settings)
|
| 1535 |
+
if idx < len(shorteners):
|
| 1536 |
+
shorteners[idx]["status"] = not shorteners[idx].get("status", True)
|
| 1537 |
+
await update_shorteners_list(json.dumps(shorteners))
|
| 1538 |
+
try:
|
| 1539 |
+
from mfinder.db.settings_sql import clear_all_user_shortener_usages
|
| 1540 |
+
await clear_all_user_shortener_usages()
|
| 1541 |
+
except Exception:
|
| 1542 |
+
pass
|
| 1543 |
+
from mfinder.utils.helpers import clear_short_url_cache
|
| 1544 |
+
clear_short_url_cache()
|
| 1545 |
+
await query.answer("Status toggled!")
|
| 1546 |
+
text, keyboard = await get_settings_screen(f"rot_manage:{idx}")
|
| 1547 |
+
try:
|
| 1548 |
+
await query.message.edit_text(text=text, reply_markup=keyboard)
|
| 1549 |
+
except Exception:
|
| 1550 |
+
pass
|
| 1551 |
+
|
| 1552 |
+
@Client.on_callback_query(filters.regex(r"^adm_rot_edit:\d+$") & filters.user(ADMINS))
|
| 1553 |
+
async def admin_rot_edit_callback(bot, query):
|
| 1554 |
+
idx = int(query.data.split(":")[1])
|
| 1555 |
+
user_id = query.from_user.id
|
| 1556 |
+
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
| 1557 |
+
ADMIN_INPUT_STATE[user_id] = {"action": f"edit_rotator_shortener:{idx}", "message_id": query.message.id}
|
| 1558 |
+
keyboard = InlineKeyboardMarkup([[InlineKeyboardButton("❌ Cancel", callback_data=f"adm_rot_manage:{idx}")]])
|
| 1559 |
+
await query.message.edit_text(
|
| 1560 |
+
text=f"⌨️ **Send the new details for Shortener #{idx+1} (format: `domain api_key tutorial_url`):**",
|
| 1561 |
+
reply_markup=keyboard
|
| 1562 |
+
)
|
| 1563 |
+
await query.answer()
|
| 1564 |
+
|
| 1565 |
+
@Client.on_callback_query(filters.regex(r"^adm_rot_delete:\d+$") & filters.user(ADMINS))
|
| 1566 |
+
async def admin_rot_delete_callback(bot, query):
|
| 1567 |
+
idx = int(query.data.split(":")[1])
|
| 1568 |
+
import json
|
| 1569 |
+
from mfinder.db.settings_sql import get_admin_settings, update_shorteners_list
|
| 1570 |
+
admin_settings = await get_admin_settings()
|
| 1571 |
+
shorteners = get_all_shorteners(admin_settings)
|
| 1572 |
+
if idx < len(shorteners):
|
| 1573 |
+
removed = shorteners.pop(idx)
|
| 1574 |
+
await update_shorteners_list(json.dumps(shorteners))
|
| 1575 |
+
try:
|
| 1576 |
+
from mfinder.db.settings_sql import clear_all_user_shortener_usages
|
| 1577 |
+
await clear_all_user_shortener_usages()
|
| 1578 |
+
except Exception:
|
| 1579 |
+
pass
|
| 1580 |
+
from mfinder.utils.helpers import clear_short_url_cache
|
| 1581 |
+
clear_short_url_cache()
|
| 1582 |
+
await query.answer(f"Removed {removed.get('site')}!")
|
| 1583 |
+
text, keyboard = await get_settings_screen("sho")
|
| 1584 |
+
try:
|
| 1585 |
+
await query.message.edit_text(text=text, reply_markup=keyboard)
|
| 1586 |
+
except Exception:
|
| 1587 |
+
pass
|
| 1588 |
+
|
| 1589 |
+
@Client.on_callback_query(filters.regex(r"^adm_rot_clear$") & filters.user(ADMINS))
|
| 1590 |
+
async def admin_rot_clear_callback(bot, query):
|
| 1591 |
+
from mfinder.db.settings_sql import update_shorteners_list
|
| 1592 |
+
await update_shorteners_list("[]")
|
| 1593 |
+
try:
|
| 1594 |
+
from mfinder.db.settings_sql import clear_all_user_shortener_usages
|
| 1595 |
+
await clear_all_user_shortener_usages()
|
| 1596 |
+
except Exception:
|
| 1597 |
+
pass
|
| 1598 |
+
from mfinder.utils.helpers import clear_short_url_cache
|
| 1599 |
+
clear_short_url_cache()
|
| 1600 |
+
await query.answer("All rotator shorteners cleared!")
|
| 1601 |
+
text, keyboard = await get_settings_screen("sho")
|
| 1602 |
+
try:
|
| 1603 |
+
await query.message.edit_text(text=text, reply_markup=keyboard)
|
| 1604 |
+
except Exception:
|
| 1605 |
+
pass
|
| 1606 |
+
|
| 1607 |
+
@Client.on_callback_query(filters.regex(r"^adm_rot_add$") & filters.user(ADMINS))
|
| 1608 |
+
async def admin_rot_add_callback(bot, query):
|
| 1609 |
+
user_id = query.from_user.id
|
| 1610 |
+
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
| 1611 |
+
ADMIN_INPUT_STATE[user_id] = {"action": "add_rotator_shortener", "message_id": query.message.id}
|
| 1612 |
+
keyboard = InlineKeyboardMarkup([[InlineKeyboardButton("❌ Cancel", callback_data="adm_cat:rot")]])
|
| 1613 |
+
await query.message.edit_text(
|
| 1614 |
+
text="⌨️ **Send the new shortener site, API key, and How to Download URL separated by spaces (e.g. `gplinks.in api_key_here https://t.me/tutorial`):**",
|
| 1615 |
+
reply_markup=keyboard
|
| 1616 |
+
)
|
| 1617 |
+
await query.answer()
|
mfinder/plugins/announcement.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import hashlib
|
| 3 |
+
import urllib.parse
|
| 4 |
+
import re
|
| 5 |
+
from mfinder import LOGGER
|
| 6 |
+
from mfinder.db.settings_sql import get_admin_settings
|
| 7 |
+
from mfinder.utils.helpers import encode_title
|
| 8 |
+
from mfinder.db.analytics_sql import extract_season
|
| 9 |
+
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
| 10 |
+
|
| 11 |
+
# Format: { "clean_title": { "year": "2026", "seasons": {"S1"}, "raw_names": [], "captions": [] } }
|
| 12 |
+
pending_batch = {}
|
| 13 |
+
batch_timer = None
|
| 14 |
+
batch_lock = asyncio.Lock()
|
| 15 |
+
|
| 16 |
+
async def queue_new_upload(bot, file_name, caption):
|
| 17 |
+
global batch_timer
|
| 18 |
+
from mfinder.db.files_sql import clean_movie_title
|
| 19 |
+
|
| 20 |
+
clean_title = clean_movie_title(file_name)
|
| 21 |
+
if not clean_title or len(clean_title) < 2:
|
| 22 |
+
return
|
| 23 |
+
|
| 24 |
+
# Extract year
|
| 25 |
+
year_match = re.search(r'\b(19\d{2}|20[0-2]\d|2030)\b', file_name)
|
| 26 |
+
year = year_match.group(1) if year_match else None
|
| 27 |
+
|
| 28 |
+
# Extract season
|
| 29 |
+
season = extract_season(file_name)
|
| 30 |
+
if not season and caption:
|
| 31 |
+
season = extract_season(caption)
|
| 32 |
+
|
| 33 |
+
async with batch_lock:
|
| 34 |
+
if clean_title not in pending_batch:
|
| 35 |
+
pending_batch[clean_title] = {
|
| 36 |
+
"year": year,
|
| 37 |
+
"seasons": set(),
|
| 38 |
+
"raw_names": [],
|
| 39 |
+
"captions": []
|
| 40 |
+
}
|
| 41 |
+
if season:
|
| 42 |
+
pending_batch[clean_title]["seasons"].add(season)
|
| 43 |
+
if not pending_batch[clean_title]["year"] and year:
|
| 44 |
+
pending_batch[clean_title]["year"] = year
|
| 45 |
+
pending_batch[clean_title]["raw_names"].append(file_name)
|
| 46 |
+
pending_batch[clean_title]["captions"].append(caption)
|
| 47 |
+
|
| 48 |
+
# Cancel existing timer
|
| 49 |
+
if batch_timer:
|
| 50 |
+
batch_timer.cancel()
|
| 51 |
+
|
| 52 |
+
# Start a new 6-second timer to wait for concurrent uploads
|
| 53 |
+
batch_timer = asyncio.create_task(wait_and_send_announcements(bot))
|
| 54 |
+
|
| 55 |
+
async def wait_and_send_announcements(bot):
|
| 56 |
+
try:
|
| 57 |
+
await asyncio.sleep(6) # Wait 6 seconds for any concurrent file transfers to finish
|
| 58 |
+
async with batch_lock:
|
| 59 |
+
if not pending_batch:
|
| 60 |
+
return
|
| 61 |
+
|
| 62 |
+
settings = await get_admin_settings()
|
| 63 |
+
if not settings or not getattr(settings, "announcement_enabled", False):
|
| 64 |
+
pending_batch.clear()
|
| 65 |
+
return
|
| 66 |
+
|
| 67 |
+
ann_channel = getattr(settings, "announcement_channel", None)
|
| 68 |
+
if not ann_channel:
|
| 69 |
+
pending_batch.clear()
|
| 70 |
+
return
|
| 71 |
+
|
| 72 |
+
bot_me = bot.me if hasattr(bot, "me") and bot.me else await bot.get_me()
|
| 73 |
+
bot_username = bot_me.username
|
| 74 |
+
|
| 75 |
+
# Process each movie/webseries in the batch
|
| 76 |
+
for title, info in list(pending_batch.items()):
|
| 77 |
+
year = info["year"]
|
| 78 |
+
seasons = info["seasons"]
|
| 79 |
+
|
| 80 |
+
# 1. Determine Display Title and Search Query
|
| 81 |
+
season_str = None
|
| 82 |
+
if seasons:
|
| 83 |
+
sorted_seasons = sorted(list(seasons), key=lambda s: int(s[1:]))
|
| 84 |
+
if len(sorted_seasons) > 1:
|
| 85 |
+
season_str = " & ".join(sorted_seasons)
|
| 86 |
+
else:
|
| 87 |
+
season_str = sorted_seasons[0]
|
| 88 |
+
|
| 89 |
+
display_title = f"{title} ({year})" if year else title
|
| 90 |
+
if season_str:
|
| 91 |
+
display_title = f"{display_title} {season_str}"
|
| 92 |
+
|
| 93 |
+
search_query = f"{title} {year}" if year else title
|
| 94 |
+
if season_str:
|
| 95 |
+
search_query = f"{search_query} {season_str}"
|
| 96 |
+
|
| 97 |
+
# 2. Get Highest Quality (HD or Theatre Print [Clear Audio] only)
|
| 98 |
+
from mfinder.utils.helpers import detect_file_quality
|
| 99 |
+
quality = "HD"
|
| 100 |
+
for fn in info["raw_names"]:
|
| 101 |
+
if detect_file_quality(fn) == "Theatre Print [Clear Audio]":
|
| 102 |
+
quality = "Theatre Print [Clear Audio]"
|
| 103 |
+
break
|
| 104 |
+
if quality == "HD" and info["captions"]:
|
| 105 |
+
for cap in info["captions"]:
|
| 106 |
+
if cap and detect_file_quality(cap) == "Theatre Print [Clear Audio]":
|
| 107 |
+
quality = "Theatre Print [Clear Audio]"
|
| 108 |
+
break
|
| 109 |
+
|
| 110 |
+
# Append quality tag
|
| 111 |
+
display_title = f"{display_title} {quality}"
|
| 112 |
+
|
| 113 |
+
# 3. Create Hyperlink Search Query Url
|
| 114 |
+
encoded = encode_title(search_query)
|
| 115 |
+
url = f"https://t.me/{bot_username}?start=q_{encoded}_ann"
|
| 116 |
+
|
| 117 |
+
# 4. Format Message Text and Inline Button
|
| 118 |
+
msg_text = f"✅ **[{display_title}]({url})**"
|
| 119 |
+
|
| 120 |
+
markup = InlineKeyboardMarkup([
|
| 121 |
+
[InlineKeyboardButton("⬇️ DOWNLOAD ⬇️", url=url)]
|
| 122 |
+
])
|
| 123 |
+
|
| 124 |
+
try:
|
| 125 |
+
await bot.send_message(
|
| 126 |
+
chat_id=int(ann_channel),
|
| 127 |
+
text=msg_text,
|
| 128 |
+
reply_markup=markup,
|
| 129 |
+
disable_web_page_preview=True
|
| 130 |
+
)
|
| 131 |
+
LOGGER.info(f"Successfully sent upload announcement for {display_title} to channel {ann_channel}")
|
| 132 |
+
except Exception as send_err:
|
| 133 |
+
LOGGER.warning(f"Failed to send announcement to channel {ann_channel}: {send_err}")
|
| 134 |
+
|
| 135 |
+
# Clear batch after processing
|
| 136 |
+
pending_batch.clear()
|
| 137 |
+
|
| 138 |
+
except asyncio.CancelledError:
|
| 139 |
+
pass
|
| 140 |
+
except Exception as e:
|
| 141 |
+
LOGGER.warning(f"Error in wait_and_send_announcements: {e}")
|
mfinder/plugins/broadcast.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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("broadcast") & filters.user(OWNER_ID)
|
| 15 |
+
)
|
| 16 |
+
async def send_text(bot, message: Message):
|
| 17 |
+
user_id = message.from_user.id
|
| 18 |
+
if "broadcast" in message.text and message.reply_to_message is not None:
|
| 19 |
+
start_time = time.time()
|
| 20 |
+
await message.reply_text("Starting broadcast, content below...")
|
| 21 |
+
await bot.copy_message(
|
| 22 |
+
chat_id=user_id,
|
| 23 |
+
from_chat_id=message.chat.id,
|
| 24 |
+
message_id=message.reply_to_message_id,
|
| 25 |
+
# caption=message.reply_to_message.caption,
|
| 26 |
+
reply_markup=message.reply_to_message.reply_markup,
|
| 27 |
+
)
|
| 28 |
+
query = await query_msg()
|
| 29 |
+
success = 0
|
| 30 |
+
failed = 0
|
| 31 |
+
for row in query:
|
| 32 |
+
chat_id = int(row[0])
|
| 33 |
+
br_msg = bool()
|
| 34 |
+
try:
|
| 35 |
+
br_msg = await bot.copy_message(
|
| 36 |
+
chat_id=chat_id,
|
| 37 |
+
from_chat_id=message.chat.id,
|
| 38 |
+
message_id=message.reply_to_message_id,
|
| 39 |
+
# caption=message.reply_to_message.caption,
|
| 40 |
+
reply_markup=message.reply_to_message.reply_markup,
|
| 41 |
+
)
|
| 42 |
+
LOGGER.info("Broadcast sent to %s", chat_id)
|
| 43 |
+
except FloodWait as e:
|
| 44 |
+
LOGGER.warning("Floodwait while broadcasting, sleeping for %s", e.value)
|
| 45 |
+
await asyncio.sleep(e.value)
|
| 46 |
+
except Exception as e:
|
| 47 |
+
from pyrogram.errors import UserBlocked, UserDeactivated, PeerIdInvalid, InputUserDeactivated
|
| 48 |
+
if isinstance(e, (UserBlocked, UserDeactivated, PeerIdInvalid, InputUserDeactivated)):
|
| 49 |
+
from mfinder.db.broadcast_sql import del_user
|
| 50 |
+
try:
|
| 51 |
+
await del_user(chat_id)
|
| 52 |
+
LOGGER.info(f"Deleted blocked/deactivated user id {chat_id} during broadcast")
|
| 53 |
+
except Exception:
|
| 54 |
+
pass
|
| 55 |
+
|
| 56 |
+
if bool(br_msg):
|
| 57 |
+
success += 1
|
| 58 |
+
else:
|
| 59 |
+
failed += 1
|
| 60 |
+
time_taken = datetime.timedelta(seconds=int(time.time() - start_time))
|
| 61 |
+
await message.reply_text(
|
| 62 |
+
f"**Broadcast Completed**\nSent to: `{success}`\nBlocked / Deleted: `{failed}`\nCompleted in `{time_taken}` HH:MM:SS"
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
else:
|
| 66 |
+
reply_error = (
|
| 67 |
+
"`Use this command as a reply to any telegram message without any spaces.`"
|
| 68 |
+
)
|
| 69 |
+
msg = await message.reply_text(reply_error, message.id)
|
| 70 |
+
await asyncio.sleep(8)
|
| 71 |
+
await msg.delete()
|
| 72 |
+
|
| 73 |
+
@Client.on_message(
|
| 74 |
+
filters.private & filters.command("stats") & filters.user(ADMINS)
|
| 75 |
+
)
|
| 76 |
+
async def get_subscribers_count(bot: Client, message: Message):
|
| 77 |
+
wait_msg = "__Calculating, please wait...__"
|
| 78 |
+
msg = await message.reply_text(wait_msg)
|
| 79 |
+
from mfinder.db.requests_sql import get_pending_requests_count
|
| 80 |
+
from mfinder.db.analytics_sql import get_today_active_users_count
|
| 81 |
+
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
| 82 |
+
active, blocked = await users_info(bot)
|
| 83 |
+
pending = await get_pending_requests_count()
|
| 84 |
+
today_users = await get_today_active_users_count()
|
| 85 |
+
stats_msg = (
|
| 86 |
+
"📊 **Interactive Analytics Dashboard**\n\n"
|
| 87 |
+
"👥 **Subscribers Stats:**\n"
|
| 88 |
+
f"• Active: `{active}`\n"
|
| 89 |
+
f"• Blocked / Deleted: `{blocked}`\n\n"
|
| 90 |
+
"⏳ **Movie Requests:**\n"
|
| 91 |
+
f"• Pending Requests: `{pending}`\n\n"
|
| 92 |
+
"🔥 **User Engagement:**\n"
|
| 93 |
+
f"• Today's Active Users: `{today_users}` *(Unique)*"
|
| 94 |
+
)
|
| 95 |
+
keyboard = InlineKeyboardMarkup([
|
| 96 |
+
[
|
| 97 |
+
InlineKeyboardButton("🔄 Refresh Stats", callback_data="dash_refresh"),
|
| 98 |
+
InlineKeyboardButton("❌ Close", callback_data="dash_close")
|
| 99 |
+
]
|
| 100 |
+
])
|
| 101 |
+
await msg.edit(stats_msg, reply_markup=keyboard)
|
| 102 |
+
|
| 103 |
+
@Client.on_callback_query(filters.regex(r"^dash_refresh$") & filters.user(ADMINS))
|
| 104 |
+
async def dash_refresh_callback(bot, query):
|
| 105 |
+
# Answer query first to prevent spinner timeout & QUERY_ID_INVALID errors
|
| 106 |
+
await query.answer("Refreshing stats, please wait...")
|
| 107 |
+
|
| 108 |
+
# Edit text immediately to show loading progress
|
| 109 |
+
try:
|
| 110 |
+
await query.message.edit_text("🔄 **Refreshing statistics, please wait...**")
|
| 111 |
+
except Exception:
|
| 112 |
+
pass
|
| 113 |
+
|
| 114 |
+
from mfinder.db.requests_sql import get_pending_requests_count
|
| 115 |
+
from mfinder.db.analytics_sql import get_today_active_users_count
|
| 116 |
+
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
| 117 |
+
|
| 118 |
+
active, blocked = await users_info(bot)
|
| 119 |
+
pending = await get_pending_requests_count()
|
| 120 |
+
today_users = await get_today_active_users_count()
|
| 121 |
+
|
| 122 |
+
stats_msg = (
|
| 123 |
+
"📊 **Interactive Analytics Dashboard**\n\n"
|
| 124 |
+
"👥 **Subscribers Stats:**\n"
|
| 125 |
+
f"• Active: `{active}`\n"
|
| 126 |
+
f"• Blocked / Deleted: `{blocked}`\n\n"
|
| 127 |
+
"⏳ **Movie Requests:**\n"
|
| 128 |
+
f"• Pending Requests: `{pending}`\n\n"
|
| 129 |
+
"🔥 **User Engagement:**\n"
|
| 130 |
+
f"• Today's Active Users: `{today_users}` *(Unique)*"
|
| 131 |
+
)
|
| 132 |
+
keyboard = InlineKeyboardMarkup([
|
| 133 |
+
[
|
| 134 |
+
InlineKeyboardButton("🔄 Refresh Stats", callback_data="dash_refresh"),
|
| 135 |
+
InlineKeyboardButton("❌ Close", callback_data="dash_close")
|
| 136 |
+
]
|
| 137 |
+
])
|
| 138 |
+
try:
|
| 139 |
+
await query.message.edit_text(stats_msg, reply_markup=keyboard)
|
| 140 |
+
except Exception:
|
| 141 |
+
pass
|
| 142 |
+
|
| 143 |
+
@Client.on_callback_query(filters.regex(r"^dash_close$") & filters.user(ADMINS))
|
| 144 |
+
async def dash_close_callback(bot, query):
|
| 145 |
+
await query.answer("Dashboard Closed.")
|
| 146 |
+
try:
|
| 147 |
+
await query.message.delete()
|
| 148 |
+
except Exception:
|
| 149 |
+
pass
|
mfinder/plugins/commands.py
ADDED
|
@@ -0,0 +1,522 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.db.analytics_sql import log_user_interaction
|
| 13 |
+
from mfinder.utils.util_support import humanbytes, get_db_size
|
| 14 |
+
from mfinder.plugins.serve import get_files
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
async def get_dynamic_start_kb(user_id=None):
|
| 18 |
+
from mfinder.db.settings_sql import get_admin_settings_sync
|
| 19 |
+
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
| 20 |
+
admin_settings = get_admin_settings_sync()
|
| 21 |
+
import json
|
| 22 |
+
import datetime
|
| 23 |
+
how_to_download_url = "https://telegram.me/FIREBOLTTutorial/23"
|
| 24 |
+
if admin_settings:
|
| 25 |
+
shorteners = []
|
| 26 |
+
if hasattr(admin_settings, "shorteners_list") and admin_settings.shorteners_list:
|
| 27 |
+
try:
|
| 28 |
+
shorteners = json.loads(admin_settings.shorteners_list)
|
| 29 |
+
except Exception:
|
| 30 |
+
pass
|
| 31 |
+
if not shorteners and admin_settings.shortener_site and admin_settings.shortener_api:
|
| 32 |
+
shorteners = [{
|
| 33 |
+
"site": admin_settings.shortener_site,
|
| 34 |
+
"api": admin_settings.shortener_api,
|
| 35 |
+
"how_to_download": admin_settings.how_to_download,
|
| 36 |
+
"status": admin_settings.shortener_status if admin_settings.shortener_status is not None else True
|
| 37 |
+
}]
|
| 38 |
+
active_shorteners = [s for s in shorteners if s.get("status", True)]
|
| 39 |
+
if active_shorteners:
|
| 40 |
+
target_idx = 0
|
| 41 |
+
smart_rotator_on = getattr(admin_settings, "smart_rotator", False)
|
| 42 |
+
if smart_rotator_on and user_id:
|
| 43 |
+
try:
|
| 44 |
+
local_now = datetime.datetime.utcnow() + datetime.timedelta(hours=5, minutes=30)
|
| 45 |
+
today_str = local_now.strftime("%Y-%m-%d")
|
| 46 |
+
from mfinder.db.settings_sql import get_user_shortener_index
|
| 47 |
+
saved_idx = await get_user_shortener_index(user_id, today_str)
|
| 48 |
+
target_idx = (saved_idx or 0) % len(active_shorteners)
|
| 49 |
+
except Exception:
|
| 50 |
+
target_idx = 0
|
| 51 |
+
if target_idx < len(active_shorteners):
|
| 52 |
+
how_to_download_url = active_shorteners[target_idx].get("how_to_download") or how_to_download_url
|
| 53 |
+
else:
|
| 54 |
+
how_to_download_url = active_shorteners[0].get("how_to_download") or how_to_download_url
|
| 55 |
+
elif admin_settings.how_to_download:
|
| 56 |
+
how_to_download_url = admin_settings.how_to_download
|
| 57 |
+
|
| 58 |
+
# Check newsletter subscription status and visibility
|
| 59 |
+
show_sub_btn = bool(getattr(admin_settings, "newsletter_enabled", False))
|
| 60 |
+
buttons_list = [
|
| 61 |
+
[
|
| 62 |
+
InlineKeyboardButton("🔥 Trending", callback_data="trnd_list"),
|
| 63 |
+
InlineKeyboardButton("🆕 New Uploads", callback_data="new_up_list"),
|
| 64 |
+
],
|
| 65 |
+
[
|
| 66 |
+
InlineKeyboardButton("🆘 Help", callback_data="help_cb"),
|
| 67 |
+
InlineKeyboardButton(
|
| 68 |
+
"📞 Contact", url="https://telegram.me/ANGRY_BIRD22_bot"
|
| 69 |
+
)
|
| 70 |
+
],
|
| 71 |
+
[
|
| 72 |
+
InlineKeyboardButton(
|
| 73 |
+
"❓ How To Download ❓", url=how_to_download_url
|
| 74 |
+
)
|
| 75 |
+
]
|
| 76 |
+
]
|
| 77 |
+
if show_sub_btn:
|
| 78 |
+
from mfinder.db.newsletter_sql import is_subscribed
|
| 79 |
+
subscribed = await is_subscribed(user_id) if user_id else False
|
| 80 |
+
sub_btn_text = "🔕 Unsubscribe from Updates" if subscribed else "🔔 Subscribe to Updates"
|
| 81 |
+
sub_callback = "nl_unsub" if subscribed else "nl_sub"
|
| 82 |
+
buttons_list.append([
|
| 83 |
+
InlineKeyboardButton(text=sub_btn_text, callback_data=sub_callback)
|
| 84 |
+
])
|
| 85 |
+
return InlineKeyboardMarkup(buttons_list)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@Client.on_message(filters.command(["start"]))
|
| 89 |
+
async def start(bot, update):
|
| 90 |
+
if len(update.command) == 1:
|
| 91 |
+
user_id = update.from_user.id
|
| 92 |
+
name = update.from_user.first_name if update.from_user.first_name else " "
|
| 93 |
+
user_name = (
|
| 94 |
+
"@" + update.from_user.username if update.from_user.username else None
|
| 95 |
+
)
|
| 96 |
+
await add_user(user_id, user_name)
|
| 97 |
+
|
| 98 |
+
try:
|
| 99 |
+
start_msg = START_MSG.format(name, user_id)
|
| 100 |
+
except Exception as e:
|
| 101 |
+
LOGGER.warning(e)
|
| 102 |
+
start_msg = STARTMSG.format(name, user_id)
|
| 103 |
+
|
| 104 |
+
await bot.send_message(
|
| 105 |
+
chat_id=update.chat.id,
|
| 106 |
+
text=start_msg,
|
| 107 |
+
reply_to_message_id=update.reply_to_message_id,
|
| 108 |
+
reply_markup=await get_dynamic_start_kb(user_id),
|
| 109 |
+
)
|
| 110 |
+
search_settings = await get_search_settings(user_id)
|
| 111 |
+
if not search_settings:
|
| 112 |
+
await change_search_settings(user_id, link_mode=True)
|
| 113 |
+
elif len(update.command) == 2:
|
| 114 |
+
param = update.command[1]
|
| 115 |
+
from mfinder.plugins.serve import verify_force_sub
|
| 116 |
+
if param.startswith("tok_"):
|
| 117 |
+
if not await verify_force_sub(bot, update):
|
| 118 |
+
return
|
| 119 |
+
|
| 120 |
+
# Support source tracking code attached to the token, e.g. tok_uuid_nl
|
| 121 |
+
parts = param.split('_')
|
| 122 |
+
token_str = parts[0] + "_" + parts[1]
|
| 123 |
+
source_code = parts[2] if len(parts) > 2 else None
|
| 124 |
+
|
| 125 |
+
source_label = None
|
| 126 |
+
if source_code == "nl":
|
| 127 |
+
source_label = "Newsletter Broadcast"
|
| 128 |
+
elif source_code == "req":
|
| 129 |
+
source_label = "Request Approval DM"
|
| 130 |
+
elif source_code == "tr":
|
| 131 |
+
source_label = "Trending List Link"
|
| 132 |
+
elif source_code == "nu":
|
| 133 |
+
source_label = "New Uploads Link"
|
| 134 |
+
|
| 135 |
+
if source_label:
|
| 136 |
+
update.search_source = source_label
|
| 137 |
+
|
| 138 |
+
from mfinder.plugins.admin_settings import verify_user_token
|
| 139 |
+
await verify_user_token(bot, update, token_str)
|
| 140 |
+
return
|
| 141 |
+
elif param.startswith("q_"):
|
| 142 |
+
try:
|
| 143 |
+
parts = param.split('_')
|
| 144 |
+
encoded = parts[1]
|
| 145 |
+
source_code = parts[2] if len(parts) > 2 else None
|
| 146 |
+
|
| 147 |
+
from mfinder.utils.helpers import decode_title
|
| 148 |
+
search_query = decode_title(encoded)
|
| 149 |
+
|
| 150 |
+
source_label = "Deep Link"
|
| 151 |
+
if source_code == "nl":
|
| 152 |
+
source_label = "Newsletter Broadcast"
|
| 153 |
+
elif source_code == "req":
|
| 154 |
+
source_label = "Request Approval DM"
|
| 155 |
+
elif source_code == "tr":
|
| 156 |
+
source_label = "Trending List Link"
|
| 157 |
+
elif source_code == "nu":
|
| 158 |
+
source_label = "New Uploads Link"
|
| 159 |
+
|
| 160 |
+
update.search_source = source_label
|
| 161 |
+
|
| 162 |
+
from mfinder.plugins.serve import filter_
|
| 163 |
+
update.text = search_query
|
| 164 |
+
await filter_(bot, update)
|
| 165 |
+
return
|
| 166 |
+
except Exception as e:
|
| 167 |
+
LOGGER.warning(f"Error decoding newsletter search query: {e}")
|
| 168 |
+
return
|
| 169 |
+
else:
|
| 170 |
+
if not await verify_force_sub(bot, update, pending_file_id=param):
|
| 171 |
+
return
|
| 172 |
+
user_id = update.from_user.id
|
| 173 |
+
from mfinder.db.settings_sql import get_admin_settings
|
| 174 |
+
admin_settings = await get_admin_settings()
|
| 175 |
+
if admin_settings and admin_settings.token_shortener_enabled:
|
| 176 |
+
from mfinder import ADMINS
|
| 177 |
+
if user_id not in ADMINS:
|
| 178 |
+
from mfinder.plugins.serve import is_token_valid, create_and_send_token_link
|
| 179 |
+
if not await is_token_valid(user_id):
|
| 180 |
+
await create_and_send_token_link(bot, update, admin_settings, target_file_id=param)
|
| 181 |
+
return
|
| 182 |
+
else:
|
| 183 |
+
# If Standard Shortener is active, advance smart rotator index upon successful file download start
|
| 184 |
+
try:
|
| 185 |
+
from mfinder.db.settings_sql import advance_user_shortener_index
|
| 186 |
+
await advance_user_shortener_index(user_id)
|
| 187 |
+
except Exception as rot_err:
|
| 188 |
+
LOGGER.warning(f"Error advancing smart rotator index in standard mode: {rot_err}")
|
| 189 |
+
await get_files(bot, update)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
@Client.on_message(filters.command(["help"]))
|
| 193 |
+
async def help_m(bot, update):
|
| 194 |
+
from mfinder.plugins.serve import verify_force_sub
|
| 195 |
+
if not await verify_force_sub(bot, update):
|
| 196 |
+
return
|
| 197 |
+
try:
|
| 198 |
+
help_msg = HELP_MSG
|
| 199 |
+
except Exception as e:
|
| 200 |
+
LOGGER.warning(e)
|
| 201 |
+
help_msg = HELPMSG
|
| 202 |
+
|
| 203 |
+
await bot.send_message(
|
| 204 |
+
chat_id=update.chat.id,
|
| 205 |
+
text=help_msg,
|
| 206 |
+
reply_to_message_id=update.reply_to_message_id,
|
| 207 |
+
reply_markup=HELP_KB,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
@Client.on_callback_query(filters.regex(r"^back_m$"))
|
| 212 |
+
async def back(bot, query):
|
| 213 |
+
from mfinder.plugins.serve import verify_force_sub
|
| 214 |
+
if not await verify_force_sub(bot, query):
|
| 215 |
+
return
|
| 216 |
+
user_id = query.from_user.id
|
| 217 |
+
name = query.from_user.first_name if query.from_user.first_name else " "
|
| 218 |
+
try:
|
| 219 |
+
start_msg = START_MSG.format(name, user_id)
|
| 220 |
+
except Exception as e:
|
| 221 |
+
LOGGER.warning(e)
|
| 222 |
+
start_msg = STARTMSG
|
| 223 |
+
await query.message.edit_text(start_msg, reply_markup=await get_dynamic_start_kb(user_id))
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@Client.on_callback_query(filters.regex(r"^help_cb$"))
|
| 227 |
+
async def help_cb(bot, query):
|
| 228 |
+
from mfinder.plugins.serve import verify_force_sub
|
| 229 |
+
if not await verify_force_sub(bot, query):
|
| 230 |
+
return
|
| 231 |
+
try:
|
| 232 |
+
help_msg = HELP_MSG
|
| 233 |
+
except Exception as e:
|
| 234 |
+
LOGGER.warning(e)
|
| 235 |
+
help_msg = HELPMSG
|
| 236 |
+
await query.message.edit_text(help_msg, reply_markup=HELP_KB)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
@Client.on_callback_query(filters.regex(r"^verify_fsub$"))
|
| 240 |
+
async def verify_fsub_cb(bot, query):
|
| 241 |
+
user_id = query.from_user.id
|
| 242 |
+
from mfinder.plugins.serve import verify_force_sub
|
| 243 |
+
if not await verify_force_sub(bot, query):
|
| 244 |
+
return
|
| 245 |
+
|
| 246 |
+
try:
|
| 247 |
+
await query.message.edit_reply_markup(reply_markup=None)
|
| 248 |
+
except Exception:
|
| 249 |
+
pass
|
| 250 |
+
|
| 251 |
+
from mfinder.db.settings_sql import get_pending_fsub_request, delete_pending_fsub_request
|
| 252 |
+
pending = await get_pending_fsub_request(user_id)
|
| 253 |
+
if not pending:
|
| 254 |
+
await query.answer("✅ Verification successful! You can now use the bot.", show_alert=True)
|
| 255 |
+
try:
|
| 256 |
+
await query.message.delete()
|
| 257 |
+
except Exception:
|
| 258 |
+
pass
|
| 259 |
+
return
|
| 260 |
+
|
| 261 |
+
try:
|
| 262 |
+
await query.message.delete()
|
| 263 |
+
except Exception:
|
| 264 |
+
pass
|
| 265 |
+
|
| 266 |
+
search_q = pending.search_query
|
| 267 |
+
target_f_id = pending.target_file_id
|
| 268 |
+
|
| 269 |
+
await delete_pending_fsub_request(user_id)
|
| 270 |
+
|
| 271 |
+
if search_q:
|
| 272 |
+
try:
|
| 273 |
+
from pyrogram.types import Message
|
| 274 |
+
mock_msg = Message(
|
| 275 |
+
id=query.message.id,
|
| 276 |
+
chat=query.message.chat,
|
| 277 |
+
from_user=query.from_user,
|
| 278 |
+
text=search_q,
|
| 279 |
+
date=query.message.date
|
| 280 |
+
)
|
| 281 |
+
mock_msg._client = bot
|
| 282 |
+
if search_q.startswith("/"):
|
| 283 |
+
if search_q == "/trending":
|
| 284 |
+
from mfinder.plugins.trending import trending_command
|
| 285 |
+
await trending_command(bot, mock_msg)
|
| 286 |
+
elif search_q == "/newuploads":
|
| 287 |
+
from mfinder.plugins.trending import new_uploads_command
|
| 288 |
+
await new_uploads_command(bot, mock_msg)
|
| 289 |
+
else:
|
| 290 |
+
from mfinder.plugins.serve import filter_
|
| 291 |
+
await filter_(bot, mock_msg)
|
| 292 |
+
except Exception as e:
|
| 293 |
+
LOGGER.warning(f"Error auto-resuming pending search '{search_q}': {e}")
|
| 294 |
+
elif target_f_id:
|
| 295 |
+
try:
|
| 296 |
+
from mfinder.plugins.serve import get_files
|
| 297 |
+
from pyrogram.types import Message
|
| 298 |
+
mock_msg = Message(
|
| 299 |
+
id=query.message.id,
|
| 300 |
+
chat=query.message.chat,
|
| 301 |
+
from_user=query.from_user,
|
| 302 |
+
text=f"/start {target_f_id}",
|
| 303 |
+
date=query.message.date
|
| 304 |
+
)
|
| 305 |
+
mock_msg._client = bot
|
| 306 |
+
await get_files(bot, mock_msg)
|
| 307 |
+
except Exception as e:
|
| 308 |
+
LOGGER.warning(f"Error auto-resuming pending download for '{target_f_id}': {e}")
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
@Client.on_message(filters.command(["restart"]) & filters.user(ADMINS))
|
| 312 |
+
async def restart(bot, update):
|
| 313 |
+
LOGGER.warning("Restarting bot using /restart command")
|
| 314 |
+
msg = await update.reply_text(text="__Restarting.....__")
|
| 315 |
+
await asyncio.sleep(5)
|
| 316 |
+
await msg.edit("__Bot restarted !__")
|
| 317 |
+
os.execv(sys.executable, ["python3", "-m", "mfinder"] + sys.argv)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
@Client.on_message(filters.command(["logs"]) & filters.user(ADMINS))
|
| 321 |
+
async def log_file(bot, update):
|
| 322 |
+
logs_msg = await update.reply("__Sending logs, please wait...__")
|
| 323 |
+
try:
|
| 324 |
+
await update.reply_document("logs.txt")
|
| 325 |
+
except Exception as e:
|
| 326 |
+
await update.reply(str(e))
|
| 327 |
+
await logs_msg.delete()
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
@Client.on_message(filters.command(["server"]) & filters.user(ADMINS))
|
| 331 |
+
async def server_stats(bot, update):
|
| 332 |
+
sts = await update.reply_text("__Calculating, please wait...__")
|
| 333 |
+
total, used, free = shutil.disk_usage(".")
|
| 334 |
+
ram = virtual_memory()
|
| 335 |
+
start_t = time.time()
|
| 336 |
+
end_t = time.time()
|
| 337 |
+
time_taken_s = (end_t - start_t) * 1000
|
| 338 |
+
|
| 339 |
+
ping = f"{time_taken_s:.3f} ms"
|
| 340 |
+
total = humanbytes(total)
|
| 341 |
+
used = humanbytes(used)
|
| 342 |
+
free = humanbytes(free)
|
| 343 |
+
t_ram = humanbytes(ram.total)
|
| 344 |
+
u_ram = humanbytes(ram.used)
|
| 345 |
+
f_ram = humanbytes(ram.available)
|
| 346 |
+
cpu_usage = cpu_percent()
|
| 347 |
+
ram_usage = virtual_memory().percent
|
| 348 |
+
used_disk = disk_usage("/").percent
|
| 349 |
+
db_size = get_db_size()
|
| 350 |
+
|
| 351 |
+
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`"
|
| 352 |
+
try:
|
| 353 |
+
await sts.edit(stats_msg)
|
| 354 |
+
except Exception as e:
|
| 355 |
+
await update.reply_text(str(e))
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
@Client.on_callback_query(filters.regex(r"^nl_sub$"))
|
| 359 |
+
async def nl_sub_cb(bot, query):
|
| 360 |
+
user_id = query.from_user.id
|
| 361 |
+
from mfinder.db.newsletter_sql import subscribe_user
|
| 362 |
+
await subscribe_user(user_id)
|
| 363 |
+
await query.answer("🎉 Successfully subscribed to Weekly Updates!", show_alert=True)
|
| 364 |
+
await query.message.edit_reply_markup(reply_markup=await get_dynamic_start_kb(user_id))
|
| 365 |
+
|
| 366 |
+
@Client.on_callback_query(filters.regex(r"^nl_unsub$"))
|
| 367 |
+
async def nl_unsub_cb(bot, query):
|
| 368 |
+
user_id = query.from_user.id
|
| 369 |
+
from mfinder.db.newsletter_sql import unsubscribe_user
|
| 370 |
+
await unsubscribe_user(user_id)
|
| 371 |
+
await query.answer("🔕 Successfully unsubscribed from Weekly Updates.", show_alert=True)
|
| 372 |
+
await query.message.edit_reply_markup(reply_markup=await get_dynamic_start_kb(user_id))
|
| 373 |
+
|
| 374 |
+
@Client.on_message(filters.command(["testshortener"]) & filters.user(ADMINS))
|
| 375 |
+
async def test_shortener_command(bot, update):
|
| 376 |
+
GOOGLE_PROXY_URL = os.environ.get("GOOGLE_PROXY_URL", "").strip()
|
| 377 |
+
from mfinder.db.settings_sql import get_admin_settings_sync
|
| 378 |
+
import json
|
| 379 |
+
import time
|
| 380 |
+
|
| 381 |
+
status_msg = await update.reply_text("\u23f3 Running diagnostic shortener test...", quote=True)
|
| 382 |
+
|
| 383 |
+
settings = get_admin_settings_sync()
|
| 384 |
+
if not settings:
|
| 385 |
+
await status_msg.edit("\u274c Error: No admin settings found in database.")
|
| 386 |
+
return
|
| 387 |
+
|
| 388 |
+
shorteners = []
|
| 389 |
+
if hasattr(settings, "shorteners_list") and settings.shorteners_list:
|
| 390 |
+
try:
|
| 391 |
+
shorteners = json.loads(settings.shorteners_list)
|
| 392 |
+
except Exception as e:
|
| 393 |
+
await status_msg.edit(f"\u274c Error decoding shorteners_list JSON: {e}")
|
| 394 |
+
return
|
| 395 |
+
|
| 396 |
+
if not shorteners:
|
| 397 |
+
await status_msg.edit("\u274c Error: No shorteners configured in database settings.")
|
| 398 |
+
return
|
| 399 |
+
|
| 400 |
+
diagnostic_output = []
|
| 401 |
+
diagnostic_output.append(f"\u2699\ufe0f **Admin Settings:**")
|
| 402 |
+
diagnostic_output.append(f"- Shortener Status: `{settings.shortener_status}`")
|
| 403 |
+
diagnostic_output.append(f"- Token Shortener Enabled: `{settings.token_shortener_enabled}`")
|
| 404 |
+
diagnostic_output.append(f"- Smart Rotator: `{settings.smart_rotator}`")
|
| 405 |
+
diagnostic_output.append(f"- Shorteners Configured Count: `{len(shorteners)}`")
|
| 406 |
+
diagnostic_output.append(f"- Google Proxy Configured: `{bool(GOOGLE_PROXY_URL)}`")
|
| 407 |
+
|
| 408 |
+
# Check curl_cffi availability
|
| 409 |
+
curl_requests = None
|
| 410 |
+
try:
|
| 411 |
+
from curl_cffi import requests as curl_requests
|
| 412 |
+
diagnostic_output.append(f"- curl_cffi: `Loaded (Chrome TLS fingerprint bypass active)`")
|
| 413 |
+
except ImportError:
|
| 414 |
+
diagnostic_output.append(f"- curl_cffi: `NOT INSTALLED (Cloudflare will likely block)`")
|
| 415 |
+
|
| 416 |
+
for idx, sh in enumerate(shorteners):
|
| 417 |
+
site = sh.get("site", "N/A")
|
| 418 |
+
api = sh.get("api", "N/A")
|
| 419 |
+
status = sh.get("status", True)
|
| 420 |
+
|
| 421 |
+
api_masked = api[:4] + "..." + api[-4:] if len(api) > 8 else "N/A"
|
| 422 |
+
diagnostic_output.append(f"\n\U0001f50d **Testing Shortener #{idx+1} ({site}):**")
|
| 423 |
+
diagnostic_output.append(f"- Status in DB: `{status}`")
|
| 424 |
+
diagnostic_output.append(f"- API Key: `{api_masked}`")
|
| 425 |
+
|
| 426 |
+
test_url = "https://telegram.me/ANGRY_BIRD22_bot?start=tok_diagnostic_test"
|
| 427 |
+
site_clean = site.strip().rstrip("/")
|
| 428 |
+
|
| 429 |
+
if not site_clean.startswith("http://") and not site_clean.startswith("https://"):
|
| 430 |
+
api_url = f"https://{site_clean}"
|
| 431 |
+
else:
|
| 432 |
+
api_url = site_clean
|
| 433 |
+
|
| 434 |
+
if not api_url.endswith("/api"):
|
| 435 |
+
api_url = f"{api_url}/api"
|
| 436 |
+
|
| 437 |
+
params = {
|
| 438 |
+
'url': test_url,
|
| 439 |
+
'api': api.strip(),
|
| 440 |
+
'format': 'json'
|
| 441 |
+
}
|
| 442 |
+
|
| 443 |
+
diagnostic_output.append(f"- Primary API Endpoint: `{api_url}`")
|
| 444 |
+
|
| 445 |
+
urls_to_try = [api_url]
|
| 446 |
+
if "shortxlinks.com" in api_url:
|
| 447 |
+
urls_to_try.append(api_url.replace("shortxlinks.com", "shortxlinks.in"))
|
| 448 |
+
urls_to_try.append(api_url.replace("shortxlinks.com", "shortxlinks.xyz"))
|
| 449 |
+
elif "shortxlinks.in" in api_url:
|
| 450 |
+
urls_to_try.append(api_url.replace("shortxlinks.in", "shortxlinks.com"))
|
| 451 |
+
urls_to_try.append(api_url.replace("shortxlinks.in", "shortxlinks.xyz"))
|
| 452 |
+
elif "shortxlinks.xyz" in api_url:
|
| 453 |
+
urls_to_try.append(api_url.replace("shortxlinks.xyz", "shortxlinks.com"))
|
| 454 |
+
urls_to_try.append(api_url.replace("shortxlinks.xyz", "shortxlinks.in"))
|
| 455 |
+
|
| 456 |
+
success = False
|
| 457 |
+
for u_idx, url in enumerate(urls_to_try):
|
| 458 |
+
is_mirror = u_idx > 0
|
| 459 |
+
label = "Mirror API" if is_mirror else "Primary API"
|
| 460 |
+
diagnostic_output.append(f" * Trying {label}: `{url}`")
|
| 461 |
+
|
| 462 |
+
t0 = time.time()
|
| 463 |
+
try:
|
| 464 |
+
if GOOGLE_PROXY_URL:
|
| 465 |
+
import urllib.parse
|
| 466 |
+
full_target_url = f"{url}?{urllib.parse.urlencode(params)}"
|
| 467 |
+
proxy_request_url = f"{GOOGLE_PROXY_URL}?url={urllib.parse.quote(full_target_url)}"
|
| 468 |
+
import requests
|
| 469 |
+
response = requests.get(proxy_request_url, timeout=20)
|
| 470 |
+
elif curl_requests:
|
| 471 |
+
response = curl_requests.get(url, params=params, impersonate="chrome", timeout=15)
|
| 472 |
+
else:
|
| 473 |
+
import requests
|
| 474 |
+
response = requests.get(url, params=params, timeout=15)
|
| 475 |
+
dt = time.time() - t0
|
| 476 |
+
diagnostic_output.append(f" - Response time: `{dt:.3f} seconds`")
|
| 477 |
+
diagnostic_output.append(f" - HTTP Status Code: `{response.status_code}`")
|
| 478 |
+
|
| 479 |
+
if response.status_code == 200:
|
| 480 |
+
try:
|
| 481 |
+
data = response.json()
|
| 482 |
+
short_link = (
|
| 483 |
+
data.get('shortenedUrl') or
|
| 484 |
+
data.get('shorturl') or
|
| 485 |
+
data.get('short_url') or
|
| 486 |
+
data.get('url') or
|
| 487 |
+
data.get('link') or
|
| 488 |
+
data.get('shortened_url') or
|
| 489 |
+
(data.get('data') and isinstance(data.get('data'), dict) and data['data'].get('url'))
|
| 490 |
+
)
|
| 491 |
+
if short_link:
|
| 492 |
+
diagnostic_output.append(f" - **\u2705 SUCCESS!** Shortened Link: `{short_link}`")
|
| 493 |
+
success = True
|
| 494 |
+
break
|
| 495 |
+
else:
|
| 496 |
+
diagnostic_output.append(f" - Warning: Failed to parse shortened link keys from JSON response.")
|
| 497 |
+
except Exception as json_err:
|
| 498 |
+
text_resp = response.text.strip()
|
| 499 |
+
if text_resp.startswith("http://") or text_resp.startswith("https://"):
|
| 500 |
+
diagnostic_output.append(f" - Plain-text URL found: `{text_resp}`")
|
| 501 |
+
success = True
|
| 502 |
+
break
|
| 503 |
+
|
| 504 |
+
if "window.location.reload()" in text_resp or "cf-challenge" in text_resp or "Turnstile" in text_resp:
|
| 505 |
+
diagnostic_output.append(f" - Warning: Cloudflare challenge page returned (likely blocked).")
|
| 506 |
+
else:
|
| 507 |
+
diagnostic_output.append(f" - Warning: Response is not JSON and not a plain URL: `{json_err}`")
|
| 508 |
+
diagnostic_output.append(f" - Response body (truncated): `{response.text[:150]}`")
|
| 509 |
+
else:
|
| 510 |
+
diagnostic_output.append(f" - Warning: Non-200 HTTP status.")
|
| 511 |
+
except Exception as req_err:
|
| 512 |
+
diagnostic_output.append(f" - Request error: `{type(req_err).__name__}: {req_err}`")
|
| 513 |
+
|
| 514 |
+
if not success:
|
| 515 |
+
diagnostic_output.append(f" * \u274c **ALL MIRRORS FAILED** - shortener did not return a valid shortened URL")
|
| 516 |
+
|
| 517 |
+
final_text = "\n".join(diagnostic_output)
|
| 518 |
+
if len(final_text) > 4000:
|
| 519 |
+
for x in range(0, len(final_text), 4000):
|
| 520 |
+
await update.reply_text(final_text[x:x+4000])
|
| 521 |
+
else:
|
| 522 |
+
await status_msg.edit(final_text)
|
mfinder/plugins/index.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 = None
|
| 38 |
+
chat_id = None
|
| 39 |
+
if hasattr(message, "forward_origin") and message.forward_origin:
|
| 40 |
+
origin = message.forward_origin
|
| 41 |
+
if hasattr(origin, "chat") and origin.chat:
|
| 42 |
+
chat_id = origin.chat.username or origin.chat.id
|
| 43 |
+
elif hasattr(origin, "sender_chat") and origin.sender_chat:
|
| 44 |
+
chat_id = origin.sender_chat.username or origin.sender_chat.id
|
| 45 |
+
elif hasattr(origin, "sender_user") and origin.sender_user:
|
| 46 |
+
chat_id = origin.sender_user.id
|
| 47 |
+
if hasattr(origin, "message_id"):
|
| 48 |
+
last_msg_id = origin.message_id
|
| 49 |
+
if not last_msg_id:
|
| 50 |
+
last_msg_id = getattr(message, "forward_from_message_id", None)
|
| 51 |
+
if not chat_id:
|
| 52 |
+
from_chat = getattr(message, "forward_from_chat", None)
|
| 53 |
+
if from_chat:
|
| 54 |
+
chat_id = from_chat.username or from_chat.id
|
| 55 |
+
if not last_msg_id or not chat_id:
|
| 56 |
+
raise ValueError("Could not extract chat details from the forwarded message.")
|
| 57 |
+
await bot.get_messages(chat_id, last_msg_id)
|
| 58 |
+
|
| 59 |
+
kb = InlineKeyboardMarkup(
|
| 60 |
+
[
|
| 61 |
+
[InlineKeyboardButton("Proceed", callback_data=f"index {chat_id} {last_msg_id}")],
|
| 62 |
+
[InlineKeyboardButton("Cancel", callback_data="can-index")],
|
| 63 |
+
]
|
| 64 |
+
)
|
| 65 |
+
await bot.send_message(user_id, "Please confirm if you want to start indexing", reply_markup=kb)
|
| 66 |
+
except Exception as e:
|
| 67 |
+
await message.reply_text(f"Unable to start indexing. Error: <code>{e}</code>")
|
| 68 |
+
|
| 69 |
+
@Client.on_callback_query(filters.regex(r"^index -?\d+ \d+"))
|
| 70 |
+
async def index(bot, query):
|
| 71 |
+
user_id = query.from_user.id
|
| 72 |
+
chat_id, last_msg_id = map(int, query.data.split()[1:])
|
| 73 |
+
await query.message.delete()
|
| 74 |
+
msg = await bot.send_message(user_id, "Processing Index...⏳")
|
| 75 |
+
total_files = 0
|
| 76 |
+
async with lock:
|
| 77 |
+
try:
|
| 78 |
+
total = last_msg_id + 1
|
| 79 |
+
current = 2
|
| 80 |
+
counter = 0
|
| 81 |
+
while True:
|
| 82 |
+
try:
|
| 83 |
+
message = await bot.get_messages(chat_id=chat_id, message_ids=current, replies=0)
|
| 84 |
+
except FloodWait as e:
|
| 85 |
+
LOGGER.warning("FloodWait while indexing, Error: %s", str(e))
|
| 86 |
+
await asyncio.sleep(e.value)
|
| 87 |
+
except Exception as e:
|
| 88 |
+
LOGGER.warning("Error occurred while fetching message: %s", str(e))
|
| 89 |
+
try:
|
| 90 |
+
for file_type in ("document", "video", "audio"):
|
| 91 |
+
media = getattr(message, file_type, None)
|
| 92 |
+
if not media:
|
| 93 |
+
break
|
| 94 |
+
file_name = media.file_name
|
| 95 |
+
file_name = edit_caption(file_name)
|
| 96 |
+
media.file_type = file_type
|
| 97 |
+
media.caption = message.caption if message.caption else file_name
|
| 98 |
+
await save_file(media)
|
| 99 |
+
total_files += 1
|
| 100 |
+
try:
|
| 101 |
+
from mfinder.plugins.requests import check_and_notify_pending_requests
|
| 102 |
+
asyncio.create_task(check_and_notify_pending_requests(bot, file_name))
|
| 103 |
+
except Exception as req_err:
|
| 104 |
+
LOGGER.warning(f"Failed to launch check_and_notify_pending_requests in index: {req_err}")
|
| 105 |
+
except Exception as e:
|
| 106 |
+
LOGGER.warning("Error occurred while saving file: %s", str(e))
|
| 107 |
+
|
| 108 |
+
current += 1
|
| 109 |
+
counter += 1
|
| 110 |
+
if counter == 50:
|
| 111 |
+
try:
|
| 112 |
+
await msg.edit(f"Total messages fetched: {current}\nTotal messages saved: {total_files}")
|
| 113 |
+
except FloodWait as e:
|
| 114 |
+
LOGGER.warning("FloodWait while indexing, sleeping for: %s", str(e.value))
|
| 115 |
+
await asyncio.sleep(e.value)
|
| 116 |
+
counter -= 50
|
| 117 |
+
if current == total:
|
| 118 |
+
break
|
| 119 |
+
except Exception as e:
|
| 120 |
+
LOGGER.exception(e)
|
| 121 |
+
await msg.edit(f"Error: {e}")
|
| 122 |
+
else:
|
| 123 |
+
await msg.edit(f"Total {total_files} Saved To DataBase!")
|
| 124 |
+
|
| 125 |
+
@Client.on_message(filters.command(["index"]) & filters.user(ADMINS))
|
| 126 |
+
async def index_comm(bot, update):
|
| 127 |
+
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.")
|
| 128 |
+
|
| 129 |
+
@Client.on_message(filters.command(["delete"]) & filters.user(ADMINS))
|
| 130 |
+
async def delete_files(bot, message):
|
| 131 |
+
if message.reply_to_message:
|
| 132 |
+
org_msg = message.reply_to_message
|
| 133 |
+
try:
|
| 134 |
+
for file_type in ("document", "video", "audio"):
|
| 135 |
+
media = getattr(org_msg, file_type, None)
|
| 136 |
+
if not media:
|
| 137 |
+
break
|
| 138 |
+
del_file = await delete_file(media)
|
| 139 |
+
if del_file == "Not Found":
|
| 140 |
+
await message.reply(f"❌ `{media.file_name}` not found in database")
|
| 141 |
+
elif del_file == True:
|
| 142 |
+
await message.reply(f"🗑️ `{media.file_name}` deleted from database")
|
| 143 |
+
else:
|
| 144 |
+
await message.reply(f"⚠️ Error occurred while deleting `{media.file_name}`")
|
| 145 |
+
except Exception as e:
|
| 146 |
+
LOGGER.warning("Error occurred while deleting file: %s", str(e))
|
| 147 |
+
else:
|
| 148 |
+
user_id = message.from_user.id
|
| 149 |
+
DELETING_USERS.add(user_id)
|
| 150 |
+
await message.reply(
|
| 151 |
+
"🧹 **Bulk Delete Mode Activated!**\n\n"
|
| 152 |
+
"Please send or forward all the files you want to delete from the database. "
|
| 153 |
+
"I will delete them one-by-one automatically.\n\n"
|
| 154 |
+
"When you are finished, type `/done` to turn off this mode."
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
@Client.on_message(filters.command(["done"]) & filters.user(ADMINS))
|
| 158 |
+
async def done_deleting(bot, message):
|
| 159 |
+
user_id = message.from_user.id
|
| 160 |
+
if user_id in DELETING_USERS:
|
| 161 |
+
DELETING_USERS.remove(user_id)
|
| 162 |
+
await message.reply("🧹 **Bulk Delete Mode Deactivated!**")
|
| 163 |
+
else:
|
| 164 |
+
await message.reply("❌ You are not currently in bulk delete mode.")
|
| 165 |
+
|
| 166 |
+
@Client.on_callback_query(filters.regex(r"^can-index$"))
|
| 167 |
+
async def cancel_index(bot, query):
|
| 168 |
+
await query.message.delete()
|
mfinder/plugins/live_index.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
from pyrogram import Client, filters
|
| 3 |
+
from mfinder import DB_CHANNELS, LOGGER
|
| 4 |
+
from mfinder.db.files_sql import save_file
|
| 5 |
+
from mfinder.utils.helpers import edit_caption
|
| 6 |
+
|
| 7 |
+
media_filter = filters.document | filters.video | filters.audio
|
| 8 |
+
|
| 9 |
+
@Client.on_message(filters.chat(DB_CHANNELS) & media_filter)
|
| 10 |
+
async def live_index(bot, message):
|
| 11 |
+
try:
|
| 12 |
+
media = None
|
| 13 |
+
file_type = None
|
| 14 |
+
for t in ("document", "video", "audio"):
|
| 15 |
+
m = getattr(message, t, None)
|
| 16 |
+
if m:
|
| 17 |
+
media = m
|
| 18 |
+
file_type = t
|
| 19 |
+
break
|
| 20 |
+
|
| 21 |
+
if not media:
|
| 22 |
+
return
|
| 23 |
+
|
| 24 |
+
file_name = media.file_name
|
| 25 |
+
file_name = edit_caption(file_name)
|
| 26 |
+
media.file_type = file_type
|
| 27 |
+
media.caption = message.caption if message.caption else file_name
|
| 28 |
+
|
| 29 |
+
# Save to database
|
| 30 |
+
saved = await save_file(media)
|
| 31 |
+
if saved:
|
| 32 |
+
try:
|
| 33 |
+
from mfinder.plugins.requests import check_and_notify_pending_requests
|
| 34 |
+
asyncio.create_task(check_and_notify_pending_requests(bot, file_name))
|
| 35 |
+
except Exception as req_err:
|
| 36 |
+
LOGGER.warning(f"Failed to launch check_and_notify_pending_requests in live_index: {req_err}")
|
| 37 |
+
|
| 38 |
+
# Trigger Upload Announcement
|
| 39 |
+
try:
|
| 40 |
+
from mfinder.plugins.announcement import queue_new_upload
|
| 41 |
+
asyncio.create_task(queue_new_upload(bot, file_name, media.caption))
|
| 42 |
+
except Exception as ann_err:
|
| 43 |
+
LOGGER.warning(f"Failed to queue new upload announcement in live_index: {ann_err}")
|
| 44 |
+
|
| 45 |
+
except Exception as e:
|
| 46 |
+
LOGGER.warning("Error occurred while saving file: %s", str(e))
|
mfinder/plugins/newsletter.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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db.newsletter_sql import get_all_subscribers
|
| 7 |
+
from mfinder.db.analytics_sql import get_latest_uploaded_movies
|
| 8 |
+
from mfinder.utils.helpers import encode_title
|
| 9 |
+
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
| 10 |
+
from pyrogram.errors import FloodWait, UserDeactivated, PeerIdInvalid, ChatWriteForbidden
|
| 11 |
+
|
| 12 |
+
# Keep track of last sent date to prevent duplicate broadcasts on the same day
|
| 13 |
+
last_sent_date = None
|
| 14 |
+
|
| 15 |
+
async def start_newsletter_loop(bot):
|
| 16 |
+
global last_sent_date
|
| 17 |
+
LOGGER.info("Starting newsletter scheduler background task...")
|
| 18 |
+
while True:
|
| 19 |
+
try:
|
| 20 |
+
await asyncio.sleep(60)
|
| 21 |
+
|
| 22 |
+
settings = await get_admin_settings()
|
| 23 |
+
if not settings or not getattr(settings, "newsletter_enabled", False):
|
| 24 |
+
continue
|
| 25 |
+
|
| 26 |
+
# Get current time adjusted to IST (UTC+5:30) since admin settings are in IST
|
| 27 |
+
utc_now = datetime.datetime.utcnow()
|
| 28 |
+
now = utc_now + datetime.timedelta(hours=5, minutes=30)
|
| 29 |
+
|
| 30 |
+
today_date_str = now.strftime("%Y-%m-%d")
|
| 31 |
+
current_day = now.strftime("%A")
|
| 32 |
+
|
| 33 |
+
configured_days = [d.strip().lower() for d in settings.newsletter_days.split(",") if d.strip()]
|
| 34 |
+
if current_day.lower() not in configured_days:
|
| 35 |
+
continue
|
| 36 |
+
|
| 37 |
+
# Parse configured time (HH:MM)
|
| 38 |
+
try:
|
| 39 |
+
conf_hour, conf_minute = map(int, settings.newsletter_time.strip().split(":"))
|
| 40 |
+
except Exception:
|
| 41 |
+
continue
|
| 42 |
+
|
| 43 |
+
scheduled_datetime = datetime.datetime(now.year, now.month, now.day, conf_hour, conf_minute)
|
| 44 |
+
|
| 45 |
+
# If current local time is before the scheduled broadcast time, wait
|
| 46 |
+
if now < scheduled_datetime:
|
| 47 |
+
continue
|
| 48 |
+
|
| 49 |
+
# If already sent today, skip
|
| 50 |
+
if last_sent_date == today_date_str:
|
| 51 |
+
continue
|
| 52 |
+
|
| 53 |
+
# Safety check: if we are more than 30 minutes past the scheduled time (e.g. late boot), skip
|
| 54 |
+
if now > scheduled_datetime + datetime.timedelta(minutes=30):
|
| 55 |
+
continue
|
| 56 |
+
|
| 57 |
+
last_sent_date = today_date_str
|
| 58 |
+
LOGGER.info(f"Triggering weekly newsletter for day={current_day} time={settings.newsletter_time}...")
|
| 59 |
+
|
| 60 |
+
limit = int(settings.newsletter_count) if settings.newsletter_count else 10
|
| 61 |
+
movies = await get_latest_uploaded_movies(limit=limit)
|
| 62 |
+
if not movies:
|
| 63 |
+
LOGGER.info("Newsletter skipped: No newly uploaded movies found.")
|
| 64 |
+
await asyncio.sleep(65)
|
| 65 |
+
continue
|
| 66 |
+
|
| 67 |
+
movie_titles = [f"{t} ({y})" if y else t for t, c, y in movies]
|
| 68 |
+
LOGGER.info(f"Newsletter movies to broadcast: {', '.join(movie_titles)}")
|
| 69 |
+
|
| 70 |
+
bot_me = bot.me if hasattr(bot, "me") and bot.me else await bot.get_me()
|
| 71 |
+
bot_username = bot_me.username
|
| 72 |
+
|
| 73 |
+
msg_text = (
|
| 74 |
+
f"🆕 **Weekly Top Uploads Digest!**\n\n"
|
| 75 |
+
f"Here are the latest **{len(movies)}** movies uploaded recently. "
|
| 76 |
+
f"Tap any movie link below (or use the buttons) to get your download links instantly:\n\n"
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
from mfinder.db.analytics_sql import get_movie_quality_sync
|
| 80 |
+
buttons = []
|
| 81 |
+
for item in movies:
|
| 82 |
+
title = item[0]
|
| 83 |
+
count = item[1]
|
| 84 |
+
year = item[2] if len(item) > 2 else None
|
| 85 |
+
season_str = item[3] if len(item) > 3 else None
|
| 86 |
+
|
| 87 |
+
display_title = f"{title} ({year})" if year else title
|
| 88 |
+
if season_str:
|
| 89 |
+
display_title = f"{display_title} {season_str}"
|
| 90 |
+
|
| 91 |
+
search_query = f"{title} {year}" if year else title
|
| 92 |
+
if season_str:
|
| 93 |
+
search_query = f"{search_query} {season_str}"
|
| 94 |
+
|
| 95 |
+
encoded = encode_title(search_query)
|
| 96 |
+
url = f"https://t.me/{bot_username}?start=q_{encoded}_nl"
|
| 97 |
+
|
| 98 |
+
# Fetch quality classification
|
| 99 |
+
quality = await asyncio.to_thread(get_movie_quality_sync, title)
|
| 100 |
+
|
| 101 |
+
msg_text += f"• [{display_title}]({url}) - {quality}\n"
|
| 102 |
+
buttons.append([InlineKeyboardButton(text=f"🎬 {display_title}", url=url)])
|
| 103 |
+
|
| 104 |
+
markup = InlineKeyboardMarkup(buttons)
|
| 105 |
+
|
| 106 |
+
target_audience = getattr(settings, "newsletter_target", "subscribed")
|
| 107 |
+
if target_audience == "all":
|
| 108 |
+
from mfinder.db.broadcast_sql import query_msg
|
| 109 |
+
all_users_res = await query_msg()
|
| 110 |
+
subscribers = [r[0] for r in all_users_res] if all_users_res else []
|
| 111 |
+
else:
|
| 112 |
+
subscribers = await get_all_subscribers()
|
| 113 |
+
if not subscribers:
|
| 114 |
+
LOGGER.info("Newsletter skipped: No subscribers found.")
|
| 115 |
+
await asyncio.sleep(65)
|
| 116 |
+
continue
|
| 117 |
+
|
| 118 |
+
LOGGER.info(f"Sending newsletter to {len(subscribers)} subscribers...")
|
| 119 |
+
|
| 120 |
+
sent_count = 0
|
| 121 |
+
fail_count = 0
|
| 122 |
+
for user_id in subscribers:
|
| 123 |
+
try:
|
| 124 |
+
await bot.send_message(
|
| 125 |
+
chat_id=user_id,
|
| 126 |
+
text=msg_text,
|
| 127 |
+
reply_markup=markup,
|
| 128 |
+
disable_web_page_preview=True
|
| 129 |
+
)
|
| 130 |
+
sent_count += 1
|
| 131 |
+
await asyncio.sleep(0.05)
|
| 132 |
+
except FloodWait as fw:
|
| 133 |
+
await asyncio.sleep(fw.value + 1)
|
| 134 |
+
try:
|
| 135 |
+
await bot.send_message(
|
| 136 |
+
chat_id=user_id,
|
| 137 |
+
text=msg_text,
|
| 138 |
+
reply_markup=markup,
|
| 139 |
+
disable_web_page_preview=True
|
| 140 |
+
)
|
| 141 |
+
sent_count += 1
|
| 142 |
+
except Exception:
|
| 143 |
+
fail_count += 1
|
| 144 |
+
except (UserDeactivated, PeerIdInvalid, ChatWriteForbidden):
|
| 145 |
+
from mfinder.db.newsletter_sql import unsubscribe_user
|
| 146 |
+
await unsubscribe_user(user_id)
|
| 147 |
+
fail_count += 1
|
| 148 |
+
except Exception:
|
| 149 |
+
fail_count += 1
|
| 150 |
+
|
| 151 |
+
LOGGER.info(f"Newsletter broadcast completed: Sent to {sent_count} users, Failed/Unsubscribed {fail_count} users.")
|
| 152 |
+
|
| 153 |
+
# Send summary report to log channel if set
|
| 154 |
+
log_channel = getattr(settings, "log_channel", None)
|
| 155 |
+
if log_channel:
|
| 156 |
+
try:
|
| 157 |
+
log_text = (
|
| 158 |
+
"📰 **Newsletter Sent Summary**\n\n"
|
| 159 |
+
f"📅 **Weekday/Time (IST):** `{current_day} {settings.newsletter_time}`\n"
|
| 160 |
+
f"🎯 **Target Audience:** `{'All Users' if target_audience == 'all' else 'Subscribed Users Only'}`\n"
|
| 161 |
+
f"✅ **Delivered to:** `{sent_count}` users\n"
|
| 162 |
+
f"❌ **Failed/Unsubscribed:** `{fail_count}` users\n\n"
|
| 163 |
+
f"🎬 **Included Movies ({len(movies)}):**\n"
|
| 164 |
+
)
|
| 165 |
+
for i, item in enumerate(movies):
|
| 166 |
+
title = item[0]
|
| 167 |
+
year = item[2] if len(item) > 2 else None
|
| 168 |
+
season_str = item[3] if len(item) > 3 else None
|
| 169 |
+
display_title = f"{title} ({year})" if year else title
|
| 170 |
+
if season_str:
|
| 171 |
+
display_title = f"{display_title} {season_str}"
|
| 172 |
+
log_text += f"{i+1}. `{display_title}`\n"
|
| 173 |
+
|
| 174 |
+
await bot.send_message(
|
| 175 |
+
chat_id=int(log_channel),
|
| 176 |
+
text=log_text
|
| 177 |
+
)
|
| 178 |
+
except Exception as log_err:
|
| 179 |
+
LOGGER.warning(f"Failed to send newsletter summary to log channel: {log_err}")
|
| 180 |
+
await asyncio.sleep(65)
|
| 181 |
+
|
| 182 |
+
except Exception as e:
|
| 183 |
+
LOGGER.warning(f"Error in newsletter background task: {e}\n{traceback.format_exc()}")
|
mfinder/plugins/requests.py
ADDED
|
@@ -0,0 +1,588 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import hashlib
|
| 3 |
+
import logging
|
| 4 |
+
import asyncio
|
| 5 |
+
from pyrogram import Client, filters
|
| 6 |
+
from pyrogram.enums import ParseMode, ChatType
|
| 7 |
+
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, ForceReply
|
| 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 |
+
get_all_pending_requests,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
# In-memory LRU-style cache mapping 12-char hashes to search queries to keep callback data < 64 bytes
|
| 20 |
+
class SimpleCache:
|
| 21 |
+
def __init__(self, maxsize=500):
|
| 22 |
+
self.cache = {}
|
| 23 |
+
self.maxsize = maxsize
|
| 24 |
+
|
| 25 |
+
def get(self, key):
|
| 26 |
+
return self.cache.get(key)
|
| 27 |
+
|
| 28 |
+
def set(self, key, value):
|
| 29 |
+
if len(self.cache) >= self.maxsize:
|
| 30 |
+
first_key = next(iter(self.cache))
|
| 31 |
+
del self.cache[first_key]
|
| 32 |
+
self.cache[key] = value
|
| 33 |
+
|
| 34 |
+
REQUEST_QUERY_CACHE = SimpleCache()
|
| 35 |
+
|
| 36 |
+
async def send_request_to_channel(bot, user, query_text: str, req_id: int):
|
| 37 |
+
"""Sends a formatted movie request card with Admin action buttons to the Log Channel."""
|
| 38 |
+
try:
|
| 39 |
+
log_channel_id = await get_log_channel()
|
| 40 |
+
if not log_channel_id:
|
| 41 |
+
return None
|
| 42 |
+
|
| 43 |
+
user_id = user.id
|
| 44 |
+
first_name = user.first_name or ""
|
| 45 |
+
last_name = user.last_name or ""
|
| 46 |
+
full_name = f"{first_name} {last_name}".strip()
|
| 47 |
+
username = f"@{user.username}" if user.username else "N/A"
|
| 48 |
+
|
| 49 |
+
def escape_html(text):
|
| 50 |
+
if not text:
|
| 51 |
+
return ""
|
| 52 |
+
return str(text).replace("&", "&").replace("<", "<").replace(">", ">")
|
| 53 |
+
|
| 54 |
+
full_name_esc = escape_html(full_name)
|
| 55 |
+
first_name_esc = escape_html(first_name)
|
| 56 |
+
username_esc = escape_html(username)
|
| 57 |
+
query_esc = escape_html(query_text)
|
| 58 |
+
|
| 59 |
+
log_msg = (
|
| 60 |
+
f"📩 <b>New Movie Request!</b>\n\n"
|
| 61 |
+
f"👤 <b>User Details:</b>\n"
|
| 62 |
+
f"• <b>User ID:</b> <code>{user_id}</code>\n"
|
| 63 |
+
f"• <b>Name:</b> {full_name_esc}\n"
|
| 64 |
+
f"• <b>Username:</b> {username_esc}\n"
|
| 65 |
+
f"• <b>Mention:</b> <a href=\"tg://user?id={user_id}\">{first_name_esc}</a>\n\n"
|
| 66 |
+
f"🎬 <b>Requested Movie:</b> <code>{query_esc}</code>\n"
|
| 67 |
+
f"🆔 <b>Request ID:</b> <code>#{req_id}</code>\n"
|
| 68 |
+
f"📊 <b>Status:</b> ⏳ <code>Pending</code>"
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
buttons = InlineKeyboardMarkup([
|
| 72 |
+
[
|
| 73 |
+
InlineKeyboardButton("✅ Mark Uploaded & Notify", callback_data=f"req_appr {req_id}"),
|
| 74 |
+
InlineKeyboardButton("❌ Reject", callback_data=f"req_rejc {req_id}")
|
| 75 |
+
],
|
| 76 |
+
[
|
| 77 |
+
InlineKeyboardButton("💬 Message User", callback_data=f"req_msg {req_id}")
|
| 78 |
+
]
|
| 79 |
+
])
|
| 80 |
+
|
| 81 |
+
target_chat_id = int(log_channel_id)
|
| 82 |
+
sent_msg = None
|
| 83 |
+
try:
|
| 84 |
+
sent_msg = await bot.send_message(
|
| 85 |
+
chat_id=target_chat_id,
|
| 86 |
+
text=log_msg,
|
| 87 |
+
reply_markup=buttons,
|
| 88 |
+
parse_mode=ParseMode.HTML
|
| 89 |
+
)
|
| 90 |
+
except Exception as send_err:
|
| 91 |
+
# If peer resolution fails (e.g. after container restart), refresh dialogs & retry
|
| 92 |
+
try:
|
| 93 |
+
async for _ in bot.get_dialogs(limit=100):
|
| 94 |
+
pass
|
| 95 |
+
sent_msg = await bot.send_message(
|
| 96 |
+
chat_id=target_chat_id,
|
| 97 |
+
text=log_msg,
|
| 98 |
+
reply_markup=buttons,
|
| 99 |
+
parse_mode=ParseMode.HTML
|
| 100 |
+
)
|
| 101 |
+
except Exception as retry_err:
|
| 102 |
+
LOGGER.warning(f"Failed to send request card to channel ({log_channel_id}): {retry_err}")
|
| 103 |
+
|
| 104 |
+
if sent_msg:
|
| 105 |
+
await update_request_status(req_id, "Pending", channel_msg_id=sent_msg.id)
|
| 106 |
+
return sent_msg.id
|
| 107 |
+
except Exception as e:
|
| 108 |
+
LOGGER.warning(f"Error sending request card to log channel: {e}")
|
| 109 |
+
return None
|
| 110 |
+
|
| 111 |
+
@Client.on_message(filters.command(["request"]))
|
| 112 |
+
async def request_command(bot, message):
|
| 113 |
+
from mfinder.plugins.serve import verify_force_sub
|
| 114 |
+
if not await verify_force_sub(bot, message, pending_query=message.text):
|
| 115 |
+
return
|
| 116 |
+
user = message.from_user
|
| 117 |
+
if len(message.command) < 2:
|
| 118 |
+
await message.reply_text(
|
| 119 |
+
"⚠️ **Please provide a movie name to request!**\n\n"
|
| 120 |
+
"**Example:** `/request Kantara Chapter 1`",
|
| 121 |
+
quote=True,
|
| 122 |
+
parse_mode=ParseMode.MARKDOWN
|
| 123 |
+
)
|
| 124 |
+
return
|
| 125 |
+
|
| 126 |
+
query_text = message.text.split(None, 1)[1].strip()
|
| 127 |
+
if len(query_text) < 2:
|
| 128 |
+
await message.reply_text("⚠️ Movie title is too short.", quote=True)
|
| 129 |
+
return
|
| 130 |
+
|
| 131 |
+
user_name = f"{user.first_name or ''} {user.last_name or ''}".strip()
|
| 132 |
+
req = await add_movie_request(user.id, user_name, query_text)
|
| 133 |
+
|
| 134 |
+
asyncio.create_task(send_request_to_channel(bot, user, query_text, req.id))
|
| 135 |
+
|
| 136 |
+
reply_msg = await message.reply_text(
|
| 137 |
+
f"✅ **Your request for** `{query_text}` **has been submitted to admins!**\n\n"
|
| 138 |
+
f"🎉 You will receive an automatic private DM as soon as it is uploaded.",
|
| 139 |
+
quote=True,
|
| 140 |
+
parse_mode=ParseMode.MARKDOWN
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@Client.on_callback_query(filters.regex(r"^req_send (\w+)$"))
|
| 146 |
+
async def request_callback(bot, query):
|
| 147 |
+
"""Handles clicking the '📩 Request Movie' button in search UI."""
|
| 148 |
+
from mfinder.plugins.serve import verify_force_sub
|
| 149 |
+
if not await verify_force_sub(bot, query):
|
| 150 |
+
return
|
| 151 |
+
user = query.from_user
|
| 152 |
+
short_hash = query.data.split()[1]
|
| 153 |
+
|
| 154 |
+
movie_title = REQUEST_QUERY_CACHE.get(short_hash)
|
| 155 |
+
if not movie_title:
|
| 156 |
+
await query.answer("⚠️ Session expired. Please search for the movie again to request it!", show_alert=True)
|
| 157 |
+
return
|
| 158 |
+
|
| 159 |
+
# Immediately answer callback query
|
| 160 |
+
await query.answer("✅ Request submitted to admins!", show_alert=True)
|
| 161 |
+
|
| 162 |
+
user_name = f"{user.first_name or ''} {user.last_name or ''}".strip()
|
| 163 |
+
req = await add_movie_request(user.id, user_name, movie_title)
|
| 164 |
+
asyncio.create_task(send_request_to_channel(bot, user, movie_title, req.id))
|
| 165 |
+
|
| 166 |
+
confirm_text = (
|
| 167 |
+
f"✅ **Your request for** `{movie_title}` **has been submitted to admins!**\n\n"
|
| 168 |
+
f"🎉 You will receive an automatic private DM as soon as it is uploaded."
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
# Immediately edit message/remove button to prevent duplicate clicks/spam
|
| 174 |
+
try:
|
| 175 |
+
if query.message and query.message.reply_markup:
|
| 176 |
+
new_rows = []
|
| 177 |
+
for row in query.message.reply_markup.inline_keyboard:
|
| 178 |
+
filtered_row = [b for b in row if not (b.callback_data and b.callback_data.startswith("req_send"))]
|
| 179 |
+
if filtered_row:
|
| 180 |
+
new_rows.append(filtered_row)
|
| 181 |
+
|
| 182 |
+
if new_rows:
|
| 183 |
+
# Other buttons (suggestion buttons) exist: update reply_markup to remove request button
|
| 184 |
+
await query.message.edit_reply_markup(reply_markup=InlineKeyboardMarkup(new_rows))
|
| 185 |
+
reply_msg = await query.message.reply_text(
|
| 186 |
+
text=confirm_text,
|
| 187 |
+
quote=True,
|
| 188 |
+
parse_mode=ParseMode.MARKDOWN
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
else:
|
| 192 |
+
# Standalone request button: replace message content directly into confirmation text
|
| 193 |
+
await query.message.edit_text(
|
| 194 |
+
text=confirm_text,
|
| 195 |
+
reply_markup=None,
|
| 196 |
+
parse_mode=ParseMode.MARKDOWN
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
else:
|
| 200 |
+
await query.message.edit_text(
|
| 201 |
+
text=confirm_text,
|
| 202 |
+
reply_markup=None,
|
| 203 |
+
parse_mode=ParseMode.MARKDOWN
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
except Exception as e:
|
| 207 |
+
LOGGER.warning(f"Notice updating request callback UI: {e}")
|
| 208 |
+
|
| 209 |
+
@Client.on_callback_query(filters.regex(r"^req_(appr|rejc) (\d+)$"))
|
| 210 |
+
async def admin_request_action(bot, query):
|
| 211 |
+
"""Handles Admin clicking '✅ Mark Uploaded' or '❌ Reject' in the Log/Request Channel."""
|
| 212 |
+
user = query.from_user
|
| 213 |
+
action = query.data.split()[0].split("_")[1]
|
| 214 |
+
req_id = int(query.data.split()[1])
|
| 215 |
+
|
| 216 |
+
admin_name = user.first_name or "Admin"
|
| 217 |
+
|
| 218 |
+
req = await get_movie_request(req_id)
|
| 219 |
+
if not req:
|
| 220 |
+
await query.answer("⚠️ Request record not found in database.", show_alert=True)
|
| 221 |
+
return
|
| 222 |
+
|
| 223 |
+
def escape_html(text):
|
| 224 |
+
if not text:
|
| 225 |
+
return ""
|
| 226 |
+
return str(text).replace("&", "&").replace("<", "<").replace(">", ">")
|
| 227 |
+
|
| 228 |
+
full_name_esc = escape_html(req.user_name or f"User {req.user_id}")
|
| 229 |
+
query_esc = escape_html(req.query)
|
| 230 |
+
admin_esc = escape_html(admin_name)
|
| 231 |
+
|
| 232 |
+
if action == "appr":
|
| 233 |
+
await update_request_status(req_id, "Uploaded")
|
| 234 |
+
status_text = f"✅ <b>Uploaded</b> (by {admin_esc})"
|
| 235 |
+
|
| 236 |
+
# 1. Update Channel Message
|
| 237 |
+
card_msg = (
|
| 238 |
+
f"📩 <b>Movie Request Updated</b>\n\n"
|
| 239 |
+
f"👤 <b>User Details:</b>\n"
|
| 240 |
+
f"• <b>User ID:</b> <code>{req.user_id}</code>\n"
|
| 241 |
+
f"• <b>Name:</b> {full_name_esc}\n\n"
|
| 242 |
+
f"🎬 <b>Requested Movie:</b> <code>{query_esc}</code>\n"
|
| 243 |
+
f"🆔 <b>Request ID:</b> <code>#{req_id}</code>\n"
|
| 244 |
+
f"📊 <b>Status:</b> {status_text}"
|
| 245 |
+
)
|
| 246 |
+
try:
|
| 247 |
+
await query.message.edit_text(card_msg, parse_mode=ParseMode.HTML, reply_markup=None)
|
| 248 |
+
except MessageNotModified:
|
| 249 |
+
pass
|
| 250 |
+
|
| 251 |
+
await query.answer("✅ Marked as Uploaded! Notifying user via DM...", show_alert=True)
|
| 252 |
+
|
| 253 |
+
# 2. Automatically notify user in private DM
|
| 254 |
+
dm_text = (
|
| 255 |
+
f"🎉 <b>Great news, {full_name_esc}!</b>\n\n"
|
| 256 |
+
f"The movie you requested (<b>{query_esc}</b>) has been <b>uploaded</b>! 🍿\n\n"
|
| 257 |
+
f"Search for <code>{query_esc}</code> now to download."
|
| 258 |
+
)
|
| 259 |
+
try:
|
| 260 |
+
await bot.send_message(chat_id=req.user_id, text=dm_text, parse_mode=ParseMode.HTML)
|
| 261 |
+
except Exception as dm_err:
|
| 262 |
+
LOGGER.warning(f"Could not send DM to user {req.user_id} for request #{req_id}: {dm_err}")
|
| 263 |
+
|
| 264 |
+
elif action == "rejc":
|
| 265 |
+
await update_request_status(req_id, "Rejected")
|
| 266 |
+
status_text = f"❌ <b>Rejected</b> (by {admin_esc})"
|
| 267 |
+
|
| 268 |
+
# 1. Update Channel Message
|
| 269 |
+
card_msg = (
|
| 270 |
+
f"📩 <b>Movie Request Updated</b>\n\n"
|
| 271 |
+
f"👤 <b>User Details:</b>\n"
|
| 272 |
+
f"• <b>User ID:</b> <code>{req.user_id}</code>\n"
|
| 273 |
+
f"• <b>Name:</b> {full_name_esc}\n\n"
|
| 274 |
+
f"🎬 <b>Requested Movie:</b> <code>{query_esc}</code>\n"
|
| 275 |
+
f"🆔 <b>Request ID:</b> <code>#{req_id}</code>\n"
|
| 276 |
+
f"📊 <b>Status:</b> {status_text}"
|
| 277 |
+
)
|
| 278 |
+
try:
|
| 279 |
+
await query.message.edit_text(card_msg, parse_mode=ParseMode.HTML, reply_markup=None)
|
| 280 |
+
except MessageNotModified:
|
| 281 |
+
pass
|
| 282 |
+
|
| 283 |
+
await query.answer("❌ Request marked as Rejected.", show_alert=True)
|
| 284 |
+
|
| 285 |
+
# 2. Automatically notify user in private DM
|
| 286 |
+
dm_text = (
|
| 287 |
+
f"ℹ️ <b>Hello {full_name_esc},</b>\n\n"
|
| 288 |
+
f"Regarding your request for <b>{query_esc}</b>: Sorry, this movie is currently unavailable."
|
| 289 |
+
)
|
| 290 |
+
try:
|
| 291 |
+
await bot.send_message(chat_id=req.user_id, text=dm_text, parse_mode=ParseMode.HTML)
|
| 292 |
+
except Exception as dm_err:
|
| 293 |
+
LOGGER.warning(f"Could not send rejection DM to user {req.user_id} for request #{req_id}: {dm_err}")
|
| 294 |
+
|
| 295 |
+
@Client.on_message(filters.command(["requests"]) & filters.user(ADMINS))
|
| 296 |
+
async def requests_admin_command(bot, message):
|
| 297 |
+
"""Admin command to check pending request count."""
|
| 298 |
+
count = await get_pending_requests_count()
|
| 299 |
+
await message.reply_text(
|
| 300 |
+
f"📊 **Movie Requests Summary**\n\n"
|
| 301 |
+
f"⏳ **Pending Requests:** `{count}`",
|
| 302 |
+
quote=True,
|
| 303 |
+
parse_mode=ParseMode.MARKDOWN
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
# Admin-User Communication Feature Implementation
|
| 308 |
+
ADMIN_REPLY_STATE = {}
|
| 309 |
+
|
| 310 |
+
@Client.on_callback_query(filters.regex(r"^req_msg (\d+)$"))
|
| 311 |
+
async def admin_request_message_user(bot, query):
|
| 312 |
+
user = query.from_user
|
| 313 |
+
req_id = int(query.data.split()[1])
|
| 314 |
+
|
| 315 |
+
req = await get_movie_request(req_id)
|
| 316 |
+
if not req:
|
| 317 |
+
await query.answer("⚠️ Request record not found in database.", show_alert=True)
|
| 318 |
+
return
|
| 319 |
+
|
| 320 |
+
try:
|
| 321 |
+
prompt = await bot.send_message(
|
| 322 |
+
chat_id=query.message.chat.id,
|
| 323 |
+
text=f"💬 **Reply to this message with the text you want to send to the user** (ID: `{req.user_id}`) **regarding their movie request for** `{req.query}`:\n\n"
|
| 324 |
+
f"Or type /cancel to abort.",
|
| 325 |
+
reply_markup=ForceReply(selective=True),
|
| 326 |
+
reply_to_message_id=query.message.id,
|
| 327 |
+
parse_mode=ParseMode.MARKDOWN
|
| 328 |
+
)
|
| 329 |
+
# Use (chat_id, prompt.id) as key to support channels/discussion groups/private chats
|
| 330 |
+
ADMIN_REPLY_STATE[(query.message.chat.id, prompt.id)] = {
|
| 331 |
+
"target_user_id": req.user_id,
|
| 332 |
+
"req_id": req_id,
|
| 333 |
+
"movie": req.query,
|
| 334 |
+
"prompt_msg_id": prompt.id
|
| 335 |
+
}
|
| 336 |
+
await query.answer("💬 Please reply to the prompt with your message.")
|
| 337 |
+
except Exception as e:
|
| 338 |
+
await query.answer(f"❌ Failed to initiate message prompt: {e}", show_alert=True)
|
| 339 |
+
|
| 340 |
+
@Client.on_message(filters.command(["message"]) & filters.user(ADMINS))
|
| 341 |
+
async def admin_message_command(bot, message):
|
| 342 |
+
if len(message.command) < 2:
|
| 343 |
+
await message.reply_text(
|
| 344 |
+
"⚠️ **Usage:**\n"
|
| 345 |
+
"• `/message <user_id>`\n"
|
| 346 |
+
"• `/message <username>`\n"
|
| 347 |
+
"• `/message <user_id_or_username> <your message text>`",
|
| 348 |
+
quote=True,
|
| 349 |
+
parse_mode=ParseMode.MARKDOWN
|
| 350 |
+
)
|
| 351 |
+
return
|
| 352 |
+
|
| 353 |
+
parts = message.text.split(None, 2)
|
| 354 |
+
target = parts[1].strip()
|
| 355 |
+
message_text = parts[2].strip() if len(parts) > 2 else None
|
| 356 |
+
|
| 357 |
+
target_user_id = None
|
| 358 |
+
if target.isdigit():
|
| 359 |
+
target_user_id = int(target)
|
| 360 |
+
else:
|
| 361 |
+
username_clean = target.lstrip("@")
|
| 362 |
+
try:
|
| 363 |
+
user_obj = await bot.get_users(username_clean)
|
| 364 |
+
target_user_id = user_obj.id
|
| 365 |
+
except Exception as e:
|
| 366 |
+
await message.reply_text(
|
| 367 |
+
f"❌ **Failed to resolve username** `@{username_clean}`:\n"
|
| 368 |
+
f"`{e}`\n\n"
|
| 369 |
+
f"Make sure the user has started/interacted with the bot before.",
|
| 370 |
+
quote=True,
|
| 371 |
+
parse_mode=ParseMode.MARKDOWN
|
| 372 |
+
)
|
| 373 |
+
return
|
| 374 |
+
|
| 375 |
+
if message_text:
|
| 376 |
+
try:
|
| 377 |
+
user_msg = (
|
| 378 |
+
f"🔔 **Message from Admins:**\n\n"
|
| 379 |
+
f"{message_text}"
|
| 380 |
+
)
|
| 381 |
+
await bot.send_message(chat_id=target_user_id, text=user_msg, parse_mode=ParseMode.MARKDOWN)
|
| 382 |
+
await message.reply_text(
|
| 383 |
+
f"✅ **Message successfully sent to user** `{target_user_id}`!",
|
| 384 |
+
quote=True,
|
| 385 |
+
parse_mode=ParseMode.MARKDOWN
|
| 386 |
+
)
|
| 387 |
+
except Exception as err:
|
| 388 |
+
await message.reply_text(
|
| 389 |
+
f"❌ **Failed to send message to user** `{target_user_id}`:\n"
|
| 390 |
+
f"`{err}`",
|
| 391 |
+
quote=True,
|
| 392 |
+
parse_mode=ParseMode.MARKDOWN
|
| 393 |
+
)
|
| 394 |
+
return
|
| 395 |
+
|
| 396 |
+
prompt = await message.reply_text(
|
| 397 |
+
f"💬 **Reply to this message with the text you want to send to user** `{target_user_id}`:\n\n"
|
| 398 |
+
f"Or type /cancel to abort.",
|
| 399 |
+
reply_markup=ForceReply(selective=True),
|
| 400 |
+
quote=True,
|
| 401 |
+
parse_mode=ParseMode.MARKDOWN
|
| 402 |
+
)
|
| 403 |
+
# Use (message.chat.id, prompt.id) as key
|
| 404 |
+
ADMIN_REPLY_STATE[(message.chat.id, prompt.id)] = {
|
| 405 |
+
"target_user_id": target_user_id,
|
| 406 |
+
"prompt_msg_id": prompt.id
|
| 407 |
+
}
|
| 408 |
+
|
| 409 |
+
@Client.on_message(filters.incoming)
|
| 410 |
+
async def admin_reply_listener(bot, message):
|
| 411 |
+
if not (message.reply_to_message and message.chat):
|
| 412 |
+
message.continue_propagation()
|
| 413 |
+
|
| 414 |
+
state_key = (message.chat.id, message.reply_to_message.id)
|
| 415 |
+
if state_key not in ADMIN_REPLY_STATE:
|
| 416 |
+
message.continue_propagation()
|
| 417 |
+
|
| 418 |
+
# If it is in a group, only admins can reply
|
| 419 |
+
if message.chat.type in [ChatType.GROUP, ChatType.SUPERGROUP]:
|
| 420 |
+
if not (message.from_user and message.from_user.id in ADMINS):
|
| 421 |
+
message.continue_propagation()
|
| 422 |
+
|
| 423 |
+
text_to_send = message.text
|
| 424 |
+
if not text_to_send:
|
| 425 |
+
message.continue_propagation()
|
| 426 |
+
|
| 427 |
+
if text_to_send.strip().startswith("/"):
|
| 428 |
+
if text_to_send.strip().lower().startswith("/cancel"):
|
| 429 |
+
ADMIN_REPLY_STATE.pop(state_key, None)
|
| 430 |
+
await message.reply_text("❌ Message sending cancelled.", quote=True)
|
| 431 |
+
return
|
| 432 |
+
else:
|
| 433 |
+
ADMIN_REPLY_STATE.pop(state_key, None)
|
| 434 |
+
message.continue_propagation()
|
| 435 |
+
|
| 436 |
+
state = ADMIN_REPLY_STATE.pop(state_key)
|
| 437 |
+
target_user_id = state["target_user_id"]
|
| 438 |
+
req_id = state.get("req_id")
|
| 439 |
+
movie = state.get("movie")
|
| 440 |
+
|
| 441 |
+
if req_id and movie:
|
| 442 |
+
user_msg = (
|
| 443 |
+
f"💬 **Admin replied to your movie request for** `{movie}`:\n\n"
|
| 444 |
+
f"{text_to_send}"
|
| 445 |
+
)
|
| 446 |
+
else:
|
| 447 |
+
user_msg = (
|
| 448 |
+
f"🔔 **Message from Admins:**\n\n"
|
| 449 |
+
f"{text_to_send}"
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
try:
|
| 453 |
+
await bot.send_message(chat_id=target_user_id, text=user_msg, parse_mode=ParseMode.MARKDOWN)
|
| 454 |
+
await message.reply_text(
|
| 455 |
+
f"✅ **Message successfully sent to user** `{target_user_id}`!",
|
| 456 |
+
quote=True,
|
| 457 |
+
parse_mode=ParseMode.MARKDOWN
|
| 458 |
+
)
|
| 459 |
+
except Exception as err:
|
| 460 |
+
await message.reply_text(
|
| 461 |
+
f"❌ **Failed to send message to user** `{target_user_id}`:\n"
|
| 462 |
+
f"`{err}`",
|
| 463 |
+
quote=True,
|
| 464 |
+
parse_mode=ParseMode.MARKDOWN
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
def parse_title_words_and_year(text):
|
| 468 |
+
# Insert space between 4-digit years and letters (e.g. beast2024 -> beast 2024)
|
| 469 |
+
normalized = re.sub(r'(?<=[a-zA-Z])(?=\d{4})', ' ', text)
|
| 470 |
+
normalized = re.sub(r'(?<=\d{4})(?=[a-zA-Z])', ' ', normalized)
|
| 471 |
+
|
| 472 |
+
# Replace dots, underscores, dashes, brackets, parentheses with spaces
|
| 473 |
+
normalized = re.sub(r'[\._\-()\[\]]', ' ', normalized)
|
| 474 |
+
|
| 475 |
+
# Search for 4-digit year (1900-2030)
|
| 476 |
+
match = re.search(r'\b(19\d\d|20[0-2]\d|2030)\b', normalized)
|
| 477 |
+
if match:
|
| 478 |
+
year = match.group(1)
|
| 479 |
+
# Remove year from normalized
|
| 480 |
+
title_part = normalized.replace(year, ' ')
|
| 481 |
+
else:
|
| 482 |
+
year = None
|
| 483 |
+
title_part = normalized
|
| 484 |
+
|
| 485 |
+
# Extract only lowercase alphanumeric words
|
| 486 |
+
words = [w.lower() for w in re.findall(r'[a-zA-Z0-9]+', title_part) if w]
|
| 487 |
+
return words, year
|
| 488 |
+
|
| 489 |
+
def check_exact_match(query, file_name):
|
| 490 |
+
q_words, q_year = parse_title_words_and_year(query)
|
| 491 |
+
f_words, f_year = parse_title_words_and_year(file_name)
|
| 492 |
+
|
| 493 |
+
if not q_words or not f_words:
|
| 494 |
+
return False
|
| 495 |
+
|
| 496 |
+
# If both years are specified, they must match exactly
|
| 497 |
+
if q_year and f_year:
|
| 498 |
+
if q_year != f_year:
|
| 499 |
+
return False
|
| 500 |
+
|
| 501 |
+
# Check if all query words are present in the file name words in correct sequence order
|
| 502 |
+
q_idx = 0
|
| 503 |
+
for w in f_words:
|
| 504 |
+
if q_idx < len(q_words) and w == q_words[q_idx]:
|
| 505 |
+
q_idx += 1
|
| 506 |
+
|
| 507 |
+
return q_idx == len(q_words)
|
| 508 |
+
|
| 509 |
+
async def check_and_notify_pending_requests(bot, file_name):
|
| 510 |
+
"""Checks pending requests for exact title and year match with file_name,
|
| 511 |
+
notifies matching users and edits their request channel cards.
|
| 512 |
+
"""
|
| 513 |
+
try:
|
| 514 |
+
from mfinder.plugins.admin_settings import get_log_channel
|
| 515 |
+
from mfinder.utils.helpers import encode_title
|
| 516 |
+
|
| 517 |
+
pending_reqs = await get_all_pending_requests()
|
| 518 |
+
if not pending_reqs:
|
| 519 |
+
return
|
| 520 |
+
|
| 521 |
+
log_channel_id = await get_log_channel()
|
| 522 |
+
|
| 523 |
+
for req in pending_reqs:
|
| 524 |
+
try:
|
| 525 |
+
if check_exact_match(req.query, file_name):
|
| 526 |
+
LOGGER.info(f"Auto-match found for request #{req.id} (Query: '{req.query}') with file '{file_name}'")
|
| 527 |
+
|
| 528 |
+
# 1. Update status in database
|
| 529 |
+
await update_request_status(req.id, "Uploaded")
|
| 530 |
+
|
| 531 |
+
# 2. Update channel message card (removing buttons)
|
| 532 |
+
if log_channel_id and req.channel_msg_id:
|
| 533 |
+
def escape_html(text):
|
| 534 |
+
if not text:
|
| 535 |
+
return ""
|
| 536 |
+
return str(text).replace("&", "&").replace("<", "<").replace(">", ">")
|
| 537 |
+
|
| 538 |
+
full_name_esc = escape_html(req.user_name or f"User {req.user_id}")
|
| 539 |
+
query_esc = escape_html(req.query)
|
| 540 |
+
status_text = "🤖 <b>Auto-Matched & Uploaded</b>"
|
| 541 |
+
|
| 542 |
+
card_msg = (
|
| 543 |
+
f"📩 <b>Movie Request Updated</b>\n\n"
|
| 544 |
+
f"👤 <b>User Details:</b>\n"
|
| 545 |
+
f"• <b>User ID:</b> <code>{req.user_id}</code>\n"
|
| 546 |
+
f"• <b>Name:</b> {full_name_esc}\n\n"
|
| 547 |
+
f"🎬 <b>Requested Movie:</b> <code>{query_esc}</code>\n"
|
| 548 |
+
f"🆔 <b>Request ID:</b> <code>#{req.id}</code>\n"
|
| 549 |
+
f"📊 <b>Status:</b> {status_text}"
|
| 550 |
+
)
|
| 551 |
+
try:
|
| 552 |
+
await bot.edit_message_text(
|
| 553 |
+
chat_id=int(log_channel_id),
|
| 554 |
+
message_id=req.channel_msg_id,
|
| 555 |
+
text=card_msg,
|
| 556 |
+
parse_mode=ParseMode.HTML,
|
| 557 |
+
reply_markup=None
|
| 558 |
+
)
|
| 559 |
+
except Exception as edit_err:
|
| 560 |
+
LOGGER.warning(f"Could not edit channel message for auto-match request #{req.id}: {edit_err}")
|
| 561 |
+
|
| 562 |
+
# 3. Notify user via private DM with Search button
|
| 563 |
+
try:
|
| 564 |
+
bot_me = bot.me if hasattr(bot, "me") and bot.me else await bot.get_me()
|
| 565 |
+
bot_username = bot_me.username
|
| 566 |
+
encoded = encode_title(req.query)
|
| 567 |
+
search_url = f"https://t.me/{bot_username}?start=q_{encoded}_req"
|
| 568 |
+
|
| 569 |
+
markup = InlineKeyboardMarkup([
|
| 570 |
+
[InlineKeyboardButton("🍿 Search Movie", url=search_url)]
|
| 571 |
+
])
|
| 572 |
+
|
| 573 |
+
dm_text = (
|
| 574 |
+
f"🎉 <b>The movie you requested: {req.query} is now available!</b>\n\n"
|
| 575 |
+
"Click below to search for it."
|
| 576 |
+
)
|
| 577 |
+
await bot.send_message(
|
| 578 |
+
chat_id=req.user_id,
|
| 579 |
+
text=dm_text,
|
| 580 |
+
reply_markup=markup,
|
| 581 |
+
parse_mode=ParseMode.HTML
|
| 582 |
+
)
|
| 583 |
+
except Exception as dm_err:
|
| 584 |
+
LOGGER.warning(f"Could not notify user {req.user_id} via DM for auto-match request #{req.id}: {dm_err}")
|
| 585 |
+
except Exception as item_err:
|
| 586 |
+
LOGGER.warning(f"Error handling auto-match check for single request #{req.id}: {item_err}")
|
| 587 |
+
except Exception as e:
|
| 588 |
+
LOGGER.warning(f"Error in check_and_notify_pending_requests: {e}")
|
mfinder/plugins/serve.py
ADDED
|
@@ -0,0 +1,1756 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from mfinder.db.analytics_sql import log_user_interaction
|
| 87 |
+
|
| 88 |
+
async def verify_force_sub(bot, event, pending_query=None, pending_file_id=None):
|
| 89 |
+
from mfinder import ADMINS, LOGGER
|
| 90 |
+
from mfinder.db.settings_sql import get_admin_settings, save_pending_fsub_request
|
| 91 |
+
from pyrogram.types import Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
|
| 92 |
+
from pyrogram.enums import ChatMemberStatus, ParseMode
|
| 93 |
+
from pyrogram.errors import UserNotParticipant
|
| 94 |
+
|
| 95 |
+
user_id = event.from_user.id
|
| 96 |
+
if user_id in ADMINS:
|
| 97 |
+
return True
|
| 98 |
+
|
| 99 |
+
admin_settings = await get_admin_settings()
|
| 100 |
+
fsub_channels = []
|
| 101 |
+
if admin_settings:
|
| 102 |
+
if admin_settings.fsub_channels_list:
|
| 103 |
+
fsub_channels = [ch.strip() for ch in admin_settings.fsub_channels_list.split(',') if ch.strip()]
|
| 104 |
+
elif admin_settings.fsub_channel:
|
| 105 |
+
fsub_channels = [str(int(admin_settings.fsub_channel))]
|
| 106 |
+
|
| 107 |
+
if not fsub_channels:
|
| 108 |
+
return True
|
| 109 |
+
|
| 110 |
+
not_joined = []
|
| 111 |
+
for ch in fsub_channels:
|
| 112 |
+
try:
|
| 113 |
+
ch_param = int(ch) if (ch.startswith('-') or ch.isdigit()) else ch
|
| 114 |
+
member = await bot.get_chat_member(ch_param, user_id)
|
| 115 |
+
if member.status == ChatMemberStatus.BANNED:
|
| 116 |
+
if isinstance(event, CallbackQuery):
|
| 117 |
+
await event.answer("Sorry, you are Banned to use me.", show_alert=True)
|
| 118 |
+
else:
|
| 119 |
+
await event.reply_text("Sorry, you are Banned to use me.", quote=True)
|
| 120 |
+
return False
|
| 121 |
+
except UserNotParticipant:
|
| 122 |
+
not_joined.append(ch)
|
| 123 |
+
except Exception as e:
|
| 124 |
+
LOGGER.warning(f"Error checking chat member for channel {ch}: {e}")
|
| 125 |
+
not_joined.append(ch)
|
| 126 |
+
|
| 127 |
+
if not not_joined:
|
| 128 |
+
return True
|
| 129 |
+
|
| 130 |
+
# Save user's pending request details so we can auto-execute on joining
|
| 131 |
+
await save_pending_fsub_request(user_id, search_query=pending_query, target_file_id=pending_file_id)
|
| 132 |
+
|
| 133 |
+
# Build buttons for channels they must join
|
| 134 |
+
buttons = []
|
| 135 |
+
for ch in fsub_channels:
|
| 136 |
+
try:
|
| 137 |
+
ch_param = int(ch) if (ch.startswith('-') or ch.isdigit()) else ch
|
| 138 |
+
chat = await bot.get_chat(ch_param)
|
| 139 |
+
title = chat.title or "Join Channel"
|
| 140 |
+
if chat.username:
|
| 141 |
+
url = f"https://t.me/{chat.username}"
|
| 142 |
+
else:
|
| 143 |
+
url = chat.invite_link or (await bot.create_chat_invite_link(ch_param)).invite_link
|
| 144 |
+
except Exception:
|
| 145 |
+
url = admin_settings.channel_link if (admin_settings and admin_settings.channel_link) else "https://t.me/FIREBOLT_File_Bot"
|
| 146 |
+
title = "Update Channel"
|
| 147 |
+
buttons.append([InlineKeyboardButton(f"🤖 Join: {title}", url=url)])
|
| 148 |
+
|
| 149 |
+
# Add the Try Again / Verification button
|
| 150 |
+
buttons.append([InlineKeyboardButton("🔄 Try Again / Verified", callback_data="verify_fsub")])
|
| 151 |
+
|
| 152 |
+
text = "**Please join my Update Channel(s) to use this Bot!**"
|
| 153 |
+
if len(not_joined) > 1:
|
| 154 |
+
text = "**Please join the required Update Channels below to use this Bot!**"
|
| 155 |
+
|
| 156 |
+
if isinstance(event, CallbackQuery):
|
| 157 |
+
await event.answer("⚠️ Please join the required channels to proceed!", show_alert=True)
|
| 158 |
+
try:
|
| 159 |
+
from pyrogram.errors import MessageNotModified
|
| 160 |
+
await event.message.edit_text(
|
| 161 |
+
text=text,
|
| 162 |
+
reply_markup=InlineKeyboardMarkup(buttons),
|
| 163 |
+
parse_mode=ParseMode.MARKDOWN,
|
| 164 |
+
)
|
| 165 |
+
except MessageNotModified:
|
| 166 |
+
pass
|
| 167 |
+
except Exception:
|
| 168 |
+
pass
|
| 169 |
+
else:
|
| 170 |
+
await event.reply_text(
|
| 171 |
+
text=text,
|
| 172 |
+
reply_markup=InlineKeyboardMarkup(buttons),
|
| 173 |
+
parse_mode=ParseMode.MARKDOWN,
|
| 174 |
+
quote=True,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
return False
|
| 178 |
+
from mfinder.utils.helpers import shorten_url
|
| 179 |
+
|
| 180 |
+
async def is_token_valid(user_id: int) -> bool:
|
| 181 |
+
import time
|
| 182 |
+
from mfinder import ADMINS
|
| 183 |
+
if user_id in ADMINS:
|
| 184 |
+
return True
|
| 185 |
+
from mfinder.db.settings_sql import get_user_token, delete_user_token
|
| 186 |
+
tok_rec = await get_user_token(user_id)
|
| 187 |
+
if tok_rec:
|
| 188 |
+
if tok_rec.status == "active":
|
| 189 |
+
if float(tok_rec.expires_at) > time.time():
|
| 190 |
+
return True
|
| 191 |
+
else:
|
| 192 |
+
# Active token has expired, delete it to save space!
|
| 193 |
+
await delete_user_token(user_id)
|
| 194 |
+
elif tok_rec.status == "pending":
|
| 195 |
+
# Preserve pending tokens within the 30-minute verification window
|
| 196 |
+
if (time.time() - float(tok_rec.created_at)) > 1800:
|
| 197 |
+
await delete_user_token(user_id)
|
| 198 |
+
return False
|
| 199 |
+
|
| 200 |
+
async def get_user_active_shortener_desc(user_id, admin_settings):
|
| 201 |
+
import json
|
| 202 |
+
import datetime
|
| 203 |
+
if not admin_settings:
|
| 204 |
+
return None
|
| 205 |
+
shorteners = []
|
| 206 |
+
if hasattr(admin_settings, "shorteners_list") and admin_settings.shorteners_list:
|
| 207 |
+
try:
|
| 208 |
+
shorteners = json.loads(admin_settings.shorteners_list)
|
| 209 |
+
except Exception:
|
| 210 |
+
pass
|
| 211 |
+
if not shorteners and admin_settings.shortener_site:
|
| 212 |
+
shorteners = [{"site": admin_settings.shortener_site, "api": admin_settings.shortener_api, "status": True}]
|
| 213 |
+
|
| 214 |
+
active_shorteners = [s for s in shorteners if s.get("status", True)]
|
| 215 |
+
if not active_shorteners:
|
| 216 |
+
return None
|
| 217 |
+
|
| 218 |
+
smart_rotator_on = getattr(admin_settings, "smart_rotator", False)
|
| 219 |
+
if smart_rotator_on:
|
| 220 |
+
try:
|
| 221 |
+
local_now = datetime.datetime.utcnow() + datetime.timedelta(hours=5, minutes=30)
|
| 222 |
+
today_str = local_now.strftime("%Y-%m-%d")
|
| 223 |
+
from mfinder.db.settings_sql import get_user_shortener_index
|
| 224 |
+
saved_idx = await get_user_shortener_index(user_id, today_str)
|
| 225 |
+
target_idx = (saved_idx or 0) % len(active_shorteners)
|
| 226 |
+
except Exception:
|
| 227 |
+
target_idx = 0
|
| 228 |
+
else:
|
| 229 |
+
target_idx = 0
|
| 230 |
+
|
| 231 |
+
if target_idx < len(active_shorteners):
|
| 232 |
+
site_name = active_shorteners[target_idx].get("site", "N/A")
|
| 233 |
+
orig_idx = -1
|
| 234 |
+
target_shortener = active_shorteners[target_idx]
|
| 235 |
+
for idx, sh in enumerate(shorteners):
|
| 236 |
+
if sh.get("site") == target_shortener.get("site") and sh.get("api") == target_shortener.get("api"):
|
| 237 |
+
orig_idx = idx
|
| 238 |
+
break
|
| 239 |
+
if orig_idx >= 0:
|
| 240 |
+
return f"{orig_idx + 1}. {site_name}"
|
| 241 |
+
return site_name
|
| 242 |
+
return None
|
| 243 |
+
|
| 244 |
+
def extract_shortener_from_results(result, btn, admin_settings):
|
| 245 |
+
if admin_settings and admin_settings.token_shortener_enabled:
|
| 246 |
+
return None
|
| 247 |
+
first_shortened_url = None
|
| 248 |
+
if btn:
|
| 249 |
+
for row in btn:
|
| 250 |
+
for button in row:
|
| 251 |
+
if button.url and (button.url.startswith("http://") or button.url.startswith("https://")) and "telegram.me" not in button.url and "t.me" not in button.url:
|
| 252 |
+
first_shortened_url = button.url
|
| 253 |
+
break
|
| 254 |
+
if first_shortened_url:
|
| 255 |
+
break
|
| 256 |
+
if not first_shortened_url and result:
|
| 257 |
+
import re
|
| 258 |
+
urls = re.findall(r'\]\((https?://[^\s\)]+)\)', result)
|
| 259 |
+
for u in urls:
|
| 260 |
+
if "telegram.me" not in u and "t.me" not in u:
|
| 261 |
+
first_shortened_url = u
|
| 262 |
+
break
|
| 263 |
+
if first_shortened_url:
|
| 264 |
+
from mfinder.utils.helpers import get_shortener_desc_for_url
|
| 265 |
+
return get_shortener_desc_for_url(first_shortened_url)
|
| 266 |
+
return None
|
| 267 |
+
|
| 268 |
+
async def log_search_attempt(bot, user, query, token_status, result_status, suggestions=None, verification_via=None):
|
| 269 |
+
try:
|
| 270 |
+
log_channel_id = await get_log_channel()
|
| 271 |
+
if not log_channel_id:
|
| 272 |
+
return # Logging is disabled or channel not configured
|
| 273 |
+
|
| 274 |
+
user_id = user.id
|
| 275 |
+
first_name = user.first_name or ""
|
| 276 |
+
last_name = user.last_name or ""
|
| 277 |
+
full_name = f"{first_name} {last_name}".strip()
|
| 278 |
+
username = f"@{user.username}" if user.username else "N/A"
|
| 279 |
+
|
| 280 |
+
# HTML escape helper
|
| 281 |
+
def escape_html(text):
|
| 282 |
+
if not text:
|
| 283 |
+
return ""
|
| 284 |
+
return str(text).replace("&", "&").replace("<", "<").replace(">", ">")
|
| 285 |
+
|
| 286 |
+
full_name_esc = escape_html(full_name)
|
| 287 |
+
first_name_esc = escape_html(first_name)
|
| 288 |
+
username_esc = escape_html(username)
|
| 289 |
+
query_esc = escape_html(query)
|
| 290 |
+
token_status_esc = escape_html(token_status)
|
| 291 |
+
result_status_esc = escape_html(result_status)
|
| 292 |
+
|
| 293 |
+
sug_block = ""
|
| 294 |
+
if suggestions:
|
| 295 |
+
if isinstance(suggestions, list) and len(suggestions) > 0:
|
| 296 |
+
formatted_sugs = ", ".join([f"<code>{escape_html(s)}</code>" for s in suggestions[:8]])
|
| 297 |
+
sug_block = f"\n💡 <b>Suggestions Offered:</b> {formatted_sugs}"
|
| 298 |
+
elif isinstance(suggestions, str) and suggestions.strip():
|
| 299 |
+
sug_block = f"\n💡 <b>Suggestions Offered:</b> <code>{escape_html(suggestions)}</code>"
|
| 300 |
+
|
| 301 |
+
ver_block = ""
|
| 302 |
+
if verification_via:
|
| 303 |
+
from mfinder.db.settings_sql import get_admin_settings_sync
|
| 304 |
+
settings = get_admin_settings_sync()
|
| 305 |
+
is_token_mode = settings.token_shortener_enabled if settings else False
|
| 306 |
+
label = "Verification Via" if is_token_mode else "Shortener Used"
|
| 307 |
+
ver_block = f"\n🌐 <b>{label}:</b> <code>{escape_html(verification_via)}</code>"
|
| 308 |
+
log_msg = (
|
| 309 |
+
f"🔍 <b>New Movie Search Log</b>\n\n"
|
| 310 |
+
f"👤 <b>User Details:</b>\n"
|
| 311 |
+
f"• <b>User ID:</b> <code>{user_id}</code>\n"
|
| 312 |
+
f"• <b>Name:</b> {full_name_esc}\n"
|
| 313 |
+
f"• <b>Username:</b> {username_esc}\n"
|
| 314 |
+
f"• <b>Mention:</b> <a href=\"tg://user?id={user_id}\">{first_name_esc}</a>\n\n"
|
| 315 |
+
f"📝 <b>Search Query:</b> <code>{query_esc}</code>\n"
|
| 316 |
+
f"🔑 <b>Token Status:</b> <code>{token_status_esc}</code>"
|
| 317 |
+
f"{ver_block}\n"
|
| 318 |
+
f"📊 <b>Search Result:</b> {result_status_esc}"
|
| 319 |
+
f"{sug_block}"
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
target_chat_id = int(log_channel_id)
|
| 323 |
+
try:
|
| 324 |
+
await bot.send_message(
|
| 325 |
+
chat_id=target_chat_id,
|
| 326 |
+
text=log_msg,
|
| 327 |
+
parse_mode=ParseMode.HTML
|
| 328 |
+
)
|
| 329 |
+
except Exception as send_err:
|
| 330 |
+
LOGGER.warning(f"Log channel send_message failed: {send_err}")
|
| 331 |
+
except Exception as e:
|
| 332 |
+
LOGGER.warning(f"Failed to send search log to channel: {e}")
|
| 333 |
+
|
| 334 |
+
async def log_file_delivery(bot, user, file_name, file_size, file_id):
|
| 335 |
+
try:
|
| 336 |
+
log_channel_id = await get_log_channel()
|
| 337 |
+
if not log_channel_id:
|
| 338 |
+
return # Logging disabled
|
| 339 |
+
|
| 340 |
+
user_id = user.id
|
| 341 |
+
first_name = user.first_name or ""
|
| 342 |
+
last_name = user.last_name or ""
|
| 343 |
+
full_name = f"{first_name} {last_name}".strip()
|
| 344 |
+
username = f"@{user.username}" if user.username else "N/A"
|
| 345 |
+
|
| 346 |
+
def escape_html(text):
|
| 347 |
+
if not text:
|
| 348 |
+
return ""
|
| 349 |
+
return str(text).replace("&", "&").replace("<", "<").replace(">", ">")
|
| 350 |
+
|
| 351 |
+
full_name_esc = escape_html(full_name)
|
| 352 |
+
first_name_esc = escape_html(first_name)
|
| 353 |
+
username_esc = escape_html(username)
|
| 354 |
+
file_name_esc = escape_html(file_name)
|
| 355 |
+
|
| 356 |
+
log_msg = (
|
| 357 |
+
f"📥 <b>File Delivered Log</b>\n\n"
|
| 358 |
+
f"👤 <b>User Details:</b>\n"
|
| 359 |
+
f"• <b>User ID:</b> <code>{user_id}</code>\n"
|
| 360 |
+
f"• <b>Name:</b> {full_name_esc}\n"
|
| 361 |
+
f"• <b>Username:</b> {username_esc}\n"
|
| 362 |
+
f"• <b>Mention:</b> <a href=\"tg://user?id={user_id}\">{first_name_esc}</a>\n\n"
|
| 363 |
+
f"📄 <b>File Name:</b> <code>{file_name_esc}</code>\n"
|
| 364 |
+
f"📦 <b>File Size:</b> <code>{file_size}</code>\n"
|
| 365 |
+
f"🆔 <b>File ID:</b> <code>{file_id}</code>"
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
target_chat_id = int(log_channel_id)
|
| 369 |
+
try:
|
| 370 |
+
await bot.send_message(
|
| 371 |
+
chat_id=target_chat_id,
|
| 372 |
+
text=log_msg,
|
| 373 |
+
parse_mode=ParseMode.HTML
|
| 374 |
+
)
|
| 375 |
+
except Exception as send_err:
|
| 376 |
+
LOGGER.warning(f"File delivery log channel send_message failed: {send_err}")
|
| 377 |
+
except Exception as e:
|
| 378 |
+
LOGGER.warning(f"Failed to send file delivery log to channel: {e}")
|
| 379 |
+
|
| 380 |
+
async def create_and_send_token_link(bot, update, admin_settings, search_query=None, target_file_id=None):
|
| 381 |
+
import uuid
|
| 382 |
+
from mfinder.db.settings_sql import create_user_token
|
| 383 |
+
from mfinder.utils.helpers import shorten_url
|
| 384 |
+
|
| 385 |
+
from pyrogram.types import CallbackQuery, Message
|
| 386 |
+
from pyrogram.enums import ChatType
|
| 387 |
+
|
| 388 |
+
if isinstance(update, CallbackQuery):
|
| 389 |
+
user_id = update.from_user.id
|
| 390 |
+
elif isinstance(update, Message):
|
| 391 |
+
if update.chat and update.chat.type == ChatType.PRIVATE:
|
| 392 |
+
user_id = update.chat.id
|
| 393 |
+
else:
|
| 394 |
+
user_id = update.from_user.id if update.from_user else None
|
| 395 |
+
else:
|
| 396 |
+
user_id = getattr(update, "from_user", None)
|
| 397 |
+
user_id = user_id.id if user_id else None
|
| 398 |
+
|
| 399 |
+
if not user_id:
|
| 400 |
+
user_id = update.from_user.id
|
| 401 |
+
|
| 402 |
+
# Delete any previous token request message to prevent chat clutter
|
| 403 |
+
try:
|
| 404 |
+
from mfinder.db.settings_sql import get_user_token
|
| 405 |
+
old_tok = await get_user_token(user_id)
|
| 406 |
+
if old_tok and old_tok.req_msg_id:
|
| 407 |
+
await bot.delete_messages(chat_id=user_id, message_ids=int(old_tok.req_msg_id))
|
| 408 |
+
except Exception as e:
|
| 409 |
+
LOGGER.warning(f"Error deleting old token request message: {e}")
|
| 410 |
+
|
| 411 |
+
token = f"tok_{uuid.uuid4().hex}"
|
| 412 |
+
|
| 413 |
+
# Save token as pending
|
| 414 |
+
await create_user_token(user_id, token, search_query=search_query, target_file_id=target_file_id)
|
| 415 |
+
|
| 416 |
+
me = bot.me
|
| 417 |
+
username = me.username
|
| 418 |
+
|
| 419 |
+
# Generate redirect link with source tracking code if present
|
| 420 |
+
source_code = None
|
| 421 |
+
search_source = None
|
| 422 |
+
if isinstance(update, Message):
|
| 423 |
+
search_source = getattr(update, "search_source", None)
|
| 424 |
+
elif isinstance(update, CallbackQuery) and update.message:
|
| 425 |
+
search_source = getattr(update.message, "search_source", None)
|
| 426 |
+
|
| 427 |
+
if search_source in ["Newsletter Broadcast", "Newsletter"]:
|
| 428 |
+
source_code = "nl"
|
| 429 |
+
elif search_source in ["Request Approval DM", "Request Notification"]:
|
| 430 |
+
source_code = "req"
|
| 431 |
+
elif search_source in ["Trending List", "Trending List Link"]:
|
| 432 |
+
source_code = "tr"
|
| 433 |
+
elif search_source in ["New Uploads List", "New Uploads Link"]:
|
| 434 |
+
source_code = "nu"
|
| 435 |
+
|
| 436 |
+
if source_code:
|
| 437 |
+
redirect_url = f"https://telegram.me/{username}?start={token}_{source_code}"
|
| 438 |
+
else:
|
| 439 |
+
redirect_url = f"https://telegram.me/{username}?start={token}"
|
| 440 |
+
|
| 441 |
+
short_url = await shorten_url(redirect_url, force=True, user_id=user_id)
|
| 442 |
+
|
| 443 |
+
text = (
|
| 444 |
+
"⚠️ **Access Token Required!**\n\n"
|
| 445 |
+
"To access search results and download files directly without ads, you need to generate a direct access token.\n\n"
|
| 446 |
+
"1. Click the button below to generate your token.\n"
|
| 447 |
+
"2. Complete the shortening link.\n"
|
| 448 |
+
"3. You will be redirected back with direct access for a dynamically set duration!\n\n"
|
| 449 |
+
"⏱️ **Note:** Standard per-file shortening is completely bypassed once verified!"
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
from mfinder.utils.helpers import get_how_to_download_for_url
|
| 453 |
+
how_to_download_url = get_how_to_download_for_url(short_url)
|
| 454 |
+
if not how_to_download_url:
|
| 455 |
+
import json
|
| 456 |
+
how_to_download_url = "https://telegram.me/FIREBOLTTutorial/23"
|
| 457 |
+
if admin_settings and hasattr(admin_settings, "shorteners_list") and admin_settings.shorteners_list:
|
| 458 |
+
try:
|
| 459 |
+
s_list = json.loads(admin_settings.shorteners_list)
|
| 460 |
+
if s_list:
|
| 461 |
+
how_to_download_url = s_list[0].get("how_to_download") or how_to_download_url
|
| 462 |
+
except Exception:
|
| 463 |
+
pass
|
| 464 |
+
if how_to_download_url == "https://telegram.me/FIREBOLTTutorial/23" and admin_settings and admin_settings.how_to_download:
|
| 465 |
+
how_to_download_url = admin_settings.how_to_download
|
| 466 |
+
|
| 467 |
+
markup = InlineKeyboardMarkup([
|
| 468 |
+
[InlineKeyboardButton("🎫 Generate Access Token", url=short_url)],
|
| 469 |
+
[InlineKeyboardButton("❓ How to Verify ❓", url=how_to_download_url)]
|
| 470 |
+
])
|
| 471 |
+
|
| 472 |
+
sent_msg = await update.reply_text(
|
| 473 |
+
text=text,
|
| 474 |
+
reply_markup=markup,
|
| 475 |
+
quote=True
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
try:
|
| 479 |
+
from mfinder.db.settings_sql import update_user_token_msg_id
|
| 480 |
+
await update_user_token_msg_id(user_id, sent_msg.id)
|
| 481 |
+
except Exception as e:
|
| 482 |
+
LOGGER.warning(f"Error saving req_msg_id to database: {e}")
|
| 483 |
+
|
| 484 |
+
# Auto-delete token request message after 30 minutes if not verified/deleted
|
| 485 |
+
async def delete_token_msg_after_delay(b, u_id, msg_id):
|
| 486 |
+
await asyncio.sleep(1800) # 30 minutes
|
| 487 |
+
try:
|
| 488 |
+
await b.delete_messages(chat_id=u_id, message_ids=msg_id)
|
| 489 |
+
except Exception:
|
| 490 |
+
pass
|
| 491 |
+
asyncio.create_task(delete_token_msg_after_delay(bot, user_id, sent_msg.id))
|
| 492 |
+
|
| 493 |
+
# Log the blocked attempt with the actual shortener used
|
| 494 |
+
try:
|
| 495 |
+
from mfinder.utils.helpers import get_shortener_desc_for_url
|
| 496 |
+
verification_via = get_shortener_desc_for_url(short_url)
|
| 497 |
+
|
| 498 |
+
query_str = search_query or ""
|
| 499 |
+
if not query_str:
|
| 500 |
+
if isinstance(update, Message):
|
| 501 |
+
query_str = update.text or ""
|
| 502 |
+
else:
|
| 503 |
+
query_str = ""
|
| 504 |
+
|
| 505 |
+
search_source = None
|
| 506 |
+
if isinstance(update, Message):
|
| 507 |
+
search_source = getattr(update, "search_source", None)
|
| 508 |
+
elif isinstance(update, CallbackQuery) and update.message:
|
| 509 |
+
search_source = getattr(update.message, "search_source", None)
|
| 510 |
+
|
| 511 |
+
if search_source and query_str:
|
| 512 |
+
query_str = f"{query_str} (from {search_source})"
|
| 513 |
+
|
| 514 |
+
if target_file_id and not query_str:
|
| 515 |
+
query_str = f"File Download ID: {target_file_id}"
|
| 516 |
+
|
| 517 |
+
# Resolve the actual user object (avoid bot details in case of query.message)
|
| 518 |
+
user_obj = update.from_user
|
| 519 |
+
bot_me = bot.me if hasattr(bot, "me") and bot.me else await bot.get_me()
|
| 520 |
+
if not user_obj or user_obj.is_bot or user_obj.id == bot_me.id:
|
| 521 |
+
try:
|
| 522 |
+
user_obj = await bot.get_users(user_id)
|
| 523 |
+
except Exception:
|
| 524 |
+
pass
|
| 525 |
+
if not user_obj:
|
| 526 |
+
user_obj = update.from_user
|
| 527 |
+
|
| 528 |
+
asyncio.create_task(
|
| 529 |
+
log_search_attempt(
|
| 530 |
+
bot=bot,
|
| 531 |
+
user=user_obj,
|
| 532 |
+
query=query_str,
|
| 533 |
+
token_status="Expired / Verification Required",
|
| 534 |
+
result_status="Blocked (Token Verification Required)",
|
| 535 |
+
verification_via=verification_via
|
| 536 |
+
)
|
| 537 |
+
)
|
| 538 |
+
except Exception as log_err:
|
| 539 |
+
LOGGER.warning(f"Error executing log_search_attempt inside create_and_send_token_link: {log_err}")
|
| 540 |
+
|
| 541 |
+
@Client.on_message(filters.private & filters.incoming, group=-1)
|
| 542 |
+
async def auto_log_message_interaction(bot, message):
|
| 543 |
+
if message.from_user and not message.from_user.is_bot:
|
| 544 |
+
asyncio.create_task(log_user_interaction(message.from_user.id))
|
| 545 |
+
|
| 546 |
+
@Client.on_callback_query(group=-1)
|
| 547 |
+
async def auto_log_callback_interaction(bot, query):
|
| 548 |
+
if query.from_user and not query.from_user.is_bot:
|
| 549 |
+
asyncio.create_task(log_user_interaction(query.from_user.id))
|
| 550 |
+
|
| 551 |
+
@Client.on_message(
|
| 552 |
+
~filters.regex(r"^\/") & filters.text & filters.private & filters.incoming
|
| 553 |
+
)
|
| 554 |
+
async def filter_(bot, message):
|
| 555 |
+
from mfinder import ADMINS
|
| 556 |
+
user_id = message.from_user.id
|
| 557 |
+
asyncio.create_task(log_user_interaction(user_id))
|
| 558 |
+
|
| 559 |
+
try:
|
| 560 |
+
from mfinder.plugins.admin_settings import ADMIN_INPUT_STATE, handle_admin_input
|
| 561 |
+
if user_id in ADMIN_INPUT_STATE:
|
| 562 |
+
await handle_admin_input(bot, message)
|
| 563 |
+
return
|
| 564 |
+
except Exception as e:
|
| 565 |
+
LOGGER.warning(f"Error checking ADMIN_INPUT_STATE: {e}")
|
| 566 |
+
|
| 567 |
+
if re.findall(r"((^\/|^,|^!|^\.|^[\U0001F600-\U000E007F]).*)", message.text):
|
| 568 |
+
return
|
| 569 |
+
|
| 570 |
+
if await is_banned(user_id):
|
| 571 |
+
await message.reply_text("You are banned. You can't use this bot.", quote=True)
|
| 572 |
+
return
|
| 573 |
+
|
| 574 |
+
if not await verify_force_sub(bot, message, pending_query=message.text):
|
| 575 |
+
return
|
| 576 |
+
|
| 577 |
+
admin_settings = await get_admin_settings()
|
| 578 |
+
if admin_settings:
|
| 579 |
+
if admin_settings.repair_mode and user_id not in ADMINS:
|
| 580 |
+
await message.reply_text(
|
| 581 |
+
"⚙️ **Bot Under Maintenance!**\n\nThe bot is currently undergoing scheduled maintenance or repair. Please try again later.",
|
| 582 |
+
quote=True
|
| 583 |
+
)
|
| 584 |
+
return
|
| 585 |
+
if admin_settings.token_shortener_enabled and user_id not in ADMINS:
|
| 586 |
+
if not await is_token_valid(user_id):
|
| 587 |
+
# Verification is required, handled by create_and_send_token_link
|
| 588 |
+
await create_and_send_token_link(bot, message, admin_settings, search_query=message.text)
|
| 589 |
+
return
|
| 590 |
+
|
| 591 |
+
fltr = await is_filter(message.text)
|
| 592 |
+
if fltr:
|
| 593 |
+
await message.reply_text(
|
| 594 |
+
text=fltr.message,
|
| 595 |
+
quote=True,
|
| 596 |
+
)
|
| 597 |
+
return
|
| 598 |
+
|
| 599 |
+
if 2 < len(message.text) < 100:
|
| 600 |
+
search = message.text
|
| 601 |
+
page_no = 1
|
| 602 |
+
me = bot.me
|
| 603 |
+
username = me.username
|
| 604 |
+
|
| 605 |
+
# Generate query hash
|
| 606 |
+
h = hashlib.md5(f"{search}_{user_id}".encode('utf-8')).hexdigest()[:12]
|
| 607 |
+
SEARCH_QUERY_CACHE.set(h, {
|
| 608 |
+
"search": search,
|
| 609 |
+
"filters": [],
|
| 610 |
+
"sort": None
|
| 611 |
+
})
|
| 612 |
+
# Send "Searching Files 🔎" message
|
| 613 |
+
search_msg = await message.reply_text("Searching Files 🔎", quote=True)
|
| 614 |
+
|
| 615 |
+
result, btn, suggestions = await get_result(search, page_no, user_id, username, query_hash=h)
|
| 616 |
+
|
| 617 |
+
# Delete the "Searching Files 🔎" message
|
| 618 |
+
try:
|
| 619 |
+
await search_msg.delete()
|
| 620 |
+
except Exception as delete_err:
|
| 621 |
+
LOGGER.warning(f"Failed to delete search_msg: {delete_err}")
|
| 622 |
+
|
| 623 |
+
# Determine token status
|
| 624 |
+
token_status = "N/A (Token Shortener Disabled)"
|
| 625 |
+
if admin_settings and admin_settings.token_shortener_enabled:
|
| 626 |
+
if user_id in ADMINS:
|
| 627 |
+
token_status = "Bypassed (Admin)"
|
| 628 |
+
else:
|
| 629 |
+
token_status = "Active / Valid"
|
| 630 |
+
|
| 631 |
+
# Parse result status
|
| 632 |
+
result_status = "Not Found"
|
| 633 |
+
if result:
|
| 634 |
+
if "No results found" in result:
|
| 635 |
+
result_status = "Not Found"
|
| 636 |
+
else:
|
| 637 |
+
match = re.search(r"Total Results.*`(\d+)`", result or "")
|
| 638 |
+
if match:
|
| 639 |
+
total_count = match.group(1)
|
| 640 |
+
result_status = f"Found ({total_count} results)"
|
| 641 |
+
else:
|
| 642 |
+
if "m_s " in str(btn) or "Did you mean" in (result or "") or "No exact match" in (result or ""):
|
| 643 |
+
result_status = "Not Found (Suggestions Offered)"
|
| 644 |
+
else:
|
| 645 |
+
result_status = "Found"
|
| 646 |
+
else:
|
| 647 |
+
result_status = "Not Found (No Suggestions)"
|
| 648 |
+
|
| 649 |
+
# Safe logging run in background
|
| 650 |
+
from mfinder.db.analytics_sql import log_search_query
|
| 651 |
+
asyncio.create_task(log_search_query(search))
|
| 652 |
+
if admin_settings and not admin_settings.token_shortener_enabled:
|
| 653 |
+
v_via = await get_user_active_shortener_desc(user_id, admin_settings)
|
| 654 |
+
else:
|
| 655 |
+
v_via = extract_shortener_from_results(result, btn, admin_settings)
|
| 656 |
+
search_source = getattr(message, "search_source", None)
|
| 657 |
+
query_log_text = search
|
| 658 |
+
if search_source:
|
| 659 |
+
query_log_text = f"{search} (from {search_source})"
|
| 660 |
+
|
| 661 |
+
asyncio.create_task(
|
| 662 |
+
log_search_attempt(
|
| 663 |
+
bot=bot,
|
| 664 |
+
user=message.from_user,
|
| 665 |
+
query=query_log_text,
|
| 666 |
+
token_status=token_status,
|
| 667 |
+
result_status=result_status,
|
| 668 |
+
suggestions=suggestions,
|
| 669 |
+
verification_via=v_via
|
| 670 |
+
)
|
| 671 |
+
)
|
| 672 |
+
|
| 673 |
+
if result:
|
| 674 |
+
if btn:
|
| 675 |
+
msg = await message.reply_text(
|
| 676 |
+
f"{result}",
|
| 677 |
+
reply_markup=InlineKeyboardMarkup(btn),
|
| 678 |
+
disable_web_page_preview=True,
|
| 679 |
+
quote=True,
|
| 680 |
+
)
|
| 681 |
+
else:
|
| 682 |
+
msg = await message.reply_text(
|
| 683 |
+
f"{result}",
|
| 684 |
+
disable_web_page_preview=True,
|
| 685 |
+
quote=True,
|
| 686 |
+
)
|
| 687 |
+
# Delete the message after 15 minutes in background
|
| 688 |
+
asyncio.create_task(auto_delete_search_result(bot, msg))
|
| 689 |
+
else:
|
| 690 |
+
no_res_msg = await message.reply_text(
|
| 691 |
+
text="No results found.\nOr retry with the correct spelling 🤐",
|
| 692 |
+
quote=True,
|
| 693 |
+
)
|
| 694 |
+
asyncio.create_task(auto_delete_search_result(bot, no_res_msg))
|
| 695 |
+
|
| 696 |
+
@Client.on_callback_query(filters.regex(r"^(nxt_pg|prev_pg) \d+ \d+ \w+$"))
|
| 697 |
+
async def pages(bot, query):
|
| 698 |
+
user_id = query.from_user.id
|
| 699 |
+
if not await verify_force_sub(bot, query):
|
| 700 |
+
return
|
| 701 |
+
admin_settings = await get_admin_settings()
|
| 702 |
+
if admin_settings and admin_settings.repair_mode and user_id not in ADMINS:
|
| 703 |
+
await query.answer("⚙️ Bot is under maintenance. Please try again later.", show_alert=True)
|
| 704 |
+
return
|
| 705 |
+
data_parts = query.data.split()
|
| 706 |
+
action = data_parts[0]
|
| 707 |
+
org_user_id = int(data_parts[1])
|
| 708 |
+
page_no = int(data_parts[2])
|
| 709 |
+
query_hash = data_parts[3]
|
| 710 |
+
|
| 711 |
+
cache_val = SEARCH_QUERY_CACHE.get(query_hash)
|
| 712 |
+
if not cache_val:
|
| 713 |
+
await query.answer("⚠️ This search session has expired. Please search again!", show_alert=True)
|
| 714 |
+
return
|
| 715 |
+
if isinstance(cache_val, dict):
|
| 716 |
+
search = cache_val.get("search")
|
| 717 |
+
else:
|
| 718 |
+
search = cache_val
|
| 719 |
+
|
| 720 |
+
me = bot.me
|
| 721 |
+
username = me.username
|
| 722 |
+
|
| 723 |
+
result, btn, suggestions = await get_result(search, page_no, user_id, username, query_hash=query_hash)
|
| 724 |
+
|
| 725 |
+
if result:
|
| 726 |
+
try:
|
| 727 |
+
if btn:
|
| 728 |
+
if query.message.text != result:
|
| 729 |
+
await query.message.edit(
|
| 730 |
+
f"{result}",
|
| 731 |
+
reply_markup=InlineKeyboardMarkup(btn),
|
| 732 |
+
disable_web_page_preview=True,
|
| 733 |
+
)
|
| 734 |
+
else:
|
| 735 |
+
if query.message.text != result:
|
| 736 |
+
await query.message.edit(
|
| 737 |
+
f"{result}",
|
| 738 |
+
disable_web_page_preview=True,
|
| 739 |
+
)
|
| 740 |
+
except MessageNotModified:
|
| 741 |
+
pass
|
| 742 |
+
else:
|
| 743 |
+
await query.answer("No more results found.", show_alert=True)
|
| 744 |
+
|
| 745 |
+
@Client.on_callback_query(filters.regex(r"^m_s (\w+)$"))
|
| 746 |
+
async def movie_selection(bot, query):
|
| 747 |
+
user_id = query.from_user.id
|
| 748 |
+
admin_settings = await get_admin_settings()
|
| 749 |
+
if admin_settings and admin_settings.repair_mode and user_id not in ADMINS:
|
| 750 |
+
await query.answer("⚙️ Bot is under maintenance. Please try again later.", show_alert=True)
|
| 751 |
+
return
|
| 752 |
+
short_hash = query.data.split()[1]
|
| 753 |
+
|
| 754 |
+
cached_val = MOVIE_CALLBACK_CACHE.get(short_hash)
|
| 755 |
+
if not cached_val:
|
| 756 |
+
await query.answer("⚠️ This suggestion session has expired. Please search again!", show_alert=True)
|
| 757 |
+
return
|
| 758 |
+
|
| 759 |
+
if isinstance(cached_val, tuple):
|
| 760 |
+
movie_title, source = cached_val
|
| 761 |
+
else:
|
| 762 |
+
movie_title = cached_val
|
| 763 |
+
source = "AI Suggestion"
|
| 764 |
+
|
| 765 |
+
query.message.search_source = source
|
| 766 |
+
|
| 767 |
+
if not await verify_force_sub(bot, query, pending_query=movie_title):
|
| 768 |
+
return
|
| 769 |
+
|
| 770 |
+
if admin_settings and admin_settings.token_shortener_enabled and user_id not in ADMINS:
|
| 771 |
+
if not await is_token_valid(user_id):
|
| 772 |
+
await query.answer("⚠️ Access token required. Generating token link...", show_alert=True)
|
| 773 |
+
await create_and_send_token_link(bot, query.message, admin_settings, search_query=movie_title)
|
| 774 |
+
return
|
| 775 |
+
|
| 776 |
+
await query.answer(f"Fetching files for {movie_title}...", cache_time=5)
|
| 777 |
+
|
| 778 |
+
me = bot.me
|
| 779 |
+
username = me.username
|
| 780 |
+
|
| 781 |
+
# We perform a direct exact search on the movie_title, starting on page_no = 1
|
| 782 |
+
h = hashlib.md5(f"{movie_title}_{user_id}".encode('utf-8')).hexdigest()[:12]
|
| 783 |
+
SEARCH_QUERY_CACHE.set(h, {
|
| 784 |
+
"search": movie_title,
|
| 785 |
+
"filters": [],
|
| 786 |
+
"sort": None
|
| 787 |
+
})
|
| 788 |
+
result, btn, suggestions = await get_result(movie_title, 1, user_id, username, query_hash=h)
|
| 789 |
+
|
| 790 |
+
# Determine token status
|
| 791 |
+
token_status = "N/A (Token Shortener Disabled)"
|
| 792 |
+
if admin_settings and admin_settings.token_shortener_enabled:
|
| 793 |
+
if user_id in ADMINS:
|
| 794 |
+
token_status = "Bypassed (Admin)"
|
| 795 |
+
else:
|
| 796 |
+
is_valid = await is_token_valid(user_id)
|
| 797 |
+
token_status = "Active / Valid" if is_valid else "Expired / Verification Required"
|
| 798 |
+
|
| 799 |
+
# Parse result status
|
| 800 |
+
result_status = "Not Found"
|
| 801 |
+
if result:
|
| 802 |
+
if "No results found" in result:
|
| 803 |
+
result_status = "Not Found via Suggestion Selection"
|
| 804 |
+
else:
|
| 805 |
+
match = re.search(r"Total Results.*`(\d+)`", result or "")
|
| 806 |
+
if match:
|
| 807 |
+
total_count = match.group(1)
|
| 808 |
+
result_status = f"Found ({total_count} results) via Suggestion Selection"
|
| 809 |
+
else:
|
| 810 |
+
result_status = "Found via Suggestion Selection"
|
| 811 |
+
else:
|
| 812 |
+
result_status = "Not Found via Suggestion Selection"
|
| 813 |
+
|
| 814 |
+
# Safe logging run in background
|
| 815 |
+
v_via = extract_shortener_from_results(result, btn, admin_settings)
|
| 816 |
+
asyncio.create_task(
|
| 817 |
+
log_search_attempt(
|
| 818 |
+
bot=bot,
|
| 819 |
+
user=query.from_user,
|
| 820 |
+
query=f"Selected Movie: {movie_title} (from {source})",
|
| 821 |
+
token_status=token_status,
|
| 822 |
+
result_status=result_status,
|
| 823 |
+
suggestions=suggestions,
|
| 824 |
+
verification_via=v_via
|
| 825 |
+
)
|
| 826 |
+
)
|
| 827 |
+
|
| 828 |
+
if result:
|
| 829 |
+
try:
|
| 830 |
+
if btn:
|
| 831 |
+
await query.message.edit(
|
| 832 |
+
f"{result}",
|
| 833 |
+
reply_markup=InlineKeyboardMarkup(btn),
|
| 834 |
+
disable_web_page_preview=True,
|
| 835 |
+
)
|
| 836 |
+
else:
|
| 837 |
+
await query.message.edit(
|
| 838 |
+
f"{result}",
|
| 839 |
+
disable_web_page_preview=True,
|
| 840 |
+
)
|
| 841 |
+
# Auto-delete suggestion search results in background after 15 mins
|
| 842 |
+
asyncio.create_task(auto_delete_search_result(bot, query.message))
|
| 843 |
+
except MessageNotModified:
|
| 844 |
+
pass
|
| 845 |
+
else:
|
| 846 |
+
await query.message.edit(
|
| 847 |
+
f"No files found for **{movie_title}**.",
|
| 848 |
+
disable_web_page_preview=True,
|
| 849 |
+
)
|
| 850 |
+
def extract_qualities_and_seasons(files):
|
| 851 |
+
from mfinder.utils.helpers import detect_file_quality
|
| 852 |
+
qualities = set()
|
| 853 |
+
seasons = set()
|
| 854 |
+
for f in files:
|
| 855 |
+
name = (f.file_name or "").lower()
|
| 856 |
+
cap = (f.caption or "").lower()
|
| 857 |
+
# Keep exact resolutions (1080p, 720p, 480p, 4k, 2160p)
|
| 858 |
+
for q in ["1080p", "720p", "480p", "4k", "2160p"]:
|
| 859 |
+
if q in name or q in cap:
|
| 860 |
+
qualities.add(q.upper())
|
| 861 |
+
# Detect exact quality classification based on rules
|
| 862 |
+
q_label = detect_file_quality(f.file_name or "")
|
| 863 |
+
if q_label == "HD" and not q_label in qualities:
|
| 864 |
+
q_label = detect_file_quality(f.caption or "")
|
| 865 |
+
qualities.add(q_label)
|
| 866 |
+
# Seasons
|
| 867 |
+
matches = re.findall(r'(?i)\b(?:s|season|series)\s*(\d{1,3})(?:e|ep|episode|\b|[^\w]|$)', name) + re.findall(r'(?i)\b(?:s|season|series)\s*(\d{1,3})(?:e|ep|episode|\b|[^\w]|$)', cap)
|
| 868 |
+
for m in matches:
|
| 869 |
+
if m.isdigit() and 0 < int(m) <= 100:
|
| 870 |
+
seasons.add(f"Season {int(m)}")
|
| 871 |
+
quality_priority = {
|
| 872 |
+
"4K": 10,
|
| 873 |
+
"2160P": 9,
|
| 874 |
+
"1080P": 8,
|
| 875 |
+
"720P": 7,
|
| 876 |
+
"480P": 6,
|
| 877 |
+
"HD": 5,
|
| 878 |
+
"Theatre Print [Clear Audio]": 4
|
| 879 |
+
}
|
| 880 |
+
sorted_quals = sorted(list(qualities), key=lambda q: quality_priority.get(q, 0), reverse=True)
|
| 881 |
+
def season_num(s):
|
| 882 |
+
try:
|
| 883 |
+
return int(s.split()[-1])
|
| 884 |
+
except Exception:
|
| 885 |
+
return 0
|
| 886 |
+
sorted_seasons = sorted(list(seasons), key=season_num)
|
| 887 |
+
return sorted_quals, sorted_seasons
|
| 888 |
+
|
| 889 |
+
async def run_delayed_delete(bot, chat_id, message_id, delay):
|
| 890 |
+
from mfinder.db.settings_sql import remove_auto_delete_msg_sync
|
| 891 |
+
await asyncio.sleep(delay)
|
| 892 |
+
try:
|
| 893 |
+
await bot.delete_messages(chat_id=int(chat_id), message_ids=int(message_id))
|
| 894 |
+
except Exception:
|
| 895 |
+
pass
|
| 896 |
+
finally:
|
| 897 |
+
try:
|
| 898 |
+
await asyncio.to_thread(remove_auto_delete_msg_sync, chat_id, message_id)
|
| 899 |
+
except Exception:
|
| 900 |
+
pass
|
| 901 |
+
|
| 902 |
+
async def auto_delete_search_result(bot, message):
|
| 903 |
+
from mfinder.db.settings_sql import add_auto_delete_msg_sync
|
| 904 |
+
delay = 900 # Always delete search results and menus after 15 minutes
|
| 905 |
+
|
| 906 |
+
# Track persistently in the database so it survives server restarts
|
| 907 |
+
try:
|
| 908 |
+
await asyncio.to_thread(add_auto_delete_msg_sync, message.chat.id, message.id, delay)
|
| 909 |
+
except Exception as db_err:
|
| 910 |
+
LOGGER.warning(f"Failed to record message for auto-deletion in DB: {db_err}")
|
| 911 |
+
|
| 912 |
+
# Launch in-memory timer
|
| 913 |
+
asyncio.create_task(run_delayed_delete(bot, message.chat.id, message.id, delay))
|
| 914 |
+
|
| 915 |
+
async def start_auto_delete_loop(bot):
|
| 916 |
+
import time
|
| 917 |
+
from mfinder.db.settings_sql import get_all_auto_delete_msgs_sync
|
| 918 |
+
LOGGER.info("Initializing database persistent auto-delete tasks on startup...")
|
| 919 |
+
try:
|
| 920 |
+
now = time.time()
|
| 921 |
+
pending_msgs = await asyncio.to_thread(get_all_auto_delete_msgs_sync)
|
| 922 |
+
if pending_msgs:
|
| 923 |
+
LOGGER.info("Restoring %s pending auto-deletion tasks from DB...", len(pending_msgs))
|
| 924 |
+
for chat_id, message_id, delete_at in pending_msgs:
|
| 925 |
+
remaining = delete_at - now
|
| 926 |
+
if remaining < 0:
|
| 927 |
+
remaining = 0
|
| 928 |
+
asyncio.create_task(run_delayed_delete(bot, chat_id, message_id, remaining))
|
| 929 |
+
except Exception as e:
|
| 930 |
+
LOGGER.warning("Error initializing auto-delete tasks on startup: %s", e)
|
| 931 |
+
|
| 932 |
+
async def get_result(search, page_no, user_id, username, query_hash=None):
|
| 933 |
+
from mfinder import ADMINS
|
| 934 |
+
admin_settings = await get_admin_settings()
|
| 935 |
+
bypass_shortening = False
|
| 936 |
+
if admin_settings and admin_settings.token_shortener_enabled:
|
| 937 |
+
bypass_shortening = True
|
| 938 |
+
if user_id in ADMINS:
|
| 939 |
+
bypass_shortening = True
|
| 940 |
+
|
| 941 |
+
search_settings = await get_search_settings(user_id)
|
| 942 |
+
if search_settings:
|
| 943 |
+
if search_settings.precise_mode:
|
| 944 |
+
files_all, count = await get_precise_filter_results(query=search, page=1, per_page=1000)
|
| 945 |
+
precise_search = "Enabled"
|
| 946 |
+
else:
|
| 947 |
+
files_all, count = await get_filter_results(query=search, page=1, per_page=1000)
|
| 948 |
+
precise_search = "Disabled"
|
| 949 |
+
else:
|
| 950 |
+
files_all, count = await get_filter_results(query=search, page=1, per_page=1000)
|
| 951 |
+
precise_search = "Disabled"
|
| 952 |
+
|
| 953 |
+
search_type = "Direct"
|
| 954 |
+
original_search = search
|
| 955 |
+
|
| 956 |
+
# If direct search returned no files and page_no == 1, run corrections
|
| 957 |
+
if not files_all and page_no == 1:
|
| 958 |
+
corrected_query = None
|
| 959 |
+
keywords = []
|
| 960 |
+
suggestions = []
|
| 961 |
+
ai_model = None
|
| 962 |
+
try:
|
| 963 |
+
from mfinder.db.suggestion_cache import get_cached_suggestion, set_cached_suggestion
|
| 964 |
+
from mfinder.utils.gemini_client import get_ai_suggestions
|
| 965 |
+
cached = await get_cached_suggestion(search)
|
| 966 |
+
if cached:
|
| 967 |
+
corrected_query = cached.get("corrected_query")
|
| 968 |
+
keywords = cached.get("keywords") or []
|
| 969 |
+
suggestions = cached.get("suggestions") or []
|
| 970 |
+
ai_model = cached.get("model") or "gemini-3.1-flash-lite"
|
| 971 |
+
else:
|
| 972 |
+
ai_res = await get_ai_suggestions(search)
|
| 973 |
+
if ai_res:
|
| 974 |
+
corrected_query = ai_res.get("corrected")
|
| 975 |
+
keywords = ai_res.get("keywords") or []
|
| 976 |
+
suggestions = ai_res.get("suggestions") or []
|
| 977 |
+
ai_model = ai_res.get("model")
|
| 978 |
+
await set_cached_suggestion(search, corrected_query, keywords, suggestions)
|
| 979 |
+
except Exception as e:
|
| 980 |
+
LOGGER.warning(f"Error in Gemini search: {e}")
|
| 981 |
+
|
| 982 |
+
candidate_files = []
|
| 983 |
+
seen_file_ids = set()
|
| 984 |
+
def add_unique_files(new_files):
|
| 985 |
+
for f in new_files:
|
| 986 |
+
if f.file_id not in seen_file_ids:
|
| 987 |
+
seen_file_ids.add(f.file_id)
|
| 988 |
+
candidate_files.append(f)
|
| 989 |
+
|
| 990 |
+
orig_fuzzy_files, _ = await get_trigram_filter_results(query=search, page=1, per_page=100, threshold=0.2)
|
| 991 |
+
add_unique_files(orig_fuzzy_files)
|
| 992 |
+
|
| 993 |
+
candidates = []
|
| 994 |
+
if corrected_query and corrected_query.strip().lower() != search.strip().lower():
|
| 995 |
+
candidates.append(corrected_query.strip())
|
| 996 |
+
for sug in suggestions:
|
| 997 |
+
if sug and sug.strip().lower() != search.strip().lower() and sug.strip() not in candidates:
|
| 998 |
+
candidates.append(sug.strip())
|
| 999 |
+
for kw in keywords:
|
| 1000 |
+
if kw and kw.strip().lower() != search.strip().lower() and len(kw.strip()) > 3 and kw.strip() not in candidates:
|
| 1001 |
+
candidates.append(kw.strip())
|
| 1002 |
+
|
| 1003 |
+
from mfinder.db.files_sql import get_keyword_db_suggestions
|
| 1004 |
+
db_kw_suggestions = await get_keyword_db_suggestions(search, limit=25)
|
| 1005 |
+
for db_sug in db_kw_suggestions:
|
| 1006 |
+
if db_sug and db_sug.strip() not in candidates:
|
| 1007 |
+
candidates.append(db_sug.strip())
|
| 1008 |
+
if db_sug not in suggestions:
|
| 1009 |
+
suggestions.append(db_sug)
|
| 1010 |
+
|
| 1011 |
+
for cand in candidates:
|
| 1012 |
+
cand_direct_files, _ = await get_filter_results(query=cand, page=1, per_page=50)
|
| 1013 |
+
add_unique_files(cand_direct_files)
|
| 1014 |
+
cand_fuzzy_files, _ = await get_trigram_filter_results(query=cand, page=1, per_page=50, threshold=0.2)
|
| 1015 |
+
add_unique_files(cand_fuzzy_files)
|
| 1016 |
+
|
| 1017 |
+
import difflib
|
| 1018 |
+
movie_groups = {}
|
| 1019 |
+
for f in candidate_files:
|
| 1020 |
+
cl_title = clean_movie_title(f.file_name)
|
| 1021 |
+
if not cl_title:
|
| 1022 |
+
cl_title = clean_movie_title(f.caption)
|
| 1023 |
+
if not cl_title:
|
| 1024 |
+
continue
|
| 1025 |
+
norm_key = cl_title.lower().strip()
|
| 1026 |
+
found_key = None
|
| 1027 |
+
for existing_title in movie_groups:
|
| 1028 |
+
if existing_title.lower().strip() == norm_key:
|
| 1029 |
+
found_key = existing_title
|
| 1030 |
+
break
|
| 1031 |
+
if found_key:
|
| 1032 |
+
movie_groups[found_key].append(f)
|
| 1033 |
+
else:
|
| 1034 |
+
movie_groups[cl_title] = [f]
|
| 1035 |
+
|
| 1036 |
+
q_clean = clean_movie_title(search).lower()
|
| 1037 |
+
if not q_clean:
|
| 1038 |
+
q_clean = search.lower()
|
| 1039 |
+
corr_clean = None
|
| 1040 |
+
if corrected_query:
|
| 1041 |
+
corr_clean = clean_movie_title(corrected_query).lower()
|
| 1042 |
+
if not corr_clean:
|
| 1043 |
+
corr_clean = corrected_query.lower()
|
| 1044 |
+
sugs_clean = []
|
| 1045 |
+
for s in suggestions:
|
| 1046 |
+
if s:
|
| 1047 |
+
sc = clean_movie_title(s).lower()
|
| 1048 |
+
if not sc:
|
| 1049 |
+
sc = s.lower()
|
| 1050 |
+
if sc not in sugs_clean:
|
| 1051 |
+
sugs_clean.append(sc)
|
| 1052 |
+
scored_groups = []
|
| 1053 |
+
for cl_title, group_files in movie_groups.items():
|
| 1054 |
+
t_clean = cl_title.lower()
|
| 1055 |
+
t_clean_no_year = re.sub(r'\s*\(\d{4}\)', '', t_clean).strip()
|
| 1056 |
+
q_clean_no_year = re.sub(r'\s*\(\d{4}\)', '', q_clean).strip()
|
| 1057 |
+
corr_clean_no_year = re.sub(r'\s*\(\d{4}\)', '', corr_clean).strip() if corr_clean else ""
|
| 1058 |
+
sugs_clean_no_year = [re.sub(r'\s*\(\d{4}\)', '', s).strip() for s in sugs_clean if s]
|
| 1059 |
+
score = 0.0
|
| 1060 |
+
if t_clean == q_clean or t_clean_no_year == q_clean_no_year:
|
| 1061 |
+
score = 1.0
|
| 1062 |
+
elif corr_clean and (t_clean == corr_clean or t_clean_no_year == corr_clean_no_year):
|
| 1063 |
+
score = 0.9
|
| 1064 |
+
elif sugs_clean and (t_clean in sugs_clean or t_clean_no_year in sugs_clean_no_year):
|
| 1065 |
+
score = 0.8
|
| 1066 |
+
else:
|
| 1067 |
+
ratio1 = difflib.SequenceMatcher(None, q_clean, t_clean).ratio()
|
| 1068 |
+
ratio2 = difflib.SequenceMatcher(None, q_clean_no_year, t_clean_no_year).ratio()
|
| 1069 |
+
score = max(ratio1, ratio2) * 0.7
|
| 1070 |
+
scored_groups.append((score, cl_title, group_files))
|
| 1071 |
+
|
| 1072 |
+
scored_groups.sort(key=lambda x: x[0], reverse=True)
|
| 1073 |
+
scored_groups = [g for g in scored_groups if g[0] >= 0.2]
|
| 1074 |
+
if scored_groups:
|
| 1075 |
+
results_text = f"🔎 **Could not find exact matches for** `{search}`.\n🍿 **Did you mean one of these?**\n"
|
| 1076 |
+
buttons = []
|
| 1077 |
+
for score, title, g_files in scored_groups[:8]:
|
| 1078 |
+
h = hashlib.md5(title.encode('utf-8')).hexdigest()[:12]
|
| 1079 |
+
MOVIE_CALLBACK_CACHE.set(h, (title, "AI Suggestion"))
|
| 1080 |
+
buttons.append([InlineKeyboardButton(f"🎬 {title} ({len(g_files)} files)", callback_data=f"m_s {h}")])
|
| 1081 |
+
# Add Request button at bottom of suggestions list!
|
| 1082 |
+
req_hash = hashlib.md5(search.encode('utf-8')).hexdigest()[:12]
|
| 1083 |
+
from mfinder.plugins.requests import REQUEST_QUERY_CACHE
|
| 1084 |
+
REQUEST_QUERY_CACHE.set(req_hash, search)
|
| 1085 |
+
buttons.append([
|
| 1086 |
+
InlineKeyboardButton(text=f"📩 Request Movie: \"{search}\"", callback_data=f"req_send {req_hash}")
|
| 1087 |
+
])
|
| 1088 |
+
return results_text, buttons, [g[1] for g in scored_groups[:8]]
|
| 1089 |
+
else:
|
| 1090 |
+
return None, None, []
|
| 1091 |
+
|
| 1092 |
+
if not files_all:
|
| 1093 |
+
return None, None, []
|
| 1094 |
+
|
| 1095 |
+
qualities, seasons = extract_qualities_and_seasons(files_all)
|
| 1096 |
+
|
| 1097 |
+
current_filters = []
|
| 1098 |
+
current_sort = None
|
| 1099 |
+
if query_hash:
|
| 1100 |
+
state = SEARCH_QUERY_CACHE.get(query_hash)
|
| 1101 |
+
if isinstance(state, dict):
|
| 1102 |
+
current_filters = state.get("filters") or []
|
| 1103 |
+
current_sort = state.get("sort")
|
| 1104 |
+
|
| 1105 |
+
# Split selected filters into seasons and qualities
|
| 1106 |
+
selected_seasons = []
|
| 1107 |
+
selected_qualities = []
|
| 1108 |
+
for f_val in current_filters:
|
| 1109 |
+
f_lower = f_val.lower().strip()
|
| 1110 |
+
if f_lower.startswith("season ") or f_lower.startswith("s"):
|
| 1111 |
+
selected_seasons.append(f_lower)
|
| 1112 |
+
else:
|
| 1113 |
+
selected_qualities.append(f_lower)
|
| 1114 |
+
|
| 1115 |
+
# Apply filters
|
| 1116 |
+
filtered_files = []
|
| 1117 |
+
for f in files_all:
|
| 1118 |
+
name = (f.file_name or "").lower()
|
| 1119 |
+
cap = (f.caption or "").lower()
|
| 1120 |
+
# Season match
|
| 1121 |
+
matches_season = True
|
| 1122 |
+
if selected_seasons:
|
| 1123 |
+
matches_season = False
|
| 1124 |
+
file_seasons = []
|
| 1125 |
+
matches = re.findall(r'(?i)\b(?:s|season|series)\s*(\d{1,3})(?:e|ep|episode|\b|[^\w]|$)', name) + re.findall(r'(?i)\b(?:s|season|series)\s*(\d{1,3})(?:e|ep|episode|\b|[^\w]|$)', cap)
|
| 1126 |
+
for m in matches:
|
| 1127 |
+
if m.isdigit() and 0 < int(m) <= 100:
|
| 1128 |
+
file_seasons.append(f"season {int(m)}")
|
| 1129 |
+
for fs in file_seasons:
|
| 1130 |
+
if fs in selected_seasons:
|
| 1131 |
+
matches_season = True
|
| 1132 |
+
break
|
| 1133 |
+
# Quality match
|
| 1134 |
+
matches_quality = True
|
| 1135 |
+
if selected_qualities:
|
| 1136 |
+
sel_classifications = []
|
| 1137 |
+
sel_resolutions = []
|
| 1138 |
+
for q in selected_qualities:
|
| 1139 |
+
q_upper = q.upper()
|
| 1140 |
+
if q_upper in ["HD", "THEATRE PRINT [CLEAR AUDIO]"]:
|
| 1141 |
+
sel_classifications.append(q_upper)
|
| 1142 |
+
else:
|
| 1143 |
+
sel_resolutions.append(q.lower())
|
| 1144 |
+
|
| 1145 |
+
# Check classification match if any selected
|
| 1146 |
+
matches_class = True
|
| 1147 |
+
if sel_classifications:
|
| 1148 |
+
matches_class = False
|
| 1149 |
+
from mfinder.utils.helpers import detect_file_quality
|
| 1150 |
+
file_quality = detect_file_quality(f.file_name or "")
|
| 1151 |
+
if file_quality == "HD" and not (f.file_name or "").strip():
|
| 1152 |
+
file_quality = detect_file_quality(f.caption or "")
|
| 1153 |
+
|
| 1154 |
+
for sc in sel_classifications:
|
| 1155 |
+
if sc == "HD" and file_quality == "HD":
|
| 1156 |
+
matches_class = True
|
| 1157 |
+
break
|
| 1158 |
+
elif sc == "THEATRE PRINT [CLEAR AUDIO]" and file_quality == "Theatre Print [Clear Audio]":
|
| 1159 |
+
matches_class = True
|
| 1160 |
+
break
|
| 1161 |
+
|
| 1162 |
+
# Check resolution match if any selected
|
| 1163 |
+
matches_res = True
|
| 1164 |
+
if sel_resolutions:
|
| 1165 |
+
matches_res = False
|
| 1166 |
+
for sr in sel_resolutions:
|
| 1167 |
+
if sr in name or sr in cap:
|
| 1168 |
+
matches_res = True
|
| 1169 |
+
break
|
| 1170 |
+
|
| 1171 |
+
matches_quality = matches_class and matches_res
|
| 1172 |
+
if matches_season and matches_quality:
|
| 1173 |
+
filtered_files.append(f)
|
| 1174 |
+
|
| 1175 |
+
# Apply sorting
|
| 1176 |
+
if current_sort == "low_to_high":
|
| 1177 |
+
filtered_files.sort(key=lambda f: float(f.file_size or 0))
|
| 1178 |
+
elif current_sort == "high_to_low":
|
| 1179 |
+
filtered_files.sort(key=lambda f: float(f.file_size or 0), reverse=True)
|
| 1180 |
+
|
| 1181 |
+
count = len(filtered_files)
|
| 1182 |
+
offset = (page_no - 1) * 10
|
| 1183 |
+
files = filtered_files[offset:offset+10]
|
| 1184 |
+
|
| 1185 |
+
button_mode = "OFF"
|
| 1186 |
+
link_mode = "OFF"
|
| 1187 |
+
search_settings = await get_search_settings(user_id)
|
| 1188 |
+
if search_settings:
|
| 1189 |
+
if search_settings.button_mode:
|
| 1190 |
+
button_mode = "ON"
|
| 1191 |
+
if search_settings.link_mode:
|
| 1192 |
+
link_mode = "ON"
|
| 1193 |
+
if search_settings.list_mode:
|
| 1194 |
+
link_mode = "OFF"
|
| 1195 |
+
else:
|
| 1196 |
+
link_mode = "ON"
|
| 1197 |
+
|
| 1198 |
+
if button_mode == "ON" and link_mode == "OFF":
|
| 1199 |
+
search_md = "Button"
|
| 1200 |
+
elif link_mode == "ON":
|
| 1201 |
+
search_md = "Link"
|
| 1202 |
+
else:
|
| 1203 |
+
search_md = "Text Button"
|
| 1204 |
+
|
| 1205 |
+
if files:
|
| 1206 |
+
btn = []
|
| 1207 |
+
index = (page_no - 1) * 10
|
| 1208 |
+
crnt_pg = page_no
|
| 1209 |
+
tot_pg = (count + 10 - 1) // 10
|
| 1210 |
+
btn_count = 0
|
| 1211 |
+
header_prefix = ""
|
| 1212 |
+
if search_type == "Fuzzy Match":
|
| 1213 |
+
header_prefix = f"⚠️ **No exact matches for** `{original_search}`.\n💡 **Showing close fuzzy matches:**\n\n"
|
| 1214 |
+
elif search_type == "AI Corrected":
|
| 1215 |
+
header_prefix = f"🤖 **AI corrected query:** `{original_search}` ➔ `{search}`\n🍿 **Showing suggested results:**\n\n"
|
| 1216 |
+
|
| 1217 |
+
async def get_short_url(f):
|
| 1218 |
+
long_url = f"https://telegram.me/{username}?start={f.file_id}"
|
| 1219 |
+
if bypass_shortening:
|
| 1220 |
+
return long_url
|
| 1221 |
+
try:
|
| 1222 |
+
return await shorten_url(long_url, user_id=user_id)
|
| 1223 |
+
except Exception as e:
|
| 1224 |
+
print(f"Error shortening URL for {f.file_name}: {e}")
|
| 1225 |
+
return long_url
|
| 1226 |
+
|
| 1227 |
+
short_urls = await asyncio.gather(*(get_short_url(f) for f in files))
|
| 1228 |
+
|
| 1229 |
+
filter_status = ""
|
| 1230 |
+
if current_filters:
|
| 1231 |
+
disp_filters = [f.replace("Theatre Print [Clear Audio]", "Theatre Print") for f in current_filters]
|
| 1232 |
+
filter_status = f"🔍 **Active Filters:** `{', '.join(disp_filters)}`\n"
|
| 1233 |
+
sort_desc = "Default"
|
| 1234 |
+
if current_sort == "low_to_high":
|
| 1235 |
+
sort_desc = "Size: Low to High ⬇️"
|
| 1236 |
+
elif current_sort == "high_to_low":
|
| 1237 |
+
sort_desc = "Size: High to Low ⬆️"
|
| 1238 |
+
|
| 1239 |
+
result = (
|
| 1240 |
+
f"{header_prefix}"
|
| 1241 |
+
f"🎬 **Search Query:** `{search}`\n"
|
| 1242 |
+
f"📊 **Total Results:** `{count}`\n"
|
| 1243 |
+
f"📄 **Page:** `{crnt_pg}/{tot_pg}`\n"
|
| 1244 |
+
f"⚙️ **Precise Search:** `{precise_search}`\n"
|
| 1245 |
+
f"📐 **Result Mode:** `{search_md}`\n"
|
| 1246 |
+
f"{filter_status}"
|
| 1247 |
+
f"↕️ **Sort Order:** `{sort_desc}`\n"
|
| 1248 |
+
)
|
| 1249 |
+
|
| 1250 |
+
for idx, file in enumerate(files):
|
| 1251 |
+
file_id = file.file_id
|
| 1252 |
+
filename = f"[{get_size(file.file_size)}]{file.file_name}"
|
| 1253 |
+
short_url = short_urls[idx]
|
| 1254 |
+
|
| 1255 |
+
if button_mode == "ON":
|
| 1256 |
+
btn_kb = InlineKeyboardButton(text=f"{filename}", url=short_url)
|
| 1257 |
+
btn.append([btn_kb])
|
| 1258 |
+
elif link_mode == "ON":
|
| 1259 |
+
index += 1
|
| 1260 |
+
btn_count += 1
|
| 1261 |
+
filename = f"**{index}.** [{file.file_name}]({short_url}) - `[{get_size(file.file_size)}]`"
|
| 1262 |
+
result += "\n" + filename
|
| 1263 |
+
else:
|
| 1264 |
+
index += 1
|
| 1265 |
+
btn_count += 1
|
| 1266 |
+
filename = f"**{index}.** `{file.file_name}` - `[{get_size(file.file_size)}]`"
|
| 1267 |
+
result += "\n" + filename
|
| 1268 |
+
btn_kb = InlineKeyboardButton(text=f"{index}", url=short_url)
|
| 1269 |
+
if btn_count == 1 or btn_count == 6:
|
| 1270 |
+
btn.append([btn_kb])
|
| 1271 |
+
elif 6 > btn_count > 1:
|
| 1272 |
+
btn[0].append(btn_kb)
|
| 1273 |
+
else:
|
| 1274 |
+
btn[1].append(btn_kb)
|
| 1275 |
+
|
| 1276 |
+
h = query_hash or hashlib.md5(f"{search}_{user_id}".encode('utf-8')).hexdigest()[:12]
|
| 1277 |
+
if not query_hash:
|
| 1278 |
+
SEARCH_QUERY_CACHE.set(h, {
|
| 1279 |
+
"search": search,
|
| 1280 |
+
"filters": [],
|
| 1281 |
+
"sort": None
|
| 1282 |
+
})
|
| 1283 |
+
|
| 1284 |
+
filter_btn_label = f"🔍 Filter: {len(current_filters)}" if current_filters else "🔍 Filter: All"
|
| 1285 |
+
sort_btn_label = "↕️ Sort: Default"
|
| 1286 |
+
if current_sort == "low_to_high":
|
| 1287 |
+
sort_btn_label = "↕️ Sort: Low to High"
|
| 1288 |
+
elif current_sort == "high_to_low":
|
| 1289 |
+
sort_btn_label = "↕️ Sort: High to Low"
|
| 1290 |
+
top_row = [
|
| 1291 |
+
InlineKeyboardButton(filter_btn_label, callback_data=f"filter_menu {user_id} {h} {page_no}"),
|
| 1292 |
+
InlineKeyboardButton(sort_btn_label, callback_data=f"sort_menu {user_id} {h} {page_no}")
|
| 1293 |
+
]
|
| 1294 |
+
btn.insert(0, top_row)
|
| 1295 |
+
|
| 1296 |
+
page_btn = InlineKeyboardButton(f"📄 Page {crnt_pg}/{tot_pg}", callback_data="cb_noop")
|
| 1297 |
+
nav_row = []
|
| 1298 |
+
if crnt_pg > 1:
|
| 1299 |
+
nav_row.append(InlineKeyboardButton("⏪ Back", callback_data=f"prev_pg {user_id} {page_no - 1} {h}"))
|
| 1300 |
+
if crnt_pg < tot_pg:
|
| 1301 |
+
nav_row.append(InlineKeyboardButton("Next ⏩", callback_data=f"nxt_pg {user_id} {page_no + 1} {h}"))
|
| 1302 |
+
if tot_pg > 1:
|
| 1303 |
+
btn.append([page_btn])
|
| 1304 |
+
if nav_row:
|
| 1305 |
+
btn.append(nav_row)
|
| 1306 |
+
|
| 1307 |
+
btn.append([InlineKeyboardButton("❌ Close", callback_data=f"search_close {user_id}")])
|
| 1308 |
+
|
| 1309 |
+
if button_mode and link_mode == "OFF":
|
| 1310 |
+
result = result + "\n\n" + "🔻 __Tap on below corresponding file number to download.__ 🔻"
|
| 1311 |
+
elif link_mode == "ON":
|
| 1312 |
+
result = result + "\n\n" + " __Tap on file name & then start to download.__"
|
| 1313 |
+
|
| 1314 |
+
return result, btn, []
|
| 1315 |
+
|
| 1316 |
+
req_hash = hashlib.md5(original_search.encode('utf-8')).hexdigest()[:12]
|
| 1317 |
+
from mfinder.plugins.requests import REQUEST_QUERY_CACHE
|
| 1318 |
+
REQUEST_QUERY_CACHE.set(req_hash, original_search)
|
| 1319 |
+
original_search_esc = original_search.replace("[", "\\[").replace("]", "\\]")
|
| 1320 |
+
no_res_text = (
|
| 1321 |
+
f"❌ **No results found for** `{original_search_esc}`\n\n"
|
| 1322 |
+
f"💡 If this movie is missing, tap below to submit a request to our admins!"
|
| 1323 |
+
)
|
| 1324 |
+
no_res_btn = [[
|
| 1325 |
+
InlineKeyboardButton(text=f"📩 Request Movie: \"{original_search}\"", callback_data=f"req_send {req_hash}")
|
| 1326 |
+
]]
|
| 1327 |
+
return no_res_text, no_res_btn, []
|
| 1328 |
+
|
| 1329 |
+
@Client.on_callback_query(filters.regex(r"^file (.+)$"))
|
| 1330 |
+
async def get_files(bot, query):
|
| 1331 |
+
user_id = query.from_user.id
|
| 1332 |
+
asyncio.create_task(log_user_interaction(user_id))
|
| 1333 |
+
file_id = None
|
| 1334 |
+
if isinstance(query, CallbackQuery):
|
| 1335 |
+
file_id = query.data.split()[1]
|
| 1336 |
+
elif isinstance(query, Message):
|
| 1337 |
+
file_id = query.text.split()[1]
|
| 1338 |
+
if not await verify_force_sub(bot, query, pending_file_id=file_id):
|
| 1339 |
+
return
|
| 1340 |
+
admin_settings = await get_admin_settings()
|
| 1341 |
+
if admin_settings and admin_settings.repair_mode and user_id not in ADMINS:
|
| 1342 |
+
if isinstance(query, CallbackQuery):
|
| 1343 |
+
await query.answer("⚙️ Bot is under maintenance. Please try again later.", show_alert=True)
|
| 1344 |
+
elif isinstance(query, Message):
|
| 1345 |
+
await query.reply_text(
|
| 1346 |
+
"⚙️ **Bot Under Maintenance!**\n\nThe bot is currently undergoing scheduled maintenance or repair. Please try again later.",
|
| 1347 |
+
quote=True
|
| 1348 |
+
)
|
| 1349 |
+
return
|
| 1350 |
+
if admin_settings and admin_settings.token_shortener_enabled and user_id not in ADMINS:
|
| 1351 |
+
if not await is_token_valid(user_id):
|
| 1352 |
+
if isinstance(query, CallbackQuery):
|
| 1353 |
+
file_id = query.data.split()[1]
|
| 1354 |
+
await query.answer("⚠️ Access token expired. Generating a new link...", show_alert=True)
|
| 1355 |
+
await create_and_send_token_link(bot, query.message, admin_settings, target_file_id=file_id)
|
| 1356 |
+
elif isinstance(query, Message):
|
| 1357 |
+
file_id = query.text.split()[1]
|
| 1358 |
+
await create_and_send_token_link(bot, query, admin_settings, target_file_id=file_id)
|
| 1359 |
+
return
|
| 1360 |
+
if isinstance(query, CallbackQuery):
|
| 1361 |
+
file_id = query.data.split()[1]
|
| 1362 |
+
await query.answer("Sending file...", cache_time=60)
|
| 1363 |
+
cbq = True
|
| 1364 |
+
elif isinstance(query, Message):
|
| 1365 |
+
file_id = query.text.split()[1]
|
| 1366 |
+
cbq = False
|
| 1367 |
+
filedetails = await get_file_details(file_id)
|
| 1368 |
+
for files in filedetails:
|
| 1369 |
+
f_caption = files.caption
|
| 1370 |
+
if admin_settings.custom_caption:
|
| 1371 |
+
f_caption = f"**{admin_settings.custom_caption}**"
|
| 1372 |
+
elif f_caption is None:
|
| 1373 |
+
f_caption = f"**{files.file_name}**"
|
| 1374 |
+
else:
|
| 1375 |
+
f_caption = f"**{f_caption}**"
|
| 1376 |
+
if admin_settings.caption_uname:
|
| 1377 |
+
f_caption = f_caption + "\n" + admin_settings.caption_uname
|
| 1378 |
+
stream_url = os.environ.get("STREAM_URL")
|
| 1379 |
+
reply_markup = None
|
| 1380 |
+
if stream_url:
|
| 1381 |
+
import urllib.parse
|
| 1382 |
+
stream_url = stream_url.rstrip("/")
|
| 1383 |
+
quoted_filename = urllib.parse.quote(files.file_name)
|
| 1384 |
+
download_url = f"{stream_url}/dl/{quoted_filename}"
|
| 1385 |
+
reply_markup = InlineKeyboardMarkup([
|
| 1386 |
+
[InlineKeyboardButton("🌐 Direct Browser Download 🌐", url=download_url)]
|
| 1387 |
+
])
|
| 1388 |
+
if cbq:
|
| 1389 |
+
msg = await query.message.reply_cached_media(
|
| 1390 |
+
file_id=file_id,
|
| 1391 |
+
caption=f_caption,
|
| 1392 |
+
parse_mode=ParseMode.MARKDOWN,
|
| 1393 |
+
reply_markup=reply_markup,
|
| 1394 |
+
quote=True,
|
| 1395 |
+
)
|
| 1396 |
+
else:
|
| 1397 |
+
msg = await query.reply_cached_media(
|
| 1398 |
+
file_id=file_id,
|
| 1399 |
+
caption=f_caption,
|
| 1400 |
+
parse_mode=ParseMode.MARKDOWN,
|
| 1401 |
+
reply_markup=reply_markup,
|
| 1402 |
+
quote=True,
|
| 1403 |
+
)
|
| 1404 |
+
user_target = query.from_user if hasattr(query, "from_user") and query.from_user else None
|
| 1405 |
+
if user_target:
|
| 1406 |
+
asyncio.create_task(
|
| 1407 |
+
log_file_delivery(
|
| 1408 |
+
bot=bot,
|
| 1409 |
+
user=user_target,
|
| 1410 |
+
file_name=files.file_name,
|
| 1411 |
+
file_size=get_size(files.file_size),
|
| 1412 |
+
file_id=files.file_id
|
| 1413 |
+
)
|
| 1414 |
+
)
|
| 1415 |
+
if admin_settings.auto_delete:
|
| 1416 |
+
delay_dur = float(admin_settings.auto_delete)
|
| 1417 |
+
delay = delay_dur / 60 if delay_dur > 60 else delay_dur
|
| 1418 |
+
delay = round(delay, 2)
|
| 1419 |
+
minsec = str(delay) + " mins" if delay_dur > 60 else str(delay) + " secs"
|
| 1420 |
+
disc = await bot.send_message(
|
| 1421 |
+
user_id,
|
| 1422 |
+
f"Please save the file to your saved messages, it will be deleted in {minsec}",
|
| 1423 |
+
)
|
| 1424 |
+
await asyncio.sleep(delay_dur)
|
| 1425 |
+
await disc.delete()
|
| 1426 |
+
await msg.delete()
|
| 1427 |
+
# Removed file deletion notification (deleted silently)
|
| 1428 |
+
|
| 1429 |
+
def get_size(size):
|
| 1430 |
+
units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"]
|
| 1431 |
+
size = float(size)
|
| 1432 |
+
i = 0
|
| 1433 |
+
while size >= 1024.0 and i < len(units):
|
| 1434 |
+
i += 1
|
| 1435 |
+
size /= 1024.0
|
| 1436 |
+
return f"{size:.2f} {units[i]}"
|
| 1437 |
+
|
| 1438 |
+
@Client.on_callback_query(filters.regex(r"^(filter_menu|sort_menu) \d+ \w+ \d+$"))
|
| 1439 |
+
async def filter_or_sort_menu_callback(bot, query):
|
| 1440 |
+
user_id = query.from_user.id
|
| 1441 |
+
data_parts = query.data.split()
|
| 1442 |
+
action = data_parts[0]
|
| 1443 |
+
org_user_id = int(data_parts[1])
|
| 1444 |
+
query_hash = data_parts[2]
|
| 1445 |
+
page_no = int(data_parts[3])
|
| 1446 |
+
if user_id != org_user_id:
|
| 1447 |
+
await query.answer("⚠️ This is not your search session!", show_alert=True)
|
| 1448 |
+
return
|
| 1449 |
+
admin_settings = await get_admin_settings()
|
| 1450 |
+
if admin_settings and admin_settings.repair_mode and user_id not in ADMINS:
|
| 1451 |
+
await query.answer("⚙️ Bot is under maintenance.", show_alert=True)
|
| 1452 |
+
return
|
| 1453 |
+
state = SEARCH_QUERY_CACHE.get(query_hash)
|
| 1454 |
+
if not state:
|
| 1455 |
+
await query.answer("⚠️ Search session has expired.", show_alert=True)
|
| 1456 |
+
return
|
| 1457 |
+
search = state.get("search")
|
| 1458 |
+
current_filters = state.get("filters") or []
|
| 1459 |
+
from mfinder.db.settings_sql import get_search_settings
|
| 1460 |
+
from mfinder.db.files_sql import get_filter_results, get_precise_filter_results
|
| 1461 |
+
search_settings = await get_search_settings(user_id)
|
| 1462 |
+
if search_settings and search_settings.precise_mode:
|
| 1463 |
+
files_all, _ = await get_precise_filter_results(query=search, page=1, per_page=1000)
|
| 1464 |
+
else:
|
| 1465 |
+
files_all, _ = await get_filter_results(query=search, page=1, per_page=1000)
|
| 1466 |
+
if action == "filter_menu":
|
| 1467 |
+
qualities, seasons = extract_qualities_and_seasons(files_all)
|
| 1468 |
+
quality_buttons = [
|
| 1469 |
+
InlineKeyboardButton(f"{'🟢 ' if q in current_filters else '⚪ '}{'Theatre Print' if q == 'Theatre Print [Clear Audio]' else q}", callback_data=f"toggle_filter {org_user_id} {query_hash} {page_no} {'TP_CA' if q == 'Theatre Print [Clear Audio]' else q}")
|
| 1470 |
+
for q in qualities
|
| 1471 |
+
]
|
| 1472 |
+
season_buttons = [
|
| 1473 |
+
InlineKeyboardButton(f"{'🟢 ' if s in current_filters else '⚪ '}{s}", callback_data=f"toggle_filter {org_user_id} {query_hash} {page_no} {s}")
|
| 1474 |
+
for s in seasons
|
| 1475 |
+
]
|
| 1476 |
+
def chunk_list(lst, n):
|
| 1477 |
+
return [lst[i:i + n] for i in range(0, len(lst), n)]
|
| 1478 |
+
kb_buttons = []
|
| 1479 |
+
if quality_buttons:
|
| 1480 |
+
kb_buttons.append([InlineKeyboardButton("🖥️ QUALITY FILTERS 🖥️", callback_data="cb_noop")])
|
| 1481 |
+
kb_buttons.extend(chunk_list(quality_buttons, 3))
|
| 1482 |
+
if season_buttons:
|
| 1483 |
+
kb_buttons.append([InlineKeyboardButton("📦 SEASON FILTERS 📦", callback_data="cb_noop")])
|
| 1484 |
+
kb_buttons.extend(chunk_list(season_buttons, 3))
|
| 1485 |
+
kb_buttons.append([InlineKeyboardButton("✅ Apply Filters", callback_data=f"apply_filters_action {org_user_id} {query_hash} {page_no}")])
|
| 1486 |
+
if current_filters:
|
| 1487 |
+
kb_buttons.append([InlineKeyboardButton("🗑️ Clear All", callback_data=f"clear_filters_action {org_user_id} {query_hash} {page_no}")])
|
| 1488 |
+
kb_buttons.append([InlineKeyboardButton("🔙 Cancel", callback_data=f"back_to_results {org_user_id} {query_hash} {page_no}")])
|
| 1489 |
+
text = f"🔍 **Filter Search Results for:** `{search}`\n\nSelect one or more filters below (active selections marked with 🟢):"
|
| 1490 |
+
try:
|
| 1491 |
+
await query.message.edit_text(text, reply_markup=InlineKeyboardMarkup(kb_buttons))
|
| 1492 |
+
except Exception:
|
| 1493 |
+
pass
|
| 1494 |
+
elif action == "sort_menu":
|
| 1495 |
+
current_sort = state.get("sort")
|
| 1496 |
+
is_lh = current_sort == "low_to_high"
|
| 1497 |
+
is_hl = current_sort == "high_to_low"
|
| 1498 |
+
is_def = current_sort is None
|
| 1499 |
+
lh_prefix = "🟢 " if is_lh else "⚪ "
|
| 1500 |
+
hl_prefix = "🟢 " if is_hl else "⚪ "
|
| 1501 |
+
def_prefix = "🟢 " if is_def else "⚪ "
|
| 1502 |
+
kb_buttons = [
|
| 1503 |
+
[InlineKeyboardButton(f"{lh_prefix}Size: Low to High", callback_data=f"toggle_sort {org_user_id} {query_hash} {page_no} low_to_high")],
|
| 1504 |
+
[InlineKeyboardButton(f"{hl_prefix}Size: High to Low", callback_data=f"toggle_sort {org_user_id} {query_hash} {page_no} high_to_low")],
|
| 1505 |
+
[InlineKeyboardButton(f"{def_prefix}Default Order", callback_data=f"toggle_sort {org_user_id} {query_hash} {page_no} default")],
|
| 1506 |
+
[InlineKeyboardButton("✅ Apply Sort", callback_data=f"apply_sort_action {org_user_id} {query_hash} {page_no}")],
|
| 1507 |
+
[InlineKeyboardButton("🔙 Cancel", callback_data=f"back_to_results {org_user_id} {query_hash} {page_no}")]
|
| 1508 |
+
]
|
| 1509 |
+
text = f"↕️ **Sort Search Results for:** `{search}`\n\nSelect a file size sorting option (active selection marked with 🟢):"
|
| 1510 |
+
try:
|
| 1511 |
+
await query.message.edit_text(text, reply_markup=InlineKeyboardMarkup(kb_buttons))
|
| 1512 |
+
except Exception:
|
| 1513 |
+
pass
|
| 1514 |
+
await query.answer()
|
| 1515 |
+
|
| 1516 |
+
@Client.on_callback_query(filters.regex(r"^toggle_filter \d+ \w+ \d+ (.+)$"))
|
| 1517 |
+
async def toggle_filter_callback(bot, query):
|
| 1518 |
+
user_id = query.from_user.id
|
| 1519 |
+
data_parts = query.data.split(None, 4)
|
| 1520 |
+
org_user_id = int(data_parts[1])
|
| 1521 |
+
query_hash = data_parts[2]
|
| 1522 |
+
page_no = int(data_parts[3])
|
| 1523 |
+
value = data_parts[4]
|
| 1524 |
+
if value == "TP_CA":
|
| 1525 |
+
value = "Theatre Print [Clear Audio]"
|
| 1526 |
+
if user_id != org_user_id:
|
| 1527 |
+
await query.answer("⚠️ This is not your search session!", show_alert=True)
|
| 1528 |
+
return
|
| 1529 |
+
state = SEARCH_QUERY_CACHE.get(query_hash)
|
| 1530 |
+
if not state:
|
| 1531 |
+
await query.answer("⚠️ Search session has expired.", show_alert=True)
|
| 1532 |
+
return
|
| 1533 |
+
filters_list = state.get("filters") or []
|
| 1534 |
+
if value in filters_list:
|
| 1535 |
+
filters_list.remove(value)
|
| 1536 |
+
else:
|
| 1537 |
+
filters_list.append(value)
|
| 1538 |
+
state["filters"] = filters_list
|
| 1539 |
+
SEARCH_QUERY_CACHE.set(query_hash, state)
|
| 1540 |
+
search = state.get("search")
|
| 1541 |
+
from mfinder.db.settings_sql import get_search_settings
|
| 1542 |
+
from mfinder.db.files_sql import get_filter_results, get_precise_filter_results
|
| 1543 |
+
search_settings = await get_search_settings(user_id)
|
| 1544 |
+
if search_settings and search_settings.precise_mode:
|
| 1545 |
+
files_all, _ = await get_precise_filter_results(query=search, page=1, per_page=1000)
|
| 1546 |
+
else:
|
| 1547 |
+
files_all, _ = await get_filter_results(query=search, page=1, per_page=1000)
|
| 1548 |
+
qualities, seasons = extract_qualities_and_seasons(files_all)
|
| 1549 |
+
quality_buttons = [
|
| 1550 |
+
InlineKeyboardButton(f"{'🟢 ' if q in filters_list else '⚪ '}{'Theatre Print' if q == 'Theatre Print [Clear Audio]' else q}", callback_data=f"toggle_filter {org_user_id} {query_hash} {page_no} {'TP_CA' if q == 'Theatre Print [Clear Audio]' else q}")
|
| 1551 |
+
for q in qualities
|
| 1552 |
+
]
|
| 1553 |
+
season_buttons = [
|
| 1554 |
+
InlineKeyboardButton(f"{'🟢 ' if s in filters_list else '⚪ '}{s}", callback_data=f"toggle_filter {org_user_id} {query_hash} {page_no} {s}")
|
| 1555 |
+
for s in seasons
|
| 1556 |
+
]
|
| 1557 |
+
def chunk_list(lst, n):
|
| 1558 |
+
return [lst[i:i + n] for i in range(0, len(lst), n)]
|
| 1559 |
+
kb_buttons = []
|
| 1560 |
+
if quality_buttons:
|
| 1561 |
+
kb_buttons.append([InlineKeyboardButton("🖥️ QUALITY FILTERS 🖥️", callback_data="cb_noop")])
|
| 1562 |
+
kb_buttons.extend(chunk_list(quality_buttons, 3))
|
| 1563 |
+
if season_buttons:
|
| 1564 |
+
kb_buttons.append([InlineKeyboardButton("📦 SEASON FILTERS 📦", callback_data="cb_noop")])
|
| 1565 |
+
kb_buttons.extend(chunk_list(season_buttons, 3))
|
| 1566 |
+
kb_buttons.append([InlineKeyboardButton("✅ Apply Filters", callback_data=f"apply_filters_action {org_user_id} {query_hash} {page_no}")])
|
| 1567 |
+
if filters_list:
|
| 1568 |
+
kb_buttons.append([InlineKeyboardButton("🗑️ Clear All", callback_data=f"clear_filters_action {org_user_id} {query_hash} {page_no}")])
|
| 1569 |
+
kb_buttons.append([InlineKeyboardButton("🔙 Cancel", callback_data=f"back_to_results {org_user_id} {query_hash} {page_no}")])
|
| 1570 |
+
text = f"🔍 **Filter Search Results for:** `{search}`\n\nSelect one or more filters below (active selections marked with 🟢):"
|
| 1571 |
+
try:
|
| 1572 |
+
await query.message.edit_text(text, reply_markup=InlineKeyboardMarkup(kb_buttons))
|
| 1573 |
+
except Exception:
|
| 1574 |
+
pass
|
| 1575 |
+
await query.answer()
|
| 1576 |
+
|
| 1577 |
+
@Client.on_callback_query(filters.regex(r"^clear_filters_action \d+ \w+ \d+$"))
|
| 1578 |
+
async def clear_filters_callback(bot, query):
|
| 1579 |
+
user_id = query.from_user.id
|
| 1580 |
+
data_parts = query.data.split()
|
| 1581 |
+
org_user_id = int(data_parts[1])
|
| 1582 |
+
query_hash = data_parts[2]
|
| 1583 |
+
page_no = int(data_parts[3])
|
| 1584 |
+
if user_id != org_user_id:
|
| 1585 |
+
await query.answer("⚠️ This is not your search session!", show_alert=True)
|
| 1586 |
+
return
|
| 1587 |
+
state = SEARCH_QUERY_CACHE.get(query_hash)
|
| 1588 |
+
if not state:
|
| 1589 |
+
await query.answer("⚠️ Search session has expired.", show_alert=True)
|
| 1590 |
+
return
|
| 1591 |
+
state["filters"] = []
|
| 1592 |
+
SEARCH_QUERY_CACHE.set(query_hash, state)
|
| 1593 |
+
search = state.get("search")
|
| 1594 |
+
from mfinder.db.settings_sql import get_search_settings
|
| 1595 |
+
from mfinder.db.files_sql import get_filter_results, get_precise_filter_results
|
| 1596 |
+
search_settings = await get_search_settings(user_id)
|
| 1597 |
+
if search_settings and search_settings.precise_mode:
|
| 1598 |
+
files_all, _ = await get_precise_filter_results(query=search, page=1, per_page=1000)
|
| 1599 |
+
else:
|
| 1600 |
+
files_all, _ = await get_filter_results(query=search, page=1, per_page=1000)
|
| 1601 |
+
qualities, seasons = extract_qualities_and_seasons(files_all)
|
| 1602 |
+
quality_buttons = [
|
| 1603 |
+
InlineKeyboardButton(f"⚪ {q}", callback_data=f"toggle_filter {org_user_id} {query_hash} {page_no} {q}")
|
| 1604 |
+
for q in qualities
|
| 1605 |
+
]
|
| 1606 |
+
season_buttons = [
|
| 1607 |
+
InlineKeyboardButton(f"⚪ {s}", callback_data=f"toggle_filter {org_user_id} {query_hash} {page_no} {s}")
|
| 1608 |
+
for s in seasons
|
| 1609 |
+
]
|
| 1610 |
+
def chunk_list(lst, n):
|
| 1611 |
+
return [lst[i:i + n] for i in range(0, len(lst), n)]
|
| 1612 |
+
kb_buttons = []
|
| 1613 |
+
if quality_buttons:
|
| 1614 |
+
kb_buttons.append([InlineKeyboardButton("🖥️ QUALITY FILTERS 🖥️", callback_data="cb_noop")])
|
| 1615 |
+
kb_buttons.extend(chunk_list(quality_buttons, 3))
|
| 1616 |
+
if season_buttons:
|
| 1617 |
+
kb_buttons.append([InlineKeyboardButton("📦 SEASON FILTERS 📦", callback_data="cb_noop")])
|
| 1618 |
+
kb_buttons.extend(chunk_list(season_buttons, 3))
|
| 1619 |
+
kb_buttons.append([InlineKeyboardButton("✅ Apply Filters", callback_data=f"apply_filters_action {org_user_id} {query_hash} {page_no}")])
|
| 1620 |
+
kb_buttons.append([InlineKeyboardButton("🔙 Cancel", callback_data=f"back_to_results {org_user_id} {query_hash} {page_no}")])
|
| 1621 |
+
text = f"🔍 **Filter Search Results for:** `{search}`\n\nSelect one or more filters below (active selections marked with 🟢):"
|
| 1622 |
+
try:
|
| 1623 |
+
await query.message.edit_text(text, reply_markup=InlineKeyboardMarkup(kb_buttons))
|
| 1624 |
+
except Exception:
|
| 1625 |
+
pass
|
| 1626 |
+
await query.answer("Filters cleared!")
|
| 1627 |
+
|
| 1628 |
+
@Client.on_callback_query(filters.regex(r"^toggle_sort \d+ \w+ \d+ (\w+)$"))
|
| 1629 |
+
async def toggle_sort_callback(bot, query):
|
| 1630 |
+
user_id = query.from_user.id
|
| 1631 |
+
data_parts = query.data.split()
|
| 1632 |
+
org_user_id = int(data_parts[1])
|
| 1633 |
+
query_hash = data_parts[2]
|
| 1634 |
+
page_no = int(data_parts[3])
|
| 1635 |
+
value = data_parts[4]
|
| 1636 |
+
if value == "TP_CA":
|
| 1637 |
+
value = "Theatre Print [Clear Audio]"
|
| 1638 |
+
if user_id != org_user_id:
|
| 1639 |
+
await query.answer("⚠️ This is not your search session!", show_alert=True)
|
| 1640 |
+
return
|
| 1641 |
+
state = SEARCH_QUERY_CACHE.get(query_hash)
|
| 1642 |
+
if not state:
|
| 1643 |
+
await query.answer("⚠️ Search session has expired.", show_alert=True)
|
| 1644 |
+
return
|
| 1645 |
+
if value == "default":
|
| 1646 |
+
state["sort"] = None
|
| 1647 |
+
else:
|
| 1648 |
+
state["sort"] = value
|
| 1649 |
+
SEARCH_QUERY_CACHE.set(query_hash, state)
|
| 1650 |
+
current_sort = state.get("sort")
|
| 1651 |
+
is_lh = current_sort == "low_to_high"
|
| 1652 |
+
is_hl = current_sort == "high_to_low"
|
| 1653 |
+
is_def = current_sort is None
|
| 1654 |
+
lh_prefix = "🟢 " if is_lh else "⚪ "
|
| 1655 |
+
hl_prefix = "🟢 " if is_hl else "⚪ "
|
| 1656 |
+
def_prefix = "🟢 " if is_def else "⚪ "
|
| 1657 |
+
kb_buttons = [
|
| 1658 |
+
[InlineKeyboardButton(f"{lh_prefix}Size: Low to High", callback_data=f"toggle_sort {org_user_id} {query_hash} {page_no} low_to_high")],
|
| 1659 |
+
[InlineKeyboardButton(f"{hl_prefix}Size: High to Low", callback_data=f"toggle_sort {org_user_id} {query_hash} {page_no} high_to_low")],
|
| 1660 |
+
[InlineKeyboardButton(f"{def_prefix}Default Order", callback_data=f"toggle_sort {org_user_id} {query_hash} {page_no} default")],
|
| 1661 |
+
[InlineKeyboardButton("✅ Apply Sort", callback_data=f"apply_sort_action {org_user_id} {query_hash} {page_no}")],
|
| 1662 |
+
[InlineKeyboardButton("🔙 Cancel", callback_data=f"back_to_results {org_user_id} {query_hash} {page_no}")]
|
| 1663 |
+
]
|
| 1664 |
+
text = f"↕️ **Sort Search Results for:** `{state.get('search')}`\n\nSelect a file size sorting option (active selection marked with 🟢):"
|
| 1665 |
+
try:
|
| 1666 |
+
await query.message.edit_text(text, reply_markup=InlineKeyboardMarkup(kb_buttons))
|
| 1667 |
+
except Exception:
|
| 1668 |
+
pass
|
| 1669 |
+
await query.answer()
|
| 1670 |
+
|
| 1671 |
+
@Client.on_callback_query(filters.regex(r"^(apply_filters_action|apply_sort_action) \d+ \w+ \d+$"))
|
| 1672 |
+
async def apply_filters_or_sort_action_callback(bot, query):
|
| 1673 |
+
user_id = query.from_user.id
|
| 1674 |
+
data_parts = query.data.split()
|
| 1675 |
+
action = data_parts[0]
|
| 1676 |
+
org_user_id = int(data_parts[1])
|
| 1677 |
+
query_hash = data_parts[2]
|
| 1678 |
+
page_no = 1
|
| 1679 |
+
if user_id != org_user_id:
|
| 1680 |
+
await query.answer("⚠️ This is not your search session!", show_alert=True)
|
| 1681 |
+
return
|
| 1682 |
+
state = SEARCH_QUERY_CACHE.get(query_hash)
|
| 1683 |
+
if not state:
|
| 1684 |
+
await query.answer("⚠️ Search session has expired.", show_alert=True)
|
| 1685 |
+
return
|
| 1686 |
+
me = bot.me
|
| 1687 |
+
username = me.username
|
| 1688 |
+
result, btn, suggestions = await get_result(state["search"], page_no, user_id, username, query_hash=query_hash)
|
| 1689 |
+
if result:
|
| 1690 |
+
try:
|
| 1691 |
+
if btn:
|
| 1692 |
+
await query.message.edit_text(
|
| 1693 |
+
f"{result}",
|
| 1694 |
+
reply_markup=InlineKeyboardMarkup(btn),
|
| 1695 |
+
disable_web_page_preview=True,
|
| 1696 |
+
)
|
| 1697 |
+
else:
|
| 1698 |
+
await query.message.edit_text(
|
| 1699 |
+
f"{result}",
|
| 1700 |
+
disable_web_page_preview=True,
|
| 1701 |
+
)
|
| 1702 |
+
except Exception:
|
| 1703 |
+
pass
|
| 1704 |
+
else:
|
| 1705 |
+
await query.answer("No files match the active filters.", show_alert=True)
|
| 1706 |
+
await query.answer()
|
| 1707 |
+
|
| 1708 |
+
@Client.on_callback_query(filters.regex(r"^back_to_results \d+ \w+ \d+$"))
|
| 1709 |
+
async def back_to_results_callback(bot, query):
|
| 1710 |
+
user_id = query.from_user.id
|
| 1711 |
+
data_parts = query.data.split()
|
| 1712 |
+
org_user_id = int(data_parts[1])
|
| 1713 |
+
query_hash = data_parts[2]
|
| 1714 |
+
page_no = int(data_parts[3])
|
| 1715 |
+
if user_id != org_user_id:
|
| 1716 |
+
await query.answer("⚠️ This is not your search session!", show_alert=True)
|
| 1717 |
+
return
|
| 1718 |
+
state = SEARCH_QUERY_CACHE.get(query_hash)
|
| 1719 |
+
if not state:
|
| 1720 |
+
await query.answer("⚠️ Search session has expired.", show_alert=True)
|
| 1721 |
+
return
|
| 1722 |
+
me = bot.me
|
| 1723 |
+
username = me.username
|
| 1724 |
+
result, btn, suggestions = await get_result(state["search"], page_no, user_id, username, query_hash=query_hash)
|
| 1725 |
+
if result:
|
| 1726 |
+
try:
|
| 1727 |
+
if btn:
|
| 1728 |
+
await query.message.edit_text(
|
| 1729 |
+
f"{result}",
|
| 1730 |
+
reply_markup=InlineKeyboardMarkup(btn),
|
| 1731 |
+
disable_web_page_preview=True,
|
| 1732 |
+
)
|
| 1733 |
+
else:
|
| 1734 |
+
await query.message.edit_text(
|
| 1735 |
+
f"{result}",
|
| 1736 |
+
disable_web_page_preview=True,
|
| 1737 |
+
)
|
| 1738 |
+
except Exception:
|
| 1739 |
+
pass
|
| 1740 |
+
await query.answer()
|
| 1741 |
+
|
| 1742 |
+
@Client.on_callback_query(filters.regex(r"^cb_noop$"))
|
| 1743 |
+
async def cb_noop_callback(bot, query):
|
| 1744 |
+
await query.answer()
|
| 1745 |
+
|
| 1746 |
+
@Client.on_callback_query(filters.regex(r"^search_close \d+$"))
|
| 1747 |
+
async def search_close_callback(bot, query):
|
| 1748 |
+
org_user_id = int(query.data.split()[1])
|
| 1749 |
+
if query.from_user.id != org_user_id:
|
| 1750 |
+
await query.answer("⚠️ This is not your search result!", show_alert=True)
|
| 1751 |
+
return
|
| 1752 |
+
try:
|
| 1753 |
+
await query.message.delete()
|
| 1754 |
+
except Exception:
|
| 1755 |
+
pass
|
| 1756 |
+
await query.answer("Search results closed.")
|
mfinder/plugins/stream_server.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import asyncio
|
| 66 |
+
queue = asyncio.Queue(maxsize=3)
|
| 67 |
+
|
| 68 |
+
async def producer():
|
| 69 |
+
try:
|
| 70 |
+
async for chunk in stream_client.stream_media(file_id, offset=chunk_offset):
|
| 71 |
+
await queue.put(chunk)
|
| 72 |
+
await queue.put(None)
|
| 73 |
+
except Exception as e:
|
| 74 |
+
print(f"Error in producer: {e}")
|
| 75 |
+
await queue.put(None)
|
| 76 |
+
|
| 77 |
+
producer_task = asyncio.create_task(producer())
|
| 78 |
+
bytes_sent = 0
|
| 79 |
+
try:
|
| 80 |
+
first = True
|
| 81 |
+
while True:
|
| 82 |
+
chunk = await queue.get()
|
| 83 |
+
if chunk is None:
|
| 84 |
+
break
|
| 85 |
+
|
| 86 |
+
if first:
|
| 87 |
+
first = False
|
| 88 |
+
if skip_bytes > 0:
|
| 89 |
+
chunk = chunk[skip_bytes:]
|
| 90 |
+
|
| 91 |
+
if bytes_sent + len(chunk) > content_length:
|
| 92 |
+
chunk = chunk[:content_length - bytes_sent]
|
| 93 |
+
|
| 94 |
+
if not chunk:
|
| 95 |
+
break
|
| 96 |
+
|
| 97 |
+
yield chunk
|
| 98 |
+
bytes_sent += len(chunk)
|
| 99 |
+
|
| 100 |
+
if bytes_sent >= content_length:
|
| 101 |
+
break
|
| 102 |
+
except Exception as e:
|
| 103 |
+
print(f"Error occurred while streaming file '{decoded_file_name}': {e}")
|
| 104 |
+
finally:
|
| 105 |
+
producer_task.cancel()
|
| 106 |
+
try:
|
| 107 |
+
await producer_task
|
| 108 |
+
except asyncio.CancelledError:
|
| 109 |
+
pass
|
| 110 |
+
except Exception as ex:
|
| 111 |
+
print(f"Error clean cancelling producer: {ex}")
|
| 112 |
+
|
| 113 |
+
headers = {
|
| 114 |
+
"Content-Disposition": f"attachment; filename=\"{decoded_file_name}\"; filename*=UTF-8''{urllib.parse.quote(decoded_file_name)}",
|
| 115 |
+
"Content-Length": str(content_length),
|
| 116 |
+
"Accept-Ranges": "bytes"
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
if range:
|
| 120 |
+
headers["Content-Range"] = f"bytes {start_bytes}-{end_bytes}/{file_size}"
|
| 121 |
+
return StreamingResponse(media_generator(), status_code=206, media_type=mime_type, headers=headers)
|
| 122 |
+
else:
|
| 123 |
+
return StreamingResponse(media_generator(), status_code=200, media_type=mime_type, headers=headers)
|
mfinder/plugins/trending.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
cl_title = item[0]
|
| 28 |
+
count_files = item[1]
|
| 29 |
+
year = item[2] if len(item) > 2 else None
|
| 30 |
+
season_str = item[3] if len(item) > 3 else None
|
| 31 |
+
|
| 32 |
+
display_title = f"{cl_title} ({year})" if year else cl_title
|
| 33 |
+
if season_str:
|
| 34 |
+
display_title = f"{display_title} {season_str}"
|
| 35 |
+
|
| 36 |
+
search_query = f"{cl_title} {year}" if year else cl_title
|
| 37 |
+
if season_str:
|
| 38 |
+
search_query = f"{search_query} {season_str}"
|
| 39 |
+
|
| 40 |
+
h = hashlib.md5(search_query.encode('utf-8')).hexdigest()[:12]
|
| 41 |
+
MOVIE_CALLBACK_CACHE.set(h, (search_query, "Trending List"))
|
| 42 |
+
buttons.append([
|
| 43 |
+
InlineKeyboardButton(
|
| 44 |
+
text=f"🎬 {display_title} — {count_files} file{'s' if count_files > 1 else ''}",
|
| 45 |
+
callback_data=f"m_s {h}"
|
| 46 |
+
)
|
| 47 |
+
])
|
| 48 |
+
|
| 49 |
+
text = "🔥 **Top Trending Movies This Week**\n\n👇 Select a movie below to view files:"
|
| 50 |
+
reply_msg = await message.reply_text(
|
| 51 |
+
text=text,
|
| 52 |
+
reply_markup=InlineKeyboardMarkup(buttons),
|
| 53 |
+
parse_mode=ParseMode.MARKDOWN,
|
| 54 |
+
quote=True
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
# Auto-delete message after 15 minutes or configured duration persistently
|
| 58 |
+
from mfinder.plugins.serve import auto_delete_search_result
|
| 59 |
+
asyncio.create_task(auto_delete_search_result(bot, reply_msg))
|
| 60 |
+
|
| 61 |
+
@Client.on_message(filters.command(["newuploads"]) & filters.private)
|
| 62 |
+
async def new_uploads_command(bot, message):
|
| 63 |
+
"""Displays latest 25 newly uploaded movies in descending order."""
|
| 64 |
+
if not await verify_force_sub(bot, message, pending_query="/newuploads"):
|
| 65 |
+
return
|
| 66 |
+
latest_list = await get_latest_uploaded_movies(limit=25)
|
| 67 |
+
|
| 68 |
+
if not latest_list:
|
| 69 |
+
await message.reply_text("ℹ️ **No newly uploaded movies available.**", quote=True)
|
| 70 |
+
return
|
| 71 |
+
|
| 72 |
+
buttons = []
|
| 73 |
+
for item in latest_list:
|
| 74 |
+
cl_title = item[0]
|
| 75 |
+
count_files = item[1]
|
| 76 |
+
year = item[2] if len(item) > 2 else None
|
| 77 |
+
season_str = item[3] if len(item) > 3 else None
|
| 78 |
+
|
| 79 |
+
display_title = f"{cl_title} ({year})" if year else cl_title
|
| 80 |
+
if season_str:
|
| 81 |
+
display_title = f"{display_title} {season_str}"
|
| 82 |
+
|
| 83 |
+
search_query = f"{cl_title} {year}" if year else cl_title
|
| 84 |
+
if season_str:
|
| 85 |
+
search_query = f"{search_query} {season_str}"
|
| 86 |
+
|
| 87 |
+
h = hashlib.md5(search_query.encode('utf-8')).hexdigest()[:12]
|
| 88 |
+
MOVIE_CALLBACK_CACHE.set(h, (search_query, "New Uploads List"))
|
| 89 |
+
buttons.append([
|
| 90 |
+
InlineKeyboardButton(
|
| 91 |
+
text=f"🎬 {display_title} — {count_files} file{'s' if count_files > 1 else ''}",
|
| 92 |
+
callback_data=f"m_s {h}"
|
| 93 |
+
)
|
| 94 |
+
])
|
| 95 |
+
|
| 96 |
+
text = f"🆕 **Newly Uploaded Movies (Top 25)**\n\n👇 Select a movie below to view files:"
|
| 97 |
+
reply_msg = await message.reply_text(
|
| 98 |
+
text=text,
|
| 99 |
+
reply_markup=InlineKeyboardMarkup(buttons),
|
| 100 |
+
parse_mode=ParseMode.MARKDOWN,
|
| 101 |
+
quote=True
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
# Auto-delete message after 15 minutes or configured duration persistently
|
| 105 |
+
from mfinder.plugins.serve import auto_delete_search_result
|
| 106 |
+
asyncio.create_task(auto_delete_search_result(bot, reply_msg))
|
| 107 |
+
|
| 108 |
+
@Client.on_callback_query(filters.regex(r"^(trnd_list|new_up_list)$"))
|
| 109 |
+
async def trending_newuploads_callback(bot, query):
|
| 110 |
+
"""Handles callback buttons for Trending and New Uploads by editing message in-place."""
|
| 111 |
+
action = query.data
|
| 112 |
+
pending = "/trending" if action == "trnd_list" else "/newuploads"
|
| 113 |
+
if not await verify_force_sub(bot, query, pending_query=pending):
|
| 114 |
+
return
|
| 115 |
+
action = query.data
|
| 116 |
+
if action == "trnd_list":
|
| 117 |
+
trending_list = await get_top_trending_movies(limit=10)
|
| 118 |
+
|
| 119 |
+
if not trending_list:
|
| 120 |
+
await query.answer("ℹ️ No trending movies data available for this week yet.", show_alert=True)
|
| 121 |
+
return
|
| 122 |
+
|
| 123 |
+
buttons = []
|
| 124 |
+
for item in trending_list:
|
| 125 |
+
cl_title = item[0]
|
| 126 |
+
count_files = item[1]
|
| 127 |
+
year = item[2] if len(item) > 2 else None
|
| 128 |
+
season_str = item[3] if len(item) > 3 else None
|
| 129 |
+
|
| 130 |
+
display_title = f"{cl_title} ({year})" if year else cl_title
|
| 131 |
+
if season_str:
|
| 132 |
+
display_title = f"{display_title} {season_str}"
|
| 133 |
+
|
| 134 |
+
search_query = f"{cl_title} {year}" if year else cl_title
|
| 135 |
+
if season_str:
|
| 136 |
+
search_query = f"{search_query} {season_str}"
|
| 137 |
+
|
| 138 |
+
h = hashlib.md5(search_query.encode('utf-8')).hexdigest()[:12]
|
| 139 |
+
MOVIE_CALLBACK_CACHE.set(h, (search_query, "Trending List"))
|
| 140 |
+
buttons.append([
|
| 141 |
+
InlineKeyboardButton(
|
| 142 |
+
text=f"🎬 {display_title} — {count_files} file{'s' if count_files > 1 else ''}",
|
| 143 |
+
callback_data=f"m_s {h}"
|
| 144 |
+
)
|
| 145 |
+
])
|
| 146 |
+
|
| 147 |
+
buttons.append([
|
| 148 |
+
InlineKeyboardButton("🔙 Back to Menu", callback_data="back_m")
|
| 149 |
+
])
|
| 150 |
+
|
| 151 |
+
text = "🔥 **Top Trending Movies This Week**\n\n👇 Select a movie below to view files:"
|
| 152 |
+
await query.answer()
|
| 153 |
+
try:
|
| 154 |
+
await query.message.edit_text(
|
| 155 |
+
text=text,
|
| 156 |
+
reply_markup=InlineKeyboardMarkup(buttons),
|
| 157 |
+
parse_mode=ParseMode.MARKDOWN
|
| 158 |
+
)
|
| 159 |
+
except Exception:
|
| 160 |
+
pass
|
| 161 |
+
|
| 162 |
+
elif action == "new_up_list":
|
| 163 |
+
latest_list = await get_latest_uploaded_movies(limit=25)
|
| 164 |
+
if not latest_list:
|
| 165 |
+
await query.answer("ℹ️ No newly uploaded movies available.", show_alert=True)
|
| 166 |
+
return
|
| 167 |
+
|
| 168 |
+
buttons = []
|
| 169 |
+
for item in latest_list:
|
| 170 |
+
cl_title = item[0]
|
| 171 |
+
count_files = item[1]
|
| 172 |
+
year = item[2] if len(item) > 2 else None
|
| 173 |
+
season_str = item[3] if len(item) > 3 else None
|
| 174 |
+
|
| 175 |
+
display_title = f"{cl_title} ({year})" if year else cl_title
|
| 176 |
+
if season_str:
|
| 177 |
+
display_title = f"{display_title} {season_str}"
|
| 178 |
+
|
| 179 |
+
search_query = f"{cl_title} {year}" if year else cl_title
|
| 180 |
+
if season_str:
|
| 181 |
+
search_query = f"{search_query} {season_str}"
|
| 182 |
+
|
| 183 |
+
h = hashlib.md5(search_query.encode('utf-8')).hexdigest()[:12]
|
| 184 |
+
MOVIE_CALLBACK_CACHE.set(h, (search_query, "New Uploads List"))
|
| 185 |
+
buttons.append([
|
| 186 |
+
InlineKeyboardButton(
|
| 187 |
+
text=f"🎬 {display_title} — {count_files} file{'s' if count_files > 1 else ''}",
|
| 188 |
+
callback_data=f"m_s {h}"
|
| 189 |
+
)
|
| 190 |
+
])
|
| 191 |
+
|
| 192 |
+
buttons.append([
|
| 193 |
+
InlineKeyboardButton("🔙 Back to Menu", callback_data="back_m")
|
| 194 |
+
])
|
| 195 |
+
|
| 196 |
+
text = f"🆕 **Newly Uploaded Movies (Top 25)**\n\n👇 Select a movie below to view files:"
|
| 197 |
+
await query.answer()
|
| 198 |
+
try:
|
| 199 |
+
await query.message.edit_text(
|
| 200 |
+
text=text,
|
| 201 |
+
reply_markup=InlineKeyboardMarkup(buttons),
|
| 202 |
+
parse_mode=ParseMode.MARKDOWN
|
| 203 |
+
)
|
| 204 |
+
except Exception:
|
| 205 |
+
pass
|
mfinder/plugins/user_settings.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import urllib3
|
| 10 |
+
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
| 11 |
+
|
| 12 |
+
load_dotenv()
|
| 13 |
+
|
| 14 |
+
def get_input_file_from_file_id(
|
| 15 |
+
file_id: str,
|
| 16 |
+
expected_file_type: FileType = None,
|
| 17 |
+
) -> Union["raw.types.InputPhoto", "raw.types.InputDocument"]:
|
| 18 |
+
try:
|
| 19 |
+
decoded = FileId.decode(file_id)
|
| 20 |
+
except Exception:
|
| 21 |
+
raise ValueError(
|
| 22 |
+
f'Failed to decode "{file_id}". The value does not represent an existing local file, '
|
| 23 |
+
f"HTTP URL, or valid file id."
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
file_type = decoded.file_type
|
| 27 |
+
|
| 28 |
+
if expected_file_type is not None and file_type != expected_file_type:
|
| 29 |
+
raise ValueError(
|
| 30 |
+
f'Expected: "{expected_file_type}", got "{file_type}" file_id instead'
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
if file_type in (FileType.THUMBNAIL, FileType.CHAT_PHOTO):
|
| 34 |
+
raise ValueError(f"This file_id can only be used for download: {file_id}")
|
| 35 |
+
|
| 36 |
+
if file_type in PHOTO_TYPES:
|
| 37 |
+
return raw.types.InputPhoto(
|
| 38 |
+
id=decoded.media_id,
|
| 39 |
+
access_hash=decoded.access_hash,
|
| 40 |
+
file_reference=decoded.file_reference,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
if file_type in DOCUMENT_TYPES:
|
| 44 |
+
return raw.types.InputDocument(
|
| 45 |
+
id=decoded.media_id,
|
| 46 |
+
access_hash=decoded.access_hash,
|
| 47 |
+
file_reference=decoded.file_reference,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
raise ValueError(f"Unknown file id: {file_id}")
|
| 51 |
+
|
| 52 |
+
def encode_file_id(s: bytes) -> str:
|
| 53 |
+
r = b""
|
| 54 |
+
n = 0
|
| 55 |
+
|
| 56 |
+
for i in s + bytes([22]) + bytes([4]):
|
| 57 |
+
if i == 0:
|
| 58 |
+
n += 1
|
| 59 |
+
else:
|
| 60 |
+
if n:
|
| 61 |
+
r += b"\x00" + bytes([n])
|
| 62 |
+
n = 0
|
| 63 |
+
|
| 64 |
+
r += bytes([i])
|
| 65 |
+
|
| 66 |
+
return base64.urlsafe_b64encode(r).decode().rstrip("=")
|
| 67 |
+
|
| 68 |
+
def encode_file_ref(file_ref: bytes) -> str:
|
| 69 |
+
return base64.urlsafe_b64encode(file_ref).decode().rstrip("=")
|
| 70 |
+
|
| 71 |
+
def unpack_new_file_id(new_file_id):
|
| 72 |
+
"""Return file_id, file_ref"""
|
| 73 |
+
decoded = FileId.decode(new_file_id)
|
| 74 |
+
file_id = encode_file_id(
|
| 75 |
+
pack(
|
| 76 |
+
"<iiqq",
|
| 77 |
+
int(decoded.file_type),
|
| 78 |
+
decoded.dc_id,
|
| 79 |
+
decoded.media_id,
|
| 80 |
+
decoded.access_hash,
|
| 81 |
+
)
|
| 82 |
+
)
|
| 83 |
+
file_ref = encode_file_ref(decoded.file_reference)
|
| 84 |
+
return file_id, file_ref
|
| 85 |
+
|
| 86 |
+
def edit_caption(c_caption):
|
| 87 |
+
return c_caption
|
| 88 |
+
|
| 89 |
+
import os
|
| 90 |
+
import requests
|
| 91 |
+
|
| 92 |
+
import asyncio
|
| 93 |
+
import time
|
| 94 |
+
|
| 95 |
+
SHORT_URL_CACHE = {}
|
| 96 |
+
SHORT_URL_TO_DOWNLOAD_URL = {}
|
| 97 |
+
SHORT_URL_TO_SHORTENER = {}
|
| 98 |
+
|
| 99 |
+
def clear_short_url_cache():
|
| 100 |
+
global SHORT_URL_CACHE
|
| 101 |
+
SHORT_URL_CACHE.clear()
|
| 102 |
+
|
| 103 |
+
def get_how_to_download_for_url(short_url):
|
| 104 |
+
return SHORT_URL_TO_DOWNLOAD_URL.get(short_url)
|
| 105 |
+
|
| 106 |
+
def get_shortener_desc_for_url(shortened_url):
|
| 107 |
+
res = SHORT_URL_TO_SHORTENER.get(shortened_url)
|
| 108 |
+
if res:
|
| 109 |
+
orig_idx, site = res
|
| 110 |
+
if orig_idx >= 0:
|
| 111 |
+
return f"{orig_idx + 1}. {site}"
|
| 112 |
+
return site
|
| 113 |
+
return "Direct Link (Bypassed)"
|
| 114 |
+
|
| 115 |
+
from mfinder import LOGGER
|
| 116 |
+
|
| 117 |
+
# Per-site circuit breaker: tracks failures per shortener domain
|
| 118 |
+
# Format: { "site_domain": { "failures": int, "blocked_until": float } }
|
| 119 |
+
_SITE_CIRCUIT_BREAKER = {}
|
| 120 |
+
_CIRCUIT_BREAKER_THRESHOLD = 3 # Block site after 3 consecutive failures
|
| 121 |
+
_CIRCUIT_BREAKER_COOLDOWN = 300 # Re-try blocked site after 5 minutes
|
| 122 |
+
|
| 123 |
+
# Use curl_cffi to bypass Cloudflare by impersonating real browser TLS fingerprints
|
| 124 |
+
GOOGLE_PROXY_URL = os.environ.get("GOOGLE_PROXY_URL", "").strip()
|
| 125 |
+
|
| 126 |
+
_CURL_CFFI_AVAILABLE = False
|
| 127 |
+
try:
|
| 128 |
+
from curl_cffi import requests as curl_requests
|
| 129 |
+
_CURL_CFFI_AVAILABLE = True
|
| 130 |
+
LOGGER.info("curl_cffi loaded — Cloudflare TLS fingerprint bypass active")
|
| 131 |
+
except ImportError:
|
| 132 |
+
LOGGER.warning("curl_cffi not installed, falling back to plain requests (Cloudflare may block)")
|
| 133 |
+
|
| 134 |
+
def _shorten_url_sync(api_url, params):
|
| 135 |
+
"""Single-attempt shortener request. Returns shortened URL or None.
|
| 136 |
+
Uses curl_cffi with Chrome TLS impersonation to bypass Cloudflare.
|
| 137 |
+
If the primary domain fails or is blocked by Cloudflare, it automatically retries with mirror domains.
|
| 138 |
+
If GOOGLE_PROXY_URL is configured in env, routes requests through Google Apps Script proxy to bypass Cloudflare completely."""
|
| 139 |
+
import urllib.parse
|
| 140 |
+
urls_to_try = [api_url]
|
| 141 |
+
|
| 142 |
+
# Mirror domains list for known shorteners
|
| 143 |
+
if "shortxlinks.com" in api_url:
|
| 144 |
+
urls_to_try.append(api_url.replace("shortxlinks.com", "shortxlinks.in"))
|
| 145 |
+
urls_to_try.append(api_url.replace("shortxlinks.com", "shortxlinks.xyz"))
|
| 146 |
+
elif "shortxlinks.in" in api_url:
|
| 147 |
+
urls_to_try.append(api_url.replace("shortxlinks.in", "shortxlinks.com"))
|
| 148 |
+
urls_to_try.append(api_url.replace("shortxlinks.in", "shortxlinks.xyz"))
|
| 149 |
+
elif "shortxlinks.xyz" in api_url:
|
| 150 |
+
urls_to_try.append(api_url.replace("shortxlinks.xyz", "shortxlinks.com"))
|
| 151 |
+
urls_to_try.append(api_url.replace("shortxlinks.xyz", "shortxlinks.in"))
|
| 152 |
+
|
| 153 |
+
for url in urls_to_try:
|
| 154 |
+
response = None
|
| 155 |
+
try:
|
| 156 |
+
if GOOGLE_PROXY_URL:
|
| 157 |
+
# Route through Google Apps Script proxy
|
| 158 |
+
full_target_url = f"{url}?{urllib.parse.urlencode(params)}"
|
| 159 |
+
proxy_request_url = f"{GOOGLE_PROXY_URL}?url={urllib.parse.quote(full_target_url)}"
|
| 160 |
+
response = requests.get(proxy_request_url, timeout=20)
|
| 161 |
+
elif _CURL_CFFI_AVAILABLE:
|
| 162 |
+
response = curl_requests.get(
|
| 163 |
+
url, params=params, impersonate="chrome", timeout=15
|
| 164 |
+
)
|
| 165 |
+
else:
|
| 166 |
+
response = requests.get(
|
| 167 |
+
url, params=params, timeout=15,
|
| 168 |
+
headers={"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"}
|
| 169 |
+
)
|
| 170 |
+
except Exception as e:
|
| 171 |
+
LOGGER.warning("Shortener request failed for %s (proxy=%s): %s", url, bool(GOOGLE_PROXY_URL), e)
|
| 172 |
+
continue
|
| 173 |
+
|
| 174 |
+
if response is None:
|
| 175 |
+
continue
|
| 176 |
+
|
| 177 |
+
if response.status_code == 200:
|
| 178 |
+
# Try JSON parsing
|
| 179 |
+
try:
|
| 180 |
+
data = response.json()
|
| 181 |
+
if isinstance(data, dict):
|
| 182 |
+
short_link = (
|
| 183 |
+
data.get('shortenedUrl') or
|
| 184 |
+
data.get('shorturl') or
|
| 185 |
+
data.get('short_url') or
|
| 186 |
+
data.get('url') or
|
| 187 |
+
data.get('link') or
|
| 188 |
+
data.get('shortened_url') or
|
| 189 |
+
(data.get('data') and isinstance(data.get('data'), dict) and data['data'].get('url'))
|
| 190 |
+
)
|
| 191 |
+
if short_link:
|
| 192 |
+
return str(short_link).strip()
|
| 193 |
+
except Exception:
|
| 194 |
+
pass
|
| 195 |
+
|
| 196 |
+
# Try plain text URL
|
| 197 |
+
text_resp = response.text.strip()
|
| 198 |
+
if text_resp.startswith("http://") or text_resp.startswith("https://"):
|
| 199 |
+
return text_resp
|
| 200 |
+
|
| 201 |
+
# Got 200 but unparseable (Cloudflare challenge page)
|
| 202 |
+
LOGGER.warning("Shortener mirror returned unparseable 200 for %s (Cloudflare block)", url)
|
| 203 |
+
continue
|
| 204 |
+
|
| 205 |
+
elif response.status_code in (429, 502, 503, 504):
|
| 206 |
+
LOGGER.warning("Shortener transient error %s for %s", response.status_code, url)
|
| 207 |
+
continue
|
| 208 |
+
else:
|
| 209 |
+
LOGGER.warning("Shortener API HTTP error %s for %s: %s", response.status_code, url, response.text[:200])
|
| 210 |
+
continue
|
| 211 |
+
|
| 212 |
+
return None
|
| 213 |
+
|
| 214 |
+
def _is_site_blocked(site):
|
| 215 |
+
"""Check if a shortener site is currently circuit-broken."""
|
| 216 |
+
cb = _SITE_CIRCUIT_BREAKER.get(site)
|
| 217 |
+
if not cb:
|
| 218 |
+
return False
|
| 219 |
+
if cb["failures"] >= _CIRCUIT_BREAKER_THRESHOLD:
|
| 220 |
+
if time.time() < cb["blocked_until"]:
|
| 221 |
+
return True
|
| 222 |
+
# Cooldown expired, reset and allow retry
|
| 223 |
+
cb["failures"] = 0
|
| 224 |
+
cb["blocked_until"] = 0
|
| 225 |
+
return False
|
| 226 |
+
|
| 227 |
+
def _record_site_failure(site):
|
| 228 |
+
"""Record a failure for a shortener site."""
|
| 229 |
+
if site not in _SITE_CIRCUIT_BREAKER:
|
| 230 |
+
_SITE_CIRCUIT_BREAKER[site] = {"failures": 0, "blocked_until": 0}
|
| 231 |
+
cb = _SITE_CIRCUIT_BREAKER[site]
|
| 232 |
+
cb["failures"] += 1
|
| 233 |
+
if cb["failures"] >= _CIRCUIT_BREAKER_THRESHOLD:
|
| 234 |
+
cb["blocked_until"] = time.time() + _CIRCUIT_BREAKER_COOLDOWN
|
| 235 |
+
LOGGER.warning("Circuit breaker OPEN for %s — skipping for %d seconds after %d consecutive failures", site, _CIRCUIT_BREAKER_COOLDOWN, cb["failures"])
|
| 236 |
+
|
| 237 |
+
def _record_site_success(site):
|
| 238 |
+
"""Reset failure count on success."""
|
| 239 |
+
if site in _SITE_CIRCUIT_BREAKER:
|
| 240 |
+
_SITE_CIRCUIT_BREAKER[site] = {"failures": 0, "blocked_until": 0}
|
| 241 |
+
|
| 242 |
+
async def shorten_url(long_url, force=False, user_id=None):
|
| 243 |
+
"""
|
| 244 |
+
Shortens a given URL using configured shorteners in strict priority order or smart rotation.
|
| 245 |
+
- If Smart Rotator is OFF: ALWAYS prioritizes active shortener #1. Falls over to #2, #3 only on server failure.
|
| 246 |
+
- If only 1 shortener is configured/active: ALWAYS uses that shortener. If it fails, falls back to direct URL.
|
| 247 |
+
- If Smart Rotator is ON: Serves the user's active shortener for today based on their verified count.
|
| 248 |
+
- Per-site circuit breaker: automatically skips shorteners that are consistently failing (e.g. Cloudflare blocked).
|
| 249 |
+
"""
|
| 250 |
+
from mfinder.db.settings_sql import get_admin_settings_sync
|
| 251 |
+
|
| 252 |
+
settings = get_admin_settings_sync()
|
| 253 |
+
if not settings:
|
| 254 |
+
return long_url
|
| 255 |
+
|
| 256 |
+
# Bypass standard shortening if disabled and not forced (e.g. for token link)
|
| 257 |
+
if not force and not getattr(settings, "shortener_status", True):
|
| 258 |
+
return long_url
|
| 259 |
+
|
| 260 |
+
import json
|
| 261 |
+
import datetime
|
| 262 |
+
|
| 263 |
+
shorteners = []
|
| 264 |
+
if hasattr(settings, "shorteners_list") and settings.shorteners_list:
|
| 265 |
+
try:
|
| 266 |
+
shorteners = json.loads(settings.shorteners_list)
|
| 267 |
+
except Exception:
|
| 268 |
+
pass
|
| 269 |
+
|
| 270 |
+
# Backwards compatibility: fallback to single settings if rotator is empty
|
| 271 |
+
if not shorteners and settings.shortener_site and settings.shortener_api:
|
| 272 |
+
shorteners = [{
|
| 273 |
+
"site": settings.shortener_site,
|
| 274 |
+
"api": settings.shortener_api,
|
| 275 |
+
"status": settings.shortener_status if settings.shortener_status is not None else True
|
| 276 |
+
}]
|
| 277 |
+
|
| 278 |
+
# Filter only active shorteners
|
| 279 |
+
active_shorteners = [s for s in shorteners if s.get("status", True)]
|
| 280 |
+
if not active_shorteners:
|
| 281 |
+
return long_url
|
| 282 |
+
|
| 283 |
+
# Determine starting shortener index
|
| 284 |
+
smart_rotator_on = getattr(settings, "smart_rotator", False)
|
| 285 |
+
start_index = 0
|
| 286 |
+
if smart_rotator_on and user_id:
|
| 287 |
+
try:
|
| 288 |
+
local_now = datetime.datetime.utcnow() + datetime.timedelta(hours=5, minutes=30)
|
| 289 |
+
today_str = local_now.strftime("%Y-%m-%d")
|
| 290 |
+
from mfinder.db.settings_sql import get_user_shortener_index
|
| 291 |
+
saved_idx = await get_user_shortener_index(user_id, today_str)
|
| 292 |
+
start_index = (saved_idx or 0) % len(active_shorteners)
|
| 293 |
+
except Exception as e:
|
| 294 |
+
start_index = 0
|
| 295 |
+
else:
|
| 296 |
+
start_index = 0
|
| 297 |
+
|
| 298 |
+
# Check cache by (long_url, site)
|
| 299 |
+
target_idx = start_index % len(active_shorteners)
|
| 300 |
+
selected_first = active_shorteners[target_idx]
|
| 301 |
+
first_site = selected_first.get("site")
|
| 302 |
+
first_how_to = selected_first.get("how_to_download") or "https://telegram.me/FIREBOLTTutorial/23"
|
| 303 |
+
|
| 304 |
+
cache_key = (long_url, first_site)
|
| 305 |
+
if cache_key in SHORT_URL_CACHE:
|
| 306 |
+
shortened = SHORT_URL_CACHE[cache_key]
|
| 307 |
+
SHORT_URL_TO_DOWNLOAD_URL[shortened] = first_how_to
|
| 308 |
+
orig_idx = -1
|
| 309 |
+
for idx, orig_sh in enumerate(shorteners):
|
| 310 |
+
if orig_sh.get("site") == first_site and orig_sh.get("api") == selected_first.get("api"):
|
| 311 |
+
orig_idx = idx
|
| 312 |
+
break
|
| 313 |
+
SHORT_URL_TO_SHORTENER[shortened] = (orig_idx, first_site)
|
| 314 |
+
return shortened
|
| 315 |
+
|
| 316 |
+
# Failover chain: tries start_index first, then remaining in order
|
| 317 |
+
num_active = len(active_shorteners)
|
| 318 |
+
for i in range(num_active):
|
| 319 |
+
target_idx = (start_index + i) % num_active
|
| 320 |
+
selected = active_shorteners[target_idx]
|
| 321 |
+
|
| 322 |
+
site = selected.get("site")
|
| 323 |
+
api = selected.get("api")
|
| 324 |
+
how_to = selected.get("how_to_download") or "https://telegram.me/FIREBOLTTutorial/23"
|
| 325 |
+
if not site or not api:
|
| 326 |
+
continue
|
| 327 |
+
|
| 328 |
+
# Circuit breaker: skip this shortener if it's been consistently failing
|
| 329 |
+
if _is_site_blocked(site):
|
| 330 |
+
LOGGER.debug("Skipping circuit-broken shortener: %s", site)
|
| 331 |
+
continue
|
| 332 |
+
|
| 333 |
+
site_clean = site.strip().rstrip("/")
|
| 334 |
+
if not site_clean.startswith("http://") and not site_clean.startswith("https://"):
|
| 335 |
+
api_url = f"https://{site_clean}"
|
| 336 |
+
else:
|
| 337 |
+
api_url = site_clean
|
| 338 |
+
|
| 339 |
+
if not api_url.endswith("/api"):
|
| 340 |
+
api_url = f"{api_url}/api"
|
| 341 |
+
|
| 342 |
+
params = {
|
| 343 |
+
'url': long_url,
|
| 344 |
+
'api': api.strip(),
|
| 345 |
+
'format': 'json'
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
try:
|
| 349 |
+
shortened = await asyncio.to_thread(_shorten_url_sync, api_url, params)
|
| 350 |
+
if shortened:
|
| 351 |
+
SHORT_URL_CACHE[(long_url, site)] = shortened
|
| 352 |
+
SHORT_URL_TO_DOWNLOAD_URL[shortened] = how_to
|
| 353 |
+
orig_idx = -1
|
| 354 |
+
for idx, orig_sh in enumerate(shorteners):
|
| 355 |
+
if orig_sh.get("site") == site and orig_sh.get("api") == api:
|
| 356 |
+
orig_idx = idx
|
| 357 |
+
break
|
| 358 |
+
SHORT_URL_TO_SHORTENER[shortened] = (orig_idx, site)
|
| 359 |
+
_record_site_success(site)
|
| 360 |
+
return shortened
|
| 361 |
+
else:
|
| 362 |
+
# Shortener returned None (failed) — record failure for circuit breaker
|
| 363 |
+
_record_site_failure(site)
|
| 364 |
+
except Exception as e:
|
| 365 |
+
LOGGER.warning("Error with shortener %s: %s", site, e)
|
| 366 |
+
_record_site_failure(site)
|
| 367 |
+
|
| 368 |
+
return long_url
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def encode_title(title):
|
| 372 |
+
import base64
|
| 373 |
+
return base64.urlsafe_b64encode(title.encode('utf-8')).decode('utf-8').replace('=', '')
|
| 374 |
+
|
| 375 |
+
def decode_title(encoded):
|
| 376 |
+
import base64
|
| 377 |
+
padded = encoded + '=' * (4 - len(encoded) % 4)
|
| 378 |
+
return base64.urlsafe_b64decode(padded.encode('utf-8')).decode('utf-8')
|
| 379 |
+
|
| 380 |
+
def detect_file_quality(filename: str) -> str:
|
| 381 |
+
filename_lower = (filename or "").lower()
|
| 382 |
+
theatre_indicators = ["predvd", "predvdrip", "cam", "theatre", "theatre print"]
|
| 383 |
+
for indicator in theatre_indicators:
|
| 384 |
+
if indicator in filename_lower:
|
| 385 |
+
return "Theatre Print [Clear Audio]"
|
| 386 |
+
return "HD"
|
mfinder/utils/util_support.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|
requirements.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
APScheduler==3.10.4
|
| 2 |
+
greenlet==3.0.3
|
| 3 |
+
psutil==5.9.8
|
| 4 |
+
psycopg2-binary==2.9.9
|
| 5 |
+
pyaes==1.6.1
|
| 6 |
+
pymediainfo==6.1.0
|
| 7 |
+
pyrotgfork==2.1.30
|
| 8 |
+
PySocks==1.7.1
|
| 9 |
+
python-dotenv==1.0.1
|
| 10 |
+
pytz==2024.1
|
| 11 |
+
six==1.16.0
|
| 12 |
+
SQLAlchemy==2.0.30
|
| 13 |
+
TgCrypto==1.2.5
|
| 14 |
+
typing_extensions==4.11.0
|
| 15 |
+
tzlocal==5.2
|
| 16 |
+
uvloop==0.19.0
|
| 17 |
+
flask
|
| 18 |
+
requests==2.31.0
|
| 19 |
+
fastapi
|
| 20 |
+
uvicorn
|
| 21 |
+
curl_cffi
|
sample_const.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Do not edit this file, copy this file & rename it to const.py. Any format error will result in not getting start or help message.
|
| 2 |
+
|
| 3 |
+
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
#use the same format for name & user_id placeholders
|
| 7 |
+
START_MSG = """
|
| 8 |
+
Hi **[{}](tg://user?id={})**, I am a media finder bot which finds media from my database channel. Just send query to find the media.
|
| 9 |
+
Send /help for more.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
HELP_MSG = """
|
| 13 |
+
REQUEST FORMAT :- *MOVIE NAME WITH YEAR (LANGUAGE OPTIONAL)
|
| 14 |
+
|
| 15 |
+
REQUEST LIKE THIS :-
|
| 16 |
+
=>IRON MAN✅
|
| 17 |
+
=>IRON MAN 2008✅
|
| 18 |
+
=>IRON MAN 2008 TAMIL✅
|
| 19 |
+
|
| 20 |
+
DON'T REQUEST LIKE THIS :-
|
| 21 |
+
=>IRON MAN MOVIE ❌
|
| 22 |
+
=>IRON MAN 2008 GIVE ❌
|
| 23 |
+
=>IRON MAN 2008 ANAPUGA ❌
|
| 24 |
+
|
| 25 |
+
[🙅Don't use this words while searching: HD, MOVIES, SEND, PREDVD, WEB-DL, ANAPUGA, SEND PANNUGA, HDrip, VENUM]
|
| 26 |
+
|
| 27 |
+
If Any Movies Not Available Send Your MOVIE NAMES Via `/request <Movie Name>` or REPORT HERE 👉 @ANGRY_BIRD22_bot
|
| 28 |
+
|
| 29 |
+
━━━━━━━━━━━━━━━━━━━━━━
|
| 30 |
+
**You can find the bot commands here.**
|
| 31 |
+
|
| 32 |
+
**User Commands:-**
|
| 33 |
+
/start - Start the bot and view main menu
|
| 34 |
+
/help - Show this help message
|
| 35 |
+
/trending - View top 10 trending movies this week
|
| 36 |
+
/newuploads - View latest 25 newly uploaded movies
|
| 37 |
+
/request - Request a missing movie from admins (`/request Movie Name`)
|
| 38 |
+
/settings - Toggle settings of Precise Mode and Button Mode
|
| 39 |
+
|
| 40 |
+
**Precise Mode:**
|
| 41 |
+
- If Enabled, bot will match the word & return results with only the exact match
|
| 42 |
+
- If Disabled, bot will match the word & return all the results containing the word
|
| 43 |
+
|
| 44 |
+
**Result Mode:**
|
| 45 |
+
- If Button, bot will return results in button format
|
| 46 |
+
- If List, bot will return results in list format
|
| 47 |
+
- If HyperLink, bot will return results in hyperlink format
|
| 48 |
+
|
| 49 |
+
**Admin Commands:-**
|
| 50 |
+
/requests - View pending movie requests summary
|
| 51 |
+
/message - Send message to user's PM - `/message <user_id/username> [optional text]`
|
| 52 |
+
/logs - Get logs as a file
|
| 53 |
+
/server - Get server stats
|
| 54 |
+
/restart - Restart the bot
|
| 55 |
+
/stats - Get bot user stats
|
| 56 |
+
/broadcast - Reply to a message to send that to all bot users
|
| 57 |
+
/index - Start indexing a database channel (bot must be admin of the channel if that is private channel)
|
| 58 |
+
*(You can just forward the message from database channel for starting indexing, no need to use the /index command)*
|
| 59 |
+
/delete - Reply to a file to delete it from database
|
| 60 |
+
/autodelete - Set file auto delete time in seconds
|
| 61 |
+
/repairmode - Enable or disable repair mode - If on, bot will not send any files
|
| 62 |
+
/customcaption - Set custom caption for files
|
| 63 |
+
/adminsettings - Get current admin settings
|
| 64 |
+
/ban - Ban a user from bot - `/ban user_id`
|
| 65 |
+
/unban - Unban a user from bot - `/unban user_id`
|
| 66 |
+
/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)*
|
| 67 |
+
/delfilter - Delete a text filter - `/delfilter filter`
|
| 68 |
+
/listfilters - List all filters currently added in the bot
|
| 69 |
+
/forcesub - Set force subscribe channel - `/forcesub channel_id` *(Bot must be admin of that channel)*
|
| 70 |
+
/checklink - Check invite link for force subscribe channel
|
| 71 |
+
/total - Get count of total files in DB
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
START_KB = InlineKeyboardMarkup(
|
| 76 |
+
[
|
| 77 |
+
[
|
| 78 |
+
InlineKeyboardButton("🆘 Help", callback_data="help_cb"),
|
| 79 |
+
InlineKeyboardButton(
|
| 80 |
+
"👨💻 Source Code", url="https://github.com/EL-Coders/mediafinder"
|
| 81 |
+
),
|
| 82 |
+
]
|
| 83 |
+
]
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
HELP_KB = InlineKeyboardMarkup(
|
| 87 |
+
[
|
| 88 |
+
[
|
| 89 |
+
InlineKeyboardButton("🔙 Back", callback_data="back_m"),
|
| 90 |
+
],
|
| 91 |
+
]
|
| 92 |
+
)
|