]> git.gir.st - subscriptionfeed.git/blob - app/youtube/__init__.py
watch: don't fail if itag specified on vevo scrambled video
[subscriptionfeed.git] / app / youtube / __init__.py
1 import re
2 import time
3 import sqlite3
4 import requests
5 from urllib.parse import urlparse
6 #from flask_login import current_user, login_required
7 from flask_login import LoginManager, UserMixin, current_user, login_user, logout_user, login_required
8 from flask import Blueprint, render_template, request, redirect, flash, url_for, jsonify, g, current_app
9 from werkzeug.exceptions import NotFound, BadGateway
10
11 from ..common.common import *
12 from ..common.anticaptcha import submit_captcha
13 from .lib import *
14
15 frontend = Blueprint('youtube', __name__,
16 template_folder='templates',
17 static_folder='static',
18 static_url_path='/static/yt')
19
20 @frontend.route('/')
21 def index():
22 return redirect(url_for('.feed'), code=302)
23
24 @frontend.route('/feed/subscriptions')
25 # disabled for guest user: @login_required
26 def feed():
27 if current_user.is_anonymous:
28 token = 'guest'
29 if 'welcome_message' in cf['frontend']:
30 flash(cf['frontend']['welcome_message'], "welcome")
31 else:
32 token = current_user.token
33 page = request.args.get('page', 0, type=int)
34 with sqlite3.connect(cf['global']['database']) as conn:
35 c = conn.cursor()
36
37 settings = {} # fallback for guest user
38 if current_user.is_authenticated:
39 c.execute("""
40 SELECT setting, value
41 FROM user_settings
42 WHERE user_id = ?
43 """, (current_user.id,))
44 settings = {
45 setting: json.loads(value)
46 for setting, value in c.fetchall()
47 }
48
49 c.execute("""
50 SELECT videos.id, channel_id, name, title, length, livestream, premiere, shorts, published > datetime('now') as upcoming, published, playlist_videos.playlist_id, display
51 FROM videos
52 JOIN channels ON videos.channel_id = channels.id
53 LEFT JOIN playlist_videos ON (videos.id = playlist_videos.video_id)
54 LEFT JOIN flags ON (videos.id = flags.video_id) AND (flags.user = ?)
55 WHERE (channel_id IN (SELECT channel_id FROM subscriptions WHERE user=? AND type = 'channel')
56 OR playlist_videos.playlist_id IN (SELECT channel_id FROM subscriptions WHERE user=? AND type = 'playlist')
57 OR flags.display = 'pinned')
58 AND flags.display IS NOT 'hidden'
59 AND (flags.display = 'pinned' OR not ? or not shorts)
60 ORDER BY (display = 'pinned') DESC, crawled DESC
61 LIMIT 36
62 OFFSET 36*?""", (token, token, token, settings.get('noshorts', False), page))
63 rows = [{
64 'video_id': video_id,
65 'channel_id': channel_id,
66 'author': author,
67 'title': title,
68 'length': length,
69 'livestream': livestream,
70 'premiere': premiere,
71 'shorts': shorts,
72 'upcoming': upcoming,
73 'published': published,
74 'playlist': playlist,
75 'pinned': display == 'pinned',
76 } for (video_id, channel_id, author, title, length, livestream, premiere, shorts, upcoming, published, playlist, display) in c.fetchall()]
77 return render_template('index.html.j2', rows=rows, page=page)
78
79 @frontend.route('/watch')
80 def watch():
81 if current_user.is_anonymous:
82 token = 'guest'
83 else:
84 token = current_user.token
85
86 if not 'v' in request.args:
87 return "missing video id", 400
88 if len(request.args.get('v')) != 11:
89 return "malformed video id", 400
90
91 plaintextheaders = {
92 'content-type': 'text/plain',
93 'Link': "<data:text/css,body%7Bcolor:%23eee;background:%23333%7D>; rel=stylesheet;"
94 }
95
96 video_id = request.args.get('v')
97 show = request.args.get("show")
98 itag = request.args.get("itag")
99 video_url, stream_map, metadata, error, errdetails = get_video_info(video_id, metaOnly=(show == 'meta'))
100
101 if itag: # if itag is specified and available, force its use even if not highest resolution
102 video_url = next((e['url'] for e in stream_map['muxed'] if 'url' in e and e['itag'] == int(itag)), video_url)
103
104 proxy_on = getattr(g, 'proxy_on', None)
105 proxy_msg = {
106 False: "Log in to use proxy.", # proxy for logged-in users only
107 None: "", # proxy disabled globally
108 True: "", # proxy is available to this user
109 }[proxy_on]
110 errdetails = {
111 'banned': "Instance is being rate limited.",
112 'malformed': "Video ID is invalid.",
113 'geolocked': f"This video is geolocked. {proxy_msg}",
114 'livestream': f"Livestreams disabled. {proxy_msg}",
115 'agegated': "Unable to bypass age-restriction.",
116 'scrambled': "VEVO style cyphering not supported.",
117 'no-url': "No muxed stream available.",
118 'exhausted': errdetails or "Couldn't extract video URLs.",
119 'player': errdetails,
120 }.get(error, error)
121
122 # if the video is geolocked, and the proxy is enabled, we can still play
123 # it, if the video is available in the instance server's region:
124 if error == 'geolocked' and video_url and proxy_on:
125 videoplayback = url_for('proxy.videoplayback')
126 query = urlparse(video_url).query
127 video_url = f"{videoplayback}?{query}"
128 for t in ('adaptive_video', 'adaptive_audio', 'muxed'):
129 for s in stream_map[t]:
130 query = urlparse(s['url']).query
131 s['url'] = f"{videoplayback}?{query}"
132 error = None
133
134 # if the proxy is enabled, we can also play livestreams:
135 if error == 'livestream' and proxy_on:
136 # Note: hlsManifestUrl's hostname will be replaced client-side
137 video_url = stream_map['hlsManifestUrl']
138 error = None
139
140 # if the instance is blocked, try submitting a job to the anti captcha service:
141 if error == 'banned' and cf['captcha']['api_key']:
142 r2 = requests.get(f'https://www.youtube.com/watch?v={video_id}&hl=en&gl=US')
143 status = submit_captcha(r2)
144 if status is False:
145 raise Exception("we are banned, but captcha wasn't triggered!")
146 else:
147 message = "right now" if status is True else f"{int(status)} seconds ago"
148 raise BadGateway(f"""
149 {errdetails} An attempt at getting unblocked has been made {message}.
150 Please try again in 30 seconds.
151 """)
152
153 if show == "raw":
154 if error:
155 msg = errdetails if error=='player' else f"{error.upper()}: {errdetails}"
156 return msg, 400, plaintextheaders # TODO: nicer
157 return redirect(video_url, code=307)
158 elif show == "json":
159 if error and not metadata:
160 return {'error': True, error: errdetails}, 400 # TODO: better (test _CpR4o81XQc)
161 return jsonify(metadata)
162 elif show == "audio":
163 # sorting: we want to prioritize mp4a over opus, and sort by highest quality first
164 # todo: geolocking; prefer open format?
165 if error and not stream_map:
166 msg = errdetails if error=='player' else f"{error.upper()}: {errdetails}"
167 return msg, 400, plaintextheaders # TODO: nicer
168 stream = next(iter(sorted(
169 stream_map['adaptive_audio'],
170 key=lambda e: ('opus' not in e['mimeType'], e['bitrate']),
171 reverse=True
172 )),{}).get('url')
173 return redirect(stream)
174 elif show == "meta":
175 # this is the subset of (useful) keys that are not present in the
176 # Android API response. the special key '_' contains ready-to-use
177 # parsed versions of that data.
178 if error and not metadata:
179 return {'error': True, error: errdetails}, 400 # TODO: better (test _CpR4o81XQc)
180 parsed = microformat_parser(metadata)
181 return {'microformat': metadata.get('microformat'),'cards':metadata.get('cards'), '_':parsed}
182 else:
183 extra = {'geolocked':'local=1', 'livestream':'raw=0'}.get(error,'')
184 invidious_url = f"https://redirect.invidious.io/watch?v={video_id}&{extra}"
185 if error and not metadata: # e.g. malformed, private/deleted video, ...
186 return render_template('video-error.html.j2', video_id=video_id,
187 video_error=error, errdetails=errdetails, invidious_url=invidious_url)
188 meta = prepare_metadata(metadata)
189 with sqlite3.connect(cf['global']['database']) as conn:
190 c = conn.cursor()
191 c.execute("""
192 SELECT COUNT((
193 SELECT 1 FROM subscriptions WHERE channel_id = ? AND user = ?
194 )), COUNT((
195 SELECT 1 FROM flags WHERE video_id = ? AND display = 'pinned' AND user = ?
196 ))""", (meta['channel_id'], token, video_id, token))
197 (is_subscribed, is_pinned) = c.fetchone()
198 return render_template('watch.html.j2',
199 video_id=video_id, video_url=video_url, stream_map=stream_map,
200 video_error=error, errdetails=errdetails, invidious_url=invidious_url,
201 is_pinned=is_pinned, is_subscribed=is_subscribed,
202 **meta)
203
204 @frontend.route('/embed/videoseries')
205 def embed_videoseries():
206 return redirect(url_for('.playlist', list=request.args.get('list')))
207 @frontend.route('/embed/<video_id>', strict_slashes=False)
208 def embed(video_id):
209 if video_id == "videoseries":
210 return redirect(url_for('.playlist', list=request.args.get('list')))
211
212 return redirect(url_for('.watch', v=video_id, t=request.args.get('start')))
213
214 @frontend.route('/live/<video_id>', strict_slashes=False)
215 @frontend.route('/shorts/<video_id>', strict_slashes=False)
216 def shorts_or_live(video_id):
217 return redirect(url_for('.watch', v=video_id, t=request.args.get('start')))
218
219 @frontend.route('/<something>', strict_slashes=False)
220 def plain_user_or_video(something):
221 # yt.com interprets this as a username, but we also want to catch youtu.be
222 # short-urls. so we check if it's a channel by querying the RSS feed (this
223 # shoudn't be rate-limited); if that fails, check if it looks like a video
224 # id; or finally give up.
225 if '.' not in something and channel_exists(something):
226 # periods are not valid in usernames, vanity urls or ucids, but common
227 # in urls that get crawled by bots (e.g. index.php). failing early
228 # reduces the amount of invalid channel names getting looked up.
229 return redirect(url_for('.channel', channel_id=something))
230 elif re.match(r"^[-_0-9A-Za-z]{11}$", something): # looks like a video id
231 return redirect(url_for('.watch', v=something, t=request.args.get('t')))
232 else: # ¯\_(ツ)_/¯
233 # XXX: something == 'thethoughtemporium' -> 404s
234 raise NotFound("Note: some usernames not recognized; try searching it")
235
236 @frontend.route('/attribution_link', strict_slashes=False)
237 def attribution_link():
238 # /attribution_link?a=anything&u=/channel/UCZYTClx2T1of7BRZ86-8fow
239 # /attribution_link?a=JdfC0C9V6ZI&u=%2Fwatch%3Fv%3DEhxJLojIE_o%26feature%3Dshare
240 return redirect(request.args.get('u') or '/')
241
242 @frontend.route('/c/<channel_id>/<subpage>')
243 @frontend.route('/c/<channel_id>/')
244 @frontend.route('/user/<channel_id>/<subpage>')
245 @frontend.route('/user/<channel_id>/')
246 def channel_redirect(channel_id, subpage=None):
247 # Note: we can't check /c/, so we have to assume it is the same as /user/,
248 # which is sometimes wrong.
249 xmlfeed = fetch_xml("user", channel_id)
250
251 if not xmlfeed:
252 raise NotFound("unknown channel name")
253
254 _, _, _, channel_id, _ = parse_xml(xmlfeed)
255
256 return redirect(url_for('.channel', channel_id=channel_id))
257
258 @frontend.route('/channel/<channel_id>/<subpage>')
259 @frontend.route('/channel/<channel_id>/')
260 def channel(channel_id, _=None):
261 token = getattr(current_user, 'token', 'guest')
262 sort = request.args.get("sort", "newest")
263
264 if not re.match(r"(UC[A-Za-z0-9_-]{22})", channel_id):
265 # canonicalize channel id, otherwise popular won't work
266 return redirect(url_for('.channel_redirect', channel_id=channel_id))
267
268 if sort == "popular":
269 xmlfeed = fetch_xml("playlist_id", f"PU{channel_id[2:]}")
270 else:
271 xmlfeed = fetch_xml("channel_id", channel_id)
272 #^note: could also use playlist_id=UU...
273
274 if not xmlfeed:
275 raise NotFound("unknown channel id")
276
277 title, author, videos, _, _ = parse_xml(xmlfeed)
278
279 with sqlite3.connect(cf['global']['database']) as conn:
280 c = conn.cursor()
281 c.execute("""
282 SELECT COUNT(*)
283 FROM subscriptions
284 WHERE channel_id = ? AND user = ?
285 """, (channel_id, token))
286 (is_subscribed,) = c.fetchone()
287
288 return render_template('xmlfeed.html.j2', title=author, rows=videos,
289 is_subscribed=is_subscribed, channel_id=channel_id)
290
291 @frontend.route('/playlist')
292 def playlist():
293 playlist_id = request.args.get('list')
294 if not playlist_id:
295 return "bad list id", 400 # todo
296
297 xmlfeed = fetch_xml("playlist_id", playlist_id)
298 if not xmlfeed:
299 return "not found or something", 404 # XXX
300 title, author, videos, _, _ = parse_xml(xmlfeed)
301 return render_template('xmlfeed.html.j2', title=f"{title} by {author}", rows=videos)
302
303 @frontend.route('/api/timedtext')
304 def timedtext():
305 r = requests.get("https://www.youtube.com/api/timedtext", request.args.to_dict())
306 # Note: in srv1 format, xmlentities are double-encoded m( a smart quote is
307 # even worse: it's '&amp;39;<smartquote>' wtf!? (at least vvt seems ok)
308 if not r.ok:
309 return "error: {r.text}", 400 # TODO: better
310 retval = r.text
311 if request.args.get('fmt') == 'vtt' and request.args.get('kind') == 'asr':
312 # autocaptions are extremely confusing, and stuck in the lower-left corner. fix it up a bit
313 retval = re.sub(r"<.+?>", "", retval) # remove inline html-like markup that times each word/adds styles
314 retval = retval.replace("align:start position:0%", "") # let browser position the text itself
315 # each subtitle-line is repeated twice (first on the lower line, then
316 # on the next "frame" on the upper line). we want to remove the
317 # repetition, as that's confusing without word and line animations:
318 lines = retval.split('\n')
319 retval = '\n'.join([line for line, prev in zip(lines, ['']+lines) if not " --> " in prev])
320 return retval, {'Content-Type': r.headers.get("Content-Type")}
321
322 @frontend.route('/manage/subscriptions')
323 # disabled for guest user: @login_required
324 def subscription_manager():
325 if current_user.is_anonymous:
326 token = 'guest'
327 else:
328 token = current_user.token
329 with sqlite3.connect(cf['global']['database']) as conn:
330 #with conn.cursor() as c:
331 c = conn.cursor()
332 c.execute("""
333 SELECT subscriptions.channel_id, name, type,
334 (subscribed_until < datetime('now')) AS obsolete
335 FROM subscriptions
336 LEFT JOIN (SELECT name, id FROM channels
337 UNION
338 SELECT name, id FROM playlists
339 ) AS channels ON channels.id = subscriptions.channel_id
340 left JOIN websub ON channels.id = websub.channel_id
341 WHERE user = ?
342 AND subscriptions.type IN ('channel', 'playlist')
343 ORDER BY obsolete=0, name COLLATE NOCASE ASC""", (token,))
344 rows = [{
345 'channel_id': channel_id,
346 'author': author or channel_id,
347 'type': type,
348 'subscribed_until': subscribed_until
349 } for (channel_id, author, type, subscribed_until) in c.fetchall()]
350 return render_template('subscription_manager.html.j2', rows=rows)
351
352 @frontend.route('/feed/subscriptions', methods=['POST'])
353 @login_required
354 def feed_post():
355 token = current_user.token
356 action = next(iter(list(request.form.keys())), None)
357 if action in ['pin', 'unpin', 'hide', 'unhide']:
358 video_id = request.form.get(action)
359 display = {
360 'pin': 'pinned',
361 'unpin': None,
362 'hide': 'hidden',
363 'unhide': None,
364 }[action]
365 with sqlite3.connect(cf['global']['database']) as conn:
366 c = conn.cursor()
367 store_video_metadata(video_id) # only needed for pinning
368 c.execute("""
369 INSERT OR REPLACE INTO flags (user, video_id, display)
370 VALUES (?, ?, ?)
371 """, (token, video_id, display))
372 undo_flash(video_id, action)
373 else:
374 flash("unsupported action", "error")
375 return redirect(request.url, code=303)
376
377 @frontend.route('/manage/subscriptions', methods=['POST'])
378 @login_required
379 def manage_subscriptions():
380 token = current_user.token
381 if 'subscribe' in request.form:
382 some_id = request.form.get("subscribe")
383 match = re.search(r"(UC[A-Za-z0-9_-]{22})", some_id)
384 if match:
385 some_id = match.group(1)
386 id_type = "channel"
387 else:
388 match = re.search(r"((?:PL|LL|EC|UU|FL|UL|OL)[A-Za-z0-9_-]{10,})", some_id)
389 if match: # NOTE: PL-playlists are 32chars, others differ in length.
390 some_id = match.group(1)
391 id_type = "playlist"
392 else:
393 flash("not a valid/subscribable URI", "error")
394 return redirect(request.url, code=303)
395 with sqlite3.connect(cf['global']['database']) as conn:
396 #with conn.cursor() as c:
397 c = conn.cursor()
398 c.execute("""
399 INSERT OR IGNORE INTO subscriptions (user, channel_id, type)
400 VALUES (?, ?, ?)
401 """, (token, some_id, id_type))
402 # TODO: sql-error-handling, asynchronically calling update-subs.pl
403 undo_flash(some_id, 'subscribe')
404
405 elif 'unsubscribe' in request.form:
406 some_id = request.form.get("unsubscribe")
407 with sqlite3.connect(cf['global']['database']) as conn:
408 #with conn.cursor() as c:
409 c = conn.cursor()
410 c.execute("""
411 DELETE FROM subscriptions
412 WHERE user = ? AND channel_id = ?
413 """, (token, some_id))
414 # TODO: sql-error-handling, report success
415 undo_flash(some_id, 'unsubscribe')
416
417 else:
418 flash("unsupported action", "error")
419
420 return redirect(request.url, code=303)
421
422 @frontend.route('/vi/<vid>/<res>.jpg')
423 def redirect_thumbnails(vid, res):
424 return redirect(f"https://i.ytimg.com{request.path}", code=301)
425
426 @frontend.record
427 def redirect_youtube_dot_com(state):
428 """
429 This is executed when the blueprint is loaded dynamically builds a number
430 of routes so that URLs like
431 https://subscriptions.gir.st/https://www.youtube.com/watch?v=dQw4w9WgXcQ
432 redirect to the /watch page. Works with /watch, /embed/ and youtu.be short
433 links, with or without protocl and/or 'www'.
434 """
435 def real_redirect_youtube_dot_com(video_id=None):
436 if not re.match(r"^[-_0-9A-Za-z]{11}$", video_id or ''): video_id = None
437 if not video_id: video_id = request.args.get('v')
438 return redirect(url_for('.watch', v=video_id))
439
440 for protocol in ("", "http://", "https://"):
441 for prefix in ("", "www.", "m."):
442 for domain in ("youtube.com", "youtu.be", "youtube-nocookie.com"):
443 for urlpath in ("/watch", "/embed/<video_id>", "/live/<video_id>", "/shorts/<video_id>", "/<video_id>"):
444 if domain != "youtu.be" and urlpath == "/<video_id>":
445 continue # that's a channel, not a video
446 frontend.add_url_rule(
447 f"/{protocol}{prefix}{domain}{urlpath}",
448 view_func=real_redirect_youtube_dot_com,
449 strict_slashes=False
450 )
451
452 def undo_flash(thing_id, action):
453 undo_action, past_action = {
454 'pin': ('unpin', 'pinned'),
455 'unpin': ('pin', 'unpinned'),
456 'hide': ('unhide', 'hidden'),
457 'unhide': ('hide', 'unhidden'),
458 'subscribe': ('unsubscribe', 'subscribed'),
459 'unsubscribe': ('subscribe', 'unsubscribed'),
460 }.get(action)
461 if 'subscribe' in action and thing_id.startswith('UC'):
462 thing = "channel"
463 thing_url = url_for('.channel', channel_id=thing_id)
464 elif 'subscribe' in action:
465 thing = "playlist"
466 thing_url = url_for('.playlist', playlist_id=thing_id)
467 else:
468 thing = "video"
469 thing_url = url_for('.watch', v=thing_id)
470 flash(f'''
471 <form method=post><input type=hidden name="{undo_action}" value="{thing_id}">
472 <a href="{thing_url}">{thing}</a> {past_action}.
473 <label><input type="submit" hidden>
474 <span style="text-decoration:underline;cursor:pointer">undo</span>.
475 </label></form>''', "info")
476
477 @frontend.app_template_filter('format_date')
478 def format_date(s):
479 import datetime # can't import at top level, because it is inherited from common
480 (y,m,d) = (int(n) for n in s.split('T')[0].split(' ')[0].split('-')) # iso-dates can seperate date from time with space or 'T'
481 M = '_ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()
482 if y == datetime.datetime.now().year:
483 return f"{d} {M[m]}"
484 else:
485 return f"{M[m]} '{y%100}"
486
487 @frontend.app_template_filter('format_time')
488 def format_time(i):
489 if i is None:
490 return None
491 h = i // (60*60)
492 m = i // 60 % 60
493 s = i % 60
494 return '%d:%02d:%02d' % (h,m,s) if h else '%02d:%02d' % (m,s)
495
496 @frontend.app_template_filter('timeoffset')
497 def timeoffset(s):
498 if s is None:
499 return None
500 match = re.match(r"^(\d+)s?$", s) # e.g. 2040s
501 if match:
502 return match.group(1)
503 match = re.match(r"^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$", s) # e.g. 34m, 1h23s
504 if match:
505 return ":".join([n.zfill(2) for n in match.groups('0')])
506 return None
Imprint / Impressum