forked from VJBots/VJ-Txt-Leech-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.py
224 lines (182 loc) · 6.54 KB
/
core.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
# Don't Remove Credit Tg - @VJ_Botz
# Subscribe YouTube Channel For Amazing Bot https://youtube.com/@Tech_VJ
# Ask Doubt on telegram @KingVJ01
import os
import time
import datetime
import aiohttp
import aiofiles
import asyncio
import logging
import requests
import tgcrypto
import subprocess
import concurrent.futures
from utils import progress_bar
from pyrogram import Client, filters
from pyrogram.types import Message
def duration(filename):
result = subprocess.run(["ffprobe", "-v", "error", "-show_entries",
"format=duration", "-of",
"default=noprint_wrappers=1:nokey=1", filename],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
return float(result.stdout)
def exec(cmd):
process = subprocess.run(cmd, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
output = process.stdout.decode()
print(output)
return output
#err = process.stdout.decode()
def pull_run(work, cmds):
with concurrent.futures.ThreadPoolExecutor(max_workers=work) as executor:
print("Waiting for tasks to complete")
fut = executor.map(exec,cmds)
async def aio(url,name):
k = f'{name}.pdf'
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
if resp.status == 200:
f = await aiofiles.open(k, mode='wb')
await f.write(await resp.read())
await f.close()
return k
async def download(url,name):
ka = f'{name}.pdf'
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
if resp.status == 200:
f = await aiofiles.open(ka, mode='wb')
await f.write(await resp.read())
await f.close()
return ka
def parse_vid_info(info):
info = info.strip()
info = info.split("\n")
new_info = []
temp = []
for i in info:
i = str(i)
if "[" not in i and '---' not in i:
while " " in i:
i = i.replace(" ", " ")
i.strip()
i = i.split("|")[0].split(" ",2)
try:
if "RESOLUTION" not in i[2] and i[2] not in temp and "audio" not in i[2]:
temp.append(i[2])
new_info.append((i[0], i[2]))
except:
pass
return new_info
def vid_info(info):
info = info.strip()
info = info.split("\n")
new_info = dict()
temp = []
for i in info:
i = str(i)
if "[" not in i and '---' not in i:
while " " in i:
i = i.replace(" ", " ")
i.strip()
i = i.split("|")[0].split(" ",3)
try:
if "RESOLUTION" not in i[2] and i[2] not in temp and "audio" not in i[2]:
temp.append(i[2])
# temp.update(f'{i[2]}')
# new_info.append((i[2], i[0]))
# mp4,mkv etc ==== f"({i[1]})"
new_info.update({f'{i[2]}':f'{i[0]}'})
except:
pass
return new_info
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 proc.returncode == 1:
return False
if stdout:
return f'[stdout]\n{stdout.decode()}'
if stderr:
return f'[stderr]\n{stderr.decode()}'
def old_download(url, file_name, chunk_size = 1024 * 10):
if os.path.exists(file_name):
os.remove(file_name)
r = requests.get(url, allow_redirects=True, stream=True)
with open(file_name, 'wb') as fd:
for chunk in r.iter_content(chunk_size=chunk_size):
if chunk:
fd.write(chunk)
return file_name
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 time_name():
date = datetime.date.today()
now = datetime.datetime.now()
current_time = now.strftime("%H%M%S")
return f"{date} {current_time}.mp4"
async def download_video(url,cmd, name):
download_cmd = f'{cmd} -R 25 --fragment-retries 25 --external-downloader aria2c --downloader-args "aria2c: -x 16 -j 32"'
global failed_counter
print(download_cmd)
logging.info(download_cmd)
k = subprocess.run(download_cmd, shell=True)
if "visionias" in cmd and k.returncode != 0 and failed_counter <= 10:
failed_counter += 1
await asyncio.sleep(5)
await download_video(url, cmd, name)
failed_counter = 0
try:
if os.path.isfile(name):
return name
elif os.path.isfile(f"{name}.webm"):
return f"{name}.webm"
name = name.split(".")[0]
if os.path.isfile(f"{name}.mkv"):
return f"{name}.mkv"
elif os.path.isfile(f"{name}.mp4"):
return f"{name}.mp4"
elif os.path.isfile(f"{name}.mp4.webm"):
return f"{name}.mp4.webm"
return name
except FileNotFoundError as exc:
return os.path.isfile.splitext[0] + "." + "mp4"
async def send_doc(bot: Client, m: Message,cc,ka,cc1,prog,count,name):
reply = await m.reply_text(f"Uploading » `{name}`")
time.sleep(1)
start_time = time.time()
await m.reply_document(ka,caption=cc1)
count+=1
await reply.delete (True)
time.sleep(1)
os.remove(ka)
time.sleep(3)
async def send_vid(bot: Client, m: Message,cc,filename,thumb,name,prog):
subprocess.run(f'ffmpeg -i "{filename}" -ss 00:00:12 -vframes 1 "{filename}.jpg"', shell=True)
await prog.delete (True)
reply = await m.reply_text(f"**Uploading ...** - `{name}`")
try:
if thumb == "no":
thumbnail = f"{filename}.jpg"
else:
thumbnail = thumb
except Exception as e:
await m.reply_text(str(e))
dur = int(duration(filename))
start_time = time.time()
try:
await m.reply_video(filename,caption=cc, supports_streaming=True,height=720,width=1280,thumb=thumbnail,duration=dur, progress=progress_bar,progress_args=(reply,start_time))
except Exception:
await m.reply_document(filename,caption=cc, progress=progress_bar,progress_args=(reply,start_time))
os.remove(filename)
os.remove(f"{filename}.jpg")
await reply.delete (True)