]> git.gir.st - subscriptionfeed.git/blob - app/youtube/__init__.py
use proxy for geolocked videos (iff enabled)
[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, 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}&raw=1"
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 videoplayback = url_for('proxy.videoplayback')
86 query = urlparse(video_url).query
87
88 video_url = f"{videoplayback}?{query}"
89 if error == 'geolocked': error = None
90 except: pass
91
92 show = request.args.get("show")
93 if show == "raw":
94 if error:
95 msg = errdetails if error=='player' else f"{error.upper()}: {errdetails}"
96 return f"{msg}\n\nRedirecting to Invidious.", 502, {
97 'Refresh': f'2; URL={invidious_url}',
98 **plaintextheaders}
99 return redirect(video_url, code=307)
100 elif show == "json":
101 if error and not metadata:
102 return {'error': True, error: errdetails}, 400 # TODO: better (test _CpR4o81XQc)
103 return jsonify(metadata)
104 else:
105 if error and not metadata: # e.g. malformed, private/deleted video, ...
106 return errdetails,400 # TODO: nicer
107 meta = prepare_metadata(metadata)
108 with sqlite3.connect(cf['global']['database']) as conn:
109 c = conn.cursor()
110 c.execute("""
111 SELECT COUNT((
112 SELECT 1 FROM subscriptions WHERE channel_id = ? AND user = ?
113 )), COUNT((
114 SELECT 1 FROM flags WHERE video_id = ? AND display = 'pinned' AND user = ?
115 ))""", (meta['channel_id'], token, video_id, token))
116 (is_subscribed, is_pinned) = c.fetchone()
117 return render_template('watch.html.j2',
118 video_id=video_id, video_url=video_url,
119 video_error=error, errdetails=errdetails, invidious_url=invidious_url,
120 is_pinned=is_pinned, is_subscribed=is_subscribed,
121 **meta)
122
123 @frontend.route('/embed/<video_id>')
124 def embed(video_id):
125 return redirect(url_for('youtube.watch', v=video_id))
126
127 @frontend.route('/<video_id>')
128 def raw_video_id_url(video_id):
129 # a "just-a-variable-endpoint" has lowest priority, but we check if it
130 # looks like a video id anyways, so we can have more than one such endpoint
131 # in the future.
132 if not re.match(r"^[-_0-9A-Za-z]{11}$", video_id): # not actually a video id
133 return fallback_route()
134 return redirect(url_for('youtube.watch', v=video_id))
135
136 @frontend.route('/channel/<channel_id>')
137 def channel(channel_id):
138 token = getattr(current_user, 'token', 'guest')
139
140 if not re.match(r"(UC[A-Za-z0-9_-]{22})", channel_id):
141 return "bad channel id", 400 # todo
142
143 xmlfeed = fetch_xml("channel_id", channel_id)
144 if not xmlfeed:
145 return "not found or something", 404 # XXX
146 title, author, videos = parse_xml(xmlfeed)
147
148 with sqlite3.connect(cf['global']['database']) as conn:
149 c = conn.cursor()
150 c.execute("""
151 SELECT COUNT(*)
152 FROM subscriptions
153 WHERE channel_id = ? AND user = ?
154 """, (channel_id, token))
155 (is_subscribed,) = c.fetchone()
156
157 return render_template('xmlfeed.html.j2', title=author, rows=videos,
158 is_subscribed=is_subscribed, channel_id=channel_id)
159
160 @frontend.route('/playlist')
161 def playlist():
162 playlist_id = request.args.get('list')
163 if not playlist_id:
164 return "bad list id", 400 # todo
165
166 xmlfeed = fetch_xml("playlist_id", playlist_id)
167 if not xmlfeed:
168 return "not found or something", 404 # XXX
169 title, author, videos = parse_xml(xmlfeed)
170 return render_template('xmlfeed.html.j2', title=f"{title} by {author}", rows=videos)
171
172 @frontend.route('/api/timedtext')
173 def timedtext():
174 r = requests.get("https://www.youtube.com/api/timedtext", request.args.to_dict())
175 # Note: in srv1 format, xmlentities are double-encoded m( a smart quote is
176 # even worse: it's '&amp;39;<smartquote>' wtf!? (at least vvt seems ok)
177 if not r.ok:
178 return "error: {r.text}", 400 # TODO: better
179 retval = r.text
180 if request.args.get('fmt') == 'vtt' and request.args.get('kind') == 'asr':
181 # autocaptions are extremely confusing, and stuck in the lower-left corner. fix it up a bit
182 retval = re.sub(r"<.+?>", "", retval) # remove inline html-like markup that times each word/adds styles
183 retval = retval.replace("align:start position:0%", "") # let browser position the text itself
184 # each subtitle-line is repeated twice (first on the lower line, then
185 # on the next "frame" on the upper line). we want to remove the
186 # repetition, as that's confusing without word and line animations:
187 lines = retval.split('\n')
188 retval = '\n'.join([line for line, prev in zip(lines, ['']+lines) if not " --> " in prev])
189 return retval, {'Content-Type': r.headers.get("Content-Type")}
190
191 @frontend.route('/manage/subscriptions')
192 # disabled for guest user: @login_required
193 def subscription_manager():
194 if current_user.is_anonymous:
195 token = 'guest'
196 else:
197 token = current_user.token
198 with sqlite3.connect(cf['global']['database']) as conn:
199 #with conn.cursor() as c:
200 c = conn.cursor()
201 c.execute("""
202 SELECT subscriptions.channel_id, name,
203 (subscribed_until < datetime('now')) AS obsolete
204 FROM subscriptions
205 left JOIN channels ON channels.id = subscriptions.channel_id
206 left JOIN websub ON channels.id = websub.channel_id
207 WHERE user = ?
208 AND subscriptions.type IN ('channel', 'playlist')
209 ORDER BY obsolete=0, name COLLATE NOCASE ASC""", (token,))
210 rows = [{
211 'channel_id': channel_id,
212 'author': author or channel_id,
213 'subscribed_until': subscribed_until
214 } for (channel_id, author, subscribed_until) in c.fetchall()]
215 return render_template('subscription_manager.html.j2', rows=rows)
216
217 @frontend.route('/feed/subscriptions', methods=['POST'])
218 @login_required
219 def feed_post():
220 token = current_user.token
221 action = next(request.form.keys(), None)
222 if action in ['pin', 'unpin', 'hide']:
223 video_id = request.form.get(action)
224 display = {
225 'pin': 'pinned',
226 'unpin': None,
227 'hide': 'hidden',
228 }[action]
229 with sqlite3.connect(cf['global']['database']) as conn:
230 c = conn.cursor()
231 store_video_metadata(video_id) # only needed for pinning
232 c.execute("""
233 INSERT OR REPLACE INTO flags (user, video_id, display)
234 VALUES (?, ?, ?)
235 """, (token, video_id, display))
236 else:
237 flash("unsupported action", "error")
238 return redirect(request.url, code=303)
239
240 @frontend.route('/manage/subscriptions', methods=['POST'])
241 @login_required
242 def manage_subscriptions():
243 token = current_user.token
244 if 'subscribe' in request.form:
245 channel_id = request.form.get("subscribe")
246 match = re.search(r"(UC[A-Za-z0-9_-]{22})", channel_id)
247 if match:
248 channel_id = match.group(1)
249 else:
250 match = re.search(r"((?:PL|LL|EC|UU|FL|UL|OL)[A-Za-z0-9_-]{10,})", channel_id)
251 if match: # NOTE: PL-playlists are 32chars, others differ in length.
252 flash("playlists not (yet?) supported.", "error")
253 return redirect(request.url, code=303) # TODO: dedup redirection
254 else:
255 flash("not a valid/subscribable URI", "error")
256 return redirect(request.url, code=303) # TODO: dedup redirection
257 with sqlite3.connect(cf['global']['database']) as conn:
258 #with conn.cursor() as c:
259 c = conn.cursor()
260 c.execute("""
261 INSERT OR IGNORE INTO subscriptions (user, channel_id)
262 VALUES (?, ?)
263 """, (token, channel_id))
264 # TODO: sql-error-handling, asynchronically calling update-subs.pl
265
266 elif 'unsubscribe' in request.form:
267 channel_id = request.form.get("unsubscribe")
268 with sqlite3.connect(cf['global']['database']) as conn:
269 #with conn.cursor() as c:
270 c = conn.cursor()
271 c.execute("""
272 DELETE FROM subscriptions
273 WHERE user = ? AND channel_id = ?
274 """, (token, channel_id))
275 # TODO: sql-error-handling, report success
276
277 else:
278 flash("unsupported action", "error")
279
280 return redirect(request.url, code=303)
281
282 def get_cipher():
283 # reload cipher from database every 1 hour
284 if 'cipher' not in g or time.time() - g.get('cipher_updated', 0) > 1 * 60 * 60:
285 with sqlite3.connect(cf['global']['database']) as conn:
286 c = conn.cursor()
287 c.execute("SELECT sts, algorithm FROM cipher")
288 g.cipher = c.fetchone()
289 g.cipher_updated = time.time()
290
291 return g.cipher
292
293 #@frontend.teardown_appcontext
294 #def teardown_db():
295 # db = g.pop('db', None)
296 #
297 # if db is not None:
298 # db.close()
299
300
301 @frontend.app_template_filter('format_date')
302 def format_date(s):
303 import datetime # can't import at top level, because it is inherited from common
304 (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'
305 M = '_ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()
306 if y == datetime.datetime.now().year:
307 return f"{d} {M[m]}"
308 else:
309 return f"{M[m]} '{y%100}"
Imprint / Impressum