forked from 1Danish-00/CompressorQueue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfuncn.py
243 lines (211 loc) · 7.36 KB
/
funcn.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
# This file is part of the CompressorQueue distribution.
# Copyright (c) 2021 Danish_00
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# License can be found in <
# https://github.com/1Danish-00/CompressorQueue/blob/main/License> .
from . import *
from .config import *
WORKING = []
QUEUE = {}
OK = {}
uptime = dt.now()
os.system(f"wget {THUMB} -O thumb.jpg")
if not os.path.isdir("downloads/"):
os.mkdir("downloads/")
if not os.path.isdir("encode/"):
os.mkdir("encode/")
if not os.path.isdir("thumb/"):
os.mkdir("thumb/")
tgp_client = TelegraphPoster(use_api=True, telegraph_api_url=TELEGRAPH_API)
def create_api_token():
retries = 10
telgrph_tkn_err_msg = (
"Couldn't not successfully create api token required by telegraph to work"
"\nAs such telegraph is therefore disabled!"
)
while retries:
try:
tgp_client.create_api_token("Mediainfo")
break
except (requests.exceptions.ConnectionError, ConnectionError) as e:
retries -= 1
if not retries:
LOGS.info(telgrph_tkn_err_msg)
break
time.sleep(1)
create_api_token()
def stdr(seconds: int) -> str:
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
if len(str(minutes)) == 1:
minutes = "0" + str(minutes)
if len(str(hours)) == 1:
hours = "0" + str(hours)
if len(str(seconds)) == 1:
seconds = "0" + str(seconds)
dur = (
((str(hours) + ":") if hours else "00:")
+ ((str(minutes) + ":") if minutes else "00:")
+ ((str(seconds)) if seconds else "")
)
return dur
def ts(milliseconds: int) -> str:
seconds, milliseconds = divmod(int(milliseconds), 1000)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
tmp = (
((str(days) + "d, ") if days else "")
+ ((str(hours) + "h, ") if hours else "")
+ ((str(minutes) + "m, ") if minutes else "")
+ ((str(seconds) + "s, ") if seconds else "")
+ ((str(milliseconds) + "ms, ") if milliseconds else "")
)
return tmp[:-2]
def hbs(size):
if not size:
return ""
power = 2**10
raised_to_pow = 0
dict_power_n = {0: "B", 1: "K", 2: "M", 3: "G", 4: "T", 5: "P"}
while size > power:
size /= power
raised_to_pow += 1
return str(round(size, 2)) + " " + dict_power_n[raised_to_pow] + "B"
No_Flood = {}
async def progress(current, total, event, start, type_of_ps, file=None):
now = time.time()
if No_Flood.get(event.chat_id):
if No_Flood[event.chat_id].get(event.id):
if (now - No_Flood[event.chat_id][event.id]) < 1.1:
return
else:
No_Flood[event.chat_id].update({event.id: now})
else:
No_Flood.update({event.chat_id: {event.id: now}})
diff = time.time() - start
if round(diff % 10.00) == 0 or current == total:
percentage = current * 100 / total
speed = current / diff
time_to_completion = round((total - current) / speed) * 1000
progress_str = "`[{0}{1}] {2}%`\n\n".format(
"".join(["●" for i in range(math.floor(percentage / 5))]),
"".join(["○" for i in range(20 - math.floor(percentage / 5))]),
round(percentage, 2),
)
tmp = (
progress_str
+ "`{0} of {1}`\n\n`✦ Speed: {2}/s`\n\n`✦ ETA: {3}`\n\n".format(
hbs(current),
hbs(total),
hbs(speed),
ts(time_to_completion),
)
)
if file:
await event.edit(
"`✦ {}`\n\n`File Name: {}`\n\n{}".format(type_of_ps, file, tmp)
)
else:
await event.edit("`✦ {}`\n\n{}".format(type_of_ps, tmp))
async def info(file, event=None):
# depreciating second arg.
try:
author = (await bot.get_me()).first_name
author_url = f"https://t.me/{((await bot.get_me()).username)}"
out = pymediainfo.MediaInfo.parse(file, output="HTML", full=False)
if len(out) > 65536:
out = (
out[:65430]
+ "<strong>...<strong><br><br><strong>(TRUNCATED DUE TO CONTENT EXCEEDING MAX LENGTH)<strong>"
)
retries = 10
while retries:
try:
page = tgp_client.post(
title="Mediainfo",
author=author,
author_url=author_url,
text=out,
)
break
except (requests.exceptions.ConnectionError, ConnectionError) as e:
retries -= 1
if not retries:
raise e
await asyncio.sleep(1)
return page["url"]
except Exception:
return None
def code(data):
OK.update({len(OK): data})
return str(len(OK) - 1)
def decode(key):
if OK.get(int(key)):
return OK[int(key)]
return
async def skip(e):
wah = e.pattern_match.group(1).decode("UTF-8")
wh = decode(wah)
out, dl, id = wh.split(";")
try:
if QUEUE.get(int(id)):
WORKING.clear()
QUEUE.pop(int(id))
await e.delete()
os.remove(dl)
os.remove(out)
# Lets kill ffmpeg else it will run in memory even after deleting
# input.
for proc in psutil.process_iter():
processName = proc.name()
processID = proc.pid
print(processName, " - ", processID)
if processName == "ffmpeg":
os.kill(processID, signal.SIGKILL)
except BaseException:
pass
return
async def fast_download(e, download_url, filename=None):
def progress_callback(d, t):
return (
asyncio.get_event_loop().create_task(
progress(
d,
t,
e,
time.time(),
f"Downloading from {download_url}",
)
),
)
async def _maybe_await(value):
if inspect.isawaitable(value):
return await value
else:
return value
async with aiohttp.ClientSession() as session:
async with session.get(download_url, timeout=None) as response:
if not filename:
filename = download_url.rpartition("/")[-1]
filename = os.path.join("downloads", filename)
total_size = int(response.headers.get("content-length", 0)) or None
downloaded_size = 0
with open(filename, "wb") as f:
async for chunk in response.content.iter_chunked(1024):
if chunk:
f.write(chunk)
downloaded_size += len(chunk)
await _maybe_await(
progress_callback(downloaded_size, total_size)
)
return filename