import re import time import sqlite3 import requests from urllib.parse import urlparse #from flask_login import current_user, login_required from flask_login import LoginManager, UserMixin, current_user, login_user, logout_user, login_required from flask import Blueprint, render_template, request, redirect, flash, url_for, jsonify, g, current_app from werkzeug.exceptions import NotFound, BadGateway from ..common.common import * from ..common.anticaptcha import submit_captcha from .lib import * frontend = Blueprint('youtube', __name__, template_folder='templates', static_folder='static', static_url_path='/static/yt') @frontend.route('/') def index(): return redirect(url_for('.feed'), code=302) @frontend.route('/feed/subscriptions') # disabled for guest user: @login_required def feed(): if current_user.is_anonymous: token = 'guest' if 'welcome_message' in cf['frontend']: flash(cf['frontend']['welcome_message'], "welcome") else: token = current_user.token page = int(request.args.get('page', 0)) with sqlite3.connect(cf['global']['database']) as conn: c = conn.cursor() c.execute(""" SELECT videos.id, channel_id, name, title, length, livestream, published, playlist_videos.playlist_id, display FROM videos JOIN channels ON videos.channel_id = channels.id LEFT JOIN playlist_videos ON (videos.id = playlist_videos.video_id) LEFT JOIN flags ON (videos.id = flags.video_id) AND (flags.user = ?) WHERE (channel_id IN (SELECT channel_id FROM subscriptions WHERE user=? AND type = 'channel') OR playlist_videos.playlist_id IN (SELECT channel_id FROM subscriptions WHERE user=? AND type = 'playlist') OR flags.display = 'pinned') AND flags.display IS NOT 'hidden' ORDER BY (display = 'pinned') DESC, crawled DESC LIMIT 36 OFFSET 36*?""", (token, token, token, page)) rows = [{ 'video_id': video_id, 'channel_id': channel_id, 'author': author, 'title': title, 'length': length, 'livestream': livestream, 'published': published, 'playlist': playlist, 'pinned': display == 'pinned', } for (video_id, channel_id, author, title, length, livestream, published, playlist, display) in c.fetchall()] return render_template('index.html.j2', rows=rows, page=page) @frontend.route('/watch') def watch(): if current_user.is_anonymous: token = 'guest' else: token = current_user.token if not 'v' in request.args: return "missing video id", 400 plaintextheaders = { 'content-type': 'text/plain', 'Link': "; rel=stylesheet;" } video_id = request.args.get('v') sts, algo = get_cipher() video_url, stream_map, metadata, error, errdetails = get_video_info(video_id, sts, algo) extra = {'geolocked':'local=1', 'livestream':'raw=0'}.get(error,'') invidious_url = f"https://invidious.snopyta.org/watch?v={video_id}&{extra}" errdetails = { 'banned': "Instance is being rate limited.", 'malformed': "Video ID is invalid.", 'geolocked': "This video is geolocked.", 'livestream': "Livestreams not supported on this instance.", 'agegated': "Unable to bypass age-restriction.", 'exhausted': errdetails or "Couldn't extract video URLs.", 'player': errdetails, }.get(error) # if the video is geolocked, and the proxy is enabled, we can still play # it, if the video is available in the instance server's region: if error == 'geolocked' and video_url and 'proxy' in current_app.blueprints.keys(): videoplayback = url_for('proxy.videoplayback') query = urlparse(video_url).query video_url = f"{videoplayback}?{query}" for s in stream_map['adaptive']: query = urlparse(s['url']).query s['url'] = f"{videoplayback}?{query}" for s in stream_map['muxed']: query = urlparse(s['url']).query s['url'] = f"{videoplayback}?{query}" error = None # if the proxy is enabled, we can also play livestreams: if error == 'livestream' and 'proxy' in current_app.blueprints.keys(): # Note: hlsManifestUrl's hostname will be replaced client-side video_url = stream_map['hlsManifestUrl'] error = None # if the instance is blocked, try submitting a job to the anti captcha service: if error == 'banned' and cf['captcha']['api_key']: r2 = requests.get(f'https://www.youtube.com/watch?v={video_id}&hl=en&gl=US') status = submit_captcha(r2) if status is False: raise Exception("we are banned, but captcha wasn't triggered!") else: message = "right now" if status is True else f"{int(status)} seconds ago" raise BadGateway(f""" {errdetails} An attempt at getting unblocked has been made {message}. Please try again in 30 seconds. """) show = request.args.get("show") if show == "raw": if error: msg = errdetails if error=='player' else f"{error.upper()}: {errdetails}" return f"{msg}\n\nRedirecting to Invidious.", 502, { 'Refresh': f'2; URL={invidious_url}&raw=1', **plaintextheaders} return redirect(video_url, code=307) elif show == "json": if error and not metadata: return {'error': True, error: errdetails}, 400 # TODO: better (test _CpR4o81XQc) return jsonify(metadata) elif show == "audio": # sorting: we want to prioritize mp4a over opus, and sort by highest quality first # todo: geolocking; prefer open format? if error and not metadata: msg = errdetails if error=='player' else f"{error.upper()}: {errdetails}" return msg, 400, plaintextheaders # TODO: nicer stream = next(iter(sorted([ stream for stream in stream_map['adaptive'] if stream['mimeType'].startswith('audio/')], key=lambda stream: ('opus' not in stream['mimeType'], stream['bitrate']), reverse=True) ),{}).get('url') return redirect(stream) else: if error and not metadata: # e.g. malformed, private/deleted video, ... return render_template('video-error.html.j2', video_id=video_id, video_error=error, errdetails=errdetails, invidious_url=invidious_url) meta = prepare_metadata(metadata) with sqlite3.connect(cf['global']['database']) as conn: c = conn.cursor() c.execute(""" SELECT COUNT(( SELECT 1 FROM subscriptions WHERE channel_id = ? AND user = ? )), COUNT(( SELECT 1 FROM flags WHERE video_id = ? AND display = 'pinned' AND user = ? ))""", (meta['channel_id'], token, video_id, token)) (is_subscribed, is_pinned) = c.fetchone() return render_template('watch.html.j2', video_id=video_id, video_url=video_url, stream_map=stream_map, video_error=error, errdetails=errdetails, invidious_url=invidious_url, is_pinned=is_pinned, is_subscribed=is_subscribed, **meta) @frontend.route('/embed/videoseries') def embed_videoseries(): return redirect(url_for('.playlist', list=request.args.get('list'))) @frontend.route('/embed/', strict_slashes=False) def embed(video_id): if video_id == "videoseries": return redirect(url_for('.playlist', list=request.args.get('list'))) return redirect(url_for('.watch', v=video_id, t=request.args.get('start'))) @frontend.route('/', strict_slashes=False) def plain_user_or_video(something): # yt.com interprets this as a username, but we also want to catch youtu.be # short-urls. so we check if it's a channel by querying the RSS feed (this # shoudn't be rate-limited); if that fails, check if it looks like a video # id; or finally give up. if '.' not in something and channel_exists(something): # periods are not valid in usernames, vanity urls or ucids, but common # in urls that get crawled by bots (e.g. index.php). failing early # reduces the amount of invalid channel names getting looked up. return redirect(url_for('.channel', channel_id=something)) elif re.match(r"^[-_0-9A-Za-z]{11}$", something): # looks like a video id return redirect(url_for('.watch', v=something, t=request.args.get('t'))) else: # ¯\_(ツ)_/¯ # XXX: something == 'thethoughtemporium' -> 404s raise NotFound("Note: some usernames not recognized; try searching it") @frontend.route('/channel//') @frontend.route('/user//') @frontend.route('/c//') @frontend.route('/channel//') @frontend.route('/user//') @frontend.route('/c//') def channel(channel_id, _=None): token = getattr(current_user, 'token', 'guest') if re.match(r"(UC[A-Za-z0-9_-]{22})", channel_id): xmlfeed = fetch_xml("channel_id", channel_id) else: xmlfeed = fetch_xml("user", channel_id) if not xmlfeed: return "not found or something", 404 # XXX title, author, videos, channel_id, _ = parse_xml(xmlfeed) with sqlite3.connect(cf['global']['database']) as conn: c = conn.cursor() c.execute(""" SELECT COUNT(*) FROM subscriptions WHERE channel_id = ? AND user = ? """, (channel_id, token)) (is_subscribed,) = c.fetchone() return render_template('xmlfeed.html.j2', title=author, rows=videos, is_subscribed=is_subscribed, channel_id=channel_id) @frontend.route('/playlist') def playlist(): playlist_id = request.args.get('list') if not playlist_id: return "bad list id", 400 # todo xmlfeed = fetch_xml("playlist_id", playlist_id) if not xmlfeed: return "not found or something", 404 # XXX title, author, videos, _, _ = parse_xml(xmlfeed) return render_template('xmlfeed.html.j2', title=f"{title} by {author}", rows=videos) @frontend.route('/api/timedtext') def timedtext(): r = requests.get("https://www.youtube.com/api/timedtext", request.args.to_dict()) # Note: in srv1 format, xmlentities are double-encoded m( a smart quote is # even worse: it's '&39;' wtf!? (at least vvt seems ok) if not r.ok: return "error: {r.text}", 400 # TODO: better retval = r.text if request.args.get('fmt') == 'vtt' and request.args.get('kind') == 'asr': # autocaptions are extremely confusing, and stuck in the lower-left corner. fix it up a bit retval = re.sub(r"<.+?>", "", retval) # remove inline html-like markup that times each word/adds styles retval = retval.replace("align:start position:0%", "") # let browser position the text itself # each subtitle-line is repeated twice (first on the lower line, then # on the next "frame" on the upper line). we want to remove the # repetition, as that's confusing without word and line animations: lines = retval.split('\n') retval = '\n'.join([line for line, prev in zip(lines, ['']+lines) if not " --> " in prev]) return retval, {'Content-Type': r.headers.get("Content-Type")} @frontend.route('/manage/subscriptions') # disabled for guest user: @login_required def subscription_manager(): if current_user.is_anonymous: token = 'guest' else: token = current_user.token with sqlite3.connect(cf['global']['database']) as conn: #with conn.cursor() as c: c = conn.cursor() c.execute(""" SELECT subscriptions.channel_id, name, type, (subscribed_until < datetime('now')) AS obsolete FROM subscriptions LEFT JOIN (SELECT name, id FROM channels UNION SELECT name, id FROM playlists ) AS channels ON channels.id = subscriptions.channel_id left JOIN websub ON channels.id = websub.channel_id WHERE user = ? AND subscriptions.type IN ('channel', 'playlist') ORDER BY obsolete=0, name COLLATE NOCASE ASC""", (token,)) rows = [{ 'channel_id': channel_id, 'author': author or channel_id, 'type': type, 'subscribed_until': subscribed_until } for (channel_id, author, type, subscribed_until) in c.fetchall()] return render_template('subscription_manager.html.j2', rows=rows) @frontend.route('/feed/subscriptions', methods=['POST']) @login_required def feed_post(): token = current_user.token action = next(request.form.keys(), None) if action in ['pin', 'unpin', 'hide', 'unhide']: video_id = request.form.get(action) display = { 'pin': 'pinned', 'unpin': None, 'hide': 'hidden', 'unhide': None, }[action] with sqlite3.connect(cf['global']['database']) as conn: c = conn.cursor() store_video_metadata(video_id) # only needed for pinning c.execute(""" INSERT OR REPLACE INTO flags (user, video_id, display) VALUES (?, ?, ?) """, (token, video_id, display)) undo_flash(video_id, action) else: flash("unsupported action", "error") return redirect(request.url, code=303) @frontend.route('/manage/subscriptions', methods=['POST']) @login_required def manage_subscriptions(): token = current_user.token if 'subscribe' in request.form: some_id = request.form.get("subscribe") match = re.search(r"(UC[A-Za-z0-9_-]{22})", some_id) if match: some_id = match.group(1) id_type = "channel" else: match = re.search(r"((?:PL|LL|EC|UU|FL|UL|OL)[A-Za-z0-9_-]{10,})", some_id) if match: # NOTE: PL-playlists are 32chars, others differ in length. some_id = match.group(1) id_type = "playlist" else: flash("not a valid/subscribable URI", "error") return redirect(request.url, code=303) with sqlite3.connect(cf['global']['database']) as conn: #with conn.cursor() as c: c = conn.cursor() c.execute(""" INSERT OR IGNORE INTO subscriptions (user, channel_id, type) VALUES (?, ?, ?) """, (token, some_id, id_type)) # TODO: sql-error-handling, asynchronically calling update-subs.pl undo_flash(some_id, 'subscribe') elif 'unsubscribe' in request.form: some_id = request.form.get("unsubscribe") with sqlite3.connect(cf['global']['database']) as conn: #with conn.cursor() as c: c = conn.cursor() c.execute(""" DELETE FROM subscriptions WHERE user = ? AND channel_id = ? """, (token, some_id)) # TODO: sql-error-handling, report success undo_flash(some_id, 'unsubscribe') else: flash("unsupported action", "error") return redirect(request.url, code=303) def get_cipher(): # reload cipher from database every 1 hour if 'cipher' not in g or time.time() - g.get('cipher_updated', 0) > 1 * 60 * 60: with sqlite3.connect(cf['global']['database']) as conn: c = conn.cursor() c.execute("SELECT sts, algorithm FROM cipher") g.cipher = c.fetchone() g.cipher_updated = time.time() return g.cipher #@frontend.teardown_appcontext #def teardown_db(): # db = g.pop('db', None) # # if db is not None: # db.close() def undo_flash(thing_id, action): undo_action, past_action = { 'pin': ('unpin', 'pinned'), 'unpin': ('pin', 'unpinned'), 'hide': ('unhide', 'hidden'), 'unhide': ('hide', 'unhidden'), 'subscribe': ('unsubscribe', 'subscribed'), 'unsubscribe': ('subscribe', 'unsubscribed'), }.get(action) if 'subscribe' in action and thing_id.startswith('UC'): thing = "channel" thing_url = url_for('.channel', channel_id=thing_id) elif 'subscribe' in action: thing = "playlist" thing_url = url_for('.playlist', playlist_id=thing_id) else: thing = "video" thing_url = url_for('.watch', v=thing_id) flash(f'''
{thing} {past_action}.
''', "info") @frontend.app_template_filter('format_date') def format_date(s): import datetime # can't import at top level, because it is inherited from common (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' M = '_ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split() if y == datetime.datetime.now().year: return f"{d} {M[m]}" else: return f"{M[m]} '{y%100}" @frontend.app_template_filter('format_time') def format_time(i): if i is None: return None h = i // (60*60) m = i // 60 % 60 s = i % 60 return '%d:%02d:%02d' % (h,m,s) if h else '%02d:%02d' % (m,s) @frontend.app_template_filter('timeoffset') def timeoffset(s): if s is None: return None match = re.match(r"^(\d+)s?$", s) # e.g. 2040s if match: return match.group(1) match = re.match(r"^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$", s) # e.g. 34m, 1h23s if match: return ":".join([n.zfill(2) for n in match.groups('0')]) return None