watch.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  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. 'params': 'CgIIAdgDAQ==',
  288. })
  289. def fetch_watch_page_info(video_id, playlist_id, index):
  290. # bpctr=9999999999 will bypass are-you-sure dialogs for controversial
  291. # videos
  292. url = 'https://m.youtube.com/embed/' + video_id + '?bpctr=9999999999'
  293. if playlist_id:
  294. url += '&list=' + playlist_id
  295. if index:
  296. url += '&index=' + index
  297. headers = (
  298. ('Accept', '*/*'),
  299. ('Accept-Language', 'en-US,en;q=0.5'),
  300. ('X-YouTube-Client-Name', '2'),
  301. ('X-YouTube-Client-Version', '2.20180830'),
  302. ) + util.mobile_ua
  303. watch_page = util.fetch_url(url, headers=headers,
  304. debug_name='watch')
  305. watch_page = watch_page.decode('utf-8')
  306. return yt_data_extract.extract_watch_info_from_html(watch_page)
  307. def extract_info(video_id, use_invidious, playlist_id=None, index=None):
  308. tasks = (
  309. # Get video metadata from here
  310. gevent.spawn(fetch_watch_page_info, video_id, playlist_id, index),
  311. gevent.spawn(fetch_player_response, 'ios', video_id)
  312. )
  313. gevent.joinall(tasks)
  314. util.check_gevent_exceptions(*tasks)
  315. info, player_response = tasks[0].value, tasks[1].value
  316. yt_data_extract.update_with_new_urls(info, player_response)
  317. # Age restricted video, retry
  318. if info['age_restricted'] or info['player_urls_missing']:
  319. if info['age_restricted']:
  320. print('Age restricted video, retrying')
  321. else:
  322. print('Player urls missing, retrying')
  323. player_response = fetch_player_response('tv_embedded', video_id)
  324. yt_data_extract.update_with_new_urls(info, player_response)
  325. # signature decryption
  326. decryption_error = decrypt_signatures(info, video_id)
  327. if decryption_error:
  328. decryption_error = 'Error decrypting url signatures: ' + decryption_error
  329. info['playability_error'] = decryption_error
  330. # check if urls ready (non-live format) in former livestream
  331. # urls not ready if all of them have no filesize
  332. if info['was_live']:
  333. info['urls_ready'] = False
  334. for fmt in info['formats']:
  335. if fmt['file_size'] is not None:
  336. info['urls_ready'] = True
  337. else:
  338. info['urls_ready'] = True
  339. # livestream urls
  340. # sometimes only the livestream urls work soon after the livestream is over
  341. if (info['hls_manifest_url']
  342. and (info['live'] or not info['formats'] or not info['urls_ready'])
  343. ):
  344. manifest = util.fetch_url(info['hls_manifest_url'],
  345. debug_name='hls_manifest.m3u8',
  346. report_text='Fetched hls manifest'
  347. ).decode('utf-8')
  348. info['hls_formats'], err = yt_data_extract.extract_hls_formats(manifest)
  349. if not err:
  350. info['playability_error'] = None
  351. for fmt in info['hls_formats']:
  352. fmt['video_quality'] = video_quality_string(fmt)
  353. else:
  354. info['hls_formats'] = []
  355. # check for 403. Unnecessary for tor video routing b/c ip address is same
  356. info['invidious_used'] = False
  357. info['invidious_reload_button'] = False
  358. info['tor_bypass_used'] = False
  359. if (settings.route_tor == 1
  360. and info['formats'] and info['formats'][0]['url']):
  361. try:
  362. response = util.head(info['formats'][0]['url'],
  363. report_text='Checked for URL access')
  364. except urllib3.exceptions.HTTPError:
  365. print('Error while checking for URL access:\n')
  366. traceback.print_exc()
  367. return info
  368. if response.status == 403:
  369. print('Access denied (403) for video urls.')
  370. print('Routing video through Tor')
  371. info['tor_bypass_used'] = True
  372. for fmt in info['formats']:
  373. fmt['url'] += '&use_tor=1'
  374. elif 300 <= response.status < 400:
  375. print('Error: exceeded max redirects while checking video URL')
  376. return info
  377. def video_quality_string(format):
  378. if format['vcodec']:
  379. result = str(format['width'] or '?') + 'x' + str(format['height'] or '?')
  380. if format['fps']:
  381. result += ' ' + str(format['fps']) + 'fps'
  382. return result
  383. elif format['acodec']:
  384. return 'audio only'
  385. return '?'
  386. def short_video_quality_string(fmt):
  387. result = str(fmt['quality'] or '?') + 'p'
  388. if fmt['fps']:
  389. result += str(fmt['fps'])
  390. if fmt['vcodec'].startswith('av01'):
  391. result += ' AV1'
  392. elif fmt['vcodec'].startswith('avc'):
  393. result += ' h264'
  394. else:
  395. result += ' ' + fmt['vcodec']
  396. return result
  397. def audio_quality_string(fmt):
  398. if fmt['acodec']:
  399. if fmt['audio_bitrate']:
  400. result = '%d' % fmt['audio_bitrate'] + 'k'
  401. else:
  402. result = '?k'
  403. if fmt['audio_sample_rate']:
  404. result += ' ' + '%.3G' % (fmt['audio_sample_rate']/1000) + 'kHz'
  405. return result
  406. elif fmt['vcodec']:
  407. return 'video only'
  408. return '?'
  409. # from https://github.com/ytdl-org/youtube-dl/blob/master/youtube_dl/utils.py
  410. def format_bytes(bytes):
  411. if bytes is None:
  412. return 'N/A'
  413. if type(bytes) is str:
  414. bytes = float(bytes)
  415. if bytes == 0.0:
  416. exponent = 0
  417. else:
  418. exponent = int(math.log(bytes, 1024.0))
  419. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  420. converted = float(bytes) / float(1024 ** exponent)
  421. return '%.2f%s' % (converted, suffix)
  422. @yt_app.route('/ytl-api/storyboard.vtt')
  423. def get_storyboard_vtt():
  424. """
  425. See:
  426. https://github.com/iv-org/invidious/blob/9a8b81fcbe49ff8d88f197b7f731d6bf79fc8087/src/invidious.cr#L3603
  427. https://github.com/iv-org/invidious/blob/3bb7fbb2f119790ee6675076b31cd990f75f64bb/src/invidious/videos.cr#L623
  428. """
  429. spec_url = request.args.get('spec_url')
  430. url, *boards = spec_url.split('|')
  431. base_url, q = url.split('?')
  432. q = parse_qs(q) # for url query
  433. storyboard = None
  434. wanted_height = 90
  435. for i, board in enumerate(boards):
  436. *t, _, sigh = board.split("#")
  437. width, height, count, width_cnt, height_cnt, interval = map(int, t)
  438. if height != wanted_height: continue
  439. q['sigh'] = [sigh]
  440. url = f"{base_url}?{urlencode(q, doseq=True)}"
  441. storyboard = SimpleNamespace(
  442. url = url.replace("$L", str(i)).replace("$N", "M$M"),
  443. width = width,
  444. height = height,
  445. interval = interval,
  446. width_cnt = width_cnt,
  447. height_cnt = height_cnt,
  448. storyboard_count = ceil(count / (width_cnt * height_cnt))
  449. )
  450. if not storyboard:
  451. flask.abort(404)
  452. def to_ts(ms):
  453. s, ms = divmod(ms, 1000)
  454. h, s = divmod(s, 3600)
  455. m, s = divmod(s, 60)
  456. return f"{h:02}:{m:02}:{s:02}.{ms:03}"
  457. r = "WEBVTT" # result
  458. ts = 0 # current timestamp
  459. for i in range(storyboard.storyboard_count):
  460. url = '/' + storyboard.url.replace("$M", str(i))
  461. interval = storyboard.interval
  462. w, h = storyboard.width, storyboard.height
  463. w_cnt, h_cnt = storyboard.width_cnt, storyboard.height_cnt
  464. for j in range(h_cnt):
  465. for k in range(w_cnt):
  466. r += f"{to_ts(ts)} --> {to_ts(ts+interval)}\n"
  467. r += f"{url}#xywh={w * k},{h * j},{w},{h}\n\n"
  468. ts += interval
  469. return flask.Response(r, mimetype='text/vtt')
  470. time_table = {'h': 3600, 'm': 60, 's': 1}
  471. @yt_app.route('/watch')
  472. @yt_app.route('/embed')
  473. @yt_app.route('/embed/<video_id>')
  474. @yt_app.route('/shorts')
  475. @yt_app.route('/shorts/<video_id>')
  476. def get_watch_page(video_id=None):
  477. video_id = request.args.get('v') or video_id
  478. if not video_id:
  479. return flask.render_template('error.html', error_message='Missing video id'), 404
  480. if len(video_id) < 11:
  481. return flask.render_template('error.html', error_message='Incomplete video id (too short): ' + video_id), 404
  482. time_start_str = request.args.get('t', '0s')
  483. time_start = 0
  484. if re.fullmatch(r'(\d+(h|m|s))+', time_start_str):
  485. for match in re.finditer(r'(\d+)(h|m|s)', time_start_str):
  486. time_start += int(match.group(1))*time_table[match.group(2)]
  487. elif re.fullmatch(r'\d+', time_start_str):
  488. time_start = int(time_start_str)
  489. lc = request.args.get('lc', '')
  490. playlist_id = request.args.get('list')
  491. index = request.args.get('index')
  492. use_invidious = bool(int(request.args.get('use_invidious', '1')))
  493. if request.path.startswith('/embed') and settings.embed_page_mode:
  494. tasks = (
  495. gevent.spawn((lambda: {})),
  496. gevent.spawn(extract_info, video_id, use_invidious,
  497. playlist_id=playlist_id, index=index),
  498. )
  499. else:
  500. tasks = (
  501. gevent.spawn(comments.video_comments, video_id,
  502. int(settings.default_comment_sorting), lc=lc),
  503. gevent.spawn(extract_info, video_id, use_invidious,
  504. playlist_id=playlist_id, index=index),
  505. )
  506. gevent.joinall(tasks)
  507. util.check_gevent_exceptions(tasks[1])
  508. comments_info, info = tasks[0].value, tasks[1].value
  509. if info['error']:
  510. return flask.render_template('error.html', error_message=info['error'])
  511. video_info = {
  512. 'duration': util.seconds_to_timestamp(info['duration'] or 0),
  513. 'id': info['id'],
  514. 'title': info['title'],
  515. 'author': info['author'],
  516. 'author_id': info['author_id'],
  517. }
  518. # prefix urls, and other post-processing not handled by yt_data_extract
  519. for item in info['related_videos']:
  520. item['thumbnail'] = "https://i.ytimg.com/vi/{}/hqdefault.jpg".format(item['id']) # set HQ relateds thumbnail videos
  521. util.prefix_urls(item)
  522. util.add_extra_html_info(item)
  523. for song in info['music_list']:
  524. song['url'] = util.prefix_url(song['url'])
  525. if info['playlist']:
  526. playlist_id = info['playlist']['id']
  527. for item in info['playlist']['items']:
  528. util.prefix_urls(item)
  529. util.add_extra_html_info(item)
  530. if playlist_id:
  531. item['url'] += '&list=' + playlist_id
  532. if item['index']:
  533. item['url'] += '&index=' + str(item['index'])
  534. info['playlist']['author_url'] = util.prefix_url(
  535. info['playlist']['author_url'])
  536. if settings.img_prefix:
  537. # Don't prefix hls_formats for now because the urls inside the manifest
  538. # would need to be prefixed as well.
  539. for fmt in info['formats']:
  540. fmt['url'] = util.prefix_url(fmt['url'])
  541. # Add video title to end of url path so it has a filename other than just
  542. # "videoplayback" when downloaded
  543. title = urllib.parse.quote(util.to_valid_filename(info['title'] or ''))
  544. for fmt in info['formats']:
  545. filename = title
  546. ext = fmt.get('ext')
  547. if ext:
  548. filename += '.' + ext
  549. fmt['url'] = fmt['url'].replace(
  550. '/videoplayback',
  551. '/videoplayback/name/' + filename)
  552. if settings.gather_googlevideo_domains:
  553. with open(os.path.join(settings.data_dir, 'googlevideo-domains.txt'), 'a+', encoding='utf-8') as f:
  554. url = info['formats'][0]['url']
  555. subdomain = url[0:url.find(".googlevideo.com")]
  556. f.write(subdomain + "\n")
  557. download_formats = []
  558. for format in (info['formats'] + info['hls_formats']):
  559. if format['acodec'] and format['vcodec']:
  560. codecs_string = format['acodec'] + ', ' + format['vcodec']
  561. else:
  562. codecs_string = format['acodec'] or format['vcodec'] or '?'
  563. download_formats.append({
  564. 'url': format['url'],
  565. 'ext': format['ext'] or '?',
  566. 'audio_quality': audio_quality_string(format),
  567. 'video_quality': video_quality_string(format),
  568. 'file_size': format_bytes(format['file_size']),
  569. 'codecs': codecs_string,
  570. })
  571. if (settings.route_tor == 2) or info['tor_bypass_used']:
  572. target_resolution = 240
  573. else:
  574. target_resolution = settings.default_resolution
  575. source_info = get_video_sources(info, target_resolution)
  576. uni_sources = source_info['uni_sources']
  577. pair_sources = source_info['pair_sources']
  578. uni_idx, pair_idx = source_info['uni_idx'], source_info['pair_idx']
  579. pair_quality = yt_data_extract.deep_get(pair_sources, pair_idx, 'quality')
  580. uni_quality = yt_data_extract.deep_get(uni_sources, uni_idx, 'quality')
  581. pair_error = abs((pair_quality or 360) - target_resolution)
  582. uni_error = abs((uni_quality or 360) - target_resolution)
  583. if uni_error == pair_error:
  584. # use settings.prefer_uni_sources as a tiebreaker
  585. closer_to_target = 'uni' if settings.prefer_uni_sources else 'pair'
  586. elif uni_error < pair_error:
  587. closer_to_target = 'uni'
  588. else:
  589. closer_to_target = 'pair'
  590. if settings.prefer_uni_sources == 2:
  591. # Use uni sources unless there's no choice.
  592. using_pair_sources = (
  593. bool(pair_sources) and (not uni_sources)
  594. )
  595. else:
  596. # Use the pair sources if they're closer to the desired resolution
  597. using_pair_sources = (
  598. bool(pair_sources)
  599. and (not uni_sources or closer_to_target == 'pair')
  600. )
  601. if using_pair_sources:
  602. video_height = pair_sources[pair_idx]['height']
  603. video_width = pair_sources[pair_idx]['width']
  604. else:
  605. video_height = yt_data_extract.deep_get(
  606. uni_sources, uni_idx, 'height', default=360
  607. )
  608. video_width = yt_data_extract.deep_get(
  609. uni_sources, uni_idx, 'width', default=640
  610. )
  611. # 1 second per pixel, or the actual video width
  612. theater_video_target_width = max(640, info['duration'] or 0, video_width)
  613. # Check for false determination of disabled comments, which comes from
  614. # the watch page. But if we got comments in the separate request for those,
  615. # then the determination is wrong.
  616. if info['comments_disabled'] and comments_info.get('comments'):
  617. info['comments_disabled'] = False
  618. print('Warning: False determination that comments are disabled')
  619. print('Comment count:', info['comment_count'])
  620. info['comment_count'] = None # hack to make it obvious there's a bug
  621. # captions and transcript
  622. subtitle_sources = get_subtitle_sources(info)
  623. other_downloads = []
  624. for source in subtitle_sources:
  625. best_caption_parse = urllib.parse.urlparse(
  626. source['url'].lstrip('/'))
  627. transcript_url = (util.URL_ORIGIN
  628. + '/watch/transcript'
  629. + best_caption_parse.path
  630. + '?' + best_caption_parse.query)
  631. other_downloads.append({
  632. 'label': 'Video Transcript: ' + source['label'],
  633. 'ext': 'txt',
  634. 'url': transcript_url
  635. })
  636. if request.path.startswith('/embed') and settings.embed_page_mode:
  637. template_name = 'embed.html'
  638. else:
  639. template_name = 'watch.html'
  640. return flask.render_template(template_name,
  641. header_playlist_names = local_playlist.get_playlist_names(),
  642. uploader_channel_url = ('/' + info['author_url']) if info['author_url'] else '',
  643. time_published = info['time_published'],
  644. view_count = (lambda x: '{:,}'.format(x) if x is not None else "")(info.get("view_count", None)),
  645. like_count = (lambda x: '{:,}'.format(x) if x is not None else "")(info.get("like_count", None)),
  646. dislike_count = (lambda x: '{:,}'.format(x) if x is not None else "")(info.get("dislike_count", None)),
  647. download_formats = download_formats,
  648. other_downloads = other_downloads,
  649. video_info = json.dumps(video_info),
  650. hls_formats = info['hls_formats'],
  651. subtitle_sources = subtitle_sources,
  652. related = info['related_videos'],
  653. playlist = info['playlist'],
  654. music_list = info['music_list'],
  655. music_attributes = get_ordered_music_list_attributes(info['music_list']),
  656. comments_info = comments_info,
  657. comment_count = info['comment_count'],
  658. comments_disabled = info['comments_disabled'],
  659. video_height = video_height,
  660. video_width = video_width,
  661. theater_video_target_width = theater_video_target_width,
  662. title = info['title'],
  663. uploader = info['author'],
  664. description = info['description'],
  665. unlisted = info['unlisted'],
  666. limited_state = info['limited_state'],
  667. age_restricted = info['age_restricted'],
  668. live = info['live'],
  669. playability_error = info['playability_error'],
  670. allowed_countries = info['allowed_countries'],
  671. ip_address = info['ip_address'] if settings.route_tor else None,
  672. invidious_used = info['invidious_used'],
  673. invidious_reload_button = info['invidious_reload_button'],
  674. video_url = util.URL_ORIGIN + '/watch?v=' + video_id,
  675. video_id = video_id,
  676. storyboard_url = (util.URL_ORIGIN + '/ytl-api/storyboard.vtt?' +
  677. urlencode([('spec_url', info['storyboard_spec_url'])])
  678. if info['storyboard_spec_url'] else None),
  679. js_data = {
  680. 'video_id': info['id'],
  681. 'video_duration': info['duration'],
  682. 'settings': settings.current_settings_dict,
  683. 'has_manual_captions': any(s.get('on') for s in subtitle_sources),
  684. **source_info,
  685. 'using_pair_sources': using_pair_sources,
  686. 'time_start': time_start,
  687. 'playlist': info['playlist'],
  688. 'related': info['related_videos'],
  689. 'playability_error': info['playability_error'],
  690. },
  691. font_family = youtube.font_choices[settings.font], # for embed page
  692. **source_info,
  693. using_pair_sources = using_pair_sources,
  694. )
  695. @yt_app.route('/api/<path:dummy>')
  696. def get_captions(dummy):
  697. result = util.fetch_url('https://www.youtube.com' + request.full_path)
  698. result = result.replace(b"align:start position:0%", b"")
  699. return result
  700. times_reg = re.compile(r'^\d\d:\d\d:\d\d\.\d\d\d --> \d\d:\d\d:\d\d\.\d\d\d.*$')
  701. inner_timestamp_removal_reg = re.compile(r'<[^>]+>')
  702. @yt_app.route('/watch/transcript/<path:caption_path>')
  703. def get_transcript(caption_path):
  704. try:
  705. captions = util.fetch_url('https://www.youtube.com/'
  706. + caption_path
  707. + '?' + request.environ['QUERY_STRING']).decode('utf-8')
  708. except util.FetchError as e:
  709. msg = ('Error retrieving captions: ' + str(e) + '\n\n'
  710. + 'The caption url may have expired.')
  711. print(msg)
  712. return flask.Response(
  713. msg,
  714. status=e.code,
  715. mimetype='text/plain;charset=UTF-8')
  716. lines = captions.splitlines()
  717. segments = []
  718. # skip captions file header
  719. i = 0
  720. while lines[i] != '':
  721. i += 1
  722. current_segment = None
  723. while i < len(lines):
  724. line = lines[i]
  725. if line == '':
  726. if ((current_segment is not None)
  727. and (current_segment['begin'] is not None)):
  728. segments.append(current_segment)
  729. current_segment = {
  730. 'begin': None,
  731. 'end': None,
  732. 'lines': [],
  733. }
  734. elif times_reg.fullmatch(line.rstrip()):
  735. current_segment['begin'], current_segment['end'] = line.split(' --> ')
  736. else:
  737. current_segment['lines'].append(
  738. inner_timestamp_removal_reg.sub('', line))
  739. i += 1
  740. # if automatic captions, but not translated
  741. if request.args.get('kind') == 'asr' and not request.args.get('tlang'):
  742. # Automatic captions repeat content. The new segment is displayed
  743. # on the bottom row; the old one is displayed on the top row.
  744. # So grab the bottom row only
  745. for seg in segments:
  746. seg['text'] = seg['lines'][1]
  747. else:
  748. for seg in segments:
  749. seg['text'] = ' '.join(map(str.rstrip, seg['lines']))
  750. result = ''
  751. for seg in segments:
  752. if seg['text'] != ' ':
  753. result += seg['begin'] + ' ' + seg['text'] + '\r\n'
  754. return flask.Response(result.encode('utf-8'),
  755. mimetype='text/plain;charset=UTF-8')