]> git.gir.st - subscriptionfeed.git/blob - app/youtube/__init__.py
Revert "use all muxed stream sources" for breaking edge-cases
[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 if 'welcome_message' in cf['frontend']:
26 flash(cf['frontend']['welcome_message'], "info")
27 else:
28 token = current_user.token
29 page = int(request.args.get('page', 0))
30 with sqlite3.connect(cf['global']['database']) as conn:
31 c = conn.cursor()
32 c.execute("""
33 SELECT videos.id, channel_id, name, title, published, flags.display
34 FROM videos
35 JOIN channels ON videos.channel_id = channels.id
36 LEFT JOIN flags ON (videos.id = flags.video_id) AND (flags.user = ?)
37 WHERE (channel_id IN (SELECT channel_id FROM subscriptions WHERE user=?)
38 OR flags.display = 'pinned')
39 AND flags.display IS NOT 'hidden'
40 ORDER BY (display = 'pinned') DESC, crawled DESC
41 LIMIT 36
42 OFFSET 36*?""", (token, token, page))
43 rows = [{
44 'video_id': video_id,
45 'channel_id': channel_id,
46 'author': author,
47 'title': title,
48 'published': published,
49 'pinned': display == 'pinned',
50 } for (video_id, channel_id, author, title, published, display) in c.fetchall()]
51 return render_template('index.html.j2', rows=rows, page=page)
52
53 @frontend.route('/watch')
54 def watch():
55 if current_user.is_anonymous:
56 token = 'guest'
57 else:
58 token = current_user.token
59
60 if not 'v' in request.args:
61 return "missing video id", 400
62
63 plaintextheaders = {
64 'content-type': 'text/plain',
65 'Link': "<data:text/css,body%7Bcolor:%23eee;background:%23333%7D>; rel=stylesheet;"
66 }
67
68 video_id = request.args.get('v')
69 sts, algo = get_cipher()
70 video_url, metadata, error, errdetails = get_video_info(video_id, sts, algo)
71
72 extra = {'geolocked':'local=1', 'livestream':'raw=0'}.get(error,'')
73 invidious_url = f"https://invidio.us/watch?v={video_id}&{extra}&raw=1"
74 errdetails = {
75 'malformed': "Video ID is invalid.",
76 'geolocked': "This video is geolocked.",
77 'livestream': "Livestreams not yet supported.",
78 'exhausted': errdetails or "Couldn't extract video URLs.",
79 'player': errdetails,
80 }.get(error)
81
82 show = request.args.get("show")
83 if show == "raw":
84 if error:
85 msg = errdetails if error=='player' else f"{error.upper()}: {errdetails}"
86 return f"{msg}\n\nRedirecting to Invidious.", 502, {
87 'Refresh': f'2; URL={invidious_url}',
88 **plaintextheaders}
89 return redirect(video_url, code=307)
90 elif show == "json":
91 if error and not metadata:
92 return {'error': True, error: errdetails}, 400 # TODO: better (test _CpR4o81XQc)
93 return jsonify(metadata)
94 else:
95 if error and not metadata: # e.g. malformed, private/deleted video, ...
96 return errdetails,400 # TODO: nicer
97 meta = prepare_metadata(metadata)
98 with sqlite3.connect(cf['global']['database']) as conn:
99 c = conn.cursor()
100 c.execute("""
101 SELECT COUNT((
102 SELECT 1 FROM subscriptions WHERE channel_id = ? AND user = ?
103 )), COUNT((
104 SELECT 1 FROM flags WHERE video_id = ? AND display = 'pinned' AND user = ?
105 ))""", (meta['channel_id'], token, video_id, token))
106 (is_subscribed, is_pinned) = c.fetchone()
107 return render_template('watch.html.j2',
108 video_id=video_id, video_url=video_url,
109 video_error=error, errdetails=errdetails, invidious_url=invidious_url,
110 is_pinned=is_pinned, is_subscribed=is_subscribed,
111 **meta)
112
113 @frontend.route('/embed/<video_id>')
114 def embed(video_id):
115 return redirect(url_for('youtube.watch', v=video_id))
116
117 @frontend.route('/channel/<channel_id>')
118 def channel(channel_id):
119 token = getattr(current_user, 'token', 'guest')
120
121 if not re.match(r"(UC[A-Za-z0-9_-]{22})", channel_id):
122 return "bad channel id", 400 # todo
123
124 xmlfeed = fetch_xml("channel_id", channel_id)
125 if not xmlfeed:
126 return "not found or something", 404 # XXX
127 title, author, videos = parse_xml(xmlfeed)
128
129 with sqlite3.connect(cf['global']['database']) as conn:
130 c = conn.cursor()
131 c.execute("""
132 SELECT COUNT(*)
133 FROM subscriptions
134 WHERE channel_id = ? AND user = ?
135 """, (channel_id, token))
136 (is_subscribed,) = c.fetchone()
137
138 return render_template('xmlfeed.html.j2', title=author, rows=videos,
139 is_subscribed=is_subscribed, channel_id=channel_id)
140
141 @frontend.route('/playlist')
142 def playlist():
143 playlist_id = request.args.get('list')
144 if not playlist_id:
145 return "bad list id", 400 # todo
146
147 xmlfeed = fetch_xml("playlist_id", playlist_id)
148 if not xmlfeed:
149 return "not found or something", 404 # XXX
150 title, author, videos = parse_xml(xmlfeed)
151 return render_template('xmlfeed.html.j2', title=f"{title} by {author}", rows=videos)
152
153 @frontend.route('/api/timedtext')
154 def timedtext():
155 r = requests.get("https://www.youtube.com/api/timedtext", request.args.to_dict())
156 # Note: in srv1 format, xmlentities are double-encoded m( a smart quote is
157 # even worse: it's '&amp;39;<smartquote>' wtf!? (at least vvt seems ok)
158 if not r.ok:
159 return "error: {r.text}", 400 # TODO: better
160 retval = r.text
161 if request.args.get('fmt') == 'vtt' and request.args.get('kind') == 'asr':
162 # autocaptions are extremely confusing, and stuck in the lower-left corner. fix it up a bit
163 retval = re.sub(r"<.+?>", "", retval) # remove inline html-like markup that times each word/adds styles
164 retval = retval.replace("align:start position:0%", "") # let browser position the text itself
165 # each subtitle-line is repeated twice (first on the lower line, then
166 # on the next "frame" on the upper line). we want to remove the
167 # repetition, as that's confusing without word and line animations:
168 lines = retval.split('\n')
169 retval = '\n'.join([line for line, prev in zip(lines, ['']+lines) if not " --> " in prev])
170 return retval, {'Content-Type': r.headers.get("Content-Type")}
171
172 @frontend.route('/manage/subscriptions')
173 # disabled for guest user: @login_required
174 def subscription_manager():
175 if current_user.is_anonymous:
176 token = 'guest'
177 else:
178 token = current_user.token
179 with sqlite3.connect(cf['global']['database']) as conn:
180 #with conn.cursor() as c:
181 c = conn.cursor()
182 c.execute("""
183 SELECT subscriptions.channel_id, name,
184 (subscribed_until < datetime('now')) AS obsolete
185 FROM subscriptions
186 left JOIN channels ON channels.id = subscriptions.channel_id
187 left JOIN websub ON channels.id = websub.channel_id
188 WHERE user = ?
189 AND subscriptions.type IN ('channel', 'playlist')
190 ORDER BY obsolete=0, name COLLATE NOCASE ASC""", (token,))
191 rows = [{
192 'channel_id': channel_id,
193 'author': author or channel_id,
194 'subscribed_until': subscribed_until
195 } for (channel_id, author, subscribed_until) in c.fetchall()]
196 return render_template('subscription_manager.html.j2', rows=rows)
197
198 @frontend.route('/feed/subscriptions', methods=['POST'])
199 @login_required
200 def feed_post():
201 token = current_user.token
202 action = next(request.form.keys(), None)
203 if action in ['pin', 'unpin', 'hide']:
204 video_id = request.form.get(action)
205 display = {
206 'pin': 'pinned',
207 'unpin': None,
208 'hide': 'hidden',
209 }[action]
210 with sqlite3.connect(cf['global']['database']) as conn:
211 c = conn.cursor()
212 store_video_metadata(video_id) # only needed for pinning
213 c.execute("""
214 INSERT OR REPLACE INTO flags (user, video_id, display)
215 VALUES (?, ?, ?)
216 """, (token, video_id, display))
217 else:
218 flash("unsupported action", "error")
219 return redirect(request.url, code=303)
220
221 @frontend.route('/manage/subscriptions', methods=['POST'])
222 @login_required
223 def manage_subscriptions():
224 token = current_user.token
225 if 'subscribe' in request.form:
226 channel_id = request.form.get("subscribe")
227 match = re.search(r"(UC[A-Za-z0-9_-]{22})", channel_id)
228 if match:
229 channel_id = match.group(1)
230 else:
231 match = re.search(r"((?:PL|LL|EC|UU|FL|UL|OL)[A-Za-z0-9_-]{10,})", channel_id)
232 if match: # NOTE: PL-playlists are 32chars, others differ in length.
233 flash("playlists not (yet?) supported.", "error")
234 return redirect(request.url, code=303) # TODO: dedup redirection
235 else:
236 flash("not a valid/subscribable URI", "error")
237 return redirect(request.url, code=303) # TODO: dedup redirection
238 with sqlite3.connect(cf['global']['database']) as conn:
239 #with conn.cursor() as c:
240 c = conn.cursor()
241 c.execute("""
242 INSERT OR IGNORE INTO subscriptions (user, channel_id)
243 VALUES (?, ?)
244 """, (token, channel_id))
245 # TODO: sql-error-handling, asynchronically calling update-subs.pl
246
247 elif 'unsubscribe' in request.form:
248 channel_id = request.form.get("unsubscribe")
249 with sqlite3.connect(cf['global']['database']) as conn:
250 #with conn.cursor() as c:
251 c = conn.cursor()
252 c.execute("""
253 DELETE FROM subscriptions
254 WHERE user = ? AND channel_id = ?
255 """, (token, channel_id))
256 # TODO: sql-error-handling, report success
257
258 else:
259 flash("unsupported action", "error")
260
261 return redirect(request.url, code=303)
262
263 def get_cipher():
264 # reload cipher from database every 1 hour
265 if 'cipher' not in g or time.time() - g.get('cipher_updated', 0) > 1 * 60 * 60:
266 with sqlite3.connect(cf['global']['database']) as conn:
267 c = conn.cursor()
268 c.execute("SELECT sts, algorithm FROM cipher")
269 g.cipher = c.fetchone()
270 g.cipher_updated = time.time()
271
272 return g.cipher
273
274 #@frontend.teardown_appcontext
275 #def teardown_db():
276 # db = g.pop('db', None)
277 #
278 # if db is not None:
279 # db.close()
280
281
282 @frontend.app_template_filter('format_date')
283 def format_date(s):
284 (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'
285 M = '_ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()
286 return f"{d} {M[m]}"
Imprint / Impressum