]> git.gir.st - subscriptionfeed.git/blob - app/youtube/__init__.py
apply proxy to whole stream map (not just best-muxed)
[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
9
10 from ..common.common import *
11
12 frontend = Blueprint('youtube', __name__,
13 template_folder='templates',
14 static_folder='static',
15 static_url_path='/static/yt')
16
17 @frontend.route('/')
18 def index():
19 return redirect(url_for('.feed'), code=302)
20
21 @frontend.route('/feed/subscriptions')
22 # disabled for guest user: @login_required
23 def feed():
24 if current_user.is_anonymous:
25 token = 'guest'
26 if 'welcome_message' in cf['frontend']:
27 flash(cf['frontend']['welcome_message'], "info")
28 else:
29 token = current_user.token
30 page = int(request.args.get('page', 0))
31 with sqlite3.connect(cf['global']['database']) as conn:
32 c = conn.cursor()
33 c.execute("""
34 SELECT videos.id, channel_id, name, title, published, flags.display
35 FROM videos
36 JOIN channels ON videos.channel_id = channels.id
37 LEFT JOIN flags ON (videos.id = flags.video_id) AND (flags.user = ?)
38 WHERE (channel_id IN (SELECT channel_id FROM subscriptions WHERE user=?)
39 OR flags.display = 'pinned')
40 AND flags.display IS NOT 'hidden'
41 ORDER BY (display = 'pinned') DESC, crawled DESC
42 LIMIT 36
43 OFFSET 36*?""", (token, token, page))
44 rows = [{
45 'video_id': video_id,
46 'channel_id': channel_id,
47 'author': author,
48 'title': title,
49 'published': published,
50 'pinned': display == 'pinned',
51 } for (video_id, channel_id, author, title, published, display) in c.fetchall()]
52 return render_template('index.html.j2', rows=rows, page=page)
53
54 @frontend.route('/watch')
55 def watch():
56 if current_user.is_anonymous:
57 token = 'guest'
58 else:
59 token = current_user.token
60
61 if not 'v' in request.args:
62 return "missing video id", 400
63
64 plaintextheaders = {
65 'content-type': 'text/plain',
66 'Link': "<data:text/css,body%7Bcolor:%23eee;background:%23333%7D>; rel=stylesheet;"
67 }
68
69 video_id = request.args.get('v')
70 sts, algo = get_cipher()
71 video_url, stream_map, metadata, error, errdetails = get_video_info(video_id, sts, algo)
72
73 extra = {'geolocked':'local=1', 'livestream':'raw=0'}.get(error,'')
74 invidious_url = f"https://invidio.us/watch?v={video_id}&{extra}"
75 errdetails = {
76 'malformed': "Video ID is invalid.",
77 'geolocked': "This video is geolocked.",
78 'livestream': "Livestreams not yet supported.",
79 'exhausted': errdetails or "Couldn't extract video URLs.",
80 'player': errdetails,
81 }.get(error)
82
83 # if the video is geolocked, and the proxy is enabled, we can still play it:
84 try:
85 if error == 'geolocked':
86 videoplayback = url_for('proxy.videoplayback')
87
88 query = urlparse(video_url).query
89 video_url = f"{videoplayback}?{query}"
90 for s in stream_map['adaptive']:
91 query = urlparse(s['url']).query
92 s['url'] = f"{videoplayback}?{query}"
93 for s in stream_map['muxed']:
94 query = urlparse(s['url']).query
95 s['url'] = f"{videoplayback}?{query}"
96
97 error = None
98 except: pass
99
100 show = request.args.get("show")
101 if show == "raw":
102 if error:
103 msg = errdetails if error=='player' else f"{error.upper()}: {errdetails}"
104 return f"{msg}\n\nRedirecting to Invidious.", 502, {
105 'Refresh': f'2; URL={invidious_url}&raw=1',
106 **plaintextheaders}
107 return redirect(video_url, code=307)
108 elif show == "json":
109 if error and not metadata:
110 return {'error': True, error: errdetails}, 400 # TODO: better (test _CpR4o81XQc)
111 return jsonify(metadata)
112 elif show == "audio":
113 # sorting: we want to prioritize mp4a over opus, and sort by highest quality first
114 # todo: geolocking; prefer open format?
115 if error and not metadata:
116 msg = errdetails if error=='player' else f"{error.upper()}: {errdetails}"
117 return msg, 400, plaintextheaders # TODO: nicer
118 stream = next(iter(sorted([
119 stream for stream in stream_map['adaptive']
120 if stream['mimeType'].startswith('audio/')],
121 key=lambda stream: ('opus' not in stream['mimeType'],
122 stream['bitrate']), reverse=True)
123 ),{}).get('url')
124 return redirect(stream)
125 else:
126 if error and not metadata: # e.g. malformed, private/deleted video, ...
127 return errdetails,400 # TODO: nicer
128 meta = prepare_metadata(metadata)
129 with sqlite3.connect(cf['global']['database']) as conn:
130 c = conn.cursor()
131 c.execute("""
132 SELECT COUNT((
133 SELECT 1 FROM subscriptions WHERE channel_id = ? AND user = ?
134 )), COUNT((
135 SELECT 1 FROM flags WHERE video_id = ? AND display = 'pinned' AND user = ?
136 ))""", (meta['channel_id'], token, video_id, token))
137 (is_subscribed, is_pinned) = c.fetchone()
138 return render_template('watch.html.j2',
139 video_id=video_id, video_url=video_url,
140 video_error=error, errdetails=errdetails, invidious_url=invidious_url,
141 is_pinned=is_pinned, is_subscribed=is_subscribed,
142 **meta)
143
144 @frontend.route('/embed/<video_id>')
145 def embed(video_id):
146 return redirect(url_for('youtube.watch', v=video_id))
147
148 @frontend.route('/<video_id>')
149 def raw_video_id_url(video_id):
150 # a "just-a-variable-endpoint" has lowest priority, but we check if it
151 # looks like a video id anyways, so we can have more than one such endpoint
152 # in the future.
153 if not re.match(r"^[-_0-9A-Za-z]{11}$", video_id): # not actually a video id
154 return fallback_route()
155 return redirect(url_for('youtube.watch', v=video_id))
156
157 @frontend.route('/channel/<channel_id>')
158 def channel(channel_id):
159 token = getattr(current_user, 'token', 'guest')
160
161 if not re.match(r"(UC[A-Za-z0-9_-]{22})", channel_id):
162 return "bad channel id", 400 # todo
163
164 xmlfeed = fetch_xml("channel_id", channel_id)
165 if not xmlfeed:
166 return "not found or something", 404 # XXX
167 title, author, videos = parse_xml(xmlfeed)
168
169 with sqlite3.connect(cf['global']['database']) as conn:
170 c = conn.cursor()
171 c.execute("""
172 SELECT COUNT(*)
173 FROM subscriptions
174 WHERE channel_id = ? AND user = ?
175 """, (channel_id, token))
176 (is_subscribed,) = c.fetchone()
177
178 return render_template('xmlfeed.html.j2', title=author, rows=videos,
179 is_subscribed=is_subscribed, channel_id=channel_id)
180
181 @frontend.route('/playlist')
182 def playlist():
183 playlist_id = request.args.get('list')
184 if not playlist_id:
185 return "bad list id", 400 # todo
186
187 xmlfeed = fetch_xml("playlist_id", playlist_id)
188 if not xmlfeed:
189 return "not found or something", 404 # XXX
190 title, author, videos = parse_xml(xmlfeed)
191 return render_template('xmlfeed.html.j2', title=f"{title} by {author}", rows=videos)
192
193 @frontend.route('/api/timedtext')
194 def timedtext():
195 r = requests.get("https://www.youtube.com/api/timedtext", request.args.to_dict())
196 # Note: in srv1 format, xmlentities are double-encoded m( a smart quote is
197 # even worse: it's '&amp;39;<smartquote>' wtf!? (at least vvt seems ok)
198 if not r.ok:
199 return "error: {r.text}", 400 # TODO: better
200 retval = r.text
201 if request.args.get('fmt') == 'vtt' and request.args.get('kind') == 'asr':
202 # autocaptions are extremely confusing, and stuck in the lower-left corner. fix it up a bit
203 retval = re.sub(r"<.+?>", "", retval) # remove inline html-like markup that times each word/adds styles
204 retval = retval.replace("align:start position:0%", "") # let browser position the text itself
205 # each subtitle-line is repeated twice (first on the lower line, then
206 # on the next "frame" on the upper line). we want to remove the
207 # repetition, as that's confusing without word and line animations:
208 lines = retval.split('\n')
209 retval = '\n'.join([line for line, prev in zip(lines, ['']+lines) if not " --> " in prev])
210 return retval, {'Content-Type': r.headers.get("Content-Type")}
211
212 @frontend.route('/manage/subscriptions')
213 # disabled for guest user: @login_required
214 def subscription_manager():
215 if current_user.is_anonymous:
216 token = 'guest'
217 else:
218 token = current_user.token
219 with sqlite3.connect(cf['global']['database']) as conn:
220 #with conn.cursor() as c:
221 c = conn.cursor()
222 c.execute("""
223 SELECT subscriptions.channel_id, name,
224 (subscribed_until < datetime('now')) AS obsolete
225 FROM subscriptions
226 left JOIN channels ON channels.id = subscriptions.channel_id
227 left JOIN websub ON channels.id = websub.channel_id
228 WHERE user = ?
229 AND subscriptions.type IN ('channel', 'playlist')
230 ORDER BY obsolete=0, name COLLATE NOCASE ASC""", (token,))
231 rows = [{
232 'channel_id': channel_id,
233 'author': author or channel_id,
234 'subscribed_until': subscribed_until
235 } for (channel_id, author, subscribed_until) in c.fetchall()]
236 return render_template('subscription_manager.html.j2', rows=rows)
237
238 @frontend.route('/feed/subscriptions', methods=['POST'])
239 @login_required
240 def feed_post():
241 token = current_user.token
242 action = next(request.form.keys(), None)
243 if action in ['pin', 'unpin', 'hide']:
244 video_id = request.form.get(action)
245 display = {
246 'pin': 'pinned',
247 'unpin': None,
248 'hide': 'hidden',
249 }[action]
250 with sqlite3.connect(cf['global']['database']) as conn:
251 c = conn.cursor()
252 store_video_metadata(video_id) # only needed for pinning
253 c.execute("""
254 INSERT OR REPLACE INTO flags (user, video_id, display)
255 VALUES (?, ?, ?)
256 """, (token, video_id, display))
257 else:
258 flash("unsupported action", "error")
259 return redirect(request.url, code=303)
260
261 @frontend.route('/manage/subscriptions', methods=['POST'])
262 @login_required
263 def manage_subscriptions():
264 token = current_user.token
265 if 'subscribe' in request.form:
266 channel_id = request.form.get("subscribe")
267 match = re.search(r"(UC[A-Za-z0-9_-]{22})", channel_id)
268 if match:
269 channel_id = match.group(1)
270 else:
271 match = re.search(r"((?:PL|LL|EC|UU|FL|UL|OL)[A-Za-z0-9_-]{10,})", channel_id)
272 if match: # NOTE: PL-playlists are 32chars, others differ in length.
273 flash("playlists not (yet?) supported.", "error")
274 return redirect(request.url, code=303) # TODO: dedup redirection
275 else:
276 flash("not a valid/subscribable URI", "error")
277 return redirect(request.url, code=303) # TODO: dedup redirection
278 with sqlite3.connect(cf['global']['database']) as conn:
279 #with conn.cursor() as c:
280 c = conn.cursor()
281 c.execute("""
282 INSERT OR IGNORE INTO subscriptions (user, channel_id)
283 VALUES (?, ?)
284 """, (token, channel_id))
285 # TODO: sql-error-handling, asynchronically calling update-subs.pl
286
287 elif 'unsubscribe' in request.form:
288 channel_id = request.form.get("unsubscribe")
289 with sqlite3.connect(cf['global']['database']) as conn:
290 #with conn.cursor() as c:
291 c = conn.cursor()
292 c.execute("""
293 DELETE FROM subscriptions
294 WHERE user = ? AND channel_id = ?
295 """, (token, channel_id))
296 # TODO: sql-error-handling, report success
297
298 else:
299 flash("unsupported action", "error")
300
301 return redirect(request.url, code=303)
302
303 def get_cipher():
304 # reload cipher from database every 1 hour
305 if 'cipher' not in g or time.time() - g.get('cipher_updated', 0) > 1 * 60 * 60:
306 with sqlite3.connect(cf['global']['database']) as conn:
307 c = conn.cursor()
308 c.execute("SELECT sts, algorithm FROM cipher")
309 g.cipher = c.fetchone()
310 g.cipher_updated = time.time()
311
312 return g.cipher
313
314 #@frontend.teardown_appcontext
315 #def teardown_db():
316 # db = g.pop('db', None)
317 #
318 # if db is not None:
319 # db.close()
320
321
322 @frontend.app_template_filter('format_date')
323 def format_date(s):
324 import datetime # can't import at top level, because it is inherited from common
325 (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'
326 M = '_ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()
327 if y == datetime.datetime.now().year:
328 return f"{d} {M[m]}"
329 else:
330 return f"{M[m]} '{y%100}"
Imprint / Impressum