Spaces:
Paused
Paused
File size: 21,546 Bytes
22d2ae1 aa49f24 22d2ae1 aa49f24 9b1b573 aa49f24 22d2ae1 aa49f24 9b1b573 aa49f24 22d2ae1 aa49f24 22d2ae1 aa49f24 9b1b573 22d2ae1 aa49f24 22d2ae1 aa49f24 22d2ae1 aa49f24 22d2ae1 aa49f24 22d2ae1 | 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 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 | import asyncio
import os
import re
import time
from pathlib import Path
from urllib.parse import parse_qs, urlparse
import qbittorrentapi
from pyrogram import Client, filters
from pyrogram.errors import FloodWait, MessageNotModified
from pyrogram.types import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Message
import aria2
from app import (
DOWNLOAD_PATH,
PIXELDRAIN_API_KEY,
STATE_FILE,
STATE_LOCK,
get_client,
get_task_state_entry,
is_rclone_upload_available,
is_aria2_task,
load_monitor_state,
rclone_remote_label,
save_monitor_state,
serialize_torrent,
start_gofile_upload_background,
start_pixeldrain_upload_background,
start_rclone_upload_background,
validate_magnet_link,
)
API_ID = int(os.getenv("TELEGRAM_API_ID", "2589472") or "0")
API_HASH = os.getenv("TELEGRAM_API_HASH", "5243628014db9798d6775b330e542602")
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "6100847173:AAE1Ph_WWGEJhENvKKIzPhziO63cv3ruYKs")
SESSION_NAME = os.getenv("TELEGRAM_BOT_SESSION", "torrent_web_bot")
OWNER_IDS = {
int(item.strip())
for item in os.getenv("TELEGRAM_OWNER_IDS", "1487943213").split(",")
if item.strip().isdigit()
}
PROGRESS_INTERVAL_SECONDS = max(2, int(os.getenv("TELEGRAM_PROGRESS_INTERVAL_SECONDS", "3") or "3"))
PROGRESS_TIMEOUT_SECONDS = max(60, int(os.getenv("TELEGRAM_PROGRESS_TIMEOUT_SECONDS", "86400") or "86400"))
bot = Client(SESSION_NAME, api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
def is_authorized(message_or_query) -> bool:
if not OWNER_IDS:
return True
user = getattr(message_or_query, "from_user", None)
return bool(user and user.id in OWNER_IDS)
def command_argument(message: Message) -> str:
text = message.text or message.caption or ""
parts = text.split(maxsplit=1)
return parts[1].strip() if len(parts) > 1 else ""
def extract_btih(magnet: str) -> str:
parsed = urlparse(magnet)
for value in parse_qs(parsed.query).get("xt", []):
if value.lower().startswith("urn:btih:"):
return value[9:]
return ""
def progress_bar(progress: int, width: int = 12) -> str:
value = max(0, min(int(progress or 0), 100))
filled = int((value / 100) * width)
return "[" + "#" * filled + "-" * (width - filled) + "]"
def task_snapshot(task_id: str) -> dict | None:
state = load_monitor_state()
if is_aria2_task(task_id):
entry = state.get("aria2", {}).get(task_id)
if not entry:
return None
item = aria2.serialize_task(entry)
item["can_rclone_upload"] = bool(item.get("can_gofile_upload"))
item["rclone_config_ready"] = is_rclone_upload_available()
item["can_raw_rclone_upload"] = False
return item
client = get_client()
torrents = client.torrents_info(torrent_hashes=task_id)
if not torrents:
return None
return serialize_torrent(torrents[0], state.get("torrents", {}).get(task_id))
def all_task_snapshots(limit: int = 8) -> list[dict]:
state = load_monitor_state()
client = get_client()
raw_torrents = list(client.torrents_info(sort="added_on", reverse=True))
torrent_items = [
serialize_torrent(torrent, state.get("torrents", {}).get(torrent.hash))
for torrent in raw_torrents
]
rclone_available = is_rclone_upload_available()
aria2_items = []
for task in state.get("aria2", {}).values():
item = aria2.serialize_task(task)
item["can_rclone_upload"] = bool(item.get("can_gofile_upload"))
item["rclone_config_ready"] = rclone_available
item["can_raw_rclone_upload"] = False
aria2_items.append(item)
items = sorted(torrent_items + aria2_items, key=lambda item: int(item.get("added_at", 0) or 0), reverse=True)
return items[:limit]
def add_magnet_task(magnet: str) -> tuple[str, str]:
is_valid, value = validate_magnet_link(magnet)
if not is_valid:
raise ValueError(value)
client = get_client()
before = {torrent.hash for torrent in client.torrents_info()}
client.torrents_add(urls=value, savepath=DOWNLOAD_PATH)
btih = extract_btih(value)
hash_candidates = []
if re.fullmatch(r"[A-Fa-f0-9]{40}", btih or ""):
hash_candidates = [btih.lower(), btih.upper()]
deadline = time.time() + 20
while time.time() < deadline:
torrents = list(client.torrents_info(sort="added_on", reverse=True))
by_hash = {torrent.hash: torrent for torrent in torrents}
for candidate in hash_candidates:
if candidate in by_hash:
return candidate, by_hash[candidate].name
new_hashes = [torrent.hash for torrent in torrents if torrent.hash not in before]
if new_hashes:
newest = by_hash[new_hashes[0]]
return newest.hash, newest.name
time.sleep(1)
raise RuntimeError("Magnet ditambahkan, tetapi task belum muncul dari qBittorrent.")
def add_aria2_task(url: str) -> tuple[str, str]:
is_valid, value = aria2.validate_download_url(url)
if not is_valid:
raise ValueError(value)
return aria2.start_download(value, DOWNLOAD_PATH, STATE_FILE, STATE_LOCK)
def set_upload_state(task_id: str, provider: str, endpoint: str = "") -> dict:
state = load_monitor_state()
entry = get_task_state_entry(state, task_id)
if entry.get("gofile_uploading"):
raise RuntimeError("Upload file eksternal masih berjalan.")
entry["gofile_uploading"] = True
entry["gofile_progress"] = 0
entry["gofile_speed"] = ""
entry["gofile_eta_seconds"] = 0
entry["gofile_cancel_requested"] = False
entry["gofile_pid"] = 0
entry["gofile_endpoint"] = endpoint
entry["gofile_provider"] = provider
entry["gofile_status"] = f"Sedang upload ke {provider}..."
entry["status_message"] = ""
save_monitor_state(state)
return entry
def start_remote_upload(task_id: str, provider: str, mode: str = "zip") -> str:
if provider not in {"gofile", "pixeldrain", "rclone"}:
raise ValueError("Provider upload tidak valid.")
if mode not in {"zip", "raw"}:
raise ValueError("Mode upload tidak valid.")
provider_name = {"gofile": "GoFile", "pixeldrain": "PixelDrain", "rclone": "rclone"}[provider]
if provider == "pixeldrain" and not PIXELDRAIN_API_KEY:
raise RuntimeError("PIXELDRAIN_API_KEY belum diset.")
if provider == "rclone" and not is_rclone_upload_available():
raise RuntimeError("rclone.conf belum tersedia atau tidak valid. Set RCLONE_CONFIG_URL dari env atau dashboard web.")
if is_aria2_task(task_id):
state = load_monitor_state()
entry = state.get("aria2", {}).get(task_id)
if not entry:
raise RuntimeError("Tugas Aria2 tidak ditemukan.")
file_path = Path(entry.get("file_path", "") or "")
if not file_path.exists():
raise RuntimeError("File Aria2 tidak ditemukan di storage.")
set_upload_state(task_id, provider_name, "pixeldrain" if provider == "pixeldrain" else rclone_remote_label() if provider == "rclone" else "")
if provider == "gofile":
start_gofile_upload_background(task_id, entry.get("name", file_path.name), file_path, mode="zip")
elif provider == "pixeldrain":
start_pixeldrain_upload_background(task_id, entry.get("name", file_path.name), file_path, mode="zip")
else:
start_rclone_upload_background(task_id, entry.get("name", file_path.name), file_path, mode="zip")
return f"Upload Aria2 ke {provider_name} dimulai."
client = get_client()
torrents = client.torrents_info(torrent_hashes=task_id)
if not torrents:
raise RuntimeError("Torrent tidak ditemukan.")
torrent = torrents[0]
if float(getattr(torrent, "progress", 0) or 0) < 1:
raise RuntimeError("Upload hanya tersedia setelah download selesai.")
content_path = Path(getattr(torrent, "content_path", "") or "")
if not content_path.exists():
raise RuntimeError("File hasil download tidak ditemukan di storage.")
if mode == "raw" and not content_path.is_dir():
raise RuntimeError("Mode raw hanya tersedia untuk folder.")
state = load_monitor_state()
entry = get_task_state_entry(state, task_id)
if entry.get("gofile_uploading"):
raise RuntimeError("Upload file eksternal masih berjalan.")
entry["gofile_uploading"] = True
entry["gofile_progress"] = 0
entry["gofile_speed"] = ""
entry["gofile_eta_seconds"] = 0
entry["gofile_cancel_requested"] = False
entry["gofile_pid"] = 0
entry["gofile_endpoint"] = "pixeldrain" if provider == "pixeldrain" else rclone_remote_label() if provider == "rclone" else ""
entry["gofile_provider"] = provider_name
entry["gofile_status"] = f"Sedang upload ke {provider_name}..."
entry["pre_upload_state"] = getattr(torrent, "state", "") or ""
entry["pre_upload_force_start"] = bool(getattr(torrent, "force_start", False))
entry["status_message"] = ""
save_monitor_state(state)
if provider == "gofile":
start_gofile_upload_background(task_id, torrent.name, content_path, mode=mode)
elif provider == "pixeldrain":
start_pixeldrain_upload_background(task_id, torrent.name, content_path, mode=mode)
else:
start_rclone_upload_background(task_id, torrent.name, content_path, mode=mode)
return f"Upload ke {provider_name} dimulai."
def pause_task(task_id: str) -> str:
if is_aria2_task(task_id):
ok, message = aria2.pause_task(task_id, STATE_FILE, STATE_LOCK)
if not ok:
raise RuntimeError(message)
return message
client = get_client()
client.torrents_pause(torrent_hashes=task_id)
return "Torrent dijeda."
def resume_task(task_id: str) -> str:
if is_aria2_task(task_id):
ok, message = aria2.resume_task(task_id, STATE_FILE, STATE_LOCK)
if not ok:
raise RuntimeError(message)
return message
client = get_client()
client.torrents_resume(torrent_hashes=task_id)
return "Torrent dilanjutkan."
def delete_task(task_id: str, delete_files: bool = False) -> str:
if is_aria2_task(task_id):
ok, message = aria2.delete_task(task_id, STATE_FILE, STATE_LOCK, delete_files)
if not ok:
raise RuntimeError(message)
return message
client = get_client()
client.torrents_delete(delete_files=delete_files, torrent_hashes=task_id)
state = load_monitor_state()
state.setdefault("torrents", {}).pop(task_id, None)
save_monitor_state(state)
return "Torrent dan file hasil download dihapus." if delete_files else "Torrent dihapus dari daftar."
def format_task_status(task: dict) -> str:
progress = int(task.get("progress", 0) or 0)
lines = [
f"Task: {task.get('name') or '-'}",
f"ID: {task.get('hash') or '-'}",
f"Type: {task.get('task_kind') or 'torrent'}",
f"Status: {task.get('state_label') or '-'}",
f"Progress: {progress_bar(progress)} {progress}%",
f"Size: {task.get('downloaded') or '-'} / {task.get('total_size') or '-'}",
f"Speed: Down {task.get('dlspeed') or '-'} | Up {task.get('upspeed') or '-'}",
f"ETA: {task.get('eta') or '-'}",
]
if task.get("gofile_uploading"):
lines.extend(
[
"",
f"Remote: {task.get('upload_provider') or '-'}",
f"Upload status: {task.get('gofile_status') or '-'}",
f"Upload speed: {task.get('gofile_speed') or '-'}",
f"Upload ETA: {task.get('gofile_eta') or '-'}",
]
)
if task.get("gofile_link"):
lines.extend(["", f"Remote link: {task.get('gofile_link')}"])
if task.get("status_message"):
lines.extend(["", f"Info: {task.get('status_message')}"])
return "\n".join(lines)
def task_keyboard(task: dict | None) -> InlineKeyboardMarkup | None:
if not task:
return None
task_id = task.get("hash", "")
rows = []
if task.get("can_pause"):
rows.append([InlineKeyboardButton("Pause", callback_data=f"pause:{task_id}")])
if task.get("can_resume"):
rows.append([InlineKeyboardButton("Resume", callback_data=f"resume:{task_id}")])
if task.get("can_gofile_upload") or task.get("can_pixeldrain_upload") or task.get("can_rclone_upload"):
upload_row = []
if task.get("can_gofile_upload"):
upload_row.append(InlineKeyboardButton("GoFile", callback_data=f"upload:gofile:zip:{task_id}"))
if task.get("can_pixeldrain_upload"):
upload_row.append(InlineKeyboardButton("PixelDrain", callback_data=f"upload:pixeldrain:zip:{task_id}"))
if task.get("can_rclone_upload"):
upload_row.append(InlineKeyboardButton("rclone", callback_data=f"upload:rclone:zip:{task_id}"))
rows.append(upload_row)
if task.get("can_raw_gofile_upload") or task.get("can_raw_pixeldrain_upload") or task.get("can_raw_rclone_upload"):
raw_row = []
if task.get("can_raw_gofile_upload"):
raw_row.append(InlineKeyboardButton("GoFile Raw", callback_data=f"upload:gofile:raw:{task_id}"))
if task.get("can_raw_pixeldrain_upload"):
raw_row.append(InlineKeyboardButton("Pixel Raw", callback_data=f"upload:pixeldrain:raw:{task_id}"))
if task.get("can_raw_rclone_upload"):
raw_row.append(InlineKeyboardButton("rclone Raw", callback_data=f"upload:rclone:raw:{task_id}"))
rows.append(raw_row)
rows.append(
[
InlineKeyboardButton("Refresh", callback_data=f"refresh:{task_id}"),
InlineKeyboardButton("Delete", callback_data=f"delete:{task_id}"),
InlineKeyboardButton("Delete Files", callback_data=f"delete_files:{task_id}"),
]
)
return InlineKeyboardMarkup(rows)
def should_stop_monitoring(task: dict | None) -> bool:
if not task:
return True
if task.get("gofile_uploading"):
return False
state = str(task.get("state") or "")
progress = int(task.get("progress", 0) or 0)
return progress >= 100 or state in {"complete", "error", "cancelled"}
async def safe_edit(message: Message, text: str, reply_markup=None) -> None:
try:
await message.edit_text(text, reply_markup=reply_markup, disable_web_page_preview=True)
except MessageNotModified:
return
except FloodWait as exc:
await asyncio.sleep(int(exc.value) + 1)
async def monitor_task_message(message: Message, task_id: str) -> None:
started = time.time()
while True:
try:
task = await asyncio.to_thread(task_snapshot, task_id)
text = format_task_status(task) if task else "Task tidak ditemukan atau sudah dihapus."
await safe_edit(message, text, reply_markup=task_keyboard(task))
if should_stop_monitoring(task):
return
except Exception as exc:
await safe_edit(message, f"Gagal membaca status task: {exc}")
return
if time.time() - started > PROGRESS_TIMEOUT_SECONDS:
return
await asyncio.sleep(PROGRESS_INTERVAL_SECONDS)
async def require_access(message: Message) -> bool:
if is_authorized(message):
return True
await message.reply_text("Akses ditolak.")
return False
@bot.on_message(filters.command(["start", "help"]))
async def help_command(_, message: Message):
if not await require_access(message):
return
await message.reply_text(
"\n".join(
[
"Torrent Web Bot siap.",
"",
"Command:",
"/qm <magnet> - tambah magnet link",
"/qbdown <magnet> - alias tambah magnet link",
"/aria2 <url> - direct download via Aria2",
"/tasks - lihat task terbaru",
"/status <task_id> - pantau task tertentu",
]
)
)
@bot.on_message(filters.command(["qm", "qbdown"]))
async def magnet_command(_, message: Message):
if not await require_access(message):
return
magnet = command_argument(message)
if not magnet:
await message.reply_text("Format: /qm magnet:?xt=urn:btih:...")
return
status_message = await message.reply_text("Menambahkan magnet ke qBittorrent...")
try:
task_id, name = await asyncio.to_thread(add_magnet_task, magnet)
await safe_edit(status_message, f"Magnet ditambahkan: {name}\nMenunggu status download...")
await monitor_task_message(status_message, task_id)
except Exception as exc:
await safe_edit(status_message, f"Gagal menambahkan magnet: {exc}")
@bot.on_message(filters.command(["aria2", "direct"]))
async def aria2_command(_, message: Message):
if not await require_access(message):
return
url = command_argument(message)
if not url:
await message.reply_text("Format: /aria2 https://example.com/file.iso")
return
status_message = await message.reply_text("Memulai Aria2 download...")
try:
task_id, filename = await asyncio.to_thread(add_aria2_task, url)
await safe_edit(status_message, f"Aria2 download dimulai: {filename}")
await monitor_task_message(status_message, task_id)
except Exception as exc:
await safe_edit(status_message, f"Gagal memulai Aria2: {exc}")
@bot.on_message(filters.command("tasks"))
async def tasks_command(_, message: Message):
if not await require_access(message):
return
try:
tasks = await asyncio.to_thread(all_task_snapshots)
except Exception as exc:
await message.reply_text(f"Gagal membaca task: {exc}")
return
if not tasks:
await message.reply_text("Belum ada task aktif.")
return
lines = ["Task terbaru:"]
for task in tasks:
lines.append(f"- {task.get('hash')}: {task.get('name')} ({task.get('progress')}%, {task.get('state_label')})")
await message.reply_text("\n".join(lines))
@bot.on_message(filters.command("status"))
async def status_command(_, message: Message):
if not await require_access(message):
return
task_id = command_argument(message)
if not task_id:
await message.reply_text("Format: /status <task_id>")
return
reply = await message.reply_text("Membaca status task...")
await monitor_task_message(reply, task_id)
@bot.on_callback_query()
async def callback_handler(_, query: CallbackQuery):
if not is_authorized(query):
await query.answer("Akses ditolak.", show_alert=True)
return
data = query.data or ""
try:
if data.startswith("upload:"):
_, provider, mode, task_id = data.split(":", 3)
message = await asyncio.to_thread(start_remote_upload, task_id, provider, mode)
await query.answer(message)
await monitor_task_message(query.message, task_id)
return
if data.startswith("pause:"):
task_id = data.split(":", 1)[1]
await query.answer(await asyncio.to_thread(pause_task, task_id))
await monitor_task_message(query.message, task_id)
return
if data.startswith("resume:"):
task_id = data.split(":", 1)[1]
await query.answer(await asyncio.to_thread(resume_task, task_id))
await monitor_task_message(query.message, task_id)
return
if data.startswith("delete_files:"):
task_id = data.split(":", 1)[1]
message = await asyncio.to_thread(delete_task, task_id, True)
await query.answer(message)
await safe_edit(query.message, message)
return
if data.startswith("delete:"):
task_id = data.split(":", 1)[1]
message = await asyncio.to_thread(delete_task, task_id, False)
await query.answer(message)
await safe_edit(query.message, message)
return
if data.startswith("refresh:"):
task_id = data.split(":", 1)[1]
task = await asyncio.to_thread(task_snapshot, task_id)
await query.answer("Status diperbarui.")
await safe_edit(query.message, format_task_status(task) if task else "Task tidak ditemukan.", task_keyboard(task))
return
await query.answer("Aksi tidak dikenal.", show_alert=True)
except Exception as exc:
await query.answer(str(exc)[:200], show_alert=True)
def main() -> None:
missing = []
if not API_ID:
missing.append("TELEGRAM_API_ID")
if not API_HASH:
missing.append("TELEGRAM_API_HASH")
if not BOT_TOKEN:
missing.append("TELEGRAM_BOT_TOKEN")
if missing:
raise RuntimeError(f"Env Telegram belum lengkap: {', '.join(missing)}")
print("Starting Telegram bot...", flush=True)
print(f"OWNER_IDS={OWNER_IDS}", flush=True)
bot.run()
if __name__ == "__main__":
main()
|