]> git.gir.st - subscriptionfeed.git/blob - app/youtube/__init__.py
split app into blueprints - part 1
[subscriptionfeed.git] / app / youtube / __init__.py
1 import re
2 import time
3 import sqlite3
4 import requests
5 #from flask_login import current_user, login_required
6 from flask_login import LoginManager, UserMixin, current_user, login_user, logout_user, login_required
7 from flask import Blueprint, render_template, request, redirect, flash, url_for, jsonify, g
8
9 from ..common.common import *
10
11 frontend = Blueprint('youtube', __name__,
12 template_folder='templates',
13 static_folder='static',
14 static_url_path='/static/yt')
15
16 @frontend.route('/')
17 def index():
18 return redirect(url_for('.feed'), code=302)
19
20 @frontend.route('/feed/subscriptions')
21 # disabled for guest user: @login_required
22 def feed():
23 if current_user.is_anonymous:
24 token = 'guest'
25 else:
26 token = current_user.token
27 page = int(request.args.get('page', 0))
28 with sqlite3.connect(cf['global']['database']) as conn:
29 c = conn.cursor()
30 c.execute("""
31 SELECT videos.id, channel_id, name, title, published, flags.display
32 FROM videos
33 JOIN channels ON videos.channel_id = channels.id
34 LEFT JOIN flags ON (videos.id = flags.video_id) AND (flags.user = ?)
35 WHERE channel_id IN
36 (SELECT channel_id FROM subscriptions WHERE user = ?)
37 AND flags.display IS NOT 'hidden'
38 ORDER BY (display = 'pinned') DESC, crawled DESC
39 LIMIT 36
40 OFFSET 36*?""", (token, token, page))
41 rows = [{
42 'video_id': video_id,
43 'channel_id': channel_id,
44 'author': author,
45 'title': title,
46 'published': published,
47 'pinned': display == 'pinned',
48 } for (video_id, channel_id, author, title, published, display) in c.fetchall()]
49 return render_template('index.html.j2', rows=rows, page=page)
50
51 @frontend.route('/watch')
52 def watch():
53 if not 'v' in request.args:
54 return "missing video id", 400
55
56 plaintextheaders = {
57 'content-type': 'text/plain',
58 'Link': "<data:text/css,body%7Bcolor:%23eee;background:%23333%7D>; rel=stylesheet;"
59 }
60
61 video_id = request.args.get('v')
62 sts, algo = get_cipher()
63 video_url, metadata, error, errdetails = get_video_info(video_id, sts, algo)
64
65 extra = {'geolocked':'local=1', 'livestream':'raw=0'}.get(error,'')
66 invidious_url = f"https://invidio.us/watch?v={video_id}&{extra}&raw=1"
67 errdetails = {
68 'malformed': "Video ID is invalid.",
69 'geolocked': "This video is geolocked.",
70 'livestream': "Livestreams not yet supported.",
71 'exhausted': errdetails or "Couldn't extract video URLs.",
72 'player': errdetails,
73 }.get(error)
74
75 show = request.args.get("show")
76 if show == "raw":
77 if error:
78 msg = errdetails if error=='player' else f"{error.upper()}: {errdetails}"
79 return f"{msg}\n\nRedirecting to Invidious.", 502, {
80 'Refresh': f'2; URL={invidious_url}',
81 **plaintextheaders}
82 return redirect(video_url, code=307)
83 elif show == "json":
84 if error and not metadata:
85 return {'error': True, error: errdetails}, 400 # TODO: better (test _CpR4o81XQc)
86 return jsonify(metadata)
87 else:
88 if error and not metadata: # e.g. malformed, private/deleted video, ...
89 return errdetails,400 # TODO: nicer
90 return render_template('watch.html.j2',
91 video_id=video_id, video_url=video_url,
92 video_error=error, errdetails=errdetails, invidious_url=invidious_url,
93 **prepare_metadata(metadata))
94
95 @frontend.route('/channel/<channel_id>')
96 def channel(channel_id):
97 if not re.match(r"(UC[A-Za-z0-9_-]{22})", channel_id):
98 return "bad channel id", 400 # todo
99
100 xmlfeed = fetch_xml("channel_id", channel_id)
101 if not xmlfeed:
102 return "not found or something", 404 # XXX
103 title, author, videos = parse_xml(xmlfeed)
104 return render_template('xmlfeed.html.j2', title=author, rows=videos)
105
106 @frontend.route('/playlist')
107 def playlist():
108 playlist_id = request.args.get('list')
109 if not playlist_id:
110 return "bad list id", 400 # todo
111
112 xmlfeed = fetch_xml("playlist_id", playlist_id)
113 if not xmlfeed:
114 return "not found or something", 404 # XXX
115 title, author, videos = parse_xml(xmlfeed)
116 return render_template('xmlfeed.html.j2', title=f"{title} by {author}", rows=videos)
117
118 @frontend.route('/manage/subscriptions')
119 # disabled for guest user: @login_required
120 def subscription_manager():
121 if current_user.is_anonymous:
122 token = 'guest'
123 else:
124 token = current_user.token
125 with sqlite3.connect(cf['global']['database']) as conn:
126 #with conn.cursor() as c:
127 c = conn.cursor()
128 c.execute("""
129 SELECT subscriptions.channel_id, name,
130 (subscribed_until < datetime('now')) AS obsolete
131 FROM subscriptions
132 left JOIN channels ON channels.id = subscriptions.channel_id
133 left JOIN websub ON channels.id = websub.channel_id
134 WHERE user = ?
135 AND subscriptions.type IN ('channel', 'playlist')
136 ORDER BY obsolete=0, name COLLATE NOCASE ASC""", (token,))
137 rows = [{
138 'channel_id': channel_id,
139 'author': author or channel_id,
140 'subscribed_until': subscribed_until
141 } for (channel_id, author, subscribed_until) in c.fetchall()]
142 return render_template('subscription_manager.html.j2', rows=rows)
143
144 @frontend.route('/feed/subscriptions', methods=['POST'])
145 @login_required
146 def feed_post():
147 token = current_user.token
148 action = next(request.form.keys(), None)
149 if action in ['pin', 'unpin', 'hide']:
150 video_id = request.form.get(action)
151 display = {
152 'pin': 'pinned',
153 'unpin': None,
154 'hide': 'hidden',
155 }[action]
156 with sqlite3.connect(cf['global']['database']) as conn:
157 #with conn.cursor() as c:
158 c = conn.cursor()
159 c.execute("""
160 INSERT OR REPLACE INTO flags (user, video_id, display)
161 VALUES (?, ?, ?)
162 """, (token, video_id, display))
163 else:
164 flash("unsupported action", "error")
165 return redirect(request.url, code=303)
166
167 @frontend.route('/manage/subscriptions', methods=['POST'])
168 @login_required
169 def manage_subscriptions():
170 token = current_user.token
171 if 'subscribe' in request.form:
172 channel_id = request.form.get("subscribe")
173 match = re.search(r"(UC[A-Za-z0-9_-]{22})", channel_id)
174 if match:
175 channel_id = match.group(1)
176 else:
177 match = re.search(r"((?:PL|LL|EC|UU|FL|UL|OL)[A-Za-z0-9_-]{10,})", channel_id)
178 if match: # NOTE: PL-playlists are 32chars, others differ in length.
179 flash("playlists not (yet?) supported.", "error")
180 return redirect(request.url, code=303) # TODO: dedup redirection
181 else:
182 flash("not a valid/subscribable URI", "error")
183 return redirect(request.url, code=303) # TODO: dedup redirection
184 with sqlite3.connect(cf['global']['database']) as conn:
185 #with conn.cursor() as c:
186 c = conn.cursor()
187 c.execute("""
188 INSERT OR IGNORE INTO subscriptions (user, channel_id)
189 VALUES (?, ?)
190 """, (token, channel_id))
191 # TODO: sql-error-handling, asynchronically calling update-subs.pl
192
193 elif 'unsubscribe' in request.form:
194 channel_id = request.form.get("unsubscribe")
195 with sqlite3.connect(cf['global']['database']) as conn:
196 #with conn.cursor() as c:
197 c = conn.cursor()
198 c.execute("""
199 DELETE FROM subscriptions
200 WHERE user = ? AND channel_id = ?
201 """, (token, channel_id))
202 # TODO: sql-error-handling, report success
203
204 else:
205 flash("unsupported action", "error")
206
207 return redirect(request.url, code=303)
208
209 @frontend.route('/r/')
210 def reddit_index():
211 return ""
212 @frontend.route('/r/<subreddit>')
213 def reddit(subreddit="videos"):
214 count = int(request.args.get('count', 0))
215 before = request.args.get('before')
216 after = request.args.get('after')
217 query = '&'.join([f"{k}={v}" for k,v in [('count',count), ('before',before), ('after',after)] if v])
218 r = requests.get(f"https://old.reddit.com/r/{subreddit}.json?{query}", headers={'User-Agent':'Mozilla/5.0'})
219 if not r.ok or not 'data' in r.json():
220 return r.text+"error retrieving reddit data", 502
221
222 good = [e for e in r.json()['data']['children'] if e['data']['score'] > 1]
223 bad = [e for e in r.json()['data']['children'] if e['data']['score'] <=1]
224 videos = []
225 for entry in (good+bad):
226 e = entry['data']
227 if e['domain'] not in ['youtube.com', 'youtu.be', 'invidio.us']:
228 continue
229 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)
230 if not video_id: continue
231 videos.append({
232 'video_id': video_id,
233 'title': e['title'],
234 'url': e['permalink'],
235 'n_comments': e['num_comments'],
236 'n_karma': e['score'],
237 })
238 before = r.json()['data']['before']
239 after = r.json()['data']['after']
240 return render_template('reddit.html.j2', subreddit=subreddit, rows=videos, before=before, after=after, count=count)
241
242 def get_cipher():
243 # reload cipher from database every 1 hour
244 if 'cipher' not in g or time.time() - g.get('cipher_updated', 0) > 1 * 60 * 60:
245 with sqlite3.connect(cf['global']['database']) as conn:
246 c = conn.cursor()
247 c.execute("SELECT sts, algorithm FROM cipher")
248 g.cipher = c.fetchone()
249 g.cipher_updated = time.time()
250
251 return g.cipher
252
253 #@frontend.teardown_appcontext
254 #def teardown_db():
255 # db = g.pop('db', None)
256 #
257 # if db is not None:
258 # db.close()
259
260
261 @frontend.app_template_filter('format_date')
262 def format_date(s):
263 (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'
264 M = '_ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()
265 return f"{d} {M[m]}"
Imprint / Impressum