diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -4,37 +4,37 @@ import json import os import platform import re -import signal -import shutil -import socket -import subprocess -import threading -import time -from pathlib import Path +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 + +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 + +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 @@ -42,8 +42,8 @@ RCLONE_CONFIG_CACHE: dict[str, object] = {"expires_at": 0.0, "path": "", "remote 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 @@ -62,28 +62,28 @@ class InsufficientStorageError(ValueError): 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 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()] @@ -93,8 +93,8 @@ def parse_gofile_upload_urls() -> list[str]: 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) @@ -195,69 +195,69 @@ def torrent_info_hash_from_bytes(data: bytes) -> str: 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 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 + 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 @@ -429,28 +429,28 @@ def path_total_size(source_path: Path) -> int: 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", "f315f659-0e6e-4cce-bdc1-2b0d654c8f51") + 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") @@ -460,35 +460,35 @@ RCLONE_CONFIG_PATH = Path(env("RCLONE_CONFIG_PATH", str(BASE_DIR / "rclone.conf" 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() - - + + +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 + 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 @@ -760,79 +760,79 @@ def add_magnet_and_confirm_task(magnet: str, torrent_hash: str) -> None: 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" - - + 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(): @@ -849,33 +849,33 @@ def load_monitor_state() -> dict: 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 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", @@ -896,18 +896,18 @@ def state_label(raw_state: str) -> str: "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 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" @@ -927,8 +927,8 @@ def effective_state_label(torrent, state_entry: dict | None = None) -> str: 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" @@ -954,13 +954,13 @@ def swarm_peer_counts(torrent) -> tuple[int, int]: def serialize_event(event: dict) -> dict: - return { - "level": event.get("level", "info"), - "message": event.get("message", ""), - "created_at": event.get("created_at", 0), - } - - + 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", "") @@ -986,18 +986,18 @@ def serialize_torrent(torrent, state_entry: dict | None = None) -> dict: 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") + 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" + 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) @@ -1009,7 +1009,7 @@ def serialize_torrent(torrent, state_entry: dict | None = None) -> dict: eta_text = "-" else: eta_text = human_eta(eta_value) - display_speed = gofile_speed if gofile_uploading else format_speed(torrent_dlspeed) + 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" @@ -1020,14 +1020,14 @@ def serialize_torrent(torrent, state_entry: dict | None = None) -> dict: 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 - ) - + + 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, @@ -1047,22 +1047,22 @@ def serialize_torrent(torrent, state_entry: dict | None = None) -> dict: "display_speed": display_speed, "display_speed_label": display_speed_label, "display_speed_meta": display_speed_meta, - "progress": display_progress, - "progress_label": progress_label, + "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, + "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), @@ -1093,8 +1093,8 @@ def update_task_entry(task_id: str, **fields) -> None: 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 @@ -1103,211 +1103,211 @@ def prepare_upload_source(source_path: Path, torrent_hash: str, provider_name: s 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, - ) - + 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() - + 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() + 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"): + 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() + 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 + 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 + 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() + 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 + 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 + 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}" - - + 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_eta_seconds"] = 0 + entry["gofile_cancel_requested"] = False entry["gofile_pid"] = 0 entry["gofile_endpoint"] = "" entry["gofile_provider"] = "" @@ -1369,227 +1369,227 @@ def restore_torrent_state_after_remote_upload(torrent_hash: str) -> None: 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." + + +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 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: + + 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}%", + 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={}) - - + "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)) - + 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() @@ -1616,14 +1616,14 @@ def get_dashboard_data() -> tuple[list[dict], dict]: "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, - } - - + 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) @@ -1639,34 +1639,34 @@ def torrent_selection_response(payload: dict): 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, - } - - + 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: @@ -1742,214 +1742,214 @@ def monitor_rclone_progress(output_pipe, torrent_hash: str, total_bytes: int, re 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( + 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( + { + "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 - - + { + "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" + 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}", + "--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( + + 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() + { + "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( + 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 - - + { + "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}" + 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", + "--retry", + "2", + "--retry-delay", + "2", + "--retry-all-errors", + "--connect-timeout", + "15", + "--speed-time", + "60", "--speed-limit", "10240", "--max-time", @@ -1965,74 +1965,74 @@ def pixeldrain_upload_attempt(torrent_hash: str, file_path: Path, started_at: fl "--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( + + 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() + { + "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( + 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()) - + { + "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 @@ -2140,62 +2140,62 @@ def rclone_upload_attempt( 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 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["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( + + 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.") - + { + "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["gofile_provider"] = "GoFile" + entry["gofile_status"] = f"Upload GoFile berhasil: {download_page}" entry["status_message"] = "" update_state(success_mutator) @@ -2204,8 +2204,8 @@ def start_gofile_upload_background(torrent_hash: str, torrent_name: str, file_pa 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["gofile_provider"] = "GoFile" + entry["gofile_status"] = "Upload GoFile dibatalkan." entry["status_message"] = "" add_event(state, "warning", f"Upload GoFile dibatalkan untuk {torrent_name}.") @@ -2215,55 +2215,55 @@ def start_gofile_upload_background(torrent_hash: str, torrent_name: str, file_pa 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}" + 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() - - + (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 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["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}" - + + 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["gofile_provider"] = "PixelDrain" + entry["gofile_status"] = f"Upload PixelDrain berhasil: {download_page}" entry["status_message"] = "" update_state(success_mutator) @@ -2272,8 +2272,8 @@ def start_pixeldrain_upload_background(torrent_hash: str, torrent_name: str, fil 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["gofile_provider"] = "PixelDrain" + entry["gofile_status"] = "Upload PixelDrain dibatalkan." entry["status_message"] = "" add_event(state, "warning", f"Upload PixelDrain dibatalkan untuk {torrent_name}.") @@ -2283,18 +2283,18 @@ def start_pixeldrain_upload_background(torrent_hash: str, torrent_name: str, fil 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}" + 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) - + 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() @@ -2372,36 +2372,36 @@ def start_rclone_upload_background( @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") - + 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) @@ -2412,16 +2412,16 @@ def healthz(): @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, - } - ) + 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 @@ -2501,15 +2501,15 @@ def apply_torrent_file_selection(torrent_hash: str): @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": {}})) + 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.") @@ -2556,10 +2556,10 @@ def pause_torrent(torrent_hash: str): 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) - - + except qbittorrentapi.APIError as exc: + return action_response(f"Gagal pause torrent: {exc}", ok=False, status_code=400) + + @app.route("/api/torrents//resume", methods=["POST"]) def resume_torrent(torrent_hash: str): if is_aria2_task(torrent_hash): @@ -2583,12 +2583,12 @@ def resume_torrent(torrent_hash: str): 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/", methods=["DELETE"]) + 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/", methods=["DELETE"]) def delete_torrent(torrent_hash: str): delete_files = request.args.get("with_files", "false").lower() == "true" if torrent_hash.startswith("aria2_"): @@ -2607,7 +2607,7 @@ def delete_torrent(torrent_hash: str): message = "Torrent dihapus dari daftar." save_monitor_state(state) return action_response(message) - except qbittorrentapi.APIError as exc: + except qbittorrentapi.APIError as exc: return action_response(f"Gagal menghapus torrent: {exc}", ok=False, status_code=400) @@ -2637,9 +2637,9 @@ def add_aria2(): 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//upload-gofile", methods=["POST"]) + + +@app.route("/api/torrents//upload-gofile", methods=["POST"]) def upload_torrent_to_gofile(torrent_hash: str): if is_aria2_task(torrent_hash): state = load_monitor_state() @@ -2666,34 +2666,34 @@ def upload_torrent_to_gofile(torrent_hash: str): 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() + 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 + 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" @@ -2702,32 +2702,32 @@ def upload_torrent_to_gofile(torrent_hash: str): 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//cancel-gofile", methods=["POST"]) + + 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//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 + + 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//upload-pixeldrain", methods=["POST"]) + 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//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) @@ -2758,32 +2758,32 @@ def upload_torrent_to_pixeldrain(torrent_hash: str): 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() + 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 + 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" @@ -2792,9 +2792,9 @@ def upload_torrent_to_pixeldrain(torrent_hash: str): 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.") + + 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) @@ -2915,25 +2915,25 @@ def add_magnet(): 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")) - + + 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) @@ -2963,11 +2963,11 @@ def upload_torrent(): 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) + 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)