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