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