-
Notifications
You must be signed in to change notification settings - Fork 3
/
urldownload.py
83 lines (69 loc) · 2.9 KB
/
urldownload.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
# Ported from Unibrog
# Uvindu Bro
import aiohttp
import os
import time
from handlers import humanbytes, time_formatter
from telethon import Button, custom, events
async def download_file(url, file_name, message, start_time, bot):
async with aiohttp.ClientSession() as session:
c_time = time.time()
await download_coroutine(session, url, file_name, message, start_time, bot)
return file_name
async def download_coroutine(session, url, file_name, event, start, bot):
CHUNK_SIZE = 1024*6 # 2341
downloaded = 0
display_message = ""
async with session.get(url) as response:
total_length = int(response.headers["Content-Length"])
content_type = response.headers["Content-Type"]
if "text" in content_type and total_length < 500:
return await response.release()
await event.edit(
"""**😉 Initiating Download 😉**
**🔗 URL:** {}
**📁 File Name:** {}
**File Size:** {}
**~ By @UvinduBro**""".format(
url,
os.path.basename(file_name).replace("%20", " "),
humanbytes(total_length),
),
parse_mode="md",
)
with open(file_name, "wb") as f_handle:
while True:
chunk = await response.content.read(CHUNK_SIZE)
if not chunk:
break
f_handle.write(chunk)
downloaded += CHUNK_SIZE
now = time.time()
diff = now - start
if round(diff % 10.00) == 0: #downloaded == total_length:
percentage = downloaded * 100 / total_length
speed = downloaded / diff
elapsed_time = round(diff) * 1000
time_to_completion = (
round((total_length - downloaded) / speed) * 1000)
estimated_total_time = elapsed_time + time_to_completion
try:
if total_length < downloaded:
total_length = downloaded
current_message = """🤗 Downloading : {}%
🔗 URL: {}
📁 File Name: {}
⚖ File Size: {}
📊 Downloaded: {}
💣 ETA: {}""".format("%.2f" % (percentage), url, file_name.split("/")[-1], humanbytes(total_length), humanbytes(downloaded), time_formatter(estimated_total_time))
if (
current_message != display_message
and current_message != "empty"
):
print(current_message)
await event.edit(current_message, parse_mode="html")
display_message = current_message
except Exception as e:
print("Error",e)
# logger.info(str(e))
return await response.release()