5 from urllib
.parse
import urlparse
6 #from flask_login import current_user, login_required
7 from flask_login
import LoginManager
, UserMixin
, current_user
, login_user
, logout_user
, login_required
8 from flask
import Blueprint
, render_template
, request
, redirect
, flash
, url_for
, jsonify
, g
, current_app
9 from werkzeug
.exceptions
import NotFound
, BadGateway
11 from ..common
.common
import *
12 from ..common
.anticaptcha
import submit_captcha
15 frontend
= Blueprint('youtube', __name__
,
16 template_folder
='templates',
17 static_folder
='static',
18 static_url_path
='/static/yt')
22 return redirect(url_for('.feed'), code
=302)
24 @frontend.route('/feed/subscriptions')
25 # disabled for guest user: @login_required
27 if current_user
.is_anonymous
:
29 if 'welcome_message' in cf
['frontend']:
30 flash(cf
['frontend']['welcome_message'], "welcome")
32 token
= current_user
.token
33 page
= request
.args
.get('page', 0, type=int)
34 with sqlite3
.connect(cf
['global']['database']) as conn
:
37 settings
= {} # fallback for guest user
38 if current_user
.is_authenticated
:
43 """, (current_user
.id,))
45 setting
: json
.loads(value
)
46 for setting
, value
in c
.fetchall()
50 SELECT videos.id, channel_id, name, title, length, livestream, premiere, shorts, published, playlist_videos.playlist_id, display
52 JOIN channels ON videos.channel_id = channels.id
53 LEFT JOIN playlist_videos ON (videos.id = playlist_videos.video_id)
54 LEFT JOIN flags ON (videos.id = flags.video_id) AND (flags.user = ?)
55 WHERE (channel_id IN (SELECT channel_id FROM subscriptions WHERE user=? AND type = 'channel')
56 OR playlist_videos.playlist_id IN (SELECT channel_id FROM subscriptions WHERE user=? AND type = 'playlist')
57 OR flags.display = 'pinned')
58 AND flags.display IS NOT 'hidden'
59 AND (flags.display = 'pinned' OR not ? or not shorts)
60 ORDER BY (display = 'pinned') DESC, crawled DESC
62 OFFSET 36*?""", (token
, token
, token
, settings
.get('noshorts', False), page
))
65 'channel_id': channel_id
,
69 'livestream': livestream
,
70 'premiere': premiere
and (# only if it hasn't yet premiered:
71 datetime
.strptime(published
+'+0000', "%Y-%m-%d %H:%M:%S%z")>datetime
.now(tz
=timezone
.utc
)
74 'published': published
,
76 'pinned': display
== 'pinned',
77 } for (video_id
, channel_id
, author
, title
, length
, livestream
, premiere
, shorts
, published
, playlist
, display
) in c
.fetchall()]
78 return render_template('index.html.j2', rows
=rows
, page
=page
)
80 @frontend.route('/watch')
82 if current_user
.is_anonymous
:
85 token
= current_user
.token
87 if not 'v' in request
.args
:
88 return "missing video id", 400
89 if len(request
.args
.get('v')) != 11:
90 return "malformed video id", 400
93 'content-type': 'text/plain',
94 'Link': "<data:text/css,body%7Bcolor:%23eee;background:%23333%7D>; rel=stylesheet;"
97 video_id
= request
.args
.get('v')
98 show
= request
.args
.get("show")
99 itag
= request
.args
.get("itag")
100 video_url
, stream_map
, metadata
, error
, errdetails
= get_video_info(video_id
, metaOnly
=(show
== 'meta'))
102 if itag
: # if itag is specified and available, force its use even if not highest resolution
103 video_url
= next((e
['url'] for e
in stream_map
['muxed'] if e
['itag'] == int(itag
)), video_url
)
105 proxy_on
= getattr(g
, 'proxy_on', None)
107 False: "Log in to use proxy.", # proxy for logged-in users only
108 None: "", # proxy disabled globally
109 True: "", # proxy is available to this user
111 extra
= {'geolocked':'local=1', 'livestream':'raw=0'}.get(error
,'')
112 invidious_url
= f
"https://invidious.snopyta.org/watch?v={video_id}&{extra}"
114 'banned': "Instance is being rate limited.",
115 'malformed': "Video ID is invalid.",
116 'geolocked': f
"This video is geolocked. {proxy_msg}",
117 'livestream': f
"Livestreams disabled. {proxy_msg}",
118 'agegated': "Unable to bypass age-restriction.",
119 'scrambled': "VEVO style cyphering not supported.",
120 'no-url': "No muxed stream available.",
121 'exhausted': errdetails
or "Couldn't extract video URLs.",
122 'player': errdetails
,
125 # if the video is geolocked, and the proxy is enabled, we can still play
126 # it, if the video is available in the instance server's region:
127 if error
== 'geolocked' and video_url
and proxy_on
:
128 videoplayback
= url_for('proxy.videoplayback')
129 query
= urlparse(video_url
).query
130 video_url
= f
"{videoplayback}?{query}"
131 for t
in ('adaptive_video', 'adaptive_audio', 'muxed'):
132 for s
in stream_map
[t
]:
133 query
= urlparse(s
['url']).query
134 s
['url'] = f
"{videoplayback}?{query}"
137 # if the proxy is enabled, we can also play livestreams:
138 if error
== 'livestream' and proxy_on
:
139 # Note: hlsManifestUrl's hostname will be replaced client-side
140 video_url
= stream_map
['hlsManifestUrl']
143 # if the instance is blocked, try submitting a job to the anti captcha service:
144 if error
== 'banned' and cf
['captcha']['api_key']:
145 r2
= requests
.get(f
'https://www.youtube.com/watch?v={video_id}&hl=en&gl=US')
146 status
= submit_captcha(r2
)
148 raise Exception("we are banned, but captcha wasn't triggered!")
150 message
= "right now" if status
is True else f
"{int(status)} seconds ago"
151 raise BadGateway(f
"""
152 {errdetails} An attempt at getting unblocked has been made {message}.
153 Please try again in 30 seconds.
158 msg
= errdetails
if error
=='player' else f
"{error.upper()}: {errdetails}"
159 return f
"{msg}\n\nRedirecting to Invidious.", 502, {
160 'Refresh': f
'2; URL={invidious_url}&raw=1',
162 return redirect(video_url
, code
=307)
164 if error
and not metadata
:
165 return {'error': True, error
: errdetails
}, 400 # TODO: better (test _CpR4o81XQc)
166 return jsonify(metadata
)
167 elif show
== "audio":
168 # sorting: we want to prioritize mp4a over opus, and sort by highest quality first
169 # todo: geolocking; prefer open format?
170 if error
and not stream_map
:
171 msg
= errdetails
if error
=='player' else f
"{error.upper()}: {errdetails}"
172 return msg
, 400, plaintextheaders
# TODO: nicer
173 stream
= next(iter(sorted(
174 stream_map
['adaptive_audio'],
175 key
=lambda e
: ('opus' not in e
['mimeType'], e
['bitrate']),
178 return redirect(stream
)
180 # this is the subset of (useful) keys that are not present in the
181 # Android API response. the special key '_' contains ready-to-use
182 # parsed versions of that data.
183 if error
and not metadata
:
184 return {'error': True, error
: errdetails
}, 400 # TODO: better (test _CpR4o81XQc)
185 parsed
= microformat_parser(metadata
)
186 return {'microformat': metadata
.get('microformat'),'cards':metadata
.get('cards'), '_':parsed
}
188 if error
and not metadata
: # e.g. malformed, private/deleted video, ...
189 return render_template('video-error.html.j2', video_id
=video_id
,
190 video_error
=error
, errdetails
=errdetails
, invidious_url
=invidious_url
)
191 meta
= prepare_metadata(metadata
)
192 with sqlite3
.connect(cf
['global']['database']) as conn
:
196 SELECT 1 FROM subscriptions WHERE channel_id = ? AND user = ?
198 SELECT 1 FROM flags WHERE video_id = ? AND display = 'pinned' AND user = ?
199 ))""", (meta
['channel_id'], token
, video_id
, token
))
200 (is_subscribed
, is_pinned
) = c
.fetchone()
201 return render_template('watch.html.j2',
202 video_id
=video_id
, video_url
=video_url
, stream_map
=stream_map
,
203 video_error
=error
, errdetails
=errdetails
, invidious_url
=invidious_url
,
204 is_pinned
=is_pinned
, is_subscribed
=is_subscribed
,
207 @frontend.route('/embed/videoseries')
208 def embed_videoseries():
209 return redirect(url_for('.playlist', list=request
.args
.get('list')))
210 @frontend.route('/embed/<video_id>', strict_slashes
=False)
212 if video_id
== "videoseries":
213 return redirect(url_for('.playlist', list=request
.args
.get('list')))
215 return redirect(url_for('.watch', v
=video_id
, t
=request
.args
.get('start')))
217 @frontend.route('/live/<video_id>', strict_slashes
=False)
218 @frontend.route('/shorts/<video_id>', strict_slashes
=False)
219 def shorts_or_live(video_id
):
220 return redirect(url_for('.watch', v
=video_id
, t
=request
.args
.get('start')))
222 @frontend.route('/<something>', strict_slashes
=False)
223 def plain_user_or_video(something
):
224 # yt.com interprets this as a username, but we also want to catch youtu.be
225 # short-urls. so we check if it's a channel by querying the RSS feed (this
226 # shoudn't be rate-limited); if that fails, check if it looks like a video
227 # id; or finally give up.
228 if '.' not in something
and channel_exists(something
):
229 # periods are not valid in usernames, vanity urls or ucids, but common
230 # in urls that get crawled by bots (e.g. index.php). failing early
231 # reduces the amount of invalid channel names getting looked up.
232 return redirect(url_for('.channel', channel_id
=something
))
233 elif re
.match(r
"^[-_0-9A-Za-z]{11}$", something
): # looks like a video id
234 return redirect(url_for('.watch', v
=something
, t
=request
.args
.get('t')))
235 else: # ¯\_(ツ)_/¯
236 # XXX: something == 'thethoughtemporium' -> 404s
237 raise NotFound("Note: some usernames not recognized; try searching it")
239 @frontend.route('/attribution_link', strict_slashes
=False)
240 def attribution_link():
241 # /attribution_link?a=anything&u=/channel/UCZYTClx2T1of7BRZ86-8fow
242 # /attribution_link?a=JdfC0C9V6ZI&u=%2Fwatch%3Fv%3DEhxJLojIE_o%26feature%3Dshare
243 return redirect(request
.args
.get('u') or '/')
245 @frontend.route('/c/<channel_id>/<subpage>')
246 @frontend.route('/c/<channel_id>/')
247 @frontend.route('/user/<channel_id>/<subpage>')
248 @frontend.route('/user/<channel_id>/')
249 def channel_redirect(channel_id
, subpage
=None):
250 # Note: we can't check /c/, so we have to assume it is the same as /user/,
251 # which is sometimes wrong.
252 xmlfeed
= fetch_xml("user", channel_id
)
255 raise NotFound("unknown channel name")
257 _
, _
, _
, channel_id
, _
= parse_xml(xmlfeed
)
259 return redirect(url_for('.channel', channel_id
=channel_id
))
261 @frontend.route('/channel/<channel_id>/<subpage>')
262 @frontend.route('/channel/<channel_id>/')
263 def channel(channel_id
, _
=None):
264 token
= getattr(current_user
, 'token', 'guest')
265 sort
= request
.args
.get("sort", "newest")
267 if not re
.match(r
"(UC[A-Za-z0-9_-]{22})", channel_id
):
268 # canonicalize channel id, otherwise popular won't work
269 return redirect(url_for('.channel_redirect', channel_id
=channel_id
))
271 if sort
== "popular":
272 xmlfeed
= fetch_xml("playlist_id", f
"PU{channel_id[2:]}")
274 xmlfeed
= fetch_xml("channel_id", channel_id
)
275 #^note: could also use playlist_id=UU...
278 raise NotFound("unknown channel id")
280 title
, author
, videos
, _
, _
= parse_xml(xmlfeed
)
282 with sqlite3
.connect(cf
['global']['database']) as conn
:
287 WHERE channel_id = ? AND user = ?
288 """, (channel_id
, token
))
289 (is_subscribed
,) = c
.fetchone()
291 return render_template('xmlfeed.html.j2', title
=author
, rows
=videos
,
292 is_subscribed
=is_subscribed
, channel_id
=channel_id
)
294 @frontend.route('/playlist')
296 playlist_id
= request
.args
.get('list')
298 return "bad list id", 400 # todo
300 xmlfeed
= fetch_xml("playlist_id", playlist_id
)
302 return "not found or something", 404 # XXX
303 title
, author
, videos
, _
, _
= parse_xml(xmlfeed
)
304 return render_template('xmlfeed.html.j2', title
=f
"{title} by {author}", rows
=videos
)
306 @frontend.route('/api/timedtext')
308 r
= requests
.get("https://www.youtube.com/api/timedtext", request
.args
.to_dict())
309 # Note: in srv1 format, xmlentities are double-encoded m( a smart quote is
310 # even worse: it's '&39;<smartquote>' wtf!? (at least vvt seems ok)
312 return "error: {r.text}", 400 # TODO: better
314 if request
.args
.get('fmt') == 'vtt' and request
.args
.get('kind') == 'asr':
315 # autocaptions are extremely confusing, and stuck in the lower-left corner. fix it up a bit
316 retval
= re
.sub(r
"<.+?>", "", retval
) # remove inline html-like markup that times each word/adds styles
317 retval
= retval
.replace("align:start position:0%", "") # let browser position the text itself
318 # each subtitle-line is repeated twice (first on the lower line, then
319 # on the next "frame" on the upper line). we want to remove the
320 # repetition, as that's confusing without word and line animations:
321 lines
= retval
.split('\n')
322 retval
= '\n'.join([line
for line
, prev
in zip(lines
, ['']+lines
) if not " --> " in prev
])
323 return retval
, {'Content-Type': r
.headers
.get("Content-Type")}
325 @frontend.route('/manage/subscriptions')
326 # disabled for guest user: @login_required
327 def subscription_manager():
328 if current_user
.is_anonymous
:
331 token
= current_user
.token
332 with sqlite3
.connect(cf
['global']['database']) as conn
:
333 #with conn.cursor() as c:
336 SELECT subscriptions.channel_id, name, type,
337 (subscribed_until < datetime('now')) AS obsolete
339 LEFT JOIN (SELECT name, id FROM channels
341 SELECT name, id FROM playlists
342 ) AS channels ON channels.id = subscriptions.channel_id
343 left JOIN websub ON channels.id = websub.channel_id
345 AND subscriptions.type IN ('channel', 'playlist')
346 ORDER BY obsolete=0, name COLLATE NOCASE ASC""", (token
,))
348 'channel_id': channel_id
,
349 'author': author
or channel_id
,
351 'subscribed_until': subscribed_until
352 } for (channel_id
, author
, type, subscribed_until
) in c
.fetchall()]
353 return render_template('subscription_manager.html.j2', rows
=rows
)
355 @frontend.route('/feed/subscriptions', methods
=['POST'])
358 token
= current_user
.token
359 action
= next(iter(list(request
.form
.keys())), None)
360 if action
in ['pin', 'unpin', 'hide', 'unhide']:
361 video_id
= request
.form
.get(action
)
368 with sqlite3
.connect(cf
['global']['database']) as conn
:
370 store_video_metadata(video_id
) # only needed for pinning
372 INSERT OR REPLACE INTO flags (user, video_id, display)
374 """, (token
, video_id
, display
))
375 undo_flash(video_id
, action
)
377 flash("unsupported action", "error")
378 return redirect(request
.url
, code
=303)
380 @frontend.route('/manage/subscriptions', methods
=['POST'])
382 def manage_subscriptions():
383 token
= current_user
.token
384 if 'subscribe' in request
.form
:
385 some_id
= request
.form
.get("subscribe")
386 match
= re
.search(r
"(UC[A-Za-z0-9_-]{22})", some_id
)
388 some_id
= match
.group(1)
391 match
= re
.search(r
"((?:PL|LL|EC|UU|FL|UL|OL)[A-Za-z0-9_-]{10,})", some_id
)
392 if match
: # NOTE: PL-playlists are 32chars, others differ in length.
393 some_id
= match
.group(1)
396 flash("not a valid/subscribable URI", "error")
397 return redirect(request
.url
, code
=303)
398 with sqlite3
.connect(cf
['global']['database']) as conn
:
399 #with conn.cursor() as c:
402 INSERT OR IGNORE INTO subscriptions (user, channel_id, type)
404 """, (token
, some_id
, id_type
))
405 # TODO: sql-error-handling, asynchronically calling update-subs.pl
406 undo_flash(some_id
, 'subscribe')
408 elif 'unsubscribe' in request
.form
:
409 some_id
= request
.form
.get("unsubscribe")
410 with sqlite3
.connect(cf
['global']['database']) as conn
:
411 #with conn.cursor() as c:
414 DELETE FROM subscriptions
415 WHERE user = ? AND channel_id = ?
416 """, (token
, some_id
))
417 # TODO: sql-error-handling, report success
418 undo_flash(some_id
, 'unsubscribe')
421 flash("unsupported action", "error")
423 return redirect(request
.url
, code
=303)
425 @frontend.route('/vi/<vid>/<res>.jpg')
426 def redirect_thumbnails(vid
, res
):
427 return redirect(f
"https://i.ytimg.com{request.path}", code
=301)
430 def redirect_youtube_dot_com(state
):
432 This is executed when the blueprint is loaded dynamically builds a number
433 of routes so that URLs like
434 https://subscriptions.gir.st/https://www.youtube.com/watch?v=dQw4w9WgXcQ
435 redirect to the /watch page. Works with /watch, /embed/ and youtu.be short
436 links, with or without protocl and/or 'www'.
438 def real_redirect_youtube_dot_com(video_id
=None):
439 if not re
.match(r
"^[-_0-9A-Za-z]{11}$", video_id
or ''): video_id
= None
440 if not video_id
: video_id
= request
.args
.get('v')
441 return redirect(url_for('.watch', v
=video_id
))
443 for protocol
in ("", "http://", "https://"):
444 for prefix
in ("", "www.", "m."):
445 for domain
in ("youtube.com", "youtu.be", "youtube-nocookie.com"):
446 for urlpath
in ("/watch", "/embed/<video_id>", "/live/<video_id>", "/shorts/<video_id>", "/<video_id>"):
447 if domain
!= "youtu.be" and urlpath
== "/<video_id>":
448 continue # that's a channel, not a video
449 frontend
.add_url_rule(
450 f
"/{protocol}{prefix}{domain}{urlpath}",
451 view_func
=real_redirect_youtube_dot_com
,
455 def undo_flash(thing_id
, action
):
456 undo_action
, past_action
= {
457 'pin': ('unpin', 'pinned'),
458 'unpin': ('pin', 'unpinned'),
459 'hide': ('unhide', 'hidden'),
460 'unhide': ('hide', 'unhidden'),
461 'subscribe': ('unsubscribe', 'subscribed'),
462 'unsubscribe': ('subscribe', 'unsubscribed'),
464 if 'subscribe' in action
and thing_id
.startswith('UC'):
466 thing_url
= url_for('.channel', channel_id
=thing_id
)
467 elif 'subscribe' in action
:
469 thing_url
= url_for('.playlist', playlist_id
=thing_id
)
472 thing_url
= url_for('.watch', v
=thing_id
)
474 <form method=post><input type=hidden name="{undo_action}" value="{thing_id}">
475 <a href="{thing_url}">{thing}</a> {past_action}.
476 <label><input type="submit" hidden>
477 <span style="text-decoration:underline;cursor:pointer">undo</span>.
478 </label></form>''', "info")
480 @frontend.app_template_filter('format_date')
482 import datetime
# can't import at top level, because it is inherited from common
483 (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'
484 M
= '_ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()
485 if y
== datetime
.datetime
.now().year
:
488 return f
"{M[m]} '{y%100}"
490 @frontend.app_template_filter('format_time')
497 return '%d:%02d:%02d' % (h
,m
,s
) if h
else '%02d:%02d' % (m
,s
)
499 @frontend.app_template_filter('timeoffset')
503 match
= re
.match(r
"^(\d+)s?$", s
) # e.g. 2040s
505 return match
.group(1)
506 match
= re
.match(r
"^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$", s
) # e.g. 34m, 1h23s
508 return ":".join([n
.zfill(2) for n
in match
.groups('0')])