nexus33rd commited on
Commit
22d2ae1
·
verified ·
1 Parent(s): 514e611

Upload 15 files

Browse files
Files changed (6) hide show
  1. .env +5 -5
  2. app.py +531 -60
  3. bot/__init__.py +1 -1
  4. bot/bot.py +521 -521
  5. static/app.js +306 -42
  6. templates/index.html +45 -7
.env CHANGED
@@ -1,5 +1,5 @@
1
- TELEGRAM_BOT_ENABLED=true
2
- TELEGRAM_API_ID=2589472
3
- TELEGRAM_API_HASH="5243628014db9798d6775b330e542602"
4
- TELEGRAM_BOT_TOKEN="6100847173:AAE1Ph_WWGEJhENvKKIzPhziO63cv3ruYKs"
5
- TELEGRAM_OWNER_IDS=1487943213
 
1
+ TELEGRAM_BOT_ENABLED=true
2
+ TELEGRAM_API_ID=2589472
3
+ TELEGRAM_API_HASH="5243628014db9798d6775b330e542602"
4
+ TELEGRAM_BOT_TOKEN="6100847173:AAE1Ph_WWGEJhENvKKIzPhziO63cv3ruYKs"
5
+ TELEGRAM_OWNER_IDS=1487943213
app.py CHANGED
@@ -1,3 +1,5 @@
 
 
1
  import json
2
  import os
3
  import platform
@@ -36,14 +38,27 @@ LOCATION_CACHE_SECONDS = 3600
36
  GOFILE_LATENCY_CACHE_SECONDS = 600
37
  GOFILE_ENDPOINT_CACHE: dict[str, object] = {"expires_at": 0.0, "urls": []}
38
  BTIH_HASH_PATTERN = re.compile(r"^(?:[A-Fa-f0-9]{40}|[A-Z2-7]{32})$")
 
39
 
40
 
41
- class GofileUploadCancelled(Exception):
42
- pass
43
-
44
-
45
- def env(name: str, default: str) -> str:
46
- return os.getenv(name, default)
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
 
49
  def default_download_path() -> str:
@@ -109,6 +124,74 @@ def validate_magnet_link(raw_value: str) -> tuple[bool, str]:
109
  return False, "Magnet link tidak valid: info hash btih tidak sesuai format."
110
 
111
  return True, magnet
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
 
114
  def parse_size_token(token: str) -> int | None:
@@ -212,7 +295,7 @@ app.config["MAX_CONTENT_LENGTH"] = 100 * 1024 * 1024
212
  DOWNLOAD_PATH = default_download_path()
213
 
214
 
215
- def get_client() -> qbittorrentapi.Client:
216
  host = env("QBITTORRENT_HOST", "127.0.0.1")
217
  port = int(env("QBITTORRENT_PORT", "8080"))
218
  username = env("QBITTORRENT_USERNAME", "")
@@ -232,11 +315,277 @@ def get_client() -> qbittorrentapi.Client:
232
  # still works while qBittorrent config is being repaired or migrated.
233
  fallback_client = qbittorrentapi.Client(host=host, port=port)
234
  fallback_client.app.version
235
- return fallback_client
236
- return client
237
-
238
-
239
- def format_size(value: int | None) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  if value in (None, 0):
241
  return "0 B"
242
 
@@ -441,6 +790,7 @@ def serialize_event(event: dict) -> dict:
441
  def serialize_torrent(torrent, state_entry: dict | None = None) -> dict:
442
  eta_value = getattr(torrent, "eta", None)
443
  raw_state = getattr(torrent, "state", "")
 
444
  torrent_progress = float(getattr(torrent, "progress", 0) or 0)
445
  raw_torrent_dlspeed = int(getattr(torrent, "dlspeed", 0) or 0)
446
  torrent_upspeed = int(getattr(torrent, "upspeed", 0) or 0)
@@ -452,6 +802,13 @@ def serialize_torrent(torrent, state_entry: dict | None = None) -> dict:
452
  int(getattr(torrent, "uploaded", 0) or 0),
453
  int(getattr(torrent, "uploaded_session", 0) or 0),
454
  )
 
 
 
 
 
 
 
455
  torrent_num_seeds, torrent_num_leechs = swarm_peer_counts(torrent)
456
  state_entry = state_entry or {}
457
  status_message = state_entry.get("status_message", "")
@@ -503,8 +860,12 @@ def serialize_torrent(torrent, state_entry: dict | None = None) -> dict:
503
  "state": torrent.state,
504
  "state_label": effective_state_label(torrent, state_entry),
505
  "state_badge": effective_status_badge(torrent, state_entry),
506
- "total_size": format_size(getattr(torrent, "total_size", 0)),
507
- "downloaded": format_size(torrent_downloaded),
 
 
 
 
508
  "uploaded": format_size(torrent_uploaded),
509
  "ratio": f"{float(getattr(torrent, 'ratio', 0) or 0):.2f}",
510
  "dlspeed": badge_download_speed,
@@ -966,7 +1327,7 @@ def get_system_info() -> dict:
966
  if cached and now - int(cached.get("fetched_at", 0)) < SYSTEM_INFO_CACHE_SECONDS:
967
  snapshot = cached
968
  else:
969
- disk = shutil.disk_usage(DOWNLOAD_PATH)
970
  memory = psutil.virtual_memory()
971
  snapshot = {
972
  "os": f"{platform.system()} {platform.release()}",
@@ -976,9 +1337,10 @@ def get_system_info() -> dict:
976
  "ram_total": format_size(memory.total),
977
  "ram_used": format_size(memory.used),
978
  "ram_percent": f"{memory.percent:.0f}%",
979
- "storage_total": format_size(disk.total),
980
- "storage_used": format_size(disk.used),
981
- "storage_percent": f"{(disk.used / disk.total) * 100:.0f}%" if disk.total else "0%",
 
982
  "hostname": platform.node() or "-",
983
  "fetched_at": now,
984
  }
@@ -1076,15 +1438,21 @@ def get_dashboard_data() -> tuple[list[dict], dict]:
1076
  }
1077
 
1078
 
1079
- def action_response(message: str, ok: bool = True, status_code: int = 200, **extra):
1080
- payload = {"success": ok, "message": message}
1081
- payload.update(extra)
1082
- return jsonify(payload), status_code
1083
-
1084
-
1085
- def wants_json_response() -> bool:
1086
- accept = request.headers.get("Accept", "")
1087
- requested_with = request.headers.get("X-Requested-With", "")
 
 
 
 
 
 
1088
  return "application/json" in accept or requested_with == "XMLHttpRequest"
1089
 
1090
 
@@ -1611,8 +1979,8 @@ def index():
1611
  return render_template("index.html", torrents=torrents, stats=stats, events=events, system_info=system_info)
1612
 
1613
 
1614
- @app.route("/api/torrents", methods=["GET"])
1615
- def torrents_api():
1616
  try:
1617
  torrents, payload = get_dashboard_data()
1618
  return jsonify(
@@ -1623,13 +1991,85 @@ def torrents_api():
1623
  "torrents": torrents,
1624
  }
1625
  )
1626
- except (qbittorrentapi.APIConnectionError, qbittorrentapi.LoginFailed, qbittorrentapi.APIError) as exc:
1627
- return jsonify({"success": False, "error": str(exc) or "Gagal mengambil data torrent."}), 503
1628
-
1629
-
1630
- @app.route("/api/system", methods=["GET"])
1631
- def system_api():
1632
- return jsonify({"success": True, "system": get_system_info()})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1633
 
1634
 
1635
  @app.route("/api/system/speedtest", methods=["POST"])
@@ -1654,12 +2094,12 @@ def pause_torrent(torrent_hash: str):
1654
  client.torrents_set_force_start(enable=False, torrent_hashes=torrent_hash)
1655
  except qbittorrentapi.APIError:
1656
  pass
1657
- client.torrents_pause(torrent_hashes=torrent_hash)
1658
  state = load_monitor_state()
1659
  entry = state.setdefault("torrents", {}).setdefault(torrent_hash, {})
1660
  entry["status_message"] = ""
1661
  save_monitor_state(state)
1662
- return action_response("Torrent dijeda.")
1663
  except qbittorrentapi.APIError as exc:
1664
  return action_response(f"Gagal pause torrent: {exc}", ok=False, status_code=400)
1665
 
@@ -1671,7 +2111,7 @@ def resume_torrent(torrent_hash: str):
1671
  return action_response(message, ok=ok, status_code=200 if ok else 400)
1672
  try:
1673
  client = get_client()
1674
- client.torrents_resume(torrent_hashes=torrent_hash)
1675
  torrents = client.torrents_info(torrent_hashes=torrent_hash)
1676
  if torrents and float(getattr(torrents[0], "progress", 0) or 0) >= 1:
1677
  try:
@@ -1914,15 +2354,31 @@ def add_magnet():
1914
  return redirect(url_for("index"))
1915
 
1916
  try:
1917
- client = get_client()
1918
- client.torrents_add(urls=magnet_or_error, savepath=DOWNLOAD_PATH)
 
1919
  if wants_json_response():
1920
- return action_response("Magnet link berhasil ditambahkan.")
 
 
 
 
 
 
 
 
 
 
 
1921
  flash("Magnet link berhasil ditambahkan.", "success")
1922
- except qbittorrentapi.APIError as exc:
1923
- if wants_json_response():
1924
- return action_response(f"Gagal menambahkan magnet link: {exc}", ok=False, status_code=400)
1925
- flash(f"Gagal menambahkan magnet link: {exc}", "error")
 
 
 
 
1926
 
1927
  return redirect(url_for("index"))
1928
 
@@ -1942,20 +2398,35 @@ def upload_torrent():
1942
  flash("File harus berekstensi .torrent.", "error")
1943
  return redirect(url_for("index"))
1944
 
1945
- destination = UPLOAD_DIR / Path(torrent_file.filename).name
1946
- torrent_file.save(destination)
1947
-
1948
- try:
1949
- client = get_client()
1950
- with destination.open("rb") as handle:
1951
- client.torrents_add(torrent_files=handle, savepath=DOWNLOAD_PATH)
1952
- if wants_json_response():
1953
- return action_response("File torrent berhasil diunggah.")
1954
- flash("File torrent berhasil diunggah.", "success")
1955
- except qbittorrentapi.APIError as exc:
1956
- if wants_json_response():
1957
- return action_response(f"Gagal menambahkan file torrent: {exc}", ok=False, status_code=400)
1958
- flash(f"Gagal menambahkan file torrent: {exc}", "error")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1959
  finally:
1960
  destination.unlink(missing_ok=True)
1961
 
 
1
+ import base64
2
+ import hashlib
3
  import json
4
  import os
5
  import platform
 
38
  GOFILE_LATENCY_CACHE_SECONDS = 600
39
  GOFILE_ENDPOINT_CACHE: dict[str, object] = {"expires_at": 0.0, "urls": []}
40
  BTIH_HASH_PATTERN = re.compile(r"^(?:[A-Fa-f0-9]{40}|[A-Z2-7]{32})$")
41
+ TORRENT_FILE_SELECTION_WAIT_SECONDS = 8
42
 
43
 
44
+ class GofileUploadCancelled(Exception):
45
+ pass
46
+
47
+
48
+ class TorrentMetadataError(ValueError):
49
+ pass
50
+
51
+
52
+ class QBittorrentWebAPIError(RuntimeError):
53
+ pass
54
+
55
+
56
+ class InsufficientStorageError(ValueError):
57
+ pass
58
+
59
+
60
+ def env(name: str, default: str) -> str:
61
+ return os.getenv(name, default)
62
 
63
 
64
  def default_download_path() -> str:
 
124
  return False, "Magnet link tidak valid: info hash btih tidak sesuai format."
125
 
126
  return True, magnet
127
+
128
+
129
+ def magnet_info_hash(magnet: str) -> str:
130
+ parsed = urlparse(magnet)
131
+ query = parse_qs(parsed.query, keep_blank_values=False)
132
+ for xt_value in query.get("xt", []):
133
+ if not xt_value.lower().startswith("urn:btih:"):
134
+ continue
135
+ raw_hash = xt_value[9:]
136
+ if re.fullmatch(r"[A-Fa-f0-9]{40}", raw_hash):
137
+ return raw_hash.lower()
138
+ if re.fullmatch(r"[A-Z2-7a-z2-7]{32}", raw_hash):
139
+ return base64.b32decode(raw_hash.upper()).hex()
140
+ raise TorrentMetadataError("Magnet link tidak mengandung info hash btih yang valid.")
141
+
142
+
143
+ def _read_bencoded_bytes(data: bytes, offset: int) -> tuple[bytes, int]:
144
+ colon_index = data.find(b":", offset)
145
+ if colon_index < 0:
146
+ raise TorrentMetadataError("Metadata torrent tidak valid.")
147
+ try:
148
+ length = int(data[offset:colon_index])
149
+ except ValueError as exc:
150
+ raise TorrentMetadataError("Metadata torrent tidak valid.") from exc
151
+ start = colon_index + 1
152
+ end = start + length
153
+ if length < 0 or end > len(data):
154
+ raise TorrentMetadataError("Metadata torrent tidak valid.")
155
+ return data[start:end], end
156
+
157
+
158
+ def _skip_bencoded_value(data: bytes, offset: int) -> int:
159
+ if offset >= len(data):
160
+ raise TorrentMetadataError("Metadata torrent tidak valid.")
161
+
162
+ token = data[offset : offset + 1]
163
+ if token == b"i":
164
+ end = data.find(b"e", offset + 1)
165
+ if end < 0:
166
+ raise TorrentMetadataError("Metadata torrent tidak valid.")
167
+ return end + 1
168
+ if token in {b"l", b"d"}:
169
+ offset += 1
170
+ while offset < len(data) and data[offset : offset + 1] != b"e":
171
+ offset = _skip_bencoded_value(data, offset)
172
+ if offset >= len(data):
173
+ raise TorrentMetadataError("Metadata torrent tidak valid.")
174
+ return offset + 1
175
+ if token.isdigit():
176
+ _value, next_offset = _read_bencoded_bytes(data, offset)
177
+ return next_offset
178
+ raise TorrentMetadataError("Metadata torrent tidak valid.")
179
+
180
+
181
+ def torrent_info_hash_from_bytes(data: bytes) -> str:
182
+ if not data.startswith(b"d"):
183
+ raise TorrentMetadataError("File torrent tidak valid.")
184
+
185
+ offset = 1
186
+ while offset < len(data) and data[offset : offset + 1] != b"e":
187
+ key, offset = _read_bencoded_bytes(data, offset)
188
+ value_start = offset
189
+ value_end = _skip_bencoded_value(data, offset)
190
+ if key == b"info":
191
+ return hashlib.sha1(data[value_start:value_end]).hexdigest()
192
+ offset = value_end
193
+
194
+ raise TorrentMetadataError("File torrent tidak mengandung metadata info.")
195
 
196
 
197
  def parse_size_token(token: str) -> int | None:
 
295
  DOWNLOAD_PATH = default_download_path()
296
 
297
 
298
+ def get_client() -> qbittorrentapi.Client:
299
  host = env("QBITTORRENT_HOST", "127.0.0.1")
300
  port = int(env("QBITTORRENT_PORT", "8080"))
301
  username = env("QBITTORRENT_USERNAME", "")
 
315
  # still works while qBittorrent config is being repaired or migrated.
316
  fallback_client = qbittorrentapi.Client(host=host, port=port)
317
  fallback_client.app.version
318
+ return fallback_client
319
+ return client
320
+
321
+
322
+ def qbt_base_url() -> str:
323
+ host = env("QBITTORRENT_HOST", "127.0.0.1")
324
+ port = int(env("QBITTORRENT_PORT", "8080"))
325
+ return f"http://{host}:{port}/api/v2"
326
+
327
+
328
+ def qbt_webapi_request(method: str, path: str, **kwargs) -> requests.Response:
329
+ session = requests.Session()
330
+ base_url = qbt_base_url()
331
+ username = env("QBITTORRENT_USERNAME", "")
332
+ password = env("QBITTORRENT_PASSWORD", "")
333
+ timeout = kwargs.pop("timeout", 20)
334
+
335
+ if username and password:
336
+ login_response = session.post(
337
+ f"{base_url}/auth/login",
338
+ data={"username": username, "password": password},
339
+ timeout=10,
340
+ )
341
+ if login_response.status_code >= 400 or login_response.text.strip() not in {"Ok.", ""}:
342
+ # Some bundled qBittorrent configs bypass auth for the app subnet.
343
+ session = requests.Session()
344
+
345
+ response = session.request(method, f"{base_url}{path}", timeout=timeout, **kwargs)
346
+ if response.status_code >= 400:
347
+ raise QBittorrentWebAPIError(response.text.strip() or f"HTTP {response.status_code}")
348
+ return response
349
+
350
+
351
+ def qbt_add_torrent_url(url: str, paused: bool) -> None:
352
+ response = qbt_webapi_request(
353
+ "POST",
354
+ "/torrents/add",
355
+ data={
356
+ "urls": url,
357
+ "savepath": DOWNLOAD_PATH,
358
+ "paused": "true" if paused else "false",
359
+ "stopped": "true" if paused else "false",
360
+ },
361
+ timeout=30,
362
+ )
363
+ if response.text.strip() not in {"Ok.", ""}:
364
+ raise QBittorrentWebAPIError(response.text.strip())
365
+
366
+
367
+ def qbt_add_torrent_file(file_path: Path, paused: bool) -> None:
368
+ with file_path.open("rb") as handle:
369
+ response = qbt_webapi_request(
370
+ "POST",
371
+ "/torrents/add",
372
+ data={
373
+ "savepath": DOWNLOAD_PATH,
374
+ "paused": "true" if paused else "false",
375
+ "stopped": "true" if paused else "false",
376
+ },
377
+ files={"torrents": (file_path.name, handle, "application/x-bittorrent")},
378
+ timeout=30,
379
+ )
380
+ if response.text.strip() not in {"Ok.", ""}:
381
+ raise QBittorrentWebAPIError(response.text.strip())
382
+
383
+
384
+ def qbt_torrent_files(torrent_hash: str) -> list[dict]:
385
+ response = qbt_webapi_request("GET", "/torrents/files", params={"hash": torrent_hash}, timeout=15)
386
+ payload = response.json()
387
+ return payload if isinstance(payload, list) else []
388
+
389
+
390
+ def qbt_torrent_exists(torrent_hash: str) -> bool:
391
+ response = qbt_webapi_request("GET", "/torrents/info", params={"hashes": torrent_hash}, timeout=15)
392
+ payload = response.json()
393
+ return isinstance(payload, list) and len(payload) > 0
394
+
395
+
396
+ def qbt_delete_torrent(torrent_hash: str, delete_files: bool = False) -> None:
397
+ qbt_webapi_request(
398
+ "POST",
399
+ "/torrents/delete",
400
+ data={"hashes": torrent_hash, "deleteFiles": "true" if delete_files else "false"},
401
+ timeout=15,
402
+ )
403
+
404
+
405
+ def wait_for_torrent_task(torrent_hash: str, timeout_seconds: int = 6) -> bool:
406
+ deadline = time.time() + timeout_seconds
407
+ while time.time() <= deadline:
408
+ if qbt_torrent_exists(torrent_hash):
409
+ return True
410
+ time.sleep(0.5)
411
+ return False
412
+
413
+
414
+ def qbt_pause_torrent(torrent_hash: str) -> None:
415
+ try:
416
+ qbt_webapi_request("POST", "/torrents/stop", data={"hashes": torrent_hash}, timeout=15)
417
+ except QBittorrentWebAPIError:
418
+ qbt_webapi_request("POST", "/torrents/pause", data={"hashes": torrent_hash}, timeout=15)
419
+
420
+
421
+ def qbt_resume_torrent(torrent_hash: str) -> None:
422
+ try:
423
+ qbt_webapi_request("POST", "/torrents/start", data={"hashes": torrent_hash}, timeout=15)
424
+ except QBittorrentWebAPIError:
425
+ qbt_webapi_request("POST", "/torrents/resume", data={"hashes": torrent_hash}, timeout=15)
426
+
427
+
428
+ def qbt_set_file_priority(torrent_hash: str, file_ids: list[int], priority: int) -> None:
429
+ if not file_ids:
430
+ return
431
+ qbt_webapi_request(
432
+ "POST",
433
+ "/torrents/filePrio",
434
+ data={
435
+ "hash": torrent_hash,
436
+ "id": "|".join(str(file_id) for file_id in file_ids),
437
+ "priority": str(priority),
438
+ },
439
+ timeout=20,
440
+ )
441
+
442
+
443
+ def torrent_file_index(file_entry: dict, fallback: int) -> int:
444
+ for key in ("index", "id"):
445
+ value = file_entry.get(key)
446
+ if value is not None:
447
+ return int(value)
448
+ return fallback
449
+
450
+
451
+ def serialize_torrent_file(file_entry: dict, fallback_index: int) -> dict:
452
+ file_index = torrent_file_index(file_entry, fallback_index)
453
+ size = int(file_entry.get("size", 0) or 0)
454
+ priority = int(file_entry.get("priority", 1) or 0)
455
+ return {
456
+ "id": file_index,
457
+ "name": str(file_entry.get("name", "") or f"File {file_index + 1}"),
458
+ "size": format_size(size),
459
+ "size_bytes": size,
460
+ "priority": priority,
461
+ "selected": priority != 0,
462
+ }
463
+
464
+
465
+ def download_storage_usage():
466
+ return shutil.disk_usage(DOWNLOAD_PATH)
467
+
468
+
469
+ def storage_validation(required_bytes: int) -> dict:
470
+ disk = download_storage_usage()
471
+ available_bytes = int(disk.free)
472
+ required_bytes = max(0, int(required_bytes or 0))
473
+ ok = required_bytes <= available_bytes
474
+ return {
475
+ "storage_ok": ok,
476
+ "storage_required_bytes": required_bytes,
477
+ "storage_required": format_size(required_bytes),
478
+ "storage_available_bytes": available_bytes,
479
+ "storage_available": format_size(available_bytes),
480
+ "storage_warning": ""
481
+ if ok
482
+ else (
483
+ f"Storage tidak cukup. Butuh {format_size(required_bytes)}, "
484
+ f"tersedia {format_size(available_bytes)}. Hapus atau bersihkan file lama dulu."
485
+ ),
486
+ }
487
+
488
+
489
+ def ensure_storage_available(required_bytes: int) -> None:
490
+ validation = storage_validation(required_bytes)
491
+ if not validation["storage_ok"]:
492
+ raise InsufficientStorageError(validation["storage_warning"])
493
+
494
+
495
+ def selected_torrent_file_stats(torrent_hash: str, fallback_total_size: int) -> dict:
496
+ try:
497
+ files = qbt_torrent_files(torrent_hash)
498
+ except (QBittorrentWebAPIError, requests.RequestException, ValueError):
499
+ files = []
500
+
501
+ if not files:
502
+ return {
503
+ "selected_total_size": fallback_total_size,
504
+ "selected_downloaded": 0,
505
+ "selected_file_count": 0,
506
+ "file_count": 0,
507
+ "has_file_selection": False,
508
+ }
509
+
510
+ selected_files = [file_entry for file_entry in files if int(file_entry.get("priority", 0) or 0) > 0]
511
+ selected_total_size = sum(int(file_entry.get("size", 0) or 0) for file_entry in selected_files)
512
+ selected_downloaded = sum(
513
+ int((int(file_entry.get("size", 0) or 0) * float(file_entry.get("progress", 0) or 0)))
514
+ for file_entry in selected_files
515
+ )
516
+
517
+ return {
518
+ "selected_total_size": selected_total_size,
519
+ "selected_downloaded": min(selected_downloaded, selected_total_size),
520
+ "selected_file_count": len(selected_files),
521
+ "file_count": len(files),
522
+ "has_file_selection": len(files) > 1 and len(selected_files) < len(files),
523
+ }
524
+
525
+
526
+ def wait_for_torrent_files(torrent_hash: str, timeout_seconds: int = TORRENT_FILE_SELECTION_WAIT_SECONDS) -> list[dict]:
527
+ deadline = time.time() + timeout_seconds
528
+ while time.time() <= deadline:
529
+ files = qbt_torrent_files(torrent_hash)
530
+ if files:
531
+ return files
532
+ time.sleep(0.5)
533
+ return []
534
+
535
+
536
+ def build_file_selection_payload(torrent_hash: str, files: list[dict]) -> dict:
537
+ serialized_files = [serialize_torrent_file(file_entry, index) for index, file_entry in enumerate(files)]
538
+ selected_total_size = sum(int(file_entry.get("size_bytes", 0) or 0) for file_entry in serialized_files if file_entry.get("selected", True))
539
+ storage = storage_validation(selected_total_size)
540
+ selection_required = len(serialized_files) > 1
541
+ if selection_required:
542
+ qbt_pause_torrent(torrent_hash)
543
+ return {
544
+ "selection_required": True,
545
+ "selection_pending": False,
546
+ "torrent_hash": torrent_hash,
547
+ "files": serialized_files,
548
+ **storage,
549
+ "message": "Torrent berisi beberapa file. Pilih file yang ingin didownload.",
550
+ }
551
+
552
+ if not storage["storage_ok"]:
553
+ try:
554
+ qbt_delete_torrent(torrent_hash, delete_files=False)
555
+ except (QBittorrentWebAPIError, requests.RequestException):
556
+ pass
557
+ raise InsufficientStorageError(storage["storage_warning"])
558
+
559
+ qbt_resume_torrent(torrent_hash)
560
+ return {
561
+ "selection_required": False,
562
+ "selection_pending": False,
563
+ "torrent_hash": torrent_hash,
564
+ "files": serialized_files,
565
+ **storage,
566
+ "message": "Torrent ditambahkan dan download dimulai.",
567
+ }
568
+
569
+
570
+ def clear_torrent_status_message(torrent_hash: str) -> None:
571
+ state = load_monitor_state()
572
+ entry = state.setdefault("torrents", {}).setdefault(torrent_hash, {})
573
+ entry["last_progress_at"] = time.time()
574
+ entry["status_message"] = ""
575
+ save_monitor_state(state)
576
+
577
+
578
+ def add_magnet_and_confirm_task(magnet: str, torrent_hash: str) -> None:
579
+ try:
580
+ qbt_add_torrent_url(magnet, paused=False)
581
+ except (QBittorrentWebAPIError, requests.RequestException):
582
+ if not wait_for_torrent_task(torrent_hash):
583
+ raise
584
+ else:
585
+ wait_for_torrent_task(torrent_hash)
586
+
587
+
588
+ def format_size(value: int | None) -> str:
589
  if value in (None, 0):
590
  return "0 B"
591
 
 
790
  def serialize_torrent(torrent, state_entry: dict | None = None) -> dict:
791
  eta_value = getattr(torrent, "eta", None)
792
  raw_state = getattr(torrent, "state", "")
793
+ torrent_total_size = int(getattr(torrent, "total_size", 0) or 0)
794
  torrent_progress = float(getattr(torrent, "progress", 0) or 0)
795
  raw_torrent_dlspeed = int(getattr(torrent, "dlspeed", 0) or 0)
796
  torrent_upspeed = int(getattr(torrent, "upspeed", 0) or 0)
 
802
  int(getattr(torrent, "uploaded", 0) or 0),
803
  int(getattr(torrent, "uploaded_session", 0) or 0),
804
  )
805
+ selected_stats = selected_torrent_file_stats(getattr(torrent, "hash", ""), torrent_total_size)
806
+ display_total_size = int(selected_stats["selected_total_size"] or 0)
807
+ display_downloaded = int(selected_stats["selected_downloaded"] or 0)
808
+ if not selected_stats["file_count"]:
809
+ display_downloaded = torrent_downloaded
810
+ elif not selected_stats["has_file_selection"]:
811
+ display_downloaded = torrent_downloaded
812
  torrent_num_seeds, torrent_num_leechs = swarm_peer_counts(torrent)
813
  state_entry = state_entry or {}
814
  status_message = state_entry.get("status_message", "")
 
860
  "state": torrent.state,
861
  "state_label": effective_state_label(torrent, state_entry),
862
  "state_badge": effective_status_badge(torrent, state_entry),
863
+ "total_size": format_size(display_total_size),
864
+ "torrent_total_size": format_size(torrent_total_size),
865
+ "selected_file_count": selected_stats["selected_file_count"],
866
+ "file_count": selected_stats["file_count"],
867
+ "has_file_selection": selected_stats["has_file_selection"],
868
+ "downloaded": format_size(display_downloaded),
869
  "uploaded": format_size(torrent_uploaded),
870
  "ratio": f"{float(getattr(torrent, 'ratio', 0) or 0):.2f}",
871
  "dlspeed": badge_download_speed,
 
1327
  if cached and now - int(cached.get("fetched_at", 0)) < SYSTEM_INFO_CACHE_SECONDS:
1328
  snapshot = cached
1329
  else:
1330
+ disk = download_storage_usage()
1331
  memory = psutil.virtual_memory()
1332
  snapshot = {
1333
  "os": f"{platform.system()} {platform.release()}",
 
1337
  "ram_total": format_size(memory.total),
1338
  "ram_used": format_size(memory.used),
1339
  "ram_percent": f"{memory.percent:.0f}%",
1340
+ "storage_total": format_size(disk.total),
1341
+ "storage_used": format_size(disk.used),
1342
+ "storage_free": format_size(disk.free),
1343
+ "storage_percent": f"{(disk.used / disk.total) * 100:.0f}%" if disk.total else "0%",
1344
  "hostname": platform.node() or "-",
1345
  "fetched_at": now,
1346
  }
 
1438
  }
1439
 
1440
 
1441
+ def action_response(message: str, ok: bool = True, status_code: int = 200, **extra):
1442
+ payload = {"success": ok, "message": message}
1443
+ payload.update(extra)
1444
+ return jsonify(payload), status_code
1445
+
1446
+
1447
+ def torrent_selection_response(payload: dict):
1448
+ message = payload.get("message", "Torrent membutuhkan seleksi file.")
1449
+ extra = {key: value for key, value in payload.items() if key != "message"}
1450
+ return action_response(message, **extra)
1451
+
1452
+
1453
+ def wants_json_response() -> bool:
1454
+ accept = request.headers.get("Accept", "")
1455
+ requested_with = request.headers.get("X-Requested-With", "")
1456
  return "application/json" in accept or requested_with == "XMLHttpRequest"
1457
 
1458
 
 
1979
  return render_template("index.html", torrents=torrents, stats=stats, events=events, system_info=system_info)
1980
 
1981
 
1982
+ @app.route("/api/torrents", methods=["GET"])
1983
+ def torrents_api():
1984
  try:
1985
  torrents, payload = get_dashboard_data()
1986
  return jsonify(
 
1991
  "torrents": torrents,
1992
  }
1993
  )
1994
+ except (qbittorrentapi.APIConnectionError, qbittorrentapi.LoginFailed, qbittorrentapi.APIError) as exc:
1995
+ return jsonify({"success": False, "error": str(exc) or "Gagal mengambil data torrent."}), 503
1996
+
1997
+
1998
+ @app.route("/api/torrents/<torrent_hash>/files", methods=["GET"])
1999
+ def torrent_files_api(torrent_hash: str):
2000
+ try:
2001
+ files = qbt_torrent_files(torrent_hash)
2002
+ if not files:
2003
+ return jsonify(
2004
+ {
2005
+ "success": True,
2006
+ "metadata_ready": False,
2007
+ "selection_required": False,
2008
+ "selection_pending": True,
2009
+ "torrent_hash": torrent_hash,
2010
+ "files": [],
2011
+ "message": "Metadata torrent masih diambil. Menunggu daftar file...",
2012
+ }
2013
+ )
2014
+
2015
+ payload = build_file_selection_payload(torrent_hash, files)
2016
+ clear_torrent_status_message(torrent_hash)
2017
+ payload["success"] = True
2018
+ payload["metadata_ready"] = True
2019
+ return jsonify(payload)
2020
+ except InsufficientStorageError as exc:
2021
+ return action_response(str(exc), ok=False, status_code=507)
2022
+ except (QBittorrentWebAPIError, requests.RequestException, ValueError) as exc:
2023
+ return action_response(f"Gagal mengambil daftar file torrent: {exc}", ok=False, status_code=502)
2024
+
2025
+
2026
+ @app.route("/api/torrents/<torrent_hash>/files/selection", methods=["POST"])
2027
+ def apply_torrent_file_selection(torrent_hash: str):
2028
+ try:
2029
+ files = qbt_torrent_files(torrent_hash)
2030
+ if not files:
2031
+ return action_response("Metadata torrent belum siap. Coba lagi sebentar.", ok=False, status_code=409)
2032
+ if len(files) <= 1:
2033
+ required_bytes = sum(int(file_entry.get("size", 0) or 0) for file_entry in files)
2034
+ ensure_storage_available(required_bytes)
2035
+ qbt_resume_torrent(torrent_hash)
2036
+ clear_torrent_status_message(torrent_hash)
2037
+ return action_response("Torrent tidak memerlukan seleksi file.")
2038
+
2039
+ payload = request.get_json(silent=True) or {}
2040
+ raw_selected_ids = payload.get("selected_file_ids", [])
2041
+ if not isinstance(raw_selected_ids, list):
2042
+ return action_response("Format pilihan file tidak valid.", ok=False, status_code=400)
2043
+
2044
+ selected_ids = {int(file_id) for file_id in raw_selected_ids}
2045
+ all_ids = {torrent_file_index(file_entry, index) for index, file_entry in enumerate(files)}
2046
+ if not selected_ids:
2047
+ return action_response("Pilih minimal satu file untuk didownload.", ok=False, status_code=400)
2048
+ if not selected_ids.issubset(all_ids):
2049
+ return action_response("Pilihan file mengandung ID yang tidak valid.", ok=False, status_code=400)
2050
+
2051
+ selected_size = sum(
2052
+ int(file_entry.get("size", 0) or 0)
2053
+ for index, file_entry in enumerate(files)
2054
+ if torrent_file_index(file_entry, index) in selected_ids
2055
+ )
2056
+ ensure_storage_available(selected_size)
2057
+
2058
+ skipped_ids = sorted(all_ids - selected_ids)
2059
+ qbt_set_file_priority(torrent_hash, sorted(skipped_ids), 0)
2060
+ qbt_set_file_priority(torrent_hash, sorted(selected_ids), 1)
2061
+ qbt_resume_torrent(torrent_hash)
2062
+ clear_torrent_status_message(torrent_hash)
2063
+ return action_response("Seleksi file diterapkan dan torrent dimulai.")
2064
+ except InsufficientStorageError as exc:
2065
+ return action_response(str(exc), ok=False, status_code=507)
2066
+ except (QBittorrentWebAPIError, requests.RequestException, ValueError) as exc:
2067
+ return action_response(f"Gagal menerapkan seleksi file: {exc}", ok=False, status_code=502)
2068
+
2069
+
2070
+ @app.route("/api/system", methods=["GET"])
2071
+ def system_api():
2072
+ return jsonify({"success": True, "system": get_system_info()})
2073
 
2074
 
2075
  @app.route("/api/system/speedtest", methods=["POST"])
 
2094
  client.torrents_set_force_start(enable=False, torrent_hashes=torrent_hash)
2095
  except qbittorrentapi.APIError:
2096
  pass
2097
+ qbt_pause_torrent(torrent_hash)
2098
  state = load_monitor_state()
2099
  entry = state.setdefault("torrents", {}).setdefault(torrent_hash, {})
2100
  entry["status_message"] = ""
2101
  save_monitor_state(state)
2102
+ return action_response("Torrent dijeda.")
2103
  except qbittorrentapi.APIError as exc:
2104
  return action_response(f"Gagal pause torrent: {exc}", ok=False, status_code=400)
2105
 
 
2111
  return action_response(message, ok=ok, status_code=200 if ok else 400)
2112
  try:
2113
  client = get_client()
2114
+ qbt_resume_torrent(torrent_hash)
2115
  torrents = client.torrents_info(torrent_hashes=torrent_hash)
2116
  if torrents and float(getattr(torrents[0], "progress", 0) or 0) >= 1:
2117
  try:
 
2354
  return redirect(url_for("index"))
2355
 
2356
  try:
2357
+ torrent_hash = magnet_info_hash(magnet_or_error)
2358
+ add_magnet_and_confirm_task(magnet_or_error, torrent_hash)
2359
+ files = wait_for_torrent_files(torrent_hash)
2360
  if wants_json_response():
2361
+ if files:
2362
+ payload = build_file_selection_payload(torrent_hash, files)
2363
+ clear_torrent_status_message(torrent_hash)
2364
+ return torrent_selection_response(payload)
2365
+ return action_response(
2366
+ "Magnet link ditambahkan. Metadata masih diambil sebelum seleksi file.",
2367
+ selection_required=False,
2368
+ selection_pending=True,
2369
+ torrent_hash=torrent_hash,
2370
+ files=[],
2371
+ )
2372
+ qbt_resume_torrent(torrent_hash)
2373
  flash("Magnet link berhasil ditambahkan.", "success")
2374
+ except InsufficientStorageError as exc:
2375
+ if wants_json_response():
2376
+ return action_response(str(exc), ok=False, status_code=507)
2377
+ flash(str(exc), "error")
2378
+ except (QBittorrentWebAPIError, TorrentMetadataError, requests.RequestException) as exc:
2379
+ if wants_json_response():
2380
+ return action_response(f"Gagal menambahkan magnet link: {exc}", ok=False, status_code=400)
2381
+ flash(f"Gagal menambahkan magnet link: {exc}", "error")
2382
 
2383
  return redirect(url_for("index"))
2384
 
 
2398
  flash("File harus berekstensi .torrent.", "error")
2399
  return redirect(url_for("index"))
2400
 
2401
+ destination = UPLOAD_DIR / Path(torrent_file.filename).name
2402
+ torrent_file.save(destination)
2403
+
2404
+ try:
2405
+ torrent_hash = torrent_info_hash_from_bytes(destination.read_bytes())
2406
+ qbt_add_torrent_file(destination, paused=True)
2407
+ files = wait_for_torrent_files(torrent_hash)
2408
+ if wants_json_response():
2409
+ if files:
2410
+ payload = build_file_selection_payload(torrent_hash, files)
2411
+ clear_torrent_status_message(torrent_hash)
2412
+ return torrent_selection_response(payload)
2413
+ return action_response(
2414
+ "File torrent berhasil diunggah, tetapi daftar file belum siap.",
2415
+ selection_required=False,
2416
+ selection_pending=True,
2417
+ torrent_hash=torrent_hash,
2418
+ files=[],
2419
+ )
2420
+ qbt_resume_torrent(torrent_hash)
2421
+ flash("File torrent berhasil diunggah.", "success")
2422
+ except InsufficientStorageError as exc:
2423
+ if wants_json_response():
2424
+ return action_response(str(exc), ok=False, status_code=507)
2425
+ flash(str(exc), "error")
2426
+ except (QBittorrentWebAPIError, TorrentMetadataError, requests.RequestException) as exc:
2427
+ if wants_json_response():
2428
+ return action_response(f"Gagal menambahkan file torrent: {exc}", ok=False, status_code=400)
2429
+ flash(f"Gagal menambahkan file torrent: {exc}", "error")
2430
  finally:
2431
  destination.unlink(missing_ok=True)
2432
 
bot/__init__.py CHANGED
@@ -1 +1 @@
1
- """Telegram bot package for managing downloader tasks."""
 
1
+ """Telegram bot package for managing downloader tasks."""
bot/bot.py CHANGED
@@ -1,521 +1,521 @@
1
- import asyncio
2
- import os
3
- import re
4
- import time
5
- from pathlib import Path
6
- from urllib.parse import parse_qs, urlparse
7
-
8
- import qbittorrentapi
9
- from pyrogram import Client, filters
10
- from pyrogram.errors import FloodWait, MessageNotModified
11
- from pyrogram.types import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Message
12
-
13
- import aria2
14
- from app import (
15
- DOWNLOAD_PATH,
16
- PIXELDRAIN_API_KEY,
17
- STATE_FILE,
18
- STATE_LOCK,
19
- get_client,
20
- get_task_state_entry,
21
- is_aria2_task,
22
- load_monitor_state,
23
- save_monitor_state,
24
- serialize_torrent,
25
- start_gofile_upload_background,
26
- start_pixeldrain_upload_background,
27
- validate_magnet_link,
28
- )
29
-
30
-
31
- API_ID = int(os.getenv("TELEGRAM_API_ID", "2589472") or "0")
32
- API_HASH = os.getenv("TELEGRAM_API_HASH", "5243628014db9798d6775b330e542602")
33
- BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "6100847173:AAE1Ph_WWGEJhENvKKIzPhziO63cv3ruYKs")
34
- SESSION_NAME = os.getenv("TELEGRAM_BOT_SESSION", "torrent_web_bot")
35
- OWNER_IDS = {
36
- int(item.strip())
37
- for item in os.getenv("TELEGRAM_OWNER_IDS", "1487943213").split(",")
38
- if item.strip().isdigit()
39
- }
40
- PROGRESS_INTERVAL_SECONDS = max(2, int(os.getenv("TELEGRAM_PROGRESS_INTERVAL_SECONDS", "3") or "3"))
41
- PROGRESS_TIMEOUT_SECONDS = max(60, int(os.getenv("TELEGRAM_PROGRESS_TIMEOUT_SECONDS", "86400") or "86400"))
42
-
43
- bot = Client(SESSION_NAME, api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
44
-
45
-
46
- def is_authorized(message_or_query) -> bool:
47
- if not OWNER_IDS:
48
- return True
49
- user = getattr(message_or_query, "from_user", None)
50
- return bool(user and user.id in OWNER_IDS)
51
-
52
-
53
- def command_argument(message: Message) -> str:
54
- text = message.text or message.caption or ""
55
- parts = text.split(maxsplit=1)
56
- return parts[1].strip() if len(parts) > 1 else ""
57
-
58
-
59
- def extract_btih(magnet: str) -> str:
60
- parsed = urlparse(magnet)
61
- for value in parse_qs(parsed.query).get("xt", []):
62
- if value.lower().startswith("urn:btih:"):
63
- return value[9:]
64
- return ""
65
-
66
-
67
- def progress_bar(progress: int, width: int = 12) -> str:
68
- value = max(0, min(int(progress or 0), 100))
69
- filled = int((value / 100) * width)
70
- return "[" + "#" * filled + "-" * (width - filled) + "]"
71
-
72
-
73
- def task_snapshot(task_id: str) -> dict | None:
74
- state = load_monitor_state()
75
- if is_aria2_task(task_id):
76
- entry = state.get("aria2", {}).get(task_id)
77
- return aria2.serialize_task(entry) if entry else None
78
-
79
- client = get_client()
80
- torrents = client.torrents_info(torrent_hashes=task_id)
81
- if not torrents:
82
- return None
83
- return serialize_torrent(torrents[0], state.get("torrents", {}).get(task_id))
84
-
85
-
86
- def all_task_snapshots(limit: int = 8) -> list[dict]:
87
- state = load_monitor_state()
88
- client = get_client()
89
- raw_torrents = list(client.torrents_info(sort="added_on", reverse=True))
90
- torrent_items = [
91
- serialize_torrent(torrent, state.get("torrents", {}).get(torrent.hash))
92
- for torrent in raw_torrents
93
- ]
94
- aria2_items = [aria2.serialize_task(task) for task in state.get("aria2", {}).values()]
95
- items = sorted(torrent_items + aria2_items, key=lambda item: int(item.get("added_at", 0) or 0), reverse=True)
96
- return items[:limit]
97
-
98
-
99
- def add_magnet_task(magnet: str) -> tuple[str, str]:
100
- is_valid, value = validate_magnet_link(magnet)
101
- if not is_valid:
102
- raise ValueError(value)
103
-
104
- client = get_client()
105
- before = {torrent.hash for torrent in client.torrents_info()}
106
- client.torrents_add(urls=value, savepath=DOWNLOAD_PATH)
107
-
108
- btih = extract_btih(value)
109
- hash_candidates = []
110
- if re.fullmatch(r"[A-Fa-f0-9]{40}", btih or ""):
111
- hash_candidates = [btih.lower(), btih.upper()]
112
-
113
- deadline = time.time() + 20
114
- while time.time() < deadline:
115
- torrents = list(client.torrents_info(sort="added_on", reverse=True))
116
- by_hash = {torrent.hash: torrent for torrent in torrents}
117
- for candidate in hash_candidates:
118
- if candidate in by_hash:
119
- return candidate, by_hash[candidate].name
120
-
121
- new_hashes = [torrent.hash for torrent in torrents if torrent.hash not in before]
122
- if new_hashes:
123
- newest = by_hash[new_hashes[0]]
124
- return newest.hash, newest.name
125
- time.sleep(1)
126
-
127
- raise RuntimeError("Magnet ditambahkan, tetapi task belum muncul dari qBittorrent.")
128
-
129
-
130
- def add_aria2_task(url: str) -> tuple[str, str]:
131
- is_valid, value = aria2.validate_download_url(url)
132
- if not is_valid:
133
- raise ValueError(value)
134
- return aria2.start_download(value, DOWNLOAD_PATH, STATE_FILE, STATE_LOCK)
135
-
136
-
137
- def set_upload_state(task_id: str, provider: str, endpoint: str = "") -> dict:
138
- state = load_monitor_state()
139
- entry = get_task_state_entry(state, task_id)
140
- if entry.get("gofile_uploading"):
141
- raise RuntimeError("Upload file eksternal masih berjalan.")
142
- entry["gofile_uploading"] = True
143
- entry["gofile_progress"] = 0
144
- entry["gofile_speed"] = ""
145
- entry["gofile_eta_seconds"] = 0
146
- entry["gofile_cancel_requested"] = False
147
- entry["gofile_pid"] = 0
148
- entry["gofile_endpoint"] = endpoint
149
- entry["gofile_provider"] = provider
150
- entry["gofile_status"] = f"Sedang upload ke {provider}..."
151
- entry["status_message"] = ""
152
- save_monitor_state(state)
153
- return entry
154
-
155
-
156
- def start_remote_upload(task_id: str, provider: str, mode: str = "zip") -> str:
157
- if provider not in {"gofile", "pixeldrain"}:
158
- raise ValueError("Provider upload tidak valid.")
159
- if mode not in {"zip", "raw"}:
160
- raise ValueError("Mode upload tidak valid.")
161
-
162
- provider_name = "GoFile" if provider == "gofile" else "PixelDrain"
163
- if provider == "pixeldrain" and not PIXELDRAIN_API_KEY:
164
- raise RuntimeError("PIXELDRAIN_API_KEY belum diset.")
165
-
166
- if is_aria2_task(task_id):
167
- state = load_monitor_state()
168
- entry = state.get("aria2", {}).get(task_id)
169
- if not entry:
170
- raise RuntimeError("Tugas Aria2 tidak ditemukan.")
171
- file_path = Path(entry.get("file_path", "") or "")
172
- if not file_path.exists():
173
- raise RuntimeError("File Aria2 tidak ditemukan di storage.")
174
- set_upload_state(task_id, provider_name, "pixeldrain" if provider == "pixeldrain" else "")
175
- if provider == "gofile":
176
- start_gofile_upload_background(task_id, entry.get("name", file_path.name), file_path, mode="zip")
177
- else:
178
- start_pixeldrain_upload_background(task_id, entry.get("name", file_path.name), file_path, mode="zip")
179
- return f"Upload Aria2 ke {provider_name} dimulai."
180
-
181
- client = get_client()
182
- torrents = client.torrents_info(torrent_hashes=task_id)
183
- if not torrents:
184
- raise RuntimeError("Torrent tidak ditemukan.")
185
- torrent = torrents[0]
186
- if float(getattr(torrent, "progress", 0) or 0) < 1:
187
- raise RuntimeError("Upload hanya tersedia setelah download selesai.")
188
-
189
- content_path = Path(getattr(torrent, "content_path", "") or "")
190
- if not content_path.exists():
191
- raise RuntimeError("File hasil download tidak ditemukan di storage.")
192
- if mode == "raw" and not content_path.is_dir():
193
- raise RuntimeError("Mode raw hanya tersedia untuk folder.")
194
-
195
- state = load_monitor_state()
196
- entry = get_task_state_entry(state, task_id)
197
- if entry.get("gofile_uploading"):
198
- raise RuntimeError("Upload file eksternal masih berjalan.")
199
- entry["gofile_uploading"] = True
200
- entry["gofile_progress"] = 0
201
- entry["gofile_speed"] = ""
202
- entry["gofile_eta_seconds"] = 0
203
- entry["gofile_cancel_requested"] = False
204
- entry["gofile_pid"] = 0
205
- entry["gofile_endpoint"] = "pixeldrain" if provider == "pixeldrain" else ""
206
- entry["gofile_provider"] = provider_name
207
- entry["gofile_status"] = f"Sedang upload ke {provider_name}..."
208
- entry["pre_upload_state"] = getattr(torrent, "state", "") or ""
209
- entry["pre_upload_force_start"] = bool(getattr(torrent, "force_start", False))
210
- entry["status_message"] = ""
211
- save_monitor_state(state)
212
-
213
- if provider == "gofile":
214
- start_gofile_upload_background(task_id, torrent.name, content_path, mode=mode)
215
- else:
216
- start_pixeldrain_upload_background(task_id, torrent.name, content_path, mode=mode)
217
- return f"Upload ke {provider_name} dimulai."
218
-
219
-
220
- def pause_task(task_id: str) -> str:
221
- if is_aria2_task(task_id):
222
- ok, message = aria2.pause_task(task_id, STATE_FILE, STATE_LOCK)
223
- if not ok:
224
- raise RuntimeError(message)
225
- return message
226
-
227
- client = get_client()
228
- client.torrents_pause(torrent_hashes=task_id)
229
- return "Torrent dijeda."
230
-
231
-
232
- def resume_task(task_id: str) -> str:
233
- if is_aria2_task(task_id):
234
- ok, message = aria2.resume_task(task_id, STATE_FILE, STATE_LOCK)
235
- if not ok:
236
- raise RuntimeError(message)
237
- return message
238
-
239
- client = get_client()
240
- client.torrents_resume(torrent_hashes=task_id)
241
- return "Torrent dilanjutkan."
242
-
243
-
244
- def delete_task(task_id: str, delete_files: bool = False) -> str:
245
- if is_aria2_task(task_id):
246
- ok, message = aria2.delete_task(task_id, STATE_FILE, STATE_LOCK, delete_files)
247
- if not ok:
248
- raise RuntimeError(message)
249
- return message
250
-
251
- client = get_client()
252
- client.torrents_delete(delete_files=delete_files, torrent_hashes=task_id)
253
- state = load_monitor_state()
254
- state.setdefault("torrents", {}).pop(task_id, None)
255
- save_monitor_state(state)
256
- return "Torrent dan file hasil download dihapus." if delete_files else "Torrent dihapus dari daftar."
257
-
258
-
259
- def format_task_status(task: dict) -> str:
260
- progress = int(task.get("progress", 0) or 0)
261
- lines = [
262
- f"Task: {task.get('name') or '-'}",
263
- f"ID: {task.get('hash') or '-'}",
264
- f"Type: {task.get('task_kind') or 'torrent'}",
265
- f"Status: {task.get('state_label') or '-'}",
266
- f"Progress: {progress_bar(progress)} {progress}%",
267
- f"Size: {task.get('downloaded') or '-'} / {task.get('total_size') or '-'}",
268
- f"Speed: Down {task.get('dlspeed') or '-'} | Up {task.get('upspeed') or '-'}",
269
- f"ETA: {task.get('eta') or '-'}",
270
- ]
271
- if task.get("gofile_uploading"):
272
- lines.extend(
273
- [
274
- "",
275
- f"Remote: {task.get('upload_provider') or '-'}",
276
- f"Upload status: {task.get('gofile_status') or '-'}",
277
- f"Upload speed: {task.get('gofile_speed') or '-'}",
278
- f"Upload ETA: {task.get('gofile_eta') or '-'}",
279
- ]
280
- )
281
- if task.get("gofile_link"):
282
- lines.extend(["", f"Remote link: {task.get('gofile_link')}"])
283
- if task.get("status_message"):
284
- lines.extend(["", f"Info: {task.get('status_message')}"])
285
- return "\n".join(lines)
286
-
287
-
288
- def task_keyboard(task: dict | None) -> InlineKeyboardMarkup | None:
289
- if not task:
290
- return None
291
- task_id = task.get("hash", "")
292
- rows = []
293
- if task.get("can_pause"):
294
- rows.append([InlineKeyboardButton("Pause", callback_data=f"pause:{task_id}")])
295
- if task.get("can_resume"):
296
- rows.append([InlineKeyboardButton("Resume", callback_data=f"resume:{task_id}")])
297
- if task.get("can_gofile_upload") or task.get("can_pixeldrain_upload"):
298
- upload_row = []
299
- if task.get("can_gofile_upload"):
300
- upload_row.append(InlineKeyboardButton("GoFile", callback_data=f"upload:gofile:zip:{task_id}"))
301
- if task.get("can_pixeldrain_upload"):
302
- upload_row.append(InlineKeyboardButton("PixelDrain", callback_data=f"upload:pixeldrain:zip:{task_id}"))
303
- rows.append(upload_row)
304
- if task.get("can_raw_gofile_upload") or task.get("can_raw_pixeldrain_upload"):
305
- raw_row = []
306
- if task.get("can_raw_gofile_upload"):
307
- raw_row.append(InlineKeyboardButton("GoFile Raw", callback_data=f"upload:gofile:raw:{task_id}"))
308
- if task.get("can_raw_pixeldrain_upload"):
309
- raw_row.append(InlineKeyboardButton("Pixel Raw", callback_data=f"upload:pixeldrain:raw:{task_id}"))
310
- rows.append(raw_row)
311
- rows.append(
312
- [
313
- InlineKeyboardButton("Refresh", callback_data=f"refresh:{task_id}"),
314
- InlineKeyboardButton("Delete", callback_data=f"delete:{task_id}"),
315
- InlineKeyboardButton("Delete Files", callback_data=f"delete_files:{task_id}"),
316
- ]
317
- )
318
- return InlineKeyboardMarkup(rows)
319
-
320
-
321
- def should_stop_monitoring(task: dict | None) -> bool:
322
- if not task:
323
- return True
324
- if task.get("gofile_uploading"):
325
- return False
326
- state = str(task.get("state") or "")
327
- progress = int(task.get("progress", 0) or 0)
328
- return progress >= 100 or state in {"complete", "error", "cancelled"}
329
-
330
-
331
- async def safe_edit(message: Message, text: str, reply_markup=None) -> None:
332
- try:
333
- await message.edit_text(text, reply_markup=reply_markup, disable_web_page_preview=True)
334
- except MessageNotModified:
335
- return
336
- except FloodWait as exc:
337
- await asyncio.sleep(int(exc.value) + 1)
338
-
339
-
340
- async def monitor_task_message(message: Message, task_id: str) -> None:
341
- started = time.time()
342
- while True:
343
- try:
344
- task = await asyncio.to_thread(task_snapshot, task_id)
345
- text = format_task_status(task) if task else "Task tidak ditemukan atau sudah dihapus."
346
- await safe_edit(message, text, reply_markup=task_keyboard(task))
347
- if should_stop_monitoring(task):
348
- return
349
- except Exception as exc:
350
- await safe_edit(message, f"Gagal membaca status task: {exc}")
351
- return
352
-
353
- if time.time() - started > PROGRESS_TIMEOUT_SECONDS:
354
- return
355
- await asyncio.sleep(PROGRESS_INTERVAL_SECONDS)
356
-
357
-
358
- async def require_access(message: Message) -> bool:
359
- if is_authorized(message):
360
- return True
361
- await message.reply_text("Akses ditolak.")
362
- return False
363
-
364
-
365
- @bot.on_message(filters.command(["start", "help"]))
366
- async def help_command(_, message: Message):
367
- if not await require_access(message):
368
- return
369
- await message.reply_text(
370
- "\n".join(
371
- [
372
- "Torrent Web Bot siap.",
373
- "",
374
- "Command:",
375
- "/qm <magnet> - tambah magnet link",
376
- "/qbdown <magnet> - alias tambah magnet link",
377
- "/aria2 <url> - direct download via Aria2",
378
- "/tasks - lihat task terbaru",
379
- "/status <task_id> - pantau task tertentu",
380
- ]
381
- )
382
- )
383
-
384
-
385
- @bot.on_message(filters.command(["qm", "qbdown"]))
386
- async def magnet_command(_, message: Message):
387
- if not await require_access(message):
388
- return
389
- magnet = command_argument(message)
390
- if not magnet:
391
- await message.reply_text("Format: /qm magnet:?xt=urn:btih:...")
392
- return
393
-
394
- status_message = await message.reply_text("Menambahkan magnet ke qBittorrent...")
395
- try:
396
- task_id, name = await asyncio.to_thread(add_magnet_task, magnet)
397
- await safe_edit(status_message, f"Magnet ditambahkan: {name}\nMenunggu status download...")
398
- await monitor_task_message(status_message, task_id)
399
- except Exception as exc:
400
- await safe_edit(status_message, f"Gagal menambahkan magnet: {exc}")
401
-
402
-
403
- @bot.on_message(filters.command(["aria2", "direct"]))
404
- async def aria2_command(_, message: Message):
405
- if not await require_access(message):
406
- return
407
- url = command_argument(message)
408
- if not url:
409
- await message.reply_text("Format: /aria2 https://example.com/file.iso")
410
- return
411
-
412
- status_message = await message.reply_text("Memulai Aria2 download...")
413
- try:
414
- task_id, filename = await asyncio.to_thread(add_aria2_task, url)
415
- await safe_edit(status_message, f"Aria2 download dimulai: {filename}")
416
- await monitor_task_message(status_message, task_id)
417
- except Exception as exc:
418
- await safe_edit(status_message, f"Gagal memulai Aria2: {exc}")
419
-
420
-
421
- @bot.on_message(filters.command("tasks"))
422
- async def tasks_command(_, message: Message):
423
- if not await require_access(message):
424
- return
425
- try:
426
- tasks = await asyncio.to_thread(all_task_snapshots)
427
- except Exception as exc:
428
- await message.reply_text(f"Gagal membaca task: {exc}")
429
- return
430
- if not tasks:
431
- await message.reply_text("Belum ada task aktif.")
432
- return
433
- lines = ["Task terbaru:"]
434
- for task in tasks:
435
- lines.append(f"- {task.get('hash')}: {task.get('name')} ({task.get('progress')}%, {task.get('state_label')})")
436
- await message.reply_text("\n".join(lines))
437
-
438
-
439
- @bot.on_message(filters.command("status"))
440
- async def status_command(_, message: Message):
441
- if not await require_access(message):
442
- return
443
- task_id = command_argument(message)
444
- if not task_id:
445
- await message.reply_text("Format: /status <task_id>")
446
- return
447
- reply = await message.reply_text("Membaca status task...")
448
- await monitor_task_message(reply, task_id)
449
-
450
-
451
- @bot.on_callback_query()
452
- async def callback_handler(_, query: CallbackQuery):
453
- if not is_authorized(query):
454
- await query.answer("Akses ditolak.", show_alert=True)
455
- return
456
-
457
- data = query.data or ""
458
- try:
459
- if data.startswith("upload:"):
460
- _, provider, mode, task_id = data.split(":", 3)
461
- message = await asyncio.to_thread(start_remote_upload, task_id, provider, mode)
462
- await query.answer(message)
463
- await monitor_task_message(query.message, task_id)
464
- return
465
-
466
- if data.startswith("pause:"):
467
- task_id = data.split(":", 1)[1]
468
- await query.answer(await asyncio.to_thread(pause_task, task_id))
469
- await monitor_task_message(query.message, task_id)
470
- return
471
-
472
- if data.startswith("resume:"):
473
- task_id = data.split(":", 1)[1]
474
- await query.answer(await asyncio.to_thread(resume_task, task_id))
475
- await monitor_task_message(query.message, task_id)
476
- return
477
-
478
- if data.startswith("delete_files:"):
479
- task_id = data.split(":", 1)[1]
480
- message = await asyncio.to_thread(delete_task, task_id, True)
481
- await query.answer(message)
482
- await safe_edit(query.message, message)
483
- return
484
-
485
- if data.startswith("delete:"):
486
- task_id = data.split(":", 1)[1]
487
- message = await asyncio.to_thread(delete_task, task_id, False)
488
- await query.answer(message)
489
- await safe_edit(query.message, message)
490
- return
491
-
492
- if data.startswith("refresh:"):
493
- task_id = data.split(":", 1)[1]
494
- task = await asyncio.to_thread(task_snapshot, task_id)
495
- await query.answer("Status diperbarui.")
496
- await safe_edit(query.message, format_task_status(task) if task else "Task tidak ditemukan.", task_keyboard(task))
497
- return
498
-
499
- await query.answer("Aksi tidak dikenal.", show_alert=True)
500
- except Exception as exc:
501
- await query.answer(str(exc)[:200], show_alert=True)
502
-
503
-
504
- def main() -> None:
505
- missing = []
506
- if not API_ID:
507
- missing.append("TELEGRAM_API_ID")
508
- if not API_HASH:
509
- missing.append("TELEGRAM_API_HASH")
510
- if not BOT_TOKEN:
511
- missing.append("TELEGRAM_BOT_TOKEN")
512
- if missing:
513
- raise RuntimeError(f"Env Telegram belum lengkap: {', '.join(missing)}")
514
-
515
- print("Starting Telegram bot...", flush=True)
516
- print(f"OWNER_IDS={OWNER_IDS}", flush=True)
517
- bot.run()
518
-
519
-
520
- if __name__ == "__main__":
521
- main()
 
1
+ import asyncio
2
+ import os
3
+ import re
4
+ import time
5
+ from pathlib import Path
6
+ from urllib.parse import parse_qs, urlparse
7
+
8
+ import qbittorrentapi
9
+ from pyrogram import Client, filters
10
+ from pyrogram.errors import FloodWait, MessageNotModified
11
+ from pyrogram.types import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Message
12
+
13
+ import aria2
14
+ from app import (
15
+ DOWNLOAD_PATH,
16
+ PIXELDRAIN_API_KEY,
17
+ STATE_FILE,
18
+ STATE_LOCK,
19
+ get_client,
20
+ get_task_state_entry,
21
+ is_aria2_task,
22
+ load_monitor_state,
23
+ save_monitor_state,
24
+ serialize_torrent,
25
+ start_gofile_upload_background,
26
+ start_pixeldrain_upload_background,
27
+ validate_magnet_link,
28
+ )
29
+
30
+
31
+ API_ID = int(os.getenv("TELEGRAM_API_ID", "2589472") or "0")
32
+ API_HASH = os.getenv("TELEGRAM_API_HASH", "5243628014db9798d6775b330e542602")
33
+ BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "6100847173:AAE1Ph_WWGEJhENvKKIzPhziO63cv3ruYKs")
34
+ SESSION_NAME = os.getenv("TELEGRAM_BOT_SESSION", "torrent_web_bot")
35
+ OWNER_IDS = {
36
+ int(item.strip())
37
+ for item in os.getenv("TELEGRAM_OWNER_IDS", "1487943213").split(",")
38
+ if item.strip().isdigit()
39
+ }
40
+ PROGRESS_INTERVAL_SECONDS = max(2, int(os.getenv("TELEGRAM_PROGRESS_INTERVAL_SECONDS", "3") or "3"))
41
+ PROGRESS_TIMEOUT_SECONDS = max(60, int(os.getenv("TELEGRAM_PROGRESS_TIMEOUT_SECONDS", "86400") or "86400"))
42
+
43
+ bot = Client(SESSION_NAME, api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
44
+
45
+
46
+ def is_authorized(message_or_query) -> bool:
47
+ if not OWNER_IDS:
48
+ return True
49
+ user = getattr(message_or_query, "from_user", None)
50
+ return bool(user and user.id in OWNER_IDS)
51
+
52
+
53
+ def command_argument(message: Message) -> str:
54
+ text = message.text or message.caption or ""
55
+ parts = text.split(maxsplit=1)
56
+ return parts[1].strip() if len(parts) > 1 else ""
57
+
58
+
59
+ def extract_btih(magnet: str) -> str:
60
+ parsed = urlparse(magnet)
61
+ for value in parse_qs(parsed.query).get("xt", []):
62
+ if value.lower().startswith("urn:btih:"):
63
+ return value[9:]
64
+ return ""
65
+
66
+
67
+ def progress_bar(progress: int, width: int = 12) -> str:
68
+ value = max(0, min(int(progress or 0), 100))
69
+ filled = int((value / 100) * width)
70
+ return "[" + "#" * filled + "-" * (width - filled) + "]"
71
+
72
+
73
+ def task_snapshot(task_id: str) -> dict | None:
74
+ state = load_monitor_state()
75
+ if is_aria2_task(task_id):
76
+ entry = state.get("aria2", {}).get(task_id)
77
+ return aria2.serialize_task(entry) if entry else None
78
+
79
+ client = get_client()
80
+ torrents = client.torrents_info(torrent_hashes=task_id)
81
+ if not torrents:
82
+ return None
83
+ return serialize_torrent(torrents[0], state.get("torrents", {}).get(task_id))
84
+
85
+
86
+ def all_task_snapshots(limit: int = 8) -> list[dict]:
87
+ state = load_monitor_state()
88
+ client = get_client()
89
+ raw_torrents = list(client.torrents_info(sort="added_on", reverse=True))
90
+ torrent_items = [
91
+ serialize_torrent(torrent, state.get("torrents", {}).get(torrent.hash))
92
+ for torrent in raw_torrents
93
+ ]
94
+ aria2_items = [aria2.serialize_task(task) for task in state.get("aria2", {}).values()]
95
+ items = sorted(torrent_items + aria2_items, key=lambda item: int(item.get("added_at", 0) or 0), reverse=True)
96
+ return items[:limit]
97
+
98
+
99
+ def add_magnet_task(magnet: str) -> tuple[str, str]:
100
+ is_valid, value = validate_magnet_link(magnet)
101
+ if not is_valid:
102
+ raise ValueError(value)
103
+
104
+ client = get_client()
105
+ before = {torrent.hash for torrent in client.torrents_info()}
106
+ client.torrents_add(urls=value, savepath=DOWNLOAD_PATH)
107
+
108
+ btih = extract_btih(value)
109
+ hash_candidates = []
110
+ if re.fullmatch(r"[A-Fa-f0-9]{40}", btih or ""):
111
+ hash_candidates = [btih.lower(), btih.upper()]
112
+
113
+ deadline = time.time() + 20
114
+ while time.time() < deadline:
115
+ torrents = list(client.torrents_info(sort="added_on", reverse=True))
116
+ by_hash = {torrent.hash: torrent for torrent in torrents}
117
+ for candidate in hash_candidates:
118
+ if candidate in by_hash:
119
+ return candidate, by_hash[candidate].name
120
+
121
+ new_hashes = [torrent.hash for torrent in torrents if torrent.hash not in before]
122
+ if new_hashes:
123
+ newest = by_hash[new_hashes[0]]
124
+ return newest.hash, newest.name
125
+ time.sleep(1)
126
+
127
+ raise RuntimeError("Magnet ditambahkan, tetapi task belum muncul dari qBittorrent.")
128
+
129
+
130
+ def add_aria2_task(url: str) -> tuple[str, str]:
131
+ is_valid, value = aria2.validate_download_url(url)
132
+ if not is_valid:
133
+ raise ValueError(value)
134
+ return aria2.start_download(value, DOWNLOAD_PATH, STATE_FILE, STATE_LOCK)
135
+
136
+
137
+ def set_upload_state(task_id: str, provider: str, endpoint: str = "") -> dict:
138
+ state = load_monitor_state()
139
+ entry = get_task_state_entry(state, task_id)
140
+ if entry.get("gofile_uploading"):
141
+ raise RuntimeError("Upload file eksternal masih berjalan.")
142
+ entry["gofile_uploading"] = True
143
+ entry["gofile_progress"] = 0
144
+ entry["gofile_speed"] = ""
145
+ entry["gofile_eta_seconds"] = 0
146
+ entry["gofile_cancel_requested"] = False
147
+ entry["gofile_pid"] = 0
148
+ entry["gofile_endpoint"] = endpoint
149
+ entry["gofile_provider"] = provider
150
+ entry["gofile_status"] = f"Sedang upload ke {provider}..."
151
+ entry["status_message"] = ""
152
+ save_monitor_state(state)
153
+ return entry
154
+
155
+
156
+ def start_remote_upload(task_id: str, provider: str, mode: str = "zip") -> str:
157
+ if provider not in {"gofile", "pixeldrain"}:
158
+ raise ValueError("Provider upload tidak valid.")
159
+ if mode not in {"zip", "raw"}:
160
+ raise ValueError("Mode upload tidak valid.")
161
+
162
+ provider_name = "GoFile" if provider == "gofile" else "PixelDrain"
163
+ if provider == "pixeldrain" and not PIXELDRAIN_API_KEY:
164
+ raise RuntimeError("PIXELDRAIN_API_KEY belum diset.")
165
+
166
+ if is_aria2_task(task_id):
167
+ state = load_monitor_state()
168
+ entry = state.get("aria2", {}).get(task_id)
169
+ if not entry:
170
+ raise RuntimeError("Tugas Aria2 tidak ditemukan.")
171
+ file_path = Path(entry.get("file_path", "") or "")
172
+ if not file_path.exists():
173
+ raise RuntimeError("File Aria2 tidak ditemukan di storage.")
174
+ set_upload_state(task_id, provider_name, "pixeldrain" if provider == "pixeldrain" else "")
175
+ if provider == "gofile":
176
+ start_gofile_upload_background(task_id, entry.get("name", file_path.name), file_path, mode="zip")
177
+ else:
178
+ start_pixeldrain_upload_background(task_id, entry.get("name", file_path.name), file_path, mode="zip")
179
+ return f"Upload Aria2 ke {provider_name} dimulai."
180
+
181
+ client = get_client()
182
+ torrents = client.torrents_info(torrent_hashes=task_id)
183
+ if not torrents:
184
+ raise RuntimeError("Torrent tidak ditemukan.")
185
+ torrent = torrents[0]
186
+ if float(getattr(torrent, "progress", 0) or 0) < 1:
187
+ raise RuntimeError("Upload hanya tersedia setelah download selesai.")
188
+
189
+ content_path = Path(getattr(torrent, "content_path", "") or "")
190
+ if not content_path.exists():
191
+ raise RuntimeError("File hasil download tidak ditemukan di storage.")
192
+ if mode == "raw" and not content_path.is_dir():
193
+ raise RuntimeError("Mode raw hanya tersedia untuk folder.")
194
+
195
+ state = load_monitor_state()
196
+ entry = get_task_state_entry(state, task_id)
197
+ if entry.get("gofile_uploading"):
198
+ raise RuntimeError("Upload file eksternal masih berjalan.")
199
+ entry["gofile_uploading"] = True
200
+ entry["gofile_progress"] = 0
201
+ entry["gofile_speed"] = ""
202
+ entry["gofile_eta_seconds"] = 0
203
+ entry["gofile_cancel_requested"] = False
204
+ entry["gofile_pid"] = 0
205
+ entry["gofile_endpoint"] = "pixeldrain" if provider == "pixeldrain" else ""
206
+ entry["gofile_provider"] = provider_name
207
+ entry["gofile_status"] = f"Sedang upload ke {provider_name}..."
208
+ entry["pre_upload_state"] = getattr(torrent, "state", "") or ""
209
+ entry["pre_upload_force_start"] = bool(getattr(torrent, "force_start", False))
210
+ entry["status_message"] = ""
211
+ save_monitor_state(state)
212
+
213
+ if provider == "gofile":
214
+ start_gofile_upload_background(task_id, torrent.name, content_path, mode=mode)
215
+ else:
216
+ start_pixeldrain_upload_background(task_id, torrent.name, content_path, mode=mode)
217
+ return f"Upload ke {provider_name} dimulai."
218
+
219
+
220
+ def pause_task(task_id: str) -> str:
221
+ if is_aria2_task(task_id):
222
+ ok, message = aria2.pause_task(task_id, STATE_FILE, STATE_LOCK)
223
+ if not ok:
224
+ raise RuntimeError(message)
225
+ return message
226
+
227
+ client = get_client()
228
+ client.torrents_pause(torrent_hashes=task_id)
229
+ return "Torrent dijeda."
230
+
231
+
232
+ def resume_task(task_id: str) -> str:
233
+ if is_aria2_task(task_id):
234
+ ok, message = aria2.resume_task(task_id, STATE_FILE, STATE_LOCK)
235
+ if not ok:
236
+ raise RuntimeError(message)
237
+ return message
238
+
239
+ client = get_client()
240
+ client.torrents_resume(torrent_hashes=task_id)
241
+ return "Torrent dilanjutkan."
242
+
243
+
244
+ def delete_task(task_id: str, delete_files: bool = False) -> str:
245
+ if is_aria2_task(task_id):
246
+ ok, message = aria2.delete_task(task_id, STATE_FILE, STATE_LOCK, delete_files)
247
+ if not ok:
248
+ raise RuntimeError(message)
249
+ return message
250
+
251
+ client = get_client()
252
+ client.torrents_delete(delete_files=delete_files, torrent_hashes=task_id)
253
+ state = load_monitor_state()
254
+ state.setdefault("torrents", {}).pop(task_id, None)
255
+ save_monitor_state(state)
256
+ return "Torrent dan file hasil download dihapus." if delete_files else "Torrent dihapus dari daftar."
257
+
258
+
259
+ def format_task_status(task: dict) -> str:
260
+ progress = int(task.get("progress", 0) or 0)
261
+ lines = [
262
+ f"Task: {task.get('name') or '-'}",
263
+ f"ID: {task.get('hash') or '-'}",
264
+ f"Type: {task.get('task_kind') or 'torrent'}",
265
+ f"Status: {task.get('state_label') or '-'}",
266
+ f"Progress: {progress_bar(progress)} {progress}%",
267
+ f"Size: {task.get('downloaded') or '-'} / {task.get('total_size') or '-'}",
268
+ f"Speed: Down {task.get('dlspeed') or '-'} | Up {task.get('upspeed') or '-'}",
269
+ f"ETA: {task.get('eta') or '-'}",
270
+ ]
271
+ if task.get("gofile_uploading"):
272
+ lines.extend(
273
+ [
274
+ "",
275
+ f"Remote: {task.get('upload_provider') or '-'}",
276
+ f"Upload status: {task.get('gofile_status') or '-'}",
277
+ f"Upload speed: {task.get('gofile_speed') or '-'}",
278
+ f"Upload ETA: {task.get('gofile_eta') or '-'}",
279
+ ]
280
+ )
281
+ if task.get("gofile_link"):
282
+ lines.extend(["", f"Remote link: {task.get('gofile_link')}"])
283
+ if task.get("status_message"):
284
+ lines.extend(["", f"Info: {task.get('status_message')}"])
285
+ return "\n".join(lines)
286
+
287
+
288
+ def task_keyboard(task: dict | None) -> InlineKeyboardMarkup | None:
289
+ if not task:
290
+ return None
291
+ task_id = task.get("hash", "")
292
+ rows = []
293
+ if task.get("can_pause"):
294
+ rows.append([InlineKeyboardButton("Pause", callback_data=f"pause:{task_id}")])
295
+ if task.get("can_resume"):
296
+ rows.append([InlineKeyboardButton("Resume", callback_data=f"resume:{task_id}")])
297
+ if task.get("can_gofile_upload") or task.get("can_pixeldrain_upload"):
298
+ upload_row = []
299
+ if task.get("can_gofile_upload"):
300
+ upload_row.append(InlineKeyboardButton("GoFile", callback_data=f"upload:gofile:zip:{task_id}"))
301
+ if task.get("can_pixeldrain_upload"):
302
+ upload_row.append(InlineKeyboardButton("PixelDrain", callback_data=f"upload:pixeldrain:zip:{task_id}"))
303
+ rows.append(upload_row)
304
+ if task.get("can_raw_gofile_upload") or task.get("can_raw_pixeldrain_upload"):
305
+ raw_row = []
306
+ if task.get("can_raw_gofile_upload"):
307
+ raw_row.append(InlineKeyboardButton("GoFile Raw", callback_data=f"upload:gofile:raw:{task_id}"))
308
+ if task.get("can_raw_pixeldrain_upload"):
309
+ raw_row.append(InlineKeyboardButton("Pixel Raw", callback_data=f"upload:pixeldrain:raw:{task_id}"))
310
+ rows.append(raw_row)
311
+ rows.append(
312
+ [
313
+ InlineKeyboardButton("Refresh", callback_data=f"refresh:{task_id}"),
314
+ InlineKeyboardButton("Delete", callback_data=f"delete:{task_id}"),
315
+ InlineKeyboardButton("Delete Files", callback_data=f"delete_files:{task_id}"),
316
+ ]
317
+ )
318
+ return InlineKeyboardMarkup(rows)
319
+
320
+
321
+ def should_stop_monitoring(task: dict | None) -> bool:
322
+ if not task:
323
+ return True
324
+ if task.get("gofile_uploading"):
325
+ return False
326
+ state = str(task.get("state") or "")
327
+ progress = int(task.get("progress", 0) or 0)
328
+ return progress >= 100 or state in {"complete", "error", "cancelled"}
329
+
330
+
331
+ async def safe_edit(message: Message, text: str, reply_markup=None) -> None:
332
+ try:
333
+ await message.edit_text(text, reply_markup=reply_markup, disable_web_page_preview=True)
334
+ except MessageNotModified:
335
+ return
336
+ except FloodWait as exc:
337
+ await asyncio.sleep(int(exc.value) + 1)
338
+
339
+
340
+ async def monitor_task_message(message: Message, task_id: str) -> None:
341
+ started = time.time()
342
+ while True:
343
+ try:
344
+ task = await asyncio.to_thread(task_snapshot, task_id)
345
+ text = format_task_status(task) if task else "Task tidak ditemukan atau sudah dihapus."
346
+ await safe_edit(message, text, reply_markup=task_keyboard(task))
347
+ if should_stop_monitoring(task):
348
+ return
349
+ except Exception as exc:
350
+ await safe_edit(message, f"Gagal membaca status task: {exc}")
351
+ return
352
+
353
+ if time.time() - started > PROGRESS_TIMEOUT_SECONDS:
354
+ return
355
+ await asyncio.sleep(PROGRESS_INTERVAL_SECONDS)
356
+
357
+
358
+ async def require_access(message: Message) -> bool:
359
+ if is_authorized(message):
360
+ return True
361
+ await message.reply_text("Akses ditolak.")
362
+ return False
363
+
364
+
365
+ @bot.on_message(filters.command(["start", "help"]))
366
+ async def help_command(_, message: Message):
367
+ if not await require_access(message):
368
+ return
369
+ await message.reply_text(
370
+ "\n".join(
371
+ [
372
+ "Torrent Web Bot siap.",
373
+ "",
374
+ "Command:",
375
+ "/qm <magnet> - tambah magnet link",
376
+ "/qbdown <magnet> - alias tambah magnet link",
377
+ "/aria2 <url> - direct download via Aria2",
378
+ "/tasks - lihat task terbaru",
379
+ "/status <task_id> - pantau task tertentu",
380
+ ]
381
+ )
382
+ )
383
+
384
+
385
+ @bot.on_message(filters.command(["qm", "qbdown"]))
386
+ async def magnet_command(_, message: Message):
387
+ if not await require_access(message):
388
+ return
389
+ magnet = command_argument(message)
390
+ if not magnet:
391
+ await message.reply_text("Format: /qm magnet:?xt=urn:btih:...")
392
+ return
393
+
394
+ status_message = await message.reply_text("Menambahkan magnet ke qBittorrent...")
395
+ try:
396
+ task_id, name = await asyncio.to_thread(add_magnet_task, magnet)
397
+ await safe_edit(status_message, f"Magnet ditambahkan: {name}\nMenunggu status download...")
398
+ await monitor_task_message(status_message, task_id)
399
+ except Exception as exc:
400
+ await safe_edit(status_message, f"Gagal menambahkan magnet: {exc}")
401
+
402
+
403
+ @bot.on_message(filters.command(["aria2", "direct"]))
404
+ async def aria2_command(_, message: Message):
405
+ if not await require_access(message):
406
+ return
407
+ url = command_argument(message)
408
+ if not url:
409
+ await message.reply_text("Format: /aria2 https://example.com/file.iso")
410
+ return
411
+
412
+ status_message = await message.reply_text("Memulai Aria2 download...")
413
+ try:
414
+ task_id, filename = await asyncio.to_thread(add_aria2_task, url)
415
+ await safe_edit(status_message, f"Aria2 download dimulai: {filename}")
416
+ await monitor_task_message(status_message, task_id)
417
+ except Exception as exc:
418
+ await safe_edit(status_message, f"Gagal memulai Aria2: {exc}")
419
+
420
+
421
+ @bot.on_message(filters.command("tasks"))
422
+ async def tasks_command(_, message: Message):
423
+ if not await require_access(message):
424
+ return
425
+ try:
426
+ tasks = await asyncio.to_thread(all_task_snapshots)
427
+ except Exception as exc:
428
+ await message.reply_text(f"Gagal membaca task: {exc}")
429
+ return
430
+ if not tasks:
431
+ await message.reply_text("Belum ada task aktif.")
432
+ return
433
+ lines = ["Task terbaru:"]
434
+ for task in tasks:
435
+ lines.append(f"- {task.get('hash')}: {task.get('name')} ({task.get('progress')}%, {task.get('state_label')})")
436
+ await message.reply_text("\n".join(lines))
437
+
438
+
439
+ @bot.on_message(filters.command("status"))
440
+ async def status_command(_, message: Message):
441
+ if not await require_access(message):
442
+ return
443
+ task_id = command_argument(message)
444
+ if not task_id:
445
+ await message.reply_text("Format: /status <task_id>")
446
+ return
447
+ reply = await message.reply_text("Membaca status task...")
448
+ await monitor_task_message(reply, task_id)
449
+
450
+
451
+ @bot.on_callback_query()
452
+ async def callback_handler(_, query: CallbackQuery):
453
+ if not is_authorized(query):
454
+ await query.answer("Akses ditolak.", show_alert=True)
455
+ return
456
+
457
+ data = query.data or ""
458
+ try:
459
+ if data.startswith("upload:"):
460
+ _, provider, mode, task_id = data.split(":", 3)
461
+ message = await asyncio.to_thread(start_remote_upload, task_id, provider, mode)
462
+ await query.answer(message)
463
+ await monitor_task_message(query.message, task_id)
464
+ return
465
+
466
+ if data.startswith("pause:"):
467
+ task_id = data.split(":", 1)[1]
468
+ await query.answer(await asyncio.to_thread(pause_task, task_id))
469
+ await monitor_task_message(query.message, task_id)
470
+ return
471
+
472
+ if data.startswith("resume:"):
473
+ task_id = data.split(":", 1)[1]
474
+ await query.answer(await asyncio.to_thread(resume_task, task_id))
475
+ await monitor_task_message(query.message, task_id)
476
+ return
477
+
478
+ if data.startswith("delete_files:"):
479
+ task_id = data.split(":", 1)[1]
480
+ message = await asyncio.to_thread(delete_task, task_id, True)
481
+ await query.answer(message)
482
+ await safe_edit(query.message, message)
483
+ return
484
+
485
+ if data.startswith("delete:"):
486
+ task_id = data.split(":", 1)[1]
487
+ message = await asyncio.to_thread(delete_task, task_id, False)
488
+ await query.answer(message)
489
+ await safe_edit(query.message, message)
490
+ return
491
+
492
+ if data.startswith("refresh:"):
493
+ task_id = data.split(":", 1)[1]
494
+ task = await asyncio.to_thread(task_snapshot, task_id)
495
+ await query.answer("Status diperbarui.")
496
+ await safe_edit(query.message, format_task_status(task) if task else "Task tidak ditemukan.", task_keyboard(task))
497
+ return
498
+
499
+ await query.answer("Aksi tidak dikenal.", show_alert=True)
500
+ except Exception as exc:
501
+ await query.answer(str(exc)[:200], show_alert=True)
502
+
503
+
504
+ def main() -> None:
505
+ missing = []
506
+ if not API_ID:
507
+ missing.append("TELEGRAM_API_ID")
508
+ if not API_HASH:
509
+ missing.append("TELEGRAM_API_HASH")
510
+ if not BOT_TOKEN:
511
+ missing.append("TELEGRAM_BOT_TOKEN")
512
+ if missing:
513
+ raise RuntimeError(f"Env Telegram belum lengkap: {', '.join(missing)}")
514
+
515
+ print("Starting Telegram bot...", flush=True)
516
+ print(f"OWNER_IDS={OWNER_IDS}", flush=True)
517
+ bot.run()
518
+
519
+
520
+ if __name__ == "__main__":
521
+ main()
static/app.js CHANGED
@@ -48,11 +48,23 @@
48
  torrentFileName: document.getElementById("torrent-file-name"),
49
  deleteModal: document.getElementById("delete-modal"),
50
  deleteModalText: document.getElementById("delete-modal-text"),
51
- deleteWithFiles: document.getElementById("delete-with-files"),
52
- modalClose: document.getElementById("modal-close"),
53
- modalCancel: document.getElementById("modal-cancel"),
54
- modalConfirm: document.getElementById("modal-confirm"),
55
- folderUploadModal: document.getElementById("folder-upload-modal"),
 
 
 
 
 
 
 
 
 
 
 
 
56
  folderUploadText: document.getElementById("folder-upload-text"),
57
  folderUploadClose: document.getElementById("folder-upload-close"),
58
  folderUploadCancel: document.getElementById("folder-upload-cancel"),
@@ -63,23 +75,37 @@
63
 
64
  let pendingDelete = null;
65
  let pendingFolderUpload = null;
 
 
66
  let selectedFolderUploadMode = "zip";
67
  const dismissedStatusMessages = new Set();
68
  const seenEventKeys = new Set((state.events || []).map(eventKey));
69
  const inFlightTorrentActions = new Map();
70
  const optimisticTorrentStates = new Map();
71
 
72
- function escapeHtml(value) {
73
- return String(value ?? "").replace(/[&<>"']/g, (char) => ({
74
- "&": "&amp;",
75
- "<": "&lt;",
76
- ">": "&gt;",
77
  '"': "&quot;",
78
- "'": "&#39;",
79
- }[char]));
80
- }
81
-
82
- function normalizeStateLabel(label) {
 
 
 
 
 
 
 
 
 
 
 
 
83
  return String(label || "").trim().toLowerCase();
84
  }
85
 
@@ -760,6 +786,7 @@
760
  : isDownloading
761
  ? "bg-neon/10 text-neon"
762
  : "bg-white/[0.04] text-stone-300";
 
763
  const primaryBadges = isAria2
764
  ? [
765
  metricBadge({ icon: "fa-box-archive", label: "Size", value: torrent.total_size || "-", tone: "muted" }),
@@ -767,7 +794,7 @@
767
  metricBadge({ icon: "fa-arrow-down", label: "Down", value: torrent.dlspeed || "-", tone: "muted", accentClass: "text-neon" }),
768
  ].join("")
769
  : [
770
- metricBadge({ icon: "fa-box-archive", label: "Size", value: torrent.total_size || "-", tone: "muted" }),
771
  metricBadge({ icon: "fa-download", label: "Downloaded", value: torrent.downloaded || "-", tone: "muted" }),
772
  metricBadge({ icon: "fa-upload", label: "Uploaded", value: torrent.uploaded || "-", tone: "muted" }),
773
  metricBadge({ icon: "fa-arrow-down", label: "Down", value: torrent.dlspeed || "-", tone: "muted", accentClass: "text-neon" }),
@@ -1017,13 +1044,218 @@
1017
  showModal(elements.folderUploadModal);
1018
  }
1019
 
1020
- function closeFolderUploadModal() {
1021
- pendingFolderUpload = null;
1022
- selectedFolderUploadMode = "zip";
1023
- hideModal(elements.folderUploadModal);
1024
- }
1025
-
1026
- async function refreshSystem() {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1027
  const response = await fetch("/api/system", {
1028
  headers: { Accept: "application/json" },
1029
  cache: "no-store",
@@ -1174,16 +1406,22 @@
1174
  "X-Requested-With": "XMLHttpRequest",
1175
  },
1176
  });
1177
- const payload = await response.json();
1178
- if (!response.ok || !payload.success) {
1179
- showToast(payload.message || "Aksi gagal diproses.", "error");
1180
- return;
1181
- }
1182
- form.reset();
1183
- syncTorrentFileName();
1184
- closeAddModal();
1185
- showToast(payload.message || successMessage);
1186
- const appeared = await waitForTorrentListMutation(previousHashes);
 
 
 
 
 
 
1187
  if (!appeared) {
1188
  await refreshTorrents();
1189
  }
@@ -1320,20 +1558,46 @@
1320
  closeDeleteModal();
1321
  }
1322
  });
1323
- elements.modalConfirm?.addEventListener("click", async () => {
1324
- if (!pendingDelete) {
1325
- return;
1326
  }
1327
  elements.modalConfirm.disabled = true;
1328
  try {
1329
  await triggerTorrentAction("delete", pendingDelete.hash);
1330
  } finally {
1331
- elements.modalConfirm.disabled = false;
1332
- }
1333
- });
1334
-
1335
- elements.folderUploadClose?.addEventListener("click", closeFolderUploadModal);
1336
- elements.folderUploadCancel?.addEventListener("click", closeFolderUploadModal);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1337
  elements.folderUploadModal?.addEventListener("click", (event) => {
1338
  if (event.target === elements.folderUploadModal) {
1339
  closeFolderUploadModal();
 
48
  torrentFileName: document.getElementById("torrent-file-name"),
49
  deleteModal: document.getElementById("delete-modal"),
50
  deleteModalText: document.getElementById("delete-modal-text"),
51
+ deleteWithFiles: document.getElementById("delete-with-files"),
52
+ modalClose: document.getElementById("modal-close"),
53
+ modalCancel: document.getElementById("modal-cancel"),
54
+ modalConfirm: document.getElementById("modal-confirm"),
55
+ torrentFileSelectionModal: document.getElementById("torrent-file-selection-modal"),
56
+ torrentFileSelectionClose: document.getElementById("torrent-file-selection-close"),
57
+ torrentFileSelectionText: document.getElementById("torrent-file-selection-text"),
58
+ torrentFileSelectionLoading: document.getElementById("torrent-file-selection-loading"),
59
+ torrentFileSelectionStorageWarning: document.getElementById("torrent-file-selection-storage-warning"),
60
+ torrentFileSelectionActions: document.getElementById("torrent-file-selection-actions"),
61
+ torrentFileSelectionCount: document.getElementById("torrent-file-selection-count"),
62
+ torrentFileSelectionAll: document.getElementById("torrent-file-selection-all"),
63
+ torrentFileSelectionNone: document.getElementById("torrent-file-selection-none"),
64
+ torrentFileSelectionList: document.getElementById("torrent-file-selection-list"),
65
+ torrentFileSelectionCancel: document.getElementById("torrent-file-selection-cancel"),
66
+ torrentFileSelectionConfirm: document.getElementById("torrent-file-selection-confirm"),
67
+ folderUploadModal: document.getElementById("folder-upload-modal"),
68
  folderUploadText: document.getElementById("folder-upload-text"),
69
  folderUploadClose: document.getElementById("folder-upload-close"),
70
  folderUploadCancel: document.getElementById("folder-upload-cancel"),
 
75
 
76
  let pendingDelete = null;
77
  let pendingFolderUpload = null;
78
+ let pendingTorrentFileSelection = null;
79
+ let torrentFileSelectionPollTimer = null;
80
  let selectedFolderUploadMode = "zip";
81
  const dismissedStatusMessages = new Set();
82
  const seenEventKeys = new Set((state.events || []).map(eventKey));
83
  const inFlightTorrentActions = new Map();
84
  const optimisticTorrentStates = new Map();
85
 
86
+ function escapeHtml(value) {
87
+ return String(value ?? "").replace(/[&<>"']/g, (char) => ({
88
+ "&": "&amp;",
89
+ "<": "&lt;",
90
+ ">": "&gt;",
91
  '"': "&quot;",
92
+ "'": "&#39;",
93
+ }[char]));
94
+ }
95
+
96
+ function formatBytes(value) {
97
+ let size = Math.max(0, Number(value || 0));
98
+ const units = ["B", "KB", "MB", "GB", "TB"];
99
+ for (const unit of units) {
100
+ if (size < 1024 || unit === units[units.length - 1]) {
101
+ return `${size.toFixed(1)} ${unit}`;
102
+ }
103
+ size /= 1024;
104
+ }
105
+ return `${size.toFixed(1)} TB`;
106
+ }
107
+
108
+ function normalizeStateLabel(label) {
109
  return String(label || "").trim().toLowerCase();
110
  }
111
 
 
786
  : isDownloading
787
  ? "bg-neon/10 text-neon"
788
  : "bg-white/[0.04] text-stone-300";
789
+ const sizeLabel = torrent.has_file_selection ? "Selected" : "Size";
790
  const primaryBadges = isAria2
791
  ? [
792
  metricBadge({ icon: "fa-box-archive", label: "Size", value: torrent.total_size || "-", tone: "muted" }),
 
794
  metricBadge({ icon: "fa-arrow-down", label: "Down", value: torrent.dlspeed || "-", tone: "muted", accentClass: "text-neon" }),
795
  ].join("")
796
  : [
797
+ metricBadge({ icon: "fa-box-archive", label: sizeLabel, value: torrent.total_size || "-", tone: "muted" }),
798
  metricBadge({ icon: "fa-download", label: "Downloaded", value: torrent.downloaded || "-", tone: "muted" }),
799
  metricBadge({ icon: "fa-upload", label: "Uploaded", value: torrent.uploaded || "-", tone: "muted" }),
800
  metricBadge({ icon: "fa-arrow-down", label: "Down", value: torrent.dlspeed || "-", tone: "muted", accentClass: "text-neon" }),
 
1044
  showModal(elements.folderUploadModal);
1045
  }
1046
 
1047
+ function closeFolderUploadModal() {
1048
+ pendingFolderUpload = null;
1049
+ selectedFolderUploadMode = "zip";
1050
+ hideModal(elements.folderUploadModal);
1051
+ }
1052
+
1053
+ function stopTorrentFileSelectionPolling() {
1054
+ if (torrentFileSelectionPollTimer) {
1055
+ window.clearInterval(torrentFileSelectionPollTimer);
1056
+ torrentFileSelectionPollTimer = null;
1057
+ }
1058
+ }
1059
+
1060
+ function updateTorrentFileSelectionCount() {
1061
+ if (!elements.torrentFileSelectionCount || !elements.torrentFileSelectionList) {
1062
+ return;
1063
+ }
1064
+ const checkedBoxes = Array.from(elements.torrentFileSelectionList.querySelectorAll("[data-file-selection-checkbox]:checked"));
1065
+ const checkedCount = checkedBoxes.length;
1066
+ elements.torrentFileSelectionCount.textContent = String(checkedCount);
1067
+
1068
+ if (!elements.torrentFileSelectionStorageWarning) {
1069
+ return;
1070
+ }
1071
+
1072
+ const selectedBytes = checkedBoxes.reduce((total, checkbox) => total + Number(checkbox.dataset.sizeBytes || 0), 0);
1073
+ const availableBytes = Number(pendingTorrentFileSelection?.storageAvailableBytes || 0);
1074
+ const selectedSize = formatBytes(selectedBytes);
1075
+ const availableSize = pendingTorrentFileSelection?.storageAvailable || formatBytes(availableBytes);
1076
+
1077
+ if (availableBytes > 0 && selectedBytes > availableBytes) {
1078
+ elements.torrentFileSelectionStorageWarning.textContent = `Storage tidak cukup. Pilihan saat ini ${selectedSize}, tersedia ${availableSize}. Kurangi pilihan atau bersihkan storage dulu.`;
1079
+ elements.torrentFileSelectionStorageWarning.classList.remove("hidden");
1080
+ return;
1081
+ }
1082
+
1083
+ if (pendingTorrentFileSelection?.storageWarning) {
1084
+ elements.torrentFileSelectionStorageWarning.textContent = pendingTorrentFileSelection.storageWarning;
1085
+ elements.torrentFileSelectionStorageWarning.classList.remove("hidden");
1086
+ return;
1087
+ }
1088
+
1089
+ elements.torrentFileSelectionStorageWarning.textContent = "";
1090
+ elements.torrentFileSelectionStorageWarning.classList.add("hidden");
1091
+ }
1092
+
1093
+ function renderTorrentFileSelectionFiles(files) {
1094
+ const torrentFiles = Array.isArray(files) ? files : [];
1095
+ if (!elements.torrentFileSelectionList) {
1096
+ return;
1097
+ }
1098
+
1099
+ elements.torrentFileSelectionList.innerHTML = torrentFiles.map((file) => `
1100
+ <label class="flex min-h-[58px] items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-stone-200 transition hover:border-white/20 hover:bg-white/[0.04]">
1101
+ <input type="checkbox" data-file-selection-checkbox data-size-bytes="${escapeHtml(file.size_bytes || 0)}" value="${escapeHtml(file.id)}" ${file.selected === false ? "" : "checked"} class="h-4 w-4 shrink-0 rounded border-white/20 bg-stone-900 text-neon focus:ring-neon" />
1102
+ <span class="min-w-0 flex-1">
1103
+ <span class="block break-words text-white">${escapeHtml(file.name)}</span>
1104
+ <span class="mt-1 block text-xs text-stone-500">${escapeHtml(file.size || "0 B")}</span>
1105
+ </span>
1106
+ </label>
1107
+ `).join("");
1108
+ updateTorrentFileSelectionCount();
1109
+ }
1110
+
1111
+ function setTorrentFileSelectionLoading(isLoading, message) {
1112
+ elements.torrentFileSelectionText.textContent = message || "";
1113
+ elements.torrentFileSelectionLoading.classList.toggle("hidden", !isLoading);
1114
+ elements.torrentFileSelectionStorageWarning.classList.add("hidden");
1115
+ elements.torrentFileSelectionActions.classList.toggle("hidden", isLoading);
1116
+ elements.torrentFileSelectionList.classList.toggle("hidden", isLoading);
1117
+ elements.torrentFileSelectionConfirm.disabled = isLoading;
1118
+ }
1119
+
1120
+ function closeTorrentFileSelectionModal() {
1121
+ stopTorrentFileSelectionPolling();
1122
+ pendingTorrentFileSelection = null;
1123
+ hideModal(elements.torrentFileSelectionModal);
1124
+ }
1125
+
1126
+ async function pollTorrentFileSelection() {
1127
+ if (!pendingTorrentFileSelection?.hash) {
1128
+ return;
1129
+ }
1130
+
1131
+ try {
1132
+ const response = await fetch(`/api/torrents/${pendingTorrentFileSelection.hash}/files`, {
1133
+ headers: { Accept: "application/json" },
1134
+ cache: "no-store",
1135
+ });
1136
+ const payload = await response.json();
1137
+ if (!response.ok || !payload.success) {
1138
+ showToast(payload.message || "Gagal mengambil daftar file torrent.", "error");
1139
+ return;
1140
+ }
1141
+ if (payload.selection_pending && !payload.metadata_ready) {
1142
+ setTorrentFileSelectionLoading(true, payload.message || "Metadata torrent masih diambil...");
1143
+ return;
1144
+ }
1145
+ if (!payload.selection_required) {
1146
+ showToast(payload.message || "Torrent dimulai.");
1147
+ closeTorrentFileSelectionModal();
1148
+ await refreshTorrents();
1149
+ return;
1150
+ }
1151
+ pendingTorrentFileSelection.files = Array.isArray(payload.files) ? payload.files : [];
1152
+ pendingTorrentFileSelection.storageAvailableBytes = Number(payload.storage_available_bytes || 0);
1153
+ pendingTorrentFileSelection.storageAvailable = payload.storage_available || "";
1154
+ pendingTorrentFileSelection.storageWarning = payload.storage_warning || "";
1155
+ setTorrentFileSelectionLoading(false, payload.message || "Pilih file yang ingin didownload.");
1156
+ renderTorrentFileSelectionFiles(pendingTorrentFileSelection.files);
1157
+ stopTorrentFileSelectionPolling();
1158
+ await refreshTorrents();
1159
+ } catch (error) {
1160
+ showToast("Gagal mengambil metadata torrent.", "error");
1161
+ }
1162
+ }
1163
+
1164
+ function openTorrentFileSelectionModal(payload) {
1165
+ const torrentHash = payload.torrent_hash;
1166
+ if (!torrentHash) {
1167
+ return;
1168
+ }
1169
+ pendingTorrentFileSelection = {
1170
+ hash: torrentHash,
1171
+ files: Array.isArray(payload.files) ? payload.files : [],
1172
+ storageAvailableBytes: Number(payload.storage_available_bytes || 0),
1173
+ storageAvailable: payload.storage_available || "",
1174
+ storageWarning: payload.storage_warning || "",
1175
+ };
1176
+ elements.torrentFileSelectionList.innerHTML = "";
1177
+ showModal(elements.torrentFileSelectionModal);
1178
+
1179
+ if (payload.selection_pending) {
1180
+ setTorrentFileSelectionLoading(true, payload.message || "Metadata torrent masih diambil...");
1181
+ stopTorrentFileSelectionPolling();
1182
+ torrentFileSelectionPollTimer = window.setInterval(pollTorrentFileSelection, 1600);
1183
+ pollTorrentFileSelection();
1184
+ return;
1185
+ }
1186
+
1187
+ setTorrentFileSelectionLoading(false, payload.message || "Pilih file yang ingin didownload.");
1188
+ renderTorrentFileSelectionFiles(pendingTorrentFileSelection.files);
1189
+ }
1190
+
1191
+ async function confirmTorrentFileSelection() {
1192
+ if (!pendingTorrentFileSelection?.hash) {
1193
+ return;
1194
+ }
1195
+ const selectedIds = Array.from(elements.torrentFileSelectionList.querySelectorAll("[data-file-selection-checkbox]:checked"))
1196
+ .map((checkbox) => Number(checkbox.value));
1197
+ if (!selectedIds.length) {
1198
+ showToast("Pilih minimal satu file.", "error");
1199
+ return;
1200
+ }
1201
+ const selectedBytes = Array.from(elements.torrentFileSelectionList.querySelectorAll("[data-file-selection-checkbox]:checked"))
1202
+ .reduce((total, checkbox) => total + Number(checkbox.dataset.sizeBytes || 0), 0);
1203
+ const availableBytes = Number(pendingTorrentFileSelection.storageAvailableBytes || 0);
1204
+ if (availableBytes > 0 && selectedBytes > availableBytes) {
1205
+ updateTorrentFileSelectionCount();
1206
+ showToast("Storage tidak cukup untuk file yang dipilih.", "error");
1207
+ return;
1208
+ }
1209
+
1210
+ elements.torrentFileSelectionConfirm.disabled = true;
1211
+ try {
1212
+ const response = await fetch(`/api/torrents/${pendingTorrentFileSelection.hash}/files/selection`, {
1213
+ method: "POST",
1214
+ headers: {
1215
+ Accept: "application/json",
1216
+ "Content-Type": "application/json",
1217
+ },
1218
+ body: JSON.stringify({ selected_file_ids: selectedIds }),
1219
+ });
1220
+ const payload = await response.json();
1221
+ if (!response.ok || !payload.success) {
1222
+ showToast(payload.message || "Gagal menerapkan seleksi file.", response.status === 507 ? "warning" : "error");
1223
+ return;
1224
+ }
1225
+ showToast(payload.message || "Seleksi file diterapkan.");
1226
+ closeTorrentFileSelectionModal();
1227
+ await refreshTorrents();
1228
+ } finally {
1229
+ elements.torrentFileSelectionConfirm.disabled = false;
1230
+ }
1231
+ }
1232
+
1233
+ async function cancelTorrentFileSelection() {
1234
+ if (!pendingTorrentFileSelection?.hash) {
1235
+ closeTorrentFileSelectionModal();
1236
+ return;
1237
+ }
1238
+ const torrentHash = pendingTorrentFileSelection.hash;
1239
+ elements.torrentFileSelectionCancel.disabled = true;
1240
+ try {
1241
+ const response = await fetch(`/api/torrents/${torrentHash}?with_files=false`, {
1242
+ method: "DELETE",
1243
+ headers: { Accept: "application/json" },
1244
+ });
1245
+ const payload = await response.json();
1246
+ if (!response.ok || !payload.success) {
1247
+ showToast(payload.message || "Gagal membatalkan torrent.", "error");
1248
+ return;
1249
+ }
1250
+ showToast("Torrent dibatalkan.");
1251
+ closeTorrentFileSelectionModal();
1252
+ await refreshTorrents();
1253
+ } finally {
1254
+ elements.torrentFileSelectionCancel.disabled = false;
1255
+ }
1256
+ }
1257
+
1258
+ async function refreshSystem() {
1259
  const response = await fetch("/api/system", {
1260
  headers: { Accept: "application/json" },
1261
  cache: "no-store",
 
1406
  "X-Requested-With": "XMLHttpRequest",
1407
  },
1408
  });
1409
+ const payload = await response.json();
1410
+ if (!response.ok || !payload.success) {
1411
+ showToast(payload.message || "Aksi gagal diproses.", response.status === 507 ? "warning" : "error");
1412
+ return;
1413
+ }
1414
+ form.reset();
1415
+ syncTorrentFileName();
1416
+ closeAddModal();
1417
+ if (payload.selection_required || payload.selection_pending) {
1418
+ showToast(payload.storage_warning || payload.message || "Pilih file torrent sebelum download dimulai.", "warning");
1419
+ openTorrentFileSelectionModal(payload);
1420
+ await refreshTorrents();
1421
+ return;
1422
+ }
1423
+ showToast(payload.message || successMessage);
1424
+ const appeared = await waitForTorrentListMutation(previousHashes);
1425
  if (!appeared) {
1426
  await refreshTorrents();
1427
  }
 
1558
  closeDeleteModal();
1559
  }
1560
  });
1561
+ elements.modalConfirm?.addEventListener("click", async () => {
1562
+ if (!pendingDelete) {
1563
+ return;
1564
  }
1565
  elements.modalConfirm.disabled = true;
1566
  try {
1567
  await triggerTorrentAction("delete", pendingDelete.hash);
1568
  } finally {
1569
+ elements.modalConfirm.disabled = false;
1570
+ }
1571
+ });
1572
+
1573
+ elements.torrentFileSelectionList?.addEventListener("change", (event) => {
1574
+ if (event.target.closest("[data-file-selection-checkbox]")) {
1575
+ updateTorrentFileSelectionCount();
1576
+ }
1577
+ });
1578
+ elements.torrentFileSelectionAll?.addEventListener("click", () => {
1579
+ elements.torrentFileSelectionList.querySelectorAll("[data-file-selection-checkbox]").forEach((checkbox) => {
1580
+ checkbox.checked = true;
1581
+ });
1582
+ updateTorrentFileSelectionCount();
1583
+ });
1584
+ elements.torrentFileSelectionNone?.addEventListener("click", () => {
1585
+ elements.torrentFileSelectionList.querySelectorAll("[data-file-selection-checkbox]").forEach((checkbox) => {
1586
+ checkbox.checked = false;
1587
+ });
1588
+ updateTorrentFileSelectionCount();
1589
+ });
1590
+ elements.torrentFileSelectionConfirm?.addEventListener("click", confirmTorrentFileSelection);
1591
+ elements.torrentFileSelectionCancel?.addEventListener("click", cancelTorrentFileSelection);
1592
+ elements.torrentFileSelectionClose?.addEventListener("click", cancelTorrentFileSelection);
1593
+ elements.torrentFileSelectionModal?.addEventListener("click", (event) => {
1594
+ if (event.target === elements.torrentFileSelectionModal) {
1595
+ cancelTorrentFileSelection();
1596
+ }
1597
+ });
1598
+
1599
+ elements.folderUploadClose?.addEventListener("click", closeFolderUploadModal);
1600
+ elements.folderUploadCancel?.addEventListener("click", closeFolderUploadModal);
1601
  elements.folderUploadModal?.addEventListener("click", (event) => {
1602
  if (event.target === elements.folderUploadModal) {
1603
  closeFolderUploadModal();
templates/index.html CHANGED
@@ -344,8 +344,8 @@
344
  </div>
345
  </div>
346
 
347
- <div id="delete-modal" class="fixed inset-0 z-[70] hidden items-center justify-center bg-black/75 px-4 backdrop-blur-xl">
348
- <div class="w-full max-w-md rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,18,28,0.96),rgba(9,11,18,0.95))] shadow-halo">
349
  <div class="flex items-start justify-between border-b border-white/5 px-5 py-5">
350
  <div>
351
  <p class="text-[11px] uppercase tracking-[0.25em] text-rose-300/80">Delete Torrent</p>
@@ -367,11 +367,49 @@
367
  <button id="modal-confirm" type="button" class="rounded-2xl border border-rose-400/30 bg-rose-400/10 px-4 py-3 text-sm font-medium text-rose-100 transition hover:bg-rose-400/20">Delete</button>
368
  </div>
369
  </div>
370
- </div>
371
- </div>
372
-
373
- <div id="folder-upload-modal" class="fixed inset-0 z-[70] hidden items-center justify-center bg-black/75 px-4 backdrop-blur-xl">
374
- <div class="w-full max-w-lg rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,18,28,0.96),rgba(9,11,18,0.95))] shadow-halo">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
375
  <div class="flex items-start justify-between border-b border-white/5 px-5 py-5">
376
  <div>
377
  <p class="text-[11px] uppercase tracking-[0.25em] text-sky-300/80">Folder Upload</p>
 
344
  </div>
345
  </div>
346
 
347
+ <div id="delete-modal" class="fixed inset-0 z-[70] hidden items-center justify-center bg-black/75 px-4 backdrop-blur-xl">
348
+ <div class="w-full max-w-md rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,18,28,0.96),rgba(9,11,18,0.95))] shadow-halo">
349
  <div class="flex items-start justify-between border-b border-white/5 px-5 py-5">
350
  <div>
351
  <p class="text-[11px] uppercase tracking-[0.25em] text-rose-300/80">Delete Torrent</p>
 
367
  <button id="modal-confirm" type="button" class="rounded-2xl border border-rose-400/30 bg-rose-400/10 px-4 py-3 text-sm font-medium text-rose-100 transition hover:bg-rose-400/20">Delete</button>
368
  </div>
369
  </div>
370
+ </div>
371
+ </div>
372
+
373
+ <div id="torrent-file-selection-modal" class="fixed inset-0 z-[80] hidden items-center justify-center bg-black/75 px-4 backdrop-blur-xl">
374
+ <div class="w-full max-w-2xl rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,18,28,0.96),rgba(9,11,18,0.95))] shadow-halo">
375
+ <div class="flex items-start justify-between border-b border-white/5 px-5 py-5">
376
+ <div>
377
+ <p class="text-[11px] uppercase tracking-[0.25em] text-neon/80">Torrent Files</p>
378
+ <h3 class="font-display mt-2 text-xl font-semibold text-white">Pilih file yang didownload</h3>
379
+ </div>
380
+ <button id="torrent-file-selection-close" type="button" class="rounded-2xl border border-white/10 px-3 py-2 text-sm text-stone-400 transition hover:bg-white/10 hover:text-white">
381
+ <i class="fa-solid fa-xmark"></i>
382
+ </button>
383
+ </div>
384
+ <div class="p-5">
385
+ <p id="torrent-file-selection-text" class="text-sm text-stone-300"></p>
386
+ <div id="torrent-file-selection-loading" class="mt-5 hidden rounded-[24px] border border-white/10 bg-black/20 px-4 py-6 text-center text-sm text-stone-300">
387
+ <i class="fa-solid fa-spinner mr-2 animate-spin text-neon"></i>
388
+ Menunggu metadata torrent...
389
+ </div>
390
+ <div id="torrent-file-selection-storage-warning" class="mt-4 hidden rounded-2xl border border-amber/25 bg-amber/10 px-4 py-3 text-sm text-amber-100"></div>
391
+ <div id="torrent-file-selection-actions" class="mt-5 hidden flex flex-wrap items-center justify-between gap-3">
392
+ <div class="text-xs text-stone-500"><span id="torrent-file-selection-count">0</span> file dipilih</div>
393
+ <div class="flex flex-wrap gap-2">
394
+ <button id="torrent-file-selection-all" type="button" class="rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2 text-xs font-medium text-white transition hover:bg-white/[0.08]">
395
+ <i class="fa-solid fa-check-double mr-2 text-[11px]"></i>Pilih semua
396
+ </button>
397
+ <button id="torrent-file-selection-none" type="button" class="rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2 text-xs font-medium text-white transition hover:bg-white/[0.08]">
398
+ <i class="fa-solid fa-minus mr-2 text-[11px]"></i>Kosongkan
399
+ </button>
400
+ </div>
401
+ </div>
402
+ <div id="torrent-file-selection-list" class="mt-4 max-h-[48vh] space-y-2 overflow-y-auto pr-1"></div>
403
+ <div class="mt-6 flex flex-wrap justify-end gap-3">
404
+ <button id="torrent-file-selection-cancel" type="button" class="rounded-2xl border border-rose-400/20 bg-rose-400/10 px-4 py-3 text-sm font-medium text-rose-100 transition hover:bg-rose-400/15">Batalkan torrent</button>
405
+ <button id="torrent-file-selection-confirm" type="button" class="rounded-2xl border border-neon/30 bg-neon/12 px-4 py-3 text-sm font-medium text-neon transition hover:bg-neon/20">Mulai download</button>
406
+ </div>
407
+ </div>
408
+ </div>
409
+ </div>
410
+
411
+ <div id="folder-upload-modal" class="fixed inset-0 z-[70] hidden items-center justify-center bg-black/75 px-4 backdrop-blur-xl">
412
+ <div class="w-full max-w-lg rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,18,28,0.96),rgba(9,11,18,0.95))] shadow-halo">
413
  <div class="flex items-start justify-between border-b border-white/5 px-5 py-5">
414
  <div>
415
  <p class="text-[11px] uppercase tracking-[0.25em] text-sky-300/80">Folder Upload</p>