README / app.py
nexus33rd's picture
Update app.py
ac0a9be verified
Raw History Blame Contribute Delete
117 kB
import base64 import hashlib import json import os import platform import re import signal import shutil import socket import subprocess import threading import time from pathlib import Path from urllib.parse import parse_qs, quote, urlparse from flask import Flask, flash, jsonify, redirect, render_template, request, url_for import psutil import qbittorrentapi import requests import aria2 BASE_DIR = Path(__file__).resolve().parent UPLOAD_DIR = BASE_DIR / "uploads" STATE_FILE = BASE_DIR / "monitor_state.json" STATE_LOCK = threading.Lock() UPLOAD_DIR.mkdir(exist_ok=True) ACTIVE_DOWNLOAD_STATES = {"downloading", "metaDL", "stalledDL", "forcedMetaDL", "forcedDL"} PAUSED_STATES = {"pausedDL", "pausedUP"} FAILED_STATES = {"error", "missingFiles", "unknown"} STUCK_TIMEOUT_MINUTES = int(os.getenv("TORRENT_STUCK_TIMEOUT_MINUTES", "5")) STUCK_TIMEOUT_SECONDS = STUCK_TIMEOUT_MINUTES * 60 MAX_EVENTS = 12 SYSTEM_INFO_CACHE_SECONDS = 900 LOCATION_CACHE_SECONDS = 3600 GOFILE_LATENCY_CACHE_SECONDS = 600 GOFILE_ENDPOINT_CACHE: dict[str, object] = {"expires_at": 0.0, "urls": []} RCLONE_CONFIG_CACHE_SECONDS = 60 RCLONE_CONFIG_CACHE: dict[str, object] = {"expires_at": 0.0, "path": "", "remotes": [], "error": ""} RCLONE_CONFIG_MAX_BYTES = 2 * 1024 * 1024 BTIH_HASH_PATTERN = re.compile(r"^(?:[A-Fa-f0-9]{40}|[A-Z2-7]{32})$") TORRENT_FILE_SELECTION_WAIT_SECONDS = 8 class GofileUploadCancelled(Exception): pass class TorrentMetadataError(ValueError): pass class QBittorrentWebAPIError(RuntimeError): pass class InsufficientStorageError(ValueError): pass def env(name: str, default: str) -> str: return os.getenv(name, default) def default_download_path() -> str: if "QBITTORRENT_SAVE_PATH" in os.environ: return os.environ["QBITTORRENT_SAVE_PATH"] if Path("/data").exists(): return "/data/downloads" return "/downloads" def default_gofile_upload_urls() -> str: return ",".join( [ "https://upload.gofile.io/uploadfile", "https://upload-na-phx.gofile.io/uploadfile", "https://upload-na-nyc.gofile.io/uploadfile", "https://upload-eu-par.gofile.io/uploadfile", "https://upload-ap-sgp.gofile.io/uploadfile", ] ) def parse_gofile_upload_urls() -> list[str]: raw_value = env("GOFILE_UPLOAD_URLS", default_gofile_upload_urls()) urls = [item.strip() for item in raw_value.split(",") if item.strip()] return urls or ["https://upload.gofile.io/uploadfile"] def safe_filename(value: str) -> str: sanitized = re.sub(r"[^A-Za-z0-9._-]+", "-", value).strip("-") return sanitized or "archive" def flatten_relative_name(relative_path: Path) -> str: flattened = "__".join(relative_path.parts) return safe_filename(flattened) def validate_magnet_link(raw_value: str) -> tuple[bool, str]: magnet = (raw_value or "").strip() if not magnet: return False, "Magnet link wajib diisi." parsed = urlparse(magnet) if parsed.scheme.lower() != "magnet": return False, "Hanya magnet link yang didukung. Link selain magnet tidak diterima." query = parse_qs(parsed.query, keep_blank_values=False) xt_values = query.get("xt", []) if not xt_values: return False, "Magnet link tidak valid: parameter xt wajib ada." btih_value = "" for xt_value in xt_values: if xt_value.lower().startswith("urn:btih:"): btih_value = xt_value[9:] break if not btih_value: return False, "Magnet link tidak valid: xt harus berupa urn:btih." if not BTIH_HASH_PATTERN.fullmatch(btih_value.upper()): return False, "Magnet link tidak valid: info hash btih tidak sesuai format." return True, magnet def magnet_info_hash(magnet: str) -> str: parsed = urlparse(magnet) query = parse_qs(parsed.query, keep_blank_values=False) for xt_value in query.get("xt", []): if not xt_value.lower().startswith("urn:btih:"): continue raw_hash = xt_value[9:] if re.fullmatch(r"[A-Fa-f0-9]{40}", raw_hash): return raw_hash.lower() if re.fullmatch(r"[A-Z2-7a-z2-7]{32}", raw_hash): return base64.b32decode(raw_hash.upper()).hex() raise TorrentMetadataError("Magnet link tidak mengandung info hash btih yang valid.") def _read_bencoded_bytes(data: bytes, offset: int) -> tuple[bytes, int]: colon_index = data.find(b":", offset) if colon_index < 0: raise TorrentMetadataError("Metadata torrent tidak valid.") try: length = int(data[offset:colon_index]) except ValueError as exc: raise TorrentMetadataError("Metadata torrent tidak valid.") from exc start = colon_index + 1 end = start + length if length < 0 or end > len(data): raise TorrentMetadataError("Metadata torrent tidak valid.") return data[start:end], end def _skip_bencoded_value(data: bytes, offset: int) -> int: if offset >= len(data): raise TorrentMetadataError("Metadata torrent tidak valid.") token = data[offset : offset + 1] if token == b"i": end = data.find(b"e", offset + 1) if end < 0: raise TorrentMetadataError("Metadata torrent tidak valid.") return end + 1 if token in {b"l", b"d"}: offset += 1 while offset < len(data) and data[offset : offset + 1] != b"e": offset = _skip_bencoded_value(data, offset) if offset >= len(data): raise TorrentMetadataError("Metadata torrent tidak valid.") return offset + 1 if token.isdigit(): _value, next_offset = _read_bencoded_bytes(data, offset) return next_offset raise TorrentMetadataError("Metadata torrent tidak valid.") def torrent_info_hash_from_bytes(data: bytes) -> str: if not data.startswith(b"d"): raise TorrentMetadataError("File torrent tidak valid.") offset = 1 while offset < len(data) and data[offset : offset + 1] != b"e": key, offset = _read_bencoded_bytes(data, offset) value_start = offset value_end = _skip_bencoded_value(data, offset) if key == b"info": return hashlib.sha1(data[value_start:value_end]).hexdigest() offset = value_end raise TorrentMetadataError("File torrent tidak mengandung metadata info.") def parse_size_token(token: str) -> int | None: cleaned = token.strip() if not cleaned or cleaned in {"-", "--", "--:--:--"}: return None unit = "" if cleaned[-1].isalpha(): unit = cleaned[-1].lower() cleaned = cleaned[:-1] try: value = float(cleaned) except ValueError: return None multipliers = { "": 1, "k": 1000, "m": 1000**2, "g": 1000**3, "t": 1000**4, "p": 1000**5, } return int(value * multipliers.get(unit, 1)) def gofile_endpoint_label(upload_url: str) -> str: host = urlparse(upload_url).hostname or "upload.gofile.io" return host.replace(".gofile.io", "") def measure_gofile_endpoint_latency(upload_url: str) -> float: host = urlparse(upload_url).hostname if not host: return float("inf") started = time.perf_counter() connection = socket.create_connection((host, 443), timeout=2) connection.close() return time.perf_counter() - started def ranked_gofile_upload_urls() -> list[str]: now = time.time() cached_urls = GOFILE_ENDPOINT_CACHE.get("urls", []) expires_at = float(GOFILE_ENDPOINT_CACHE.get("expires_at", 0.0) or 0.0) if cached_urls and now < expires_at: return list(cached_urls) ranked: list[tuple[float, int, str]] = [] for index, upload_url in enumerate(GOFILE_UPLOAD_URLS): try: latency = measure_gofile_endpoint_latency(upload_url) except OSError: latency = float("inf") ranked.append((latency, index, upload_url)) ranked.sort(key=lambda item: (item[0], item[1])) ordered_urls = [item[2] for item in ranked] GOFILE_ENDPOINT_CACHE["urls"] = ordered_urls GOFILE_ENDPOINT_CACHE["expires_at"] = now + GOFILE_LATENCY_CACHE_SECONDS return ordered_urls def discover_root_rclone_config() -> Path | None: candidates = [ RCLONE_CONFIG_PATH, BASE_DIR / "rclone.conf", Path("/config/rclone.conf"), Path("/data/rclone.conf"), ] for candidate in candidates: if candidate.exists() and candidate.is_file() and candidate.stat().st_size > 0: return candidate return None def download_rclone_config_from_url(raw_url: str) -> Path: parsed = urlparse(raw_url) if parsed.scheme.lower() not in {"http", "https"}: raise ValueError("RCLONE_CONFIG_URL harus berupa URL http/https.") response = requests.get(raw_url, timeout=30) response.raise_for_status() content = response.content if len(content) > RCLONE_CONFIG_MAX_BYTES: raise ValueError("rclone.conf dari URL terlalu besar.") if not content.strip(): raise ValueError("rclone.conf dari URL kosong.") destination = UPLOAD_DIR / "rclone.conf" destination.write_bytes(content) return destination def runtime_rclone_config_url() -> str: if RCLONE_CONFIG_URL: return RCLONE_CONFIG_URL try: state = load_monitor_state() except Exception: return "" return str(state.get("rclone", {}).get("config_url", "") or "").strip() def set_runtime_rclone_config_url(raw_url: str) -> None: def mutator(state: dict): state.setdefault("rclone", {})["config_url"] = raw_url.strip() update_state(mutator) RCLONE_CONFIG_CACHE.update({"expires_at": 0.0, "path": "", "remotes": [], "error": ""}) def rclone_config_path() -> Path: config_url = runtime_rclone_config_url() if config_url: return download_rclone_config_from_url(config_url) config_path = discover_root_rclone_config() if config_path is None: raise FileNotFoundError( "rclone.conf belum ditemukan. Tambahkan rclone.conf di root project, /config, /data, " "atau set RCLONE_CONFIG_URL ke raw URL GitHub/Gist." ) return config_path def validate_rclone_config(force_refresh: bool = False) -> dict: now = time.time() if not force_refresh and now < float(RCLONE_CONFIG_CACHE.get("expires_at", 0.0) or 0.0): return dict(RCLONE_CONFIG_CACHE) result: dict[str, object] = {"expires_at": now + RCLONE_CONFIG_CACHE_SECONDS, "path": "", "remotes": [], "error": ""} try: if shutil.which("rclone") is None: raise FileNotFoundError("Binary rclone belum tersedia di container.") config_path = rclone_config_path() process = subprocess.run( ["rclone", "--config", str(config_path), "listremotes"], capture_output=True, text=True, timeout=30, check=False, ) if process.returncode != 0: detail = (process.stderr or process.stdout or "").strip() raise ValueError(f"rclone.conf tidak valid: {detail[:500]}") remotes = [line.strip().rstrip(":") for line in process.stdout.splitlines() if line.strip()] if not remotes: raise ValueError("rclone.conf tidak berisi remote aktif.") if RCLONE_REMOTE and RCLONE_REMOTE not in remotes: raise ValueError(f"Remote rclone '{RCLONE_REMOTE}' tidak ditemukan. Remote tersedia: {', '.join(remotes)}") result["path"] = str(config_path) result["remotes"] = remotes except (OSError, ValueError, requests.RequestException) as exc: result["error"] = str(exc) RCLONE_CONFIG_CACHE.update(result) return dict(RCLONE_CONFIG_CACHE) def is_rclone_upload_available() -> bool: config = validate_rclone_config() return bool(config.get("remotes")) and not config.get("error") def rclone_config_summary(force_refresh: bool = False) -> dict: config = validate_rclone_config(force_refresh=force_refresh) return { "available": bool(config.get("remotes")) and not config.get("error"), "error": config.get("error", ""), "remotes": config.get("remotes", []), "selected_remote": selected_rclone_remote(config), "config_url_set": bool(runtime_rclone_config_url()), "config_path": config.get("path", ""), } def selected_rclone_remote(config: dict | None = None) -> str: config = config or validate_rclone_config() remotes = list(config.get("remotes", []) or []) if RCLONE_REMOTE: return RCLONE_REMOTE return str(remotes[0]) if remotes else "" def requested_rclone_remote(config: dict, raw_remote: str) -> str: remotes = [str(remote) for remote in list(config.get("remotes", []) or [])] remote = raw_remote.strip().rstrip(":") if not remote: remote = selected_rclone_remote(config) if not remote: raise ValueError("Remote rclone belum dipilih.") if remote not in remotes: available = ", ".join(remotes) if remotes else "-" raise ValueError(f"Remote rclone '{remote}' tidak ditemukan. Remote tersedia: {available}") return remote def rclone_remote_label() -> str: remote = selected_rclone_remote() return remote or "rclone" def rclone_remote_path(*parts: str) -> str: cleaned = [part.strip("/").replace("\\", "/") for part in parts if part and part.strip("/")] return "/".join(cleaned) def rclone_destination_spec(remote: str, *parts: str) -> str: destination_path = rclone_remote_path(RCLONE_DESTINATION_PATH, *parts) return f"{remote}:{destination_path}" if destination_path else f"{remote}:" def path_total_size(source_path: Path) -> int: if source_path.is_file(): return source_path.stat().st_size total = 0 for item in source_path.rglob("*"): if item.is_file(): try: total += item.stat().st_size except OSError: continue return total def process_exists(pid: int | None) -> bool: if not pid or pid <= 0: return False try: os.kill(pid, 0) except OSError: return False return True def cancel_upload_process(pid: int | None) -> bool: if not process_exists(pid): return False try: os.kill(pid, signal.SIGTERM) return True except OSError: return False GOFILE_UPLOAD_URLS = parse_gofile_upload_urls() GOFILE_API_TOKEN = env("GOFILE_API_TOKEN", "Rqm8uMPcbDbAV8wdiG93lNRcGuvSJj3r") PIXELDRAIN_API_KEY = env("PIXELDRAIN_API_KEY", "acee6b32-bba9-45f1-bfb1-71cf583ad405") PIXELDRAIN_API_URL = env("PIXELDRAIN_API_URL", "https://pixeldrain.com/api") IP_LOCATION_API_URL = env("IP_LOCATION_API_URL", "https://ipapi.co/json/") CLOUDFLARE_DOWNLOAD_URL = env("CLOUDFLARE_DOWNLOAD_URL", "https://speed.cloudflare.com/__down") CLOUDFLARE_UPLOAD_URL = env("CLOUDFLARE_UPLOAD_URL", "https://speed.cloudflare.com/__up") RCLONE_CONFIG_URL = env("RCLONE_CONFIG_URL", "").strip() RCLONE_CONFIG_PATH = Path(env("RCLONE_CONFIG_PATH", str(BASE_DIR / "rclone.conf"))).expanduser() RCLONE_REMOTE = env("RCLONE_REMOTE", "").strip().rstrip(":") RCLONE_DESTINATION_PATH = env("RCLONE_DESTINATION_PATH", "torrent-web").strip().strip("/") WEB_PORT = int(env("PORT", "5000")) app = Flask(__name__) app.config["SECRET_KEY"] = env("FLASK_SECRET_KEY", "dev-secret") app.config["MAX_CONTENT_LENGTH"] = 100 * 1024 * 1024 DOWNLOAD_PATH = default_download_path() def get_client() -> qbittorrentapi.Client: host = env("QBITTORRENT_HOST", "127.0.0.1") port = int(env("QBITTORRENT_PORT", "8080")) username = env("QBITTORRENT_USERNAME", "") password = env("QBITTORRENT_PASSWORD", "") client = qbittorrentapi.Client( host=host, port=port, username=username, password=password, ) if username and password: try: client.auth_log_in() except qbittorrentapi.LoginFailed: # Docker deployments in this repo can allow the app subnet to bypass # WebUI auth. Fall back to a session without explicit login so the UI # still works while qBittorrent config is being repaired or migrated. fallback_client = qbittorrentapi.Client(host=host, port=port) fallback_client.app.version return fallback_client return client def qbt_base_url() -> str: host = env("QBITTORRENT_HOST", "127.0.0.1") port = int(env("QBITTORRENT_PORT", "8080")) return f"http://{host}:{port}/api/v2" def qbt_webapi_request(method: str, path: str, **kwargs) -> requests.Response: session = requests.Session() base_url = qbt_base_url() username = env("QBITTORRENT_USERNAME", "") password = env("QBITTORRENT_PASSWORD", "") timeout = kwargs.pop("timeout", 20) if username and password: login_response = session.post( f"{base_url}/auth/login", data={"username": username, "password": password}, timeout=10, ) if login_response.status_code >= 400 or login_response.text.strip() not in {"Ok.", ""}: # Some bundled qBittorrent configs bypass auth for the app subnet. session = requests.Session() response = session.request(method, f"{base_url}{path}", timeout=timeout, **kwargs) if response.status_code >= 400: raise QBittorrentWebAPIError(response.text.strip() or f"HTTP {response.status_code}") return response def qbt_add_torrent_url(url: str, paused: bool) -> None: response = qbt_webapi_request( "POST", "/torrents/add", data={ "urls": url, "savepath": DOWNLOAD_PATH, "paused": "true" if paused else "false", "stopped": "true" if paused else "false", }, timeout=30, ) if response.text.strip() not in {"Ok.", ""}: raise QBittorrentWebAPIError(response.text.strip()) def qbt_add_torrent_file(file_path: Path, paused: bool) -> None: with file_path.open("rb") as handle: response = qbt_webapi_request( "POST", "/torrents/add", data={ "savepath": DOWNLOAD_PATH, "paused": "true" if paused else "false", "stopped": "true" if paused else "false", }, files={"torrents": (file_path.name, handle, "application/x-bittorrent")}, timeout=30, ) if response.text.strip() not in {"Ok.", ""}: raise QBittorrentWebAPIError(response.text.strip()) def qbt_torrent_files(torrent_hash: str) -> list[dict]: response = qbt_webapi_request("GET", "/torrents/files", params={"hash": torrent_hash}, timeout=15) payload = response.json() return payload if isinstance(payload, list) else [] def qbt_torrent_exists(torrent_hash: str) -> bool: response = qbt_webapi_request("GET", "/torrents/info", params={"hashes": torrent_hash}, timeout=15) payload = response.json() return isinstance(payload, list) and len(payload) > 0 def qbt_delete_torrent(torrent_hash: str, delete_files: bool = False) -> None: qbt_webapi_request( "POST", "/torrents/delete", data={"hashes": torrent_hash, "deleteFiles": "true" if delete_files else "false"}, timeout=15, ) def wait_for_torrent_task(torrent_hash: str, timeout_seconds: int = 6) -> bool: deadline = time.time() + timeout_seconds while time.time() <= deadline: if qbt_torrent_exists(torrent_hash): return True time.sleep(0.5) return False def qbt_pause_torrent(torrent_hash: str) -> None: try: qbt_webapi_request("POST", "/torrents/stop", data={"hashes": torrent_hash}, timeout=15) except QBittorrentWebAPIError: qbt_webapi_request("POST", "/torrents/pause", data={"hashes": torrent_hash}, timeout=15) def qbt_resume_torrent(torrent_hash: str) -> None: try: qbt_webapi_request("POST", "/torrents/start", data={"hashes": torrent_hash}, timeout=15) except QBittorrentWebAPIError: qbt_webapi_request("POST", "/torrents/resume", data={"hashes": torrent_hash}, timeout=15) def qbt_set_file_priority(torrent_hash: str, file_ids: list[int], priority: int) -> None: if not file_ids: return qbt_webapi_request( "POST", "/torrents/filePrio", data={ "hash": torrent_hash, "id": "|".join(str(file_id) for file_id in file_ids), "priority": str(priority), }, timeout=20, ) def torrent_file_index(file_entry: dict, fallback: int) -> int: for key in ("index", "id"): value = file_entry.get(key) if value is not None: return int(value) return fallback def serialize_torrent_file(file_entry: dict, fallback_index: int) -> dict: file_index = torrent_file_index(file_entry, fallback_index) size = int(file_entry.get("size", 0) or 0) priority = int(file_entry.get("priority", 1) or 0) return { "id": file_index, "name": str(file_entry.get("name", "") or f"File {file_index + 1}"), "size": format_size(size), "size_bytes": size, "priority": priority, "selected": priority != 0, } def download_storage_usage(): return shutil.disk_usage(DOWNLOAD_PATH) def storage_validation(required_bytes: int) -> dict: disk = download_storage_usage() available_bytes = int(disk.free) required_bytes = max(0, int(required_bytes or 0)) ok = required_bytes <= available_bytes return { "storage_ok": ok, "storage_required_bytes": required_bytes, "storage_required": format_size(required_bytes), "storage_available_bytes": available_bytes, "storage_available": format_size(available_bytes), "storage_warning": "" if ok else ( f"Storage tidak cukup. Butuh {format_size(required_bytes)}, " f"tersedia {format_size(available_bytes)}. Hapus atau bersihkan file lama dulu." ), } def ensure_storage_available(required_bytes: int) -> None: validation = storage_validation(required_bytes) if not validation["storage_ok"]: raise InsufficientStorageError(validation["storage_warning"]) def selected_torrent_file_stats(torrent_hash: str, fallback_total_size: int) -> dict: try: files = qbt_torrent_files(torrent_hash) except (QBittorrentWebAPIError, requests.RequestException, ValueError): files = [] if not files: return { "selected_total_size": fallback_total_size, "selected_downloaded": 0, "selected_file_count": 0, "file_count": 0, "has_file_selection": False, } selected_files = [file_entry for file_entry in files if int(file_entry.get("priority", 0) or 0) > 0] selected_total_size = sum(int(file_entry.get("size", 0) or 0) for file_entry in selected_files) selected_downloaded = sum( int((int(file_entry.get("size", 0) or 0) * float(file_entry.get("progress", 0) or 0))) for file_entry in selected_files ) return { "selected_total_size": selected_total_size, "selected_downloaded": min(selected_downloaded, selected_total_size), "selected_file_count": len(selected_files), "file_count": len(files), "has_file_selection": len(files) > 1 and len(selected_files) < len(files), } def wait_for_torrent_files(torrent_hash: str, timeout_seconds: int = TORRENT_FILE_SELECTION_WAIT_SECONDS) -> list[dict]: deadline = time.time() + timeout_seconds while time.time() <= deadline: files = qbt_torrent_files(torrent_hash) if files: return files time.sleep(0.5) return [] def build_file_selection_payload(torrent_hash: str, files: list[dict]) -> dict: serialized_files = [serialize_torrent_file(file_entry, index) for index, file_entry in enumerate(files)] selected_total_size = sum(int(file_entry.get("size_bytes", 0) or 0) for file_entry in serialized_files if file_entry.get("selected", True)) storage = storage_validation(selected_total_size) selection_required = len(serialized_files) > 1 if selection_required: qbt_pause_torrent(torrent_hash) return { "selection_required": True, "selection_pending": False, "torrent_hash": torrent_hash, "files": serialized_files, **storage, "message": "Torrent berisi beberapa file. Pilih file yang ingin didownload.", } if not storage["storage_ok"]: try: qbt_delete_torrent(torrent_hash, delete_files=False) except (QBittorrentWebAPIError, requests.RequestException): pass raise InsufficientStorageError(storage["storage_warning"]) qbt_resume_torrent(torrent_hash) return { "selection_required": False, "selection_pending": False, "torrent_hash": torrent_hash, "files": serialized_files, **storage, "message": "Torrent ditambahkan dan download dimulai.", } def clear_torrent_status_message(torrent_hash: str) -> None: state = load_monitor_state() entry = state.setdefault("torrents", {}).setdefault(torrent_hash, {}) entry["last_progress_at"] = time.time() entry["status_message"] = "" save_monitor_state(state) def add_magnet_and_confirm_task(magnet: str, torrent_hash: str) -> None: try: qbt_add_torrent_url(magnet, paused=False) except (QBittorrentWebAPIError, requests.RequestException): if not wait_for_torrent_task(torrent_hash): raise else: wait_for_torrent_task(torrent_hash) def format_size(value: int | None) -> str: if value in (None, 0): return "0 B" size = float(value) units = ["B", "KB", "MB", "GB", "TB"] for unit in units: if size < 1024 or unit == units[-1]: return f"{size:.1f} {unit}" size /= 1024 return f"{size:.1f} TB" def format_speed(value: int | None) -> str: return f"{format_size(value)}/s" def format_mbps(bits_per_second: float | None) -> str: if not bits_per_second: return "0 Mbps" return f"{bits_per_second / 1_000_000:.2f} Mbps" def progress_percent(progress: float | None) -> int: if progress is None: return 0 return round(progress * 100) def format_duration(seconds: float) -> str: seconds = max(0, int(seconds)) if seconds < 60: return f"{seconds} detik" if seconds < 3600: return f"{seconds // 60} menit" return f"{seconds // 3600} jam" def human_eta(seconds: float | int | None) -> str: if seconds is None: return "-" total_seconds = int(seconds) if total_seconds <= 0: return "-" if total_seconds < 60: return f"{total_seconds} seconds left" minutes = total_seconds // 60 if total_seconds < 3600: return f"{minutes} minute left" if minutes == 1 else f"{minutes} minutes left" if total_seconds < 86400: hours = total_seconds // 3600 remaining_minutes = (total_seconds % 3600) // 60 if remaining_minutes == 0: return f"{hours} hour left" if hours == 1 else f"{hours} hours left" hour_label = "hour" if hours == 1 else "hours" minute_label = "minute" if remaining_minutes == 1 else "minutes" return f"{hours} {hour_label} {remaining_minutes} {minute_label} left" days = total_seconds // 86400 hours = total_seconds // 3600 remaining_hours = (total_seconds % 86400) // 3600 if remaining_hours == 0: return f"{days} day left" if days == 1 else f"{days} days left" day_label = "day" if days == 1 else "days" hour_label = "hour" if remaining_hours == 1 else "hours" return f"{days} {day_label} {remaining_hours} {hour_label} left" def load_monitor_state() -> dict: with STATE_LOCK: if not STATE_FILE.exists(): return {"torrents": {}, "aria2": {}, "events": [], "system": {}, "speedtest": {"running": False}} try: data = json.loads(STATE_FILE.read_text(encoding="utf-8")) except (json.JSONDecodeError, OSError): return {"torrents": {}, "aria2": {}, "events": [], "system": {}, "speedtest": {"running": False}} data.setdefault("torrents", {}) data.setdefault("aria2", {}) data.setdefault("events", []) data.setdefault("system", {}) data.setdefault("speedtest", {"running": False}) return data def save_monitor_state(state: dict) -> None: with STATE_LOCK: temp_file = STATE_FILE.with_suffix(".tmp") temp_file.write_text(json.dumps(state, ensure_ascii=True, indent=2), encoding="utf-8") temp_file.replace(STATE_FILE) def update_state(mutator): state = load_monitor_state() mutator(state) save_monitor_state(state) def add_event(state: dict, level: str, message: str) -> None: state.setdefault("events", []).insert( 0, { "level": level, "message": message, "created_at": int(time.time()), }, ) state["events"] = state["events"][:MAX_EVENTS] def state_label(raw_state: str) -> str: mapping = { "downloading": "Downloading", "stalledDL": "Stalled", "metaDL": "Fetching Metadata", "pausedDL": "Paused", "pausedUP": "Paused", "uploading": "Seeding", "stalledUP": "Stalled Up", "queuedDL": "Queued", "queuedUP": "Queued Up", "checkingUP": "Checking", "checkingDL": "Checking", "forcedDL": "Forced Download", "forcedMetaDL": "Forced Metadata", "forcedUP": "Seeding", "error": "Error", "missingFiles": "Missing Files", } return mapping.get(raw_state, raw_state) def status_badge(raw_state: str) -> str: if raw_state in FAILED_STATES: return "border-rose-500/30 bg-rose-500/10 text-rose-200" if raw_state in ACTIVE_DOWNLOAD_STATES: return "border-amber-500/30 bg-amber-500/10 text-amber-100" if raw_state in PAUSED_STATES: return "border-stone-500/30 bg-stone-500/10 text-stone-200" return "border-emerald-500/30 bg-emerald-500/10 text-emerald-100" def effective_state_label(torrent, state_entry: dict | None = None) -> str: if state_entry and state_entry.get("gofile_uploading"): provider_name = state_entry.get("gofile_provider") or "Remote" return f"{provider_name} Upload" raw_state = getattr(torrent, "state", "") progress = float(getattr(torrent, "progress", 0) or 0) if progress >= 1: if raw_state in {"uploading", "forcedUP", "stalledUP"}: return "Seeding" if raw_state == "pausedUP": return "Paused" if raw_state == "queuedUP": return "Queued Up" if raw_state == "checkingUP": return "Checking Up" return state_label(raw_state) def effective_status_badge(torrent, state_entry: dict | None = None) -> str: if state_entry and state_entry.get("gofile_uploading"): return "border-sky-500/30 bg-sky-500/10 text-sky-100" raw_state = getattr(torrent, "state", "") progress = float(getattr(torrent, "progress", 0) or 0) upspeed = int(getattr(torrent, "upspeed", 0) or 0) if progress >= 1 and raw_state in {"uploading", "forcedUP", "stalledUP"}: if upspeed > 0: return "border-sky-500/30 bg-sky-500/10 text-sky-100" return "border-lime/30 bg-lime/10 text-lime" return status_badge(raw_state) def swarm_peer_counts(torrent) -> tuple[int, int]: live_seeds = int(getattr(torrent, "num_seeds", 0) or 0) live_leechs = int(getattr(torrent, "num_leechs", 0) or 0) tracker_complete = int(getattr(torrent, "num_complete", 0) or 0) tracker_incomplete = int(getattr(torrent, "num_incomplete", 0) or 0) return max(live_seeds, tracker_complete), max(live_leechs, tracker_incomplete) def serialize_event(event: dict) -> dict: return { "level": event.get("level", "info"), "message": event.get("message", ""), "created_at": event.get("created_at", 0), } def serialize_torrent(torrent, state_entry: dict | None = None) -> dict: eta_value = getattr(torrent, "eta", None) raw_state = getattr(torrent, "state", "") torrent_total_size = int(getattr(torrent, "total_size", 0) or 0) torrent_progress = float(getattr(torrent, "progress", 0) or 0) raw_torrent_dlspeed = int(getattr(torrent, "dlspeed", 0) or 0) torrent_upspeed = int(getattr(torrent, "upspeed", 0) or 0) torrent_downloaded = max( int(getattr(torrent, "downloaded", 0) or 0), int(getattr(torrent, "downloaded_session", 0) or 0), ) torrent_uploaded = max( int(getattr(torrent, "uploaded", 0) or 0), int(getattr(torrent, "uploaded_session", 0) or 0), ) selected_stats = selected_torrent_file_stats(getattr(torrent, "hash", ""), torrent_total_size) display_total_size = int(selected_stats["selected_total_size"] or 0) display_downloaded = int(selected_stats["selected_downloaded"] or 0) if not selected_stats["file_count"]: display_downloaded = torrent_downloaded elif not selected_stats["has_file_selection"]: display_downloaded = torrent_downloaded torrent_num_seeds, torrent_num_leechs = swarm_peer_counts(torrent) state_entry = state_entry or {} status_message = state_entry.get("status_message", "") content_path = Path(getattr(torrent, "content_path", "") or "") is_folder = bool(content_path and content_path.exists() and content_path.is_dir()) gofile_uploading = bool(state_entry.get("gofile_uploading")) upload_provider = state_entry.get("gofile_provider", "GoFile") gofile_progress = int(state_entry.get("gofile_progress", 0) or 0) gofile_eta_seconds = int(state_entry.get("gofile_eta_seconds", 0) or 0) torrent_dlspeed = 0 if not gofile_uploading and torrent_progress >= 1 else raw_torrent_dlspeed display_progress = gofile_progress if gofile_uploading else progress_percent(torrent_progress) if gofile_uploading and upload_provider == "Archiving": progress_label = "Archiving" else: progress_label = f"{upload_provider} Upload" if gofile_uploading else "Progress" gofile_speed = state_entry.get("gofile_speed", "") badge_download_speed = format_speed(torrent_dlspeed) badge_upload_speed = format_speed(torrent_upspeed) if gofile_uploading: eta_text = human_eta(gofile_eta_seconds) badge_download_speed = "0 B/s" badge_upload_speed = gofile_speed or "0 B/s" elif torrent_progress >= 1: eta_text = "-" else: eta_text = human_eta(eta_value) display_speed = gofile_speed if gofile_uploading else format_speed(torrent_dlspeed) if gofile_uploading and upload_provider == "Archiving": display_speed = state_entry.get("gofile_status", "") or "Archiving..." display_speed_label = "Archive" else: display_speed_label = f"{upload_provider} Upload" if gofile_uploading else "Down" display_speed_meta = f"{gofile_progress}%" if gofile_uploading else "" if not gofile_uploading and torrent_progress >= 1: display_speed = format_speed(torrent_upspeed) display_speed_label = "Up" display_speed_meta = "" can_gofile_upload = ( bool(content_path) and content_path.exists() and progress_percent(torrent_progress) >= 100 and not gofile_uploading ) return { "hash": torrent.hash, "name": torrent.name, "state": torrent.state, "state_label": effective_state_label(torrent, state_entry), "state_badge": effective_status_badge(torrent, state_entry), "total_size": format_size(display_total_size), "torrent_total_size": format_size(torrent_total_size), "selected_file_count": selected_stats["selected_file_count"], "file_count": selected_stats["file_count"], "has_file_selection": selected_stats["has_file_selection"], "downloaded": format_size(display_downloaded), "uploaded": format_size(torrent_uploaded), "ratio": f"{float(getattr(torrent, 'ratio', 0) or 0):.2f}", "dlspeed": badge_download_speed, "upspeed": badge_upload_speed, "display_speed": display_speed, "display_speed_label": display_speed_label, "display_speed_meta": display_speed_meta, "progress": display_progress, "progress_label": progress_label, "num_seeds": torrent_num_seeds, "num_leechs": torrent_num_leechs, "eta": eta_text, "status_message": status_message, "can_pause": torrent.state not in PAUSED_STATES and torrent.state not in FAILED_STATES and not gofile_uploading, "can_resume": torrent.state in PAUSED_STATES, "can_gofile_upload": can_gofile_upload, "gofile_link": state_entry.get("gofile_link", ""), "gofile_status": state_entry.get("gofile_status", ""), "gofile_uploading": gofile_uploading, "gofile_speed": gofile_speed, "gofile_eta": human_eta(gofile_eta_seconds) if gofile_uploading else "-", "gofile_endpoint": state_entry.get("gofile_endpoint", ""), "upload_provider": upload_provider, "can_copy_link": bool(state_entry.get("gofile_link")), "can_cancel_gofile_upload": gofile_uploading, "can_pixeldrain_upload": can_gofile_upload and bool(PIXELDRAIN_API_KEY), "can_rclone_upload": can_gofile_upload, "rclone_config_ready": is_rclone_upload_available(), "rclone_config_error": validate_rclone_config().get("error", ""), "is_folder": is_folder, "can_raw_gofile_upload": is_folder and bool(GOFILE_API_TOKEN), "can_raw_pixeldrain_upload": is_folder and bool(PIXELDRAIN_API_KEY), "can_raw_rclone_upload": is_folder, "task_kind": "torrent", "added_at": int(getattr(torrent, "added_on", 0) or 0), } def is_aria2_task(task_id: str) -> bool: return str(task_id).startswith("aria2_") def get_task_state_entry(state: dict, task_id: str) -> dict: bucket_name = "aria2" if is_aria2_task(task_id) else "torrents" return state.setdefault(bucket_name, {}).setdefault(task_id, {}) def update_task_entry(task_id: str, **fields) -> None: def mutator(state: dict): entry = get_task_state_entry(state, task_id) entry.update(fields) update_state(mutator) def prepare_upload_source(source_path: Path, torrent_hash: str, provider_name: str) -> tuple[Path, bool]: if source_path.is_file(): return source_path, False archive_name = f"{source_path.name}.zip" archive_path = UPLOAD_DIR / archive_name if archive_path.exists(): archive_path = UPLOAD_DIR / f"{source_path.name}-{torrent_hash[:8]}.zip" update_task_entry( torrent_hash, gofile_provider="Archiving", gofile_status=f"Archiving folder for {provider_name}...", status_message=f"Archiving folder for {provider_name}...", gofile_progress=0, gofile_speed="", gofile_eta_seconds=0, ) process = subprocess.Popen( ["7z", "a", "-tzip", "-mx=5", "-bsp1", str(archive_path), source_path.name], cwd=str(source_path.parent), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, ) error_lines: list[str] = [] monitor_thread = threading.Thread( target=monitor_7z_progress, args=(process.stdout, torrent_hash, provider_name, error_lines), daemon=True, ) monitor_thread.start() update_task_entry(torrent_hash, gofile_pid=process.pid) while True: return_code = process.poll() current_state = load_monitor_state() current_entry = get_task_state_entry(current_state, torrent_hash) if current_entry.get("gofile_cancel_requested"): cancel_upload_process(process.pid) if return_code is not None: break time.sleep(1) monitor_thread.join(timeout=1) if current_entry.get("gofile_cancel_requested") or process.returncode == -15: archive_path.unlink(missing_ok=True) raise GofileUploadCancelled(f"Archiving {provider_name} dibatalkan.") if process.returncode != 0: archive_path.unlink(missing_ok=True) raise ValueError(" | ".join(error_lines[-3:]).strip() or "Gagal membuat arsip ZIP.") update_task_entry( torrent_hash, gofile_provider=provider_name, gofile_status=f"Archive ready, memulai upload ke {provider_name}...", status_message="", gofile_progress=100, ) return archive_path, True def list_folder_files(source_path: Path) -> list[tuple[Path, Path]]: return [(file_path, file_path.relative_to(source_path)) for file_path in source_path.rglob("*") if file_path.is_file()] def upload_folder_raw_gofile(torrent_hash: str, source_path: Path) -> tuple[str, str]: if not GOFILE_API_TOKEN: raise ValueError("Raw folder upload GoFile memerlukan GOFILE_API_TOKEN.") file_entries = list_folder_files(source_path) if not file_entries: raise ValueError("Folder tidak berisi file yang bisa diupload.") total_files = len(file_entries) total_bytes = sum(file_path.stat().st_size for file_path, _ in file_entries) uploaded_bytes = 0 folder_id = "" folder_link = "" folder_renamed = False for index, (file_path, relative_path) in enumerate(file_entries, start=1): current_state = load_monitor_state() current_entry = get_task_state_entry(current_state, torrent_hash) if current_entry.get("gofile_cancel_requested"): raise GofileUploadCancelled("Upload GoFile dibatalkan.") progress = int((uploaded_bytes / total_bytes) * 100) if total_bytes else 0 update_task_entry( torrent_hash, gofile_progress=progress, gofile_speed="", gofile_eta_seconds=0, gofile_status=f"Uploading raw folder to GoFile... {index}/{total_files}", status_message=f"Uploading raw folder to GoFile... {index}/{total_files}", ) with file_path.open("rb") as handle: files = {"file": (relative_path.name, handle)} data: dict[str, str] = {} headers = {"Authorization": f"Bearer {GOFILE_API_TOKEN}"} if folder_id: data["folderId"] = folder_id response = requests.post(GOFILE_UPLOAD_URLS[0], files=files, data=data, headers=headers, timeout=3600) response.raise_for_status() payload = response.json() data_payload = payload.get("data", payload) folder_id = ( data_payload.get("parentFolder") or data_payload.get("folderId") or data_payload.get("parentFolderId") or folder_id ) folder_link = data_payload.get("downloadPage", folder_link) if folder_id and not folder_renamed: requests.put( f"https://api.gofile.io/contents/{folder_id}/update", json={"attribute": "name", "attributeValue": source_path.name}, headers={"Authorization": f"Bearer {GOFILE_API_TOKEN}"}, timeout=60, ).raise_for_status() folder_renamed = True uploaded_bytes += file_path.stat().st_size progress = int((uploaded_bytes / total_bytes) * 100) if total_bytes else 100 update_task_entry( torrent_hash, gofile_progress=progress, gofile_status=f"Uploading raw folder to GoFile... {index}/{total_files}", status_message=f"Uploading raw folder to GoFile... {index}/{total_files}", ) if not folder_link: raise ValueError("GoFile tidak mengembalikan link folder.") return folder_link, folder_id def upload_folder_raw_pixeldrain(torrent_hash: str, source_path: Path) -> str: file_entries = list_folder_files(source_path) if not file_entries: raise ValueError("Folder tidak berisi file yang bisa diupload.") total_files = len(file_entries) total_bytes = sum(file_path.stat().st_size for file_path, _ in file_entries) uploaded_bytes = 0 uploaded_files: list[dict[str, str]] = [] for index, (file_path, relative_path) in enumerate(file_entries, start=1): current_state = load_monitor_state() current_entry = get_task_state_entry(current_state, torrent_hash) if current_entry.get("gofile_cancel_requested"): raise GofileUploadCancelled("Upload PixelDrain dibatalkan.") progress = int((uploaded_bytes / total_bytes) * 100) if total_bytes else 0 update_task_entry( torrent_hash, gofile_progress=progress, gofile_speed="", gofile_eta_seconds=0, gofile_status=f"Uploading raw folder to PixelDrain... {index}/{total_files}", status_message=f"Uploading raw folder to PixelDrain... {index}/{total_files}", ) with file_path.open("rb") as handle: encoded_name = quote(relative_path.name, safe="") response = requests.put( f"{PIXELDRAIN_API_URL}/file/{encoded_name}", data=handle, auth=("", PIXELDRAIN_API_KEY), timeout=3600, ) response.raise_for_status() payload = response.json() file_id = payload.get("id") if not file_id: raise ValueError("Respons PixelDrain tidak mengandung file id.") uploaded_files.append({"id": file_id, "description": relative_path.as_posix()}) uploaded_bytes += file_path.stat().st_size progress = int((uploaded_bytes / total_bytes) * 100) if total_bytes else 100 update_task_entry( torrent_hash, gofile_progress=progress, gofile_status=f"Uploading raw folder to PixelDrain... {index}/{total_files}", status_message=f"Uploading raw folder to PixelDrain... {index}/{total_files}", ) response = requests.post( f"{PIXELDRAIN_API_URL}/list", json={"title": source_path.name, "anonymous": False, "files": uploaded_files}, auth=("", PIXELDRAIN_API_KEY), timeout=60, ) response.raise_for_status() payload = response.json() list_id = payload.get("id") if not list_id: raise ValueError("Respons PixelDrain tidak mengandung list id.") return f"https://pixeldrain.com/l/{list_id}" def clear_gofile_runtime_fields(entry: dict) -> None: entry["gofile_uploading"] = False entry["gofile_progress"] = 0 entry["gofile_speed"] = "" entry["gofile_eta_seconds"] = 0 entry["gofile_cancel_requested"] = False entry["gofile_pid"] = 0 entry["gofile_endpoint"] = "" entry["gofile_provider"] = "" def clear_pre_upload_restore_fields(entry: dict) -> None: entry.pop("pre_upload_state", None) entry.pop("pre_upload_force_start", None) def restore_torrent_state_after_remote_upload(torrent_hash: str) -> None: if is_aria2_task(torrent_hash): update_state(lambda current: clear_pre_upload_restore_fields(get_task_state_entry(current, torrent_hash))) return state = load_monitor_state() entry = get_task_state_entry(state, torrent_hash) previous_state = str(entry.get("pre_upload_state", "") or "") previous_force_start = bool(entry.get("pre_upload_force_start", False)) if not previous_state and "pre_upload_force_start" not in entry: return try: client = get_client() torrents = client.torrents_info(torrent_hashes=torrent_hash) if not torrents: return torrent = torrents[0] progress = float(getattr(torrent, "progress", 0) or 0) seeding_states = {"uploading", "stalledUP", "forcedUP", "checkingUP"} if previous_state in PAUSED_STATES: try: client.torrents_set_force_start(enable=False, torrent_hashes=torrent_hash) except qbittorrentapi.APIError: pass client.torrents_pause(torrent_hashes=torrent_hash) else: client.torrents_resume(torrent_hashes=torrent_hash) if previous_force_start or previous_state in {"forcedDL", "forcedUP"}: try: client.torrents_set_force_start(enable=True, torrent_hashes=torrent_hash) except qbittorrentapi.APIError: pass elif progress >= 1 and previous_state in seeding_states: try: client.torrents_reannounce(torrent_hashes=torrent_hash) except qbittorrentapi.APIError: pass refreshed = client.torrents_info(torrent_hashes=torrent_hash) current_state = getattr(refreshed[0], "state", "") if refreshed else "" if current_state == "queuedUP": try: client.torrents_set_force_start(enable=True, torrent_hashes=torrent_hash) except qbittorrentapi.APIError: pass except qbittorrentapi.APIError: pass finally: update_state(lambda current: clear_pre_upload_restore_fields(get_task_state_entry(current, torrent_hash))) def evaluate_torrent_health(client, torrents: list, state: dict) -> bool: now = time.time() torrent_state = state.setdefault("torrents", {}) active_hashes = {torrent.hash for torrent in torrents} changed = False for hash_value in list(torrent_state.keys()): if hash_value not in active_hashes: entry = torrent_state[hash_value] if entry.get("gofile_uploading"): continue del torrent_state[hash_value] changed = True for torrent in torrents: entry = torrent_state.setdefault( torrent.hash, { "name": torrent.name, "last_progress": float(getattr(torrent, "progress", 0) or 0), "last_downloaded": int(getattr(torrent, "downloaded", 0) or 0), "last_progress_at": now, "status_message": "", "gofile_progress": 0, "gofile_uploading": False, "gofile_speed": "", "gofile_status": "", "gofile_link": "", "gofile_pid": 0, "gofile_endpoint": "", "gofile_provider": "", }, ) entry["name"] = torrent.name current_progress = float(getattr(torrent, "progress", 0) or 0) current_downloaded = int(getattr(torrent, "downloaded", 0) or 0) current_speed = int(getattr(torrent, "dlspeed", 0) or 0) previous_progress = float(entry.get("last_progress", 0)) previous_downloaded = int(entry.get("last_downloaded", 0)) if current_downloaded > previous_downloaded or current_progress > previous_progress or current_speed > 0: entry["last_progress"] = current_progress entry["last_downloaded"] = current_downloaded entry["last_progress_at"] = now if entry.get("status_message") and not entry.get("gofile_uploading"): entry["status_message"] = "" changed = True idle_for = now - float(entry.get("last_progress_at", now)) status_message = entry.get("status_message", "") if entry.get("gofile_uploading"): status_message = "" elif torrent.state in FAILED_STATES: status_message = "Torrent gagal diproses. Cek file torrent atau sumber tracker." elif torrent.state in PAUSED_STATES: status_message = "" elif torrent.state in ACTIVE_DOWNLOAD_STATES and current_speed == 0: if idle_for >= STUCK_TIMEOUT_SECONDS: if torrent.num_seeds <= 0: reason = f"{torrent.name} dibatalkan otomatis karena tidak ada seed selama {format_duration(idle_for)}." else: reason = f"{torrent.name} dibatalkan otomatis karena tidak ada progres selama {format_duration(idle_for)}." client.torrents_delete(delete_files=False, torrent_hashes=torrent.hash) add_event(state, "error", reason) torrent_state.pop(torrent.hash, None) changed = True continue remaining = max(0, STUCK_TIMEOUT_SECONDS - int(idle_for)) if torrent.num_seeds <= 0 and torrent.num_leechs <= 0: status_message = f"Seed dan peer tidak ada. Auto cancel dalam {format_duration(remaining)}." elif torrent.num_seeds <= 0: status_message = f"Seed tidak tersedia. Menunggu sampai {format_duration(remaining)} sebelum auto cancel." else: status_message = f"Torrent belum bergerak selama {format_duration(idle_for)}. Auto cancel dalam {format_duration(remaining)}." elif float(getattr(torrent, "progress", 0) or 0) >= 1: status_message = "" if entry.get("status_message") != status_message: entry["status_message"] = status_message changed = True if entry.get("last_progress") != current_progress or entry.get("last_downloaded") != current_downloaded: entry["last_progress"] = current_progress entry["last_downloaded"] = current_downloaded changed = True return changed def fetch_location_info(state: dict) -> dict: cached = state.setdefault("system", {}).get("location", {}) now = int(time.time()) if cached and now - int(cached.get("fetched_at", 0)) < LOCATION_CACHE_SECONDS: return cached try: response = requests.get(IP_LOCATION_API_URL, timeout=10) response.raise_for_status() data = response.json() location = { "ip": data.get("ip", "-"), "city": data.get("city", "-"), "region": data.get("region", "-"), "country": data.get("country_name", data.get("country", "-")), "org": data.get("org", "-"), "timezone": data.get("timezone", "-"), "fetched_at": now, } except requests.RequestException: location = { "ip": "-", "city": "-", "region": "-", "country": "-", "org": "unavailable", "timezone": "-", "fetched_at": now, } state.setdefault("system", {})["location"] = location return location def get_system_info() -> dict: state = load_monitor_state() cached = state.setdefault("system", {}).get("snapshot", {}) now = int(time.time()) if cached and now - int(cached.get("fetched_at", 0)) < SYSTEM_INFO_CACHE_SECONDS: snapshot = cached else: disk = download_storage_usage() memory = psutil.virtual_memory() snapshot = { "os": f"{platform.system()} {platform.release()}", "cpu": platform.processor() or platform.machine() or "Unknown CPU", "cpu_cores": psutil.cpu_count(logical=True) or 0, "cpu_usage": f"{psutil.cpu_percent(interval=0.2):.0f}%", "ram_total": format_size(memory.total), "ram_used": format_size(memory.used), "ram_percent": f"{memory.percent:.0f}%", "storage_total": format_size(disk.total), "storage_used": format_size(disk.used), "storage_free": format_size(disk.free), "storage_percent": f"{(disk.used / disk.total) * 100:.0f}%" if disk.total else "0%", "hostname": platform.node() or "-", "fetched_at": now, } state.setdefault("system", {})["snapshot"] = snapshot save_monitor_state(state) location = fetch_location_info(state) save_monitor_state(state) speedtest = state.get("speedtest", {"running": False}) return { **snapshot, "location": location, "speedtest": speedtest, } def run_speedtest_background() -> None: def set_speedtest_state(**fields): def mutator(state: dict): speedtest = state.setdefault("speedtest", {}) speedtest.update(fields) update_state(mutator) try: set_speedtest_state(running=True, status="Running speedtest...", result={}) ping_samples = [] for _ in range(3): start = time.perf_counter() response = requests.get(CLOUDFLARE_DOWNLOAD_URL, params={"bytes": 0}, timeout=15) response.raise_for_status() ping_samples.append((time.perf_counter() - start) * 1000) download_bytes = 25_000_000 start = time.perf_counter() response = requests.get(CLOUDFLARE_DOWNLOAD_URL, params={"bytes": download_bytes}, timeout=120) response.raise_for_status() total_download = len(response.content) elapsed = max(time.perf_counter() - start, 0.001) download_bps = (total_download * 8) / elapsed payload = os.urandom(10_000_000) start = time.perf_counter() response = requests.post(CLOUDFLARE_UPLOAD_URL, data=payload, timeout=120) response.raise_for_status() elapsed = max(time.perf_counter() - start, 0.001) upload_bps = (len(payload) * 8) / elapsed result = { "download": format_mbps(download_bps), "upload": format_mbps(upload_bps), "ping": f"{sum(ping_samples) / len(ping_samples):.0f} ms", "tested_at": int(time.time()), } set_speedtest_state(running=False, status="Speedtest selesai.", result=result) except requests.RequestException as exc: set_speedtest_state(running=False, status=f"Speedtest gagal: {exc}", result={}) def get_dashboard_data() -> tuple[list[dict], dict]: client = get_client() state = load_monitor_state() raw_torrents = list(client.torrents_info(sort="added_on", reverse=True)) state_changed = evaluate_torrent_health(client, raw_torrents, state) if state_changed: save_monitor_state(state) raw_torrents = list(client.torrents_info(sort="added_on", reverse=True)) version = client.app.version 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["rclone_config_error"] = validate_rclone_config().get("error", "") item["can_raw_rclone_upload"] = False aria2_items.append(item) torrents = sorted(torrent_items + aria2_items, key=lambda item: int(item.get("added_at", 0) or 0), reverse=True) seeding_states = {"uploading", "stalledUP", "forcedUP", "pausedUP", "queuedUP", "checkingUP"} aria2_active_count = sum(1 for item in state.get("aria2", {}).values() if item.get("state") == "downloading") aria2_downloaded_bytes = sum(int(item.get("downloaded_bytes", 0) or 0) for item in state.get("aria2", {}).values()) stats = { "connected": True, "download_path": DOWNLOAD_PATH, "version": version, "torrent_count": len(torrents), "downloading": sum(1 for item in raw_torrents if item.state in ACTIVE_DOWNLOAD_STATES) + aria2_active_count, "total_seeds": sum(1 for item in raw_torrents if getattr(item, "state", "") in seeding_states), "total_leechs": sum(1 for item in raw_torrents if getattr(item, "state", "") in ACTIVE_DOWNLOAD_STATES) + aria2_active_count, "all_time_download": format_size(sum(int(getattr(item, "downloaded", 0) or 0) for item in raw_torrents) + aria2_downloaded_bytes), "all_time_upload": format_size(sum(int(getattr(item, "uploaded", 0) or 0) for item in raw_torrents)), } system_info = get_system_info() return torrents, { "stats": stats, "events": [serialize_event(event) for event in state.get("events", [])], "system_info": system_info, } def action_response(message: str, ok: bool = True, status_code: int = 200, **extra): payload = {"success": ok, "message": message} payload.update(extra) return jsonify(payload), status_code def torrent_selection_response(payload: dict): message = payload.get("message", "Torrent membutuhkan seleksi file.") extra = {key: value for key, value in payload.items() if key != "message"} return action_response(message, **extra) def wants_json_response() -> bool: accept = request.headers.get("Accept", "") requested_with = request.headers.get("X-Requested-With", "") return "application/json" in accept or requested_with == "XMLHttpRequest" def parse_curl_progress_line(line: str, total_bytes: int) -> dict | None: stripped = line.strip() if not stripped or "%" in stripped or "Total" in stripped: return None parts = stripped.split() if len(parts) < 2: return None try: progress_percent_value = int(parts[0]) except ValueError: return None current_speed = parse_size_token(parts[-1]) or 0 uploaded_bytes = int((total_bytes * progress_percent_value) / 100) if total_bytes > 0 else 0 remaining_bytes = max(0, total_bytes - uploaded_bytes) eta_seconds = int(remaining_bytes / current_speed) if current_speed > 0 else 0 return { "progress": max(0, min(progress_percent_value, 100)), "speed": current_speed, "eta_seconds": eta_seconds, } def parse_7z_progress_line(line: str) -> int | None: match = re.search(r"(\d{1,3})%", line) if not match: return None return max(0, min(int(match.group(1)), 100)) def parse_rclone_progress_line(line: str, total_bytes: int) -> dict | None: stripped = line.strip() if not stripped: return None progress_match = re.search(r"\b(\d{1,3})%", stripped) if not progress_match: return None speed = 0 speed_match = re.search(r"([\d.]+)\s*([KMGTPE]?i?B|Bytes)/s", stripped, re.IGNORECASE) if speed_match: value = float(speed_match.group(1)) unit = speed_match.group(2).lower() multipliers = { "b": 1, "bytes": 1, "kb": 1000, "kib": 1024, "mb": 1000**2, "mib": 1024**2, "gb": 1000**3, "gib": 1024**3, "tb": 1000**4, "tib": 1024**4, } speed = int(value * multipliers.get(unit, 1)) progress = max(0, min(int(progress_match.group(1)), 100)) uploaded_bytes = int((total_bytes * progress) / 100) if total_bytes > 0 else 0 remaining_bytes = max(0, total_bytes - uploaded_bytes) eta_seconds = int(remaining_bytes / speed) if speed > 0 else 0 return {"progress": progress, "speed": speed, "eta_seconds": eta_seconds} def monitor_rclone_progress(output_pipe, torrent_hash: str, total_bytes: int, remote_label: str, error_lines: list[str]) -> None: last_progress = -1 try: for line in output_pipe: progress = parse_rclone_progress_line(line, total_bytes) if progress: if progress["progress"] != last_progress: last_progress = progress["progress"] speed_text = format_speed(progress["speed"]) if progress["speed"] else "" update_state( lambda state: get_task_state_entry(state, torrent_hash).update( { "gofile_progress": progress["progress"], "gofile_speed": speed_text, "gofile_eta_seconds": progress["eta_seconds"], "gofile_status": f"Sedang upload ke rclone remote {remote_label}...", "status_message": "", } ) ) continue stripped = line.strip() if stripped and not any(token in stripped.lower() for token in ["transferred:", "elapsed time:", "checks:"]): error_lines.append(stripped) finally: try: output_pipe.close() except OSError: pass def monitor_7z_progress(stdout_pipe, torrent_hash: str, provider_name: str, error_lines: list[str]) -> None: buffer = "" last_progress = -1 try: while True: chunk = stdout_pipe.read(1) if chunk == "": break buffer += chunk progress = parse_7z_progress_line(buffer) if progress is not None and progress != last_progress: last_progress = progress update_state( lambda state: get_task_state_entry(state, torrent_hash).update( { "gofile_provider": "Archiving", "gofile_progress": progress, "gofile_speed": "", "gofile_eta_seconds": 0, "gofile_status": f"Archiving folder for {provider_name}... {progress}%", "status_message": f"Archiving folder for {provider_name}... {progress}%", } ) ) if chunk in {"\r", "\n"}: if buffer.strip() and parse_7z_progress_line(buffer) is None: error_lines.append(buffer.strip()) buffer = "" continue if len(buffer) > 256: # Keep only the latest tail so progress repaints from 7z remain parseable. buffer = buffer[-256:] finally: if buffer.strip() and parse_7z_progress_line(buffer) is None: error_lines.append(buffer.strip()) try: stdout_pipe.close() except OSError: pass def monitor_curl_progress(stderr_pipe, torrent_hash: str, total_bytes: int, upload_label: str, error_lines: list[str]) -> None: buffer = "" try: while True: chunk = stderr_pipe.read(1) if chunk == "": break if chunk in {"\r", "\n"}: progress = parse_curl_progress_line(buffer, total_bytes) if progress: speed_text = format_speed(progress["speed"]) update_state( lambda state: get_task_state_entry(state, torrent_hash).update( { "gofile_progress": progress["progress"], "gofile_speed": speed_text, "gofile_eta_seconds": progress["eta_seconds"], "gofile_status": f"Sedang upload ke {state.setdefault('torrents', {}).setdefault(torrent_hash, {}).get('gofile_provider', 'GoFile')} via {upload_label}...", "status_message": "", } ) ) elif buffer.strip(): error_lines.append(buffer.strip()) buffer = "" continue buffer += chunk finally: if buffer.strip(): error_lines.append(buffer.strip()) try: stderr_pipe.close() except OSError: pass def gofile_upload_attempt( upload_url: str, torrent_hash: str, file_path: Path, started_at: float, ) -> dict: response_path = UPLOAD_DIR / f"gofile-{torrent_hash}.json" command = [ "curl", "--show-error", "--location", "--globoff", "--ipv4", "--retry", "2", "--retry-delay", "2", "--retry-all-errors", "--connect-timeout", "15", "--speed-time", "60", "--speed-limit", "10240", "--max-time", "0", "--output", str(response_path), "--write-out", "%{http_code}", ] if GOFILE_API_TOKEN: command.extend(["-H", f"Authorization: Bearer {GOFILE_API_TOKEN}"]) command.extend(["-F", f'file=@"{file_path}"', upload_url]) process = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1, ) total_bytes = file_path.stat().st_size upload_label = gofile_endpoint_label(upload_url) error_lines: list[str] = [] monitor_thread = threading.Thread( target=monitor_curl_progress, args=(process.stderr, torrent_hash, total_bytes, upload_label, error_lines), daemon=True, ) monitor_thread.start() update_state( lambda state: get_task_state_entry(state, torrent_hash).update( { "gofile_uploading": True, "gofile_pid": process.pid, "gofile_endpoint": upload_label, "gofile_provider": "GoFile", "gofile_status": f"Sedang upload ke GoFile via {upload_label}...", "status_message": "", } ) ) while True: return_code = process.poll() current_state = load_monitor_state() current_entry = get_task_state_entry(current_state, torrent_hash) if current_entry.get("gofile_cancel_requested"): cancel_upload_process(process.pid) if return_code is not None: break elapsed = max(int(time.time() - started_at), 1) update_state( lambda state: get_task_state_entry(state, torrent_hash).update( { "gofile_uploading": True, "gofile_pid": process.pid, "gofile_endpoint": upload_label, "gofile_provider": "GoFile", "gofile_status": f"Sedang upload ke GoFile via {upload_label}...", "status_message": "", } ) ) time.sleep(1) stdout = process.stdout.read() if process.stdout else "" monitor_thread.join(timeout=1) if current_entry.get("gofile_cancel_requested") or process.returncode == -15: raise GofileUploadCancelled("Upload GoFile dibatalkan.") if process.returncode != 0: error_detail = " | ".join(error_lines[-3:]).strip() or stdout.strip() or f"curl exited with code {process.returncode}" raise ValueError(error_detail) http_code = int((stdout or "0").strip() or "0") if http_code >= 400 or http_code == 0: error_body = response_path.read_text(encoding="utf-8", errors="replace") if response_path.exists() else "" raise ValueError(f"HTTP {http_code}: {error_body[:500]}".strip()) payload = json.loads(response_path.read_text(encoding="utf-8")) return payload def pixeldrain_upload_attempt(torrent_hash: str, file_path: Path, started_at: float) -> dict: response_path = UPLOAD_DIR / f"pixeldrain-{torrent_hash}.json" encoded_name = quote(file_path.name, safe="") upload_url = f"{PIXELDRAIN_API_URL}/file/{encoded_name}" command = [ "curl", "--show-error", "--location", "--globoff", "--ipv4", "--retry", "2", "--retry-delay", "2", "--retry-all-errors", "--connect-timeout", "15", "--speed-time", "60", "--speed-limit", "10240", "--max-time", "0", "--url", upload_url, "--upload-file", str(file_path), "--user", f":{PIXELDRAIN_API_KEY}", "--output", str(response_path), "--write-out", "%{http_code}", ] process = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1, ) total_bytes = file_path.stat().st_size upload_label = "pixeldrain" error_lines: list[str] = [] monitor_thread = threading.Thread( target=monitor_curl_progress, args=(process.stderr, torrent_hash, total_bytes, upload_label, error_lines), daemon=True, ) monitor_thread.start() update_state( lambda state: get_task_state_entry(state, torrent_hash).update( { "gofile_uploading": True, "gofile_pid": process.pid, "gofile_endpoint": upload_label, "gofile_provider": "PixelDrain", "gofile_status": "Sedang upload ke PixelDrain...", "status_message": "", } ) ) while True: return_code = process.poll() current_state = load_monitor_state() current_entry = get_task_state_entry(current_state, torrent_hash) if current_entry.get("gofile_cancel_requested"): cancel_upload_process(process.pid) if return_code is not None: break update_state( lambda state: get_task_state_entry(state, torrent_hash).update( { "gofile_uploading": True, "gofile_pid": process.pid, "gofile_endpoint": upload_label, "gofile_provider": "PixelDrain", "gofile_status": "Sedang upload ke PixelDrain...", "status_message": "", } ) ) time.sleep(1) stdout = process.stdout.read() if process.stdout else "" monitor_thread.join(timeout=1) if current_entry.get("gofile_cancel_requested") or process.returncode == -15: raise GofileUploadCancelled("Upload PixelDrain dibatalkan.") if process.returncode != 0: error_detail = " | ".join(error_lines[-3:]).strip() or stdout.strip() or f"curl exited with code {process.returncode}" raise ValueError(error_detail) http_code = int((stdout or "0").strip() or "0") if http_code >= 400 or http_code == 0: error_body = response_path.read_text(encoding="utf-8", errors="replace") if response_path.exists() else "" raise ValueError(f"HTTP {http_code}: {error_body[:500]}".strip()) payload = json.loads(response_path.read_text(encoding="utf-8")) return payload def rclone_link(config_path: Path, destination_spec: str) -> str: process = subprocess.run( ["rclone", "--config", str(config_path), "link", destination_spec], capture_output=True, text=True, timeout=60, check=False, ) if process.returncode != 0: return "" for line in process.stdout.splitlines(): candidate = line.strip() if candidate.startswith(("http://", "https://")): return candidate return "" def rclone_upload_attempt( torrent_hash: str, source_path: Path, destination_spec: str, config_path: Path, remote_label: str, ) -> str: command = [ "rclone", "--config", str(config_path), "--stats", "1s", "--stats-one-line", "--progress", ] if source_path.is_dir(): command.extend(["copy", str(source_path), destination_spec]) else: command.extend(["copyto", str(source_path), destination_spec]) process = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, ) total_bytes = path_total_size(source_path) error_lines: list[str] = [] monitor_thread = threading.Thread( target=monitor_rclone_progress, args=(process.stdout, torrent_hash, total_bytes, remote_label, error_lines), daemon=True, ) monitor_thread.start() update_state( lambda state: get_task_state_entry(state, torrent_hash).update( { "gofile_uploading": True, "gofile_pid": process.pid, "gofile_endpoint": remote_label, "gofile_provider": "rclone", "gofile_status": f"Sedang upload ke rclone remote {remote_label}...", "status_message": "", } ) ) while True: return_code = process.poll() current_state = load_monitor_state() current_entry = get_task_state_entry(current_state, torrent_hash) if current_entry.get("gofile_cancel_requested"): cancel_upload_process(process.pid) if return_code is not None: break update_state( lambda state: get_task_state_entry(state, torrent_hash).update( { "gofile_uploading": True, "gofile_pid": process.pid, "gofile_endpoint": remote_label, "gofile_provider": "rclone", "gofile_status": f"Sedang upload ke rclone remote {remote_label}...", "status_message": "", } ) ) time.sleep(1) monitor_thread.join(timeout=1) if current_entry.get("gofile_cancel_requested") or process.returncode == -15: raise GofileUploadCancelled("Upload rclone dibatalkan.") if process.returncode != 0: error_detail = " | ".join(error_lines[-4:]).strip() or f"rclone exited with code {process.returncode}" raise ValueError(error_detail) update_task_entry(torrent_hash, gofile_progress=100, gofile_speed="", gofile_eta_seconds=0) return rclone_link(config_path, destination_spec) def start_gofile_upload_background(torrent_hash: str, torrent_name: str, file_path: Path, mode: str = "zip") -> None: def worker(): upload_path = file_path cleanup_upload_path = False try: if file_path.is_dir() and mode == "raw": folder_link, _folder_id = upload_folder_raw_gofile(torrent_hash, file_path) def success_raw_mutator(state: dict): entry = get_task_state_entry(state, torrent_hash) clear_gofile_runtime_fields(entry) entry["gofile_link"] = folder_link entry["gofile_provider"] = "GoFile" entry["gofile_status"] = f"Upload raw folder GoFile berhasil: {folder_link}" entry["status_message"] = "" update_state(success_raw_mutator) restore_torrent_state_after_remote_upload(torrent_hash) return upload_path, cleanup_upload_path = prepare_upload_source(file_path, torrent_hash, "GoFile") started_at = time.time() payload = None last_error = None for upload_url in ranked_gofile_upload_urls(): try: payload = gofile_upload_attempt(upload_url, torrent_hash, upload_path, started_at) break except GofileUploadCancelled: raise except ValueError as exc: last_error = f"{upload_url}: {exc}" update_state( lambda state: get_task_state_entry(state, torrent_hash).update( { "gofile_uploading": True, "gofile_provider": "GoFile", "gofile_status": f"Endpoint gagal, mencoba server lain: {upload_url}", "status_message": f"Endpoint gagal, mencoba server lain: {upload_url}", } ) ) if payload is None: raise ValueError(last_error or "Semua endpoint GoFile gagal.") data = payload.get("data", {}) download_page = data.get("downloadPage") if not download_page: raise ValueError("Respons GoFile tidak mengandung downloadPage.") def success_mutator(state: dict): entry = get_task_state_entry(state, torrent_hash) clear_gofile_runtime_fields(entry) entry["gofile_link"] = download_page entry["gofile_provider"] = "GoFile" entry["gofile_status"] = f"Upload GoFile berhasil: {download_page}" entry["status_message"] = "" update_state(success_mutator) restore_torrent_state_after_remote_upload(torrent_hash) except GofileUploadCancelled: def cancel_mutator(state: dict): entry = get_task_state_entry(state, torrent_hash) clear_gofile_runtime_fields(entry) entry["gofile_provider"] = "GoFile" entry["gofile_status"] = "Upload GoFile dibatalkan." entry["status_message"] = "" add_event(state, "warning", f"Upload GoFile dibatalkan untuk {torrent_name}.") update_state(cancel_mutator) restore_torrent_state_after_remote_upload(torrent_hash) except (ValueError, requests.RequestException) as exc: def error_mutator(state: dict): entry = get_task_state_entry(state, torrent_hash) clear_gofile_runtime_fields(entry) entry["gofile_provider"] = "GoFile" entry["gofile_status"] = f"Upload GoFile gagal: {exc}" entry["status_message"] = f"Upload GoFile gagal: {exc}" add_event(state, "error", f"Upload GoFile gagal untuk {torrent_name}: {exc}") update_state(error_mutator) restore_torrent_state_after_remote_upload(torrent_hash) finally: (UPLOAD_DIR / f"gofile-{torrent_hash}.json").unlink(missing_ok=True) if cleanup_upload_path: upload_path.unlink(missing_ok=True) thread = threading.Thread(target=worker, daemon=True) thread.start() def start_pixeldrain_upload_background(torrent_hash: str, torrent_name: str, file_path: Path, mode: str = "zip") -> None: def worker(): upload_path = file_path cleanup_upload_path = False try: if file_path.is_dir() and mode == "raw": download_page = upload_folder_raw_pixeldrain(torrent_hash, file_path) def success_raw_mutator(state: dict): entry = get_task_state_entry(state, torrent_hash) clear_gofile_runtime_fields(entry) entry["gofile_link"] = download_page entry["gofile_provider"] = "PixelDrain" entry["gofile_status"] = f"Upload raw folder PixelDrain berhasil: {download_page}" entry["status_message"] = "" update_state(success_raw_mutator) restore_torrent_state_after_remote_upload(torrent_hash) return upload_path, cleanup_upload_path = prepare_upload_source(file_path, torrent_hash, "PixelDrain") payload = pixeldrain_upload_attempt(torrent_hash, upload_path, time.time()) file_id = payload.get("id") if not file_id: raise ValueError("Respons PixelDrain tidak mengandung file id.") download_page = f"https://pixeldrain.com/u/{file_id}" def success_mutator(state: dict): entry = get_task_state_entry(state, torrent_hash) clear_gofile_runtime_fields(entry) entry["gofile_link"] = download_page entry["gofile_provider"] = "PixelDrain" entry["gofile_status"] = f"Upload PixelDrain berhasil: {download_page}" entry["status_message"] = "" update_state(success_mutator) restore_torrent_state_after_remote_upload(torrent_hash) except GofileUploadCancelled: def cancel_mutator(state: dict): entry = get_task_state_entry(state, torrent_hash) clear_gofile_runtime_fields(entry) entry["gofile_provider"] = "PixelDrain" entry["gofile_status"] = "Upload PixelDrain dibatalkan." entry["status_message"] = "" add_event(state, "warning", f"Upload PixelDrain dibatalkan untuk {torrent_name}.") update_state(cancel_mutator) restore_torrent_state_after_remote_upload(torrent_hash) except (ValueError, requests.RequestException) as exc: def error_mutator(state: dict): entry = get_task_state_entry(state, torrent_hash) clear_gofile_runtime_fields(entry) entry["gofile_provider"] = "PixelDrain" entry["gofile_status"] = f"Upload PixelDrain gagal: {exc}" entry["status_message"] = f"Upload PixelDrain gagal: {exc}" add_event(state, "error", f"Upload PixelDrain gagal untuk {torrent_name}: {exc}") update_state(error_mutator) restore_torrent_state_after_remote_upload(torrent_hash) finally: (UPLOAD_DIR / f"pixeldrain-{torrent_hash}.json").unlink(missing_ok=True) if cleanup_upload_path: upload_path.unlink(missing_ok=True) thread = threading.Thread(target=worker, daemon=True) thread.start() def start_rclone_upload_background( torrent_hash: str, torrent_name: str, file_path: Path, mode: str = "zip", remote_name: str = "", ) -> None: def worker(): upload_path = file_path cleanup_upload_path = False destination_spec = "" try: config = validate_rclone_config(force_refresh=True) if config.get("error") or not config.get("remotes"): raise ValueError(str(config.get("error") or "rclone.conf tidak berisi remote aktif.")) config_path = Path(str(config["path"])) remote = requested_rclone_remote(config, remote_name) remote_label = remote or "rclone" if file_path.is_dir() and mode == "raw": destination_spec = rclone_destination_spec(remote, safe_filename(torrent_name or file_path.name)) download_link = rclone_upload_attempt(torrent_hash, file_path, destination_spec, config_path, remote_label) else: upload_path, cleanup_upload_path = prepare_upload_source(file_path, torrent_hash, "rclone") destination_spec = rclone_destination_spec(remote, upload_path.name) download_link = rclone_upload_attempt(torrent_hash, upload_path, destination_spec, config_path, remote_label) def success_mutator(state: dict): entry = get_task_state_entry(state, torrent_hash) clear_gofile_runtime_fields(entry) entry["gofile_link"] = download_link entry["gofile_provider"] = "rclone" if download_link: entry["gofile_status"] = f"Upload rclone berhasil: {download_link}" else: entry["gofile_status"] = f"Upload rclone berhasil ke {destination_spec}. Public link tidak tersedia dari remote ini." entry["status_message"] = "" update_state(success_mutator) restore_torrent_state_after_remote_upload(torrent_hash) except GofileUploadCancelled: def cancel_mutator(state: dict): entry = get_task_state_entry(state, torrent_hash) clear_gofile_runtime_fields(entry) entry["gofile_provider"] = "rclone" entry["gofile_status"] = "Upload rclone dibatalkan." entry["status_message"] = "" add_event(state, "warning", f"Upload rclone dibatalkan untuk {torrent_name}.") update_state(cancel_mutator) restore_torrent_state_after_remote_upload(torrent_hash) except (ValueError, requests.RequestException, OSError) as exc: def error_mutator(state: dict): entry = get_task_state_entry(state, torrent_hash) clear_gofile_runtime_fields(entry) entry["gofile_provider"] = "rclone" entry["gofile_status"] = f"Upload rclone gagal: {exc}" entry["status_message"] = f"Upload rclone gagal: {exc}" add_event(state, "error", f"Upload rclone gagal untuk {torrent_name}: {exc}") update_state(error_mutator) restore_torrent_state_after_remote_upload(torrent_hash) finally: if cleanup_upload_path: upload_path.unlink(missing_ok=True) thread = threading.Thread(target=worker, daemon=True) thread.start() @app.route("/", methods=["GET"]) def index(): try: torrents, payload = get_dashboard_data() stats = payload["stats"] events = payload["events"] system_info = payload["system_info"] except qbittorrentapi.APIConnectionError as exc: torrents = [] events = [] stats = { "connected": False, "download_path": "-", "version": "unreachable", "torrent_count": 0, "downloading": 0, } system_info = get_system_info() flash(f"Gagal terhubung ke qBittorrent: {exc}", "error") except qbittorrentapi.LoginFailed as exc: torrents = [] events = [] stats = { "connected": False, "download_path": "-", "version": "login failed", "torrent_count": 0, "downloading": 0, } system_info = get_system_info() flash(f"Login qBittorrent gagal: {exc}", "error") return render_template("index.html", torrents=torrents, stats=stats, events=events, system_info=system_info) @app.route("/healthz", methods=["GET"]) def healthz(): return jsonify({"status": "ok"}) @app.route("/api/torrents", methods=["GET"]) def torrents_api(): try: torrents, payload = get_dashboard_data() return jsonify( { "success": True, "stats": payload["stats"], "events": payload["events"], "torrents": torrents, } ) except (qbittorrentapi.APIConnectionError, qbittorrentapi.LoginFailed, qbittorrentapi.APIError) as exc: return jsonify({"success": False, "error": str(exc) or "Gagal mengambil data torrent."}), 503 @app.route("/api/torrents/<torrent_hash>/files", methods=["GET"]) def torrent_files_api(torrent_hash: str): try: files = qbt_torrent_files(torrent_hash) if not files: return jsonify( { "success": True, "metadata_ready": False, "selection_required": False, "selection_pending": True, "torrent_hash": torrent_hash, "files": [], "message": "Metadata torrent masih diambil. Menunggu daftar file...", } ) payload = build_file_selection_payload(torrent_hash, files) clear_torrent_status_message(torrent_hash) payload["success"] = True payload["metadata_ready"] = True return jsonify(payload) except InsufficientStorageError as exc: return action_response(str(exc), ok=False, status_code=507) except (QBittorrentWebAPIError, requests.RequestException, ValueError) as exc: return action_response(f"Gagal mengambil daftar file torrent: {exc}", ok=False, status_code=502) @app.route("/api/torrents/<torrent_hash>/files/selection", methods=["POST"]) def apply_torrent_file_selection(torrent_hash: str): try: files = qbt_torrent_files(torrent_hash) if not files: return action_response("Metadata torrent belum siap. Coba lagi sebentar.", ok=False, status_code=409) if len(files) <= 1: required_bytes = sum(int(file_entry.get("size", 0) or 0) for file_entry in files) ensure_storage_available(required_bytes) qbt_resume_torrent(torrent_hash) clear_torrent_status_message(torrent_hash) return action_response("Torrent tidak memerlukan seleksi file.") payload = request.get_json(silent=True) or {} raw_selected_ids = payload.get("selected_file_ids", []) if not isinstance(raw_selected_ids, list): return action_response("Format pilihan file tidak valid.", ok=False, status_code=400) selected_ids = {int(file_id) for file_id in raw_selected_ids} all_ids = {torrent_file_index(file_entry, index) for index, file_entry in enumerate(files)} if not selected_ids: return action_response("Pilih minimal satu file untuk didownload.", ok=False, status_code=400) if not selected_ids.issubset(all_ids): return action_response("Pilihan file mengandung ID yang tidak valid.", ok=False, status_code=400) selected_size = sum( int(file_entry.get("size", 0) or 0) for index, file_entry in enumerate(files) if torrent_file_index(file_entry, index) in selected_ids ) ensure_storage_available(selected_size) skipped_ids = sorted(all_ids - selected_ids) qbt_set_file_priority(torrent_hash, sorted(skipped_ids), 0) qbt_set_file_priority(torrent_hash, sorted(selected_ids), 1) qbt_resume_torrent(torrent_hash) clear_torrent_status_message(torrent_hash) return action_response("Seleksi file diterapkan dan torrent dimulai.") except InsufficientStorageError as exc: return action_response(str(exc), ok=False, status_code=507) except (QBittorrentWebAPIError, requests.RequestException, ValueError) as exc: return action_response(f"Gagal menerapkan seleksi file: {exc}", ok=False, status_code=502) @app.route("/api/system", methods=["GET"]) def system_api(): return jsonify({"success": True, "system": get_system_info()}) @app.route("/api/system/speedtest", methods=["POST"]) def system_speedtest(): state = load_monitor_state() if state.get("speedtest", {}).get("running"): return action_response("Speedtest sedang berjalan.", ok=False, status_code=409) update_state(lambda current: current.setdefault("speedtest", {}).update({"running": True, "status": "Memulai speedtest...", "result": {}})) threading.Thread(target=run_speedtest_background, daemon=True).start() return action_response("Speedtest dimulai.") @app.route("/api/rclone/config", methods=["GET", "POST"]) def rclone_config_api(): if request.method == "GET": return action_response("Status rclone config.", rclone=rclone_config_summary(force_refresh=True)) payload = request.get_json(silent=True) or {} raw_url = str(payload.get("config_url", "") or "").strip() if not raw_url: return action_response("Raw URL rclone.conf wajib diisi.", ok=False, status_code=400) parsed = urlparse(raw_url) if parsed.scheme.lower() not in {"http", "https"}: return action_response("Raw URL harus memakai http atau https.", ok=False, status_code=400) set_runtime_rclone_config_url(raw_url) summary = rclone_config_summary(force_refresh=True) if not summary["available"]: return action_response(f"rclone.conf belum valid: {summary['error']}", ok=False, status_code=400, rclone=summary) return action_response( f"rclone.conf valid. Remote terdeteksi: {', '.join(summary['remotes'])}", rclone=summary, ) @app.route("/api/torrents/<torrent_hash>/pause", methods=["POST"]) def pause_torrent(torrent_hash: str): if is_aria2_task(torrent_hash): ok, message = aria2.pause_task(torrent_hash, STATE_FILE, STATE_LOCK) return action_response(message, ok=ok, status_code=200 if ok else 400) try: client = get_client() try: client.torrents_set_force_start(enable=False, torrent_hashes=torrent_hash) except qbittorrentapi.APIError: pass qbt_pause_torrent(torrent_hash) state = load_monitor_state() entry = state.setdefault("torrents", {}).setdefault(torrent_hash, {}) entry["status_message"] = "" save_monitor_state(state) return action_response("Torrent dijeda.") except qbittorrentapi.APIError as exc: return action_response(f"Gagal pause torrent: {exc}", ok=False, status_code=400) @app.route("/api/torrents/<torrent_hash>/resume", methods=["POST"]) def resume_torrent(torrent_hash: str): if is_aria2_task(torrent_hash): ok, message = aria2.resume_task(torrent_hash, STATE_FILE, STATE_LOCK) return action_response(message, ok=ok, status_code=200 if ok else 400) try: client = get_client() qbt_resume_torrent(torrent_hash) torrents = client.torrents_info(torrent_hashes=torrent_hash) if torrents and float(getattr(torrents[0], "progress", 0) or 0) >= 1: try: client.torrents_set_force_start(enable=True, torrent_hashes=torrent_hash) except qbittorrentapi.APIError: pass try: client.torrents_reannounce(torrent_hashes=torrent_hash) except qbittorrentapi.APIError: pass state = load_monitor_state() entry = state.setdefault("torrents", {}).setdefault(torrent_hash, {}) entry["last_progress_at"] = time.time() entry["status_message"] = "" save_monitor_state(state) return action_response("Torrent dilanjutkan.") except qbittorrentapi.APIError as exc: return action_response(f"Gagal melanjutkan torrent: {exc}", ok=False, status_code=400) @app.route("/api/torrents/<torrent_hash>", methods=["DELETE"]) def delete_torrent(torrent_hash: str): delete_files = request.args.get("with_files", "false").lower() == "true" if torrent_hash.startswith("aria2_"): ok, message = aria2.delete_task(torrent_hash, STATE_FILE, STATE_LOCK, delete_files) if ok: return action_response(message) return action_response(message, ok=False, status_code=404) try: client = get_client() client.torrents_delete(delete_files=delete_files, torrent_hashes=torrent_hash) state = load_monitor_state() state.setdefault("torrents", {}).pop(torrent_hash, None) if delete_files: message = "Torrent dan file hasil download dihapus." else: message = "Torrent dihapus dari daftar." save_monitor_state(state) return action_response(message) except qbittorrentapi.APIError as exc: return action_response(f"Gagal menghapus torrent: {exc}", ok=False, status_code=400) @app.route("/add-aria2", methods=["POST"]) def add_aria2(): is_valid_url, url_or_error = aria2.validate_download_url(request.form.get("aria2_link", "")) if not is_valid_url: if wants_json_response(): return action_response(url_or_error, ok=False, status_code=400) flash(url_or_error, "error") return redirect(url_for("index")) if shutil.which("aria2c") is None: message = "aria2c belum tersedia di environment aplikasi." if wants_json_response(): return action_response(message, ok=False, status_code=503) flash(message, "error") return redirect(url_for("index")) try: _task_id, filename = aria2.start_download(url_or_error, DOWNLOAD_PATH, STATE_FILE, STATE_LOCK) if wants_json_response(): return action_response(f"Aria2 download dimulai: {filename}") flash(f"Aria2 download dimulai: {filename}", "success") except (OSError, requests.RequestException) as exc: if wants_json_response(): return action_response(f"Gagal memulai Aria2 download: {exc}", ok=False, status_code=502) flash(f"Gagal memulai Aria2 download: {exc}", "error") return redirect(url_for("index")) @app.route("/api/torrents/<torrent_hash>/upload-gofile", methods=["POST"]) def upload_torrent_to_gofile(torrent_hash: str): if is_aria2_task(torrent_hash): state = load_monitor_state() entry = state.get("aria2", {}).get(torrent_hash) if not entry: return action_response("Tugas Aria2 tidak ditemukan.", ok=False, status_code=404) if entry.get("gofile_uploading"): return action_response("Upload GoFile masih berjalan.", ok=False, status_code=409) file_path = Path(entry.get("file_path", "") or "") if not file_path.exists(): return action_response("File Aria2 tidak ditemukan di storage.", ok=False, status_code=404) 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"] = "" entry["gofile_provider"] = "GoFile" entry["gofile_status"] = "Sedang upload ke GoFile..." entry["status_message"] = "" save_monitor_state(state) start_gofile_upload_background(torrent_hash, entry.get("name", file_path.name), file_path, mode="zip") return action_response("Upload Aria2 ke GoFile dimulai.") try: client = get_client() torrents = client.torrents_info(torrent_hashes=torrent_hash) if not torrents: return action_response("Torrent tidak ditemukan.", ok=False, status_code=404) torrent = torrents[0] mode = request.args.get("mode", "zip").lower() progress = float(getattr(torrent, "progress", 0) or 0) if progress < 1: return action_response("Upload ke GoFile hanya tersedia setelah download selesai.", ok=False, status_code=400) content_path = Path(getattr(torrent, "content_path", "") or "") if not content_path.exists(): return action_response("File hasil download tidak ditemukan di storage.", ok=False, status_code=404) if mode not in {"zip", "raw"}: return action_response("Mode upload tidak valid.", ok=False, status_code=400) if mode == "raw" and content_path.is_dir() and not GOFILE_API_TOKEN: return action_response("Raw folder upload GoFile memerlukan GOFILE_API_TOKEN.", ok=False, status_code=400) state = load_monitor_state() entry = get_task_state_entry(state, torrent_hash) if entry.get("gofile_uploading"): return action_response("Upload GoFile masih berjalan.", ok=False, status_code=409) 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"] = "" entry["gofile_provider"] = "GoFile" entry["gofile_status"] = "Sedang upload ke GoFile..." 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) start_gofile_upload_background(torrent_hash, torrent.name, content_path, mode=mode) return action_response("Upload ke GoFile dimulai." if mode == "zip" else "Upload raw folder ke GoFile dimulai.") except qbittorrentapi.APIError as exc: return action_response(f"Gagal memulai upload GoFile: {exc}", ok=False, status_code=502) @app.route("/api/torrents/<torrent_hash>/cancel-gofile", methods=["POST"]) def cancel_gofile_upload(torrent_hash: str): state = load_monitor_state() bucket_name = "aria2" if is_aria2_task(torrent_hash) else "torrents" entry = state.setdefault(bucket_name, {}).get(torrent_hash) if not entry or not entry.get("gofile_uploading"): return action_response("Upload GoFile tidak sedang berjalan.", ok=False, status_code=409) provider = entry.get("gofile_provider", "upload") entry["gofile_cancel_requested"] = True entry["status_message"] = "" save_monitor_state(state) cancel_upload_process(int(entry.get("gofile_pid", 0) or 0)) if provider == "Archiving": return action_response("Pembatalan proses archive diproses.") return action_response(f"Pembatalan upload {provider} diproses.") @app.route("/api/torrents/<torrent_hash>/upload-pixeldrain", methods=["POST"]) def upload_torrent_to_pixeldrain(torrent_hash: str): if not PIXELDRAIN_API_KEY: return action_response("PIXELDRAIN_API_KEY belum diset.", ok=False, status_code=400) if is_aria2_task(torrent_hash): state = load_monitor_state() entry = state.get("aria2", {}).get(torrent_hash) if not entry: return action_response("Tugas Aria2 tidak ditemukan.", ok=False, status_code=404) if entry.get("gofile_uploading"): return action_response("Upload file eksternal masih berjalan.", ok=False, status_code=409) file_path = Path(entry.get("file_path", "") or "") if not file_path.exists(): return action_response("File Aria2 tidak ditemukan di storage.", ok=False, status_code=404) 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" entry["gofile_provider"] = "PixelDrain" entry["gofile_status"] = "Sedang upload ke PixelDrain..." entry["status_message"] = "" save_monitor_state(state) start_pixeldrain_upload_background(torrent_hash, entry.get("name", file_path.name), file_path, mode="zip") return action_response("Upload Aria2 ke PixelDrain dimulai.") try: client = get_client() torrents = client.torrents_info(torrent_hashes=torrent_hash) if not torrents: return action_response("Torrent tidak ditemukan.", ok=False, status_code=404) torrent = torrents[0] mode = request.args.get("mode", "zip").lower() progress = float(getattr(torrent, "progress", 0) or 0) if progress < 1: return action_response("Upload ke PixelDrain hanya tersedia setelah download selesai.", ok=False, status_code=400) content_path = Path(getattr(torrent, "content_path", "") or "") if not content_path.exists(): return action_response("File hasil download tidak ditemukan di storage.", ok=False, status_code=404) if mode not in {"zip", "raw"}: return action_response("Mode upload tidak valid.", ok=False, status_code=400) state = load_monitor_state() entry = get_task_state_entry(state, torrent_hash) if entry.get("gofile_uploading"): return action_response("Upload file eksternal masih berjalan.", ok=False, status_code=409) 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" entry["gofile_provider"] = "PixelDrain" entry["gofile_status"] = "Sedang upload ke PixelDrain..." 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) start_pixeldrain_upload_background(torrent_hash, torrent.name, content_path, mode=mode) return action_response("Upload ke PixelDrain dimulai." if mode == "zip" else "Upload raw folder ke PixelDrain dimulai.") except qbittorrentapi.APIError as exc: return action_response(f"Gagal memulai upload PixelDrain: {exc}", ok=False, status_code=502) @app.route("/api/torrents/<torrent_hash>/upload-rclone", methods=["POST"]) def upload_torrent_to_rclone(torrent_hash: str): config = validate_rclone_config(force_refresh=True) if config.get("error") or not config.get("remotes"): return action_response(f"rclone belum siap: {config.get('error') or 'remote tidak ditemukan.'}", ok=False, status_code=400) try: remote = requested_rclone_remote(config, request.args.get("remote", "")) except ValueError as exc: return action_response(str(exc), ok=False, status_code=400, rclone=rclone_config_summary(force_refresh=False)) if is_aria2_task(torrent_hash): state = load_monitor_state() entry = state.get("aria2", {}).get(torrent_hash) if not entry: return action_response("Tugas Aria2 tidak ditemukan.", ok=False, status_code=404) if entry.get("gofile_uploading"): return action_response("Upload file eksternal masih berjalan.", ok=False, status_code=409) file_path = Path(entry.get("file_path", "") or "") if not file_path.exists(): return action_response("File Aria2 tidak ditemukan di storage.", ok=False, status_code=404) 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"] = remote entry["gofile_provider"] = "rclone" entry["gofile_status"] = f"Sedang upload ke rclone remote {remote}..." entry["status_message"] = "" save_monitor_state(state) start_rclone_upload_background(torrent_hash, entry.get("name", file_path.name), file_path, mode="zip", remote_name=remote) return action_response("Upload Aria2 ke rclone dimulai.") try: client = get_client() torrents = client.torrents_info(torrent_hashes=torrent_hash) if not torrents: return action_response("Torrent tidak ditemukan.", ok=False, status_code=404) torrent = torrents[0] mode = request.args.get("mode", "zip").lower() progress = float(getattr(torrent, "progress", 0) or 0) if progress < 1: return action_response("Upload ke rclone hanya tersedia setelah download selesai.", ok=False, status_code=400) content_path = Path(getattr(torrent, "content_path", "") or "") if not content_path.exists(): return action_response("File hasil download tidak ditemukan di storage.", ok=False, status_code=404) if mode not in {"zip", "raw"}: return action_response("Mode upload tidak valid.", ok=False, status_code=400) if mode == "raw" and not content_path.is_dir(): return action_response("Mode raw rclone hanya tersedia untuk folder.", ok=False, status_code=400) state = load_monitor_state() entry = get_task_state_entry(state, torrent_hash) if entry.get("gofile_uploading"): return action_response("Upload file eksternal masih berjalan.", ok=False, status_code=409) 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"] = remote entry["gofile_provider"] = "rclone" entry["gofile_status"] = f"Sedang upload ke rclone remote {remote}..." 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) start_rclone_upload_background(torrent_hash, torrent.name, content_path, mode=mode, remote_name=remote) return action_response("Upload ke rclone dimulai." if mode == "zip" else "Upload raw folder ke rclone dimulai.") except qbittorrentapi.APIError as exc: return action_response(f"Gagal memulai upload rclone: {exc}", ok=False, status_code=502) @app.route("/add-magnet", methods=["POST"]) def add_magnet(): magnet = request.form.get("magnet_link", "").strip() is_valid_magnet, magnet_or_error = validate_magnet_link(magnet) if not is_valid_magnet: if wants_json_response(): return action_response(magnet_or_error, ok=False, status_code=400) flash(magnet_or_error, "error") return redirect(url_for("index")) try: torrent_hash = magnet_info_hash(magnet_or_error) add_magnet_and_confirm_task(magnet_or_error, torrent_hash) files = wait_for_torrent_files(torrent_hash) if wants_json_response(): if files: payload = build_file_selection_payload(torrent_hash, files) clear_torrent_status_message(torrent_hash) return torrent_selection_response(payload) return action_response( "Magnet link ditambahkan. Metadata masih diambil sebelum seleksi file.", selection_required=False, selection_pending=True, torrent_hash=torrent_hash, files=[], ) qbt_resume_torrent(torrent_hash) flash("Magnet link berhasil ditambahkan.", "success") except InsufficientStorageError as exc: if wants_json_response(): return action_response(str(exc), ok=False, status_code=507) flash(str(exc), "error") except (QBittorrentWebAPIError, TorrentMetadataError, requests.RequestException) as exc: if wants_json_response(): return action_response(f"Gagal menambahkan magnet link: {exc}", ok=False, status_code=400) flash(f"Gagal menambahkan magnet link: {exc}", "error") return redirect(url_for("index")) @app.route("/upload-torrent", methods=["POST"]) def upload_torrent(): torrent_file = request.files.get("torrent_file") if torrent_file is None or torrent_file.filename == "": if wants_json_response(): return action_response("Silakan pilih file torrent.", ok=False, status_code=400) flash("Silakan pilih file torrent.", "error") return redirect(url_for("index")) if not torrent_file.filename.lower().endswith(".torrent"): if wants_json_response(): return action_response("File harus berekstensi .torrent.", ok=False, status_code=400) flash("File harus berekstensi .torrent.", "error") return redirect(url_for("index")) destination = UPLOAD_DIR / Path(torrent_file.filename).name torrent_file.save(destination) try: torrent_hash = torrent_info_hash_from_bytes(destination.read_bytes()) qbt_add_torrent_file(destination, paused=True) files = wait_for_torrent_files(torrent_hash) if wants_json_response(): if files: payload = build_file_selection_payload(torrent_hash, files) clear_torrent_status_message(torrent_hash) return torrent_selection_response(payload) return action_response( "File torrent berhasil diunggah, tetapi daftar file belum siap.", selection_required=False, selection_pending=True, torrent_hash=torrent_hash, files=[], ) qbt_resume_torrent(torrent_hash) flash("File torrent berhasil diunggah.", "success") except InsufficientStorageError as exc: if wants_json_response(): return action_response(str(exc), ok=False, status_code=507) flash(str(exc), "error") except (QBittorrentWebAPIError, TorrentMetadataError, requests.RequestException) as exc: if wants_json_response(): return action_response(f"Gagal menambahkan file torrent: {exc}", ok=False, status_code=400) flash(f"Gagal menambahkan file torrent: {exc}", "error") finally: destination.unlink(missing_ok=True) return redirect(url_for("index")) if __name__ == "__main__": app.run(host="0.0.0.0", port=WEB_PORT, debug=False)
import base64
import hashlib
import json
import os
import platform
import re
import signal
import shutil
import socket
import subprocess
import threading
import time
from pathlib import Path
from urllib.parse import parse_qs, quote, urlparse
from flask import Flask, flash, jsonify, redirect, render_template, request, url_for
import psutil
import qbittorrentapi
import requests
import aria2
BASE_DIR = Path(__file__).resolve().parent
UPLOAD_DIR = BASE_DIR / "uploads"
STATE_FILE = BASE_DIR / "monitor_state.json"
STATE_LOCK = threading.Lock()
UPLOAD_DIR.mkdir(exist_ok=True)
ACTIVE_DOWNLOAD_STATES = {"downloading", "metaDL", "stalledDL", "forcedMetaDL", "forcedDL"}
PAUSED_STATES = {"pausedDL", "pausedUP"}
FAILED_STATES = {"error", "missingFiles", "unknown"}
STUCK_TIMEOUT_MINUTES = int(os.getenv("TORRENT_STUCK_TIMEOUT_MINUTES", "5"))
STUCK_TIMEOUT_SECONDS = STUCK_TIMEOUT_MINUTES * 60
MAX_EVENTS = 12
SYSTEM_INFO_CACHE_SECONDS = 900
LOCATION_CACHE_SECONDS = 3600
GOFILE_LATENCY_CACHE_SECONDS = 600
GOFILE_ENDPOINT_CACHE: dict[str, object] = {"expires_at": 0.0, "urls": []}
RCLONE_CONFIG_CACHE_SECONDS = 60
RCLONE_CONFIG_CACHE: dict[str, object] = {"expires_at": 0.0, "path": "", "remotes": [], "error": ""}
RCLONE_CONFIG_MAX_BYTES = 2 * 1024 * 1024
BTIH_HASH_PATTERN = re.compile(r"^(?:[A-Fa-f0-9]{40}|[A-Z2-7]{32})$")
TORRENT_FILE_SELECTION_WAIT_SECONDS = 8
class GofileUploadCancelled(Exception):
pass
class TorrentMetadataError(ValueError):
pass
class QBittorrentWebAPIError(RuntimeError):
pass
class InsufficientStorageError(ValueError):
pass
def env(name: str, default: str) -> str:
return os.getenv(name, default)
def default_download_path() -> str:
if "QBITTORRENT_SAVE_PATH" in os.environ:
return os.environ["QBITTORRENT_SAVE_PATH"]
if Path("/data").exists():
return "/data/downloads"
return "/downloads"
def default_gofile_upload_urls() -> str:
return ",".join(
[
"https://upload.gofile.io/uploadfile",
"https://upload-na-phx.gofile.io/uploadfile",
"https://upload-na-nyc.gofile.io/uploadfile",
"https://upload-eu-par.gofile.io/uploadfile",
"https://upload-ap-sgp.gofile.io/uploadfile",
]
)
def parse_gofile_upload_urls() -> list[str]:
raw_value = env("GOFILE_UPLOAD_URLS", default_gofile_upload_urls())
urls = [item.strip() for item in raw_value.split(",") if item.strip()]
return urls or ["https://upload.gofile.io/uploadfile"]
def safe_filename(value: str) -> str:
sanitized = re.sub(r"[^A-Za-z0-9._-]+", "-", value).strip("-")
return sanitized or "archive"
def flatten_relative_name(relative_path: Path) -> str:
flattened = "__".join(relative_path.parts)
return safe_filename(flattened)