Spaces:
Runtime error
Runtime error
Create links.py
Browse files- handlers/links.py +145 -0
handlers/links.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# filename: handlers/links.py
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import re
|
| 5 |
+
import uuid
|
| 6 |
+
import asyncio
|
| 7 |
+
from telethon import events, Button
|
| 8 |
+
|
| 9 |
+
from core.bot import bot, BATCH_JOBS, PREMIUM_QUEUE, FREE_QUEUE, ACTIVE_USER_TASKS, USER_TURN_ORDER
|
| 10 |
+
import config
|
| 11 |
+
import templates
|
| 12 |
+
from utils import terabox, helpers
|
| 13 |
+
from database import manager as db_manager
|
| 14 |
+
from datetime import datetime
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
# This regular expression finds all URLs in a message
|
| 19 |
+
URL_REGEX = r'https?://[^\s<>"\']+'
|
| 20 |
+
|
| 21 |
+
@bot.on(events.NewMessage(func=lambda e: e.text and not e.text.startswith('/')))
|
| 22 |
+
async def main_link_handler(event):
|
| 23 |
+
sender = await event.get_sender()
|
| 24 |
+
user_id = sender.id
|
| 25 |
+
|
| 26 |
+
# --- Step 1: Pre-flight Checks ---
|
| 27 |
+
user = await db_manager.get_user(user_id)
|
| 28 |
+
if not user:
|
| 29 |
+
user = await db_manager.add_or_update_user(user_id, sender.username, sender.first_name)
|
| 30 |
+
|
| 31 |
+
if user.get('is_banned'):
|
| 32 |
+
await event.reply(templates.BotResponses.USER_BANNED_MESSAGE)
|
| 33 |
+
return
|
| 34 |
+
|
| 35 |
+
if event.is_group and not await db_manager.is_group_authorized(event.chat_id):
|
| 36 |
+
# Only reply if the group is not authorized, to avoid spam
|
| 37 |
+
# You could add a check to only reply once per hour per group
|
| 38 |
+
# await event.reply(templates.BotResponses.GROUP_NOT_AUTHORIZED.format(owner_id=config.OWNER_ID))
|
| 39 |
+
return
|
| 40 |
+
|
| 41 |
+
# Force Subscribe Check
|
| 42 |
+
if config.FORCE_SUB_CHANNEL_USERNAME:
|
| 43 |
+
try:
|
| 44 |
+
await bot.get_permissions(config.FORCE_SUB_CHANNEL_USERNAME, user_id)
|
| 45 |
+
except Exception:
|
| 46 |
+
await event.reply(templates.BotResponses.FORCE_SUBSCRIBE_MESSAGE.format(channel_username=config.FORCE_SUB_CHANNEL_USERNAME))
|
| 47 |
+
return
|
| 48 |
+
|
| 49 |
+
# --- Step 2: Parse Links and Create Batch ---
|
| 50 |
+
links = list(set(re.findall(URL_REGEX, event.text)))
|
| 51 |
+
terabox_links = [link for link in links if "terabox" in link or "terashare" in link]
|
| 52 |
+
|
| 53 |
+
if not terabox_links:
|
| 54 |
+
return
|
| 55 |
+
|
| 56 |
+
batch_id = str(uuid.uuid4())[:6]
|
| 57 |
+
status_msg = await event.reply(templates.BotResponses.BATCH_ACKNOWLEDGEMENT.format(
|
| 58 |
+
link_count=len(terabox_links),
|
| 59 |
+
batch_id=batch_id
|
| 60 |
+
))
|
| 61 |
+
|
| 62 |
+
# --- Step 3: Evaluate Each Link ---
|
| 63 |
+
valid_tasks = []
|
| 64 |
+
skipped_links = []
|
| 65 |
+
|
| 66 |
+
for link in terabox_links:
|
| 67 |
+
short_id = await terabox.extract_terabox_short_id(link)
|
| 68 |
+
if not short_id:
|
| 69 |
+
skipped_links.append({"link": link, "error": "Invalid Link Format"})
|
| 70 |
+
continue
|
| 71 |
+
|
| 72 |
+
cached = await db_manager.get_cached_file(short_id)
|
| 73 |
+
task_data = {"batch_id": batch_id, "link": link, "user_id": user_id, "short_id": short_id}
|
| 74 |
+
|
| 75 |
+
if cached:
|
| 76 |
+
task_data['metadata'] = {"file_name": cached['file_name'], "file_size": cached['file_size']}
|
| 77 |
+
task_data['cached'] = True
|
| 78 |
+
valid_tasks.append(task_data)
|
| 79 |
+
continue
|
| 80 |
+
|
| 81 |
+
# If not cached, get metadata for size check
|
| 82 |
+
metadata = await terabox.get_final_url_and_metadata(link)
|
| 83 |
+
if not metadata['success']:
|
| 84 |
+
skipped_links.append({"link": link, "error": metadata['error']})
|
| 85 |
+
continue
|
| 86 |
+
|
| 87 |
+
task_data['metadata'] = metadata
|
| 88 |
+
task_data['cached'] = False
|
| 89 |
+
|
| 90 |
+
# Apply free user limit
|
| 91 |
+
is_premium = user.get('is_premium') and user.get('premium_expiry_date', datetime.min) > datetime.utcnow()
|
| 92 |
+
if not is_premium and metadata['file_size'] > config.FREE_USER_FILE_SIZE_LIMIT_BYTES:
|
| 93 |
+
skipped_links.append({
|
| 94 |
+
"link": link,
|
| 95 |
+
"error": templates.BotResponses.PREMIUM_REQUIRED_ERROR.format(
|
| 96 |
+
file_name=metadata['file_name'],
|
| 97 |
+
file_size=helpers.format_bytes(metadata['file_size']),
|
| 98 |
+
free_limit=helpers.format_bytes(config.FREE_USER_FILE_SIZE_LIMIT_BYTES)
|
| 99 |
+
)
|
| 100 |
+
})
|
| 101 |
+
continue
|
| 102 |
+
|
| 103 |
+
valid_tasks.append(task_data)
|
| 104 |
+
|
| 105 |
+
# --- Step 4: Queue the Valid Tasks ---
|
| 106 |
+
if not valid_tasks:
|
| 107 |
+
# Handle case where no links were valid
|
| 108 |
+
await status_msg.edit("❌ All links provided were invalid or failed the initial check.")
|
| 109 |
+
return
|
| 110 |
+
|
| 111 |
+
# Update the batch job tracker
|
| 112 |
+
BATCH_JOBS[batch_id] = {
|
| 113 |
+
"user_id": user_id,
|
| 114 |
+
"chat_id": event.chat_id,
|
| 115 |
+
"status_message_id": status_msg.id,
|
| 116 |
+
"total_links": len(valid_tasks),
|
| 117 |
+
"processed_links": 0,
|
| 118 |
+
"original_total": len(terabox_links),
|
| 119 |
+
"failed_links": skipped_links, # pre-flight failures
|
| 120 |
+
"lock": asyncio.Lock()
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
is_premium = user.get('is_premium') and user.get('premium_expiry_date', datetime.min) > datetime.utcnow()
|
| 124 |
+
|
| 125 |
+
if is_premium:
|
| 126 |
+
for task in valid_tasks:
|
| 127 |
+
await PREMIUM_QUEUE.put(task)
|
| 128 |
+
else:
|
| 129 |
+
# For free users, add tasks to their personal list and add them to the round-robin deque
|
| 130 |
+
if user_id not in ACTIVE_USER_TASKS:
|
| 131 |
+
ACTIVE_USER_TASKS[user_id] = []
|
| 132 |
+
ACTIVE_USER_TASKS[user_id].extend(valid_tasks)
|
| 133 |
+
|
| 134 |
+
if user_id not in USER_TURN_ORDER:
|
| 135 |
+
USER_TURN_ORDER.append(user_id)
|
| 136 |
+
|
| 137 |
+
# Update the status message to show how many links are being processed
|
| 138 |
+
await status_msg.edit(templates.BotResponses.BATCH_UPDATE_VALIDATED.format(
|
| 139 |
+
batch_id=batch_id,
|
| 140 |
+
valid_count=len(valid_tasks),
|
| 141 |
+
total_count=len(terabox_links),
|
| 142 |
+
skipped_count=len(skipped_links),
|
| 143 |
+
progress_bar=helpers.create_progress_bar(0),
|
| 144 |
+
processed_count=0
|
| 145 |
+
))
|