forked from TheGreatAzizi/AzuDL-GC2GD
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode [1.3.0 CLI].py
More file actions
2076 lines (1625 loc) · 64 KB
/
Code [1.3.0 CLI].py
File metadata and controls
2076 lines (1625 loc) · 64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
!apt update -qq
!apt install -y aria2 ffmpeg p7zip-full
!pip install -q tqdm requests yt-dlp
import os
import re
import json
import time
import socket
import base64
import shutil
import hashlib
import subprocess
from pathlib import Path
from datetime import datetime
from urllib.parse import urlparse
import requests
from tqdm.notebook import tqdm
from google.colab import drive
from yt_dlp import YoutubeDL
class AzuDlGC2GD:
def __init__(self):
self.project_name = "AzuDl - GC2GD"
self.project_subtitle = "Azizi Universal Downloader - Google Colab to Google Drive"
self.version = "1.3.0"
self.drive_mount_path = Path("/content/drive")
self.my_drive_path = self.drive_mount_path / "MyDrive"
self.base_dir = self.my_drive_path / "AzuDl-GC2GD"
self.torrent_dir = self.base_dir / "TorrentDownloads"
self.youtube_dir = self.base_dir / "YouTubeDownloads"
self.direct_dir = self.base_dir / "DirectDownloads"
self.batch_dir = self.base_dir / "BatchDownloads"
self.archive_dir = self.base_dir / "Archives"
self.logs_dir = self.base_dir / "Logs"
self.history_file = self.logs_dir / "download_history.json"
self.aria2_session_file = self.logs_dir / "aria2.session"
self.rpc_url = "http://localhost:6800/jsonrpc"
def setup(self):
self.print_banner()
self.mount_google_drive()
self.prepare_directories()
self.start_aria2_rpc()
def print_banner(self):
print("=" * 70)
print(self.project_name)
print(self.project_subtitle)
print("Version:", self.version)
print("=" * 70)
def mount_google_drive(self):
if self.my_drive_path.exists():
print("Google Drive already mounted")
return
attempts = [
{"force_remount": False, "label": "standard mount"},
{"force_remount": True, "label": "force remount"}
]
last_error = None
for attempt in attempts:
try:
print("Trying Google Drive", attempt["label"])
drive.mount(str(self.drive_mount_path), force_remount=attempt["force_remount"])
if self.my_drive_path.exists():
print("Google Drive mounted successfully")
return
except Exception as error:
last_error = error
print("Mount attempt failed:", error)
time.sleep(2)
self.print_drive_mount_help()
raise RuntimeError(f"Google Drive mount failed: {last_error}")
def print_drive_mount_help(self):
print("")
print("=" * 70)
print("Google Drive mount failed")
print("=" * 70)
print("Try these fixes:")
print("1. Runtime > Restart session")
print("2. Run this in a separate cell: from google.colab import drive; drive.flush_and_unmount()")
print("3. Use only one Google account in your browser")
print("4. Open Colab in Incognito mode")
print("5. Make sure third-party cookies are not blocked")
print("6. Reconnect Google Drive manually from the Colab file panel")
print("=" * 70)
print("")
def prepare_directories(self):
dirs = [
self.base_dir,
self.torrent_dir,
self.youtube_dir,
self.direct_dir,
self.batch_dir,
self.archive_dir,
self.logs_dir
]
for item in dirs:
item.mkdir(parents=True, exist_ok=True)
if not self.aria2_session_file.exists():
self.aria2_session_file.write_text("")
def is_port_open(self, host="127.0.0.1", port=6800):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(1)
return s.connect_ex((host, port)) == 0
def start_aria2_rpc(self):
if self.is_port_open():
try:
options = self.rpc("aria2.getGlobalOption")
save_session = str(options.get("save-session", ""))
input_file = str(options.get("input-file", ""))
if str(self.aria2_session_file) in [save_session, input_file]:
print("aria2 RPC already running")
return
print("aria2 RPC is running with old options")
print("Restarting aria2 RPC")
try:
self.rpc("aria2.shutdown")
time.sleep(2)
except Exception:
pass
except Exception:
pass
if self.is_port_open():
subprocess.run(["pkill", "-9", "aria2c"], check=False)
time.sleep(2)
cmd = [
"aria2c",
"--enable-rpc=true",
"--rpc-listen-all=false",
"--rpc-listen-port=6800",
"--rpc-allow-origin-all=true",
"--daemon=true",
"--seed-time=0",
"--seed-ratio=0.0",
"--file-allocation=none",
"--continue=true",
"--always-resume=true",
"--auto-save-interval=10",
"--save-session-interval=10",
f"--input-file={self.aria2_session_file}",
f"--save-session={self.aria2_session_file}",
"--force-save=true",
"--max-tries=0",
"--retry-wait=10",
"--timeout=60",
"--connect-timeout=60",
"--enable-dht=true",
"--enable-dht6=true",
"--enable-peer-exchange=true",
"--bt-enable-lpd=true",
"--bt-save-metadata=true",
"--bt-load-saved-metadata=true",
"--console-log-level=warn"
]
subprocess.run(cmd, check=True)
for _ in range(30):
if self.is_port_open():
print("aria2 RPC started")
print("aria2 session:", self.aria2_session_file)
return
time.sleep(0.5)
raise RuntimeError("Failed to start aria2 RPC server.")
def rpc(self, method, params=None):
payload = {
"jsonrpc": "2.0",
"id": "azudl-gc2gd",
"method": method,
"params": params or []
}
response = requests.post(self.rpc_url, json=payload, timeout=30)
if response.status_code != 200:
message = response.text[:1000]
raise RuntimeError(f"aria2 RPC HTTP {response.status_code}: {message}")
try:
data = response.json()
except Exception:
raise RuntimeError(f"Invalid aria2 RPC response: {response.text[:1000]}")
if "error" in data:
raise RuntimeError(data["error"])
return data["result"]
def save_aria2_session(self):
try:
result = self.rpc("aria2.saveSession")
print("aria2 session saved")
return result
except Exception as error:
message = str(error)
if "Filename is not given" in message:
return None
print("Failed to save aria2 session:", error)
return None
def sanitize_name(self, name):
name = str(name or "").strip()
name = re.sub(r'[\/\\:*?"<>|]', "_", name)
name = re.sub(r"\s+", " ", name)
return name or f"Download_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}"
def format_bytes(self, value):
value = float(value or 0)
for unit in ["B", "KB", "MB", "GB", "TB"]:
if value < 1024:
return f"{value:.2f} {unit}"
value /= 1024
return f"{value:.2f} PB"
def format_seconds(self, seconds):
seconds = int(seconds or 0)
hours = seconds // 3600
minutes = (seconds % 3600) // 60
secs = seconds % 60
if hours > 0:
return f"{hours:02d}:{minutes:02d}:{secs:02d}"
return f"{minutes:02d}:{secs:02d}"
def detect_link_type(self, value):
value = str(value or "").strip()
lower = value.lower()
if lower.startswith("magnet:?"):
return "torrent"
parsed = urlparse(value)
host = parsed.netloc.lower()
path = parsed.path.lower()
youtube_hosts = [
"youtube.com",
"www.youtube.com",
"m.youtube.com",
"youtu.be",
"music.youtube.com"
]
if any(host == item or host.endswith("." + item) for item in youtube_hosts):
return "youtube"
if path.endswith(".torrent"):
return "torrent_file"
if lower.startswith(("http://", "https://", "ftp://")):
return "direct"
if Path(value).suffix.lower() == ".torrent":
return "torrent_file"
return "unknown"
def save_history(self, item):
history = []
if self.history_file.exists():
try:
history = json.loads(self.history_file.read_text())
except Exception:
history = []
item["time"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
history.append(item)
self.history_file.write_text(json.dumps(history, indent=2, ensure_ascii=False))
def print_history(self):
if not self.history_file.exists():
print("No history found")
return
try:
history = json.loads(self.history_file.read_text())
except Exception:
print("History file is invalid")
return
if not history:
print("No history found")
return
for index, item in enumerate(history[-50:], 1):
print("-" * 80)
print("Index:", index)
print("Type:", item.get("type", "unknown"))
print("Time:", item.get("time", "unknown"))
print("Source:", item.get("source", "unknown"))
print("Output:", item.get("output", "unknown"))
print("Status:", item.get("status", "unknown"))
if item.get("format"):
print("Format:", item.get("format"))
if item.get("seed") is not None:
print("Seed:", item.get("seed"))
if item.get("error"):
print("Error:", item.get("error"))
def get_all_downloaded_files(self):
folders = [
self.torrent_dir,
self.youtube_dir,
self.direct_dir,
self.batch_dir,
self.archive_dir
]
files = []
for folder in folders:
if folder.exists():
files.extend([item for item in folder.glob("**/*") if item.is_file()])
return sorted(files, key=lambda x: x.stat().st_mtime, reverse=True)
def get_latest_file(self):
files = self.get_all_downloaded_files()
if not files:
return None
return files[0]
def get_latest_downloaded_file(self):
return self.get_latest_file()
def get_latest_downloaded_folder(self):
folders = [
self.torrent_dir,
self.youtube_dir,
self.direct_dir,
self.batch_dir,
self.archive_dir
]
all_dirs = []
for folder in folders:
if folder.exists():
all_dirs.extend([item for item in folder.glob("**/*") if item.is_dir()])
if not all_dirs:
return None
return max(all_dirs, key=lambda item: item.stat().st_mtime)
def list_downloads(self):
folders = [
self.torrent_dir,
self.youtube_dir,
self.direct_dir,
self.batch_dir,
self.archive_dir
]
for folder in folders:
print("")
print(str(folder))
print("-" * 80)
if not folder.exists():
print("Folder does not exist")
continue
items = sorted(
folder.glob("**/*"),
key=lambda x: x.stat().st_mtime if x.exists() else 0,
reverse=True
)
files = [item for item in items if item.is_file()]
if not files:
print("No files")
continue
for item in files[:100]:
size = self.format_bytes(item.stat().st_size)
print(f"{size:<12} {item}")
def print_latest_file(self):
latest = self.get_latest_downloaded_file()
if not latest:
print("No files found")
return
print("Latest file")
print("-" * 80)
print("Path:", latest)
print("Size:", self.format_bytes(latest.stat().st_size))
print("Modified:", datetime.fromtimestamp(latest.stat().st_mtime).strftime("%Y-%m-%d %H:%M:%S"))
def select_file(self):
files = self.get_all_downloaded_files()
if not files:
print("No files found")
return None
for index, item in enumerate(files[:100], 1):
print(f"{index:<4} {self.format_bytes(item.stat().st_size):<12} {item}")
value = input("File number: ").strip()
if not value.isdigit():
print("Invalid number")
return None
index = int(value)
if index < 1 or index > min(len(files), 100):
print("Invalid number")
return None
return files[index - 1]
def add_aria2_download(self, uris, save_dir, speed_limit="", extra_options=None):
options = {
"dir": str(save_dir),
"file-allocation": "none",
"continue": "true",
"always-resume": "true",
"max-tries": "0",
"retry-wait": "10",
"timeout": "60",
"connect-timeout": "60",
"allow-overwrite": "false",
"auto-file-renaming": "true",
"max-connection-per-server": "16",
"split": "16",
"min-split-size": "1M"
}
if speed_limit:
options["max-overall-download-limit"] = speed_limit.strip()
if extra_options:
options.update(extra_options)
gid = self.rpc("aria2.addUri", [uris, options])
self.save_aria2_session()
return gid
def add_aria2_torrent(self, torrent_bytes, save_dir, speed_limit="", extra_options=None):
torrent_base64 = base64.b64encode(torrent_bytes).decode("utf-8")
options = {
"dir": str(save_dir),
"file-allocation": "none",
"continue": "true",
"always-resume": "true",
"max-tries": "0",
"retry-wait": "10",
"timeout": "60",
"connect-timeout": "60",
"allow-overwrite": "false",
"auto-file-renaming": "true",
"seed-time": "0",
"seed-ratio": "0.0",
"enable-dht": "true",
"enable-dht6": "true",
"enable-peer-exchange": "true",
"bt-enable-lpd": "true"
}
if speed_limit:
options["max-overall-download-limit"] = speed_limit.strip()
if extra_options:
options.update(extra_options)
gid = self.rpc("aria2.addTorrent", [torrent_base64, [], options])
self.save_aria2_session()
return gid
def fetch_torrent_file_bytes(self, source):
source = source.strip()
headers = {
"User-Agent": "Mozilla/5.0 AzuDl-GC2GD/1.3.0",
"Accept": "application/x-bittorrent,application/octet-stream,*/*"
}
if source.startswith(("http://", "https://")):
print("Downloading torrent file metadata")
response = requests.get(source, headers=headers, timeout=60, allow_redirects=True)
response.raise_for_status()
content = response.content
else:
path = Path(source)
if not path.exists():
raise FileNotFoundError(f"Torrent file not found: {path}")
content = path.read_bytes()
if not content:
raise ValueError("Torrent file is empty")
stripped = content.lstrip()
if not stripped.startswith(b"d"):
preview = content[:300].decode("utf-8", errors="replace")
raise ValueError(
"Downloaded file is not a valid .torrent file. "
"The server may have returned HTML, an error page, or blocked the request.\n"
f"Preview:\n{preview}"
)
return content
def skip_bencode_value(self, data, index):
token = data[index:index + 1]
if token == b"i":
end = data.index(b"e", index)
return end + 1
if token in [b"l", b"d"]:
index += 1
while data[index:index + 1] != b"e":
index = self.skip_bencode_value(data, index)
return index + 1
if token.isdigit():
colon = data.index(b":", index)
length = int(data[index:colon])
return colon + 1 + length
raise ValueError("Invalid bencode data")
def get_torrent_infohash(self, torrent_bytes):
data = torrent_bytes
if not data.startswith(b"d"):
return ""
index = 1
while index < len(data) and data[index:index + 1] != b"e":
key_start = index
key_end = self.skip_bencode_value(data, key_start)
key_data = data[key_start:key_end]
colon = key_data.index(b":")
key = key_data[colon + 1:]
value_start = key_end
value_end = self.skip_bencode_value(data, value_start)
if key == b"info":
return hashlib.sha1(data[value_start:value_end]).hexdigest()
index = value_end
return ""
def find_existing_torrent_by_infohash(self, infohash):
if not infohash:
return None
target = str(infohash).lower()
active, waiting, stopped = self.get_aria2_items()
for item in active + waiting + stopped:
bittorrent = item.get("bittorrent", {})
current = str(bittorrent.get("infoHash", "")).lower()
if current == target:
return item
return None
def remove_existing_torrent_gid(self, gid):
if not gid:
return False
try:
self.rpc("aria2.remove", [gid])
self.save_aria2_session()
return True
except Exception:
pass
try:
self.rpc("aria2.removeDownloadResult", [gid])
self.save_aria2_session()
return True
except Exception:
return False
def build_torrent_options(self, private=False, seed=False):
if seed:
seed_time = "525600"
else:
seed_time = "0"
if private:
return {
"seed-time": seed_time,
"seed-ratio": "0.0",
"enable-dht": "false",
"enable-dht6": "false",
"enable-peer-exchange": "false",
"bt-enable-lpd": "false",
"bt-save-metadata": "true",
"bt-load-saved-metadata": "true",
"bt-request-peer-speed-limit": "50K"
}
return {
"seed-time": seed_time,
"seed-ratio": "0.0",
"enable-dht": "true",
"enable-dht6": "true",
"enable-peer-exchange": "true",
"bt-enable-lpd": "true",
"bt-save-metadata": "true",
"bt-load-saved-metadata": "true",
"bt-request-peer-speed-limit": "50K"
}
def get_aria2_status(self, gid):
keys = [
"gid",
"status",
"totalLength",
"completedLength",
"downloadSpeed",
"uploadSpeed",
"uploadLength",
"connections",
"numSeeders",
"shareRatio",
"errorCode",
"errorMessage",
"files",
"bittorrent",
"followedBy",
"following",
"belongsTo"
]
return self.rpc("aria2.tellStatus", [gid, keys])
def get_aria2_items(self):
keys = [
"gid",
"status",
"totalLength",
"completedLength",
"downloadSpeed",
"uploadSpeed",
"uploadLength",
"connections",
"numSeeders",
"shareRatio",
"errorCode",
"errorMessage",
"files",
"bittorrent",
"followedBy",
"following",
"belongsTo"
]
active = self.rpc("aria2.tellActive", [keys])
waiting = self.rpc("aria2.tellWaiting", [0, 100, keys])
stopped = self.rpc("aria2.tellStopped", [0, 100, keys])
return active, waiting, stopped
def get_active_waiting_stopped(self):
return self.get_aria2_items()
def print_aria2_status(self):
active, waiting, stopped = self.get_aria2_items()
groups = [
("Active", active),
("Waiting", waiting),
("Stopped", stopped)
]
for title, items in groups:
print("")
print(title)
print("-" * 80)
if not items:
print("No items")
continue
for item in items:
gid = item.get("gid", "")
status = item.get("status", "")
total = int(item.get("totalLength", "0") or 0)
completed = int(item.get("completedLength", "0") or 0)
speed = int(item.get("downloadSpeed", "0") or 0)
upload_speed = int(item.get("uploadSpeed", "0") or 0)
uploaded = int(item.get("uploadLength", "0") or 0)
share_ratio = item.get("shareRatio", "0")
connections = item.get("connections", "0")
seeders = item.get("numSeeders", "0")
bittorrent = item.get("bittorrent", {})
infohash = bittorrent.get("infoHash", "")
percent = 0
if total > 0:
percent = completed * 100 / total
files = item.get("files", [])
name = ""
if files:
name = Path(files[0].get("path", "")).name
print("GID:", gid)
print("Status:", status)
print("Name:", name or "unknown")
print("InfoHash:", infohash or "unknown")
print("Progress:", f"{percent:.2f}%")
print("Completed:", self.format_bytes(completed), "/", self.format_bytes(total))
print("Download Speed:", self.format_bytes(speed) + "/s")
print("Upload Speed:", self.format_bytes(upload_speed) + "/s")
print("Uploaded:", self.format_bytes(uploaded))
print("Ratio:", share_ratio)
print("Connections:", connections)
print("Seeders:", seeders)
if item.get("errorMessage"):
print("Error:", item.get("errorMessage"))
print("-" * 80)
def purge_aria2_stopped(self):
try:
result = self.rpc("aria2.purgeDownloadResult")
self.save_aria2_session()
print("Stopped download results cleared")
print(result)
except Exception as error:
print("Failed to purge stopped downloads:", error)
def remove_aria2_gid(self):
gid = input("GID to remove: ").strip()
if not gid:
print("No GID entered")
return
removed = self.remove_existing_torrent_gid(gid)
if removed:
print("GID removed:", gid)
else:
print("Failed to remove GID:", gid)
def find_real_torrent_gid(self, metadata_gid, save_dir):
save_dir = str(save_dir)
for _ in range(120):
try:
status = self.get_aria2_status(metadata_gid)
except Exception:
status = {}
followed_by = status.get("followedBy", [])
if followed_by:
real_gid = followed_by[0]
print("Metadata completed")
print("Real torrent GID:", real_gid)
return real_gid
active, waiting, stopped = self.get_active_waiting_stopped()
candidates = active + waiting + stopped
for item in candidates:
gid = item.get("gid")
if gid == metadata_gid:
continue
belongs_to = item.get("belongsTo")
following = item.get("following")
if belongs_to == metadata_gid or following == metadata_gid:
print("Real torrent GID:", gid)
return gid
files = item.get("files", [])
for file_item in files:
path = file_item.get("path", "")
if path and str(path).startswith(save_dir):
total = int(item.get("totalLength", "0") or 0)
if total > 0:
print("Real torrent GID:", gid)
return gid
state = status.get("status")
if state == "error":
raise RuntimeError(status.get("errorMessage") or "Metadata failed.")
time.sleep(1)
print("Could not detect a separate real torrent GID")
print("Using original GID")
return metadata_gid
def wait_for_torrent_metadata(self, gid):
bar = tqdm(total=1, desc="Fetching metadata", unit="step")
while True:
status = self.get_aria2_status(gid)
if status.get("status") == "error":
bar.close()
self.save_aria2_session()
raise RuntimeError(status.get("errorMessage") or "Metadata fetch failed.")
followed_by = status.get("followedBy", [])
files = status.get("files", [])
total = int(status.get("totalLength", "0") or 0)
if followed_by:
bar.update(1)
bar.close()
self.save_aria2_session()
return
if files and total > 0:
bittorrent = status.get("bittorrent", {})
info = bittorrent.get("info", {})
if info:
bar.update(1)
bar.close()
self.save_aria2_session()
return
if status.get("status") == "complete" and files and total > 0:
bar.update(1)
bar.close()
self.save_aria2_session()
return
time.sleep(1)
def monitor_aria2(self, gid, label, seed=False):
last_completed = 0
progress = None
last_state = None
printed_file = None
seeding_notice_printed = False
seed_started_at = None
seed_bar = None
last_session_save = time.time()
while True:
status = self.get_aria2_status(gid)
state = status.get("status")
total = int(status.get("totalLength", "0") or 0)
completed = int(status.get("completedLength", "0") or 0)
speed = int(status.get("downloadSpeed", "0") or 0)
upload_speed = int(status.get("uploadSpeed", "0") or 0)
uploaded = int(status.get("uploadLength", "0") or 0)
seeders = status.get("numSeeders", "0")
connections = status.get("connections", "0")
share_ratio = status.get("shareRatio", "0")
files = status.get("files", [])
if time.time() - last_session_save >= 30:
self.save_aria2_session()
last_session_save = time.time()
if state != last_state:
print("Status:", state)
last_state = state
if files:
first_file = files[0].get("path", "")
if first_file and first_file != printed_file:
print("File:", Path(first_file).name)
printed_file = first_file
if state == "error":
if progress is not None:
progress.close()
if seed_bar is not None:
seed_bar.close()
self.save_aria2_session()
raise RuntimeError(status.get("errorMessage") or "Download failed.")
if progress is None and total > 0 and not (seed and completed >= total):
progress = tqdm(
total=total,
unit="B",
unit_scale=True,
unit_divisor=1024,
desc=label
)
if progress is not None:
if completed < last_completed:
last_completed = 0
progress.n = 0
delta = completed - last_completed
if delta > 0:
progress.update(delta)
percent = 0
if total > 0:
percent = completed * 100 / total
postfix = {
"percent": f"{percent:.2f}%",
"down": self.format_bytes(speed) + "/s",
"up": self.format_bytes(upload_speed) + "/s",
"uploaded": self.format_bytes(uploaded),
"ratio": str(share_ratio),
"connections": connections
}
if str(seeders) != "0":
postfix["seeders"] = seeders
progress.set_postfix(postfix)
last_completed = completed
if seed and total > 0 and completed >= total:
if seed_started_at is None:
seed_started_at = time.time()
if not seeding_notice_printed:
print("Download completed")
print("Seeding is enabled")
print("Keep this Colab runtime alive to continue seeding")
print("Press interrupt if you want to stop seeding")
seeding_notice_printed = True
if progress is not None:
progress.n = total
progress.refresh()
progress.close()
progress = None
seed_bar = tqdm(
total=1,
unit="step",