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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
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."