README / aria2.py
nexus33rd's picture
Upload 29 files
9b1b573 verified
Raw History Blame Contribute Delete
15.9 kB
import json
import os
import re
import signal
import subprocess
import threading
import time
import uuid
from pathlib import Path
from urllib.parse import unquote, urlparse
import requests
ARIA2_STATE_KEY = "aria2"
CONTENT_DISPOSITION_FILENAME_PATTERN = re.compile(r'filename\*?=(?:UTF-8\'\')?"?([^\";]+)"?')
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 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
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 validate_download_url(raw_value: str) -> tuple[bool, str]:
url = (raw_value or "").strip()
if not url:
return False, "Aria2 link wajib diisi."
parsed = urlparse(url)
if parsed.scheme.lower() not in {"http", "https"} or not parsed.netloc:
return False, "Aria2 hanya menerima URL http atau https yang valid."
return True, url
def ensure_state_defaults(state: dict) -> dict:
return state.setdefault(ARIA2_STATE_KEY, {})
def load_state(state_file: Path, state_lock: threading.Lock) -> dict:
with state_lock:
if not state_file.exists():
return {"torrents": {}, "events": [], "system": {}, "speedtest": {"running": False}, ARIA2_STATE_KEY: {}}
try:
data = json.loads(state_file.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
return {"torrents": {}, "events": [], "system": {}, "speedtest": {"running": False}, ARIA2_STATE_KEY: {}}
data.setdefault("torrents", {})
data.setdefault("events", [])
data.setdefault("system", {})
data.setdefault("speedtest", {"running": False})
data.setdefault(ARIA2_STATE_KEY, {})
return data
def save_state(state_file: Path, state_lock: threading.Lock, 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(state_file: Path, state_lock: threading.Lock, mutator) -> None:
state = load_state(state_file, state_lock)
mutator(state)
save_state(state_file, state_lock, state)
def add_event(state_file: Path, state_lock: threading.Lock, level: str, message: str) -> None:
def mutator(state: dict):
state.setdefault("events", []).insert(
0,
{
"level": level,
"message": message,
"created_at": int(time.time()),
},
)
state["events"] = state["events"][:12]
update_state(state_file, state_lock, mutator)
def derive_filename(url: str, headers: dict[str, str]) -> str:
content_disposition = headers.get("content-disposition", "")
match = CONTENT_DISPOSITION_FILENAME_PATTERN.search(content_disposition)
if match:
return Path(unquote(match.group(1).strip())).name or "download.bin"
parsed = urlparse(url)
name = Path(unquote(parsed.path)).name
return name or "download.bin"
def inspect_remote_file(url: str) -> tuple[str, int]:
try:
response = requests.head(url, allow_redirects=True, timeout=20)
response.raise_for_status()
final_url = response.url
headers = {key.lower(): value for key, value in response.headers.items()}
total_bytes = int(headers.get("content-length", "0") or "0")
return derive_filename(final_url, headers), total_bytes
except requests.RequestException:
return derive_filename(url, {}), 0
def serialize_task(task: dict) -> dict:
state_value = task.get("state", "downloading")
progress = int(task.get("progress", 0) or 0)
total_bytes = int(task.get("total_bytes", 0) or 0)
downloaded_bytes = int(task.get("downloaded_bytes", 0) or 0)
status_map = {
"downloading": "Aria2 Download",
"complete": "Completed",
"error": "Failed",
"cancelled": "Cancelled",
"paused": "Paused",
}
badge_map = {
"downloading": "border-cyan-500/30 bg-cyan-500/10 text-cyan-100",
"complete": "border-emerald-500/30 bg-emerald-500/10 text-emerald-100",
"error": "border-rose-500/30 bg-rose-500/10 text-rose-100",
"cancelled": "border-stone-500/30 bg-stone-500/10 text-stone-200",
"paused": "border-stone-500/30 bg-stone-500/10 text-stone-200",
}
file_path = Path(task.get("file_path", "") or "")
gofile_uploading = bool(task.get("gofile_uploading"))
can_remote_upload = state_value == "complete" and file_path.exists() and not gofile_uploading
return {
"hash": task.get("id", ""),
"name": task.get("name", "Aria2 Download"),
"state": "downloading" if state_value == "downloading" else state_value,
"state_label": status_map.get(state_value, "Aria2 Download"),
"state_badge": badge_map.get(state_value, badge_map["downloading"]),
"total_size": format_size(total_bytes),
"downloaded": format_size(downloaded_bytes),
"uploaded": "0 B",
"ratio": "-",
"dlspeed": format_speed(int(task.get("download_speed", 0) or 0)),
"upspeed": "0 B/s",
"display_speed": format_speed(int(task.get("download_speed", 0) or 0)),
"display_speed_label": "Down",
"display_speed_meta": "",
"progress": progress,
"progress_label": "Progress",
"num_seeds": 0,
"num_leechs": 0,
"eta": human_eta(task.get("eta_seconds", 0)),
"status_message": task.get("status_message", ""),
"can_pause": state_value == "downloading" and not gofile_uploading,
"can_resume": state_value == "paused",
"can_gofile_upload": can_remote_upload,
"gofile_link": task.get("gofile_link", ""),
"gofile_status": task.get("gofile_status", ""),
"gofile_uploading": gofile_uploading,
"gofile_speed": task.get("gofile_speed", ""),
"gofile_eta": human_eta(task.get("gofile_eta_seconds", 0)) if gofile_uploading else "-",
"gofile_endpoint": task.get("gofile_endpoint", ""),
"upload_provider": task.get("gofile_provider", ""),
"can_copy_link": bool(task.get("gofile_link")),
"can_cancel_gofile_upload": gofile_uploading,
"can_pixeldrain_upload": can_remote_upload,
"can_rclone_upload": can_remote_upload,
"rclone_config_ready": False,
"rclone_config_error": "",
"is_folder": False,
"can_raw_gofile_upload": False,
"can_raw_pixeldrain_upload": False,
"can_raw_rclone_upload": False,
"task_kind": "aria2",
"added_at": int(task.get("created_at", 0) or 0),
}
def _kill_process(pid: int | None) -> None:
if not pid:
return
try:
os.kill(pid, signal.SIGTERM)
except OSError:
pass
def _monitor_download(task_id: str, file_path: Path, process: subprocess.Popen, state_file: Path, state_lock: threading.Lock) -> None:
last_size = 0
last_at = time.time()
while process.poll() is None:
now = time.time()
current_size = file_path.stat().st_size if file_path.exists() else 0
elapsed = max(now - last_at, 0.001)
speed = max(0, int((current_size - last_size) / elapsed))
def mutator(state: dict):
entry = ensure_state_defaults(state).get(task_id)
if not entry:
return
if entry.get("state") == "paused":
entry["download_speed"] = 0
entry["eta_seconds"] = 0
return
total_bytes = int(entry.get("total_bytes", 0) or 0)
entry["downloaded_bytes"] = current_size
entry["download_speed"] = speed
entry["progress"] = int((current_size / total_bytes) * 100) if total_bytes > 0 else entry.get("progress", 0)
if total_bytes > current_size and speed > 0:
entry["eta_seconds"] = int((total_bytes - current_size) / speed)
else:
entry["eta_seconds"] = 0
entry["state"] = "downloading"
update_state(state_file, state_lock, mutator)
last_size = current_size
last_at = now
time.sleep(1)
current_size = file_path.stat().st_size if file_path.exists() else 0
stdout = process.stdout.read() if process.stdout else ""
stderr = process.stderr.read() if process.stderr else ""
if process.returncode == 0:
def success_mutator(state: dict):
entry = ensure_state_defaults(state).get(task_id)
if not entry:
return
total_bytes = max(int(entry.get("total_bytes", 0) or 0), current_size)
entry["downloaded_bytes"] = total_bytes
entry["total_bytes"] = total_bytes
entry["download_speed"] = 0
entry["eta_seconds"] = 0
entry["progress"] = 100
entry["pid"] = 0
entry["state"] = "complete"
entry["status_message"] = ""
update_state(state_file, state_lock, success_mutator)
return
def error_mutator(state: dict):
entry = ensure_state_defaults(state).get(task_id)
if not entry:
return
entry["downloaded_bytes"] = current_size
entry["download_speed"] = 0
entry["eta_seconds"] = 0
entry["pid"] = 0
if entry.get("state") != "cancelled":
entry["state"] = "error"
detail = (stderr or stdout).strip().splitlines()
entry["status_message"] = detail[-1][:300] if detail else "Download gagal."
update_state(state_file, state_lock, error_mutator)
add_event(state_file, state_lock, "error", f"Aria2 download gagal: {file_path.name}")
def start_download(url: str, download_dir: str, state_file: Path, state_lock: threading.Lock) -> tuple[str, str]:
filename, total_bytes = inspect_remote_file(url)
task_id = f"aria2_{uuid.uuid4().hex[:12]}"
created_at = int(time.time())
target_dir = Path(download_dir)
target_dir.mkdir(parents=True, exist_ok=True)
file_path = target_dir / filename
command = [
"aria2c",
"--dir",
str(target_dir),
"--out",
filename,
"--allow-overwrite=true",
"--auto-file-renaming=false",
"--file-allocation=none",
"--summary-interval=0",
"--console-log-level=warn",
url,
]
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
def mutator(state: dict):
ensure_state_defaults(state)[task_id] = {
"id": task_id,
"name": filename,
"url": url,
"file_path": str(file_path),
"created_at": created_at,
"pid": process.pid,
"state": "downloading",
"progress": 0,
"downloaded_bytes": 0,
"total_bytes": total_bytes,
"download_speed": 0,
"eta_seconds": 0,
"gofile_progress": 0,
"gofile_uploading": False,
"gofile_speed": "",
"gofile_eta_seconds": 0,
"gofile_cancel_requested": False,
"gofile_pid": 0,
"gofile_endpoint": "",
"gofile_provider": "",
"gofile_status": "",
"gofile_link": "",
"status_message": "",
}
update_state(state_file, state_lock, mutator)
threading.Thread(
target=_monitor_download,
args=(task_id, file_path, process, state_file, state_lock),
daemon=True,
).start()
return task_id, filename
def delete_task(task_id: str, state_file: Path, state_lock: threading.Lock, delete_files: bool) -> tuple[bool, str]:
state = load_state(state_file, state_lock)
entry = ensure_state_defaults(state).get(task_id)
if not entry:
return False, "Tugas Aria2 tidak ditemukan."
pid = int(entry.get("pid", 0) or 0)
_kill_process(pid)
file_path = Path(entry.get("file_path", "") or "")
if delete_files and file_path.exists():
file_path.unlink(missing_ok=True)
partial_path = Path(f"{file_path}.aria2")
partial_path.unlink(missing_ok=True)
del state[ARIA2_STATE_KEY][task_id]
save_state(state_file, state_lock, state)
if delete_files:
return True, "Tugas Aria2 dan file hasil download dihapus."
return True, "Tugas Aria2 dihapus."
def pause_task(task_id: str, state_file: Path, state_lock: threading.Lock) -> tuple[bool, str]:
state = load_state(state_file, state_lock)
entry = ensure_state_defaults(state).get(task_id)
if not entry:
return False, "Tugas Aria2 tidak ditemukan."
if entry.get("state") != "downloading":
return False, "Tugas Aria2 tidak bisa dijeda."
pid = int(entry.get("pid", 0) or 0)
if not pid:
return False, "Process Aria2 tidak ditemukan."
try:
os.kill(pid, signal.SIGSTOP)
except OSError as exc:
return False, f"Gagal pause Aria2: {exc}"
entry["state"] = "paused"
entry["download_speed"] = 0
entry["eta_seconds"] = 0
entry["status_message"] = ""
save_state(state_file, state_lock, state)
return True, "Tugas Aria2 dijeda."
def resume_task(task_id: str, state_file: Path, state_lock: threading.Lock) -> tuple[bool, str]:
state = load_state(state_file, state_lock)
entry = ensure_state_defaults(state).get(task_id)
if not entry:
return False, "Tugas Aria2 tidak ditemukan."
if entry.get("state") != "paused":
return False, "Tugas Aria2 tidak bisa dilanjutkan."
pid = int(entry.get("pid", 0) or 0)
if not pid:
return False, "Process Aria2 tidak ditemukan."
try:
os.kill(pid, signal.SIGCONT)
except OSError as exc:
return False, f"Gagal melanjutkan Aria2: {exc}"
entry["state"] = "downloading"
entry["status_message"] = ""
save_state(state_file, state_lock, state)
return True, "Tugas Aria2 dilanjutkan."