]>
git.gir.st - subscriptionfeed.git/blob - app/frontend.py
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
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'
24 return redirect(url_for('feed'), code
=302)
26 @app.route('/feed/subscriptions')
27 # disabled for guest user: @login_required
29 if current_user
.is_anonymous
:
32 token
= current_user
.token
33 page
= int(request
.args
.get('page', 0))
34 with sqlite3
.connect(cf
['global']['database']) as conn
:
37 SELECT videos.id, channel_id, name, title, published, flags.display
39 JOIN channels ON videos.channel_id = channels.id
40 LEFT JOIN flags ON (videos.id = flags.video_id) AND (flags.user = ?)
42 (SELECT channel_id FROM subscriptions WHERE user = ?)
43 AND flags.display IS NOT 'hidden'
44 ORDER BY (display = 'pinned') DESC, crawled DESC
46 OFFSET 36*?""", (token
, token
, page
))
49 'channel_id': channel_id
,
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
)
59 if not 'v' in request
.args
:
60 return "missing video id", 400
63 'content-type': 'text/plain',
64 'Link': "<data:text/css,body%7Bcolor:%23eee;background:%23333%7D>; rel=stylesheet;"
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
)
71 extra
= {'geolocked':'local=1', 'livestream':'raw=0'}.get(error
,'')
72 invidious_url
= f
"https://invidio.us/watch?v={video_id}&{extra}&raw=1"
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.",
81 show
= request
.args
.get("show")
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}',
88 return redirect(video_url
, code
=307)
90 if error
and not metadata
:
91 return {'error': True, error
: errdetails
}, 400 # TODO: better (test _CpR4o81XQc)
92 return jsonify(metadata
)
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
))
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
106 xmlfeed
= fetch_xml("channel_id", channel_id
)
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
)
112 @app.route('/playlist')
114 playlist_id
= request
.args
.get('list')
116 return "bad list id", 400 # todo
118 xmlfeed
= fetch_xml("playlist_id", playlist_id
)
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
)
124 @app.route('/manage/subscriptions')
125 # disabled for guest user: @login_required
126 def subscription_manager():
127 if current_user
.is_anonymous
:
130 token
= current_user
.token
131 with sqlite3
.connect(cf
['global']['database']) as conn
:
132 #with conn.cursor() as c:
135 SELECT subscriptions.channel_id, name,
136 (subscribed_until < datetime('now')) AS obsolete
138 left JOIN channels ON channels.id = subscriptions.channel_id
139 left JOIN websub ON channels.id = websub.channel_id
141 AND subscriptions.type IN ('channel', 'playlist')
142 ORDER BY obsolete=0, name COLLATE NOCASE ASC""", (token
,))
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
)
150 @app.route('/feed/subscriptions', methods
=['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
)
162 with sqlite3
.connect(cf
['global']['database']) as conn
:
163 #with conn.cursor() as c:
166 INSERT OR REPLACE INTO flags (user, video_id, display)
168 """, (token
, video_id
, display
))
170 flash("unsupported action", "error")
171 return redirect(request
.url
, code
=303)
173 @app.route('/manage/subscriptions', methods
=['POST'])
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
)
181 channel_id
= match
.group(1)
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
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:
194 INSERT OR IGNORE INTO subscriptions (user, channel_id)
196 """, (token
, channel_id
))
197 # TODO: sql-error-handling, asynchronically calling update-subs.pl
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:
205 DELETE FROM subscriptions
206 WHERE user = ? AND channel_id = ?
207 """, (token
, channel_id
))
208 # TODO: sql-error-handling, report success
211 flash("unsupported action", "error")
213 return redirect(request
.url
, code
=303)
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
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]
231 for entry
in (good
+bad
):
233 if e
['domain'] not in ['youtube.com', 'youtu.be', 'invidio.us']:
235 video_id
= re
.match(r
'^https?://(?:www.|m.)?(?:youtube.com/watch\?(?:.*&)?v=|youtu.be/|youtube.com/embed/)([-_0-9A-Za-z]+)', e
['url']).group(1)
236 if not video_id
: continue
238 'video_id': video_id
,
240 'url': e
['permalink'],
241 'n_comments': e
['num_comments'],
242 'n_karma': e
['score'],
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
)
250 return render_template('login.html.j2')
252 @app.route('/login', methods
=['POST'])
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':
265 return redirect(url_for('index'))
267 flash('unsupported action', 'error')
268 return redirect(url_for('login_form'))
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
:
275 c
.execute("SELECT sts, algorithm FROM cipher")
276 g
.cipher
= c
.fetchone()
277 g
.cipher_updated
= time
.time()
281 class User(UserMixin
):
282 def __init__(self
, id, name
, passwd
, 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
)
293 def from_id(self
, id):
294 with sqlite3
.connect(cf
['global']['database']) as conn
:
296 c
.execute("SELECT name,password,token FROM users WHERE id = ?", (id,))
298 name
, passwd
, token
= c
.fetchone()
299 except: return None # todo: ugly
300 return User(id, name
, passwd
, token
)
302 def from_name(self
, name
):
303 with sqlite3
.connect(cf
['global']['database']) as conn
:
305 c
.execute("SELECT id,password,token FROM users WHERE name=?", (name
,))
307 id, passwd
, token
= c
.fetchone()
308 except: return None # todo: ugly
309 return User(id, name
, passwd
, token
)
311 def from_token(self
, token
):
312 with sqlite3
.connect(cf
['global']['database']) as conn
:
314 c
.execute("SELECT id,name,password FROM users WHERE token=?", (token
,))
316 id, name
, passwd
, = c
.fetchone()
317 except: return None # todo: ugly
318 return User(id, name
, passwd
, token
)
322 return User
.from_id(int(id))
324 @login.request_loader
325 def querytoken_auth(request
):
326 if request
.args
.get('token'):
327 return User
.from_token(request
.args
.get('token'))
330 #@app.teardown_appcontext
332 # db = g.pop('db', None)
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.
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
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()))
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
361 @app.template_filter('format_date')
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()
367 if __name__
== '__main__':