watch.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  1. import youtube
  2. from youtube import yt_app
  3. from youtube import util, comments, local_playlist, yt_data_extract
  4. from youtube.util import time_utc_isoformat
  5. import settings
  6. from flask import request
  7. import flask
  8. import json
  9. import gevent
  10. import os
  11. import math
  12. import traceback
  13. import urllib
  14. import re
  15. import urllib3.exceptions
  16. from urllib.parse import parse_qs, urlencode
  17. from types import SimpleNamespace
  18. from math import ceil
  19. try:
  20. with open(os.path.join(settings.data_dir, 'decrypt_function_cache.json'), 'r') as f:
  21. decrypt_cache = json.loads(f.read())['decrypt_cache']
  22. except FileNotFoundError:
  23. decrypt_cache = {}
  24. def codec_name(vcodec):
  25. if vcodec.startswith('avc'):
  26. return 'h264'
  27. elif vcodec.startswith('av01'):
  28. return 'av1'
  29. elif vcodec.startswith('vp'):
  30. return 'vp'
  31. else:
  32. return 'unknown'
  33. def get_video_sources(info, target_resolution):
  34. '''return dict with organized sources: {
  35. 'uni_sources': [{}, ...], # video and audio in one file
  36. 'uni_idx': int, # default unified source index
  37. 'pair_sources': [{video: {}, audio: {}, quality: ..., ...}, ...],
  38. 'pair_idx': int, # default pair source index
  39. }
  40. '''
  41. audio_sources = []
  42. video_only_sources = {}
  43. uni_sources = []
  44. pair_sources = []
  45. for fmt in info['formats']:
  46. if not all(fmt[attr] for attr in ('ext', 'url', 'itag')):
  47. continue
  48. # unified source
  49. if fmt['acodec'] and fmt['vcodec']:
  50. source = {
  51. 'type': 'video/' + fmt['ext'],
  52. 'quality_string': short_video_quality_string(fmt),
  53. }
  54. source['quality_string'] += ' (integrated)'
  55. source.update(fmt)
  56. uni_sources.append(source)
  57. continue
  58. if not (fmt['init_range'] and fmt['index_range']):
  59. continue
  60. # audio source
  61. if fmt['acodec'] and not fmt['vcodec'] and (
  62. fmt['audio_bitrate'] or fmt['bitrate']):
  63. if fmt['bitrate']: # prefer this one, more accurate right now
  64. fmt['audio_bitrate'] = int(fmt['bitrate']/1000)
  65. source = {
  66. 'type': 'audio/' + fmt['ext'],
  67. 'quality_string': audio_quality_string(fmt),
  68. }
  69. source.update(fmt)
  70. source['mime_codec'] = (source['type'] + '; codecs="'
  71. + source['acodec'] + '"')
  72. audio_sources.append(source)
  73. # video-only source
  74. elif all(fmt[attr] for attr in ('vcodec', 'quality', 'width', 'fps',
  75. 'file_size')):
  76. if codec_name(fmt['vcodec']) == 'unknown':
  77. continue
  78. source = {
  79. 'type': 'video/' + fmt['ext'],
  80. 'quality_string': short_video_quality_string(fmt),
  81. }
  82. source.update(fmt)
  83. source['mime_codec'] = (source['type'] + '; codecs="'
  84. + source['vcodec'] + '"')
  85. quality = str(fmt['quality']) + 'p' + str(fmt['fps'])
  86. if quality in video_only_sources:
  87. video_only_sources[quality].append(source)
  88. else:
  89. video_only_sources[quality] = [source]
  90. audio_sources.sort(key=lambda source: source['audio_bitrate'])
  91. uni_sources.sort(key=lambda src: src['quality'])
  92. webm_audios = [a for a in audio_sources if a['ext'] == 'webm']
  93. mp4_audios = [a for a in audio_sources if a['ext'] == 'mp4']
  94. for quality_string, sources in video_only_sources.items():
  95. # choose an audio source to go with it
  96. # 0.5 is semiarbitrary empirical constant to spread audio sources
  97. # between 144p and 1080p. Use something better eventually.
  98. quality, fps = map(int, quality_string.split('p'))
  99. target_audio_bitrate = quality*fps/30*0.5
  100. pair_info = {
  101. 'quality_string': quality_string,
  102. 'quality': quality,
  103. 'height': sources[0]['height'],
  104. 'width': sources[0]['width'],
  105. 'fps': fps,
  106. 'videos': sources,
  107. 'audios': [],
  108. }
  109. for audio_choices in (webm_audios, mp4_audios):
  110. if not audio_choices:
  111. continue
  112. closest_audio_source = audio_choices[0]
  113. best_err = target_audio_bitrate - audio_choices[0]['audio_bitrate']
  114. best_err = abs(best_err)
  115. for audio_source in audio_choices[1:]:
  116. err = abs(audio_source['audio_bitrate'] - target_audio_bitrate)
  117. # once err gets worse we have passed the closest one
  118. if err > best_err:
  119. break
  120. best_err = err
  121. closest_audio_source = audio_source
  122. pair_info['audios'].append(closest_audio_source)
  123. if not pair_info['audios']:
  124. continue
  125. def video_rank(src):
  126. ''' Sort by settings preference. Use file size as tiebreaker '''
  127. setting_name = 'codec_rank_' + codec_name(src['vcodec'])
  128. return (settings.current_settings_dict[setting_name],
  129. src['file_size'])
  130. pair_info['videos'].sort(key=video_rank)
  131. pair_sources.append(pair_info)
  132. pair_sources.sort(key=lambda src: src['quality'])
  133. uni_idx = 0 if uni_sources else None
  134. for i, source in enumerate(uni_sources):
  135. if source['quality'] > target_resolution:
  136. break
  137. uni_idx = i
  138. pair_idx = 0 if pair_sources else None
  139. for i, pair_info in enumerate(pair_sources):
  140. if pair_info['quality'] > target_resolution:
  141. break
  142. pair_idx = i
  143. return {
  144. 'uni_sources': uni_sources,
  145. 'uni_idx': uni_idx,
  146. 'pair_sources': pair_sources,
  147. 'pair_idx': pair_idx,
  148. }
  149. def make_caption_src(info, lang, auto=False, trans_lang=None):
  150. label = lang
  151. if auto:
  152. label += ' (Automatic)'
  153. if trans_lang:
  154. label += ' -> ' + trans_lang
  155. return {
  156. 'url': util.prefix_url(yt_data_extract.get_caption_url(info, lang, 'vtt', auto, trans_lang)),
  157. 'label': label,
  158. 'srclang': trans_lang[0:2] if trans_lang else lang[0:2],
  159. 'on': False,
  160. }
  161. def lang_in(lang, sequence):
  162. '''Tests if the language is in sequence, with e.g. en and en-US considered the same'''
  163. if lang is None:
  164. return False
  165. lang = lang[0:2]
  166. return lang in (l[0:2] for l in sequence)
  167. def lang_eq(lang1, lang2):
  168. '''Tests if two iso 639-1 codes are equal, with en and en-US considered the same.
  169. Just because the codes are equal does not mean the dialects are mutually intelligible, but this will have to do for now without a complex language model'''
  170. if lang1 is None or lang2 is None:
  171. return False
  172. return lang1[0:2] == lang2[0:2]
  173. def equiv_lang_in(lang, sequence):
  174. '''Extracts a language in sequence which is equivalent to lang.
  175. e.g. if lang is en, extracts en-GB from sequence.
  176. Necessary because if only a specific variant like en-GB is available, can't ask YouTube for simply en. Need to get the available variant.'''
  177. lang = lang[0:2]
  178. for l in sequence:
  179. if l[0:2] == lang:
  180. return l
  181. return None
  182. def get_subtitle_sources(info):
  183. '''Returns these sources, ordered from least to most intelligible:
  184. native_video_lang (Automatic)
  185. foreign_langs (Manual)
  186. native_video_lang (Automatic) -> pref_lang
  187. foreign_langs (Manual) -> pref_lang
  188. native_video_lang (Manual) -> pref_lang
  189. pref_lang (Automatic)
  190. pref_lang (Manual)'''
  191. sources = []
  192. if not yt_data_extract.captions_available(info):
  193. return []
  194. pref_lang = settings.subtitles_language
  195. native_video_lang = None
  196. if info['automatic_caption_languages']:
  197. native_video_lang = info['automatic_caption_languages'][0]
  198. highest_fidelity_is_manual = False
  199. # Sources are added in very specific order outlined above
  200. # More intelligible sources are put further down to avoid browser bug when there are too many languages
  201. # (in firefox, it is impossible to select a language near the top of the list because it is cut off)
  202. # native_video_lang (Automatic)
  203. if native_video_lang and not lang_eq(native_video_lang, pref_lang):
  204. sources.append(make_caption_src(info, native_video_lang, auto=True))
  205. # foreign_langs (Manual)
  206. for lang in info['manual_caption_languages']:
  207. if not lang_eq(lang, pref_lang):
  208. sources.append(make_caption_src(info, lang))
  209. if (lang_in(pref_lang, info['translation_languages'])
  210. and not lang_in(pref_lang, info['automatic_caption_languages'])
  211. and not lang_in(pref_lang, info['manual_caption_languages'])):
  212. # native_video_lang (Automatic) -> pref_lang
  213. if native_video_lang and not lang_eq(pref_lang, native_video_lang):
  214. sources.append(make_caption_src(info, native_video_lang, auto=True, trans_lang=pref_lang))
  215. # foreign_langs (Manual) -> pref_lang
  216. for lang in info['manual_caption_languages']:
  217. if not lang_eq(lang, native_video_lang) and not lang_eq(lang, pref_lang):
  218. sources.append(make_caption_src(info, lang, trans_lang=pref_lang))
  219. # native_video_lang (Manual) -> pref_lang
  220. if lang_in(native_video_lang, info['manual_caption_languages']):
  221. sources.append(make_caption_src(info, native_video_lang, trans_lang=pref_lang))
  222. # pref_lang (Automatic)
  223. if lang_in(pref_lang, info['automatic_caption_languages']):
  224. sources.append(make_caption_src(info, equiv_lang_in(pref_lang, info['automatic_caption_languages']), auto=True))
  225. # pref_lang (Manual)
  226. if lang_in(pref_lang, info['manual_caption_languages']):
  227. sources.append(make_caption_src(info, equiv_lang_in(pref_lang, info['manual_caption_languages'])))
  228. highest_fidelity_is_manual = True
  229. if sources and sources[-1]['srclang'] == pref_lang:
  230. # set as on by default since it's manual a default-on subtitles mode is in settings
  231. if highest_fidelity_is_manual and settings.subtitles_mode > 0:
  232. sources[-1]['on'] = True
  233. # set as on by default since settings indicate to set it as such even if it's not manual
  234. elif settings.subtitles_mode == 2:
  235. sources[-1]['on'] = True
  236. if len(sources) == 0:
  237. assert len(info['automatic_caption_languages']) == 0 and len(info['manual_caption_languages']) == 0
  238. return sources
  239. def get_ordered_music_list_attributes(music_list):
  240. # get the set of attributes which are used by atleast 1 track
  241. # so there isn't an empty, extraneous album column which no tracks use, for example
  242. used_attributes = set()
  243. for track in music_list:
  244. used_attributes = used_attributes | track.keys()
  245. # now put them in the right order
  246. ordered_attributes = []
  247. for attribute in ('Artist', 'Title', 'Album'):
  248. if attribute.lower() in used_attributes:
  249. ordered_attributes.append(attribute)
  250. return ordered_attributes
  251. def save_decrypt_cache():
  252. try:
  253. f = open(os.path.join(settings.data_dir, 'decrypt_function_cache.json'), 'w')
  254. except FileNotFoundError:
  255. os.makedirs(settings.data_dir)
  256. f = open(os.path.join(settings.data_dir, 'decrypt_function_cache.json'), 'w')
  257. f.write(json.dumps({'version': 1, 'decrypt_cache':decrypt_cache}, indent=4, sort_keys=True))
  258. f.close()
  259. def decrypt_signatures(info, video_id):
  260. '''return error string, or False if no errors'''
  261. if not yt_data_extract.requires_decryption(info):
  262. return False
  263. if not info['player_name']:
  264. return 'Could not find player name'
  265. player_name = info['player_name']
  266. if player_name in decrypt_cache:
  267. print('Using cached decryption function for: ' + player_name)
  268. info['decryption_function'] = decrypt_cache[player_name]
  269. else:
  270. base_js = util.fetch_url(info['base_js'], debug_name='base.js', report_text='Fetched player ' + player_name)
  271. base_js = base_js.decode('utf-8')
  272. err = yt_data_extract.extract_decryption_function(info, base_js)
  273. if err:
  274. return err
  275. decrypt_cache[player_name] = info['decryption_function']
  276. save_decrypt_cache()
  277. err = yt_data_extract.decrypt_signatures(info)
  278. return err
  279. def _add_to_error(info, key, additional_message):
  280. if key in info and info[key]:
  281. info[key] += additional_message
  282. else:
  283. info[key] = additional_message
  284. def fetch_player_response(client, video_id):
  285. return util.call_youtube_api(client, 'player', {
  286. 'videoId': video_id,
  287. })
  288. def fetch_watch_page_info(video_id, playlist_id, index):
  289. # bpctr=9999999999 will bypass are-you-sure dialogs for controversial
  290. # videos
  291. url = 'https://m.youtube.com/embed/' + video_id + '?bpctr=9999999999'
  292. if playlist_id:
  293. url += '&list=' + playlist_id
  294. if index:
  295. url += '&index=' + index
  296. headers = (
  297. ('Accept', '*/*'),
  298. ('Accept-Language', 'en-US,en;q=0.5'),
  299. ('X-YouTube-Client-Name', '2'),
  300. ('X-YouTube-Client-Version', '2.20180830'),
  301. ) + util.mobile_ua
  302. watch_page = util.fetch_url(url, headers=headers,
  303. debug_name='watch')
  304. watch_page = watch_page.decode('utf-8')
  305. return yt_data_extract.extract_watch_info_from_html(watch_page)
  306. def extract_info(video_id, use_invidious, playlist_id=None, index=None):
  307. tasks = (
  308. # Get video metadata from here
  309. gevent.spawn(fetch_watch_page_info, video_id, playlist_id, index),
  310. gevent.spawn(fetch_player_response, 'android_vr', video_id)
  311. )
  312. gevent.joinall(tasks)
  313. util.check_gevent_exceptions(*tasks)
  314. info, player_response = tasks[0].value, tasks[1].value
  315. yt_data_extract.update_with_new_urls(info, player_response)
  316. # Age restricted video, retry
  317. if info['age_restricted'] or info['player_urls_missing']:
  318. if info['age_restricted']:
  319. print('Age restricted video, retrying')
  320. else:
  321. print('Player urls missing, retrying')
  322. player_response = fetch_player_response('tv_embedded', video_id)
  323. yt_data_extract.update_with_new_urls(info, player_response)
  324. # signature decryption
  325. decryption_error = decrypt_signatures(info, video_id)
  326. if decryption_error:
  327. decryption_error = 'Error decrypting url signatures: ' + decryption_error
  328. info['playability_error'] = decryption_error
  329. # check if urls ready (non-live format) in former livestream
  330. # urls not ready if all of them have no filesize
  331. if info['was_live']:
  332. info['urls_ready'] = False
  333. for fmt in info['formats']:
  334. if fmt['file_size'] is not None:
  335. info['urls_ready'] = True
  336. else:
  337. info['urls_ready'] = True
  338. # livestream urls
  339. # sometimes only the livestream urls work soon after the livestream is over
  340. if (info['hls_manifest_url']
  341. and (info['live'] or not info['formats'] or not info['urls_ready'])
  342. ):
  343. manifest = util.fetch_url(info['hls_manifest_url'],
  344. debug_name='hls_manifest.m3u8',
  345. report_text='Fetched hls manifest'
  346. ).decode('utf-8')
  347. info['hls_formats'], err = yt_data_extract.extract_hls_formats(manifest)
  348. if not err:
  349. info['playability_error'] = None
  350. for fmt in info['hls_formats']:
  351. fmt['video_quality'] = video_quality_string(fmt)
  352. else:
  353. info['hls_formats'] = []
  354. # check for 403. Unnecessary for tor video routing b/c ip address is same
  355. info['invidious_used'] = False
  356. info['invidious_reload_button'] = False
  357. info['tor_bypass_used'] = False
  358. if (settings.route_tor == 1
  359. and info['formats'] and info['formats'][0]['url']):
  360. try:
  361. response = util.head(info['formats'][0]['url'],
  362. report_text='Checked for URL access')
  363. except urllib3.exceptions.HTTPError:
  364. print('Error while checking for URL access:\n')
  365. traceback.print_exc()
  366. return info
  367. if response.status == 403:
  368. print('Access denied (403) for video urls.')
  369. print('Routing video through Tor')
  370. info['tor_bypass_used'] = True
  371. for fmt in info['formats']:
  372. fmt['url'] += '&use_tor=1'
  373. elif 300 <= response.status < 400:
  374. print('Error: exceeded max redirects while checking video URL')
  375. return info
  376. def video_quality_string(format):
  377. if format['vcodec']:
  378. result = str(format['width'] or '?') + 'x' + str(format['height'] or '?')
  379. if format['fps']:
  380. result += ' ' + str(format['fps']) + 'fps'
  381. return result
  382. elif format['acodec']:
  383. return 'audio only'
  384. return '?'
  385. def short_video_quality_string(fmt):
  386. result = str(fmt['quality'] or '?') + 'p'
  387. if fmt['fps']:
  388. result += str(fmt['fps'])
  389. if fmt['vcodec'].startswith('av01'):
  390. result += ' AV1'
  391. elif fmt['vcodec'].startswith('avc'):
  392. result += ' h264'
  393. else:
  394. result += ' ' + fmt['vcodec']
  395. return result
  396. def audio_quality_string(fmt):
  397. if fmt['acodec']:
  398. if fmt['audio_bitrate']:
  399. result = '%d' % fmt['audio_bitrate'] + 'k'
  400. else:
  401. result = '?k'
  402. if fmt['audio_sample_rate']:
  403. result += ' ' + '%.3G' % (fmt['audio_sample_rate']/1000) + 'kHz'
  404. return result
  405. elif fmt['vcodec']:
  406. return 'video only'
  407. return '?'
  408. # from https://github.com/ytdl-org/youtube-dl/blob/master/youtube_dl/utils.py
  409. def format_bytes(bytes):
  410. if bytes is None:
  411. return 'N/A'
  412. if type(bytes) is str:
  413. bytes = float(bytes)
  414. if bytes == 0.0:
  415. exponent = 0
  416. else:
  417. exponent = int(math.log(bytes, 1024.0))
  418. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  419. converted = float(bytes) / float(1024 ** exponent)
  420. return '%.2f%s' % (converted, suffix)
  421. @yt_app.route('/ytl-api/storyboard.vtt')
  422. def get_storyboard_vtt():
  423. """
  424. See:
  425. https://github.com/iv-org/invidious/blob/9a8b81fcbe49ff8d88f197b7f731d6bf79fc8087/src/invidious.cr#L3603
  426. https://github.com/iv-org/invidious/blob/3bb7fbb2f119790ee6675076b31cd990f75f64bb/src/invidious/videos.cr#L623
  427. """
  428. spec_url = request.args.get('spec_url')
  429. url, *boards = spec_url.split('|')
  430. base_url, q = url.split('?')
  431. q = parse_qs(q) # for url query
  432. storyboard = None
  433. wanted_height = 90
  434. for i, board in enumerate(boards):
  435. *t, _, sigh = board.split("#")
  436. width, height, count, width_cnt, height_cnt, interval = map(int, t)
  437. if height != wanted_height: continue
  438. q['sigh'] = [sigh]
  439. url = f"{base_url}?{urlencode(q, doseq=True)}"
  440. storyboard = SimpleNamespace(
  441. url = url.replace("$L", str(i)).replace("$N", "M$M"),
  442. width = width,
  443. height = height,
  444. interval = interval,
  445. width_cnt = width_cnt,
  446. height_cnt = height_cnt,
  447. storyboard_count = ceil(count / (width_cnt * height_cnt))
  448. )
  449. if not storyboard:
  450. flask.abort(404)
  451. def to_ts(ms):
  452. s, ms = divmod(ms, 1000)
  453. h, s = divmod(s, 3600)
  454. m, s = divmod(s, 60)
  455. return f"{h:02}:{m:02}:{s:02}.{ms:03}"
  456. r = "WEBVTT" # result
  457. ts = 0 # current timestamp
  458. for i in range(storyboard.storyboard_count):
  459. url = '/' + storyboard.url.replace("$M", str(i))
  460. interval = storyboard.interval
  461. w, h = storyboard.width, storyboard.height
  462. w_cnt, h_cnt = storyboard.width_cnt, storyboard.height_cnt
  463. for j in range(h_cnt):
  464. for k in range(w_cnt):
  465. r += f"{to_ts(ts)} --> {to_ts(ts+interval)}\n"
  466. r += f"{url}#xywh={w * k},{h * j},{w},{h}\n\n"
  467. ts += interval
  468. return flask.Response(r, mimetype='text/vtt')
  469. time_table = {'h': 3600, 'm': 60, 's': 1}
  470. @yt_app.route('/watch')
  471. @yt_app.route('/embed')
  472. @yt_app.route('/embed/<video_id>')
  473. @yt_app.route('/shorts')
  474. @yt_app.route('/shorts/<video_id>')
  475. def get_watch_page(video_id=None):
  476. video_id = request.args.get('v') or video_id
  477. if not video_id:
  478. return flask.render_template('error.html', error_message='Missing video id'), 404
  479. if len(video_id) < 11:
  480. return flask.render_template('error.html', error_message='Incomplete video id (too short): ' + video_id), 404
  481. time_start_str = request.args.get('t', '0s')
  482. time_start = 0
  483. if re.fullmatch(r'(\d+(h|m|s))+', time_start_str):
  484. for match in re.finditer(r'(\d+)(h|m|s)', time_start_str):
  485. time_start += int(match.group(1))*time_table[match.group(2)]
  486. elif re.fullmatch(r'\d+', time_start_str):
  487. time_start = int(time_start_str)
  488. lc = request.args.get('lc', '')
  489. playlist_id = request.args.get('list')
  490. index = request.args.get('index')
  491. use_invidious = bool(int(request.args.get('use_invidious', '1')))
  492. if request.path.startswith('/embed') and settings.embed_page_mode:
  493. tasks = (
  494. gevent.spawn((lambda: {})),
  495. gevent.spawn(extract_info, video_id, use_invidious,
  496. playlist_id=playlist_id, index=index),
  497. )
  498. else:
  499. tasks = (
  500. gevent.spawn(comments.video_comments, video_id,
  501. int(settings.default_comment_sorting), lc=lc),
  502. gevent.spawn(extract_info, video_id, use_invidious,
  503. playlist_id=playlist_id, index=index),
  504. )
  505. gevent.joinall(tasks)
  506. util.check_gevent_exceptions(tasks[1])
  507. comments_info, info = tasks[0].value, tasks[1].value
  508. if info['error']:
  509. return flask.render_template('error.html', error_message=info['error'])
  510. video_info = {
  511. 'duration': util.seconds_to_timestamp(info['duration'] or 0),
  512. 'id': info['id'],
  513. 'title': info['title'],
  514. 'author': info['author'],
  515. 'author_id': info['author_id'],
  516. }
  517. # prefix urls, and other post-processing not handled by yt_data_extract
  518. for item in info['related_videos']:
  519. item['thumbnail'] = "https://i.ytimg.com/vi/{}/hqdefault.jpg".format(item['id']) # set HQ relateds thumbnail videos
  520. util.prefix_urls(item)
  521. util.add_extra_html_info(item)
  522. for song in info['music_list']:
  523. song['url'] = util.prefix_url(song['url'])
  524. if info['playlist']:
  525. playlist_id = info['playlist']['id']
  526. for item in info['playlist']['items']:
  527. util.prefix_urls(item)
  528. util.add_extra_html_info(item)
  529. if playlist_id:
  530. item['url'] += '&list=' + playlist_id
  531. if item['index']:
  532. item['url'] += '&index=' + str(item['index'])
  533. info['playlist']['author_url'] = util.prefix_url(
  534. info['playlist']['author_url'])
  535. if settings.img_prefix:
  536. # Don't prefix hls_formats for now because the urls inside the manifest
  537. # would need to be prefixed as well.
  538. for fmt in info['formats']:
  539. fmt['url'] = util.prefix_url(fmt['url'])
  540. # Add video title to end of url path so it has a filename other than just
  541. # "videoplayback" when downloaded
  542. title = urllib.parse.quote(util.to_valid_filename(info['title'] or ''))
  543. for fmt in info['formats']:
  544. filename = title
  545. ext = fmt.get('ext')
  546. if ext:
  547. filename += '.' + ext
  548. fmt['url'] = fmt['url'].replace(
  549. '/videoplayback',
  550. '/videoplayback/name/' + filename)
  551. download_formats = []
  552. for format in (info['formats'] + info['hls_formats']):
  553. if format['acodec'] and format['vcodec']:
  554. codecs_string = format['acodec'] + ', ' + format['vcodec']
  555. else:
  556. codecs_string = format['acodec'] or format['vcodec'] or '?'
  557. download_formats.append({
  558. 'url': format['url'],
  559. 'ext': format['ext'] or '?',
  560. 'audio_quality': audio_quality_string(format),
  561. 'video_quality': video_quality_string(format),
  562. 'file_size': format_bytes(format['file_size']),
  563. 'codecs': codecs_string,
  564. })
  565. if (settings.route_tor == 2) or info['tor_bypass_used']:
  566. target_resolution = 240
  567. else:
  568. target_resolution = settings.default_resolution
  569. source_info = get_video_sources(info, target_resolution)
  570. uni_sources = source_info['uni_sources']
  571. pair_sources = source_info['pair_sources']
  572. uni_idx, pair_idx = source_info['uni_idx'], source_info['pair_idx']
  573. pair_quality = yt_data_extract.deep_get(pair_sources, pair_idx, 'quality')
  574. uni_quality = yt_data_extract.deep_get(uni_sources, uni_idx, 'quality')
  575. pair_error = abs((pair_quality or 360) - target_resolution)
  576. uni_error = abs((uni_quality or 360) - target_resolution)
  577. if uni_error == pair_error:
  578. # use settings.prefer_uni_sources as a tiebreaker
  579. closer_to_target = 'uni' if settings.prefer_uni_sources else 'pair'
  580. elif uni_error < pair_error:
  581. closer_to_target = 'uni'
  582. else:
  583. closer_to_target = 'pair'
  584. if settings.prefer_uni_sources == 2:
  585. # Use uni sources unless there's no choice.
  586. using_pair_sources = (
  587. bool(pair_sources) and (not uni_sources)
  588. )
  589. else:
  590. # Use the pair sources if they're closer to the desired resolution
  591. using_pair_sources = (
  592. bool(pair_sources)
  593. and (not uni_sources or closer_to_target == 'pair')
  594. )
  595. if using_pair_sources:
  596. video_height = pair_sources[pair_idx]['height']
  597. video_width = pair_sources[pair_idx]['width']
  598. else:
  599. video_height = yt_data_extract.deep_get(
  600. uni_sources, uni_idx, 'height', default=360
  601. )
  602. video_width = yt_data_extract.deep_get(
  603. uni_sources, uni_idx, 'width', default=640
  604. )
  605. # 1 second per pixel, or the actual video width
  606. theater_video_target_width = max(640, info['duration'] or 0, video_width)
  607. # Check for false determination of disabled comments, which comes from
  608. # the watch page. But if we got comments in the separate request for those,
  609. # then the determination is wrong.
  610. if info['comments_disabled'] and comments_info.get('comments'):
  611. info['comments_disabled'] = False
  612. print('Warning: False determination that comments are disabled')
  613. print('Comment count:', info['comment_count'])
  614. info['comment_count'] = None # hack to make it obvious there's a bug
  615. # captions and transcript
  616. subtitle_sources = get_subtitle_sources(info)
  617. other_downloads = []
  618. for source in subtitle_sources:
  619. best_caption_parse = urllib.parse.urlparse(
  620. source['url'].lstrip('/'))
  621. transcript_url = (util.URL_ORIGIN
  622. + '/watch/transcript'
  623. + best_caption_parse.path
  624. + '?' + best_caption_parse.query)
  625. other_downloads.append({
  626. 'label': 'Video Transcript: ' + source['label'],
  627. 'ext': 'txt',
  628. 'url': transcript_url
  629. })
  630. if request.path.startswith('/embed') and settings.embed_page_mode:
  631. template_name = 'embed.html'
  632. else:
  633. template_name = 'watch.html'
  634. return flask.render_template(template_name,
  635. header_playlist_names = local_playlist.get_playlist_names(),
  636. uploader_channel_url = ('/' + info['author_url']) if info['author_url'] else '',
  637. time_published = info['time_published'],
  638. view_count = (lambda x: '{:,}'.format(x) if x is not None else "")(info.get("view_count", None)),
  639. like_count = (lambda x: '{:,}'.format(x) if x is not None else "")(info.get("like_count", None)),
  640. dislike_count = (lambda x: '{:,}'.format(x) if x is not None else "")(info.get("dislike_count", None)),
  641. download_formats = download_formats,
  642. other_downloads = other_downloads,
  643. video_info = json.dumps(video_info),
  644. hls_formats = info['hls_formats'],
  645. subtitle_sources = subtitle_sources,
  646. related = info['related_videos'],
  647. playlist = info['playlist'],
  648. music_list = info['music_list'],
  649. music_attributes = get_ordered_music_list_attributes(info['music_list']),
  650. comments_info = comments_info,
  651. comment_count = info['comment_count'],
  652. comments_disabled = info['comments_disabled'],
  653. video_height = video_height,
  654. video_width = video_width,
  655. theater_video_target_width = theater_video_target_width,
  656. title = info['title'],
  657. uploader = info['author'],
  658. description = info['description'],
  659. unlisted = info['unlisted'],
  660. limited_state = info['limited_state'],
  661. age_restricted = info['age_restricted'],
  662. live = info['live'],
  663. playability_error = info['playability_error'],
  664. allowed_countries = info['allowed_countries'],
  665. ip_address = info['ip_address'] if settings.route_tor else None,
  666. invidious_used = info['invidious_used'],
  667. invidious_reload_button = info['invidious_reload_button'],
  668. video_url = util.URL_ORIGIN + '/watch?v=' + video_id,
  669. video_id = video_id,
  670. storyboard_url = (util.URL_ORIGIN + '/ytl-api/storyboard.vtt?' +
  671. urlencode([('spec_url', info['storyboard_spec_url'])])
  672. if info['storyboard_spec_url'] else None),
  673. js_data = {
  674. 'video_id': info['id'],
  675. 'video_duration': info['duration'],
  676. 'settings': settings.current_settings_dict,
  677. 'has_manual_captions': any(s.get('on') for s in subtitle_sources),
  678. **source_info,
  679. 'using_pair_sources': using_pair_sources,
  680. 'time_start': time_start,
  681. 'playlist': info['playlist'],
  682. 'related': info['related_videos'],
  683. 'playability_error': info['playability_error'],
  684. },
  685. font_family = youtube.font_choices[settings.font], # for embed page
  686. **source_info,
  687. using_pair_sources = using_pair_sources,
  688. )
  689. @yt_app.route('/api/<path:dummy>')
  690. def get_captions(dummy):
  691. result = util.fetch_url('https://www.youtube.com' + request.full_path)
  692. result = result.replace(b"align:start position:0%", b"")
  693. return result
  694. times_reg = re.compile(r'^\d\d:\d\d:\d\d\.\d\d\d --> \d\d:\d\d:\d\d\.\d\d\d.*$')
  695. inner_timestamp_removal_reg = re.compile(r'<[^>]+>')
  696. @yt_app.route('/watch/transcript/<path:caption_path>')
  697. def get_transcript(caption_path):
  698. try:
  699. captions = util.fetch_url('https://www.youtube.com/'
  700. + caption_path
  701. + '?' + request.environ['QUERY_STRING']).decode('utf-8')
  702. except util.FetchError as e:
  703. msg = ('Error retrieving captions: ' + str(e) + '\n\n'
  704. + 'The caption url may have expired.')
  705. print(msg)
  706. return flask.Response(
  707. msg,
  708. status=e.code,
  709. mimetype='text/plain;charset=UTF-8')
  710. lines = captions.splitlines()
  711. segments = []
  712. # skip captions file header
  713. i = 0
  714. while lines[i] != '':
  715. i += 1
  716. current_segment = None
  717. while i < len(lines):
  718. line = lines[i]
  719. if line == '':
  720. if ((current_segment is not None)
  721. and (current_segment['begin'] is not None)):
  722. segments.append(current_segment)
  723. current_segment = {
  724. 'begin': None,
  725. 'end': None,
  726. 'lines': [],
  727. }
  728. elif times_reg.fullmatch(line.rstrip()):
  729. current_segment['begin'], current_segment['end'] = line.split(' --> ')
  730. else:
  731. current_segment['lines'].append(
  732. inner_timestamp_removal_reg.sub('', line))
  733. i += 1
  734. # if automatic captions, but not translated
  735. if request.args.get('kind') == 'asr' and not request.args.get('tlang'):
  736. # Automatic captions repeat content. The new segment is displayed
  737. # on the bottom row; the old one is displayed on the top row.
  738. # So grab the bottom row only
  739. for seg in segments:
  740. seg['text'] = seg['lines'][1]
  741. else:
  742. for seg in segments:
  743. seg['text'] = ' '.join(map(str.rstrip, seg['lines']))
  744. result = ''
  745. for seg in segments:
  746. if seg['text'] != ' ':
  747. result += seg['begin'] + ' ' + seg['text'] + '\r\n'
  748. return flask.Response(result.encode('utf-8'),
  749. mimetype='text/plain;charset=UTF-8')