-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
210 lines (170 loc) · 7.1 KB
/
Copy pathmain.py
File metadata and controls
210 lines (170 loc) · 7.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import os
import asyncio
import logging
import time
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
import config
from services import extractor, downloader, uploader, auth, queue_manager
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Global Task Registry (Still used for cancellation if needed, but Queue manages execution)
TASKS = {}
# Initialize the Bot
if not config.BOT_TOKEN:
logger.error("BOT_TOKEN is missing. Please add it to .env")
exit(1)
app = Client(
"dim_bot",
api_id=config.API_ID,
api_hash=config.API_HASH,
bot_token=config.BOT_TOKEN
)
async def process_upload_task(client, message, url, status_msg):
"""
Worker task: Extract -> Download -> Notify.
"""
task_id = f"{message.chat.id}_{message.id}"
# Register this active task for cancellation
current_task = asyncio.current_task()
TASKS[task_id] = current_task
# Cancel Button
cancel_btn = InlineKeyboardMarkup([
[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_{task_id}")]
])
try:
# 1. Extract
await status_msg.edit_text(f"🔍 **Extracting URL...**\n`{url}`", reply_markup=cancel_btn)
direct_url, headers, filename = await extractor.extract_direct_url(url)
if not direct_url:
await status_msg.edit_text(f"❌ **Extraction Failed**\nURL: `{url}`")
return
# 2. Setup Filename
if not filename:
timestamp = int(time.time())
filename = f"video_{timestamp}_{message.id}"
if "." not in filename:
if ".mkv" in direct_url: filename += ".mkv"
elif ".avi" in direct_url: filename += ".avi"
else: filename += ".mp4"
filename = "".join([c for c in filename if c.isalnum() or c in "._- "]).strip()
output_path = os.path.join(config.DOWNLOAD_PATH, filename)
# Update Status: Found
await status_msg.edit_text(f"✅ **File Found**\n📄 `{filename}`\n⬇️ Starting Download...", reply_markup=cancel_btn)
# 3. Download with Progress
async def progress(current, total, speed, eta):
try:
percentage = current
filled = int(percentage // 10)
bar = '█' * filled + '-' * (10 - filled)
text = (
f"⬇️ **Downloading...**\n"
f"`[{bar}]` **{percentage}%**\n\n"
f"🚀 Speed: **{speed}**\n"
f"⏳ ETA: **{eta}**\n"
f"📄 `{filename}`"
)
await status_msg.edit_text(text, reply_markup=cancel_btn)
except Exception:
pass
result_path = await downloader.download_file(direct_url, headers, output_path, progress_callback=progress)
if not result_path:
await status_msg.edit_text(f"❌ **Download Failed**\nCheck logs for details.")
return
# 4. Final Success
file_size = os.path.getsize(result_path)
size_str = downloader.format_size(file_size)
final_text = (
f"✅ **Download Complete**\n\n"
f"📄 `{filename}`\n"
f"📦 Size: `{size_str}`"
)
# Remove cancel button on success
await status_msg.edit_text(final_text)
# Call API if enabled
if config.ENABLE_API_UPLOAD:
await status_msg.edit_text(final_text + "\n\n📡 Notifying API...")
api_success = await uploader.notify_api(filename, result_path)
api_status = "✅ Sent" if api_success else "❌ Failed"
await status_msg.edit_text(final_text + f"\n\n📡 API: {api_status}")
except asyncio.CancelledError:
await status_msg.edit_text("🛑 **Task Cancelled by User**")
except Exception as e:
logger.error(f"Task failed: {e}")
await status_msg.edit_text(f"❌ **Critical Error**\n`{str(e)}`")
if 'output_path' in locals() and os.path.exists(output_path):
os.remove(output_path)
finally:
# Remove task from registry
if task_id in TASKS:
del TASKS[task_id]
# --- Admin Commands ---
def is_owner(user_id):
return user_id == config.OWNER_ID or str(user_id) == str(config.OWNER_ID)
@app.on_message(filters.command("adduser", prefixes="/"))
async def add_user_handler(client, message):
if not is_owner(message.from_user.id):
return
if len(message.command) < 2:
await message.reply_text("Usage: /adduser <id or username>")
return
identifier = message.command[1]
if auth.add_user(identifier):
await message.reply_text(f"✅ User {identifier} added.")
else:
await message.reply_text(f"⚠️ User {identifier} already exists.")
@app.on_message(filters.command("removeuser", prefixes="/"))
async def remove_user_handler(client, message):
if not is_owner(message.from_user.id):
return
if len(message.command) < 2:
await message.reply_text("Usage: /removeuser <id or username>")
return
identifier = message.command[1]
if auth.remove_user(identifier):
await message.reply_text(f"✅ User {identifier} removed.")
else:
await message.reply_text(f"⚠️ User {identifier} not found.")
@app.on_message(filters.command("listusers", prefixes="/"))
async def list_users_handler(client, message):
if not is_owner(message.from_user.id):
return
users = auth.get_users()
if not users:
await message.reply_text("📂 No allowed users.")
else:
await message.reply_text(f"📂 Allowed Users:\n" + "\n".join([f"- `{u}`" for u in users]))
# --- Cancel Handler ---
@app.on_callback_query(filters.regex(r"^cancel_"))
async def cancel_handler(client, callback_query: CallbackQuery):
task_key = callback_query.data.split("cancel_")[1]
if task_key in TASKS:
task = TASKS[task_key]
task.cancel() # Raises CancelledError in the task
await callback_query.answer("🛑 Task cancelling...")
else:
await callback_query.answer("⚠️ Task not found or already finished.", show_alert=True)
# --- Upload Handler ---
@app.on_message(filters.command("upload", prefixes="/"))
async def upload_handler(client, message):
user = message.from_user
if not auth.is_authorized(user.id, user.username):
await message.reply_text("⛔ You are not authorized to use this bot.")
return
if len(message.command) < 2:
await message.reply_text("Usage: /upload <url>")
return
url = message.command[1]
# Add to Queue
await queue_manager.queue_manager.add(client, message, url)
logger.info(f"Added to queue: {url}")
if __name__ == "__main__":
print("Dim Userbot started...")
# Initialize Queue Workers
loop = asyncio.get_event_loop()
loop.create_task(queue_manager.queue_manager.start(process_upload_task))
app.run()