-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathutils.py
More file actions
155 lines (132 loc) · 5.49 KB
/
utils.py
File metadata and controls
155 lines (132 loc) · 5.49 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
import time
import asyncio
from FastTelethonhelper import fast_upload, fast_download
from config import bot
import os
import libtorrent as lt
import datetime
from config import DESTINATION
import shutil
import requests
D = str(DESTINATION).replace("-100", "")
async def run(cmd):
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
print(f'[{cmd!r} exited with {proc.returncode}]')
if stdout:
return f'[stdout]\n{stdout.decode()}'
if stderr:
return f'[stderr]\n{stderr.decode()}'
async def encode(msg, r, file, cmd, res, name):
command = cmd.text.replace('[file]', file)
if res == 1080:
command = command.replace("-vf scale=1280:720", "-vf scale=1920:1080")
elif res == 360:
command = command.replace("-vf scale=1280:720", "-vf scale=640:360")
c = await r.reply(command)
o = await run(f'{command}')
x = await r.reply(o[-2000:])
res_file = await fast_upload(client = bot, file_location = f"./downloads/[AG] {file}", reply = r, name=name)
os.remove(f"./downloads/[AG] {file}")
try:
y = await bot.send_message(DESTINATION,f"[AG] {name.replace('.mkv', '')}", file=res_file, thumb="thumb.png", force_document=True)
except:
y = await r.reply(f"[AG] {name.replace('.mkv', '')}", file=res_file, thumb="thumb.png", force_document=True)
await r.reply(f"Encoding done....\n`./downloads/[AG] {file}`\nt.me/c/{D}/{y.id}")
await asyncio.sleep(5)
await x.delete()
await c.delete()
class Timer:
def __init__(self, time_between=5):
self.start_time = time.time()
self.time_between = time_between
def can_send(self):
if time.time() > (self.start_time + self.time_between):
self.start_time = time.time()
return True
return False
def human_readable_size(size, decimal_places=2):
for unit in ['B', 'KB', 'MB', 'GB', 'TB', 'PB']:
if size < 1024.0 or unit == 'PB':
break
size /= 1024.0
return f"{size:.{decimal_places}f} {unit}"
def progress_bar_str(done, total):
percent = round(done/total*100, 2)
strin = "░░░░░░░░░░"
strin = list(strin)
for i in range(round(percent)//10):
strin[i] = "█"
strin = "".join(strin)
final = f"Percent: {percent}%\n{human_readable_size(done)}/{human_readable_size(total)}\n{strin}"
return final
async def download_file(url, reply, chunk_size=1024*10, file_name="file.mkv"):
if os.path.exists(file_name):
os.remove(file_name)
if not url:
return file_name
timer = Timer()
r = requests.get(url, allow_redirects=True, stream=True)
total_size = int(r.headers.get("content-length", 0))
downloaded_size = 0
with open(f"./downloads/{file_name}", 'wb') as fd:
for chunk in r.iter_content(chunk_size=chunk_size):
if chunk:
fd.write(chunk)
downloaded_size += chunk_size
if timer.can_send():
try:
data = progress_bar_str(downloaded_size, total_size)
await reply.edit(f"Downloading\n{data}")
except:
pass
return file_name
async def download_torrent(link, event):
ses = lt.session()
ses.listen_on(6881, 6891)
params = {
'save_path': 'downloads',
'storage_mode': lt.storage_mode_t(2)
}
handle = lt.add_magnet_uri(ses, link, params)
ses.start_dht()
begin = time.time()
print(datetime.datetime.now())
message = await bot.send_message(event.chat_id,"Downloading Metadata...")
while (not handle.has_metadata()):
time.sleep(1)
await bot.edit_message(event.chat_id,message,"Got Metadata, Starting Torrent Download...")
await bot.edit_message(event.chat_id,message,f"Starting, {handle.name()}")
while (handle.status().state != lt.torrent_status.seeding):
s = handle.status()
state_str = ['queued', 'checking', 'downloading metadata', \
'downloading', 'finished', 'seeding', 'allocating']
size_bytes = s.total_wanted
size_mb = size_bytes/(1024*1024)
size_gb = size_bytes/(1024*1024*1024)
size = size_mb
byte = "MB"
if size_gb > 1:
size = size_gb
byte = "GB"
await bot.edit_message(event.chat_id,message,"%s \n\nSize: %.2f %s\n\n %.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s " % \
(handle.name(), size,byte, s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, \
s.num_peers, state_str[s.state]))
time.sleep(5)
end = time.time()
await bot.edit_message(event.chat_id,message,f"{handle.name()} COMPLETE")
await bot.send_message(event.chat_id, f"Elapsed Time: {int((end-begin)//60)} min :{int((end-begin)%60)} sec")
return handle.name()
def delete_files(folder):
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.remove(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print('Failed to delete %s. Reason: %s' % (file_path, e))