Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

3487 řádky
154KB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import itertools
  4. import json
  5. import os.path
  6. import random
  7. import re
  8. import time
  9. import traceback
  10. from .common import InfoExtractor, SearchInfoExtractor
  11. from ..jsinterp import JSInterpreter
  12. from ..swfinterp import SWFInterpreter
  13. from ..compat import (
  14. compat_chr,
  15. compat_HTTPError,
  16. compat_kwargs,
  17. compat_parse_qs,
  18. compat_urllib_parse_unquote,
  19. compat_urllib_parse_unquote_plus,
  20. compat_urllib_parse_urlencode,
  21. compat_urllib_parse_urlparse,
  22. compat_urlparse,
  23. compat_str,
  24. )
  25. from ..utils import (
  26. bool_or_none,
  27. clean_html,
  28. error_to_compat_str,
  29. extract_attributes,
  30. ExtractorError,
  31. float_or_none,
  32. get_element_by_attribute,
  33. get_element_by_id,
  34. int_or_none,
  35. mimetype2ext,
  36. orderedSet,
  37. parse_codecs,
  38. parse_duration,
  39. remove_quotes,
  40. remove_start,
  41. smuggle_url,
  42. str_or_none,
  43. str_to_int,
  44. try_get,
  45. unescapeHTML,
  46. unified_strdate,
  47. unsmuggle_url,
  48. uppercase_escape,
  49. url_or_none,
  50. urlencode_postdata,
  51. )
  52. class YoutubeBaseInfoExtractor(InfoExtractor):
  53. """Provide base functions for Youtube extractors"""
  54. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  55. _TWOFACTOR_URL = 'https://accounts.google.com/signin/challenge'
  56. _LOOKUP_URL = 'https://accounts.google.com/_/signin/sl/lookup'
  57. _CHALLENGE_URL = 'https://accounts.google.com/_/signin/sl/challenge'
  58. _TFA_URL = 'https://accounts.google.com/_/signin/challenge?hl=en&TL={0}'
  59. _NETRC_MACHINE = 'youtube'
  60. # If True it will raise an error if no login info is provided
  61. _LOGIN_REQUIRED = False
  62. _PLAYLIST_ID_RE = r'(?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,}'
  63. _YOUTUBE_CLIENT_HEADERS = {
  64. 'x-youtube-client-name': '1',
  65. 'x-youtube-client-version': '1.20200609.04.02',
  66. }
  67. def _set_language(self):
  68. self._set_cookie(
  69. '.youtube.com', 'PREF', 'f1=50000000&f6=8&hl=en',
  70. # YouTube sets the expire time to about two months
  71. expire_time=time.time() + 2 * 30 * 24 * 3600)
  72. def _ids_to_results(self, ids):
  73. return [
  74. self.url_result(vid_id, 'Youtube', video_id=vid_id)
  75. for vid_id in ids]
  76. def _login(self):
  77. """
  78. Attempt to log in to YouTube.
  79. True is returned if successful or skipped.
  80. False is returned if login failed.
  81. If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
  82. """
  83. username, password = self._get_login_info()
  84. # No authentication to be performed
  85. if username is None:
  86. if self._LOGIN_REQUIRED and self._downloader.params.get('cookiefile') is None:
  87. raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  88. return True
  89. login_page = self._download_webpage(
  90. self._LOGIN_URL, None,
  91. note='Downloading login page',
  92. errnote='unable to fetch login page', fatal=False)
  93. if login_page is False:
  94. return
  95. login_form = self._hidden_inputs(login_page)
  96. def req(url, f_req, note, errnote):
  97. data = login_form.copy()
  98. data.update({
  99. 'pstMsg': 1,
  100. 'checkConnection': 'youtube',
  101. 'checkedDomains': 'youtube',
  102. 'hl': 'en',
  103. 'deviceinfo': '[null,null,null,[],null,"US",null,null,[],"GlifWebSignIn",null,[null,null,[]]]',
  104. 'f.req': json.dumps(f_req),
  105. 'flowName': 'GlifWebSignIn',
  106. 'flowEntry': 'ServiceLogin',
  107. # TODO: reverse actual botguard identifier generation algo
  108. 'bgRequest': '["identifier",""]',
  109. })
  110. return self._download_json(
  111. url, None, note=note, errnote=errnote,
  112. transform_source=lambda s: re.sub(r'^[^[]*', '', s),
  113. fatal=False,
  114. data=urlencode_postdata(data), headers={
  115. 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
  116. 'Google-Accounts-XSRF': 1,
  117. })
  118. def warn(message):
  119. self._downloader.report_warning(message)
  120. lookup_req = [
  121. username,
  122. None, [], None, 'US', None, None, 2, False, True,
  123. [
  124. None, None,
  125. [2, 1, None, 1,
  126. 'https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3D%252F%26action_handle_signin%3Dtrue%26hl%3Den%26app%3Ddesktop%26feature%3Dsign_in_button&hl=en&service=youtube&uilel=3&requestPath=%2FServiceLogin&Page=PasswordSeparationSignIn',
  127. None, [], 4],
  128. 1, [None, None, []], None, None, None, True
  129. ],
  130. username,
  131. ]
  132. lookup_results = req(
  133. self._LOOKUP_URL, lookup_req,
  134. 'Looking up account info', 'Unable to look up account info')
  135. if lookup_results is False:
  136. return False
  137. user_hash = try_get(lookup_results, lambda x: x[0][2], compat_str)
  138. if not user_hash:
  139. warn('Unable to extract user hash')
  140. return False
  141. challenge_req = [
  142. user_hash,
  143. None, 1, None, [1, None, None, None, [password, None, True]],
  144. [
  145. None, None, [2, 1, None, 1, 'https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3D%252F%26action_handle_signin%3Dtrue%26hl%3Den%26app%3Ddesktop%26feature%3Dsign_in_button&hl=en&service=youtube&uilel=3&requestPath=%2FServiceLogin&Page=PasswordSeparationSignIn', None, [], 4],
  146. 1, [None, None, []], None, None, None, True
  147. ]]
  148. challenge_results = req(
  149. self._CHALLENGE_URL, challenge_req,
  150. 'Logging in', 'Unable to log in')
  151. if challenge_results is False:
  152. return
  153. login_res = try_get(challenge_results, lambda x: x[0][5], list)
  154. if login_res:
  155. login_msg = try_get(login_res, lambda x: x[5], compat_str)
  156. warn(
  157. 'Unable to login: %s' % 'Invalid password'
  158. if login_msg == 'INCORRECT_ANSWER_ENTERED' else login_msg)
  159. return False
  160. res = try_get(challenge_results, lambda x: x[0][-1], list)
  161. if not res:
  162. warn('Unable to extract result entry')
  163. return False
  164. login_challenge = try_get(res, lambda x: x[0][0], list)
  165. if login_challenge:
  166. challenge_str = try_get(login_challenge, lambda x: x[2], compat_str)
  167. if challenge_str == 'TWO_STEP_VERIFICATION':
  168. # SEND_SUCCESS - TFA code has been successfully sent to phone
  169. # QUOTA_EXCEEDED - reached the limit of TFA codes
  170. status = try_get(login_challenge, lambda x: x[5], compat_str)
  171. if status == 'QUOTA_EXCEEDED':
  172. warn('Exceeded the limit of TFA codes, try later')
  173. return False
  174. tl = try_get(challenge_results, lambda x: x[1][2], compat_str)
  175. if not tl:
  176. warn('Unable to extract TL')
  177. return False
  178. tfa_code = self._get_tfa_info('2-step verification code')
  179. if not tfa_code:
  180. warn(
  181. 'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
  182. '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
  183. return False
  184. tfa_code = remove_start(tfa_code, 'G-')
  185. tfa_req = [
  186. user_hash, None, 2, None,
  187. [
  188. 9, None, None, None, None, None, None, None,
  189. [None, tfa_code, True, 2]
  190. ]]
  191. tfa_results = req(
  192. self._TFA_URL.format(tl), tfa_req,
  193. 'Submitting TFA code', 'Unable to submit TFA code')
  194. if tfa_results is False:
  195. return False
  196. tfa_res = try_get(tfa_results, lambda x: x[0][5], list)
  197. if tfa_res:
  198. tfa_msg = try_get(tfa_res, lambda x: x[5], compat_str)
  199. warn(
  200. 'Unable to finish TFA: %s' % 'Invalid TFA code'
  201. if tfa_msg == 'INCORRECT_ANSWER_ENTERED' else tfa_msg)
  202. return False
  203. check_cookie_url = try_get(
  204. tfa_results, lambda x: x[0][-1][2], compat_str)
  205. else:
  206. CHALLENGES = {
  207. 'LOGIN_CHALLENGE': "This device isn't recognized. For your security, Google wants to make sure it's really you.",
  208. 'USERNAME_RECOVERY': 'Please provide additional information to aid in the recovery process.',
  209. 'REAUTH': "There is something unusual about your activity. For your security, Google wants to make sure it's really you.",
  210. }
  211. challenge = CHALLENGES.get(
  212. challenge_str,
  213. '%s returned error %s.' % (self.IE_NAME, challenge_str))
  214. warn('%s\nGo to https://accounts.google.com/, login and solve a challenge.' % challenge)
  215. return False
  216. else:
  217. check_cookie_url = try_get(res, lambda x: x[2], compat_str)
  218. if not check_cookie_url:
  219. warn('Unable to extract CheckCookie URL')
  220. return False
  221. check_cookie_results = self._download_webpage(
  222. check_cookie_url, None, 'Checking cookie', fatal=False)
  223. if check_cookie_results is False:
  224. return False
  225. if 'https://myaccount.google.com/' not in check_cookie_results:
  226. warn('Unable to log in')
  227. return False
  228. return True
  229. def _download_webpage_handle(self, *args, **kwargs):
  230. query = kwargs.get('query', {}).copy()
  231. query['disable_polymer'] = 'true'
  232. kwargs['query'] = query
  233. return super(YoutubeBaseInfoExtractor, self)._download_webpage_handle(
  234. *args, **compat_kwargs(kwargs))
  235. def _real_initialize(self):
  236. if self._downloader is None:
  237. return
  238. self._set_language()
  239. if not self._login():
  240. return
  241. class YoutubeEntryListBaseInfoExtractor(YoutubeBaseInfoExtractor):
  242. # Extract entries from page with "Load more" button
  243. def _entries(self, page, playlist_id):
  244. more_widget_html = content_html = page
  245. for page_num in itertools.count(1):
  246. for entry in self._process_page(content_html):
  247. yield entry
  248. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  249. if not mobj:
  250. break
  251. count = 0
  252. retries = 3
  253. while count <= retries:
  254. try:
  255. # Downloading page may result in intermittent 5xx HTTP error
  256. # that is usually worked around with a retry
  257. more = self._download_json(
  258. 'https://www.youtube.com/%s' % mobj.group('more'), playlist_id,
  259. 'Downloading page #%s%s'
  260. % (page_num, ' (retry #%d)' % count if count else ''),
  261. transform_source=uppercase_escape,
  262. headers=self._YOUTUBE_CLIENT_HEADERS)
  263. break
  264. except ExtractorError as e:
  265. if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503):
  266. count += 1
  267. if count <= retries:
  268. continue
  269. raise
  270. content_html = more['content_html']
  271. if not content_html.strip():
  272. # Some webpages show a "Load more" button but they don't
  273. # have more videos
  274. break
  275. more_widget_html = more['load_more_widget_html']
  276. class YoutubePlaylistBaseInfoExtractor(YoutubeEntryListBaseInfoExtractor):
  277. def _process_page(self, content):
  278. for video_id, video_title in self.extract_videos_from_page(content):
  279. yield self.url_result(video_id, 'Youtube', video_id, video_title)
  280. def extract_videos_from_page_impl(self, video_re, page, ids_in_page, titles_in_page):
  281. for mobj in re.finditer(video_re, page):
  282. # The link with index 0 is not the first video of the playlist (not sure if still actual)
  283. if 'index' in mobj.groupdict() and mobj.group('id') == '0':
  284. continue
  285. video_id = mobj.group('id')
  286. video_title = unescapeHTML(
  287. mobj.group('title')) if 'title' in mobj.groupdict() else None
  288. if video_title:
  289. video_title = video_title.strip()
  290. if video_title == '► Play all':
  291. video_title = None
  292. try:
  293. idx = ids_in_page.index(video_id)
  294. if video_title and not titles_in_page[idx]:
  295. titles_in_page[idx] = video_title
  296. except ValueError:
  297. ids_in_page.append(video_id)
  298. titles_in_page.append(video_title)
  299. def extract_videos_from_page(self, page):
  300. ids_in_page = []
  301. titles_in_page = []
  302. self.extract_videos_from_page_impl(
  303. self._VIDEO_RE, page, ids_in_page, titles_in_page)
  304. return zip(ids_in_page, titles_in_page)
  305. class YoutubePlaylistsBaseInfoExtractor(YoutubeEntryListBaseInfoExtractor):
  306. def _process_page(self, content):
  307. for playlist_id in orderedSet(re.findall(
  308. r'<h3[^>]+class="[^"]*yt-lockup-title[^"]*"[^>]*><a[^>]+href="/?playlist\?list=([0-9A-Za-z-_]{10,})"',
  309. content)):
  310. yield self.url_result(
  311. 'https://www.youtube.com/playlist?list=%s' % playlist_id, 'YoutubePlaylist')
  312. def _real_extract(self, url):
  313. playlist_id = self._match_id(url)
  314. webpage = self._download_webpage(url, playlist_id)
  315. title = self._og_search_title(webpage, fatal=False)
  316. return self.playlist_result(self._entries(webpage, playlist_id), playlist_id, title)
  317. class YoutubeIE(YoutubeBaseInfoExtractor):
  318. IE_DESC = 'YouTube.com'
  319. _VALID_URL = r"""(?x)^
  320. (
  321. (?:https?://|//) # http(s):// or protocol-independent URL
  322. (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com/|
  323. (?:www\.)?deturl\.com/www\.youtube\.com/|
  324. (?:www\.)?pwnyoutube\.com/|
  325. (?:www\.)?hooktube\.com/|
  326. (?:www\.)?yourepeat\.com/|
  327. tube\.majestyc\.net/|
  328. # Invidious instances taken from https://github.com/omarroth/invidious/wiki/Invidious-Instances
  329. (?:(?:www|dev)\.)?invidio\.us/|
  330. (?:(?:www|no)\.)?invidiou\.sh/|
  331. (?:(?:www|fi|de)\.)?invidious\.snopyta\.org/|
  332. (?:www\.)?invidious\.kabi\.tk/|
  333. (?:www\.)?invidious\.13ad\.de/|
  334. (?:www\.)?invidious\.mastodon\.host/|
  335. (?:www\.)?invidious\.nixnet\.xyz/|
  336. (?:www\.)?invidious\.drycat\.fr/|
  337. (?:www\.)?tube\.poal\.co/|
  338. (?:www\.)?vid\.wxzm\.sx/|
  339. (?:www\.)?yewtu\.be/|
  340. (?:www\.)?yt\.elukerio\.org/|
  341. (?:www\.)?yt\.lelux\.fi/|
  342. (?:www\.)?invidious\.ggc-project\.de/|
  343. (?:www\.)?yt\.maisputain\.ovh/|
  344. (?:www\.)?invidious\.13ad\.de/|
  345. (?:www\.)?invidious\.toot\.koeln/|
  346. (?:www\.)?invidious\.fdn\.fr/|
  347. (?:www\.)?watch\.nettohikari\.com/|
  348. (?:www\.)?kgg2m7yk5aybusll\.onion/|
  349. (?:www\.)?qklhadlycap4cnod\.onion/|
  350. (?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion/|
  351. (?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion/|
  352. (?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion/|
  353. (?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion/|
  354. (?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p/|
  355. (?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion/|
  356. youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
  357. (?:.*?\#/)? # handle anchor (#/) redirect urls
  358. (?: # the various things that can precede the ID:
  359. (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
  360. |(?: # or the v= param in all its forms
  361. (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  362. (?:\?|\#!?) # the params delimiter ? or # or #!
  363. (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&amp;v=V36LpHqtcDY)
  364. v=
  365. )
  366. ))
  367. |(?:
  368. youtu\.be| # just youtu.be/xxxx
  369. vid\.plus| # or vid.plus/xxxx
  370. zwearz\.com/watch| # or zwearz.com/watch/xxxx
  371. )/
  372. |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
  373. )
  374. )? # all until now is optional -> you can pass the naked ID
  375. ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  376. (?!.*?\blist=
  377. (?:
  378. %(playlist_id)s| # combined list/video URLs are handled by the playlist IE
  379. WL # WL are handled by the watch later IE
  380. )
  381. )
  382. (?(1).+)? # if we found the ID, everything can follow
  383. $""" % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
  384. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  385. _PLAYER_INFO_RE = (
  386. r'/(?P<id>[a-zA-Z0-9_-]{8,})/player_ias\.vflset(?:/[a-zA-Z]{2,3}_[a-zA-Z]{2,3})?/base\.(?P<ext>[a-z]+)$',
  387. r'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.(?P<ext>[a-z]+)$',
  388. )
  389. _formats = {
  390. '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
  391. '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
  392. '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'},
  393. '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'},
  394. '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'},
  395. '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  396. '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  397. '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  398. # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
  399. '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'},
  400. '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  401. '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  402. '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
  403. '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
  404. '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
  405. '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
  406. '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  407. '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  408. # 3D videos
  409. '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
  410. '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
  411. '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
  412. '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
  413. '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20},
  414. '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
  415. '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
  416. # Apple HTTP Live Streaming
  417. '91': {'ext': 'mp4', 'height': 144, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  418. '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  419. '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
  420. '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
  421. '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
  422. '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
  423. '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  424. '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10},
  425. # DASH mp4 video
  426. '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264'},
  427. '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264'},
  428. '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
  429. '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264'},
  430. '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264'},
  431. '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264'}, # Height can vary (https://github.com/ytdl-org/youtube-dl/issues/4559)
  432. '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264'},
  433. '212': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
  434. '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264'},
  435. '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
  436. '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
  437. '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264'},
  438. # Dash mp4 audio
  439. '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'container': 'm4a_dash'},
  440. '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'container': 'm4a_dash'},
  441. '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'container': 'm4a_dash'},
  442. '256': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
  443. '258': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
  444. '325': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'dtse', 'container': 'm4a_dash'},
  445. '328': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'ec-3', 'container': 'm4a_dash'},
  446. # Dash webm
  447. '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  448. '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  449. '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  450. '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  451. '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  452. '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  453. '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9'},
  454. '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  455. '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  456. '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  457. '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  458. '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  459. '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  460. '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  461. '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  462. # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
  463. '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  464. '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  465. '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  466. '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  467. '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  468. '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  469. # Dash webm audio
  470. '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128},
  471. '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256},
  472. # Dash webm audio with opus inside
  473. '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50},
  474. '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70},
  475. '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160},
  476. # RTMP (unnamed)
  477. '_rtmp': {'protocol': 'rtmp'},
  478. # av01 video only formats sometimes served with "unknown" codecs
  479. '394': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  480. '395': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  481. '396': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  482. '397': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  483. }
  484. _SUBTITLE_FORMATS = ('srv1', 'srv2', 'srv3', 'ttml', 'vtt')
  485. _GEO_BYPASS = False
  486. IE_NAME = 'youtube'
  487. _TESTS = [
  488. {
  489. 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
  490. 'info_dict': {
  491. 'id': 'BaW_jenozKc',
  492. 'ext': 'mp4',
  493. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  494. 'uploader': 'Philipp Hagemeister',
  495. 'uploader_id': 'phihag',
  496. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
  497. 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
  498. 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
  499. 'upload_date': '20121002',
  500. 'description': 'test chars: "\'/\\ä↭𝕐\ntest URL: https://github.com/rg3/youtube-dl/issues/1892\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de .',
  501. 'categories': ['Science & Technology'],
  502. 'tags': ['youtube-dl'],
  503. 'duration': 10,
  504. 'view_count': int,
  505. 'like_count': int,
  506. 'dislike_count': int,
  507. 'start_time': 1,
  508. 'end_time': 9,
  509. }
  510. },
  511. {
  512. 'url': 'https://www.youtube.com/watch?v=UxxajLWwzqY',
  513. 'note': 'Test generic use_cipher_signature video (#897)',
  514. 'info_dict': {
  515. 'id': 'UxxajLWwzqY',
  516. 'ext': 'mp4',
  517. 'upload_date': '20120506',
  518. 'title': 'Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]',
  519. 'alt_title': 'I Love It (feat. Charli XCX)',
  520. 'description': 'md5:19a2f98d9032b9311e686ed039564f63',
  521. 'tags': ['Icona Pop i love it', 'sweden', 'pop music', 'big beat records', 'big beat', 'charli',
  522. 'xcx', 'charli xcx', 'girls', 'hbo', 'i love it', "i don't care", 'icona', 'pop',
  523. 'iconic ep', 'iconic', 'love', 'it'],
  524. 'duration': 180,
  525. 'uploader': 'Icona Pop',
  526. 'uploader_id': 'IconaPop',
  527. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/IconaPop',
  528. 'creator': 'Icona Pop',
  529. 'track': 'I Love It (feat. Charli XCX)',
  530. 'artist': 'Icona Pop',
  531. }
  532. },
  533. {
  534. 'url': 'https://www.youtube.com/watch?v=07FYdnEawAQ',
  535. 'note': 'Test VEVO video with age protection (#956)',
  536. 'info_dict': {
  537. 'id': '07FYdnEawAQ',
  538. 'ext': 'mp4',
  539. 'upload_date': '20130703',
  540. 'title': 'Justin Timberlake - Tunnel Vision (Official Music Video) (Explicit)',
  541. 'alt_title': 'Tunnel Vision',
  542. 'description': 'md5:07dab3356cde4199048e4c7cd93471e1',
  543. 'duration': 419,
  544. 'uploader': 'justintimberlakeVEVO',
  545. 'uploader_id': 'justintimberlakeVEVO',
  546. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/justintimberlakeVEVO',
  547. 'creator': 'Justin Timberlake',
  548. 'track': 'Tunnel Vision',
  549. 'artist': 'Justin Timberlake',
  550. 'age_limit': 18,
  551. }
  552. },
  553. {
  554. 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
  555. 'note': 'Embed-only video (#1746)',
  556. 'info_dict': {
  557. 'id': 'yZIXLfi8CZQ',
  558. 'ext': 'mp4',
  559. 'upload_date': '20120608',
  560. 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
  561. 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
  562. 'uploader': 'SET India',
  563. 'uploader_id': 'setindia',
  564. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/setindia',
  565. 'age_limit': 18,
  566. }
  567. },
  568. {
  569. 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=UxxajLWwzqY',
  570. 'note': 'Use the first video ID in the URL',
  571. 'info_dict': {
  572. 'id': 'BaW_jenozKc',
  573. 'ext': 'mp4',
  574. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  575. 'uploader': 'Philipp Hagemeister',
  576. 'uploader_id': 'phihag',
  577. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
  578. 'upload_date': '20121002',
  579. 'description': 'test chars: "\'/\\ä↭𝕐\ntest URL: https://github.com/rg3/youtube-dl/issues/1892\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de .',
  580. 'categories': ['Science & Technology'],
  581. 'tags': ['youtube-dl'],
  582. 'duration': 10,
  583. 'view_count': int,
  584. 'like_count': int,
  585. 'dislike_count': int,
  586. },
  587. 'params': {
  588. 'skip_download': True,
  589. },
  590. },
  591. {
  592. 'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
  593. 'note': '256k DASH audio (format 141) via DASH manifest',
  594. 'info_dict': {
  595. 'id': 'a9LDPn-MO4I',
  596. 'ext': 'm4a',
  597. 'upload_date': '20121002',
  598. 'uploader_id': '8KVIDEO',
  599. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/8KVIDEO',
  600. 'description': '',
  601. 'uploader': '8KVIDEO',
  602. 'title': 'UHDTV TEST 8K VIDEO.mp4'
  603. },
  604. 'params': {
  605. 'youtube_include_dash_manifest': True,
  606. 'format': '141',
  607. },
  608. 'skip': 'format 141 not served anymore',
  609. },
  610. # DASH manifest with encrypted signature
  611. {
  612. 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
  613. 'info_dict': {
  614. 'id': 'IB3lcPjvWLA',
  615. 'ext': 'm4a',
  616. 'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
  617. 'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
  618. 'duration': 244,
  619. 'uploader': 'AfrojackVEVO',
  620. 'uploader_id': 'AfrojackVEVO',
  621. 'upload_date': '20131011',
  622. },
  623. 'params': {
  624. 'youtube_include_dash_manifest': True,
  625. 'format': '141/bestaudio[ext=m4a]',
  626. },
  627. },
  628. # JS player signature function name containing $
  629. {
  630. 'url': 'https://www.youtube.com/watch?v=nfWlot6h_JM',
  631. 'info_dict': {
  632. 'id': 'nfWlot6h_JM',
  633. 'ext': 'm4a',
  634. 'title': 'Taylor Swift - Shake It Off',
  635. 'description': 'md5:307195cd21ff7fa352270fe884570ef0',
  636. 'duration': 242,
  637. 'uploader': 'TaylorSwiftVEVO',
  638. 'uploader_id': 'TaylorSwiftVEVO',
  639. 'upload_date': '20140818',
  640. },
  641. 'params': {
  642. 'youtube_include_dash_manifest': True,
  643. 'format': '141/bestaudio[ext=m4a]',
  644. },
  645. },
  646. # Controversy video
  647. {
  648. 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
  649. 'info_dict': {
  650. 'id': 'T4XJQO3qol8',
  651. 'ext': 'mp4',
  652. 'duration': 219,
  653. 'upload_date': '20100909',
  654. 'uploader': 'Amazing Atheist',
  655. 'uploader_id': 'TheAmazingAtheist',
  656. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheAmazingAtheist',
  657. 'title': 'Burning Everyone\'s Koran',
  658. 'description': 'SUBSCRIBE: http://www.youtube.com/saturninefilms\n\nEven Obama has taken a stand against freedom on this issue: http://www.huffingtonpost.com/2010/09/09/obama-gma-interview-quran_n_710282.html',
  659. }
  660. },
  661. # Normal age-gate video (No vevo, embed allowed)
  662. {
  663. 'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
  664. 'info_dict': {
  665. 'id': 'HtVdAasjOgU',
  666. 'ext': 'mp4',
  667. 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
  668. 'description': r're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
  669. 'duration': 142,
  670. 'uploader': 'The Witcher',
  671. 'uploader_id': 'WitcherGame',
  672. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/WitcherGame',
  673. 'upload_date': '20140605',
  674. 'age_limit': 18,
  675. },
  676. },
  677. # Age-gate video with encrypted signature
  678. {
  679. 'url': 'https://www.youtube.com/watch?v=6kLq3WMV1nU',
  680. 'info_dict': {
  681. 'id': '6kLq3WMV1nU',
  682. 'ext': 'mp4',
  683. 'title': 'Dedication To My Ex (Miss That) (Lyric Video)',
  684. 'description': 'md5:33765bb339e1b47e7e72b5490139bb41',
  685. 'duration': 246,
  686. 'uploader': 'LloydVEVO',
  687. 'uploader_id': 'LloydVEVO',
  688. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/LloydVEVO',
  689. 'upload_date': '20110629',
  690. 'age_limit': 18,
  691. },
  692. },
  693. # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
  694. # YouTube Red ad is not captured for creator
  695. {
  696. 'url': '__2ABJjxzNo',
  697. 'info_dict': {
  698. 'id': '__2ABJjxzNo',
  699. 'ext': 'mp4',
  700. 'duration': 266,
  701. 'upload_date': '20100430',
  702. 'uploader_id': 'deadmau5',
  703. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/deadmau5',
  704. 'creator': 'Dada Life, deadmau5',
  705. 'description': 'md5:12c56784b8032162bb936a5f76d55360',
  706. 'uploader': 'deadmau5',
  707. 'title': 'Deadmau5 - Some Chords (HD)',
  708. 'alt_title': 'This Machine Kills Some Chords',
  709. },
  710. 'expected_warnings': [
  711. 'DASH manifest missing',
  712. ]
  713. },
  714. # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
  715. {
  716. 'url': 'lqQg6PlCWgI',
  717. 'info_dict': {
  718. 'id': 'lqQg6PlCWgI',
  719. 'ext': 'mp4',
  720. 'duration': 6085,
  721. 'upload_date': '20150827',
  722. 'uploader_id': 'olympic',
  723. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/olympic',
  724. 'description': 'HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
  725. 'uploader': 'Olympic',
  726. 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
  727. },
  728. 'params': {
  729. 'skip_download': 'requires avconv',
  730. }
  731. },
  732. # Non-square pixels
  733. {
  734. 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
  735. 'info_dict': {
  736. 'id': '_b-2C3KPAM0',
  737. 'ext': 'mp4',
  738. 'stretched_ratio': 16 / 9.,
  739. 'duration': 85,
  740. 'upload_date': '20110310',
  741. 'uploader_id': 'AllenMeow',
  742. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/AllenMeow',
  743. 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
  744. 'uploader': '孫ᄋᄅ',
  745. 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
  746. },
  747. },
  748. # url_encoded_fmt_stream_map is empty string
  749. {
  750. 'url': 'qEJwOuvDf7I',
  751. 'info_dict': {
  752. 'id': 'qEJwOuvDf7I',
  753. 'ext': 'webm',
  754. 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
  755. 'description': '',
  756. 'upload_date': '20150404',
  757. 'uploader_id': 'spbelect',
  758. 'uploader': 'Наблюдатели Петербурга',
  759. },
  760. 'params': {
  761. 'skip_download': 'requires avconv',
  762. },
  763. 'skip': 'This live event has ended.',
  764. },
  765. # Extraction from multiple DASH manifests (https://github.com/ytdl-org/youtube-dl/pull/6097)
  766. {
  767. 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
  768. 'info_dict': {
  769. 'id': 'FIl7x6_3R5Y',
  770. 'ext': 'webm',
  771. 'title': 'md5:7b81415841e02ecd4313668cde88737a',
  772. 'description': 'md5:116377fd2963b81ec4ce64b542173306',
  773. 'duration': 220,
  774. 'upload_date': '20150625',
  775. 'uploader_id': 'dorappi2000',
  776. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/dorappi2000',
  777. 'uploader': 'dorappi2000',
  778. 'formats': 'mincount:31',
  779. },
  780. 'skip': 'not actual anymore',
  781. },
  782. # DASH manifest with segment_list
  783. {
  784. 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
  785. 'md5': '8ce563a1d667b599d21064e982ab9e31',
  786. 'info_dict': {
  787. 'id': 'CsmdDsKjzN8',
  788. 'ext': 'mp4',
  789. 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
  790. 'uploader': 'Airtek',
  791. 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
  792. 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
  793. 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
  794. },
  795. 'params': {
  796. 'youtube_include_dash_manifest': True,
  797. 'format': '135', # bestvideo
  798. },
  799. 'skip': 'This live event has ended.',
  800. },
  801. {
  802. # Multifeed videos (multiple cameras), URL is for Main Camera
  803. 'url': 'https://www.youtube.com/watch?v=jqWvoWXjCVs',
  804. 'info_dict': {
  805. 'id': 'jqWvoWXjCVs',
  806. 'title': 'teamPGP: Rocket League Noob Stream',
  807. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  808. },
  809. 'playlist': [{
  810. 'info_dict': {
  811. 'id': 'jqWvoWXjCVs',
  812. 'ext': 'mp4',
  813. 'title': 'teamPGP: Rocket League Noob Stream (Main Camera)',
  814. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  815. 'duration': 7335,
  816. 'upload_date': '20150721',
  817. 'uploader': 'Beer Games Beer',
  818. 'uploader_id': 'beergamesbeer',
  819. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
  820. 'license': 'Standard YouTube License',
  821. },
  822. }, {
  823. 'info_dict': {
  824. 'id': '6h8e8xoXJzg',
  825. 'ext': 'mp4',
  826. 'title': 'teamPGP: Rocket League Noob Stream (kreestuh)',
  827. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  828. 'duration': 7337,
  829. 'upload_date': '20150721',
  830. 'uploader': 'Beer Games Beer',
  831. 'uploader_id': 'beergamesbeer',
  832. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
  833. 'license': 'Standard YouTube License',
  834. },
  835. }, {
  836. 'info_dict': {
  837. 'id': 'PUOgX5z9xZw',
  838. 'ext': 'mp4',
  839. 'title': 'teamPGP: Rocket League Noob Stream (grizzle)',
  840. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  841. 'duration': 7337,
  842. 'upload_date': '20150721',
  843. 'uploader': 'Beer Games Beer',
  844. 'uploader_id': 'beergamesbeer',
  845. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
  846. 'license': 'Standard YouTube License',
  847. },
  848. }, {
  849. 'info_dict': {
  850. 'id': 'teuwxikvS5k',
  851. 'ext': 'mp4',
  852. 'title': 'teamPGP: Rocket League Noob Stream (zim)',
  853. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  854. 'duration': 7334,
  855. 'upload_date': '20150721',
  856. 'uploader': 'Beer Games Beer',
  857. 'uploader_id': 'beergamesbeer',
  858. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
  859. 'license': 'Standard YouTube License',
  860. },
  861. }],
  862. 'params': {
  863. 'skip_download': True,
  864. },
  865. 'skip': 'This video is not available.',
  866. },
  867. {
  868. # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
  869. 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
  870. 'info_dict': {
  871. 'id': 'gVfLd0zydlo',
  872. 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
  873. },
  874. 'playlist_count': 2,
  875. 'skip': 'Not multifeed anymore',
  876. },
  877. {
  878. 'url': 'https://vid.plus/FlRa-iH7PGw',
  879. 'only_matching': True,
  880. },
  881. {
  882. 'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
  883. 'only_matching': True,
  884. },
  885. {
  886. # Title with JS-like syntax "};" (see https://github.com/ytdl-org/youtube-dl/issues/7468)
  887. # Also tests cut-off URL expansion in video description (see
  888. # https://github.com/ytdl-org/youtube-dl/issues/1892,
  889. # https://github.com/ytdl-org/youtube-dl/issues/8164)
  890. 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
  891. 'info_dict': {
  892. 'id': 'lsguqyKfVQg',
  893. 'ext': 'mp4',
  894. 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
  895. 'alt_title': 'Dark Walk - Position Music',
  896. 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
  897. 'duration': 133,
  898. 'upload_date': '20151119',
  899. 'uploader_id': 'IronSoulElf',
  900. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/IronSoulElf',
  901. 'uploader': 'IronSoulElf',
  902. 'creator': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
  903. 'track': 'Dark Walk - Position Music',
  904. 'artist': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
  905. 'album': 'Position Music - Production Music Vol. 143 - Dark Walk',
  906. },
  907. 'params': {
  908. 'skip_download': True,
  909. },
  910. },
  911. {
  912. # Tags with '};' (see https://github.com/ytdl-org/youtube-dl/issues/7468)
  913. 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
  914. 'only_matching': True,
  915. },
  916. {
  917. # Video with yt:stretch=17:0
  918. 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
  919. 'info_dict': {
  920. 'id': 'Q39EVAstoRM',
  921. 'ext': 'mp4',
  922. 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
  923. 'description': 'md5:ee18a25c350637c8faff806845bddee9',
  924. 'upload_date': '20151107',
  925. 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
  926. 'uploader': 'CH GAMER DROID',
  927. },
  928. 'params': {
  929. 'skip_download': True,
  930. },
  931. 'skip': 'This video does not exist.',
  932. },
  933. {
  934. # Video licensed under Creative Commons
  935. 'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
  936. 'info_dict': {
  937. 'id': 'M4gD1WSo5mA',
  938. 'ext': 'mp4',
  939. 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
  940. 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
  941. 'duration': 721,
  942. 'upload_date': '20150127',
  943. 'uploader_id': 'BerkmanCenter',
  944. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/BerkmanCenter',
  945. 'uploader': 'The Berkman Klein Center for Internet & Society',
  946. 'license': 'Creative Commons Attribution license (reuse allowed)',
  947. },
  948. 'params': {
  949. 'skip_download': True,
  950. },
  951. },
  952. {
  953. # Channel-like uploader_url
  954. 'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
  955. 'info_dict': {
  956. 'id': 'eQcmzGIKrzg',
  957. 'ext': 'mp4',
  958. 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
  959. 'description': 'md5:dda0d780d5a6e120758d1711d062a867',
  960. 'duration': 4060,
  961. 'upload_date': '20151119',
  962. 'uploader': 'Bernie Sanders',
  963. 'uploader_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
  964. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
  965. 'license': 'Creative Commons Attribution license (reuse allowed)',
  966. },
  967. 'params': {
  968. 'skip_download': True,
  969. },
  970. },
  971. {
  972. 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;amp;v=V36LpHqtcDY',
  973. 'only_matching': True,
  974. },
  975. {
  976. # YouTube Red paid video (https://github.com/ytdl-org/youtube-dl/issues/10059)
  977. 'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
  978. 'only_matching': True,
  979. },
  980. {
  981. # Rental video preview
  982. 'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
  983. 'info_dict': {
  984. 'id': 'uGpuVWrhIzE',
  985. 'ext': 'mp4',
  986. 'title': 'Piku - Trailer',
  987. 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
  988. 'upload_date': '20150811',
  989. 'uploader': 'FlixMatrix',
  990. 'uploader_id': 'FlixMatrixKaravan',
  991. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/FlixMatrixKaravan',
  992. 'license': 'Standard YouTube License',
  993. },
  994. 'params': {
  995. 'skip_download': True,
  996. },
  997. 'skip': 'This video is not available.',
  998. },
  999. {
  1000. # YouTube Red video with episode data
  1001. 'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
  1002. 'info_dict': {
  1003. 'id': 'iqKdEhx-dD4',
  1004. 'ext': 'mp4',
  1005. 'title': 'Isolation - Mind Field (Ep 1)',
  1006. 'description': 'md5:46a29be4ceffa65b92d277b93f463c0f',
  1007. 'duration': 2085,
  1008. 'upload_date': '20170118',
  1009. 'uploader': 'Vsauce',
  1010. 'uploader_id': 'Vsauce',
  1011. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Vsauce',
  1012. 'series': 'Mind Field',
  1013. 'season_number': 1,
  1014. 'episode_number': 1,
  1015. },
  1016. 'params': {
  1017. 'skip_download': True,
  1018. },
  1019. 'expected_warnings': [
  1020. 'Skipping DASH manifest',
  1021. ],
  1022. },
  1023. {
  1024. # The following content has been identified by the YouTube community
  1025. # as inappropriate or offensive to some audiences.
  1026. 'url': 'https://www.youtube.com/watch?v=6SJNVb0GnPI',
  1027. 'info_dict': {
  1028. 'id': '6SJNVb0GnPI',
  1029. 'ext': 'mp4',
  1030. 'title': 'Race Differences in Intelligence',
  1031. 'description': 'md5:5d161533167390427a1f8ee89a1fc6f1',
  1032. 'duration': 965,
  1033. 'upload_date': '20140124',
  1034. 'uploader': 'New Century Foundation',
  1035. 'uploader_id': 'UCEJYpZGqgUob0zVVEaLhvVg',
  1036. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCEJYpZGqgUob0zVVEaLhvVg',
  1037. },
  1038. 'params': {
  1039. 'skip_download': True,
  1040. },
  1041. },
  1042. {
  1043. # itag 212
  1044. 'url': '1t24XAntNCY',
  1045. 'only_matching': True,
  1046. },
  1047. {
  1048. # geo restricted to JP
  1049. 'url': 'sJL6WA-aGkQ',
  1050. 'only_matching': True,
  1051. },
  1052. {
  1053. 'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
  1054. 'only_matching': True,
  1055. },
  1056. {
  1057. 'url': 'https://invidio.us/watch?v=BaW_jenozKc',
  1058. 'only_matching': True,
  1059. },
  1060. {
  1061. # DRM protected
  1062. 'url': 'https://www.youtube.com/watch?v=s7_qI6_mIXc',
  1063. 'only_matching': True,
  1064. },
  1065. {
  1066. # Video with unsupported adaptive stream type formats
  1067. 'url': 'https://www.youtube.com/watch?v=Z4Vy8R84T1U',
  1068. 'info_dict': {
  1069. 'id': 'Z4Vy8R84T1U',
  1070. 'ext': 'mp4',
  1071. 'title': 'saman SMAN 53 Jakarta(Sancety) opening COFFEE4th at SMAN 53 Jakarta',
  1072. 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
  1073. 'duration': 433,
  1074. 'upload_date': '20130923',
  1075. 'uploader': 'Amelia Putri Harwita',
  1076. 'uploader_id': 'UCpOxM49HJxmC1qCalXyB3_Q',
  1077. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCpOxM49HJxmC1qCalXyB3_Q',
  1078. 'formats': 'maxcount:10',
  1079. },
  1080. 'params': {
  1081. 'skip_download': True,
  1082. 'youtube_include_dash_manifest': False,
  1083. },
  1084. 'skip': 'not actual anymore',
  1085. },
  1086. {
  1087. # Youtube Music Auto-generated description
  1088. 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
  1089. 'info_dict': {
  1090. 'id': 'MgNrAu2pzNs',
  1091. 'ext': 'mp4',
  1092. 'title': 'Voyeur Girl',
  1093. 'description': 'md5:7ae382a65843d6df2685993e90a8628f',
  1094. 'upload_date': '20190312',
  1095. 'uploader': 'Stephen - Topic',
  1096. 'uploader_id': 'UC-pWHpBjdGG69N9mM2auIAA',
  1097. 'artist': 'Stephen',
  1098. 'track': 'Voyeur Girl',
  1099. 'album': 'it\'s too much love to know my dear',
  1100. 'release_date': '20190313',
  1101. 'release_year': 2019,
  1102. },
  1103. 'params': {
  1104. 'skip_download': True,
  1105. },
  1106. },
  1107. {
  1108. # Youtube Music Auto-generated description
  1109. # Retrieve 'artist' field from 'Artist:' in video description
  1110. # when it is present on youtube music video
  1111. 'url': 'https://www.youtube.com/watch?v=k0jLE7tTwjY',
  1112. 'info_dict': {
  1113. 'id': 'k0jLE7tTwjY',
  1114. 'ext': 'mp4',
  1115. 'title': 'Latch Feat. Sam Smith',
  1116. 'description': 'md5:3cb1e8101a7c85fcba9b4fb41b951335',
  1117. 'upload_date': '20150110',
  1118. 'uploader': 'Various Artists - Topic',
  1119. 'uploader_id': 'UCNkEcmYdjrH4RqtNgh7BZ9w',
  1120. 'artist': 'Disclosure',
  1121. 'track': 'Latch Feat. Sam Smith',
  1122. 'album': 'Latch Featuring Sam Smith',
  1123. 'release_date': '20121008',
  1124. 'release_year': 2012,
  1125. },
  1126. 'params': {
  1127. 'skip_download': True,
  1128. },
  1129. },
  1130. {
  1131. # Youtube Music Auto-generated description
  1132. # handle multiple artists on youtube music video
  1133. 'url': 'https://www.youtube.com/watch?v=74qn0eJSjpA',
  1134. 'info_dict': {
  1135. 'id': '74qn0eJSjpA',
  1136. 'ext': 'mp4',
  1137. 'title': 'Eastside',
  1138. 'description': 'md5:290516bb73dcbfab0dcc4efe6c3de5f2',
  1139. 'upload_date': '20180710',
  1140. 'uploader': 'Benny Blanco - Topic',
  1141. 'uploader_id': 'UCzqz_ksRu_WkIzmivMdIS7A',
  1142. 'artist': 'benny blanco, Halsey, Khalid',
  1143. 'track': 'Eastside',
  1144. 'album': 'Eastside',
  1145. 'release_date': '20180713',
  1146. 'release_year': 2018,
  1147. },
  1148. 'params': {
  1149. 'skip_download': True,
  1150. },
  1151. },
  1152. {
  1153. # Youtube Music Auto-generated description
  1154. # handle youtube music video with release_year and no release_date
  1155. 'url': 'https://www.youtube.com/watch?v=-hcAI0g-f5M',
  1156. 'info_dict': {
  1157. 'id': '-hcAI0g-f5M',
  1158. 'ext': 'mp4',
  1159. 'title': 'Put It On Me',
  1160. 'description': 'md5:f6422397c07c4c907c6638e1fee380a5',
  1161. 'upload_date': '20180426',
  1162. 'uploader': 'Matt Maeson - Topic',
  1163. 'uploader_id': 'UCnEkIGqtGcQMLk73Kp-Q5LQ',
  1164. 'artist': 'Matt Maeson',
  1165. 'track': 'Put It On Me',
  1166. 'album': 'The Hearse',
  1167. 'release_date': None,
  1168. 'release_year': 2018,
  1169. },
  1170. 'params': {
  1171. 'skip_download': True,
  1172. },
  1173. },
  1174. {
  1175. 'url': 'https://www.youtubekids.com/watch?v=3b8nCWDgZ6Q',
  1176. 'only_matching': True,
  1177. },
  1178. {
  1179. # invalid -> valid video id redirection
  1180. 'url': 'DJztXj2GPfl',
  1181. 'info_dict': {
  1182. 'id': 'DJztXj2GPfk',
  1183. 'ext': 'mp4',
  1184. 'title': 'Panjabi MC - Mundian To Bach Ke (The Dictator Soundtrack)',
  1185. 'description': 'md5:bf577a41da97918e94fa9798d9228825',
  1186. 'upload_date': '20090125',
  1187. 'uploader': 'Prochorowka',
  1188. 'uploader_id': 'Prochorowka',
  1189. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Prochorowka',
  1190. 'artist': 'Panjabi MC',
  1191. 'track': 'Beware of the Boys (Mundian to Bach Ke) - Motivo Hi-Lectro Remix',
  1192. 'album': 'Beware of the Boys (Mundian To Bach Ke)',
  1193. },
  1194. 'params': {
  1195. 'skip_download': True,
  1196. },
  1197. },
  1198. {
  1199. # empty description results in an empty string
  1200. 'url': 'https://www.youtube.com/watch?v=x41yOUIvK2k',
  1201. 'info_dict': {
  1202. 'id': 'x41yOUIvK2k',
  1203. 'ext': 'mp4',
  1204. 'title': 'IMG 3456',
  1205. 'description': '',
  1206. 'upload_date': '20170613',
  1207. 'uploader_id': 'ElevageOrVert',
  1208. 'uploader': 'ElevageOrVert',
  1209. },
  1210. 'params': {
  1211. 'skip_download': True,
  1212. },
  1213. },
  1214. ]
  1215. def __init__(self, *args, **kwargs):
  1216. super(YoutubeIE, self).__init__(*args, **kwargs)
  1217. self._player_cache = {}
  1218. def report_video_info_webpage_download(self, video_id):
  1219. """Report attempt to download video info webpage."""
  1220. self.to_screen('%s: Downloading video info webpage' % video_id)
  1221. def report_information_extraction(self, video_id):
  1222. """Report attempt to extract video information."""
  1223. self.to_screen('%s: Extracting video information' % video_id)
  1224. def report_unavailable_format(self, video_id, format):
  1225. """Report extracted video URL."""
  1226. self.to_screen('%s: Format %s not available' % (video_id, format))
  1227. def report_rtmp_download(self):
  1228. """Indicate the download will use the RTMP protocol."""
  1229. self.to_screen('RTMP download detected')
  1230. def _signature_cache_id(self, example_sig):
  1231. """ Return a string representation of a signature """
  1232. return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
  1233. @classmethod
  1234. def _extract_player_info(cls, player_url):
  1235. for player_re in cls._PLAYER_INFO_RE:
  1236. id_m = re.search(player_re, player_url)
  1237. if id_m:
  1238. break
  1239. else:
  1240. raise ExtractorError('Cannot identify player %r' % player_url)
  1241. return id_m.group('ext'), id_m.group('id')
  1242. def _extract_signature_function(self, video_id, player_url, example_sig):
  1243. player_type, player_id = self._extract_player_info(player_url)
  1244. # Read from filesystem cache
  1245. func_id = '%s_%s_%s' % (
  1246. player_type, player_id, self._signature_cache_id(example_sig))
  1247. assert os.path.basename(func_id) == func_id
  1248. cache_spec = self._downloader.cache.load('youtube-sigfuncs', func_id)
  1249. if cache_spec is not None:
  1250. return lambda s: ''.join(s[i] for i in cache_spec)
  1251. download_note = (
  1252. 'Downloading player %s' % player_url
  1253. if self._downloader.params.get('verbose') else
  1254. 'Downloading %s player %s' % (player_type, player_id)
  1255. )
  1256. if player_type == 'js':
  1257. code = self._download_webpage(
  1258. player_url, video_id,
  1259. note=download_note,
  1260. errnote='Download of %s failed' % player_url)
  1261. res = self._parse_sig_js(code)
  1262. elif player_type == 'swf':
  1263. urlh = self._request_webpage(
  1264. player_url, video_id,
  1265. note=download_note,
  1266. errnote='Download of %s failed' % player_url)
  1267. code = urlh.read()
  1268. res = self._parse_sig_swf(code)
  1269. else:
  1270. assert False, 'Invalid player type %r' % player_type
  1271. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  1272. cache_res = res(test_string)
  1273. cache_spec = [ord(c) for c in cache_res]
  1274. self._downloader.cache.store('youtube-sigfuncs', func_id, cache_spec)
  1275. return res
  1276. def _print_sig_code(self, func, example_sig):
  1277. def gen_sig_code(idxs):
  1278. def _genslice(start, end, step):
  1279. starts = '' if start == 0 else str(start)
  1280. ends = (':%d' % (end + step)) if end + step >= 0 else ':'
  1281. steps = '' if step == 1 else (':%d' % step)
  1282. return 's[%s%s%s]' % (starts, ends, steps)
  1283. step = None
  1284. # Quelch pyflakes warnings - start will be set when step is set
  1285. start = '(Never used)'
  1286. for i, prev in zip(idxs[1:], idxs[:-1]):
  1287. if step is not None:
  1288. if i - prev == step:
  1289. continue
  1290. yield _genslice(start, prev, step)
  1291. step = None
  1292. continue
  1293. if i - prev in [-1, 1]:
  1294. step = i - prev
  1295. start = prev
  1296. continue
  1297. else:
  1298. yield 's[%d]' % prev
  1299. if step is None:
  1300. yield 's[%d]' % i
  1301. else:
  1302. yield _genslice(start, i, step)
  1303. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  1304. cache_res = func(test_string)
  1305. cache_spec = [ord(c) for c in cache_res]
  1306. expr_code = ' + '.join(gen_sig_code(cache_spec))
  1307. signature_id_tuple = '(%s)' % (
  1308. ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
  1309. code = ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
  1310. ' return %s\n') % (signature_id_tuple, expr_code)
  1311. self.to_screen('Extracted signature function:\n' + code)
  1312. def _parse_sig_js(self, jscode):
  1313. funcname = self._search_regex(
  1314. (r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1315. r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1316. r'(?:\b|[^a-zA-Z0-9$])(?P<sig>[a-zA-Z0-9$]{2})\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
  1317. r'(?P<sig>[a-zA-Z0-9$]+)\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
  1318. # Obsolete patterns
  1319. r'(["\'])signature\1\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1320. r'\.sig\|\|(?P<sig>[a-zA-Z0-9$]+)\(',
  1321. r'yt\.akamaized\.net/\)\s*\|\|\s*.*?\s*[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?:encodeURIComponent\s*\()?\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1322. r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1323. r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1324. r'\bc\s*&&\s*a\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1325. r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1326. r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\('),
  1327. jscode, 'Initial JS player signature function name', group='sig')
  1328. jsi = JSInterpreter(jscode)
  1329. initial_function = jsi.extract_function(funcname)
  1330. return lambda s: initial_function([s])
  1331. def _parse_sig_swf(self, file_contents):
  1332. swfi = SWFInterpreter(file_contents)
  1333. TARGET_CLASSNAME = 'SignatureDecipher'
  1334. searched_class = swfi.extract_class(TARGET_CLASSNAME)
  1335. initial_function = swfi.extract_function(searched_class, 'decipher')
  1336. return lambda s: initial_function([s])
  1337. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  1338. """Turn the encrypted s field into a working signature"""
  1339. if player_url is None:
  1340. raise ExtractorError('Cannot decrypt signature without player_url')
  1341. if player_url.startswith('//'):
  1342. player_url = 'https:' + player_url
  1343. elif not re.match(r'https?://', player_url):
  1344. player_url = compat_urlparse.urljoin(
  1345. 'https://www.youtube.com', player_url)
  1346. try:
  1347. player_id = (player_url, self._signature_cache_id(s))
  1348. if player_id not in self._player_cache:
  1349. func = self._extract_signature_function(
  1350. video_id, player_url, s
  1351. )
  1352. self._player_cache[player_id] = func
  1353. func = self._player_cache[player_id]
  1354. if self._downloader.params.get('youtube_print_sig_code'):
  1355. self._print_sig_code(func, s)
  1356. return func(s)
  1357. except Exception as e:
  1358. tb = traceback.format_exc()
  1359. raise ExtractorError(
  1360. 'Signature extraction failed: ' + tb, cause=e)
  1361. def _get_subtitles(self, video_id, webpage):
  1362. try:
  1363. subs_doc = self._download_xml(
  1364. 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  1365. video_id, note=False)
  1366. except ExtractorError as err:
  1367. self._downloader.report_warning('unable to download video subtitles: %s' % error_to_compat_str(err))
  1368. return {}
  1369. sub_lang_list = {}
  1370. for track in subs_doc.findall('track'):
  1371. lang = track.attrib['lang_code']
  1372. if lang in sub_lang_list:
  1373. continue
  1374. sub_formats = []
  1375. for ext in self._SUBTITLE_FORMATS:
  1376. params = compat_urllib_parse_urlencode({
  1377. 'lang': lang,
  1378. 'v': video_id,
  1379. 'fmt': ext,
  1380. 'name': track.attrib['name'].encode('utf-8'),
  1381. })
  1382. sub_formats.append({
  1383. 'url': 'https://www.youtube.com/api/timedtext?' + params,
  1384. 'ext': ext,
  1385. })
  1386. sub_lang_list[lang] = sub_formats
  1387. if not sub_lang_list:
  1388. self._downloader.report_warning('video doesn\'t have subtitles')
  1389. return {}
  1390. return sub_lang_list
  1391. def _get_ytplayer_config(self, video_id, webpage):
  1392. patterns = (
  1393. # User data may contain arbitrary character sequences that may affect
  1394. # JSON extraction with regex, e.g. when '};' is contained the second
  1395. # regex won't capture the whole JSON. Yet working around by trying more
  1396. # concrete regex first keeping in mind proper quoted string handling
  1397. # to be implemented in future that will replace this workaround (see
  1398. # https://github.com/ytdl-org/youtube-dl/issues/7468,
  1399. # https://github.com/ytdl-org/youtube-dl/pull/7599)
  1400. r';ytplayer\.config\s*=\s*({.+?});ytplayer',
  1401. r';ytplayer\.config\s*=\s*({.+?});',
  1402. )
  1403. config = self._search_regex(
  1404. patterns, webpage, 'ytplayer.config', default=None)
  1405. if config:
  1406. return self._parse_json(
  1407. uppercase_escape(config), video_id, fatal=False)
  1408. def _get_automatic_captions(self, video_id, webpage):
  1409. """We need the webpage for getting the captions url, pass it as an
  1410. argument to speed up the process."""
  1411. self.to_screen('%s: Looking for automatic captions' % video_id)
  1412. player_config = self._get_ytplayer_config(video_id, webpage)
  1413. err_msg = 'Couldn\'t find automatic captions for %s' % video_id
  1414. if not player_config:
  1415. self._downloader.report_warning(err_msg)
  1416. return {}
  1417. try:
  1418. args = player_config['args']
  1419. caption_url = args.get('ttsurl')
  1420. if caption_url:
  1421. timestamp = args['timestamp']
  1422. # We get the available subtitles
  1423. list_params = compat_urllib_parse_urlencode({
  1424. 'type': 'list',
  1425. 'tlangs': 1,
  1426. 'asrs': 1,
  1427. })
  1428. list_url = caption_url + '&' + list_params
  1429. caption_list = self._download_xml(list_url, video_id)
  1430. original_lang_node = caption_list.find('track')
  1431. if original_lang_node is None:
  1432. self._downloader.report_warning('Video doesn\'t have automatic captions')
  1433. return {}
  1434. original_lang = original_lang_node.attrib['lang_code']
  1435. caption_kind = original_lang_node.attrib.get('kind', '')
  1436. sub_lang_list = {}
  1437. for lang_node in caption_list.findall('target'):
  1438. sub_lang = lang_node.attrib['lang_code']
  1439. sub_formats = []
  1440. for ext in self._SUBTITLE_FORMATS:
  1441. params = compat_urllib_parse_urlencode({
  1442. 'lang': original_lang,
  1443. 'tlang': sub_lang,
  1444. 'fmt': ext,
  1445. 'ts': timestamp,
  1446. 'kind': caption_kind,
  1447. })
  1448. sub_formats.append({
  1449. 'url': caption_url + '&' + params,
  1450. 'ext': ext,
  1451. })
  1452. sub_lang_list[sub_lang] = sub_formats
  1453. return sub_lang_list
  1454. def make_captions(sub_url, sub_langs):
  1455. parsed_sub_url = compat_urllib_parse_urlparse(sub_url)
  1456. caption_qs = compat_parse_qs(parsed_sub_url.query)
  1457. captions = {}
  1458. for sub_lang in sub_langs:
  1459. sub_formats = []
  1460. for ext in self._SUBTITLE_FORMATS:
  1461. caption_qs.update({
  1462. 'tlang': [sub_lang],
  1463. 'fmt': [ext],
  1464. })
  1465. sub_url = compat_urlparse.urlunparse(parsed_sub_url._replace(
  1466. query=compat_urllib_parse_urlencode(caption_qs, True)))
  1467. sub_formats.append({
  1468. 'url': sub_url,
  1469. 'ext': ext,
  1470. })
  1471. captions[sub_lang] = sub_formats
  1472. return captions
  1473. # New captions format as of 22.06.2017
  1474. player_response = args.get('player_response')
  1475. if player_response and isinstance(player_response, compat_str):
  1476. player_response = self._parse_json(
  1477. player_response, video_id, fatal=False)
  1478. if player_response:
  1479. renderer = player_response['captions']['playerCaptionsTracklistRenderer']
  1480. base_url = renderer['captionTracks'][0]['baseUrl']
  1481. sub_lang_list = []
  1482. for lang in renderer['translationLanguages']:
  1483. lang_code = lang.get('languageCode')
  1484. if lang_code:
  1485. sub_lang_list.append(lang_code)
  1486. return make_captions(base_url, sub_lang_list)
  1487. # Some videos don't provide ttsurl but rather caption_tracks and
  1488. # caption_translation_languages (e.g. 20LmZk1hakA)
  1489. # Does not used anymore as of 22.06.2017
  1490. caption_tracks = args['caption_tracks']
  1491. caption_translation_languages = args['caption_translation_languages']
  1492. caption_url = compat_parse_qs(caption_tracks.split(',')[0])['u'][0]
  1493. sub_lang_list = []
  1494. for lang in caption_translation_languages.split(','):
  1495. lang_qs = compat_parse_qs(compat_urllib_parse_unquote_plus(lang))
  1496. sub_lang = lang_qs.get('lc', [None])[0]
  1497. if sub_lang:
  1498. sub_lang_list.append(sub_lang)
  1499. return make_captions(caption_url, sub_lang_list)
  1500. # An extractor error can be raise by the download process if there are
  1501. # no automatic captions but there are subtitles
  1502. except (KeyError, IndexError, ExtractorError):
  1503. self._downloader.report_warning(err_msg)
  1504. return {}
  1505. def _mark_watched(self, video_id, video_info, player_response):
  1506. playback_url = url_or_none(try_get(
  1507. player_response,
  1508. lambda x: x['playbackTracking']['videostatsPlaybackUrl']['baseUrl']) or try_get(
  1509. video_info, lambda x: x['videostats_playback_base_url'][0]))
  1510. if not playback_url:
  1511. return
  1512. parsed_playback_url = compat_urlparse.urlparse(playback_url)
  1513. qs = compat_urlparse.parse_qs(parsed_playback_url.query)
  1514. # cpn generation algorithm is reverse engineered from base.js.
  1515. # In fact it works even with dummy cpn.
  1516. CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
  1517. cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
  1518. qs.update({
  1519. 'ver': ['2'],
  1520. 'cpn': [cpn],
  1521. })
  1522. playback_url = compat_urlparse.urlunparse(
  1523. parsed_playback_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
  1524. self._download_webpage(
  1525. playback_url, video_id, 'Marking watched',
  1526. 'Unable to mark watched', fatal=False)
  1527. @staticmethod
  1528. def _extract_urls(webpage):
  1529. # Embedded YouTube player
  1530. entries = [
  1531. unescapeHTML(mobj.group('url'))
  1532. for mobj in re.finditer(r'''(?x)
  1533. (?:
  1534. <iframe[^>]+?src=|
  1535. data-video-url=|
  1536. <embed[^>]+?src=|
  1537. embedSWF\(?:\s*|
  1538. <object[^>]+data=|
  1539. new\s+SWFObject\(
  1540. )
  1541. (["\'])
  1542. (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
  1543. (?:embed|v|p)/[0-9A-Za-z_-]{11}.*?)
  1544. \1''', webpage)]
  1545. # lazyYT YouTube embed
  1546. entries.extend(list(map(
  1547. unescapeHTML,
  1548. re.findall(r'class="lazyYT" data-youtube-id="([^"]+)"', webpage))))
  1549. # Wordpress "YouTube Video Importer" plugin
  1550. matches = re.findall(r'''(?x)<div[^>]+
  1551. class=(?P<q1>[\'"])[^\'"]*\byvii_single_video_player\b[^\'"]*(?P=q1)[^>]+
  1552. data-video_id=(?P<q2>[\'"])([^\'"]+)(?P=q2)''', webpage)
  1553. entries.extend(m[-1] for m in matches)
  1554. return entries
  1555. @staticmethod
  1556. def _extract_url(webpage):
  1557. urls = YoutubeIE._extract_urls(webpage)
  1558. return urls[0] if urls else None
  1559. @classmethod
  1560. def extract_id(cls, url):
  1561. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  1562. if mobj is None:
  1563. raise ExtractorError('Invalid URL: %s' % url)
  1564. video_id = mobj.group(2)
  1565. return video_id
  1566. def _extract_chapters_from_json(self, webpage, video_id, duration):
  1567. if not webpage:
  1568. return
  1569. player = self._parse_json(
  1570. self._search_regex(
  1571. r'RELATED_PLAYER_ARGS["\']\s*:\s*({.+})\s*,?\s*\n', webpage,
  1572. 'player args', default='{}'),
  1573. video_id, fatal=False)
  1574. if not player or not isinstance(player, dict):
  1575. return
  1576. watch_next_response = player.get('watch_next_response')
  1577. if not isinstance(watch_next_response, compat_str):
  1578. return
  1579. response = self._parse_json(watch_next_response, video_id, fatal=False)
  1580. if not response or not isinstance(response, dict):
  1581. return
  1582. chapters_list = try_get(
  1583. response,
  1584. lambda x: x['playerOverlays']
  1585. ['playerOverlayRenderer']
  1586. ['decoratedPlayerBarRenderer']
  1587. ['decoratedPlayerBarRenderer']
  1588. ['playerBar']
  1589. ['chapteredPlayerBarRenderer']
  1590. ['chapters'],
  1591. list)
  1592. if not chapters_list:
  1593. return
  1594. def chapter_time(chapter):
  1595. return float_or_none(
  1596. try_get(
  1597. chapter,
  1598. lambda x: x['chapterRenderer']['timeRangeStartMillis'],
  1599. int),
  1600. scale=1000)
  1601. chapters = []
  1602. for next_num, chapter in enumerate(chapters_list, start=1):
  1603. start_time = chapter_time(chapter)
  1604. if start_time is None:
  1605. continue
  1606. end_time = (chapter_time(chapters_list[next_num])
  1607. if next_num < len(chapters_list) else duration)
  1608. if end_time is None:
  1609. continue
  1610. title = try_get(
  1611. chapter, lambda x: x['chapterRenderer']['title']['simpleText'],
  1612. compat_str)
  1613. chapters.append({
  1614. 'start_time': start_time,
  1615. 'end_time': end_time,
  1616. 'title': title,
  1617. })
  1618. return chapters
  1619. @staticmethod
  1620. def _extract_chapters_from_description(description, duration):
  1621. if not description:
  1622. return None
  1623. chapter_lines = re.findall(
  1624. r'(?:^|<br\s*/>)([^<]*<a[^>]+onclick=["\']yt\.www\.watch\.player\.seekTo[^>]+>(\d{1,2}:\d{1,2}(?::\d{1,2})?)</a>[^>]*)(?=$|<br\s*/>)',
  1625. description)
  1626. if not chapter_lines:
  1627. return None
  1628. chapters = []
  1629. for next_num, (chapter_line, time_point) in enumerate(
  1630. chapter_lines, start=1):
  1631. start_time = parse_duration(time_point)
  1632. if start_time is None:
  1633. continue
  1634. if start_time > duration:
  1635. break
  1636. end_time = (duration if next_num == len(chapter_lines)
  1637. else parse_duration(chapter_lines[next_num][1]))
  1638. if end_time is None:
  1639. continue
  1640. if end_time > duration:
  1641. end_time = duration
  1642. if start_time > end_time:
  1643. break
  1644. chapter_title = re.sub(
  1645. r'<a[^>]+>[^<]+</a>', '', chapter_line).strip(' \t-')
  1646. chapter_title = re.sub(r'\s+', ' ', chapter_title)
  1647. chapters.append({
  1648. 'start_time': start_time,
  1649. 'end_time': end_time,
  1650. 'title': chapter_title,
  1651. })
  1652. return chapters
  1653. def _extract_chapters(self, webpage, description, video_id, duration):
  1654. return (self._extract_chapters_from_json(webpage, video_id, duration)
  1655. or self._extract_chapters_from_description(description, duration))
  1656. def _real_extract(self, url):
  1657. url, smuggled_data = unsmuggle_url(url, {})
  1658. proto = (
  1659. 'http' if self._downloader.params.get('prefer_insecure', False)
  1660. else 'https')
  1661. start_time = None
  1662. end_time = None
  1663. parsed_url = compat_urllib_parse_urlparse(url)
  1664. for component in [parsed_url.fragment, parsed_url.query]:
  1665. query = compat_parse_qs(component)
  1666. if start_time is None and 't' in query:
  1667. start_time = parse_duration(query['t'][0])
  1668. if start_time is None and 'start' in query:
  1669. start_time = parse_duration(query['start'][0])
  1670. if end_time is None and 'end' in query:
  1671. end_time = parse_duration(query['end'][0])
  1672. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  1673. mobj = re.search(self._NEXT_URL_RE, url)
  1674. if mobj:
  1675. url = proto + '://www.youtube.com/' + compat_urllib_parse_unquote(mobj.group(1)).lstrip('/')
  1676. video_id = self.extract_id(url)
  1677. # Get video webpage
  1678. url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1&bpctr=9999999999' % video_id
  1679. video_webpage, urlh = self._download_webpage_handle(url, video_id)
  1680. qs = compat_parse_qs(compat_urllib_parse_urlparse(urlh.geturl()).query)
  1681. video_id = qs.get('v', [None])[0] or video_id
  1682. # Attempt to extract SWF player URL
  1683. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  1684. if mobj is not None:
  1685. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  1686. else:
  1687. player_url = None
  1688. dash_mpds = []
  1689. def add_dash_mpd(video_info):
  1690. dash_mpd = video_info.get('dashmpd')
  1691. if dash_mpd and dash_mpd[0] not in dash_mpds:
  1692. dash_mpds.append(dash_mpd[0])
  1693. def add_dash_mpd_pr(pl_response):
  1694. dash_mpd = url_or_none(try_get(
  1695. pl_response, lambda x: x['streamingData']['dashManifestUrl'],
  1696. compat_str))
  1697. if dash_mpd and dash_mpd not in dash_mpds:
  1698. dash_mpds.append(dash_mpd)
  1699. is_live = None
  1700. view_count = None
  1701. def extract_view_count(v_info):
  1702. return int_or_none(try_get(v_info, lambda x: x['view_count'][0]))
  1703. def extract_player_response(player_response, video_id):
  1704. pl_response = str_or_none(player_response)
  1705. if not pl_response:
  1706. return
  1707. pl_response = self._parse_json(pl_response, video_id, fatal=False)
  1708. if isinstance(pl_response, dict):
  1709. add_dash_mpd_pr(pl_response)
  1710. return pl_response
  1711. player_response = {}
  1712. # Get video info
  1713. video_info = {}
  1714. embed_webpage = None
  1715. if (self._og_search_property('restrictions:age', video_webpage, default=None) == '18+'
  1716. or re.search(r'player-age-gate-content">', video_webpage) is not None):
  1717. age_gate = True
  1718. # We simulate the access to the video from www.youtube.com/v/{video_id}
  1719. # this can be viewed without login into Youtube
  1720. url = proto + '://www.youtube.com/embed/%s' % video_id
  1721. embed_webpage = self._download_webpage(url, video_id, 'Downloading embed webpage')
  1722. data = compat_urllib_parse_urlencode({
  1723. 'video_id': video_id,
  1724. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  1725. 'sts': self._search_regex(
  1726. r'"sts"\s*:\s*(\d+)', embed_webpage, 'sts', default=''),
  1727. })
  1728. video_info_url = proto + '://www.youtube.com/get_video_info?' + data
  1729. try:
  1730. video_info_webpage = self._download_webpage(
  1731. video_info_url, video_id,
  1732. note='Refetching age-gated info webpage',
  1733. errnote='unable to download video info webpage')
  1734. except ExtractorError:
  1735. video_info_webpage = None
  1736. if video_info_webpage:
  1737. video_info = compat_parse_qs(video_info_webpage)
  1738. pl_response = video_info.get('player_response', [None])[0]
  1739. player_response = extract_player_response(pl_response, video_id)
  1740. add_dash_mpd(video_info)
  1741. view_count = extract_view_count(video_info)
  1742. else:
  1743. age_gate = False
  1744. # Try looking directly into the video webpage
  1745. ytplayer_config = self._get_ytplayer_config(video_id, video_webpage)
  1746. if ytplayer_config:
  1747. args = ytplayer_config['args']
  1748. if args.get('url_encoded_fmt_stream_map') or args.get('hlsvp'):
  1749. # Convert to the same format returned by compat_parse_qs
  1750. video_info = dict((k, [v]) for k, v in args.items())
  1751. add_dash_mpd(video_info)
  1752. # Rental video is not rented but preview is available (e.g.
  1753. # https://www.youtube.com/watch?v=yYr8q0y5Jfg,
  1754. # https://github.com/ytdl-org/youtube-dl/issues/10532)
  1755. if not video_info and args.get('ypc_vid'):
  1756. return self.url_result(
  1757. args['ypc_vid'], YoutubeIE.ie_key(), video_id=args['ypc_vid'])
  1758. if args.get('livestream') == '1' or args.get('live_playback') == 1:
  1759. is_live = True
  1760. if not player_response:
  1761. player_response = extract_player_response(args.get('player_response'), video_id)
  1762. if not video_info or self._downloader.params.get('youtube_include_dash_manifest', True):
  1763. add_dash_mpd_pr(player_response)
  1764. def extract_unavailable_message():
  1765. messages = []
  1766. for tag, kind in (('h1', 'message'), ('div', 'submessage')):
  1767. msg = self._html_search_regex(
  1768. r'(?s)<{tag}[^>]+id=["\']unavailable-{kind}["\'][^>]*>(.+?)</{tag}>'.format(tag=tag, kind=kind),
  1769. video_webpage, 'unavailable %s' % kind, default=None)
  1770. if msg:
  1771. messages.append(msg)
  1772. if messages:
  1773. return '\n'.join(messages)
  1774. if not video_info and not player_response:
  1775. unavailable_message = extract_unavailable_message()
  1776. if not unavailable_message:
  1777. unavailable_message = 'Unable to extract video data'
  1778. raise ExtractorError(
  1779. 'YouTube said: %s' % unavailable_message, expected=True, video_id=video_id)
  1780. if not isinstance(video_info, dict):
  1781. video_info = {}
  1782. video_details = try_get(
  1783. player_response, lambda x: x['videoDetails'], dict) or {}
  1784. microformat = try_get(
  1785. player_response, lambda x: x['microformat']['playerMicroformatRenderer'], dict) or {}
  1786. video_title = video_info.get('title', [None])[0] or video_details.get('title')
  1787. if not video_title:
  1788. self._downloader.report_warning('Unable to extract video title')
  1789. video_title = '_'
  1790. description_original = video_description = get_element_by_id("eow-description", video_webpage)
  1791. if video_description:
  1792. def replace_url(m):
  1793. redir_url = compat_urlparse.urljoin(url, m.group(1))
  1794. parsed_redir_url = compat_urllib_parse_urlparse(redir_url)
  1795. if re.search(r'^(?:www\.)?(?:youtube(?:-nocookie)?\.com|youtu\.be)$', parsed_redir_url.netloc) and parsed_redir_url.path == '/redirect':
  1796. qs = compat_parse_qs(parsed_redir_url.query)
  1797. q = qs.get('q')
  1798. if q and q[0]:
  1799. return q[0]
  1800. return redir_url
  1801. description_original = video_description = re.sub(r'''(?x)
  1802. <a\s+
  1803. (?:[a-zA-Z-]+="[^"]*"\s+)*?
  1804. (?:title|href)="([^"]+)"\s+
  1805. (?:[a-zA-Z-]+="[^"]*"\s+)*?
  1806. class="[^"]*"[^>]*>
  1807. [^<]+\.{3}\s*
  1808. </a>
  1809. ''', replace_url, video_description)
  1810. video_description = clean_html(video_description)
  1811. else:
  1812. video_description = video_details.get('shortDescription')
  1813. if video_description is None:
  1814. video_description = self._html_search_meta('description', video_webpage)
  1815. if not smuggled_data.get('force_singlefeed', False):
  1816. if not self._downloader.params.get('noplaylist'):
  1817. multifeed_metadata_list = try_get(
  1818. player_response,
  1819. lambda x: x['multicamera']['playerLegacyMulticameraRenderer']['metadataList'],
  1820. compat_str) or try_get(
  1821. video_info, lambda x: x['multifeed_metadata_list'][0], compat_str)
  1822. if multifeed_metadata_list:
  1823. entries = []
  1824. feed_ids = []
  1825. for feed in multifeed_metadata_list.split(','):
  1826. # Unquote should take place before split on comma (,) since textual
  1827. # fields may contain comma as well (see
  1828. # https://github.com/ytdl-org/youtube-dl/issues/8536)
  1829. feed_data = compat_parse_qs(compat_urllib_parse_unquote_plus(feed))
  1830. def feed_entry(name):
  1831. return try_get(feed_data, lambda x: x[name][0], compat_str)
  1832. feed_id = feed_entry('id')
  1833. if not feed_id:
  1834. continue
  1835. feed_title = feed_entry('title')
  1836. title = video_title
  1837. if feed_title:
  1838. title += ' (%s)' % feed_title
  1839. entries.append({
  1840. '_type': 'url_transparent',
  1841. 'ie_key': 'Youtube',
  1842. 'url': smuggle_url(
  1843. '%s://www.youtube.com/watch?v=%s' % (proto, feed_data['id'][0]),
  1844. {'force_singlefeed': True}),
  1845. 'title': title,
  1846. })
  1847. feed_ids.append(feed_id)
  1848. self.to_screen(
  1849. 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
  1850. % (', '.join(feed_ids), video_id))
  1851. return self.playlist_result(entries, video_id, video_title, video_description)
  1852. else:
  1853. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1854. if view_count is None:
  1855. view_count = extract_view_count(video_info)
  1856. if view_count is None and video_details:
  1857. view_count = int_or_none(video_details.get('viewCount'))
  1858. if view_count is None and microformat:
  1859. view_count = int_or_none(microformat.get('viewCount'))
  1860. if is_live is None:
  1861. is_live = bool_or_none(video_details.get('isLive'))
  1862. # Check for "rental" videos
  1863. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  1864. raise ExtractorError('"rental" videos not supported. See https://github.com/ytdl-org/youtube-dl/issues/359 for more information.', expected=True)
  1865. def _extract_filesize(media_url):
  1866. return int_or_none(self._search_regex(
  1867. r'\bclen[=/](\d+)', media_url, 'filesize', default=None))
  1868. streaming_formats = try_get(player_response, lambda x: x['streamingData']['formats'], list) or []
  1869. streaming_formats.extend(try_get(player_response, lambda x: x['streamingData']['adaptiveFormats'], list) or [])
  1870. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1871. self.report_rtmp_download()
  1872. formats = [{
  1873. 'format_id': '_rtmp',
  1874. 'protocol': 'rtmp',
  1875. 'url': video_info['conn'][0],
  1876. 'player_url': player_url,
  1877. }]
  1878. elif not is_live and (streaming_formats or len(video_info.get('url_encoded_fmt_stream_map', [''])[0]) >= 1 or len(video_info.get('adaptive_fmts', [''])[0]) >= 1):
  1879. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts', [''])[0]
  1880. if 'rtmpe%3Dyes' in encoded_url_map:
  1881. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/ytdl-org/youtube-dl/issues/343 for more information.', expected=True)
  1882. formats = []
  1883. formats_spec = {}
  1884. fmt_list = video_info.get('fmt_list', [''])[0]
  1885. if fmt_list:
  1886. for fmt in fmt_list.split(','):
  1887. spec = fmt.split('/')
  1888. if len(spec) > 1:
  1889. width_height = spec[1].split('x')
  1890. if len(width_height) == 2:
  1891. formats_spec[spec[0]] = {
  1892. 'resolution': spec[1],
  1893. 'width': int_or_none(width_height[0]),
  1894. 'height': int_or_none(width_height[1]),
  1895. }
  1896. for fmt in streaming_formats:
  1897. itag = str_or_none(fmt.get('itag'))
  1898. if not itag:
  1899. continue
  1900. quality = fmt.get('quality')
  1901. quality_label = fmt.get('qualityLabel') or quality
  1902. formats_spec[itag] = {
  1903. 'asr': int_or_none(fmt.get('audioSampleRate')),
  1904. 'filesize': int_or_none(fmt.get('contentLength')),
  1905. 'format_note': quality_label,
  1906. 'fps': int_or_none(fmt.get('fps')),
  1907. 'height': int_or_none(fmt.get('height')),
  1908. # bitrate for itag 43 is always 2147483647
  1909. 'tbr': float_or_none(fmt.get('averageBitrate') or fmt.get('bitrate'), 1000) if itag != '43' else None,
  1910. 'width': int_or_none(fmt.get('width')),
  1911. }
  1912. for fmt in streaming_formats:
  1913. if fmt.get('drmFamilies') or fmt.get('drm_families'):
  1914. continue
  1915. url = url_or_none(fmt.get('url'))
  1916. if not url:
  1917. cipher = fmt.get('cipher') or fmt.get('signatureCipher')
  1918. if not cipher:
  1919. continue
  1920. url_data = compat_parse_qs(cipher)
  1921. url = url_or_none(try_get(url_data, lambda x: x['url'][0], compat_str))
  1922. if not url:
  1923. continue
  1924. else:
  1925. cipher = None
  1926. url_data = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
  1927. stream_type = int_or_none(try_get(url_data, lambda x: x['stream_type'][0]))
  1928. # Unsupported FORMAT_STREAM_TYPE_OTF
  1929. if stream_type == 3:
  1930. continue
  1931. format_id = fmt.get('itag') or url_data['itag'][0]
  1932. if not format_id:
  1933. continue
  1934. format_id = compat_str(format_id)
  1935. if cipher:
  1936. if 's' in url_data or self._downloader.params.get('youtube_include_dash_manifest', True):
  1937. ASSETS_RE = r'"assets":.+?"js":\s*("[^"]+")'
  1938. jsplayer_url_json = self._search_regex(
  1939. ASSETS_RE,
  1940. embed_webpage if age_gate else video_webpage,
  1941. 'JS player URL (1)', default=None)
  1942. if not jsplayer_url_json and not age_gate:
  1943. # We need the embed website after all
  1944. if embed_webpage is None:
  1945. embed_url = proto + '://www.youtube.com/embed/%s' % video_id
  1946. embed_webpage = self._download_webpage(
  1947. embed_url, video_id, 'Downloading embed webpage')
  1948. jsplayer_url_json = self._search_regex(
  1949. ASSETS_RE, embed_webpage, 'JS player URL')
  1950. player_url = json.loads(jsplayer_url_json)
  1951. if player_url is None:
  1952. player_url_json = self._search_regex(
  1953. r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
  1954. video_webpage, 'age gate player URL')
  1955. player_url = json.loads(player_url_json)
  1956. if 'sig' in url_data:
  1957. url += '&signature=' + url_data['sig'][0]
  1958. elif 's' in url_data:
  1959. encrypted_sig = url_data['s'][0]
  1960. if self._downloader.params.get('verbose'):
  1961. if player_url is None:
  1962. player_desc = 'unknown'
  1963. else:
  1964. player_type, player_version = self._extract_player_info(player_url)
  1965. player_desc = '%s player %s' % ('flash' if player_type == 'swf' else 'html5', player_version)
  1966. parts_sizes = self._signature_cache_id(encrypted_sig)
  1967. self.to_screen('{%s} signature length %s, %s' %
  1968. (format_id, parts_sizes, player_desc))
  1969. signature = self._decrypt_signature(
  1970. encrypted_sig, video_id, player_url, age_gate)
  1971. sp = try_get(url_data, lambda x: x['sp'][0], compat_str) or 'signature'
  1972. url += '&%s=%s' % (sp, signature)
  1973. if 'ratebypass' not in url:
  1974. url += '&ratebypass=yes'
  1975. dct = {
  1976. 'format_id': format_id,
  1977. 'url': url,
  1978. 'player_url': player_url,
  1979. }
  1980. if format_id in self._formats:
  1981. dct.update(self._formats[format_id])
  1982. if format_id in formats_spec:
  1983. dct.update(formats_spec[format_id])
  1984. # Some itags are not included in DASH manifest thus corresponding formats will
  1985. # lack metadata (see https://github.com/ytdl-org/youtube-dl/pull/5993).
  1986. # Trying to extract metadata from url_encoded_fmt_stream_map entry.
  1987. mobj = re.search(r'^(?P<width>\d+)[xX](?P<height>\d+)$', url_data.get('size', [''])[0])
  1988. width, height = (int(mobj.group('width')), int(mobj.group('height'))) if mobj else (None, None)
  1989. if width is None:
  1990. width = int_or_none(fmt.get('width'))
  1991. if height is None:
  1992. height = int_or_none(fmt.get('height'))
  1993. filesize = int_or_none(url_data.get(
  1994. 'clen', [None])[0]) or _extract_filesize(url)
  1995. quality = url_data.get('quality', [None])[0] or fmt.get('quality')
  1996. quality_label = url_data.get('quality_label', [None])[0] or fmt.get('qualityLabel')
  1997. tbr = (float_or_none(url_data.get('bitrate', [None])[0], 1000)
  1998. or float_or_none(fmt.get('bitrate'), 1000)) if format_id != '43' else None
  1999. fps = int_or_none(url_data.get('fps', [None])[0]) or int_or_none(fmt.get('fps'))
  2000. more_fields = {
  2001. 'filesize': filesize,
  2002. 'tbr': tbr,
  2003. 'width': width,
  2004. 'height': height,
  2005. 'fps': fps,
  2006. 'format_note': quality_label or quality,
  2007. }
  2008. for key, value in more_fields.items():
  2009. if value:
  2010. dct[key] = value
  2011. type_ = url_data.get('type', [None])[0] or fmt.get('mimeType')
  2012. if type_:
  2013. type_split = type_.split(';')
  2014. kind_ext = type_split[0].split('/')
  2015. if len(kind_ext) == 2:
  2016. kind, _ = kind_ext
  2017. dct['ext'] = mimetype2ext(type_split[0])
  2018. if kind in ('audio', 'video'):
  2019. codecs = None
  2020. for mobj in re.finditer(
  2021. r'(?P<key>[a-zA-Z_-]+)=(?P<quote>["\']?)(?P<val>.+?)(?P=quote)(?:;|$)', type_):
  2022. if mobj.group('key') == 'codecs':
  2023. codecs = mobj.group('val')
  2024. break
  2025. if codecs:
  2026. dct.update(parse_codecs(codecs))
  2027. if dct.get('acodec') == 'none' or dct.get('vcodec') == 'none':
  2028. dct['downloader_options'] = {
  2029. # Youtube throttles chunks >~10M
  2030. 'http_chunk_size': 10485760,
  2031. }
  2032. formats.append(dct)
  2033. else:
  2034. manifest_url = (
  2035. url_or_none(try_get(
  2036. player_response,
  2037. lambda x: x['streamingData']['hlsManifestUrl'],
  2038. compat_str))
  2039. or url_or_none(try_get(
  2040. video_info, lambda x: x['hlsvp'][0], compat_str)))
  2041. if manifest_url:
  2042. formats = []
  2043. m3u8_formats = self._extract_m3u8_formats(
  2044. manifest_url, video_id, 'mp4', fatal=False)
  2045. for a_format in m3u8_formats:
  2046. itag = self._search_regex(
  2047. r'/itag/(\d+)/', a_format['url'], 'itag', default=None)
  2048. if itag:
  2049. a_format['format_id'] = itag
  2050. if itag in self._formats:
  2051. dct = self._formats[itag].copy()
  2052. dct.update(a_format)
  2053. a_format = dct
  2054. a_format['player_url'] = player_url
  2055. # Accept-Encoding header causes failures in live streams on Youtube and Youtube Gaming
  2056. a_format.setdefault('http_headers', {})['Youtubedl-no-compression'] = 'True'
  2057. formats.append(a_format)
  2058. else:
  2059. error_message = extract_unavailable_message()
  2060. if not error_message:
  2061. error_message = clean_html(try_get(
  2062. player_response, lambda x: x['playabilityStatus']['reason'],
  2063. compat_str))
  2064. if not error_message:
  2065. error_message = clean_html(
  2066. try_get(video_info, lambda x: x['reason'][0], compat_str))
  2067. if error_message:
  2068. raise ExtractorError(error_message, expected=True)
  2069. raise ExtractorError('no conn, hlsvp, hlsManifestUrl or url_encoded_fmt_stream_map information found in video info')
  2070. # uploader
  2071. video_uploader = try_get(
  2072. video_info, lambda x: x['author'][0],
  2073. compat_str) or str_or_none(video_details.get('author'))
  2074. if video_uploader:
  2075. video_uploader = compat_urllib_parse_unquote_plus(video_uploader)
  2076. else:
  2077. self._downloader.report_warning('unable to extract uploader name')
  2078. # uploader_id
  2079. video_uploader_id = None
  2080. video_uploader_url = None
  2081. mobj = re.search(
  2082. r'<link itemprop="url" href="(?P<uploader_url>https?://www\.youtube\.com/(?:user|channel)/(?P<uploader_id>[^"]+))">',
  2083. video_webpage)
  2084. if mobj is not None:
  2085. video_uploader_id = mobj.group('uploader_id')
  2086. video_uploader_url = mobj.group('uploader_url')
  2087. else:
  2088. owner_profile_url = url_or_none(microformat.get('ownerProfileUrl'))
  2089. if owner_profile_url:
  2090. video_uploader_id = self._search_regex(
  2091. r'(?:user|channel)/([^/]+)', owner_profile_url, 'uploader id',
  2092. default=None)
  2093. video_uploader_url = owner_profile_url
  2094. channel_id = (
  2095. str_or_none(video_details.get('channelId'))
  2096. or self._html_search_meta(
  2097. 'channelId', video_webpage, 'channel id', default=None)
  2098. or self._search_regex(
  2099. r'data-channel-external-id=(["\'])(?P<id>(?:(?!\1).)+)\1',
  2100. video_webpage, 'channel id', default=None, group='id'))
  2101. channel_url = 'http://www.youtube.com/channel/%s' % channel_id if channel_id else None
  2102. thumbnails = []
  2103. thumbnails_list = try_get(
  2104. video_details, lambda x: x['thumbnail']['thumbnails'], list) or []
  2105. for t in thumbnails_list:
  2106. if not isinstance(t, dict):
  2107. continue
  2108. thumbnail_url = url_or_none(t.get('url'))
  2109. if not thumbnail_url:
  2110. continue
  2111. thumbnails.append({
  2112. 'url': thumbnail_url,
  2113. 'width': int_or_none(t.get('width')),
  2114. 'height': int_or_none(t.get('height')),
  2115. })
  2116. if not thumbnails:
  2117. video_thumbnail = None
  2118. # We try first to get a high quality image:
  2119. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  2120. video_webpage, re.DOTALL)
  2121. if m_thumb is not None:
  2122. video_thumbnail = m_thumb.group(1)
  2123. thumbnail_url = try_get(video_info, lambda x: x['thumbnail_url'][0], compat_str)
  2124. if thumbnail_url:
  2125. video_thumbnail = compat_urllib_parse_unquote_plus(thumbnail_url)
  2126. if video_thumbnail:
  2127. thumbnails.append({'url': video_thumbnail})
  2128. # upload date
  2129. upload_date = self._html_search_meta(
  2130. 'datePublished', video_webpage, 'upload date', default=None)
  2131. if not upload_date:
  2132. upload_date = self._search_regex(
  2133. [r'(?s)id="eow-date.*?>(.*?)</span>',
  2134. r'(?:id="watch-uploader-info".*?>.*?|["\']simpleText["\']\s*:\s*["\'])(?:Published|Uploaded|Streamed live|Started) on (.+?)[<"\']'],
  2135. video_webpage, 'upload date', default=None)
  2136. if not upload_date:
  2137. upload_date = microformat.get('publishDate') or microformat.get('uploadDate')
  2138. upload_date = unified_strdate(upload_date)
  2139. video_license = self._html_search_regex(
  2140. r'<h4[^>]+class="title"[^>]*>\s*License\s*</h4>\s*<ul[^>]*>\s*<li>(.+?)</li',
  2141. video_webpage, 'license', default=None)
  2142. m_music = re.search(
  2143. r'''(?x)
  2144. <h4[^>]+class="title"[^>]*>\s*Music\s*</h4>\s*
  2145. <ul[^>]*>\s*
  2146. <li>(?P<title>.+?)
  2147. by (?P<creator>.+?)
  2148. (?:
  2149. \(.+?\)|
  2150. <a[^>]*
  2151. (?:
  2152. \bhref=["\']/red[^>]*>| # drop possible
  2153. >\s*Listen ad-free with YouTube Red # YouTube Red ad
  2154. )
  2155. .*?
  2156. )?</li
  2157. ''',
  2158. video_webpage)
  2159. if m_music:
  2160. video_alt_title = remove_quotes(unescapeHTML(m_music.group('title')))
  2161. video_creator = clean_html(m_music.group('creator'))
  2162. else:
  2163. video_alt_title = video_creator = None
  2164. def extract_meta(field):
  2165. return self._html_search_regex(
  2166. r'<h4[^>]+class="title"[^>]*>\s*%s\s*</h4>\s*<ul[^>]*>\s*<li>(.+?)</li>\s*' % field,
  2167. video_webpage, field, default=None)
  2168. track = extract_meta('Song')
  2169. artist = extract_meta('Artist')
  2170. album = extract_meta('Album')
  2171. # Youtube Music Auto-generated description
  2172. release_date = release_year = None
  2173. if video_description:
  2174. mobj = re.search(r'(?s)Provided to YouTube by [^\n]+\n+(?P<track>[^·]+)·(?P<artist>[^\n]+)\n+(?P<album>[^\n]+)(?:.+?℗\s*(?P<release_year>\d{4})(?!\d))?(?:.+?Released on\s*:\s*(?P<release_date>\d{4}-\d{2}-\d{2}))?(.+?\nArtist\s*:\s*(?P<clean_artist>[^\n]+))?', video_description)
  2175. if mobj:
  2176. if not track:
  2177. track = mobj.group('track').strip()
  2178. if not artist:
  2179. artist = mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·'))
  2180. if not album:
  2181. album = mobj.group('album'.strip())
  2182. release_year = mobj.group('release_year')
  2183. release_date = mobj.group('release_date')
  2184. if release_date:
  2185. release_date = release_date.replace('-', '')
  2186. if not release_year:
  2187. release_year = int(release_date[:4])
  2188. if release_year:
  2189. release_year = int(release_year)
  2190. m_episode = re.search(
  2191. r'<div[^>]+id="watch7-headline"[^>]*>\s*<span[^>]*>.*?>(?P<series>[^<]+)</a></b>\s*S(?P<season>\d+)\s*•\s*E(?P<episode>\d+)</span>',
  2192. video_webpage)
  2193. if m_episode:
  2194. series = unescapeHTML(m_episode.group('series'))
  2195. season_number = int(m_episode.group('season'))
  2196. episode_number = int(m_episode.group('episode'))
  2197. else:
  2198. series = season_number = episode_number = None
  2199. m_cat_container = self._search_regex(
  2200. r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>',
  2201. video_webpage, 'categories', default=None)
  2202. category = None
  2203. if m_cat_container:
  2204. category = self._html_search_regex(
  2205. r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
  2206. default=None)
  2207. if not category:
  2208. category = try_get(
  2209. microformat, lambda x: x['category'], compat_str)
  2210. video_categories = None if category is None else [category]
  2211. video_tags = [
  2212. unescapeHTML(m.group('content'))
  2213. for m in re.finditer(self._meta_regex('og:video:tag'), video_webpage)]
  2214. if not video_tags:
  2215. video_tags = try_get(video_details, lambda x: x['keywords'], list)
  2216. def _extract_count(count_name):
  2217. return str_to_int(self._search_regex(
  2218. r'-%s-button[^>]+><span[^>]+class="yt-uix-button-content"[^>]*>([\d,]+)</span>'
  2219. % re.escape(count_name),
  2220. video_webpage, count_name, default=None))
  2221. like_count = _extract_count('like')
  2222. dislike_count = _extract_count('dislike')
  2223. if view_count is None:
  2224. view_count = str_to_int(self._search_regex(
  2225. r'<[^>]+class=["\']watch-view-count[^>]+>\s*([\d,\s]+)', video_webpage,
  2226. 'view count', default=None))
  2227. average_rating = (
  2228. float_or_none(video_details.get('averageRating'))
  2229. or try_get(video_info, lambda x: float_or_none(x['avg_rating'][0])))
  2230. # subtitles
  2231. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  2232. automatic_captions = self.extract_automatic_captions(video_id, video_webpage)
  2233. video_duration = try_get(
  2234. video_info, lambda x: int_or_none(x['length_seconds'][0]))
  2235. if not video_duration:
  2236. video_duration = int_or_none(video_details.get('lengthSeconds'))
  2237. if not video_duration:
  2238. video_duration = parse_duration(self._html_search_meta(
  2239. 'duration', video_webpage, 'video duration'))
  2240. # annotations
  2241. video_annotations = None
  2242. if self._downloader.params.get('writeannotations', False):
  2243. xsrf_token = self._search_regex(
  2244. r'([\'"])XSRF_TOKEN\1\s*:\s*([\'"])(?P<xsrf_token>[A-Za-z0-9+/=]+)\2',
  2245. video_webpage, 'xsrf token', group='xsrf_token', fatal=False)
  2246. invideo_url = try_get(
  2247. player_response, lambda x: x['annotations'][0]['playerAnnotationsUrlsRenderer']['invideoUrl'], compat_str)
  2248. if xsrf_token and invideo_url:
  2249. xsrf_field_name = self._search_regex(
  2250. r'([\'"])XSRF_FIELD_NAME\1\s*:\s*([\'"])(?P<xsrf_field_name>\w+)\2',
  2251. video_webpage, 'xsrf field name',
  2252. group='xsrf_field_name', default='session_token')
  2253. video_annotations = self._download_webpage(
  2254. self._proto_relative_url(invideo_url),
  2255. video_id, note='Downloading annotations',
  2256. errnote='Unable to download video annotations', fatal=False,
  2257. data=urlencode_postdata({xsrf_field_name: xsrf_token}))
  2258. chapters = self._extract_chapters(video_webpage, description_original, video_id, video_duration)
  2259. # Look for the DASH manifest
  2260. if self._downloader.params.get('youtube_include_dash_manifest', True):
  2261. dash_mpd_fatal = True
  2262. for mpd_url in dash_mpds:
  2263. dash_formats = {}
  2264. try:
  2265. def decrypt_sig(mobj):
  2266. s = mobj.group(1)
  2267. dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
  2268. return '/signature/%s' % dec_s
  2269. mpd_url = re.sub(r'/s/([a-fA-F0-9\.]+)', decrypt_sig, mpd_url)
  2270. for df in self._extract_mpd_formats(
  2271. mpd_url, video_id, fatal=dash_mpd_fatal,
  2272. formats_dict=self._formats):
  2273. if not df.get('filesize'):
  2274. df['filesize'] = _extract_filesize(df['url'])
  2275. # Do not overwrite DASH format found in some previous DASH manifest
  2276. if df['format_id'] not in dash_formats:
  2277. dash_formats[df['format_id']] = df
  2278. # Additional DASH manifests may end up in HTTP Error 403 therefore
  2279. # allow them to fail without bug report message if we already have
  2280. # some DASH manifest succeeded. This is temporary workaround to reduce
  2281. # burst of bug reports until we figure out the reason and whether it
  2282. # can be fixed at all.
  2283. dash_mpd_fatal = False
  2284. except (ExtractorError, KeyError) as e:
  2285. self.report_warning(
  2286. 'Skipping DASH manifest: %r' % e, video_id)
  2287. if dash_formats:
  2288. # Remove the formats we found through non-DASH, they
  2289. # contain less info and it can be wrong, because we use
  2290. # fixed values (for example the resolution). See
  2291. # https://github.com/ytdl-org/youtube-dl/issues/5774 for an
  2292. # example.
  2293. formats = [f for f in formats if f['format_id'] not in dash_formats.keys()]
  2294. formats.extend(dash_formats.values())
  2295. # Check for malformed aspect ratio
  2296. stretched_m = re.search(
  2297. r'<meta\s+property="og:video:tag".*?content="yt:stretch=(?P<w>[0-9]+):(?P<h>[0-9]+)">',
  2298. video_webpage)
  2299. if stretched_m:
  2300. w = float(stretched_m.group('w'))
  2301. h = float(stretched_m.group('h'))
  2302. # yt:stretch may hold invalid ratio data (e.g. for Q39EVAstoRM ratio is 17:0).
  2303. # We will only process correct ratios.
  2304. if w > 0 and h > 0:
  2305. ratio = w / h
  2306. for f in formats:
  2307. if f.get('vcodec') != 'none':
  2308. f['stretched_ratio'] = ratio
  2309. if not formats:
  2310. if 'reason' in video_info:
  2311. if 'The uploader has not made this video available in your country.' in video_info['reason']:
  2312. regions_allowed = self._html_search_meta(
  2313. 'regionsAllowed', video_webpage, default=None)
  2314. countries = regions_allowed.split(',') if regions_allowed else None
  2315. self.raise_geo_restricted(
  2316. msg=video_info['reason'][0], countries=countries)
  2317. reason = video_info['reason'][0]
  2318. if 'Invalid parameters' in reason:
  2319. unavailable_message = extract_unavailable_message()
  2320. if unavailable_message:
  2321. reason = unavailable_message
  2322. raise ExtractorError(
  2323. 'YouTube said: %s' % reason,
  2324. expected=True, video_id=video_id)
  2325. if video_info.get('license_info') or try_get(player_response, lambda x: x['streamingData']['licenseInfos']):
  2326. raise ExtractorError('This video is DRM protected.', expected=True)
  2327. self._sort_formats(formats)
  2328. self.mark_watched(video_id, video_info, player_response)
  2329. return {
  2330. 'id': video_id,
  2331. 'uploader': video_uploader,
  2332. 'uploader_id': video_uploader_id,
  2333. 'uploader_url': video_uploader_url,
  2334. 'channel_id': channel_id,
  2335. 'channel_url': channel_url,
  2336. 'upload_date': upload_date,
  2337. 'license': video_license,
  2338. 'creator': video_creator or artist,
  2339. 'title': video_title,
  2340. 'alt_title': video_alt_title or track,
  2341. 'thumbnails': thumbnails,
  2342. 'description': video_description,
  2343. 'categories': video_categories,
  2344. 'tags': video_tags,
  2345. 'subtitles': video_subtitles,
  2346. 'automatic_captions': automatic_captions,
  2347. 'duration': video_duration,
  2348. 'age_limit': 18 if age_gate else 0,
  2349. 'annotations': video_annotations,
  2350. 'chapters': chapters,
  2351. 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
  2352. 'view_count': view_count,
  2353. 'like_count': like_count,
  2354. 'dislike_count': dislike_count,
  2355. 'average_rating': average_rating,
  2356. 'formats': formats,
  2357. 'is_live': is_live,
  2358. 'start_time': start_time,
  2359. 'end_time': end_time,
  2360. 'series': series,
  2361. 'season_number': season_number,
  2362. 'episode_number': episode_number,
  2363. 'track': track,
  2364. 'artist': artist,
  2365. 'album': album,
  2366. 'release_date': release_date,
  2367. 'release_year': release_year,
  2368. }
  2369. class YoutubePlaylistIE(YoutubePlaylistBaseInfoExtractor):
  2370. IE_DESC = 'YouTube.com playlists'
  2371. _VALID_URL = r"""(?x)(?:
  2372. (?:https?://)?
  2373. (?:\w+\.)?
  2374. (?:
  2375. (?:
  2376. youtube(?:kids)?\.com|
  2377. invidio\.us
  2378. )
  2379. /
  2380. (?:
  2381. (?:course|view_play_list|my_playlists|artist|playlist|watch|embed/(?:videoseries|[0-9A-Za-z_-]{11}))
  2382. \? (?:.*?[&;])*? (?:p|a|list)=
  2383. | p/
  2384. )|
  2385. youtu\.be/[0-9A-Za-z_-]{11}\?.*?\blist=
  2386. )
  2387. (
  2388. (?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)?[0-9A-Za-z-_]{10,}
  2389. # Top tracks, they can also include dots
  2390. |(?:MC)[\w\.]*
  2391. )
  2392. .*
  2393. |
  2394. (%(playlist_id)s)
  2395. )""" % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
  2396. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
  2397. _VIDEO_RE_TPL = r'href="\s*/watch\?v=%s(?:&amp;(?:[^"]*?index=(?P<index>\d+))?(?:[^>]+>(?P<title>[^<]+))?)?'
  2398. _VIDEO_RE = _VIDEO_RE_TPL % r'(?P<id>[0-9A-Za-z_-]{11})'
  2399. IE_NAME = 'youtube:playlist'
  2400. _TESTS = [{
  2401. 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
  2402. 'info_dict': {
  2403. 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
  2404. 'uploader': 'Sergey M.',
  2405. 'id': 'PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
  2406. 'title': 'youtube-dl public playlist',
  2407. },
  2408. 'playlist_count': 1,
  2409. }, {
  2410. 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
  2411. 'info_dict': {
  2412. 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
  2413. 'uploader': 'Sergey M.',
  2414. 'id': 'PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
  2415. 'title': 'youtube-dl empty playlist',
  2416. },
  2417. 'playlist_count': 0,
  2418. }, {
  2419. 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
  2420. 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  2421. 'info_dict': {
  2422. 'title': '29C3: Not my department',
  2423. 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  2424. 'uploader': 'Christiaan008',
  2425. 'uploader_id': 'ChRiStIaAn008',
  2426. },
  2427. 'playlist_count': 96,
  2428. }, {
  2429. 'note': 'issue #673',
  2430. 'url': 'PLBB231211A4F62143',
  2431. 'info_dict': {
  2432. 'title': '[OLD]Team Fortress 2 (Class-based LP)',
  2433. 'id': 'PLBB231211A4F62143',
  2434. 'uploader': 'Wickydoo',
  2435. 'uploader_id': 'Wickydoo',
  2436. },
  2437. 'playlist_mincount': 26,
  2438. }, {
  2439. 'note': 'Large playlist',
  2440. 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
  2441. 'info_dict': {
  2442. 'title': 'Uploads from Cauchemar',
  2443. 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
  2444. 'uploader': 'Cauchemar',
  2445. 'uploader_id': 'Cauchemar89',
  2446. },
  2447. 'playlist_mincount': 799,
  2448. }, {
  2449. 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  2450. 'info_dict': {
  2451. 'title': 'YDL_safe_search',
  2452. 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  2453. },
  2454. 'playlist_count': 2,
  2455. 'skip': 'This playlist is private',
  2456. }, {
  2457. 'note': 'embedded',
  2458. 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  2459. 'playlist_count': 4,
  2460. 'info_dict': {
  2461. 'title': 'JODA15',
  2462. 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  2463. 'uploader': 'milan',
  2464. 'uploader_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
  2465. }
  2466. }, {
  2467. 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  2468. 'playlist_mincount': 485,
  2469. 'info_dict': {
  2470. 'title': '2018 Chinese New Singles (11/6 updated)',
  2471. 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  2472. 'uploader': 'LBK',
  2473. 'uploader_id': 'sdragonfang',
  2474. }
  2475. }, {
  2476. 'note': 'Embedded SWF player',
  2477. 'url': 'https://www.youtube.com/p/YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ?hl=en_US&fs=1&rel=0',
  2478. 'playlist_count': 4,
  2479. 'info_dict': {
  2480. 'title': 'JODA7',
  2481. 'id': 'YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ',
  2482. },
  2483. 'skip': 'This playlist does not exist',
  2484. }, {
  2485. 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
  2486. 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
  2487. 'info_dict': {
  2488. 'title': 'Uploads from Interstellar Movie',
  2489. 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
  2490. 'uploader': 'Interstellar Movie',
  2491. 'uploader_id': 'InterstellarMovie1',
  2492. },
  2493. 'playlist_mincount': 21,
  2494. }, {
  2495. # Playlist URL that does not actually serve a playlist
  2496. 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
  2497. 'info_dict': {
  2498. 'id': 'FqZTN594JQw',
  2499. 'ext': 'webm',
  2500. 'title': "Smiley's People 01 detective, Adventure Series, Action",
  2501. 'uploader': 'STREEM',
  2502. 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
  2503. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
  2504. 'upload_date': '20150526',
  2505. 'license': 'Standard YouTube License',
  2506. 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
  2507. 'categories': ['People & Blogs'],
  2508. 'tags': list,
  2509. 'view_count': int,
  2510. 'like_count': int,
  2511. 'dislike_count': int,
  2512. },
  2513. 'params': {
  2514. 'skip_download': True,
  2515. },
  2516. 'skip': 'This video is not available.',
  2517. 'add_ie': [YoutubeIE.ie_key()],
  2518. }, {
  2519. 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
  2520. 'info_dict': {
  2521. 'id': 'yeWKywCrFtk',
  2522. 'ext': 'mp4',
  2523. 'title': 'Small Scale Baler and Braiding Rugs',
  2524. 'uploader': 'Backus-Page House Museum',
  2525. 'uploader_id': 'backuspagemuseum',
  2526. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
  2527. 'upload_date': '20161008',
  2528. 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
  2529. 'categories': ['Nonprofits & Activism'],
  2530. 'tags': list,
  2531. 'like_count': int,
  2532. 'dislike_count': int,
  2533. },
  2534. 'params': {
  2535. 'noplaylist': True,
  2536. 'skip_download': True,
  2537. },
  2538. }, {
  2539. # https://github.com/ytdl-org/youtube-dl/issues/21844
  2540. 'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
  2541. 'info_dict': {
  2542. 'title': 'Data Analysis with Dr Mike Pound',
  2543. 'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
  2544. 'uploader_id': 'Computerphile',
  2545. 'uploader': 'Computerphile',
  2546. },
  2547. 'playlist_mincount': 11,
  2548. }, {
  2549. 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
  2550. 'only_matching': True,
  2551. }, {
  2552. 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
  2553. 'only_matching': True,
  2554. }, {
  2555. # music album playlist
  2556. 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
  2557. 'only_matching': True,
  2558. }, {
  2559. 'url': 'https://invidio.us/playlist?list=PLDIoUOhQQPlXr63I_vwF9GD8sAKh77dWU',
  2560. 'only_matching': True,
  2561. }, {
  2562. 'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
  2563. 'only_matching': True,
  2564. }]
  2565. def _real_initialize(self):
  2566. self._login()
  2567. def extract_videos_from_page(self, page):
  2568. ids_in_page = []
  2569. titles_in_page = []
  2570. for item in re.findall(
  2571. r'(<[^>]*\bdata-video-id\s*=\s*["\'][0-9A-Za-z_-]{11}[^>]+>)', page):
  2572. attrs = extract_attributes(item)
  2573. video_id = attrs['data-video-id']
  2574. video_title = unescapeHTML(attrs.get('data-title'))
  2575. if video_title:
  2576. video_title = video_title.strip()
  2577. ids_in_page.append(video_id)
  2578. titles_in_page.append(video_title)
  2579. # Fallback with old _VIDEO_RE
  2580. self.extract_videos_from_page_impl(
  2581. self._VIDEO_RE, page, ids_in_page, titles_in_page)
  2582. # Relaxed fallbacks
  2583. self.extract_videos_from_page_impl(
  2584. r'href="\s*/watch\?v\s*=\s*(?P<id>[0-9A-Za-z_-]{11})', page,
  2585. ids_in_page, titles_in_page)
  2586. self.extract_videos_from_page_impl(
  2587. r'data-video-ids\s*=\s*["\'](?P<id>[0-9A-Za-z_-]{11})', page,
  2588. ids_in_page, titles_in_page)
  2589. return zip(ids_in_page, titles_in_page)
  2590. def _extract_mix(self, playlist_id):
  2591. # The mixes are generated from a single video
  2592. # the id of the playlist is just 'RD' + video_id
  2593. ids = []
  2594. last_id = playlist_id[-11:]
  2595. for n in itertools.count(1):
  2596. url = 'https://www.youtube.com/watch?v=%s&list=%s' % (last_id, playlist_id)
  2597. webpage = self._download_webpage(
  2598. url, playlist_id, 'Downloading page {0} of Youtube mix'.format(n))
  2599. new_ids = orderedSet(re.findall(
  2600. r'''(?xs)data-video-username=".*?".*?
  2601. href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id),
  2602. webpage))
  2603. # Fetch new pages until all the videos are repeated, it seems that
  2604. # there are always 51 unique videos.
  2605. new_ids = [_id for _id in new_ids if _id not in ids]
  2606. if not new_ids:
  2607. break
  2608. ids.extend(new_ids)
  2609. last_id = ids[-1]
  2610. url_results = self._ids_to_results(ids)
  2611. search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
  2612. title_span = (
  2613. search_title('playlist-title')
  2614. or search_title('title long-title')
  2615. or search_title('title'))
  2616. title = clean_html(title_span)
  2617. return self.playlist_result(url_results, playlist_id, title)
  2618. def _extract_playlist(self, playlist_id):
  2619. url = self._TEMPLATE_URL % playlist_id
  2620. page = self._download_webpage(url, playlist_id)
  2621. # the yt-alert-message now has tabindex attribute (see https://github.com/ytdl-org/youtube-dl/issues/11604)
  2622. for match in re.findall(r'<div class="yt-alert-message"[^>]*>([^<]+)</div>', page):
  2623. match = match.strip()
  2624. # Check if the playlist exists or is private
  2625. mobj = re.match(r'[^<]*(?:The|This) playlist (?P<reason>does not exist|is private)[^<]*', match)
  2626. if mobj:
  2627. reason = mobj.group('reason')
  2628. message = 'This playlist %s' % reason
  2629. if 'private' in reason:
  2630. message += ', use --username or --netrc to access it'
  2631. message += '.'
  2632. raise ExtractorError(message, expected=True)
  2633. elif re.match(r'[^<]*Invalid parameters[^<]*', match):
  2634. raise ExtractorError(
  2635. 'Invalid parameters. Maybe URL is incorrect.',
  2636. expected=True)
  2637. elif re.match(r'[^<]*Choose your language[^<]*', match):
  2638. continue
  2639. else:
  2640. self.report_warning('Youtube gives an alert message: ' + match)
  2641. playlist_title = self._html_search_regex(
  2642. r'(?s)<h1 class="pl-header-title[^"]*"[^>]*>\s*(.*?)\s*</h1>',
  2643. page, 'title', default=None)
  2644. _UPLOADER_BASE = r'class=["\']pl-header-details[^>]+>\s*<li>\s*<a[^>]+\bhref='
  2645. uploader = self._html_search_regex(
  2646. r'%s["\']/(?:user|channel)/[^>]+>([^<]+)' % _UPLOADER_BASE,
  2647. page, 'uploader', default=None)
  2648. mobj = re.search(
  2649. r'%s(["\'])(?P<path>/(?:user|channel)/(?P<uploader_id>.+?))\1' % _UPLOADER_BASE,
  2650. page)
  2651. if mobj:
  2652. uploader_id = mobj.group('uploader_id')
  2653. uploader_url = compat_urlparse.urljoin(url, mobj.group('path'))
  2654. else:
  2655. uploader_id = uploader_url = None
  2656. has_videos = True
  2657. if not playlist_title:
  2658. try:
  2659. # Some playlist URLs don't actually serve a playlist (e.g.
  2660. # https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4)
  2661. next(self._entries(page, playlist_id))
  2662. except StopIteration:
  2663. has_videos = False
  2664. playlist = self.playlist_result(
  2665. self._entries(page, playlist_id), playlist_id, playlist_title)
  2666. playlist.update({
  2667. 'uploader': uploader,
  2668. 'uploader_id': uploader_id,
  2669. 'uploader_url': uploader_url,
  2670. })
  2671. return has_videos, playlist
  2672. def _check_download_just_video(self, url, playlist_id):
  2673. # Check if it's a video-specific URL
  2674. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  2675. video_id = query_dict.get('v', [None])[0] or self._search_regex(
  2676. r'(?:(?:^|//)youtu\.be/|youtube\.com/embed/(?!videoseries))([0-9A-Za-z_-]{11})', url,
  2677. 'video id', default=None)
  2678. if video_id:
  2679. if self._downloader.params.get('noplaylist'):
  2680. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  2681. return video_id, self.url_result(video_id, 'Youtube', video_id=video_id)
  2682. else:
  2683. self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  2684. return video_id, None
  2685. return None, None
  2686. def _real_extract(self, url):
  2687. # Extract playlist id
  2688. mobj = re.match(self._VALID_URL, url)
  2689. if mobj is None:
  2690. raise ExtractorError('Invalid URL: %s' % url)
  2691. playlist_id = mobj.group(1) or mobj.group(2)
  2692. video_id, video = self._check_download_just_video(url, playlist_id)
  2693. if video:
  2694. return video
  2695. if playlist_id.startswith(('RD', 'UL', 'PU')):
  2696. # Mixes require a custom extraction process
  2697. return self._extract_mix(playlist_id)
  2698. has_videos, playlist = self._extract_playlist(playlist_id)
  2699. if has_videos or not video_id:
  2700. return playlist
  2701. # Some playlist URLs don't actually serve a playlist (see
  2702. # https://github.com/ytdl-org/youtube-dl/issues/10537).
  2703. # Fallback to plain video extraction if there is a video id
  2704. # along with playlist id.
  2705. return self.url_result(video_id, 'Youtube', video_id=video_id)
  2706. class YoutubeChannelIE(YoutubePlaylistBaseInfoExtractor):
  2707. IE_DESC = 'YouTube.com channels'
  2708. _VALID_URL = r'https?://(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie|kids)?\.com|(?:www\.)?invidio\.us)/channel/(?P<id>[0-9A-Za-z_-]+)'
  2709. _TEMPLATE_URL = 'https://www.youtube.com/channel/%s/videos'
  2710. _VIDEO_RE = r'(?:title="(?P<title>[^"]+)"[^>]+)?href="/watch\?v=(?P<id>[0-9A-Za-z_-]+)&?'
  2711. IE_NAME = 'youtube:channel'
  2712. _TESTS = [{
  2713. 'note': 'paginated channel',
  2714. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
  2715. 'playlist_mincount': 91,
  2716. 'info_dict': {
  2717. 'id': 'UUKfVa3S1e4PHvxWcwyMMg8w',
  2718. 'title': 'Uploads from lex will',
  2719. 'uploader': 'lex will',
  2720. 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  2721. }
  2722. }, {
  2723. 'note': 'Age restricted channel',
  2724. # from https://www.youtube.com/user/DeusExOfficial
  2725. 'url': 'https://www.youtube.com/channel/UCs0ifCMCm1icqRbqhUINa0w',
  2726. 'playlist_mincount': 64,
  2727. 'info_dict': {
  2728. 'id': 'UUs0ifCMCm1icqRbqhUINa0w',
  2729. 'title': 'Uploads from Deus Ex',
  2730. 'uploader': 'Deus Ex',
  2731. 'uploader_id': 'DeusExOfficial',
  2732. },
  2733. }, {
  2734. 'url': 'https://invidio.us/channel/UC23qupoDRn9YOAVzeoxjOQA',
  2735. 'only_matching': True,
  2736. }, {
  2737. 'url': 'https://www.youtubekids.com/channel/UCyu8StPfZWapR6rfW_JgqcA',
  2738. 'only_matching': True,
  2739. }]
  2740. @classmethod
  2741. def suitable(cls, url):
  2742. return (False if YoutubePlaylistsIE.suitable(url) or YoutubeLiveIE.suitable(url)
  2743. else super(YoutubeChannelIE, cls).suitable(url))
  2744. def _build_template_url(self, url, channel_id):
  2745. return self._TEMPLATE_URL % channel_id
  2746. def _real_extract(self, url):
  2747. channel_id = self._match_id(url)
  2748. url = self._build_template_url(url, channel_id)
  2749. # Channel by page listing is restricted to 35 pages of 30 items, i.e. 1050 videos total (see #5778)
  2750. # Workaround by extracting as a playlist if managed to obtain channel playlist URL
  2751. # otherwise fallback on channel by page extraction
  2752. channel_page = self._download_webpage(
  2753. url + '?view=57', channel_id,
  2754. 'Downloading channel page', fatal=False)
  2755. if channel_page is False:
  2756. channel_playlist_id = False
  2757. else:
  2758. channel_playlist_id = self._html_search_meta(
  2759. 'channelId', channel_page, 'channel id', default=None)
  2760. if not channel_playlist_id:
  2761. channel_url = self._html_search_meta(
  2762. ('al:ios:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad'),
  2763. channel_page, 'channel url', default=None)
  2764. if channel_url:
  2765. channel_playlist_id = self._search_regex(
  2766. r'vnd\.youtube://user/([0-9A-Za-z_-]+)',
  2767. channel_url, 'channel id', default=None)
  2768. if channel_playlist_id and channel_playlist_id.startswith('UC'):
  2769. playlist_id = 'UU' + channel_playlist_id[2:]
  2770. return self.url_result(
  2771. compat_urlparse.urljoin(url, '/playlist?list=%s' % playlist_id), 'YoutubePlaylist')
  2772. channel_page = self._download_webpage(url, channel_id, 'Downloading page #1')
  2773. autogenerated = re.search(r'''(?x)
  2774. class="[^"]*?(?:
  2775. channel-header-autogenerated-label|
  2776. yt-channel-title-autogenerated
  2777. )[^"]*"''', channel_page) is not None
  2778. if autogenerated:
  2779. # The videos are contained in a single page
  2780. # the ajax pages can't be used, they are empty
  2781. entries = [
  2782. self.url_result(
  2783. video_id, 'Youtube', video_id=video_id,
  2784. video_title=video_title)
  2785. for video_id, video_title in self.extract_videos_from_page(channel_page)]
  2786. return self.playlist_result(entries, channel_id)
  2787. try:
  2788. next(self._entries(channel_page, channel_id))
  2789. except StopIteration:
  2790. alert_message = self._html_search_regex(
  2791. r'(?s)<div[^>]+class=(["\']).*?\byt-alert-message\b.*?\1[^>]*>(?P<alert>[^<]+)</div>',
  2792. channel_page, 'alert', default=None, group='alert')
  2793. if alert_message:
  2794. raise ExtractorError('Youtube said: %s' % alert_message, expected=True)
  2795. return self.playlist_result(self._entries(channel_page, channel_id), channel_id)
  2796. class YoutubeUserIE(YoutubeChannelIE):
  2797. IE_DESC = 'YouTube.com user videos (URL or "ytuser" keyword)'
  2798. _VALID_URL = r'(?:(?:https?://(?:\w+\.)?youtube\.com/(?:(?P<user>user|c)/)?(?!(?:attribution_link|watch|results|shared)(?:$|[^a-z_A-Z0-9%-])))|ytuser:)(?!feed/)(?P<id>[A-Za-z0-9_%-]+)'
  2799. _TEMPLATE_URL = 'https://www.youtube.com/%s/%s/videos'
  2800. IE_NAME = 'youtube:user'
  2801. _TESTS = [{
  2802. 'url': 'https://www.youtube.com/user/TheLinuxFoundation',
  2803. 'playlist_mincount': 320,
  2804. 'info_dict': {
  2805. 'id': 'UUfX55Sx5hEFjoC3cNs6mCUQ',
  2806. 'title': 'Uploads from The Linux Foundation',
  2807. 'uploader': 'The Linux Foundation',
  2808. 'uploader_id': 'TheLinuxFoundation',
  2809. }
  2810. }, {
  2811. # Only available via https://www.youtube.com/c/12minuteathlete/videos
  2812. # but not https://www.youtube.com/user/12minuteathlete/videos
  2813. 'url': 'https://www.youtube.com/c/12minuteathlete/videos',
  2814. 'playlist_mincount': 249,
  2815. 'info_dict': {
  2816. 'id': 'UUVjM-zV6_opMDx7WYxnjZiQ',
  2817. 'title': 'Uploads from 12 Minute Athlete',
  2818. 'uploader': '12 Minute Athlete',
  2819. 'uploader_id': 'the12minuteathlete',
  2820. }
  2821. }, {
  2822. 'url': 'ytuser:phihag',
  2823. 'only_matching': True,
  2824. }, {
  2825. 'url': 'https://www.youtube.com/c/gametrailers',
  2826. 'only_matching': True,
  2827. }, {
  2828. 'url': 'https://www.youtube.com/c/Pawe%C5%82Zadro%C5%BCniak',
  2829. 'only_matching': True,
  2830. }, {
  2831. 'url': 'https://www.youtube.com/gametrailers',
  2832. 'only_matching': True,
  2833. }, {
  2834. # This channel is not available, geo restricted to JP
  2835. 'url': 'https://www.youtube.com/user/kananishinoSMEJ/videos',
  2836. 'only_matching': True,
  2837. }]
  2838. @classmethod
  2839. def suitable(cls, url):
  2840. # Don't return True if the url can be extracted with other youtube
  2841. # extractor, the regex would is too permissive and it would match.
  2842. other_yt_ies = iter(klass for (name, klass) in globals().items() if name.startswith('Youtube') and name.endswith('IE') and klass is not cls)
  2843. if any(ie.suitable(url) for ie in other_yt_ies):
  2844. return False
  2845. else:
  2846. return super(YoutubeUserIE, cls).suitable(url)
  2847. def _build_template_url(self, url, channel_id):
  2848. mobj = re.match(self._VALID_URL, url)
  2849. return self._TEMPLATE_URL % (mobj.group('user') or 'user', mobj.group('id'))
  2850. class YoutubeLiveIE(YoutubeBaseInfoExtractor):
  2851. IE_DESC = 'YouTube.com live streams'
  2852. _VALID_URL = r'(?P<base_url>https?://(?:\w+\.)?youtube\.com/(?:(?:user|channel|c)/)?(?P<id>[^/]+))/live'
  2853. IE_NAME = 'youtube:live'
  2854. _TESTS = [{
  2855. 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
  2856. 'info_dict': {
  2857. 'id': 'a48o2S1cPoo',
  2858. 'ext': 'mp4',
  2859. 'title': 'The Young Turks - Live Main Show',
  2860. 'uploader': 'The Young Turks',
  2861. 'uploader_id': 'TheYoungTurks',
  2862. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
  2863. 'upload_date': '20150715',
  2864. 'license': 'Standard YouTube License',
  2865. 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
  2866. 'categories': ['News & Politics'],
  2867. 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
  2868. 'like_count': int,
  2869. 'dislike_count': int,
  2870. },
  2871. 'params': {
  2872. 'skip_download': True,
  2873. },
  2874. }, {
  2875. 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
  2876. 'only_matching': True,
  2877. }, {
  2878. 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
  2879. 'only_matching': True,
  2880. }, {
  2881. 'url': 'https://www.youtube.com/TheYoungTurks/live',
  2882. 'only_matching': True,
  2883. }]
  2884. def _real_extract(self, url):
  2885. mobj = re.match(self._VALID_URL, url)
  2886. channel_id = mobj.group('id')
  2887. base_url = mobj.group('base_url')
  2888. webpage = self._download_webpage(url, channel_id, fatal=False)
  2889. if webpage:
  2890. page_type = self._og_search_property(
  2891. 'type', webpage, 'page type', default='')
  2892. video_id = self._html_search_meta(
  2893. 'videoId', webpage, 'video id', default=None)
  2894. if page_type.startswith('video') and video_id and re.match(
  2895. r'^[0-9A-Za-z_-]{11}$', video_id):
  2896. return self.url_result(video_id, YoutubeIE.ie_key())
  2897. return self.url_result(base_url)
  2898. class YoutubePlaylistsIE(YoutubePlaylistsBaseInfoExtractor):
  2899. IE_DESC = 'YouTube.com user/channel playlists'
  2900. _VALID_URL = r'https?://(?:\w+\.)?youtube\.com/(?:user|channel|c)/(?P<id>[^/]+)/playlists'
  2901. IE_NAME = 'youtube:playlists'
  2902. _TESTS = [{
  2903. 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
  2904. 'playlist_mincount': 4,
  2905. 'info_dict': {
  2906. 'id': 'ThirstForScience',
  2907. 'title': 'ThirstForScience',
  2908. },
  2909. }, {
  2910. # with "Load more" button
  2911. 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
  2912. 'playlist_mincount': 70,
  2913. 'info_dict': {
  2914. 'id': 'igorkle1',
  2915. 'title': 'Игорь Клейнер',
  2916. },
  2917. }, {
  2918. 'url': 'https://www.youtube.com/channel/UCiU1dHvZObB2iP6xkJ__Icw/playlists',
  2919. 'playlist_mincount': 17,
  2920. 'info_dict': {
  2921. 'id': 'UCiU1dHvZObB2iP6xkJ__Icw',
  2922. 'title': 'Chem Player',
  2923. },
  2924. 'skip': 'Blocked',
  2925. }, {
  2926. 'url': 'https://www.youtube.com/c/ChristophLaimer/playlists',
  2927. 'only_matching': True,
  2928. }]
  2929. class YoutubeSearchBaseInfoExtractor(YoutubePlaylistBaseInfoExtractor):
  2930. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})(?:[^"]*"[^>]+\btitle="(?P<title>[^"]+))?'
  2931. class YoutubeSearchIE(SearchInfoExtractor, YoutubeSearchBaseInfoExtractor):
  2932. IE_DESC = 'YouTube.com searches'
  2933. # there doesn't appear to be a real limit, for example if you search for
  2934. # 'python' you get more than 8.000.000 results
  2935. _MAX_RESULTS = float('inf')
  2936. IE_NAME = 'youtube:search'
  2937. _SEARCH_KEY = 'ytsearch'
  2938. _SEARCH_PARAMS = None
  2939. _TESTS = []
  2940. def _entries(self, query, n):
  2941. data = {
  2942. 'context': {
  2943. 'client': {
  2944. 'clientName': 'WEB',
  2945. 'clientVersion': '2.20201021.03.00',
  2946. }
  2947. },
  2948. 'query': query,
  2949. }
  2950. if self._SEARCH_PARAMS:
  2951. data['params'] = self._SEARCH_PARAMS
  2952. total = 0
  2953. for page_num in itertools.count(1):
  2954. search = self._download_json(
  2955. 'https://www.youtube.com/youtubei/v1/search?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
  2956. video_id='query "%s"' % query,
  2957. note='Downloading page %s' % page_num,
  2958. errnote='Unable to download API page', fatal=False,
  2959. data=json.dumps(data).encode('utf8'),
  2960. headers={'content-type': 'application/json'})
  2961. if not search:
  2962. break
  2963. slr_contents = try_get(
  2964. search,
  2965. (lambda x: x['contents']['twoColumnSearchResultsRenderer']['primaryContents']['sectionListRenderer']['contents'],
  2966. lambda x: x['onResponseReceivedCommands'][0]['appendContinuationItemsAction']['continuationItems']),
  2967. list)
  2968. if not slr_contents:
  2969. break
  2970. isr_contents = try_get(
  2971. slr_contents,
  2972. lambda x: x[0]['itemSectionRenderer']['contents'],
  2973. list)
  2974. if not isr_contents:
  2975. break
  2976. for content in isr_contents:
  2977. if not isinstance(content, dict):
  2978. continue
  2979. video = content.get('videoRenderer')
  2980. if not isinstance(video, dict):
  2981. continue
  2982. video_id = video.get('videoId')
  2983. if not video_id:
  2984. continue
  2985. title = try_get(video, lambda x: x['title']['runs'][0]['text'], compat_str)
  2986. description = try_get(video, lambda x: x['descriptionSnippet']['runs'][0]['text'], compat_str)
  2987. duration = parse_duration(try_get(video, lambda x: x['lengthText']['simpleText'], compat_str))
  2988. view_count_text = try_get(video, lambda x: x['viewCountText']['simpleText'], compat_str) or ''
  2989. view_count = int_or_none(self._search_regex(
  2990. r'^(\d+)', re.sub(r'\s', '', view_count_text),
  2991. 'view count', default=None))
  2992. uploader = try_get(video, lambda x: x['ownerText']['runs'][0]['text'], compat_str)
  2993. total += 1
  2994. yield {
  2995. '_type': 'url_transparent',
  2996. 'ie_key': YoutubeIE.ie_key(),
  2997. 'id': video_id,
  2998. 'url': video_id,
  2999. 'title': title,
  3000. 'description': description,
  3001. 'duration': duration,
  3002. 'view_count': view_count,
  3003. 'uploader': uploader,
  3004. }
  3005. if total == n:
  3006. return
  3007. token = try_get(
  3008. slr_contents,
  3009. lambda x: x[1]['continuationItemRenderer']['continuationEndpoint']['continuationCommand']['token'],
  3010. compat_str)
  3011. if not token:
  3012. break
  3013. data['continuation'] = token
  3014. def _get_n_results(self, query, n):
  3015. """Get a specified number of results for a query"""
  3016. return self.playlist_result(self._entries(query, n), query)
  3017. class YoutubeSearchDateIE(YoutubeSearchIE):
  3018. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  3019. _SEARCH_KEY = 'ytsearchdate'
  3020. IE_DESC = 'YouTube.com searches, newest videos first'
  3021. _SEARCH_PARAMS = 'CAI%3D'
  3022. class YoutubeSearchURLIE(YoutubeSearchBaseInfoExtractor):
  3023. IE_DESC = 'YouTube.com search URLs'
  3024. IE_NAME = 'youtube:search_url'
  3025. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?P<query>[^&]+)(?:[&]|$)'
  3026. _TESTS = [{
  3027. 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
  3028. 'playlist_mincount': 5,
  3029. 'info_dict': {
  3030. 'title': 'youtube-dl test video',
  3031. }
  3032. }, {
  3033. 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
  3034. 'only_matching': True,
  3035. }]
  3036. def _real_extract(self, url):
  3037. mobj = re.match(self._VALID_URL, url)
  3038. query = compat_urllib_parse_unquote_plus(mobj.group('query'))
  3039. webpage = self._download_webpage(url, query)
  3040. return self.playlist_result(self._process_page(webpage), playlist_title=query)
  3041. class YoutubeShowIE(YoutubePlaylistsBaseInfoExtractor):
  3042. IE_DESC = 'YouTube.com (multi-season) shows'
  3043. _VALID_URL = r'https?://(?:www\.)?youtube\.com/show/(?P<id>[^?#]*)'
  3044. IE_NAME = 'youtube:show'
  3045. _TESTS = [{
  3046. 'url': 'https://www.youtube.com/show/airdisasters',
  3047. 'playlist_mincount': 5,
  3048. 'info_dict': {
  3049. 'id': 'airdisasters',
  3050. 'title': 'Air Disasters',
  3051. }
  3052. }]
  3053. def _real_extract(self, url):
  3054. playlist_id = self._match_id(url)
  3055. return super(YoutubeShowIE, self)._real_extract(
  3056. 'https://www.youtube.com/show/%s/playlists' % playlist_id)
  3057. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  3058. """
  3059. Base class for feed extractors
  3060. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  3061. """
  3062. _LOGIN_REQUIRED = True
  3063. @property
  3064. def IE_NAME(self):
  3065. return 'youtube:%s' % self._FEED_NAME
  3066. def _real_initialize(self):
  3067. self._login()
  3068. def _entries(self, page):
  3069. # The extraction process is the same as for playlists, but the regex
  3070. # for the video ids doesn't contain an index
  3071. ids = []
  3072. more_widget_html = content_html = page
  3073. for page_num in itertools.count(1):
  3074. matches = re.findall(r'href="\s*/watch\?v=([0-9A-Za-z_-]{11})', content_html)
  3075. # 'recommended' feed has infinite 'load more' and each new portion spins
  3076. # the same videos in (sometimes) slightly different order, so we'll check
  3077. # for unicity and break when portion has no new videos
  3078. new_ids = list(filter(lambda video_id: video_id not in ids, orderedSet(matches)))
  3079. if not new_ids:
  3080. break
  3081. ids.extend(new_ids)
  3082. for entry in self._ids_to_results(new_ids):
  3083. yield entry
  3084. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  3085. if not mobj:
  3086. break
  3087. more = self._download_json(
  3088. 'https://www.youtube.com/%s' % mobj.group('more'), self._PLAYLIST_TITLE,
  3089. 'Downloading page #%s' % page_num,
  3090. transform_source=uppercase_escape,
  3091. headers=self._YOUTUBE_CLIENT_HEADERS)
  3092. content_html = more['content_html']
  3093. more_widget_html = more['load_more_widget_html']
  3094. def _real_extract(self, url):
  3095. page = self._download_webpage(
  3096. 'https://www.youtube.com/feed/%s' % self._FEED_NAME,
  3097. self._PLAYLIST_TITLE)
  3098. return self.playlist_result(
  3099. self._entries(page), playlist_title=self._PLAYLIST_TITLE)
  3100. class YoutubeWatchLaterIE(YoutubePlaylistIE):
  3101. IE_NAME = 'youtube:watchlater'
  3102. IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
  3103. _VALID_URL = r'https?://(?:www\.)?youtube\.com/(?:feed/watch_later|(?:playlist|watch)\?(?:.+&)?list=WL)|:ytwatchlater'
  3104. _TESTS = [{
  3105. 'url': 'https://www.youtube.com/playlist?list=WL',
  3106. 'only_matching': True,
  3107. }, {
  3108. 'url': 'https://www.youtube.com/watch?v=bCNU9TrbiRk&index=1&list=WL',
  3109. 'only_matching': True,
  3110. }]
  3111. def _real_extract(self, url):
  3112. _, video = self._check_download_just_video(url, 'WL')
  3113. if video:
  3114. return video
  3115. _, playlist = self._extract_playlist('WL')
  3116. return playlist
  3117. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  3118. IE_NAME = 'youtube:favorites'
  3119. IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
  3120. _VALID_URL = r'https?://(?:www\.)?youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  3121. _LOGIN_REQUIRED = True
  3122. def _real_extract(self, url):
  3123. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  3124. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, 'favourites playlist id')
  3125. return self.url_result(playlist_id, 'YoutubePlaylist')
  3126. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  3127. IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
  3128. _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  3129. _FEED_NAME = 'recommended'
  3130. _PLAYLIST_TITLE = 'Youtube Recommended videos'
  3131. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  3132. IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  3133. _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  3134. _FEED_NAME = 'subscriptions'
  3135. _PLAYLIST_TITLE = 'Youtube Subscriptions'
  3136. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  3137. IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
  3138. _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/history|:ythistory'
  3139. _FEED_NAME = 'history'
  3140. _PLAYLIST_TITLE = 'Youtube History'
  3141. class YoutubeTruncatedURLIE(InfoExtractor):
  3142. IE_NAME = 'youtube:truncated_url'
  3143. IE_DESC = False # Do not list
  3144. _VALID_URL = r'''(?x)
  3145. (?:https?://)?
  3146. (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
  3147. (?:watch\?(?:
  3148. feature=[a-z_]+|
  3149. annotation_id=annotation_[^&]+|
  3150. x-yt-cl=[0-9]+|
  3151. hl=[^&]*|
  3152. t=[0-9]+
  3153. )?
  3154. |
  3155. attribution_link\?a=[^&]+
  3156. )
  3157. $
  3158. '''
  3159. _TESTS = [{
  3160. 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
  3161. 'only_matching': True,
  3162. }, {
  3163. 'url': 'https://www.youtube.com/watch?',
  3164. 'only_matching': True,
  3165. }, {
  3166. 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
  3167. 'only_matching': True,
  3168. }, {
  3169. 'url': 'https://www.youtube.com/watch?feature=foo',
  3170. 'only_matching': True,
  3171. }, {
  3172. 'url': 'https://www.youtube.com/watch?hl=en-GB',
  3173. 'only_matching': True,
  3174. }, {
  3175. 'url': 'https://www.youtube.com/watch?t=2372',
  3176. 'only_matching': True,
  3177. }]
  3178. def _real_extract(self, url):
  3179. raise ExtractorError(
  3180. 'Did you forget to quote the URL? Remember that & is a meta '
  3181. 'character in most shells, so you want to put the URL in quotes, '
  3182. 'like youtube-dl '
  3183. '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  3184. ' or simply youtube-dl BaW_jenozKc .',
  3185. expected=True)
  3186. class YoutubeTruncatedIDIE(InfoExtractor):
  3187. IE_NAME = 'youtube:truncated_id'
  3188. IE_DESC = False # Do not list
  3189. _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
  3190. _TESTS = [{
  3191. 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
  3192. 'only_matching': True,
  3193. }]
  3194. def _real_extract(self, url):
  3195. video_id = self._match_id(url)
  3196. raise ExtractorError(
  3197. 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),
  3198. expected=True)