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