You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3338 lines
149 KiB

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