forked from XronTrix10/Telegram-Leecher
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
1616 lines (1380 loc) · 53.1 KB
/
main.py
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
# @title 🖥️ Main Colab Leech Code [ Click on RUN for Magic ✨ ]
import os, io, re, sys, shutil, time, yt_dlp, math, pytz, psutil, threading, pickle, uvloop, pathlib, datetime, subprocess
from PIL import Image
from pyrogram import Client
from natsort import natsorted
from urllib.parse import urlparse
from re import search as re_search
from os import makedirs, path as ospath
from IPython.display import clear_output
from urllib.parse import parse_qs, urlparse
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaIoBaseDownload
from moviepy.video.io.VideoFileClip import VideoFileClip
from pyrogram.types import (
ReplyKeyboardMarkup,
InlineKeyboardMarkup,
InlineKeyboardButton,
)
uvloop.install()
# =================================================================
# Local OS Functions
# =================================================================
def convert_seconds(seconds):
seconds = int(seconds)
days = seconds // (24 * 3600)
seconds = seconds % (24 * 3600)
hours = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
if days > 0:
return f"{days}d {hours}h {minutes}m {seconds}s"
elif hours > 0:
return f"{hours}h {minutes}m {seconds}s"
elif minutes > 0:
return f"{minutes}m {seconds}s"
else:
return f"{seconds}s"
def size_measure(size):
if size > 1024 * 1024 * 1024 * 1024 * 1024:
siz = f"{size/(1024**5):.2f} PiB"
elif size > 1024 * 1024 * 1024 * 1024:
siz = f"{size/(1024**4):.2f} TiB"
elif size > 1024 * 1024 * 1024:
siz = f"{size/(1024**3):.2f} GiB"
elif size > 1024 * 1024:
siz = f"{size/(1024**2):.2f} MiB"
elif size > 1024:
siz = f"{size/1024:.2f} KiB"
else:
siz = f"{size} B"
return siz
def get_file_type(file_path):
extensions_dict = {
".mp4": "video",
".avi": "video",
".mkv": "video",
".mov": "video",
".webm": "video",
".vob": "video",
".m4v": "video",
".mp3": "audio",
".wav": "audio",
".flac": "audio",
".aac": "audio",
".ogg": "audio",
".jpg": "photo",
".jpeg": "photo",
".png": "photo",
".bmp": "photo",
".gif": "photo",
}
_, extension = ospath.splitext(file_path)
if extension.lower() in extensions_dict:
if extensions_dict[extension] == "video":
new_path = video_extension_fixer(file_path)
else:
new_path = file_path
return extensions_dict[extension], new_path
else:
return "document", file_path
def shorterFileName(path):
if ospath.isfile(path):
dir_path, filename = ospath.split(path)
if len(filename) > 60:
basename, ext = ospath.splitext(filename)
basename = basename[: 60 - len(ext)]
filename = basename + ext
path = ospath.join(dir_path, filename)
return path
elif ospath.isdir(path):
dir_path, dirname = ospath.split(path)
if len(dirname) > 60:
dirname = dirname[:60]
path = ospath.join(dir_path, dirname)
return path
else:
if len(path) > 60:
path = path[:60]
return path
def get_folder_size(folder_path):
if ospath.isfile(folder_path):
return ospath.getsize(folder_path)
else:
total_size = 0
for dirpath, _, filenames in os.walk(folder_path):
for f in filenames:
fp = ospath.join(dirpath, f)
total_size += ospath.getsize(fp)
return total_size
def get_file_count(folder_path):
count = 0
for _, __, filenames in os.walk(folder_path):
for f_ in filenames:
count += 1
return count
def video_extension_fixer(file_path):
_, f_name = ospath.split(file_path)
if f_name.endswith(".mp4") or f_name.endswith(".mkv"):
return file_path
else:
os.rename(file_path, ospath.join(file_path + ".mp4"))
return ospath.join(file_path + ".mp4")
def Thumbnail_Maintainer(file_path):
thmb = f"{d_path}/video_frame.jpg"
if ospath.exists(thmb):
os.remove(thmb)
try:
fname, _ = ospath.splitext(ospath.basename(file_path))
ytdl_thmb = f"{d_path}/ytdl_thumbnails/{fname}.webp"
with VideoFileClip(file_path) as video:
if ospath.exists(custom_thumb):
return custom_thumb, video.duration
elif ospath.exists(ytdl_thmb):
return convert_to_jpg(ytdl_thmb), video.duration
else:
video.save_frame(thmb, t=math.floor(video.duration / 2))
return thmb, video.duration
except Exception as e:
print(f"Thmb Gen ERROR: {e}")
return thumb_path, 0
def Thumbnail_Checker(dir_path):
for filename in os.listdir(dir_path):
_, ext = ospath.splitext(filename)
if ext in [".png", ".webp", ".bmp"]:
n_path = convert_to_jpg(ospath.join(dir_path, filename))
os.rename(n_path, custom_thumb)
return True
elif ext in [".jpeg", ".jpg"]:
os.rename(ospath.join(dir_path, filename), custom_thumb)
return True
# No jpg file was found
return False
def convert_to_jpg(image_path):
image = Image.open(image_path)
if image.mode != "RGB":
image = image.convert("RGB")
output_path = ospath.splitext(image_path)[0] + ".jpg"
image.save(output_path, "JPEG")
os.remove(image_path)
return output_path
def system_info():
ram_usage = psutil.Process(os.getpid()).memory_info().rss
disk_usage = psutil.disk_usage("/")
cpu_usage_percent = psutil.cpu_percent()
string = "\n\n⍟───── [Colab Usage](https://colab.research.google.com/drive/12hdEqaidRZ8krqj7rpnyDzg1dkKmvdvp) ─────⍟\n"
string += f"\n╭🖥️ **CPU Usage »** __{cpu_usage_percent}%__"
string += f"\n├💽 **RAM Usage »** __{size_measure(ram_usage)}__"
string += f"\n╰💾 **DISK Free »** __{size_measure(disk_usage.free)}__"
string += f"\n\n<i>💖 When I'm Doin This, Do Something Else ! **Because, Time Is Precious ✨**</i>"
return string
async def zip_folder(path):
dir_p, p_name = ospath.split(path)
r = "-r" if ospath.isdir(path) else ""
if len(custom_name) != 0:
name = custom_name
elif ospath.isfile(path):
name = ospath.basename(path)
else:
name = d_name
zip_msg = f"<b>🔐 ZIPPING » </b>\n\n<code>{name}</code>\n"
starting_time = datetime.datetime.now()
cmd = f'cd "{dir_p}" && zip {r} -s 2000m -0 "{temp_zpath}/{name}.zip" "{p_name}"'
proc = subprocess.Popen(cmd, shell=True)
total = size_measure(get_folder_size(path))
while proc.poll() is None:
speed_string, eta, percentage = speed_eta(
starting_time, get_folder_size(temp_zpath), get_folder_size(path)
)
await status_bar(
zip_msg,
speed_string,
percentage,
convert_seconds(eta),
size_measure(get_folder_size(temp_zpath)),
total,
"Xr-Zipp 🔒",
)
time.sleep(1)
if ospath.isfile(path):
os.remove(path)
else:
shutil.rmtree(path)
async def extract_zip(zip_filepath):
starting_time = datetime.datetime.now()
dirname, filename = ospath.split(zip_filepath)
unzip_msg = f"<b>📂 EXTRACTING »</b>\n\n<code>{filename}</code>\n"
file_pattern = ""
p = f"-p{z_pswd}" if len(z_pswd) != 0 else ""
name, ext = ospath.splitext(filename)
if ext == ".rar":
if "part" in name:
cmd = f"unrar x -kb -idq {p} '{zip_filepath}' {temp_unzip_path}"
file_pattern = "rar"
else:
cmd = f"unrar x {p} '{zip_filepath}' {temp_unzip_path}"
elif ext == ".tar":
cmd = f"tar -xvf '{zip_filepath}' -C {temp_unzip_path}"
elif ext == ".gz":
cmd = f"tar -zxvf '{zip_filepath}' -C {temp_unzip_path}"
else:
cmd = f"7z x {p} '{zip_filepath}' -o{temp_unzip_path}"
if ext == ".001":
file_pattern = "7z"
elif ext == ".z01":
file_pattern = "zip"
proc = subprocess.Popen(cmd, shell=True)
total = size_measure(get_folder_size(zip_filepath))
while proc.poll() is None:
speed_string, eta, percentage = speed_eta(
starting_time,
get_folder_size(temp_unzip_path),
get_folder_size(zip_filepath),
)
await status_bar(
unzip_msg,
speed_string,
percentage,
convert_seconds(eta),
size_measure(get_folder_size(temp_unzip_path)),
total,
"Xr-Unzip 🔓",
)
time.sleep(1)
# Deletes all remaining Multi Part Volumes
c = 1
if file_pattern == "rar":
name_, _ = ospath.splitext(name)
na_p = name_ + ".part" + str(c) + ".rar"
p_ap = ospath.join(dirname, na_p)
while ospath.exists(p_ap):
os.remove(p_ap)
c += 1
na_p = name_ + ".part" + str(c) + ".rar"
p_ap = ospath.join(dirname, na_p)
elif file_pattern == "7z":
na_p = name + "." + str(c).zfill(3)
p_ap = ospath.join(dirname, na_p)
while ospath.exists(p_ap):
os.remove(p_ap)
c += 1
na_p = name + "." + str(c).zfill(3)
p_ap = ospath.join(dirname, na_p)
elif file_pattern == "zip":
na_p = name + ".zip"
p_ap = ospath.join(dirname, na_p)
if ospath.exists(p_ap):
os.remove(p_ap)
na_p = name + ".z" + str(c).zfill(2)
p_ap = ospath.join(dirname, na_p)
while ospath.exists(p_ap):
os.remove(p_ap)
c += 1
na_p = name + ".z" + str(c).zfill(2)
p_ap = ospath.join(dirname, na_p)
if ospath.exists(zip_filepath):
os.remove(zip_filepath)
async def size_checker(file_path):
max_size = 2097152000 # 2 GB
file_size = os.stat(file_path).st_size
if file_size > max_size:
if not ospath.exists(temp_lpath):
makedirs(temp_lpath)
_, filename = ospath.split(file_path)
filename = filename.lower()
if (
filename.endswith(".zip")
or filename.endswith(".rar")
or filename.endswith(".7z")
or filename.endswith(".tar")
or filename.endswith(".gz")
):
await split_zipFile(file_path, max_size)
else:
await zip_folder(file_path)
time.sleep(2)
return True
else:
return False
async def split_zipFile(file_path, max_size):
starting_time = datetime.datetime.now()
_, filename = ospath.split(file_path)
new_path = f"{temp_lpath}/{filename}"
down_msg = f"<b>✂️ SPLITTING » </b>\n\n<code>{filename}</code>\n"
# Get the total size of the file
total_size = ospath.getsize(file_path)
with open(file_path, "rb") as f:
chunk = f.read(max_size)
i = 1
bytes_written = 0
while chunk:
# Generate filename for this chunk
ext = str(i).zfill(3)
output_filename = "{}.{}".format(new_path, ext)
# Write chunk to file
with open(output_filename, "wb") as out:
out.write(chunk)
bytes_written += len(chunk)
speed_string, eta, percentage = speed_eta(
starting_time, bytes_written, total_size
)
await status_bar(
down_msg,
speed_string,
percentage,
convert_seconds(eta),
size_measure(bytes_written),
size_measure(total_size),
"Xr-Split ✂️",
)
# Get next chunk
chunk = f.read(max_size)
i += 1 # Increment chunk counter
def is_time_over(current_time):
ten_sec_passed = time.time() - current_time[0] >= 3
if ten_sec_passed:
current_time[0] = time.time()
return ten_sec_passed
def speed_eta(start, done, total):
percentage = (done / total) * 100
elapsed_time = (datetime.datetime.now() - start).seconds
if done > 0 and elapsed_time != 0:
raw_speed = done / elapsed_time
speed = f"{size_measure(raw_speed)}/s"
eta = (total - done) / raw_speed
else:
speed, eta = "N/A", 0
return speed, eta, percentage
# =================================================================
# Direct Link Handler Functions
# =================================================================
async def on_output(output: str):
# print("=" * 60 + f"\n\n{output}\n\n" + "*" * 60)
global link_info
total_size = "0B"
progress_percentage = "0B"
downloaded_bytes = "0B"
eta = "0S"
try:
if "ETA:" in output:
parts = output.split()
total_size = parts[1].split("/")[1]
total_size = total_size.split("(")[0]
progress_percentage = parts[1][parts[1].find("(") + 1 : parts[1].find(")")]
downloaded_bytes = parts[1].split("/")[0]
eta = parts[4].split(":")[1][:-1]
except Exception as do:
print(f"Could't Get Info Due to: {do}")
percentage = re.findall("\d+\.\d+|\d+", progress_percentage)[0]
down = re.findall("\d+\.\d+|\d+", downloaded_bytes)[0]
down_unit = re.findall("[a-zA-Z]+", downloaded_bytes)[0]
if "G" in down_unit:
spd = 3
elif "M" in down_unit:
spd = 2
elif "K" in down_unit:
spd = 1
else:
spd = 0
elapsed_time_seconds = (datetime.datetime.now() - start_time).seconds
if elapsed_time_seconds >= 270 and not link_info:
raise Exception("Failed to get download information ! Probably dead link 💀")
# Only Do this if got Information
if total_size != "0B":
# Calculate download speed
link_info = True
current_speed = (float(down) * 1024**spd) / elapsed_time_seconds
speed_string = f"{size_measure(current_speed)}/s"
await status_bar(
down_msg,
speed_string,
int(percentage),
eta,
downloaded_bytes,
total_size,
"Aria2c 🧨",
)
async def aria2_Download(link, num):
global start_time, down_msg
name_d = get_Aria2c_Name(link)
start_time = datetime.datetime.now()
down_msg = f"<b>📥 DOWNLOADING FROM » </b><i>🔗Link {str(num).zfill(2)}</i>\n\n<b>🏷️ Name » </b><code>{name_d}</code>\n"
# Create a command to run aria2p with the link
command = [
"aria2c",
"-x16",
"--seed-time=0",
"--summary-interval=1",
"--max-tries=3",
"--console-log-level=notice",
"-d",
d_fol_path,
link,
]
# Run the command using subprocess.Popen
proc = subprocess.Popen(
command, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
# Read and print output in real-time
while True:
output = proc.stdout.readline()
if output == b"" and proc.poll() is not None:
break
if output:
# sys.stdout.write(output.decode("utf-8"))
# sys.stdout.flush()
await on_output(output.decode("utf-8"))
# Retrieve exit code and any error output
exit_code = proc.wait()
error_output = proc.stderr.read()
if exit_code != 0:
if exit_code == 3:
raise Exception(f"The Resource was Not Found in {link}")
elif exit_code == 9:
raise Exception(f"Not enough disk space available")
elif exit_code == 24:
raise Exception(f"HTTP authorization failed.")
else:
raise Exception(
f"aria2c download failed with return code {exit_code} for {link}.\nError: {error_output}"
)
# =================================================================
# Telegram Downloader
# =================================================================
async def media_Identifier(link):
parts = link.split("/")
message_id = parts[-1]
msg_chat_id = "-100" + parts[4]
message_id, msg_chat_id = int(message_id), int(msg_chat_id)
message = await bot.get_messages(msg_chat_id, message_id)
media = (
message.document
or message.photo
or message.video
or message.audio
or message.voice
or message.video_note
or message.sticker
or message.animation
or None
)
if media is None:
raise Exception("Couldn't Download Telegram Message")
return media, message
async def download_progress(current, total):
speed_string, eta, percentage = speed_eta(start_time, current, total)
await status_bar(
down_msg=down_msg,
speed=speed_string,
percentage=percentage,
eta=convert_seconds(eta),
done=size_measure(sum(down_bytes) + current),
left=size_measure(folder_info[0]),
engine="Pyrogram 💥",
)
async def TelegramDownload(link, num):
global start_time, down_msg
media, message = await media_Identifier(link)
if media is not None:
name = media.file_name if hasattr(media, "file_name") else "None"
else:
raise Exception("Couldn't Download Telegram Message")
down_msg = f"<b>📥 DOWNLOADING FROM » </b><i>🔗Link {str(num).zfill(2)}</i>\n\n<code>{name}</code>\n"
start_time = datetime.datetime.now()
file_path = ospath.join(d_fol_path, name)
await message.download(
progress=download_progress, in_memory=False, file_name=file_path
)
down_bytes.append(media.file_size)
# =================================================================
# Youtube Link Handler Functions
# =================================================================
async def YTDL_Status(link, num):
global down_msg
name = get_YT_Name(link)
down_msg = f"<b>📥 DOWNLOADING FROM » </b><i>🔗Link {str(num).zfill(2)}</i>\n\n<code>{name}</code>\n"
YTDL_Thread = threading.Thread(target=YouTubeDL, name="YouTubeDL", args=(link,))
YTDL_Thread.start()
while YTDL_Thread.is_alive(): # Until ytdl is downloading
if ytdl_status[0]:
sys_text = system_info()
message = ytdl_status[0]
try:
await bot.edit_message_text(
chat_id=chat_id,
message_id=msg.id,
text=task_msg + down_msg + message + sys_text,
reply_markup=keyboard(),
)
except Exception as f:
pass
else:
try:
message = ytdl_status[1].split("@")
await status_bar(
down_msg=down_msg,
speed=message[0],
percentage=float(message[1]),
eta=message[2],
done=message[3],
left=message[4],
engine="Xr-YtDL 🏮",
)
except Exception as f:
pass
time.sleep(2.5)
class MyLogger:
def __init__(self):
pass
def debug(self, msg):
global ytdl_status
if "item" in str(msg):
msgs = msg.split(" ")
ytdl_status[0] = f"\n⏳ __Getting Video Information {msgs[-3]} of {msgs[-1]}__"
@staticmethod
def warning(msg):
pass
@staticmethod
def error(msg):
# if msg != "ERROR: Cancelling...":
# print(msg)
pass
def YouTubeDL(url):
global ytdl_status
def my_hook(d):
global ytdl_status
if d["status"] == "downloading":
if d.get("total_bytes"):
total_bytes = d["total_bytes"]
elif d.get("total_bytes_estimate"):
total_bytes = d["total_bytes_estimate"]
else:
total_bytes = 0
dl_bytes = d.get("downloaded_bytes", 0)
percent = d.get("downloaded_percent", 0)
speed = d.get("speed", "N/A")
eta = d.get("eta", 0)
if percent == 0 and total_bytes != 0:
percent = round((float(dl_bytes) * 100 / float(total_bytes)), 2)
# print(
# f"\rDL: {size_measure(dl_bytes)}/{size_measure(total_bytes)} | {percent}% | Speed: {size_measure(speed)}/s | ETA: {eta}",
# end="",
# )
ytdl_status[0] = False
ytdl_status[
1
] = f"{size_measure(speed)}/s@{percent}@{convert_seconds(eta)}@{size_measure(dl_bytes)}@{size_measure(total_bytes)}"
elif d["status"] == "downloading fragment":
# log_str = d["message"]
# print(log_str, end="")
pass
ydl_opts = {
"format": "bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4",
"allow_multiple_video_streams": True,
"allow_multiple_audio_streams": True,
"writethumbnail": True,
"allow_playlist_files": True,
"overwrites": True,
"postprocessors": [{"key": "FFmpegVideoConvertor", "preferedformat": "mp4"}],
"progress_hooks": [my_hook],
"logger": MyLogger(),
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
if not ospath.exists(f"{d_path}/ytdl_thumbnails"):
makedirs(f"{d_path}/ytdl_thumbnails")
try:
info_dict = ydl.extract_info(url, download=False)
ytdl_status[0] = "⌛ __Please WAIT a bit...__"
if "_type" in info_dict and info_dict["_type"] == "playlist":
playlist_name = info_dict["title"]
if not ospath.exists(ospath.join(d_fol_path, playlist_name)):
makedirs(ospath.join(d_fol_path, playlist_name))
ydl_opts["outtmpl"] = {
"default": f"{d_fol_path}/{playlist_name}/%(title)s.%(ext)s",
"thumbnail": f"{d_path}/ytdl_thumbnails/%(title)s.%(ext)s",
}
for entry in info_dict["entries"]:
video_url = entry["webpage_url"]
ydl.download([video_url])
else:
ytdl_status[0] = False
ydl_opts["outtmpl"] = {
"default": f"{d_fol_path}/%(title)s.%(ext)s",
"thumbnail": f"{d_path}/ytdl_thumbnails/%(title)s.%(ext)s",
}
ydl.download([url])
except Exception as e:
print(f"YTDL ERROR: {e}")
# =================================================================
# Initiator Functions
# =================================================================
async def calG_DownSize(links):
for link in natsorted(links):
if "drive.google.com" in link:
id = getIDFromURL(link)
try:
meta = getFileMetadata(id)
except Exception as e:
if "File not found" in str(e):
raise Exception(
"The file link you gave either doesn't exist or You don't have access to it!"
)
elif "Failed to retrieve" in str(e):
clear_output()
raise Exception(
"Authorization Error with Google ! Make Sure you uploaded token.pickle !"
)
else:
raise Exception(f"Error in G-API: {e}")
if meta.get("mimeType") == "application/vnd.google-apps.folder":
folder_info[0] += get_Gfolder_size(id)
else:
folder_info[0] += int(meta["size"])
elif "t.me" in link:
media, _ = await media_Identifier(link)
if media is not None:
size = media.file_size
folder_info[0] += size
else:
raise Exception("Couldn't Download Telegram Message")
else:
pass
def get_Aria2c_Name(link):
cmd = f'aria2c -x10 --dry-run --file-allocation=none "{link}"'
result = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True)
stdout_str = result.stdout.decode("utf-8")
filename = stdout_str.split("complete: ")[-1].split("\n")[0]
name = filename.split("/")[-1]
if len(name) == 0:
name = "UNKNOWN DOWNLOAD NAME"
return name
def get_YT_Name(link):
with yt_dlp.YoutubeDL({"logger": MyLogger()}) as ydl:
info = ydl.extract_info(link, download=False)
if "title" in info:
return info["title"]
else:
return "UNKNOWN DOWNLOAD NAME"
async def get_d_name(link):
global d_name
if custom_name:
d_name = custom_name
return
if "drive.google.com" in link:
id = getIDFromURL(link)
meta = getFileMetadata(id)
d_name = meta["name"]
elif "t.me" in link:
media, _ = await media_Identifier(link)
d_name = media.file_name if hasattr(media, "file_name") else "None"
elif "youtube.com" in link or "youtu.be" in link:
d_name = get_YT_Name(link)
else:
d_name = get_Aria2c_Name(link)
# =================================================================
# G Drive Functions
# =================================================================
def build_service():
# create credentials object from token.pickle file
creds = None
if ospath.exists("/content/token.pickle"):
with open("/content/token.pickle", "rb") as token:
creds = pickle.load(token)
else:
exit(1)
# create drive API client
service = build("drive", "v3", credentials=creds)
return service
async def g_DownLoad(link, num):
global start_time, down_msg
down_msg = f"<b>📥 DOWNLOADING FROM » </b><i>🔗Link {str(num).zfill(2)}</i>\n\n<b>🏷️ Name » </b><code>{d_name}</code>\n"
file_id = getIDFromURL(link)
meta = getFileMetadata(file_id)
if meta.get("mimeType") == "application/vnd.google-apps.folder":
await gDownloadFolder(file_id, d_fol_path)
else:
await gDownloadFile(file_id, d_fol_path)
clear_output()
def getIDFromURL(link: str):
if "folders" in link or "file" in link:
regex = r"https:\/\/drive\.google\.com\/(?:drive(.*?)\/folders\/|file(.*?)?\/d\/)([-\w]+)"
res = re_search(regex, link)
if res is None:
raise IndexError("G-Drive ID not found.")
return res.group(3)
parsed = urlparse(link)
return parse_qs(parsed.query)["id"][0]
def getFilesByFolderID(folder_id):
page_token = None
files = []
while True:
response = (
service.files()
.list(
supportsAllDrives=True,
includeItemsFromAllDrives=True,
q=f"'{folder_id}' in parents and trashed = false",
spaces="drive",
pageSize=200,
fields="nextPageToken, files(id, name, mimeType, size, shortcutDetails)",
orderBy="folder, name",
pageToken=page_token,
)
.execute()
)
files.extend(response.get("files", []))
page_token = response.get("nextPageToken")
if page_token is None:
break
return files
def getFileMetadata(file_id):
return (
service.files()
.get(fileId=file_id, supportsAllDrives=True, fields="name, id, mimeType, size")
.execute()
)
def get_Gfolder_size(folder_id):
try:
query = "trashed = false and '{0}' in parents".format(folder_id)
results = (
service.files()
.list(
supportsAllDrives=True,
includeItemsFromAllDrives=True,
q=query,
fields="files(id, mimeType, size)",
)
.execute()
)
total_size = 0
items = results.get("files", [])
folders_without_size = (
item["id"]
for item in items
if item.get("size") is None
and item["mimeType"] == "application/vnd.google-apps.folder"
)
for item in items:
# If the item has a size attribute
if "size" in item:
total_size += int(item["size"])
# Recursively call the function for folders whose size is not found
for folder_id in folders_without_size:
total_size += get_Gfolder_size(folder_id)
return total_size
except HttpError as error:
print(f"Error while checking size: {error}")
return -1
async def gDownloadFile(file_id, path):
# Check if the specified file or folder exists and is downloadable.
try:
file = getFileMetadata(file_id)
except HttpError as error:
print("An error occurred: {0}".format(error))
file = None
if file is None:
print(
"Sorry, the specified file or folder does not exist or is not accessible."
)
else:
if file["mimeType"].startswith("application/vnd.google-apps"):
print(
"Sorry, the specified ID is for a Google Docs, Sheets, Slides, or Forms document. You can only download these types of files in specific formats."
)
else:
try:
file_name = file.get("name", f"untitleddrivefile_{file_id}")
file_name = ospath.join(path, file_name)
# Create a BytesIO stream to hold the downloaded file data.
file_contents = io.BytesIO()
# Download the file or folder contents to the BytesIO stream.
request = service.files().get_media(
fileId=file_id, supportsAllDrives=True
)
file_downloader = MediaIoBaseDownload(
file_contents, request, chunksize=70 * 1024 * 1024
)
done = False
while done is False:
status, done = file_downloader.next_chunk()
# Get current value from file_contents.
file_contents.seek(0)
with open(file_name, "ab") as f:
f.write(file_contents.getvalue())
# Reset the buffer for the next chunk.
file_contents.seek(0)
file_contents.truncate()
# The saved bytes until now
file_d_size = int(status.progress() * int(file["size"]))
down_done = sum(down_bytes) + file_d_size
speed_string, eta, percentage = speed_eta(
start_time, down_done, folder_info[0]
)
await status_bar(
down_msg=down_msg,
speed=speed_string,
percentage=percentage,
eta=convert_seconds(eta),
done=size_measure(down_done),
left=size_measure(folder_info[0]),
engine="G-API ♻️",
)
down_bytes.append(int(file["size"]))
down_count[0] += 1
except HttpError as error:
if error.resp.status == 403 and "User Rate Limit Exceeded" in str(
error
):
raise HttpError("Download quota for the file has been exceeded.")
else:
print("Error downloading: {0}".format(error))
except Exception as e:
print("Error downloading: {0}".format(e))
async def gDownloadFolder(folder_id, path):
folder_meta = getFileMetadata(folder_id)
folder_name = folder_meta["name"]
if not ospath.exists(f"{path}/{folder_name}"):
makedirs(f"{path}/{folder_name}")
path += f"/{folder_name}"
result = getFilesByFolderID(folder_id)
if len(result) == 0:
return
result = natsorted(result, key=lambda k: k["name"])
for item in result:
file_id = item["id"]
shortcut_details = item.get("shortcutDetails")
if shortcut_details is not None:
file_id = shortcut_details["targetId"]
mime_type = shortcut_details["targetMimeType"]
else:
mime_type = item.get("mimeType")
if mime_type == "application/vnd.google-apps.folder":
await gDownloadFolder(file_id, path)
else:
await gDownloadFile(file_id, path)
# =================================================================
# Telegram Upload Functions
# =================================================================
def keyboard():