]> git.gir.st - subscriptionfeed.git/blob - app/frontend.py
better error messages on EXHAUSTED, fix invidious_url, minor cleanups
[subscriptionfeed.git] / app / frontend.py
1 import re
2 import time
3 import hmac
4 import hashlib
5 import sqlite3
6 import secrets
7 import requests
8 from urllib.parse import parse_qs
9 from flask import Flask, render_template, request, redirect, flash, url_for, jsonify, g
10
11 from common import *
12
13 app = Flask(__name__)
14 app.secret_key = secrets.token_bytes(16) # XXX: generate and hard-code, or cookies and csrf-validation will fail!
15
16 @app.route('/')
17 def index():
18 return redirect(url_for('feed'), code=302)
19
20 @app.route('/feed/subscriptions')
21 def feed():
22 token = request.args.get('token', 'guest')
23 page = int(request.args.get('page', 0))
24 with sqlite3.connect(cf['global']['database']) as conn:
25 c = conn.cursor()
26 c.execute("""
27 SELECT videos.id, channel_id, name, title, published, flags.display
28 FROM videos
29 JOIN channels ON videos.channel_id = channels.id
30 LEFT JOIN flags ON (videos.id = flags.video_id) AND (flags.user = ?)
31 WHERE channel_id IN
32 (SELECT channel_id FROM subscriptions WHERE user = ?)
33 AND flags.display IS NOT 'hidden'
34 ORDER BY (display = 'pinned') DESC, crawled DESC
35 LIMIT 36
36 OFFSET 36*?""", (token, token, page))
37 rows = [{
38 'video_id': video_id,
39 'channel_id': channel_id,
40 'author': author,
41 'title': title,
42 'published': published,
43 'pinned': display == 'pinned',
44 } for (video_id, channel_id, author, title, published, display) in c.fetchall()]
45 return render_template('index.html.j2', rows=rows, page=page)
46
47 @app.route('/watch')
48 def watch():
49 if not 'v' in request.args:
50 return "missing video id", 400
51
52 plaintextheaders = {
53 'content-type': 'text/plain',
54 'Link': "<data:text/css,body%7Bcolor:%23eee;background:%23333%7D>; rel=stylesheet;"
55 }
56
57 video_id = request.args.get('v')
58 sts, algo = get_cipher()
59 video_url, metadata, error, errdetails = get_video_info(video_id, sts, algo)
60
61 extra = {'geolocked':'local=1', 'livestream':'raw=0'}.get(error,'')
62 invidious_url = f"https://invidio.us/watch?v={video_id}&{extra}&raw=1"
63 errdetails = {
64 'malformed': "Video ID is invalid.",
65 'geolocked': "This video is geolocked.",
66 'livestream': "Livestreams not yet supported.",
67 'exhausted': errdetails or "Couldn't extract video URLs.",
68 'player': errdetails,
69 }.get(error)
70
71 show = request.args.get("show")
72 if show == "raw":
73 if error:
74 msg = errdetails if error=='player' else f"{error.upper()}: {errdetails}"
75 return f"{msg}\n\nRedirecting to Invidious.", 502, {
76 'Refresh': f'2; URL={invidious_url}',
77 **plaintextheaders}
78 return redirect(video_url, code=307)
79 elif show == "json":
80 if error and not metadata:
81 return {'error': True, error: errdetails}, 400 # TODO: better (test _CpR4o81XQc)
82 return jsonify(metadata)
83 else:
84 if error and not metadata: # e.g. malformed, private/deleted video, ...
85 return errdetails,400 # TODO: nicer
86 return render_template('watch.html.j2',
87 video_id=video_id, video_url=video_url,
88 video_error=error, errdetails=errdetails, invidious_url=invidious_url,
89 **prepare_metadata(metadata))
90
91 @app.route('/channel/<channel_id>')
92 def channel(channel_id):
93 if not re.match(r"(UC[A-Za-z0-9_-]{22})", channel_id):
94 return "bad channel id", 400 # todo
95
96 xmlfeed = fetch_xml("channel_id", channel_id)
97 if not xmlfeed:
98 return "not found or something", 404 # XXX
99 title, author, videos = parse_xml(xmlfeed)
100 return render_template('xmlfeed.html.j2', title=author, rows=videos)
101
102 @app.route('/playlist')
103 def playlist():
104 playlist_id = request.args.get('list')
105 if not playlist_id:
106 return "bad list id", 400 # todo
107
108 xmlfeed = fetch_xml("playlist_id", playlist_id)
109 if not xmlfeed:
110 return "not found or something", 404 # XXX
111 title, author, videos = parse_xml(xmlfeed)
112 return render_template('xmlfeed.html.j2', title=f"{title} by {author}", rows=videos)
113
114 @app.route('/subscription_manager')
115 def subscription_manager():
116 token = request.args.get('token', 'guest')
117 with sqlite3.connect(cf['global']['database']) as conn:
118 #with conn.cursor() as c:
119 c = conn.cursor()
120 c.execute("""
121 SELECT subscriptions.channel_id, name,
122 (subscribed_until < datetime('now')) AS obsolete
123 FROM subscriptions
124 left JOIN channels ON channels.id = subscriptions.channel_id
125 left JOIN websub ON channels.id = websub.channel_id
126 WHERE user = ?
127 ORDER BY obsolete=0, name COLLATE NOCASE ASC""", (token,))
128 rows = [{
129 'channel_id': channel_id,
130 'author': author or channel_id,
131 'subscribed_until': subscribed_until
132 } for (channel_id, author, subscribed_until) in c.fetchall()]
133 return render_template('subscription_manager.html.j2', rows=rows)
134
135 @app.route('/feed/subscriptions', methods=['POST'])
136 def feed_post():
137 token = request.args.get('token', 'guest')
138 if token == 'guest': return "guest user is read-only", 403
139 action = next(request.form.keys(), None)
140 if action in ['pin', 'unpin', 'hide']:
141 video_id = request.form.get(action)
142 display = {
143 'pin': 'pinned',
144 'unpin': None,
145 'hide': 'hidden',
146 }[action]
147 with sqlite3.connect(cf['global']['database']) as conn:
148 #with conn.cursor() as c:
149 c = conn.cursor()
150 c.execute("""
151 INSERT OR REPLACE INTO flags (user, video_id, display)
152 VALUES (?, ?, ?)
153 """, (token, video_id, display))
154 else:
155 flash(("error","unsupported action"))
156 return redirect(request.url, code=303)
157
158 @app.route('/subscription_manager', methods=['POST'])
159 def manage_subscriptions():
160 token = request.args.get('token', 'guest')
161 if token == 'guest': return "guest user is read-only", 403
162 if 'subscribe' in request.form:
163 channel_id = request.form.get("subscribe")
164 match = re.match(r"(UC[A-Za-z0-9_-]{22})", channel_id)
165 if match:
166 channel_id = match.group(1)
167 else:
168 match = re.match(r"((?:PL|LL|EC|UU|FL|UL|OL)[A-Za-z0-9_-]{10,})", channel_id)
169 if match: # NOTE: PL-playlists are 32chars, others differ in length.
170 flash(("error","playlists not (yet?) supported."))
171 return redirect(request.url, code=303) # TODO: dedup redirection
172 else:
173 flash(("error","not a valid/subscribable URI"))
174 return redirect(request.url, code=303) # TODO: dedup redirection
175 with sqlite3.connect(cf['global']['database']) as conn:
176 #with conn.cursor() as c:
177 c = conn.cursor()
178 c.execute("""
179 INSERT OR IGNORE INTO subscriptions (user, channel_id)
180 VALUES (?, ?)
181 """, (token, channel_id))
182 # TODO: sql-error-handling, asynchronically calling update-subs.pl
183
184 elif 'unsubscribe' in request.form:
185 with sqlite3.connect(cf['global']['database']) as conn:
186 #with conn.cursor() as c:
187 c = conn.cursor()
188 c.execute("""
189 DELETE FROM subscriptions
190 WHERE user = ? AND channel_id = ?
191 """, (token, channel_id))
192 # TODO: sql-error-handling, report success
193
194 else:
195 flash(("error","unsupported action"))
196
197 return redirect(request.url, code=303)
198
199 @app.route('/r/')
200 def reddit_index():
201 return ""
202 @app.route('/r/<subreddit>')
203 def reddit(subreddit="videos"):
204 count = int(request.args.get('count', 0))
205 before = request.args.get('before')
206 after = request.args.get('after')
207 query = '&'.join([f"{k}={v}" for k,v in [('count',count), ('before',before), ('after',after)] if v])
208 r = requests.get(f"https://old.reddit.com/r/{subreddit}.json?{query}", headers={'User-Agent':'Mozilla/5.0'})
209 if not r.ok or not 'data' in r.json():
210 return r.text+"error retrieving reddit data", 502
211
212 good = [e for e in r.json()['data']['children'] if e['data']['score'] > 1]
213 bad = [e for e in r.json()['data']['children'] if e['data']['score'] <=1]
214 videos = []
215 for entry in (good+bad):
216 e = entry['data']
217 if e['domain'] not in ['youtube.com', 'youtu.be', 'invidio.us']:
218 continue
219 video_id = re.match(r'^https?://(?:www.|m.)?(?:youtube.com/watch\?(?:.*&amp;)?v=|youtu.be/|youtube.com/embed/)([-_0-9A-Za-z]+)', e['url']).group(1)
220 if not video_id: continue
221 videos.append({
222 'video_id': video_id,
223 'title': e['title'],
224 'url': e['permalink'],
225 'n_comments': e['num_comments'],
226 'n_karma': e['score'],
227 })
228 before = r.json()['data']['before']
229 after = r.json()['data']['after']
230 return render_template('reddit.html.j2', subreddit=subreddit, rows=videos, before=before, after=after, count=count)
231
232 def get_cipher():
233 # reload cipher from database every 1 hour
234 if 'cipher' not in g or time.time() - g.get('cipher_updated', 0) > 1 * 60 * 60:
235 with sqlite3.connect(cf['global']['database']) as conn:
236 c = conn.cursor()
237 c.execute("SELECT sts, algorithm FROM cipher")
238 g.cipher = c.fetchone()
239 g.cipher_updated = time.time()
240
241 return g.cipher
242
243 #@app.teardown_appcontext
244 #def teardown_db():
245 # db = g.pop('db', None)
246 #
247 # if db is not None:
248 # db.close()
249
250 # Magic CSRF protection: This modifies outgoing HTML responses and injects a csrf token into all forms.
251 # All post requests are then checked if they contain the valid token.
252 # TODO:
253 # - don't use regex for injecting
254 # - inject a http header into all responses (that could be used by apis)
255 # - allow csrf token to be passed in http header, json, ...
256 # - a decorator on routes to opt out of verification or output munging
257 @app.after_request
258 def add_csrf_protection(response):
259 if response.mimetype == "text/html":
260 token = hmac.new(app.secret_key, request.remote_addr.encode('ascii'), hashlib.sha256).hexdigest() # TODO: will fail behind reverse proxy (remote_addr always localhost)
261 response.set_data( re.sub(
262 rb'''(<[Ff][Oo][Rr][Mm](\s+[a-zA-Z0-9-]+(=(\w*|'[^']*'|"[^"]*"))?)*>)''', # match form tags with any number of attributes and any type of quotes
263 rb'\1<input type="hidden" name="csrf" value="'+token.encode('ascii')+rb'">', # hackily append a hidden input with our csrf protection value
264 response.get_data()))
265 return response
266 @app.before_request
267 def verify_csrf_protection():
268 token = hmac.new(app.secret_key, request.remote_addr.encode('ascii'), hashlib.sha256).hexdigest() # TODO: will fail behind reverse proxy (remote_addr always localhost)
269 if request.method == "POST" and request.form.get('csrf') != token:
270 return "CSRF validation failed!", 400
271 request.form = request.form.copy() # make it mutable
272 request.form.poplist('csrf') # remove our csrf again
273
274 @app.template_filter('format_date')
275 def format_date(s):
276 (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'
277 M = '_ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()
278 return f"{d} {M[m]}"
279
280 if __name__ == '__main__':
281 app.run(debug=True)
Imprint / Impressum