]>
git.gir.st - subscriptionfeed.git/blob - app/youtube/__init__.py
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
9 from ..common
.common
import *
11 frontend
= Blueprint('youtube', __name__
,
12 template_folder
='templates',
13 static_folder
='static',
14 static_url_path
='/static/yt')
18 return redirect(url_for('.feed'), code
=302)
20 @frontend.route('/feed/subscriptions')
21 # disabled for guest user: @login_required
23 if current_user
.is_anonymous
:
25 if 'welcome_message' in cf
['frontend']:
26 flash(cf
['frontend']['welcome_message'], "info")
28 token
= current_user
.token
29 page
= int(request
.args
.get('page', 0))
30 with sqlite3
.connect(cf
['global']['database']) as conn
:
33 SELECT videos.id, channel_id, name, title, published, flags.display
35 JOIN channels ON videos.channel_id = channels.id
36 LEFT JOIN flags ON (videos.id = flags.video_id) AND (flags.user = ?)
38 (SELECT channel_id FROM subscriptions WHERE user = ?)
39 AND flags.display IS NOT 'hidden'
40 ORDER BY (display = 'pinned') DESC, crawled DESC
42 OFFSET 36*?""", (token
, token
, page
))
45 'channel_id': channel_id
,
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
)
53 @frontend.route('/watch')
55 if not 'v' in request
.args
:
56 return "missing video id", 400
59 'content-type': 'text/plain',
60 'Link': "<data:text/css,body%7Bcolor:%23eee;background:%23333%7D>; rel=stylesheet;"
63 video_id
= request
.args
.get('v')
64 sts
, algo
= get_cipher()
65 muxed
, metadata
, error
, errdetails
= get_video_info(video_id
, sts
, algo
)
67 extra
= {'geolocked':'local=1', 'livestream':'raw=0'}.get(error
,'')
68 invidious_url
= f
"https://invidio.us/watch?v={video_id}&{extra}&raw=1"
70 'malformed': "Video ID is invalid.",
71 'geolocked': "This video is geolocked.",
72 'livestream': "Livestreams not yet supported.",
73 'exhausted': errdetails
or "Couldn't extract video URLs.",
77 show
= request
.args
.get("show")
80 msg
= errdetails
if error
=='player' else f
"{error.upper()}: {errdetails}"
81 return f
"{msg}\n\nRedirecting to Invidious.", 502, {
82 'Refresh': f
'2; URL={invidious_url}',
84 return redirect(muxed
[0], code
=307)
86 if error
and not metadata
:
87 return {'error': True, error
: errdetails
}, 400 # TODO: better (test _CpR4o81XQc)
88 return jsonify(metadata
)
90 if error
and not metadata
: # e.g. malformed, private/deleted video, ...
91 return errdetails
,400 # TODO: nicer
92 return render_template('watch.html.j2',
93 video_id
=video_id
, video_url
=muxed
,
94 video_error
=error
, errdetails
=errdetails
, invidious_url
=invidious_url
,
95 **prepare_metadata(metadata
))
97 @frontend.route('/channel/<channel_id>')
98 def channel(channel_id
):
99 if not re
.match(r
"(UC[A-Za-z0-9_-]{22})", channel_id
):
100 return "bad channel id", 400 # todo
102 xmlfeed
= fetch_xml("channel_id", channel_id
)
104 return "not found or something", 404 # XXX
105 title
, author
, videos
= parse_xml(xmlfeed
)
106 return render_template('xmlfeed.html.j2', title
=author
, rows
=videos
)
108 @frontend.route('/playlist')
110 playlist_id
= request
.args
.get('list')
112 return "bad list id", 400 # todo
114 xmlfeed
= fetch_xml("playlist_id", playlist_id
)
116 return "not found or something", 404 # XXX
117 title
, author
, videos
= parse_xml(xmlfeed
)
118 return render_template('xmlfeed.html.j2', title
=f
"{title} by {author}", rows
=videos
)
120 @frontend.route('/api/timedtext')
122 r
= requests
.get("https://www.youtube.com/api/timedtext", request
.args
.to_dict())
123 # Note: in srv1 format, xmlentities are double-encoded m( a smart quote is
124 # even worse: it's '&39;<smartquote>' wtf!? (at least vvt seems ok)
126 return "error: {r.text}", 400 # TODO: better
128 if request
.args
.get('fmt') == 'vtt' and request
.args
.get('kind') == 'asr':
129 # autocaptions are extremely confusing, and stuck in the lower-left corner. fix it up a bit
130 retval
= re
.sub(r
"<.+?>", "", retval
) # remove inline html-like markup that times each word/adds styles
131 retval
= retval
.replace("align:start position:0%", "") # let browser position the text itself
132 # each subtitle-line is repeated twice (first on the lower line, then
133 # on the next "frame" on the upper line). we want to remove the
134 # repetition, as that's confusing without word and line animations:
135 lines
= retval
.split('\n')
136 retval
= '\n'.join([line
for line
, prev
in zip(lines
, ['']+lines
) if not " --> " in prev
])
137 return retval
, {'Content-Type': r
.headers
.get("Content-Type")}
139 @frontend.route('/manage/subscriptions')
140 # disabled for guest user: @login_required
141 def subscription_manager():
142 if current_user
.is_anonymous
:
145 token
= current_user
.token
146 with sqlite3
.connect(cf
['global']['database']) as conn
:
147 #with conn.cursor() as c:
150 SELECT subscriptions.channel_id, name,
151 (subscribed_until < datetime('now')) AS obsolete
153 left JOIN channels ON channels.id = subscriptions.channel_id
154 left JOIN websub ON channels.id = websub.channel_id
156 AND subscriptions.type IN ('channel', 'playlist')
157 ORDER BY obsolete=0, name COLLATE NOCASE ASC""", (token
,))
159 'channel_id': channel_id
,
160 'author': author
or channel_id
,
161 'subscribed_until': subscribed_until
162 } for (channel_id
, author
, subscribed_until
) in c
.fetchall()]
163 return render_template('subscription_manager.html.j2', rows
=rows
)
165 @frontend.route('/feed/subscriptions', methods
=['POST'])
168 token
= current_user
.token
169 action
= next(request
.form
.keys(), None)
170 if action
in ['pin', 'unpin', 'hide']:
171 video_id
= request
.form
.get(action
)
177 with sqlite3
.connect(cf
['global']['database']) as conn
:
178 #with conn.cursor() as c:
181 INSERT OR REPLACE INTO flags (user, video_id, display)
183 """, (token
, video_id
, display
))
185 flash("unsupported action", "error")
186 return redirect(request
.url
, code
=303)
188 @frontend.route('/manage/subscriptions', methods
=['POST'])
190 def manage_subscriptions():
191 token
= current_user
.token
192 if 'subscribe' in request
.form
:
193 channel_id
= request
.form
.get("subscribe")
194 match
= re
.search(r
"(UC[A-Za-z0-9_-]{22})", channel_id
)
196 channel_id
= match
.group(1)
198 match
= re
.search(r
"((?:PL|LL|EC|UU|FL|UL|OL)[A-Za-z0-9_-]{10,})", channel_id
)
199 if match
: # NOTE: PL-playlists are 32chars, others differ in length.
200 flash("playlists not (yet?) supported.", "error")
201 return redirect(request
.url
, code
=303) # TODO: dedup redirection
203 flash("not a valid/subscribable URI", "error")
204 return redirect(request
.url
, code
=303) # TODO: dedup redirection
205 with sqlite3
.connect(cf
['global']['database']) as conn
:
206 #with conn.cursor() as c:
209 INSERT OR IGNORE INTO subscriptions (user, channel_id)
211 """, (token
, channel_id
))
212 # TODO: sql-error-handling, asynchronically calling update-subs.pl
214 elif 'unsubscribe' in request
.form
:
215 channel_id
= request
.form
.get("unsubscribe")
216 with sqlite3
.connect(cf
['global']['database']) as conn
:
217 #with conn.cursor() as c:
220 DELETE FROM subscriptions
221 WHERE user = ? AND channel_id = ?
222 """, (token
, channel_id
))
223 # TODO: sql-error-handling, report success
226 flash("unsupported action", "error")
228 return redirect(request
.url
, code
=303)
231 # reload cipher from database every 1 hour
232 if 'cipher' not in g
or time
.time() - g
.get('cipher_updated', 0) > 1 * 60 * 60:
233 with sqlite3
.connect(cf
['global']['database']) as conn
:
235 c
.execute("SELECT sts, algorithm FROM cipher")
236 g
.cipher
= c
.fetchone()
237 g
.cipher_updated
= time
.time()
241 #@frontend.teardown_appcontext
243 # db = g.pop('db', None)
249 @frontend.app_template_filter('format_date')
251 (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'
252 M
= '_ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()