1818# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
1919# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2020
21- from humanize import naturalsize
2221from subprocess import PIPE , Popen
2322
2423import re
2524import json
26- import wget
2725import os
26+ import time
2827
28+ from pySmartDL import SmartDL
2929from os .path import exists
30+ from urllib .error import HTTPError
3031
31- from userbot import CMD_HELP
32+ from userbot import CMD_HELP , LOGS
3233from userbot .events import register
3334
3435
@@ -48,72 +49,121 @@ def subprocess_run(cmd):
4849
4950
5051@register (outgoing = True , pattern = r"^.mega(?: |$)(.*)" )
51- async def mega_downloader (event ):
52- await event .edit ("`Processing...`" )
53- textx = await event .get_reply_message ()
54- link = event .pattern_match .group (1 )
52+ async def mega_downloader (megadl ):
53+ await megadl .edit ("`Processing...`" )
54+ textx = await megadl .get_reply_message ()
55+ link = megadl .pattern_match .group (1 )
5556 if link :
5657 pass
5758 elif textx :
5859 link = textx .text
5960 else :
60- await event .edit ("`Usage: .mega <mega url>`" )
61+ await megadl .edit ("`Usage: .mega <mega url>`" )
6162 return
62- reply = ''
6363 if not link :
64- reply = "`No MEGA.nz link found!`"
65- await event .edit (reply )
66- await event .edit ("`Downloading...`" )
67- reply += mega_download (link )
68- await event .edit (reply )
64+ await megadl .edit ("`No MEGA.nz link found!`" )
65+ await mega_download (link , megadl )
6966
7067
71- def mega_download (url : str ) -> str :
72- reply = ''
68+ async def mega_download (url , megadl ):
7369 try :
7470 link = re .findall (r'\bhttps?://.*mega.*\.nz\S+' , url )[0 ]
7571 except IndexError :
76- reply = "`No MEGA.nz link found`\n "
77- return reply
72+ await megadl . edit ( "`No MEGA.nz link found`\n " )
73+ return
7874 cmd = f'bin/megadirect { link } '
7975 result = subprocess_run (cmd )
8076 try :
8177 data = json .loads (result [0 ])
8278 except json .JSONDecodeError :
83- reply += "`Error: Can't extract the link`\n "
84- return reply
79+ await megadl . edit ( "`Error: Can't extract the link`\n " )
80+ return
8581 file_name = data ['file_name' ]
86- file_size = naturalsize (int (data ['file_size' ]))
8782 file_url = data ['url' ]
8883 file_hex = data ['hex' ]
8984 file_raw_hex = data ['raw_hex' ]
9085 if exists (file_name ):
9186 os .remove (file_name )
9287 if not exists (file_name ):
93- wget .download (file_url , out = file_name )
94- if exists (file_name ):
95- encrypt_file (file_name , file_hex , file_raw_hex )
96- reply += (f"`{ file_name } `\n "
97- f"Size: { file_size } \n \n "
98- "Successfully downloaded..." )
88+ temp_file_name = file_name + ".temp"
89+ downloaded_file_name = "./" + "" + temp_file_name
90+ downloader = SmartDL (file_url , downloaded_file_name , progress_bar = False )
91+ display_message = None
92+ try :
93+ downloader .start (blocking = False )
94+ except HTTPError as e :
95+ await megadl .edit ("`" + str (e ) + "`" )
96+ LOGS .info (str (e ))
97+ return
98+ while not downloader .isFinished ():
99+ status = downloader .get_status ().capitalize ()
100+ total_length = downloader .filesize if downloader .filesize else None
101+ downloaded = downloader .get_dl_size ()
102+ percentage = int (downloader .get_progress () * 100 )
103+ progress = downloader .get_progress_bar ()
104+ speed = downloader .get_speed (human = True )
105+ estimated_total_time = downloader .get_eta (human = True )
106+ try :
107+ current_message = (
108+ f"**{ status } **..."
109+ f"\n File Name: `{ file_name } `\n "
110+ f"\n { progress } `{ percentage } %`"
111+ f"\n { humanbytes (downloaded )} of { humanbytes (total_length )} "
112+ f" @ { speed } "
113+ f"\n ETA: { estimated_total_time } "
114+ )
115+ if status == "Downloading" :
116+ await megadl .edit (current_message )
117+ time .sleep (0.2 )
118+ elif status == "Combining" :
119+ if display_message != current_message :
120+ await megadl .edit (current_message )
121+ display_message = current_message
122+ except Exception as e :
123+ LOGS .info (str (e ))
124+ if downloader .isSuccessful ():
125+ download_time = downloader .get_dl_time (human = True )
126+ if exists (temp_file_name ):
127+ await megadl .edit ("Decrypting file..." )
128+ decrypt_file (file_name , temp_file_name , file_hex , file_raw_hex )
129+ await megadl .edit (f"`{ file_name } `\n \n "
130+ "Successfully downloaded\n "
131+ f"Download took: { download_time } " )
99132 else :
100- reply += "Failed to download..."
101- return reply
133+ await megadl .edit ("Failed to download..." )
134+ for e in downloader .get_errors ():
135+ LOGS .info (str (e ))
136+ return
102137
103138
104- def encrypt_file (file_name , file_hex , file_raw_hex ):
105- os .rename (file_name , r"old_{}" .format (file_name ))
106- cmd = ("cat 'old_{}' | openssl enc -d -aes-128-ctr -K {} -iv {} > '{}'"
107- .format (file_name , file_hex , file_raw_hex , file_name ))
139+ def decrypt_file (file_name , temp_file_name , file_hex , file_raw_hex ):
140+ cmd = ("cat '{}' | openssl enc -d -aes-128-ctr -K {} -iv {} > '{}'"
141+ .format (temp_file_name , file_hex , file_raw_hex , file_name ))
108142 subprocess_run (cmd )
109- os .remove (r"old_ {}" .format (file_name ))
143+ os .remove (r"{}" .format (temp_file_name ))
110144 return
111145
112146
147+ def humanbytes (size ):
148+ """Input size in bytes,
149+ outputs in a human readable format"""
150+ # https://stackoverflow.com/a/49361727/4723940
151+ if not size :
152+ return ""
153+ # 2 ** 10 = 1024
154+ power = 2 ** 10
155+ raised_to_pow = 0
156+ dict_power_n = {0 : "" , 1 : "Ki" , 2 : "Mi" , 3 : "Gi" , 4 : "Ti" }
157+ while size > power :
158+ size /= power
159+ raised_to_pow += 1
160+ return str (round (size , 2 )) + " " + dict_power_n [raised_to_pow ] + "B"
161+
162+
113163CMD_HELP .update ({
114164 "mega" :
115165 ".mega <mega url>\n "
116166 "Usage: Reply to a mega link or paste your mega link to\n "
117167 "download the file into your userbot server\n \n "
118- "Only support for *FILE* only.\n "
168+ "Only support for ** FILE* * only.\n "
119169})
0 commit comments