-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathutils.py
284 lines (237 loc) · 9.65 KB
/
utils.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
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
import urllib.request
import urllib.parse
import http.cookiejar
import re
import time
from enum import Enum, auto
import os
import json
import functools
import http.client
import ipaddress
import random
import threading
from addons import discord
from addons import telegram
import const
import socket
socket.setdefaulttimeout(5)
def log(msg):
print(f"[INFO]{msg}")
def warn(msg):
print(f"[WARN]{msg}")
class PlayabilityStatus(Enum):
PRIVATED = auto()
COPYRIGHTED = auto()
REMOVED = auto()
MEMBERS_ONLY = auto()
OFFLINE = auto()
OK = auto()
ON_LIVE = auto()
UNKNOWN = auto()
LOGIN_REQUIRED = auto()
UNLISTED = auto()
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self._timer = threading.Timer(self.interval, self._run)
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False
class BoundHTTPHandler(urllib.request.HTTPHandler):
def __init__(self, *args, source_address=None, **kwargs):
urllib.request.HTTPHandler.__init__(self, *args, **kwargs)
self.http_class = functools.partial(http.client.HTTPConnection,
source_address=source_address,
timeout=5)
def http_open(self, req):
return self.do_open(self.http_class, req)
class BoundHTTPSHandler(urllib.request.HTTPSHandler):
def __init__(self, *args, source_address=None, **kwargs):
urllib.request.HTTPSHandler.__init__(self, *args, **kwargs)
self.https_class = functools.partial(http.client.HTTPSConnection,
source_address=source_address,
timeout=5)
def https_open(self, req):
return self.do_open(self.https_class, req,
context=self._context, check_hostname=self._check_hostname)
def get_random_line(filepath: str) -> str:
file_size = os.path.getsize(filepath)
with open(filepath, 'rb') as f:
while True:
pos = random.randint(0, file_size)
if not pos: # the first line is chosen
return f.readline().decode() # return str
f.seek(pos) # seek to random position
f.readline() # skip possibly incomplete line
line = f.readline() # read next (full) line
if line:
return line.decode()
# else: line is empty -> EOF -> try another position in next iteration
def is_ip(ip):
try:
ip = ipaddress.ip_address(ip)
return True
except ValueError:
return False
def get_pool_ip():
if const.IP_POOL:
if os.path.isfile(const.IP_POOL):
for _ in range(3): # Retry for 3 times.
ip = get_random_line(const.IP_POOL).rstrip().lstrip()
if is_ip(ip):
return ip
return None
def urlopen(url, retry=0, source_address="random", use_cookie=False):
try:
handlers = []
if source_address == "random":
source_address = get_pool_ip()
if not is_ip(source_address):
source_address = None
if use_cookie:
if hasattr(const, "COOKIE") and const.COOKIE and os.path.isfile(const.COOKIE):
cj = http.cookiejar.MozillaCookieJar()
cj.load(const.COOKIE)
cookie_handler = urllib.request.HTTPCookieProcessor(cj)
handlers.append(cookie_handler)
if source_address:
log(f" Using IP: {source_address}")
scheme = "https"
if type(url) == str:
scheme = urllib.parse.urlsplit(url).scheme
elif isinstance(url, urllib.request.Request):
scheme = urllib.parse.urlsplit(url.full_url).scheme
handler = (BoundHTTPHandler if scheme == "http" else BoundHTTPSHandler)(source_address=(source_address, 0))
handlers.append(handler)
if handlers:
return urllib.request.build_opener(*handlers).open(url)
else:
return urllib.request.urlopen(url)
except (http.client.IncompleteRead, socket.timeout) as e:
if retry < const.HTTP_RETRY:
warn(f" Get IncompleteRead/Timeout Error. Trying {retry+1}/{const.HTTP_RETRY}...")
return urlopen(url, retry+1, get_pool_ip() if source_address else None, use_cookie)
else:
raise e
except urllib.error.HTTPError as e:
if e.code == 503:
if retry < const.HTTP_RETRY:
warn(f" Get {e.code} Error. Trying {retry+1}/{const.HTTP_RETRY}...")
time.sleep(1)
return urlopen(url, retry+1, get_pool_ip() if source_address else None, use_cookie)
else:
raise e
else:
raise e
except urllib.error.URLError as e:
if retry < const.HTTP_RETRY:
warn(f" Get urllib.error.URLError Error. Trying {retry+1}/{const.HTTP_RETRY}...")
return urlopen(url, retry+1, get_pool_ip() if source_address else None, use_cookie)
else:
raise e
def is_live(channel_id, use_cookie=False, retry=0):
url = f"https://www.youtube.com/channel/{channel_id}/live"
with urlopen(url, use_cookie=use_cookie) as response:
html = response.read().decode()
try:
og_url = re.search(
r'<meta property="og:url" content="(.+?)">', html).group(1)
except AttributeError:
try:
og_url = re.search(
r'<link rel="canonical" href="(.+?)">', html).group(1)
except:
if retry < const.HTTP_RETRY:
return is_live(channel_id, use_cookie=use_cookie, retry=retry + 1) # Try again, sth weird happened
else:
return False
if "watch?v=" in og_url:
if 'hlsManifestUrl' not in html:
if '"status":"LOGIN_REQUIRED"' in html:
if use_cookie:
return False # No permission
else:
# Try again with cookie
return is_live(channel_id, use_cookie=True, retry=retry)
return False # No stream found
return og_url # Stream found
elif "/channel/" in og_url or "/user/" in og_url:
return False
else:
warn(
f" Something weird happened on checking Live for {channel_id}...")
return False
# 2021.5.7 Youtube chokes for PlayabilityStatus.REMOVED
# if PlayabilityStatus.REMOVED, we now check 3 times for accuracy.
def get_video_status(video_id):
def _get_video_status(video_id):
url = f"https://www.youtube.com/watch?v={video_id}"
req = urllib.request.Request(url)
req.add_header('Accept-Language', 'en-US,en;q=0.5')
with urlopen(req) as response:
html = response.read().decode()
if '"offerId":"sponsors_only_video"' in html:
return PlayabilityStatus.MEMBERS_ONLY
elif '"status":"UNPLAYABLE"' in html:
return PlayabilityStatus.COPYRIGHTED
elif '"status":"LOGIN_REQUIRED"' in html:
return PlayabilityStatus.PRIVATED
elif '"status":"ERROR"' in html:
return PlayabilityStatus.REMOVED
elif '"status":"OK"' in html:
if '"isUnlisted":true' in html:
return PlayabilityStatus.UNLISTED
if 'hlsManifestUrl' in html:
return PlayabilityStatus.ON_LIVE
return PlayabilityStatus.OK
elif '"status":"LIVE_STREAM_OFFLINE"' in html:
return PlayabilityStatus.OFFLINE
elif '"status":"LOGIN_REQUIRED"' in html:
return PlayabilityStatus.LOGIN_REQUIRED
else:
with open(os.path.join(const.LOGS_DIR, f"{video_id}.html"), "w", encoding="utf8") as f:
f.write(html)
return PlayabilityStatus.UNKNOWN
status = _get_video_status(video_id)
if status is PlayabilityStatus.REMOVED:
for _ in range(3):
tmp = _get_video_status(video_id)
if tmp is not PlayabilityStatus.REMOVED:
return tmp
return status
def notify(message, files=None):
if const.ENABLED_MODULES["discord"]:
threading.Thread(target=discord.send, args=(const.DISCORD_WEBHOOK_URL, message), kwargs={
"version": const.VERSION,
"files": files if const.DISCORD_SEND_FILES else None
}, daemon=True).start()
if const.ENABLED_MODULES["telegram"]:
if const.TELEGRAM_SEND_FILES:
threading.Thread(target=telegram.send_files, args=(const.TELEGRAM_BOT_TOKEN, const.TELEGRAM_CHAT_ID, message, files), daemon=True).start()
else:
threading.Thread(target=telegram.send, args=(const.TELEGRAM_BOT_TOKEN, const.TELEGRAM_CHAT_ID, message), daemon=True).start()
def get_avatar(url):
regex = r'"avatar":{"thumbnails":(\[{[^\]]+?\])}'
with urlopen(url) as resp:
html = resp.read().decode()
result = re.findall(regex, html)
result = [json.loads(x) for x in result]
result = [item for sublist in result for item in sublist]
result = max(result, key=lambda x: x['width'])
result = result['url']
return result