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