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