-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathOneDL.py
More file actions
2575 lines (2128 loc) · 91.8 KB
/
OneDL.py
File metadata and controls
2575 lines (2128 loc) · 91.8 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
#!/usr/bin/env python3
"""
OneDL - Universal Debrid & Downloader Tool
https://github.com/ellite/OneDL
By ellite
OneDL is a command-line tool to simplify downloading from hosters, torrents, cloud debrid services, direct HTTP(S) links, and container files (.torrent & .nzb).
It supports Real-Debrid, AllDebrid, Premiumize.me, Torbox and Debrid-Link, allowing you to resolve direct links from magnets,
hoster URLs, MEGA folders, standard HTTP(S) links, or by uploading .torrent and .nzb files, and download them.
USAGE:
1. Run the script from the folder where you want your downloaded files: onedl
2. Choose to load URLs from a file, paste them manually, or use a debrid service.
3. For debrid services, select Real-Debrid, AllDebrid, Premiumize.me, Torbox, Debrid-Link or let OneDL find the best option.
4. Paste your magnet, hoster, MEGA, HTTP(S) URL, or upload a .torrent/.nzb file when prompted.
5. Select files if needed, and OneDL will resolve and download them for you.
FEATURES:
- Supports magnet links, hoster URLs, MEGA folders, direct HTTP(S) links, and container files (.torrent & .nzb).
- Integrates with Real-Debrid, AllDebrid, Premiumize.me, Torbox and Debrid-Link.
- Shows download progress bars with speed and seeders.
- Lets you pick files from torrents, NZBs, or containers.
- Colorful, user-friendly terminal output.
Configure your API tokens by editing ~/.onedl.conf (check https://raw.githubusercontent.com/ellite/OneDL/refs/heads/main/.onedl.conf).
More info: https://github.com/ellite/OneDL/blob/main/README.md
"""
import os
import sys
import hashlib
import urllib.parse
import time
import requests
import json
import re
import bencodepy
VERSION = "1.10.0"
CYAN = "\033[96m"
YELLOW = "\033[93m"
GREEN = "\033[92m"
RED = "\033[91m"
RESET = "\033[0m"
LOADED_PATH = None
# --- CONFIGURATION LOADER ---
def load_config():
# Define search paths in order of priority
search_paths = [
# 1. Same directory as the script (Portable / Windows friendly)
os.path.join(os.path.dirname(os.path.abspath(__file__)), ".onedl.conf"),
# 2. User Home Directory (Linux/macOS standard)
os.path.join(os.path.expanduser("~"), ".onedl.conf")
]
config = {}
loaded_path = None
for path in search_paths:
if os.path.exists(path):
try:
with open(path, 'r') as f:
config = json.load(f)
loaded_path = path
break # Stop searching if found
except Exception as e:
print(f"{RED}Warning: Found config at {path} but failed to load: {e}{RESET}")
return config, loaded_path
user_config, LOADED_PATH = load_config()
# Load keys from config, default to empty string if missing
REAL_DEBRID_API_TOKEN = user_config.get("REAL_DEBRID_API_TOKEN", "")
ALLDEBRID_API_TOKEN = user_config.get("ALLDEBRID_API_TOKEN", "")
PREMIUMIZE_API_TOKEN = user_config.get("PREMIUMIZE_API_TOKEN", "")
TORBOX_API_TOKEN = user_config.get("TORBOX_API_TOKEN", "")
DEBRID_LINK_API_TOKEN = user_config.get("DEBRID_LINK_API_TOKEN", "")
def check_for_updates():
update_url = "https://raw.githubusercontent.com/ellite/OneDL/main/OneDL.py"
try:
response = requests.get(update_url, timeout=5)
response.raise_for_status()
match = re.search(r'VERSION\s*=\s*["\']([^"\']+)["\']', response.text)
if match:
remote_version_str = match.group(1)
local_ver = tuple(map(int, VERSION.split('.')))
remote_ver = tuple(map(int, remote_version_str.split('.')))
if remote_ver > local_ver:
print(f"\n{YELLOW}┌────────────────────────────────────────────────┐{RESET}")
print(f"{YELLOW}│{RESET} {GREEN}Update Available!{RESET} v{VERSION} -> v{remote_version_str} {YELLOW}│{RESET}")
print(f"{YELLOW}│{RESET} Run the update command in README to upgrade. {RESET} {YELLOW}│{RESET}")
print(f"{YELLOW}└────────────────────────────────────────────────┘{RESET}\n")
return True
except Exception as e:
pass
return False
# --- STATUS DASHBOARD ---
def print_status_box():
# Define services map
services = [
("Real-Debrid", REAL_DEBRID_API_TOKEN),
("AllDebrid", ALLDEBRID_API_TOKEN),
("Premiumize", PREMIUMIZE_API_TOKEN),
("Torbox", TORBOX_API_TOKEN),
("Debrid-Link", DEBRID_LINK_API_TOKEN)
]
# Calculate box width
path_str = LOADED_PATH if LOADED_PATH else "None (Using defaults)"
box_width = max(50, len(path_str) + 14)
# Helper to print lines
def print_line(content, color=CYAN):
print(f"{color}║{RESET} {content} {color}║{RESET}")
def print_border(start, mid, end, color=CYAN):
print(f"{color}{start}{mid * (box_width - 2)}{end}{RESET}")
# --- DRAW BOX ---
print_border("╔", "═", "╗")
# Title (Centered)
title = f"OneDL v{VERSION}"
padding = (box_width - 4 - len(title)) // 2
# Adjust right padding if odd length
r_padding = box_width - 4 - len(title) - padding
print_line(" " * padding + f"{YELLOW}{title}{RESET}" + " " * r_padding)
print_border("╠", "═", "╣")
# Config Path (Left Aligned)
label = "Config:"
spaces = box_width - 4 - len(label) - 1 - len(path_str)
print_line(f"{label} {GREEN}{path_str}{RESET}" + " " * spaces)
print_border("╟", "─", "╢")
# Service Status
for name, token in services:
status_text = "ENABLED" if token else "DISABLED"
status_color = GREEN if token else RED
spaces = box_width - 4 - len(name) - 1 - len(status_text)
# Construct the line
line_content = f"{name}:{ ' ' * spaces }{status_color}{status_text}{RESET}"
print_line(line_content)
print_border("╚", "═", "╝")
def list_files():
files = [f for f in os.listdir('.') if os.path.isfile(f)]
return files
def list_text_files():
files = [f for f in os.listdir('.') if os.path.isfile(f) and f.endswith('.txt')]
return files
def get_urls_from_file():
files = list_files()
if not files:
print(f"{RED}No files found in the current directory.{RESET}")
return []
print()
print(f"{CYAN}Select a file to load URLs from:{RESET}")
for idx, f in enumerate(files, 1):
print(f"{YELLOW}{idx}{RESET}: {f}")
while True:
choice = input(f"Enter the number of the file: ")
if choice.isdigit() and 1 <= int(choice) <= len(files):
filename = files[int(choice) - 1]
try:
with open(filename, 'r') as file:
# 1. Read all non-empty lines
all_urls = [line.strip() for line in file if line.strip()]
if not all_urls:
print(f"{RED}File is empty.{RESET}")
return []
print(f"{GREEN}Loaded {len(all_urls)} URLs from '{filename}'.{RESET}")
selected_indexes = select_files_interactive(all_urls, "Select URLs to download")
final_urls = [all_urls[i] for i in selected_indexes]
print(f"{GREEN}Selected {len(final_urls)} URLs.{RESET}")
return final_urls
except Exception as e:
print(f"{RED}Could not read file '{filename}': {e}{RESET}")
print(f"{YELLOW}Please select a different file.{RESET}")
continue
print(f"{RED}Invalid choice, try again.{RESET}")
def get_urls_from_input():
print()
print("Paste your URLs one per line (press enter on an empty line to finish):")
urls = []
while True:
line = input()
if not line.strip():
break
urls.append(line.strip())
return urls
def select_files_interactive(files, prompt="Enter selection"):
"""
Unified selection handler for all debrid providers.
files: list of dicts or strings (anything indexable)
prompt: custom prompt string
Returns: list of 0-based indexes
"""
max_index = len(files)
print(f"{CYAN}{prompt}:{RESET}")
for idx, f in enumerate(files, 1):
if isinstance(f, dict):
name = f.get("name") or f.get("short_name") or f.get("path") or str(f)
else:
name = str(f)
size = f.get("size") if isinstance(f, dict) else None
if size:
mb = size // (1024 * 1024)
print(f"{YELLOW}{idx}{RESET}: {name} {CYAN}({mb} MB){RESET}")
else:
print(f"{YELLOW}{idx}{RESET}: {name}")
choice = input(
f"{CYAN}Enter numbers, commas, ranges (e.g. 1,3-5) or 'all' (default all): {RESET}"
).strip()
# Default = all
if not choice or choice.lower() == "all":
return list(range(max_index))
# Use your existing range parser
raw = parse_selection(choice, max_index)
selected = [i - 1 for i in raw if 1 <= i <= max_index]
return selected
def show_progress_factory():
start_time = [time.time()]
def show_progress(block_num, block_size, total_size):
downloaded = block_num * block_size
elapsed = time.time() - start_time[0]
speed = downloaded / elapsed if elapsed > 0 else 0
percent = min(100, downloaded * 100 // (total_size or 1))
bar_length = 50
num_hashes = percent // 2
bar = '#' * num_hashes
bar = bar.ljust(bar_length)
bar_colored = f"{YELLOW}{bar}{RESET}"
if speed >= 1024 * 1024:
speed_str = f"{speed/1024/1024:.2f} MB/s"
elif speed >= 1024:
speed_str = f"{speed/1024:.1f} KB/s"
else:
speed_str = f"{speed:.0f} B/s"
elapsed_str = time.strftime("%M:%S", time.gmtime(elapsed))
sys.stdout.write(f"\r[{bar_colored}] {GREEN}{percent}%{RESET} {YELLOW}::{RESET} {speed_str} {YELLOW}::{RESET} {elapsed_str}")
sys.stdout.flush()
if downloaded >= total_size:
print()
return show_progress
def download_file(url, filename=None):
def human_readable_size(num):
for unit in ["B", "KB", "MB", "GB", "TB"]:
if num < 1024:
return f"{num:.2f} {unit}"
num /= 1024
return f"{num:.2f} PB"
try:
with requests.get(url, stream=True, allow_redirects=True) as r:
r.raise_for_status()
if filename is None:
cd = r.headers.get('content-disposition')
if cd:
fname = re.findall('filename="(.+)"', cd)
filename = fname[0] if fname else url.split("/")[-1]
else:
filename = r.url.split("/")[-1]
else:
cd = r.headers.get('content-disposition')
if cd:
fname = re.findall('filename="(.+)"', cd)
filename = fname[0] if fname else url.split("/")[-1]
else:
filename = r.url.split("/")[-1]
filename = urllib.parse.unquote(filename)
total_size = int(r.headers.get('content-length', 0))
total_human = human_readable_size(total_size)
print(f"Downloading: {YELLOW}{filename}{RESET} ({CYAN}{total_human}{RESET})")
start_time = time.time()
downloaded = 0
block_size = 8192
with open(filename, "wb") as f:
for chunk in r.iter_content(block_size):
if not chunk:
continue
f.write(chunk)
downloaded += len(chunk)
elapsed = time.time() - start_time
speed = downloaded / elapsed if elapsed > 0 else 0
percent = int(downloaded * 100 / total_size) if total_size else 0
bar_length = 50
filled = percent * bar_length // 100
bar = "#" * filled + " " * (bar_length - filled)
# Convert speed
if speed >= 1024 * 1024:
speed_str = f"{speed/1024/1024:.2f} MB/s"
elif speed >= 1024:
speed_str = f"{speed/1024:.1f} KB/s"
else:
speed_str = f"{speed:.0f} B/s"
elapsed_str = time.strftime("%M:%S", time.gmtime(elapsed))
downloaded_human = human_readable_size(downloaded)
sys.stdout.write(
f"\r[{YELLOW}{bar}{RESET}] "
f"{GREEN}{percent}%{RESET} "
f":: {CYAN}{speed_str}{RESET} "
f":: {downloaded_human}/{total_human} "
f":: {elapsed_str}"
)
sys.stdout.flush()
print()
print(f"{GREEN}Saved as:{RESET} {YELLOW}{filename}{RESET}")
except Exception as e:
print(f"{RED}Failed to download:{RESET} {YELLOW}{url}{RESET} {RED}- {e}{RESET}")
def torrent_to_magnet(filepath):
with open(filepath, 'rb') as f:
torrent = bencodepy.decode(f.read())
info = torrent[b'info']
# Get the bencoded info dict and SHA1 hash
info_bencoded = bencodepy.encode(info)
info_hash = hashlib.sha1(info_bencoded).hexdigest()
# Get display name
name = info.get(b'name', b'').decode('utf-8', errors='ignore')
# Build magnet link
magnet = f"magnet:?xt=urn:btih:{info_hash}"
if name:
magnet += f"&dn={urllib.parse.quote(name)}"
return magnet
def is_magnet(url):
return url.strip().startswith("magnet:")
def parse_selection(selection_input, max_index):
selection = set()
for part in selection_input.split(","):
part = part.strip()
if '-' in part:
try:
start, end = map(int, part.split('-'))
if start <= end and 1 <= start <= max_index and 1 <= end <= max_index:
selection.update(range(start, end + 1))
except ValueError:
continue
elif part.isdigit():
idx = int(part)
if 1 <= idx <= max_index:
selection.add(idx)
return sorted(selection)
def get_real_debrid_links(url=None):
token = REAL_DEBRID_API_TOKEN
while not url:
url = input(f"Paste your magnet or hoster URL: ").strip()
headers = {"Authorization": f"Bearer {token}"}
if is_magnet(url):
# Magnet logic
resp = requests.post(
"https://api.real-debrid.com/rest/1.0/torrents/addMagnet",
data={"magnet": url},
headers=headers
)
if resp.status_code != 201:
print(f"{RED}Failed to add magnet.{RESET}")
return []
torrent_id = resp.json()["id"]
# Wait for torrent to be ready
selection_sent = False
while True:
info = requests.get(
f"https://api.real-debrid.com/rest/1.0/torrents/info/{torrent_id}",
headers=headers
).json()
if info["status"] in ("waiting_files", "waiting_files_selection"):
if not selection_sent:
files = info["files"]
display_files = []
for f in files:
path = f.get("path", "").lstrip("/\\")
size_bytes = f.get("bytes", 0)
mb = size_bytes // (1024 * 1024)
display_files.append({
"name": path,
"size": size_bytes,
})
print()
selected_indexes = select_files_interactive(
display_files,
"Select files in torrent"
)
if not selected_indexes:
print(f"{RED}No files selected.{RESET}")
return []
file_ids = [str(files[i]["id"]) for i in selected_indexes]
requests.post(
f"https://api.real-debrid.com/rest/1.0/torrents/selectFiles/{torrent_id}",
data={"files": ",".join(file_ids)},
headers=headers
)
print(f"{GREEN}Selection sent, waiting for Real-Debrid to process...{RESET}")
selection_sent = True
else:
print(f"{YELLOW}Waiting for Real-Debrid to process your selection...{RESET}")
time.sleep(3)
elif info["status"] == "downloaded":
links = []
for dl in info["links"]:
# Unrestrict each link to get the direct download
r = requests.post(
"https://api.real-debrid.com/rest/1.0/unrestrict/link",
data={"link": dl},
headers=headers
)
if r.status_code == 200 and "download" in r.json():
links.append(r.json()["download"])
print(f"{GREEN}Resolved direct links:{RESET}")
for l in links:
print(f"{YELLOW}{l}{RESET}")
return links
elif info["status"] == "magnet_error":
print(f"{RED}Magnet error.{RESET}")
return []
else:
if info["status"] == "downloading":
speed = info.get("speed", 0)
seeders = info.get("seeders", 0)
percent = info.get("progress", 0)
bar_length = 30
num_hashes = int(percent * bar_length // 100)
bar = '#' * num_hashes
bar = bar.ljust(bar_length)
bar_colored = f"{YELLOW}{bar}{RESET}"
percent_str = f"{GREEN}{percent}%{RESET}"
if speed >= 1024 * 1024:
speed_str = f"{speed/1024/1024:.2f} MB/s"
elif speed >= 1024:
speed_str = f"{speed/1024:.1f} KB/s"
else:
speed_str = f"{speed:.0f} B/s"
sys.stdout.write(
f"\r{YELLOW}Downloading to cloud...{RESET} [{bar_colored}] "
f"{percent_str} | Speed: {CYAN}{speed_str}{RESET} | "
f"Seeders: {GREEN}{seeders}{RESET} "
)
sys.stdout.flush()
else:
print(f"{YELLOW}Waiting for Real-Debrid... Status: {info['status']}{RESET}")
time.sleep(3)
if info["status"] != "downloading":
print()
time.sleep(3)
elif "mega.nz/folder/" in url and "/file/" not in url:
# Extract file links from folder
file_links = extract_mega_files_from_folder(url)
if not file_links:
print(f"{RED}Could not extract MEGA file links from folder.{RESET}")
return []
print()
print(f"{YELLOW}Unlocking files...{RESET}")
unlocked = []
for f in file_links:
resp = requests.post(
"https://api.real-debrid.com/rest/1.0/unrestrict/link",
data={"link": f},
headers=headers
)
data = resp.json()
if "download" in data:
filename = data.get("filename") or urllib.parse.unquote(f.split("/")[-1])
unlocked.append({
"name": filename,
"url": data["download"]
})
else:
print(f"{RED}Could not unlock:{RESET} {YELLOW}{f}{RESET}")
if not unlocked:
print(f"{RED}No files were unlocked.{RESET}")
return []
selected_indexes = select_files_interactive(
unlocked,
"Select files to download"
)
if not selected_indexes:
print(f"{RED}No files selected.{RESET}")
return []
return [unlocked[i]["url"] for i in selected_indexes]
else:
# Hoster logic
resp = requests.post(
"https://api.real-debrid.com/rest/1.0/unrestrict/link",
data={"link": url},
headers=headers
)
data = resp.json()
if resp.status_code == 200 and "download" in data:
print(f"{GREEN}Resolved direct link:{RESET}")
print(f"{YELLOW}{data['download']}{RESET}")
return [data["download"]]
print(f"{RED}Hoster not supported or failed.{RESET}")
def parse_alldebrid_files(files_list):
"""
Recursively extract files with links from AllDebrid's nested structure.
AllDebrid uses 'e' for folder entries and 'l' for file links.
"""
flat_files = []
for item in files_list:
# If it has a link ('l'), it's a download-ready file
if "l" in item:
flat_files.append({
"name": item.get("n", "Unknown"),
"size": item.get("s", 0),
"link": item.get("l")
})
# If it has entries ('e'), it's a folder -> recurse down
elif "e" in item:
flat_files.extend(parse_alldebrid_files(item["e"]))
return flat_files
def get_alldebrid_links(url=None):
token = ALLDEBRID_API_TOKEN or input(f"{CYAN}Enter your AllDebrid API token:{RESET} ").strip()
if not url:
url = input(f"{CYAN}Paste your magnet or hoster URL:{RESET} ").strip()
if is_magnet(url):
# 1. UPLOAD MAGNET
resp = requests.post(
"https://api.alldebrid.com/v4/magnet/upload",
data={"agent": "dl-script", "apikey": token, "magnets[]": url}
)
data = resp.json()
if data.get("status") != "success":
print(f"{RED}Failed to add magnet: {data.get('error', {}).get('message', 'Unknown error')}{RESET}")
return []
# AllDebrid upload response 'magnets' is a list
magnet_id = data["data"]["magnets"][0]["id"]
# 2. POLL STATUS
while True:
status_resp = requests.get(
"https://api.alldebrid.com/v4.1/magnet/status",
params={"agent": "dl-script", "apikey": token, "id": magnet_id}
).json()
if status_resp.get("status") != "success":
print(f"{RED}Error fetching status.{RESET}")
return []
# For ID requests, 'magnets' is usually a dict, but safety check for list
magnet = status_resp["data"]["magnets"]
if isinstance(magnet, list):
magnet = magnet[0]
status_code = magnet.get("statusCode")
status_msg = magnet.get("status", "Unknown")
# --- CASE A: READY (Links available) ---
if status_code == 4:
# FIXED: Extract links recursively from the 'files' tree
files_tree = magnet.get("files", [])
# Use our new helper function to flatten the nested JSON
available_files = parse_alldebrid_files(files_tree)
if not available_files:
print(f"{RED}Torrent is ready but returned no links/files.{RESET}")
# Debug print to help identify structure issues
# print(json.dumps(magnet, indent=3))
return []
print(f"\n{GREEN}Torrent Ready! Found {len(available_files)} links.{RESET}")
# Build display list for the Unified Selector
display_files = []
for f in available_files:
display_files.append({
"name": f["name"],
"size": f["size"]
})
# 3. SELECT FILES (Client-Side)
selected_indexes = select_files_interactive(
display_files,
"Select files to download"
)
if not selected_indexes:
print(f"{RED}No files selected.{RESET}")
return []
final_urls = []
print(f"{CYAN}Unlocking selected links...{RESET}")
# 4. UNLOCK SELECTED LINKS
for idx in selected_indexes:
file_info = available_files[idx]
link_to_unlock = file_info["link"]
unlock_resp = requests.get(
"https://api.alldebrid.com/v4.1/link/unlock",
params={"agent": "dl-script", "apikey": token, "link": link_to_unlock}
).json()
if unlock_resp.get("status") == "success":
unlocked_link = unlock_resp["data"].get("link")
if unlocked_link:
final_urls.append(unlocked_link)
print(f"{GREEN}Unlocked:{RESET} {file_info['name']}")
else:
err = unlock_resp.get("error", {}).get("message", "Unknown")
print(f"{RED}Failed to unlock:{RESET} {file_info['name']} ({err})")
return final_urls
# --- CASE B: DOWNLOADING / QUEUED ---
elif status_code in (0, 1, 2, 3):
downloaded = magnet.get("downloaded", 0)
size = magnet.get("size", 1)
speed = magnet.get("downloadSpeed", 0)
seeders = magnet.get("seeders", 0)
percent = (downloaded / size) * 100 if size > 0 else 0
if speed > 1024*1024: speed_str = f"{speed/1024/1024:.2f} MB/s"
elif speed > 1024: speed_str = f"{speed/1024:.0f} KB/s"
else: speed_str = f"{speed} B/s"
bar_len = 30
filled = int(percent / 100 * bar_len)
bar = "#" * filled + "-" * (bar_len - filled)
sys.stdout.write(
f"\r{YELLOW}{status_msg}...{RESET} "
f"[{bar}] {GREEN}{percent:.1f}%{RESET} "
f"| {CYAN}{speed_str}{RESET} | S: {seeders} "
)
sys.stdout.flush()
time.sleep(2)
# --- CASE C: ERROR ---
elif status_code > 4:
error_code = magnet.get("errorCode")
print(f"\n{RED}Magnet Error {error_code}: {status_msg}{RESET}")
requests.get(
"https://api.alldebrid.com/v4.1/magnet/delete",
params={"agent": "dl-script", "apikey": token, "id": magnet_id}
)
return []
else:
time.sleep(2)
elif "mega.nz/folder/" in url and "/file/" not in url:
# Extract MEGA folder contents
file_links = extract_mega_files_from_folder(url)
if not file_links:
print(f"{RED}Could not extract MEGA file links from folder.{RESET}")
return []
print(f"{YELLOW}Unlocking files...{RESET}")
unlocked = []
for f in file_links:
resp = requests.get(
"https://api.alldebrid.com/v4.1/link/unlock",
params={"agent": "dl-script", "apikey": token, "link": f}
)
data = resp.json()
if data.get("status") == "success" and "link" in data.get("data", {}):
filename = data["data"].get("filename") or f.split("/")[-1]
unlocked.append({
"name": filename,
"url": data["data"]["link"]
})
else:
print(f"{RED}Could not unlock:{RESET} {YELLOW}{f}{RESET}")
if not unlocked:
print(f"{RED}No files were unlocked.{RESET}")
return []
# Unified selection
selected = select_files_interactive(
unlocked,
"Select files to download"
)
return [unlocked[i]["url"] for i in selected]
else:
# Hoster direct unlock
resp = requests.get(
"https://api.alldebrid.com/v4.1/link/unlock",
params={"agent": "dl-script", "apikey": token, "link": url}
)
data = resp.json()
if data.get("status") == "success" and "link" in data.get("data", {}):
print(f"{GREEN}Resolved direct link:{RESET}")
print(f"{YELLOW}{data['data']['link']}{RESET}")
return [data["data"]["link"]]
print(f"{RED}Hoster not supported or failed.{RESET}")
return []
def get_premiumize_links(url=None):
token = PREMIUMIZE_API_TOKEN or input(f"{CYAN}Enter your Premiumize.me API token:{RESET} ").strip()
if not url:
url = input(f"{CYAN}Paste your magnet or hoster URL:{RESET} ").strip()
if is_magnet(url):
# Magnet logic
resp = requests.get(
"https://www.premiumize.me/api/transfer/create",
params={"apikey": token, "src": url}
)
resp.raise_for_status()
data = resp.json()
transfer_id = data["id"]
print()
print(f"{GREEN}Transfer created, ID:{RESET} {YELLOW}{transfer_id}{RESET}")
# Wait until finished
while True:
resp = requests.get(
"https://www.premiumize.me/api/transfer/list",
params={"apikey": token}
)
resp.raise_for_status()
library = resp.json().get("transfers", [])
transfer = next((t for t in library if t["id"] == transfer_id), None)
if not transfer:
print(f"{RED}Transfer not found after creation.{RESET}")
return []
progress = transfer.get('progress')
if progress is None:
progress = 1.0 if transfer.get("status") == "finished" else 0.0
percent = progress * 100
# Try to extract speed and peers from the message
speed = 0
seeders = 0
msg = transfer.get("message") or ""
if msg:
speed_match = re.search(r"([\d\.]+)\s*(KB|MB|B)/s", msg)
if speed_match:
val, unit = speed_match.groups()
val = float(val)
if unit == "MB":
speed = int(val * 1024 * 1024)
elif unit == "KB":
speed = int(val * 1024)
else:
speed = int(val)
seeders_match = re.search(r"from (\d+) peer", msg)
if seeders_match:
seeders = int(seeders_match.group(1))
bar_length = 30
num_hashes = int(percent * bar_length // 100)
bar = '#' * num_hashes
bar = bar.ljust(bar_length)
bar_colored = f"{YELLOW}{bar}{RESET}"
percent_str = f"{GREEN}{percent:.2f}%{RESET}"
if speed >= 1024 * 1024:
speed_str = f"{speed/1024/1024:.2f} MB/s"
elif speed >= 1024:
speed_str = f"{speed/1024:.1f} KB/s"
else:
speed_str = f"{speed:.0f} B/s"
# Only show progress bar if actually downloading
if transfer["status"] == "running" and progress < 1.0 and "Moving to cloud" not in msg:
sys.stdout.write(
f"\r{YELLOW}Downloading to cloud...{RESET} [{bar_colored}] {percent_str} | Speed: {CYAN}{speed_str}{RESET} | Seeders: {GREEN}{seeders}{RESET} "
)
sys.stdout.flush()
else:
# Print a status message instead of progress bar
sys.stdout.write(f"\r{YELLOW}{msg or transfer['status'].capitalize()}{RESET} {' ' * 60}\n")
sys.stdout.flush()
if transfer["status"] == "finished":
folder_id = transfer["folder_id"]
break
if transfer["status"] == "error":
print(f"\n{RED}Premiumize transfer error.{RESET}")
return []
time.sleep(3)
folder_resp = requests.get(
"https://www.premiumize.me/api/folder/list",
params={"apikey": token, "id": folder_id}
).json()
files = [
f for f in folder_resp.get("content", [])
if f.get("type") == "file" and "link" in f
]
if not files:
print(f"{RED}No downloadable files found in transfer folder.{RESET}")
return []
display_files = [
{"name": f.get("name", "Unknown"), "size": f.get("size", 0)}
for f in files
]
selected_indexes = select_files_interactive(
display_files,
"Select files to download"
)
return [files[i]["link"] for i in selected_indexes]
else:
# Hoster logic
resp = requests.get(
"https://www.premiumize.me/api/transfer/directdl",
params={"apikey": token, "src": url}
)
data = resp.json()
if data.get("status") == "success":
if "location" in data:
print(f"{GREEN}Resolved direct link:{RESET}")
print(f"{YELLOW}{data['location']}{RESET}")
return [data["location"]]
elif data.get("type") == "container" and "content" in data:
print(f"{CYAN}Container detected. Files in folder:{RESET}")
files = data["content"]
# Build display list for unified selector
display_files = [
{"name": str(f), "size": None}
for f in files
]
selected_indexes = select_files_interactive(
display_files,
"Select container entries"
)
selected = [files[i] for i in selected_indexes]
# Now unlock each selected file
unlocked = []
for f in selected:
unlock_resp = requests.get(
"https://www.premiumize.me/api/transfer/directdl",
params={"apikey": token, "src": f}
)
unlock_data = unlock_resp.json()
if unlock_data.get("status") == "success" and "location" in unlock_data:
unlocked.append(unlock_data["location"])
print(f"{GREEN}Unlocked:{RESET} {YELLOW}{f}{RESET} {CYAN}→{RESET} {GREEN}{unlock_data['location']}{RESET}")
else:
print(f"{RED}Could not unlock:{RESET} {YELLOW}{f}{RESET}")
return unlocked
print(f"{RED}Hoster not supported or failed.{RESET}")
return []
def get_premiumize_links_from_nzb(nzb_path: str) -> list[str]:
from pathlib import Path
import requests, time
print(f"{CYAN}Processing NZB via Premiumize...{RESET}")
params = {'apikey': PREMIUMIZE_API_TOKEN}
nzb_name = Path(nzb_path).name
try:
# 1️⃣ Create transfer
with open(nzb_path, "rb") as f:
resp = requests.post(
"https://www.premiumize.me/api/transfer/create",
params=params,
files={'file': (nzb_name, f, 'application/x-nzb')},
timeout=30
)
data = resp.json()
if data.get("status") != "success":
if data.get("message") == "You have already added this nzb file.":
print(f"{YELLOW}NZB already added. Attempting to find in transfer list...{RESET}")
list_resp = requests.get(
"https://www.premiumize.me/api/transfer/list",
params=params,
timeout=10
).json()
transfers = list_resp.get("transfers", [])
match = next((t for t in transfers if t.get("name") == nzb_name), None)
if match:
transfer_id = match.get("id")
print(f"{GREEN}Found existing transfer with ID {transfer_id}. Proceeding...{RESET}")
else:
print(f"{RED}Could not find existing transfer for this NZB.{RESET}")
return []
else:
print(f"{RED}Transfer failed: {data.get('error') or data.get('message')}{RESET}")
return []
else:
transfer_id = data["id"]
print(f"{GREEN}Transfer queued—ID {transfer_id}. {RESET}")
# 2️⃣ Poll until done (“finished” or “error”)
status = None
try:
while True:
lst = requests.get(
"https://www.premiumize.me/api/transfer/list",
params={**params, 'id': transfer_id},
timeout=10
).json()
info = lst.get("transfers", [{}])[0]
status = info.get("status")
message = (info.get("message") or "").strip()
progress = info.get("progress") or 0