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.

3337 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'(?P<sig>[a-zA-Z0-9$]+)\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
  1262. # Obsolete patterns
  1263. r'(["\'])signature\1\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1264. r'\.sig\|\|(?P<sig>[a-zA-Z0-9$]+)\(',
  1265. r'yt\.akamaized\.net/\)\s*\|\|\s*.*?\s*[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?:encodeURIComponent\s*\()?\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1266. r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1267. r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1268. r'\bc\s*&&\s*a\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1269. r'\bc\s*&&\s*[a-zA-Z0-9]+\.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. jscode, 'Initial JS player signature function name', group='sig')
  1272. jsi = JSInterpreter(jscode)
  1273. initial_function = jsi.extract_function(funcname)
  1274. return lambda s: initial_function([s])
  1275. def _parse_sig_swf(self, file_contents):
  1276. swfi = SWFInterpreter(file_contents)
  1277. TARGET_CLASSNAME = 'SignatureDecipher'
  1278. searched_class = swfi.extract_class(TARGET_CLASSNAME)
  1279. initial_function = swfi.extract_function(searched_class, 'decipher')
  1280. return lambda s: initial_function([s])
  1281. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  1282. """Turn the encrypted s field into a working signature"""
  1283. if player_url is None:
  1284. raise ExtractorError('Cannot decrypt signature without player_url')
  1285. if player_url.startswith('//'):
  1286. player_url = 'https:' + player_url
  1287. elif not re.match(r'https?://', player_url):
  1288. player_url = compat_urlparse.urljoin(
  1289. 'https://www.youtube.com', player_url)
  1290. try:
  1291. player_id = (player_url, self._signature_cache_id(s))
  1292. if player_id not in self._player_cache:
  1293. func = self._extract_signature_function(
  1294. video_id, player_url, s
  1295. )
  1296. self._player_cache[player_id] = func
  1297. func = self._player_cache[player_id]
  1298. if self._downloader.params.get('youtube_print_sig_code'):
  1299. self._print_sig_code(func, s)
  1300. return func(s)
  1301. except Exception as e:
  1302. tb = traceback.format_exc()
  1303. raise ExtractorError(
  1304. 'Signature extraction failed: ' + tb, cause=e)
  1305. def _get_subtitles(self, video_id, webpage):
  1306. try:
  1307. subs_doc = self._download_xml(
  1308. 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  1309. video_id, note=False)
  1310. except ExtractorError as err:
  1311. self._downloader.report_warning('unable to download video subtitles: %s' % error_to_compat_str(err))
  1312. return {}
  1313. sub_lang_list = {}
  1314. for track in subs_doc.findall('track'):
  1315. lang = track.attrib['lang_code']
  1316. if lang in sub_lang_list:
  1317. continue
  1318. sub_formats = []
  1319. for ext in self._SUBTITLE_FORMATS:
  1320. params = compat_urllib_parse_urlencode({
  1321. 'lang': lang,
  1322. 'v': video_id,
  1323. 'fmt': ext,
  1324. 'name': track.attrib['name'].encode('utf-8'),
  1325. })
  1326. sub_formats.append({
  1327. 'url': 'https://www.youtube.com/api/timedtext?' + params,
  1328. 'ext': ext,
  1329. })
  1330. sub_lang_list[lang] = sub_formats
  1331. if not sub_lang_list:
  1332. self._downloader.report_warning('video doesn\'t have subtitles')
  1333. return {}
  1334. return sub_lang_list
  1335. def _get_ytplayer_config(self, video_id, webpage):
  1336. patterns = (
  1337. # User data may contain arbitrary character sequences that may affect
  1338. # JSON extraction with regex, e.g. when '};' is contained the second
  1339. # regex won't capture the whole JSON. Yet working around by trying more
  1340. # concrete regex first keeping in mind proper quoted string handling
  1341. # to be implemented in future that will replace this workaround (see
  1342. # https://github.com/ytdl-org/youtube-dl/issues/7468,
  1343. # https://github.com/ytdl-org/youtube-dl/pull/7599)
  1344. r';ytplayer\.config\s*=\s*({.+?});ytplayer',
  1345. r';ytplayer\.config\s*=\s*({.+?});',
  1346. )
  1347. config = self._search_regex(
  1348. patterns, webpage, 'ytplayer.config', default=None)
  1349. if config:
  1350. return self._parse_json(
  1351. uppercase_escape(config), video_id, fatal=False)
  1352. def _get_automatic_captions(self, video_id, webpage):
  1353. """We need the webpage for getting the captions url, pass it as an
  1354. argument to speed up the process."""
  1355. self.to_screen('%s: Looking for automatic captions' % video_id)
  1356. player_config = self._get_ytplayer_config(video_id, webpage)
  1357. err_msg = 'Couldn\'t find automatic captions for %s' % video_id
  1358. if not player_config:
  1359. self._downloader.report_warning(err_msg)
  1360. return {}
  1361. try:
  1362. args = player_config['args']
  1363. caption_url = args.get('ttsurl')
  1364. if caption_url:
  1365. timestamp = args['timestamp']
  1366. # We get the available subtitles
  1367. list_params = compat_urllib_parse_urlencode({
  1368. 'type': 'list',
  1369. 'tlangs': 1,
  1370. 'asrs': 1,
  1371. })
  1372. list_url = caption_url + '&' + list_params
  1373. caption_list = self._download_xml(list_url, video_id)
  1374. original_lang_node = caption_list.find('track')
  1375. if original_lang_node is None:
  1376. self._downloader.report_warning('Video doesn\'t have automatic captions')
  1377. return {}
  1378. original_lang = original_lang_node.attrib['lang_code']
  1379. caption_kind = original_lang_node.attrib.get('kind', '')
  1380. sub_lang_list = {}
  1381. for lang_node in caption_list.findall('target'):
  1382. sub_lang = lang_node.attrib['lang_code']
  1383. sub_formats = []
  1384. for ext in self._SUBTITLE_FORMATS:
  1385. params = compat_urllib_parse_urlencode({
  1386. 'lang': original_lang,
  1387. 'tlang': sub_lang,
  1388. 'fmt': ext,
  1389. 'ts': timestamp,
  1390. 'kind': caption_kind,
  1391. })
  1392. sub_formats.append({
  1393. 'url': caption_url + '&' + params,
  1394. 'ext': ext,
  1395. })
  1396. sub_lang_list[sub_lang] = sub_formats
  1397. return sub_lang_list
  1398. def make_captions(sub_url, sub_langs):
  1399. parsed_sub_url = compat_urllib_parse_urlparse(sub_url)
  1400. caption_qs = compat_parse_qs(parsed_sub_url.query)
  1401. captions = {}
  1402. for sub_lang in sub_langs:
  1403. sub_formats = []
  1404. for ext in self._SUBTITLE_FORMATS:
  1405. caption_qs.update({
  1406. 'tlang': [sub_lang],
  1407. 'fmt': [ext],
  1408. })
  1409. sub_url = compat_urlparse.urlunparse(parsed_sub_url._replace(
  1410. query=compat_urllib_parse_urlencode(caption_qs, True)))
  1411. sub_formats.append({
  1412. 'url': sub_url,
  1413. 'ext': ext,
  1414. })
  1415. captions[sub_lang] = sub_formats
  1416. return captions
  1417. # New captions format as of 22.06.2017
  1418. player_response = args.get('player_response')
  1419. if player_response and isinstance(player_response, compat_str):
  1420. player_response = self._parse_json(
  1421. player_response, video_id, fatal=False)
  1422. if player_response:
  1423. renderer = player_response['captions']['playerCaptionsTracklistRenderer']
  1424. base_url = renderer['captionTracks'][0]['baseUrl']
  1425. sub_lang_list = []
  1426. for lang in renderer['translationLanguages']:
  1427. lang_code = lang.get('languageCode')
  1428. if lang_code:
  1429. sub_lang_list.append(lang_code)
  1430. return make_captions(base_url, sub_lang_list)
  1431. # Some videos don't provide ttsurl but rather caption_tracks and
  1432. # caption_translation_languages (e.g. 20LmZk1hakA)
  1433. # Does not used anymore as of 22.06.2017
  1434. caption_tracks = args['caption_tracks']
  1435. caption_translation_languages = args['caption_translation_languages']
  1436. caption_url = compat_parse_qs(caption_tracks.split(',')[0])['u'][0]
  1437. sub_lang_list = []
  1438. for lang in caption_translation_languages.split(','):
  1439. lang_qs = compat_parse_qs(compat_urllib_parse_unquote_plus(lang))
  1440. sub_lang = lang_qs.get('lc', [None])[0]
  1441. if sub_lang:
  1442. sub_lang_list.append(sub_lang)
  1443. return make_captions(caption_url, sub_lang_list)
  1444. # An extractor error can be raise by the download process if there are
  1445. # no automatic captions but there are subtitles
  1446. except (KeyError, IndexError, ExtractorError):
  1447. self._downloader.report_warning(err_msg)
  1448. return {}
  1449. def _mark_watched(self, video_id, video_info, player_response):
  1450. playback_url = url_or_none(try_get(
  1451. player_response,
  1452. lambda x: x['playbackTracking']['videostatsPlaybackUrl']['baseUrl']) or try_get(
  1453. video_info, lambda x: x['videostats_playback_base_url'][0]))
  1454. if not playback_url:
  1455. return
  1456. parsed_playback_url = compat_urlparse.urlparse(playback_url)
  1457. qs = compat_urlparse.parse_qs(parsed_playback_url.query)
  1458. # cpn generation algorithm is reverse engineered from base.js.
  1459. # In fact it works even with dummy cpn.
  1460. CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
  1461. cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
  1462. qs.update({
  1463. 'ver': ['2'],
  1464. 'cpn': [cpn],
  1465. })
  1466. playback_url = compat_urlparse.urlunparse(
  1467. parsed_playback_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
  1468. self._download_webpage(
  1469. playback_url, video_id, 'Marking watched',
  1470. 'Unable to mark watched', fatal=False)
  1471. @staticmethod
  1472. def _extract_urls(webpage):
  1473. # Embedded YouTube player
  1474. entries = [
  1475. unescapeHTML(mobj.group('url'))
  1476. for mobj in re.finditer(r'''(?x)
  1477. (?:
  1478. <iframe[^>]+?src=|
  1479. data-video-url=|
  1480. <embed[^>]+?src=|
  1481. embedSWF\(?:\s*|
  1482. <object[^>]+data=|
  1483. new\s+SWFObject\(
  1484. )
  1485. (["\'])
  1486. (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
  1487. (?:embed|v|p)/[0-9A-Za-z_-]{11}.*?)
  1488. \1''', webpage)]
  1489. # lazyYT YouTube embed
  1490. entries.extend(list(map(
  1491. unescapeHTML,
  1492. re.findall(r'class="lazyYT" data-youtube-id="([^"]+)"', webpage))))
  1493. # Wordpress "YouTube Video Importer" plugin
  1494. matches = re.findall(r'''(?x)<div[^>]+
  1495. class=(?P<q1>[\'"])[^\'"]*\byvii_single_video_player\b[^\'"]*(?P=q1)[^>]+
  1496. data-video_id=(?P<q2>[\'"])([^\'"]+)(?P=q2)''', webpage)
  1497. entries.extend(m[-1] for m in matches)
  1498. return entries
  1499. @staticmethod
  1500. def _extract_url(webpage):
  1501. urls = YoutubeIE._extract_urls(webpage)
  1502. return urls[0] if urls else None
  1503. @classmethod
  1504. def extract_id(cls, url):
  1505. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  1506. if mobj is None:
  1507. raise ExtractorError('Invalid URL: %s' % url)
  1508. video_id = mobj.group(2)
  1509. return video_id
  1510. @staticmethod
  1511. def _extract_chapters(description, duration):
  1512. if not description:
  1513. return None
  1514. chapter_lines = re.findall(
  1515. r'(?:^|<br\s*/>)([^<]*<a[^>]+onclick=["\']yt\.www\.watch\.player\.seekTo[^>]+>(\d{1,2}:\d{1,2}(?::\d{1,2})?)</a>[^>]*)(?=$|<br\s*/>)',
  1516. description)
  1517. if not chapter_lines:
  1518. return None
  1519. chapters = []
  1520. for next_num, (chapter_line, time_point) in enumerate(
  1521. chapter_lines, start=1):
  1522. start_time = parse_duration(time_point)
  1523. if start_time is None:
  1524. continue
  1525. if start_time > duration:
  1526. break
  1527. end_time = (duration if next_num == len(chapter_lines)
  1528. else parse_duration(chapter_lines[next_num][1]))
  1529. if end_time is None:
  1530. continue
  1531. if end_time > duration:
  1532. end_time = duration
  1533. if start_time > end_time:
  1534. break
  1535. chapter_title = re.sub(
  1536. r'<a[^>]+>[^<]+</a>', '', chapter_line).strip(' \t-')
  1537. chapter_title = re.sub(r'\s+', ' ', chapter_title)
  1538. chapters.append({
  1539. 'start_time': start_time,
  1540. 'end_time': end_time,
  1541. 'title': chapter_title,
  1542. })
  1543. return chapters
  1544. def _real_extract(self, url):
  1545. url, smuggled_data = unsmuggle_url(url, {})
  1546. proto = (
  1547. 'http' if self._downloader.params.get('prefer_insecure', False)
  1548. else 'https')
  1549. start_time = None
  1550. end_time = None
  1551. parsed_url = compat_urllib_parse_urlparse(url)
  1552. for component in [parsed_url.fragment, parsed_url.query]:
  1553. query = compat_parse_qs(component)
  1554. if start_time is None and 't' in query:
  1555. start_time = parse_duration(query['t'][0])
  1556. if start_time is None and 'start' in query:
  1557. start_time = parse_duration(query['start'][0])
  1558. if end_time is None and 'end' in query:
  1559. end_time = parse_duration(query['end'][0])
  1560. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  1561. mobj = re.search(self._NEXT_URL_RE, url)
  1562. if mobj:
  1563. url = proto + '://www.youtube.com/' + compat_urllib_parse_unquote(mobj.group(1)).lstrip('/')
  1564. video_id = self.extract_id(url)
  1565. # Get video webpage
  1566. url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1&bpctr=9999999999' % video_id
  1567. video_webpage = self._download_webpage(url, video_id)
  1568. # Attempt to extract SWF player URL
  1569. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  1570. if mobj is not None:
  1571. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  1572. else:
  1573. player_url = None
  1574. dash_mpds = []
  1575. def add_dash_mpd(video_info):
  1576. dash_mpd = video_info.get('dashmpd')
  1577. if dash_mpd and dash_mpd[0] not in dash_mpds:
  1578. dash_mpds.append(dash_mpd[0])
  1579. def add_dash_mpd_pr(pl_response):
  1580. dash_mpd = url_or_none(try_get(
  1581. pl_response, lambda x: x['streamingData']['dashManifestUrl'],
  1582. compat_str))
  1583. if dash_mpd and dash_mpd not in dash_mpds:
  1584. dash_mpds.append(dash_mpd)
  1585. is_live = None
  1586. view_count = None
  1587. def extract_view_count(v_info):
  1588. return int_or_none(try_get(v_info, lambda x: x['view_count'][0]))
  1589. def extract_token(v_info):
  1590. return dict_get(v_info, ('account_playback_token', 'accountPlaybackToken', 'token'))
  1591. def extract_player_response(player_response, video_id):
  1592. pl_response = str_or_none(player_response)
  1593. if not pl_response:
  1594. return
  1595. pl_response = self._parse_json(pl_response, video_id, fatal=False)
  1596. if isinstance(pl_response, dict):
  1597. add_dash_mpd_pr(pl_response)
  1598. return pl_response
  1599. player_response = {}
  1600. # Get video info
  1601. embed_webpage = None
  1602. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  1603. age_gate = True
  1604. # We simulate the access to the video from www.youtube.com/v/{video_id}
  1605. # this can be viewed without login into Youtube
  1606. url = proto + '://www.youtube.com/embed/%s' % video_id
  1607. embed_webpage = self._download_webpage(url, video_id, 'Downloading embed webpage')
  1608. data = compat_urllib_parse_urlencode({
  1609. 'video_id': video_id,
  1610. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  1611. 'sts': self._search_regex(
  1612. r'"sts"\s*:\s*(\d+)', embed_webpage, 'sts', default=''),
  1613. })
  1614. video_info_url = proto + '://www.youtube.com/get_video_info?' + data
  1615. video_info_webpage = self._download_webpage(
  1616. video_info_url, video_id,
  1617. note='Refetching age-gated info webpage',
  1618. errnote='unable to download video info webpage')
  1619. video_info = compat_parse_qs(video_info_webpage)
  1620. pl_response = video_info.get('player_response', [None])[0]
  1621. player_response = extract_player_response(pl_response, video_id)
  1622. add_dash_mpd(video_info)
  1623. view_count = extract_view_count(video_info)
  1624. else:
  1625. age_gate = False
  1626. video_info = None
  1627. sts = None
  1628. # Try looking directly into the video webpage
  1629. ytplayer_config = self._get_ytplayer_config(video_id, video_webpage)
  1630. if ytplayer_config:
  1631. args = ytplayer_config['args']
  1632. if args.get('url_encoded_fmt_stream_map') or args.get('hlsvp'):
  1633. # Convert to the same format returned by compat_parse_qs
  1634. video_info = dict((k, [v]) for k, v in args.items())
  1635. add_dash_mpd(video_info)
  1636. # Rental video is not rented but preview is available (e.g.
  1637. # https://www.youtube.com/watch?v=yYr8q0y5Jfg,
  1638. # https://github.com/ytdl-org/youtube-dl/issues/10532)
  1639. if not video_info and args.get('ypc_vid'):
  1640. return self.url_result(
  1641. args['ypc_vid'], YoutubeIE.ie_key(), video_id=args['ypc_vid'])
  1642. if args.get('livestream') == '1' or args.get('live_playback') == 1:
  1643. is_live = True
  1644. sts = ytplayer_config.get('sts')
  1645. if not player_response:
  1646. player_response = extract_player_response(args.get('player_response'), video_id)
  1647. if not video_info or self._downloader.params.get('youtube_include_dash_manifest', True):
  1648. add_dash_mpd_pr(player_response)
  1649. # We also try looking in get_video_info since it may contain different dashmpd
  1650. # URL that points to a DASH manifest with possibly different itag set (some itags
  1651. # are missing from DASH manifest pointed by webpage's dashmpd, some - from DASH
  1652. # manifest pointed by get_video_info's dashmpd).
  1653. # The general idea is to take a union of itags of both DASH manifests (for example
  1654. # video with such 'manifest behavior' see https://github.com/ytdl-org/youtube-dl/issues/6093)
  1655. self.report_video_info_webpage_download(video_id)
  1656. for el in ('embedded', 'detailpage', 'vevo', ''):
  1657. query = {
  1658. 'video_id': video_id,
  1659. 'ps': 'default',
  1660. 'eurl': '',
  1661. 'gl': 'US',
  1662. 'hl': 'en',
  1663. }
  1664. if el:
  1665. query['el'] = el
  1666. if sts:
  1667. query['sts'] = sts
  1668. video_info_webpage = self._download_webpage(
  1669. '%s://www.youtube.com/get_video_info' % proto,
  1670. video_id, note=False,
  1671. errnote='unable to download video info webpage',
  1672. fatal=False, query=query)
  1673. if not video_info_webpage:
  1674. continue
  1675. get_video_info = compat_parse_qs(video_info_webpage)
  1676. if not player_response:
  1677. pl_response = get_video_info.get('player_response', [None])[0]
  1678. player_response = extract_player_response(pl_response, video_id)
  1679. add_dash_mpd(get_video_info)
  1680. if view_count is None:
  1681. view_count = extract_view_count(get_video_info)
  1682. if not video_info:
  1683. video_info = get_video_info
  1684. get_token = extract_token(get_video_info)
  1685. if get_token:
  1686. # Different get_video_info requests may report different results, e.g.
  1687. # some may report video unavailability, but some may serve it without
  1688. # any complaint (see https://github.com/ytdl-org/youtube-dl/issues/7362,
  1689. # the original webpage as well as el=info and el=embedded get_video_info
  1690. # requests report video unavailability due to geo restriction while
  1691. # el=detailpage succeeds and returns valid data). This is probably
  1692. # due to YouTube measures against IP ranges of hosting providers.
  1693. # Working around by preferring the first succeeded video_info containing
  1694. # the token if no such video_info yet was found.
  1695. token = extract_token(video_info)
  1696. if not token:
  1697. video_info = get_video_info
  1698. break
  1699. def extract_unavailable_message():
  1700. messages = []
  1701. for tag, kind in (('h1', 'message'), ('div', 'submessage')):
  1702. msg = self._html_search_regex(
  1703. r'(?s)<{tag}[^>]+id=["\']unavailable-{kind}["\'][^>]*>(.+?)</{tag}>'.format(tag=tag, kind=kind),
  1704. video_webpage, 'unavailable %s' % kind, default=None)
  1705. if msg:
  1706. messages.append(msg)
  1707. if messages:
  1708. return '\n'.join(messages)
  1709. if not video_info:
  1710. unavailable_message = extract_unavailable_message()
  1711. if not unavailable_message:
  1712. unavailable_message = 'Unable to extract video data'
  1713. raise ExtractorError(
  1714. 'YouTube said: %s' % unavailable_message, expected=True, video_id=video_id)
  1715. video_details = try_get(
  1716. player_response, lambda x: x['videoDetails'], dict) or {}
  1717. video_title = video_info.get('title', [None])[0] or video_details.get('title')
  1718. if not video_title:
  1719. self._downloader.report_warning('Unable to extract video title')
  1720. video_title = '_'
  1721. description_original = video_description = get_element_by_id("eow-description", video_webpage)
  1722. if video_description:
  1723. def replace_url(m):
  1724. redir_url = compat_urlparse.urljoin(url, m.group(1))
  1725. parsed_redir_url = compat_urllib_parse_urlparse(redir_url)
  1726. if re.search(r'^(?:www\.)?(?:youtube(?:-nocookie)?\.com|youtu\.be)$', parsed_redir_url.netloc) and parsed_redir_url.path == '/redirect':
  1727. qs = compat_parse_qs(parsed_redir_url.query)
  1728. q = qs.get('q')
  1729. if q and q[0]:
  1730. return q[0]
  1731. return redir_url
  1732. description_original = video_description = re.sub(r'''(?x)
  1733. <a\s+
  1734. (?:[a-zA-Z-]+="[^"]*"\s+)*?
  1735. (?:title|href)="([^"]+)"\s+
  1736. (?:[a-zA-Z-]+="[^"]*"\s+)*?
  1737. class="[^"]*"[^>]*>
  1738. [^<]+\.{3}\s*
  1739. </a>
  1740. ''', replace_url, video_description)
  1741. video_description = clean_html(video_description)
  1742. else:
  1743. video_description = self._html_search_meta('description', video_webpage) or video_details.get('shortDescription')
  1744. if not smuggled_data.get('force_singlefeed', False):
  1745. if not self._downloader.params.get('noplaylist'):
  1746. multifeed_metadata_list = try_get(
  1747. player_response,
  1748. lambda x: x['multicamera']['playerLegacyMulticameraRenderer']['metadataList'],
  1749. compat_str) or try_get(
  1750. video_info, lambda x: x['multifeed_metadata_list'][0], compat_str)
  1751. if multifeed_metadata_list:
  1752. entries = []
  1753. feed_ids = []
  1754. for feed in multifeed_metadata_list.split(','):
  1755. # Unquote should take place before split on comma (,) since textual
  1756. # fields may contain comma as well (see
  1757. # https://github.com/ytdl-org/youtube-dl/issues/8536)
  1758. feed_data = compat_parse_qs(compat_urllib_parse_unquote_plus(feed))
  1759. entries.append({
  1760. '_type': 'url_transparent',
  1761. 'ie_key': 'Youtube',
  1762. 'url': smuggle_url(
  1763. '%s://www.youtube.com/watch?v=%s' % (proto, feed_data['id'][0]),
  1764. {'force_singlefeed': True}),
  1765. 'title': '%s (%s)' % (video_title, feed_data['title'][0]),
  1766. })
  1767. feed_ids.append(feed_data['id'][0])
  1768. self.to_screen(
  1769. 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
  1770. % (', '.join(feed_ids), video_id))
  1771. return self.playlist_result(entries, video_id, video_title, video_description)
  1772. else:
  1773. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1774. if view_count is None:
  1775. view_count = extract_view_count(video_info)
  1776. if view_count is None and video_details:
  1777. view_count = int_or_none(video_details.get('viewCount'))
  1778. if is_live is None:
  1779. is_live = bool_or_none(video_details.get('isLive'))
  1780. # Check for "rental" videos
  1781. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  1782. raise ExtractorError('"rental" videos not supported. See https://github.com/ytdl-org/youtube-dl/issues/359 for more information.', expected=True)
  1783. def _extract_filesize(media_url):
  1784. return int_or_none(self._search_regex(
  1785. r'\bclen[=/](\d+)', media_url, 'filesize', default=None))
  1786. streaming_formats = try_get(player_response, lambda x: x['streamingData']['formats'], list) or []
  1787. streaming_formats.extend(try_get(player_response, lambda x: x['streamingData']['adaptiveFormats'], list) or [])
  1788. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1789. self.report_rtmp_download()
  1790. formats = [{
  1791. 'format_id': '_rtmp',
  1792. 'protocol': 'rtmp',
  1793. 'url': video_info['conn'][0],
  1794. 'player_url': player_url,
  1795. }]
  1796. 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):
  1797. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts', [''])[0]
  1798. if 'rtmpe%3Dyes' in encoded_url_map:
  1799. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/ytdl-org/youtube-dl/issues/343 for more information.', expected=True)
  1800. formats = []
  1801. formats_spec = {}
  1802. fmt_list = video_info.get('fmt_list', [''])[0]
  1803. if fmt_list:
  1804. for fmt in fmt_list.split(','):
  1805. spec = fmt.split('/')
  1806. if len(spec) > 1:
  1807. width_height = spec[1].split('x')
  1808. if len(width_height) == 2:
  1809. formats_spec[spec[0]] = {
  1810. 'resolution': spec[1],
  1811. 'width': int_or_none(width_height[0]),
  1812. 'height': int_or_none(width_height[1]),
  1813. }
  1814. for fmt in streaming_formats:
  1815. itag = str_or_none(fmt.get('itag'))
  1816. if not itag:
  1817. continue
  1818. quality = fmt.get('quality')
  1819. quality_label = fmt.get('qualityLabel') or quality
  1820. formats_spec[itag] = {
  1821. 'asr': int_or_none(fmt.get('audioSampleRate')),
  1822. 'filesize': int_or_none(fmt.get('contentLength')),
  1823. 'format_note': quality_label,
  1824. 'fps': int_or_none(fmt.get('fps')),
  1825. 'height': int_or_none(fmt.get('height')),
  1826. # bitrate for itag 43 is always 2147483647
  1827. 'tbr': float_or_none(fmt.get('averageBitrate') or fmt.get('bitrate'), 1000) if itag != '43' else None,
  1828. 'width': int_or_none(fmt.get('width')),
  1829. }
  1830. for fmt in streaming_formats:
  1831. if fmt.get('drm_families'):
  1832. continue
  1833. url = url_or_none(fmt.get('url'))
  1834. if not url:
  1835. cipher = fmt.get('cipher')
  1836. if not cipher:
  1837. continue
  1838. url_data = compat_parse_qs(cipher)
  1839. url = url_or_none(try_get(url_data, lambda x: x['url'][0], compat_str))
  1840. if not url:
  1841. continue
  1842. else:
  1843. cipher = None
  1844. url_data = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
  1845. stream_type = int_or_none(try_get(url_data, lambda x: x['stream_type'][0]))
  1846. # Unsupported FORMAT_STREAM_TYPE_OTF
  1847. if stream_type == 3:
  1848. continue
  1849. format_id = fmt.get('itag') or url_data['itag'][0]
  1850. if not format_id:
  1851. continue
  1852. format_id = compat_str(format_id)
  1853. if cipher:
  1854. if 's' in url_data or self._downloader.params.get('youtube_include_dash_manifest', True):
  1855. ASSETS_RE = r'"assets":.+?"js":\s*("[^"]+")'
  1856. jsplayer_url_json = self._search_regex(
  1857. ASSETS_RE,
  1858. embed_webpage if age_gate else video_webpage,
  1859. 'JS player URL (1)', default=None)
  1860. if not jsplayer_url_json and not age_gate:
  1861. # We need the embed website after all
  1862. if embed_webpage is None:
  1863. embed_url = proto + '://www.youtube.com/embed/%s' % video_id
  1864. embed_webpage = self._download_webpage(
  1865. embed_url, video_id, 'Downloading embed webpage')
  1866. jsplayer_url_json = self._search_regex(
  1867. ASSETS_RE, embed_webpage, 'JS player URL')
  1868. player_url = json.loads(jsplayer_url_json)
  1869. if player_url is None:
  1870. player_url_json = self._search_regex(
  1871. r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
  1872. video_webpage, 'age gate player URL')
  1873. player_url = json.loads(player_url_json)
  1874. if 'sig' in url_data:
  1875. url += '&signature=' + url_data['sig'][0]
  1876. elif 's' in url_data:
  1877. encrypted_sig = url_data['s'][0]
  1878. if self._downloader.params.get('verbose'):
  1879. if player_url is None:
  1880. player_version = 'unknown'
  1881. player_desc = 'unknown'
  1882. else:
  1883. if player_url.endswith('swf'):
  1884. player_version = self._search_regex(
  1885. r'-(.+?)(?:/watch_as3)?\.swf$', player_url,
  1886. 'flash player', fatal=False)
  1887. player_desc = 'flash player %s' % player_version
  1888. else:
  1889. player_version = self._search_regex(
  1890. [r'html5player-([^/]+?)(?:/html5player(?:-new)?)?\.js',
  1891. r'(?:www|player(?:_ias)?)-([^/]+)(?:/[a-z]{2,3}_[A-Z]{2})?/base\.js'],
  1892. player_url,
  1893. 'html5 player', fatal=False)
  1894. player_desc = 'html5 player %s' % player_version
  1895. parts_sizes = self._signature_cache_id(encrypted_sig)
  1896. self.to_screen('{%s} signature length %s, %s' %
  1897. (format_id, parts_sizes, player_desc))
  1898. signature = self._decrypt_signature(
  1899. encrypted_sig, video_id, player_url, age_gate)
  1900. sp = try_get(url_data, lambda x: x['sp'][0], compat_str) or 'signature'
  1901. url += '&%s=%s' % (sp, signature)
  1902. if 'ratebypass' not in url:
  1903. url += '&ratebypass=yes'
  1904. dct = {
  1905. 'format_id': format_id,
  1906. 'url': url,
  1907. 'player_url': player_url,
  1908. }
  1909. if format_id in self._formats:
  1910. dct.update(self._formats[format_id])
  1911. if format_id in formats_spec:
  1912. dct.update(formats_spec[format_id])
  1913. # Some itags are not included in DASH manifest thus corresponding formats will
  1914. # lack metadata (see https://github.com/ytdl-org/youtube-dl/pull/5993).
  1915. # Trying to extract metadata from url_encoded_fmt_stream_map entry.
  1916. mobj = re.search(r'^(?P<width>\d+)[xX](?P<height>\d+)$', url_data.get('size', [''])[0])
  1917. width, height = (int(mobj.group('width')), int(mobj.group('height'))) if mobj else (None, None)
  1918. if width is None:
  1919. width = int_or_none(fmt.get('width'))
  1920. if height is None:
  1921. height = int_or_none(fmt.get('height'))
  1922. filesize = int_or_none(url_data.get(
  1923. 'clen', [None])[0]) or _extract_filesize(url)
  1924. quality = url_data.get('quality', [None])[0] or fmt.get('quality')
  1925. quality_label = url_data.get('quality_label', [None])[0] or fmt.get('qualityLabel')
  1926. tbr = (float_or_none(url_data.get('bitrate', [None])[0], 1000)
  1927. or float_or_none(fmt.get('bitrate'), 1000)) if format_id != '43' else None
  1928. fps = int_or_none(url_data.get('fps', [None])[0]) or int_or_none(fmt.get('fps'))
  1929. more_fields = {
  1930. 'filesize': filesize,
  1931. 'tbr': tbr,
  1932. 'width': width,
  1933. 'height': height,
  1934. 'fps': fps,
  1935. 'format_note': quality_label or quality,
  1936. }
  1937. for key, value in more_fields.items():
  1938. if value:
  1939. dct[key] = value
  1940. type_ = url_data.get('type', [None])[0] or fmt.get('mimeType')
  1941. if type_:
  1942. type_split = type_.split(';')
  1943. kind_ext = type_split[0].split('/')
  1944. if len(kind_ext) == 2:
  1945. kind, _ = kind_ext
  1946. dct['ext'] = mimetype2ext(type_split[0])
  1947. if kind in ('audio', 'video'):
  1948. codecs = None
  1949. for mobj in re.finditer(
  1950. r'(?P<key>[a-zA-Z_-]+)=(?P<quote>["\']?)(?P<val>.+?)(?P=quote)(?:;|$)', type_):
  1951. if mobj.group('key') == 'codecs':
  1952. codecs = mobj.group('val')
  1953. break
  1954. if codecs:
  1955. dct.update(parse_codecs(codecs))
  1956. if dct.get('acodec') == 'none' or dct.get('vcodec') == 'none':
  1957. dct['downloader_options'] = {
  1958. # Youtube throttles chunks >~10M
  1959. 'http_chunk_size': 10485760,
  1960. }
  1961. formats.append(dct)
  1962. else:
  1963. manifest_url = (
  1964. url_or_none(try_get(
  1965. player_response,
  1966. lambda x: x['streamingData']['hlsManifestUrl'],
  1967. compat_str))
  1968. or url_or_none(try_get(
  1969. video_info, lambda x: x['hlsvp'][0], compat_str)))
  1970. if manifest_url:
  1971. formats = []
  1972. m3u8_formats = self._extract_m3u8_formats(
  1973. manifest_url, video_id, 'mp4', fatal=False)
  1974. for a_format in m3u8_formats:
  1975. itag = self._search_regex(
  1976. r'/itag/(\d+)/', a_format['url'], 'itag', default=None)
  1977. if itag:
  1978. a_format['format_id'] = itag
  1979. if itag in self._formats:
  1980. dct = self._formats[itag].copy()
  1981. dct.update(a_format)
  1982. a_format = dct
  1983. a_format['player_url'] = player_url
  1984. # Accept-Encoding header causes failures in live streams on Youtube and Youtube Gaming
  1985. a_format.setdefault('http_headers', {})['Youtubedl-no-compression'] = 'True'
  1986. formats.append(a_format)
  1987. else:
  1988. error_message = extract_unavailable_message()
  1989. if not error_message:
  1990. error_message = clean_html(try_get(
  1991. player_response, lambda x: x['playabilityStatus']['reason'],
  1992. compat_str))
  1993. if not error_message:
  1994. error_message = clean_html(
  1995. try_get(video_info, lambda x: x['reason'][0], compat_str))
  1996. if error_message:
  1997. raise ExtractorError(error_message, expected=True)
  1998. raise ExtractorError('no conn, hlsvp, hlsManifestUrl or url_encoded_fmt_stream_map information found in video info')
  1999. # uploader
  2000. video_uploader = try_get(
  2001. video_info, lambda x: x['author'][0],
  2002. compat_str) or str_or_none(video_details.get('author'))
  2003. if video_uploader:
  2004. video_uploader = compat_urllib_parse_unquote_plus(video_uploader)
  2005. else:
  2006. self._downloader.report_warning('unable to extract uploader name')
  2007. # uploader_id
  2008. video_uploader_id = None
  2009. video_uploader_url = None
  2010. mobj = re.search(
  2011. r'<link itemprop="url" href="(?P<uploader_url>https?://www\.youtube\.com/(?:user|channel)/(?P<uploader_id>[^"]+))">',
  2012. video_webpage)
  2013. if mobj is not None:
  2014. video_uploader_id = mobj.group('uploader_id')
  2015. video_uploader_url = mobj.group('uploader_url')
  2016. else:
  2017. self._downloader.report_warning('unable to extract uploader nickname')
  2018. channel_id = (
  2019. str_or_none(video_details.get('channelId'))
  2020. or self._html_search_meta(
  2021. 'channelId', video_webpage, 'channel id', default=None)
  2022. or self._search_regex(
  2023. r'data-channel-external-id=(["\'])(?P<id>(?:(?!\1).)+)\1',
  2024. video_webpage, 'channel id', default=None, group='id'))
  2025. channel_url = 'http://www.youtube.com/channel/%s' % channel_id if channel_id else None
  2026. # thumbnail image
  2027. # We try first to get a high quality image:
  2028. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  2029. video_webpage, re.DOTALL)
  2030. if m_thumb is not None:
  2031. video_thumbnail = m_thumb.group(1)
  2032. elif 'thumbnail_url' not in video_info:
  2033. self._downloader.report_warning('unable to extract video thumbnail')
  2034. video_thumbnail = None
  2035. else: # don't panic if we can't find it
  2036. video_thumbnail = compat_urllib_parse_unquote_plus(video_info['thumbnail_url'][0])
  2037. # upload date
  2038. upload_date = self._html_search_meta(
  2039. 'datePublished', video_webpage, 'upload date', default=None)
  2040. if not upload_date:
  2041. upload_date = self._search_regex(
  2042. [r'(?s)id="eow-date.*?>(.*?)</span>',
  2043. r'(?:id="watch-uploader-info".*?>.*?|["\']simpleText["\']\s*:\s*["\'])(?:Published|Uploaded|Streamed live|Started) on (.+?)[<"\']'],
  2044. video_webpage, 'upload date', default=None)
  2045. upload_date = unified_strdate(upload_date)
  2046. video_license = self._html_search_regex(
  2047. r'<h4[^>]+class="title"[^>]*>\s*License\s*</h4>\s*<ul[^>]*>\s*<li>(.+?)</li',
  2048. video_webpage, 'license', default=None)
  2049. m_music = re.search(
  2050. r'''(?x)
  2051. <h4[^>]+class="title"[^>]*>\s*Music\s*</h4>\s*
  2052. <ul[^>]*>\s*
  2053. <li>(?P<title>.+?)
  2054. by (?P<creator>.+?)
  2055. (?:
  2056. \(.+?\)|
  2057. <a[^>]*
  2058. (?:
  2059. \bhref=["\']/red[^>]*>| # drop possible
  2060. >\s*Listen ad-free with YouTube Red # YouTube Red ad
  2061. )
  2062. .*?
  2063. )?</li
  2064. ''',
  2065. video_webpage)
  2066. if m_music:
  2067. video_alt_title = remove_quotes(unescapeHTML(m_music.group('title')))
  2068. video_creator = clean_html(m_music.group('creator'))
  2069. else:
  2070. video_alt_title = video_creator = None
  2071. def extract_meta(field):
  2072. return self._html_search_regex(
  2073. r'<h4[^>]+class="title"[^>]*>\s*%s\s*</h4>\s*<ul[^>]*>\s*<li>(.+?)</li>\s*' % field,
  2074. video_webpage, field, default=None)
  2075. track = extract_meta('Song')
  2076. artist = extract_meta('Artist')
  2077. album = extract_meta('Album')
  2078. # Youtube Music Auto-generated description
  2079. release_date = release_year = None
  2080. if video_description:
  2081. 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)
  2082. if mobj:
  2083. if not track:
  2084. track = mobj.group('track').strip()
  2085. if not artist:
  2086. artist = mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·'))
  2087. if not album:
  2088. album = mobj.group('album'.strip())
  2089. release_year = mobj.group('release_year')
  2090. release_date = mobj.group('release_date')
  2091. if release_date:
  2092. release_date = release_date.replace('-', '')
  2093. if not release_year:
  2094. release_year = int(release_date[:4])
  2095. if release_year:
  2096. release_year = int(release_year)
  2097. m_episode = re.search(
  2098. r'<div[^>]+id="watch7-headline"[^>]*>\s*<span[^>]*>.*?>(?P<series>[^<]+)</a></b>\s*S(?P<season>\d+)\s*•\s*E(?P<episode>\d+)</span>',
  2099. video_webpage)
  2100. if m_episode:
  2101. series = unescapeHTML(m_episode.group('series'))
  2102. season_number = int(m_episode.group('season'))
  2103. episode_number = int(m_episode.group('episode'))
  2104. else:
  2105. series = season_number = episode_number = None
  2106. m_cat_container = self._search_regex(
  2107. r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>',
  2108. video_webpage, 'categories', default=None)
  2109. if m_cat_container:
  2110. category = self._html_search_regex(
  2111. r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
  2112. default=None)
  2113. video_categories = None if category is None else [category]
  2114. else:
  2115. video_categories = None
  2116. video_tags = [
  2117. unescapeHTML(m.group('content'))
  2118. for m in re.finditer(self._meta_regex('og:video:tag'), video_webpage)]
  2119. def _extract_count(count_name):
  2120. return str_to_int(self._search_regex(
  2121. r'-%s-button[^>]+><span[^>]+class="yt-uix-button-content"[^>]*>([\d,]+)</span>'
  2122. % re.escape(count_name),
  2123. video_webpage, count_name, default=None))
  2124. like_count = _extract_count('like')
  2125. dislike_count = _extract_count('dislike')
  2126. if view_count is None:
  2127. view_count = str_to_int(self._search_regex(
  2128. r'<[^>]+class=["\']watch-view-count[^>]+>\s*([\d,\s]+)', video_webpage,
  2129. 'view count', default=None))
  2130. average_rating = (
  2131. float_or_none(video_details.get('averageRating'))
  2132. or try_get(video_info, lambda x: float_or_none(x['avg_rating'][0])))
  2133. # subtitles
  2134. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  2135. automatic_captions = self.extract_automatic_captions(video_id, video_webpage)
  2136. video_duration = try_get(
  2137. video_info, lambda x: int_or_none(x['length_seconds'][0]))
  2138. if not video_duration:
  2139. video_duration = int_or_none(video_details.get('lengthSeconds'))
  2140. if not video_duration:
  2141. video_duration = parse_duration(self._html_search_meta(
  2142. 'duration', video_webpage, 'video duration'))
  2143. # annotations
  2144. video_annotations = None
  2145. if self._downloader.params.get('writeannotations', False):
  2146. xsrf_token = self._search_regex(
  2147. r'([\'"])XSRF_TOKEN\1\s*:\s*([\'"])(?P<xsrf_token>[A-Za-z0-9+/=]+)\2',
  2148. video_webpage, 'xsrf token', group='xsrf_token', fatal=False)
  2149. invideo_url = try_get(
  2150. player_response, lambda x: x['annotations'][0]['playerAnnotationsUrlsRenderer']['invideoUrl'], compat_str)
  2151. if xsrf_token and invideo_url:
  2152. xsrf_field_name = self._search_regex(
  2153. r'([\'"])XSRF_FIELD_NAME\1\s*:\s*([\'"])(?P<xsrf_field_name>\w+)\2',
  2154. video_webpage, 'xsrf field name',
  2155. group='xsrf_field_name', default='session_token')
  2156. video_annotations = self._download_webpage(
  2157. self._proto_relative_url(invideo_url),
  2158. video_id, note='Downloading annotations',
  2159. errnote='Unable to download video annotations', fatal=False,
  2160. data=urlencode_postdata({xsrf_field_name: xsrf_token}))
  2161. chapters = self._extract_chapters(description_original, video_duration)
  2162. # Look for the DASH manifest
  2163. if self._downloader.params.get('youtube_include_dash_manifest', True):
  2164. dash_mpd_fatal = True
  2165. for mpd_url in dash_mpds:
  2166. dash_formats = {}
  2167. try:
  2168. def decrypt_sig(mobj):
  2169. s = mobj.group(1)
  2170. dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
  2171. return '/signature/%s' % dec_s
  2172. mpd_url = re.sub(r'/s/([a-fA-F0-9\.]+)', decrypt_sig, mpd_url)
  2173. for df in self._extract_mpd_formats(
  2174. mpd_url, video_id, fatal=dash_mpd_fatal,
  2175. formats_dict=self._formats):
  2176. if not df.get('filesize'):
  2177. df['filesize'] = _extract_filesize(df['url'])
  2178. # Do not overwrite DASH format found in some previous DASH manifest
  2179. if df['format_id'] not in dash_formats:
  2180. dash_formats[df['format_id']] = df
  2181. # Additional DASH manifests may end up in HTTP Error 403 therefore
  2182. # allow them to fail without bug report message if we already have
  2183. # some DASH manifest succeeded. This is temporary workaround to reduce
  2184. # burst of bug reports until we figure out the reason and whether it
  2185. # can be fixed at all.
  2186. dash_mpd_fatal = False
  2187. except (ExtractorError, KeyError) as e:
  2188. self.report_warning(
  2189. 'Skipping DASH manifest: %r' % e, video_id)
  2190. if dash_formats:
  2191. # Remove the formats we found through non-DASH, they
  2192. # contain less info and it can be wrong, because we use
  2193. # fixed values (for example the resolution). See
  2194. # https://github.com/ytdl-org/youtube-dl/issues/5774 for an
  2195. # example.
  2196. formats = [f for f in formats if f['format_id'] not in dash_formats.keys()]
  2197. formats.extend(dash_formats.values())
  2198. # Check for malformed aspect ratio
  2199. stretched_m = re.search(
  2200. r'<meta\s+property="og:video:tag".*?content="yt:stretch=(?P<w>[0-9]+):(?P<h>[0-9]+)">',
  2201. video_webpage)
  2202. if stretched_m:
  2203. w = float(stretched_m.group('w'))
  2204. h = float(stretched_m.group('h'))
  2205. # yt:stretch may hold invalid ratio data (e.g. for Q39EVAstoRM ratio is 17:0).
  2206. # We will only process correct ratios.
  2207. if w > 0 and h > 0:
  2208. ratio = w / h
  2209. for f in formats:
  2210. if f.get('vcodec') != 'none':
  2211. f['stretched_ratio'] = ratio
  2212. if not formats:
  2213. token = extract_token(video_info)
  2214. if not token:
  2215. if 'reason' in video_info:
  2216. if 'The uploader has not made this video available in your country.' in video_info['reason']:
  2217. regions_allowed = self._html_search_meta(
  2218. 'regionsAllowed', video_webpage, default=None)
  2219. countries = regions_allowed.split(',') if regions_allowed else None
  2220. self.raise_geo_restricted(
  2221. msg=video_info['reason'][0], countries=countries)
  2222. reason = video_info['reason'][0]
  2223. if 'Invalid parameters' in reason:
  2224. unavailable_message = extract_unavailable_message()
  2225. if unavailable_message:
  2226. reason = unavailable_message
  2227. raise ExtractorError(
  2228. 'YouTube said: %s' % reason,
  2229. expected=True, video_id=video_id)
  2230. else:
  2231. raise ExtractorError(
  2232. '"token" parameter not in video info for unknown reason',
  2233. video_id=video_id)
  2234. if not formats and (video_info.get('license_info') or try_get(player_response, lambda x: x['streamingData']['licenseInfos'])):
  2235. raise ExtractorError('This video is DRM protected.', expected=True)
  2236. self._sort_formats(formats)
  2237. self.mark_watched(video_id, video_info, player_response)
  2238. return {
  2239. 'id': video_id,
  2240. 'uploader': video_uploader,
  2241. 'uploader_id': video_uploader_id,
  2242. 'uploader_url': video_uploader_url,
  2243. 'channel_id': channel_id,
  2244. 'channel_url': channel_url,
  2245. 'upload_date': upload_date,
  2246. 'license': video_license,
  2247. 'creator': video_creator or artist,
  2248. 'title': video_title,
  2249. 'alt_title': video_alt_title or track,
  2250. 'thumbnail': video_thumbnail,
  2251. 'description': video_description,
  2252. 'categories': video_categories,
  2253. 'tags': video_tags,
  2254. 'subtitles': video_subtitles,
  2255. 'automatic_captions': automatic_captions,
  2256. 'duration': video_duration,
  2257. 'age_limit': 18 if age_gate else 0,
  2258. 'annotations': video_annotations,
  2259. 'chapters': chapters,
  2260. 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
  2261. 'view_count': view_count,
  2262. 'like_count': like_count,
  2263. 'dislike_count': dislike_count,
  2264. 'average_rating': average_rating,
  2265. 'formats': formats,
  2266. 'is_live': is_live,
  2267. 'start_time': start_time,
  2268. 'end_time': end_time,
  2269. 'series': series,
  2270. 'season_number': season_number,
  2271. 'episode_number': episode_number,
  2272. 'track': track,
  2273. 'artist': artist,
  2274. 'album': album,
  2275. 'release_date': release_date,
  2276. 'release_year': release_year,
  2277. }
  2278. class YoutubePlaylistIE(YoutubePlaylistBaseInfoExtractor):
  2279. IE_DESC = 'YouTube.com playlists'
  2280. _VALID_URL = r"""(?x)(?:
  2281. (?:https?://)?
  2282. (?:\w+\.)?
  2283. (?:
  2284. (?:
  2285. youtube(?:kids)?\.com|
  2286. invidio\.us
  2287. )
  2288. /
  2289. (?:
  2290. (?:course|view_play_list|my_playlists|artist|playlist|watch|embed/(?:videoseries|[0-9A-Za-z_-]{11}))
  2291. \? (?:.*?[&;])*? (?:p|a|list)=
  2292. | p/
  2293. )|
  2294. youtu\.be/[0-9A-Za-z_-]{11}\?.*?\blist=
  2295. )
  2296. (
  2297. (?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)?[0-9A-Za-z-_]{10,}
  2298. # Top tracks, they can also include dots
  2299. |(?:MC)[\w\.]*
  2300. )
  2301. .*
  2302. |
  2303. (%(playlist_id)s)
  2304. )""" % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
  2305. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
  2306. _VIDEO_RE_TPL = r'href="\s*/watch\?v=%s(?:&amp;(?:[^"]*?index=(?P<index>\d+))?(?:[^>]+>(?P<title>[^<]+))?)?'
  2307. _VIDEO_RE = _VIDEO_RE_TPL % r'(?P<id>[0-9A-Za-z_-]{11})'
  2308. IE_NAME = 'youtube:playlist'
  2309. _TESTS = [{
  2310. 'url': 'https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  2311. 'info_dict': {
  2312. 'title': 'ytdl test PL',
  2313. 'id': 'PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  2314. },
  2315. 'playlist_count': 3,
  2316. }, {
  2317. 'url': 'https://www.youtube.com/playlist?list=PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  2318. 'info_dict': {
  2319. 'id': 'PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  2320. 'title': 'YDL_Empty_List',
  2321. },
  2322. 'playlist_count': 0,
  2323. 'skip': 'This playlist is private',
  2324. }, {
  2325. 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
  2326. 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  2327. 'info_dict': {
  2328. 'title': '29C3: Not my department',
  2329. 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  2330. 'uploader': 'Christiaan008',
  2331. 'uploader_id': 'ChRiStIaAn008',
  2332. },
  2333. 'playlist_count': 95,
  2334. }, {
  2335. 'note': 'issue #673',
  2336. 'url': 'PLBB231211A4F62143',
  2337. 'info_dict': {
  2338. 'title': '[OLD]Team Fortress 2 (Class-based LP)',
  2339. 'id': 'PLBB231211A4F62143',
  2340. 'uploader': 'Wickydoo',
  2341. 'uploader_id': 'Wickydoo',
  2342. },
  2343. 'playlist_mincount': 26,
  2344. }, {
  2345. 'note': 'Large playlist',
  2346. 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
  2347. 'info_dict': {
  2348. 'title': 'Uploads from Cauchemar',
  2349. 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
  2350. 'uploader': 'Cauchemar',
  2351. 'uploader_id': 'Cauchemar89',
  2352. },
  2353. 'playlist_mincount': 799,
  2354. }, {
  2355. 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  2356. 'info_dict': {
  2357. 'title': 'YDL_safe_search',
  2358. 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  2359. },
  2360. 'playlist_count': 2,
  2361. 'skip': 'This playlist is private',
  2362. }, {
  2363. 'note': 'embedded',
  2364. 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  2365. 'playlist_count': 4,
  2366. 'info_dict': {
  2367. 'title': 'JODA15',
  2368. 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  2369. 'uploader': 'milan',
  2370. 'uploader_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
  2371. }
  2372. }, {
  2373. 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  2374. 'playlist_mincount': 485,
  2375. 'info_dict': {
  2376. 'title': '2018 Chinese New Singles (11/6 updated)',
  2377. 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  2378. 'uploader': 'LBK',
  2379. 'uploader_id': 'sdragonfang',
  2380. }
  2381. }, {
  2382. 'note': 'Embedded SWF player',
  2383. 'url': 'https://www.youtube.com/p/YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ?hl=en_US&fs=1&rel=0',
  2384. 'playlist_count': 4,
  2385. 'info_dict': {
  2386. 'title': 'JODA7',
  2387. 'id': 'YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ',
  2388. },
  2389. 'skip': 'This playlist does not exist',
  2390. }, {
  2391. 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
  2392. 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
  2393. 'info_dict': {
  2394. 'title': 'Uploads from Interstellar Movie',
  2395. 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
  2396. 'uploader': 'Interstellar Movie',
  2397. 'uploader_id': 'InterstellarMovie1',
  2398. },
  2399. 'playlist_mincount': 21,
  2400. }, {
  2401. # Playlist URL that does not actually serve a playlist
  2402. 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
  2403. 'info_dict': {
  2404. 'id': 'FqZTN594JQw',
  2405. 'ext': 'webm',
  2406. 'title': "Smiley's People 01 detective, Adventure Series, Action",
  2407. 'uploader': 'STREEM',
  2408. 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
  2409. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
  2410. 'upload_date': '20150526',
  2411. 'license': 'Standard YouTube License',
  2412. 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
  2413. 'categories': ['People & Blogs'],
  2414. 'tags': list,
  2415. 'view_count': int,
  2416. 'like_count': int,
  2417. 'dislike_count': int,
  2418. },
  2419. 'params': {
  2420. 'skip_download': True,
  2421. },
  2422. 'skip': 'This video is not available.',
  2423. 'add_ie': [YoutubeIE.ie_key()],
  2424. }, {
  2425. 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
  2426. 'info_dict': {
  2427. 'id': 'yeWKywCrFtk',
  2428. 'ext': 'mp4',
  2429. 'title': 'Small Scale Baler and Braiding Rugs',
  2430. 'uploader': 'Backus-Page House Museum',
  2431. 'uploader_id': 'backuspagemuseum',
  2432. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
  2433. 'upload_date': '20161008',
  2434. 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
  2435. 'categories': ['Nonprofits & Activism'],
  2436. 'tags': list,
  2437. 'like_count': int,
  2438. 'dislike_count': int,
  2439. },
  2440. 'params': {
  2441. 'noplaylist': True,
  2442. 'skip_download': True,
  2443. },
  2444. }, {
  2445. # https://github.com/ytdl-org/youtube-dl/issues/21844
  2446. 'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
  2447. 'info_dict': {
  2448. 'title': 'Data Analysis with Dr Mike Pound',
  2449. 'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
  2450. 'uploader_id': 'Computerphile',
  2451. 'uploader': 'Computerphile',
  2452. },
  2453. 'playlist_mincount': 11,
  2454. }, {
  2455. 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
  2456. 'only_matching': True,
  2457. }, {
  2458. 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
  2459. 'only_matching': True,
  2460. }, {
  2461. # music album playlist
  2462. 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
  2463. 'only_matching': True,
  2464. }, {
  2465. 'url': 'https://invidio.us/playlist?list=PLDIoUOhQQPlXr63I_vwF9GD8sAKh77dWU',
  2466. 'only_matching': True,
  2467. }, {
  2468. 'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
  2469. 'only_matching': True,
  2470. }]
  2471. def _real_initialize(self):
  2472. self._login()
  2473. def extract_videos_from_page(self, page):
  2474. ids_in_page = []
  2475. titles_in_page = []
  2476. for item in re.findall(
  2477. r'(<[^>]*\bdata-video-id\s*=\s*["\'][0-9A-Za-z_-]{11}[^>]+>)', page):
  2478. attrs = extract_attributes(item)
  2479. video_id = attrs['data-video-id']
  2480. video_title = unescapeHTML(attrs.get('data-title'))
  2481. if video_title:
  2482. video_title = video_title.strip()
  2483. ids_in_page.append(video_id)
  2484. titles_in_page.append(video_title)
  2485. # Fallback with old _VIDEO_RE
  2486. self.extract_videos_from_page_impl(
  2487. self._VIDEO_RE, page, ids_in_page, titles_in_page)
  2488. # Relaxed fallbacks
  2489. self.extract_videos_from_page_impl(
  2490. r'href="\s*/watch\?v\s*=\s*(?P<id>[0-9A-Za-z_-]{11})', page,
  2491. ids_in_page, titles_in_page)
  2492. self.extract_videos_from_page_impl(
  2493. r'data-video-ids\s*=\s*["\'](?P<id>[0-9A-Za-z_-]{11})', page,
  2494. ids_in_page, titles_in_page)
  2495. return zip(ids_in_page, titles_in_page)
  2496. def _extract_mix(self, playlist_id):
  2497. # The mixes are generated from a single video
  2498. # the id of the playlist is just 'RD' + video_id
  2499. ids = []
  2500. last_id = playlist_id[-11:]
  2501. for n in itertools.count(1):
  2502. url = 'https://youtube.com/watch?v=%s&list=%s' % (last_id, playlist_id)
  2503. webpage = self._download_webpage(
  2504. url, playlist_id, 'Downloading page {0} of Youtube mix'.format(n))
  2505. new_ids = orderedSet(re.findall(
  2506. r'''(?xs)data-video-username=".*?".*?
  2507. href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id),
  2508. webpage))
  2509. # Fetch new pages until all the videos are repeated, it seems that
  2510. # there are always 51 unique videos.
  2511. new_ids = [_id for _id in new_ids if _id not in ids]
  2512. if not new_ids:
  2513. break
  2514. ids.extend(new_ids)
  2515. last_id = ids[-1]
  2516. url_results = self._ids_to_results(ids)
  2517. search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
  2518. title_span = (
  2519. search_title('playlist-title')
  2520. or search_title('title long-title')
  2521. or search_title('title'))
  2522. title = clean_html(title_span)
  2523. return self.playlist_result(url_results, playlist_id, title)
  2524. def _extract_playlist(self, playlist_id):
  2525. url = self._TEMPLATE_URL % playlist_id
  2526. page = self._download_webpage(url, playlist_id)
  2527. # the yt-alert-message now has tabindex attribute (see https://github.com/ytdl-org/youtube-dl/issues/11604)
  2528. for match in re.findall(r'<div class="yt-alert-message"[^>]*>([^<]+)</div>', page):
  2529. match = match.strip()
  2530. # Check if the playlist exists or is private
  2531. mobj = re.match(r'[^<]*(?:The|This) playlist (?P<reason>does not exist|is private)[^<]*', match)
  2532. if mobj:
  2533. reason = mobj.group('reason')
  2534. message = 'This playlist %s' % reason
  2535. if 'private' in reason:
  2536. message += ', use --username or --netrc to access it'
  2537. message += '.'
  2538. raise ExtractorError(message, expected=True)
  2539. elif re.match(r'[^<]*Invalid parameters[^<]*', match):
  2540. raise ExtractorError(
  2541. 'Invalid parameters. Maybe URL is incorrect.',
  2542. expected=True)
  2543. elif re.match(r'[^<]*Choose your language[^<]*', match):
  2544. continue
  2545. else:
  2546. self.report_warning('Youtube gives an alert message: ' + match)
  2547. playlist_title = self._html_search_regex(
  2548. r'(?s)<h1 class="pl-header-title[^"]*"[^>]*>\s*(.*?)\s*</h1>',
  2549. page, 'title', default=None)
  2550. _UPLOADER_BASE = r'class=["\']pl-header-details[^>]+>\s*<li>\s*<a[^>]+\bhref='
  2551. uploader = self._html_search_regex(
  2552. r'%s["\']/(?:user|channel)/[^>]+>([^<]+)' % _UPLOADER_BASE,
  2553. page, 'uploader', default=None)
  2554. mobj = re.search(
  2555. r'%s(["\'])(?P<path>/(?:user|channel)/(?P<uploader_id>.+?))\1' % _UPLOADER_BASE,
  2556. page)
  2557. if mobj:
  2558. uploader_id = mobj.group('uploader_id')
  2559. uploader_url = compat_urlparse.urljoin(url, mobj.group('path'))
  2560. else:
  2561. uploader_id = uploader_url = None
  2562. has_videos = True
  2563. if not playlist_title:
  2564. try:
  2565. # Some playlist URLs don't actually serve a playlist (e.g.
  2566. # https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4)
  2567. next(self._entries(page, playlist_id))
  2568. except StopIteration:
  2569. has_videos = False
  2570. playlist = self.playlist_result(
  2571. self._entries(page, playlist_id), playlist_id, playlist_title)
  2572. playlist.update({
  2573. 'uploader': uploader,
  2574. 'uploader_id': uploader_id,
  2575. 'uploader_url': uploader_url,
  2576. })
  2577. return has_videos, playlist
  2578. def _check_download_just_video(self, url, playlist_id):
  2579. # Check if it's a video-specific URL
  2580. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  2581. video_id = query_dict.get('v', [None])[0] or self._search_regex(
  2582. r'(?:(?:^|//)youtu\.be/|youtube\.com/embed/(?!videoseries))([0-9A-Za-z_-]{11})', url,
  2583. 'video id', default=None)
  2584. if video_id:
  2585. if self._downloader.params.get('noplaylist'):
  2586. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  2587. return video_id, self.url_result(video_id, 'Youtube', video_id=video_id)
  2588. else:
  2589. self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  2590. return video_id, None
  2591. return None, None
  2592. def _real_extract(self, url):
  2593. # Extract playlist id
  2594. mobj = re.match(self._VALID_URL, url)
  2595. if mobj is None:
  2596. raise ExtractorError('Invalid URL: %s' % url)
  2597. playlist_id = mobj.group(1) or mobj.group(2)
  2598. video_id, video = self._check_download_just_video(url, playlist_id)
  2599. if video:
  2600. return video
  2601. if playlist_id.startswith(('RD', 'UL', 'PU')):
  2602. # Mixes require a custom extraction process
  2603. return self._extract_mix(playlist_id)
  2604. has_videos, playlist = self._extract_playlist(playlist_id)
  2605. if has_videos or not video_id:
  2606. return playlist
  2607. # Some playlist URLs don't actually serve a playlist (see
  2608. # https://github.com/ytdl-org/youtube-dl/issues/10537).
  2609. # Fallback to plain video extraction if there is a video id
  2610. # along with playlist id.
  2611. return self.url_result(video_id, 'Youtube', video_id=video_id)
  2612. class YoutubeChannelIE(YoutubePlaylistBaseInfoExtractor):
  2613. IE_DESC = 'YouTube.com channels'
  2614. _VALID_URL = r'https?://(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie|kids)?\.com|(?:www\.)?invidio\.us)/channel/(?P<id>[0-9A-Za-z_-]+)'
  2615. _TEMPLATE_URL = 'https://www.youtube.com/channel/%s/videos'
  2616. _VIDEO_RE = r'(?:title="(?P<title>[^"]+)"[^>]+)?href="/watch\?v=(?P<id>[0-9A-Za-z_-]+)&?'
  2617. IE_NAME = 'youtube:channel'
  2618. _TESTS = [{
  2619. 'note': 'paginated channel',
  2620. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
  2621. 'playlist_mincount': 91,
  2622. 'info_dict': {
  2623. 'id': 'UUKfVa3S1e4PHvxWcwyMMg8w',
  2624. 'title': 'Uploads from lex will',
  2625. 'uploader': 'lex will',
  2626. 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  2627. }
  2628. }, {
  2629. 'note': 'Age restricted channel',
  2630. # from https://www.youtube.com/user/DeusExOfficial
  2631. 'url': 'https://www.youtube.com/channel/UCs0ifCMCm1icqRbqhUINa0w',
  2632. 'playlist_mincount': 64,
  2633. 'info_dict': {
  2634. 'id': 'UUs0ifCMCm1icqRbqhUINa0w',
  2635. 'title': 'Uploads from Deus Ex',
  2636. 'uploader': 'Deus Ex',
  2637. 'uploader_id': 'DeusExOfficial',
  2638. },
  2639. }, {
  2640. 'url': 'https://invidio.us/channel/UC23qupoDRn9YOAVzeoxjOQA',
  2641. 'only_matching': True,
  2642. }, {
  2643. 'url': 'https://www.youtubekids.com/channel/UCyu8StPfZWapR6rfW_JgqcA',
  2644. 'only_matching': True,
  2645. }]
  2646. @classmethod
  2647. def suitable(cls, url):
  2648. return (False if YoutubePlaylistsIE.suitable(url) or YoutubeLiveIE.suitable(url)
  2649. else super(YoutubeChannelIE, cls).suitable(url))
  2650. def _build_template_url(self, url, channel_id):
  2651. return self._TEMPLATE_URL % channel_id
  2652. def _real_extract(self, url):
  2653. channel_id = self._match_id(url)
  2654. url = self._build_template_url(url, channel_id)
  2655. # Channel by page listing is restricted to 35 pages of 30 items, i.e. 1050 videos total (see #5778)
  2656. # Workaround by extracting as a playlist if managed to obtain channel playlist URL
  2657. # otherwise fallback on channel by page extraction
  2658. channel_page = self._download_webpage(
  2659. url + '?view=57', channel_id,
  2660. 'Downloading channel page', fatal=False)
  2661. if channel_page is False:
  2662. channel_playlist_id = False
  2663. else:
  2664. channel_playlist_id = self._html_search_meta(
  2665. 'channelId', channel_page, 'channel id', default=None)
  2666. if not channel_playlist_id:
  2667. channel_url = self._html_search_meta(
  2668. ('al:ios:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad'),
  2669. channel_page, 'channel url', default=None)
  2670. if channel_url:
  2671. channel_playlist_id = self._search_regex(
  2672. r'vnd\.youtube://user/([0-9A-Za-z_-]+)',
  2673. channel_url, 'channel id', default=None)
  2674. if channel_playlist_id and channel_playlist_id.startswith('UC'):
  2675. playlist_id = 'UU' + channel_playlist_id[2:]
  2676. return self.url_result(
  2677. compat_urlparse.urljoin(url, '/playlist?list=%s' % playlist_id), 'YoutubePlaylist')
  2678. channel_page = self._download_webpage(url, channel_id, 'Downloading page #1')
  2679. autogenerated = re.search(r'''(?x)
  2680. class="[^"]*?(?:
  2681. channel-header-autogenerated-label|
  2682. yt-channel-title-autogenerated
  2683. )[^"]*"''', channel_page) is not None
  2684. if autogenerated:
  2685. # The videos are contained in a single page
  2686. # the ajax pages can't be used, they are empty
  2687. entries = [
  2688. self.url_result(
  2689. video_id, 'Youtube', video_id=video_id,
  2690. video_title=video_title)
  2691. for video_id, video_title in self.extract_videos_from_page(channel_page)]
  2692. return self.playlist_result(entries, channel_id)
  2693. try:
  2694. next(self._entries(channel_page, channel_id))
  2695. except StopIteration:
  2696. alert_message = self._html_search_regex(
  2697. r'(?s)<div[^>]+class=(["\']).*?\byt-alert-message\b.*?\1[^>]*>(?P<alert>[^<]+)</div>',
  2698. channel_page, 'alert', default=None, group='alert')
  2699. if alert_message:
  2700. raise ExtractorError('Youtube said: %s' % alert_message, expected=True)
  2701. return self.playlist_result(self._entries(channel_page, channel_id), channel_id)
  2702. class YoutubeUserIE(YoutubeChannelIE):
  2703. IE_DESC = 'YouTube.com user videos (URL or "ytuser" keyword)'
  2704. _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_-]+)'
  2705. _TEMPLATE_URL = 'https://www.youtube.com/%s/%s/videos'
  2706. IE_NAME = 'youtube:user'
  2707. _TESTS = [{
  2708. 'url': 'https://www.youtube.com/user/TheLinuxFoundation',
  2709. 'playlist_mincount': 320,
  2710. 'info_dict': {
  2711. 'id': 'UUfX55Sx5hEFjoC3cNs6mCUQ',
  2712. 'title': 'Uploads from The Linux Foundation',
  2713. 'uploader': 'The Linux Foundation',
  2714. 'uploader_id': 'TheLinuxFoundation',
  2715. }
  2716. }, {
  2717. # Only available via https://www.youtube.com/c/12minuteathlete/videos
  2718. # but not https://www.youtube.com/user/12minuteathlete/videos
  2719. 'url': 'https://www.youtube.com/c/12minuteathlete/videos',
  2720. 'playlist_mincount': 249,
  2721. 'info_dict': {
  2722. 'id': 'UUVjM-zV6_opMDx7WYxnjZiQ',
  2723. 'title': 'Uploads from 12 Minute Athlete',
  2724. 'uploader': '12 Minute Athlete',
  2725. 'uploader_id': 'the12minuteathlete',
  2726. }
  2727. }, {
  2728. 'url': 'ytuser:phihag',
  2729. 'only_matching': True,
  2730. }, {
  2731. 'url': 'https://www.youtube.com/c/gametrailers',
  2732. 'only_matching': True,
  2733. }, {
  2734. 'url': 'https://www.youtube.com/gametrailers',
  2735. 'only_matching': True,
  2736. }, {
  2737. # This channel is not available, geo restricted to JP
  2738. 'url': 'https://www.youtube.com/user/kananishinoSMEJ/videos',
  2739. 'only_matching': True,
  2740. }]
  2741. @classmethod
  2742. def suitable(cls, url):
  2743. # Don't return True if the url can be extracted with other youtube
  2744. # extractor, the regex would is too permissive and it would match.
  2745. other_yt_ies = iter(klass for (name, klass) in globals().items() if name.startswith('Youtube') and name.endswith('IE') and klass is not cls)
  2746. if any(ie.suitable(url) for ie in other_yt_ies):
  2747. return False
  2748. else:
  2749. return super(YoutubeUserIE, cls).suitable(url)
  2750. def _build_template_url(self, url, channel_id):
  2751. mobj = re.match(self._VALID_URL, url)
  2752. return self._TEMPLATE_URL % (mobj.group('user') or 'user', mobj.group('id'))
  2753. class YoutubeLiveIE(YoutubeBaseInfoExtractor):
  2754. IE_DESC = 'YouTube.com live streams'
  2755. _VALID_URL = r'(?P<base_url>https?://(?:\w+\.)?youtube\.com/(?:(?:user|channel|c)/)?(?P<id>[^/]+))/live'
  2756. IE_NAME = 'youtube:live'
  2757. _TESTS = [{
  2758. 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
  2759. 'info_dict': {
  2760. 'id': 'a48o2S1cPoo',
  2761. 'ext': 'mp4',
  2762. 'title': 'The Young Turks - Live Main Show',
  2763. 'uploader': 'The Young Turks',
  2764. 'uploader_id': 'TheYoungTurks',
  2765. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
  2766. 'upload_date': '20150715',
  2767. 'license': 'Standard YouTube License',
  2768. 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
  2769. 'categories': ['News & Politics'],
  2770. 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
  2771. 'like_count': int,
  2772. 'dislike_count': int,
  2773. },
  2774. 'params': {
  2775. 'skip_download': True,
  2776. },
  2777. }, {
  2778. 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
  2779. 'only_matching': True,
  2780. }, {
  2781. 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
  2782. 'only_matching': True,
  2783. }, {
  2784. 'url': 'https://www.youtube.com/TheYoungTurks/live',
  2785. 'only_matching': True,
  2786. }]
  2787. def _real_extract(self, url):
  2788. mobj = re.match(self._VALID_URL, url)
  2789. channel_id = mobj.group('id')
  2790. base_url = mobj.group('base_url')
  2791. webpage = self._download_webpage(url, channel_id, fatal=False)
  2792. if webpage:
  2793. page_type = self._og_search_property(
  2794. 'type', webpage, 'page type', default='')
  2795. video_id = self._html_search_meta(
  2796. 'videoId', webpage, 'video id', default=None)
  2797. if page_type.startswith('video') and video_id and re.match(
  2798. r'^[0-9A-Za-z_-]{11}$', video_id):
  2799. return self.url_result(video_id, YoutubeIE.ie_key())
  2800. return self.url_result(base_url)
  2801. class YoutubePlaylistsIE(YoutubePlaylistsBaseInfoExtractor):
  2802. IE_DESC = 'YouTube.com user/channel playlists'
  2803. _VALID_URL = r'https?://(?:\w+\.)?youtube\.com/(?:user|channel)/(?P<id>[^/]+)/playlists'
  2804. IE_NAME = 'youtube:playlists'
  2805. _TESTS = [{
  2806. 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
  2807. 'playlist_mincount': 4,
  2808. 'info_dict': {
  2809. 'id': 'ThirstForScience',
  2810. 'title': 'ThirstForScience',
  2811. },
  2812. }, {
  2813. # with "Load more" button
  2814. 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
  2815. 'playlist_mincount': 70,
  2816. 'info_dict': {
  2817. 'id': 'igorkle1',
  2818. 'title': 'Игорь Клейнер',
  2819. },
  2820. }, {
  2821. 'url': 'https://www.youtube.com/channel/UCiU1dHvZObB2iP6xkJ__Icw/playlists',
  2822. 'playlist_mincount': 17,
  2823. 'info_dict': {
  2824. 'id': 'UCiU1dHvZObB2iP6xkJ__Icw',
  2825. 'title': 'Chem Player',
  2826. },
  2827. 'skip': 'Blocked',
  2828. }]
  2829. class YoutubeSearchBaseInfoExtractor(YoutubePlaylistBaseInfoExtractor):
  2830. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})(?:[^"]*"[^>]+\btitle="(?P<title>[^"]+))?'
  2831. class YoutubeSearchIE(SearchInfoExtractor, YoutubeSearchBaseInfoExtractor):
  2832. IE_DESC = 'YouTube.com searches'
  2833. # there doesn't appear to be a real limit, for example if you search for
  2834. # 'python' you get more than 8.000.000 results
  2835. _MAX_RESULTS = float('inf')
  2836. IE_NAME = 'youtube:search'
  2837. _SEARCH_KEY = 'ytsearch'
  2838. _EXTRA_QUERY_ARGS = {}
  2839. _TESTS = []
  2840. def _get_n_results(self, query, n):
  2841. """Get a specified number of results for a query"""
  2842. videos = []
  2843. limit = n
  2844. url_query = {
  2845. 'search_query': query.encode('utf-8'),
  2846. }
  2847. url_query.update(self._EXTRA_QUERY_ARGS)
  2848. result_url = 'https://www.youtube.com/results?' + compat_urllib_parse_urlencode(url_query)
  2849. for pagenum in itertools.count(1):
  2850. data = self._download_json(
  2851. result_url, video_id='query "%s"' % query,
  2852. note='Downloading page %s' % pagenum,
  2853. errnote='Unable to download API page',
  2854. query={'spf': 'navigate'})
  2855. html_content = data[1]['body']['content']
  2856. if 'class="search-message' in html_content:
  2857. raise ExtractorError(
  2858. '[youtube] No video results', expected=True)
  2859. new_videos = list(self._process_page(html_content))
  2860. videos += new_videos
  2861. if not new_videos or len(videos) > limit:
  2862. break
  2863. next_link = self._html_search_regex(
  2864. r'href="(/results\?[^"]*\bsp=[^"]+)"[^>]*>\s*<span[^>]+class="[^"]*\byt-uix-button-content\b[^"]*"[^>]*>Next',
  2865. html_content, 'next link', default=None)
  2866. if next_link is None:
  2867. break
  2868. result_url = compat_urlparse.urljoin('https://www.youtube.com/', next_link)
  2869. if len(videos) > n:
  2870. videos = videos[:n]
  2871. return self.playlist_result(videos, query)
  2872. class YoutubeSearchDateIE(YoutubeSearchIE):
  2873. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  2874. _SEARCH_KEY = 'ytsearchdate'
  2875. IE_DESC = 'YouTube.com searches, newest videos first'
  2876. _EXTRA_QUERY_ARGS = {'search_sort': 'video_date_uploaded'}
  2877. class YoutubeSearchURLIE(YoutubeSearchBaseInfoExtractor):
  2878. IE_DESC = 'YouTube.com search URLs'
  2879. IE_NAME = 'youtube:search_url'
  2880. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?P<query>[^&]+)(?:[&]|$)'
  2881. _TESTS = [{
  2882. 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
  2883. 'playlist_mincount': 5,
  2884. 'info_dict': {
  2885. 'title': 'youtube-dl test video',
  2886. }
  2887. }, {
  2888. 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
  2889. 'only_matching': True,
  2890. }]
  2891. def _real_extract(self, url):
  2892. mobj = re.match(self._VALID_URL, url)
  2893. query = compat_urllib_parse_unquote_plus(mobj.group('query'))
  2894. webpage = self._download_webpage(url, query)
  2895. return self.playlist_result(self._process_page(webpage), playlist_title=query)
  2896. class YoutubeShowIE(YoutubePlaylistsBaseInfoExtractor):
  2897. IE_DESC = 'YouTube.com (multi-season) shows'
  2898. _VALID_URL = r'https?://(?:www\.)?youtube\.com/show/(?P<id>[^?#]*)'
  2899. IE_NAME = 'youtube:show'
  2900. _TESTS = [{
  2901. 'url': 'https://www.youtube.com/show/airdisasters',
  2902. 'playlist_mincount': 5,
  2903. 'info_dict': {
  2904. 'id': 'airdisasters',
  2905. 'title': 'Air Disasters',
  2906. }
  2907. }]
  2908. def _real_extract(self, url):
  2909. playlist_id = self._match_id(url)
  2910. return super(YoutubeShowIE, self)._real_extract(
  2911. 'https://www.youtube.com/show/%s/playlists' % playlist_id)
  2912. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  2913. """
  2914. Base class for feed extractors
  2915. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  2916. """
  2917. _LOGIN_REQUIRED = True
  2918. @property
  2919. def IE_NAME(self):
  2920. return 'youtube:%s' % self._FEED_NAME
  2921. def _real_initialize(self):
  2922. self._login()
  2923. def _entries(self, page):
  2924. # The extraction process is the same as for playlists, but the regex
  2925. # for the video ids doesn't contain an index
  2926. ids = []
  2927. more_widget_html = content_html = page
  2928. for page_num in itertools.count(1):
  2929. matches = re.findall(r'href="\s*/watch\?v=([0-9A-Za-z_-]{11})', content_html)
  2930. # 'recommended' feed has infinite 'load more' and each new portion spins
  2931. # the same videos in (sometimes) slightly different order, so we'll check
  2932. # for unicity and break when portion has no new videos
  2933. new_ids = list(filter(lambda video_id: video_id not in ids, orderedSet(matches)))
  2934. if not new_ids:
  2935. break
  2936. ids.extend(new_ids)
  2937. for entry in self._ids_to_results(new_ids):
  2938. yield entry
  2939. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  2940. if not mobj:
  2941. break
  2942. more = self._download_json(
  2943. 'https://youtube.com/%s' % mobj.group('more'), self._PLAYLIST_TITLE,
  2944. 'Downloading page #%s' % page_num,
  2945. transform_source=uppercase_escape)
  2946. content_html = more['content_html']
  2947. more_widget_html = more['load_more_widget_html']
  2948. def _real_extract(self, url):
  2949. page = self._download_webpage(
  2950. 'https://www.youtube.com/feed/%s' % self._FEED_NAME,
  2951. self._PLAYLIST_TITLE)
  2952. return self.playlist_result(
  2953. self._entries(page), playlist_title=self._PLAYLIST_TITLE)
  2954. class YoutubeWatchLaterIE(YoutubePlaylistIE):
  2955. IE_NAME = 'youtube:watchlater'
  2956. IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
  2957. _VALID_URL = r'https?://(?:www\.)?youtube\.com/(?:feed/watch_later|(?:playlist|watch)\?(?:.+&)?list=WL)|:ytwatchlater'
  2958. _TESTS = [{
  2959. 'url': 'https://www.youtube.com/playlist?list=WL',
  2960. 'only_matching': True,
  2961. }, {
  2962. 'url': 'https://www.youtube.com/watch?v=bCNU9TrbiRk&index=1&list=WL',
  2963. 'only_matching': True,
  2964. }]
  2965. def _real_extract(self, url):
  2966. _, video = self._check_download_just_video(url, 'WL')
  2967. if video:
  2968. return video
  2969. _, playlist = self._extract_playlist('WL')
  2970. return playlist
  2971. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  2972. IE_NAME = 'youtube:favorites'
  2973. IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
  2974. _VALID_URL = r'https?://(?:www\.)?youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  2975. _LOGIN_REQUIRED = True
  2976. def _real_extract(self, url):
  2977. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  2978. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, 'favourites playlist id')
  2979. return self.url_result(playlist_id, 'YoutubePlaylist')
  2980. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  2981. IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
  2982. _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  2983. _FEED_NAME = 'recommended'
  2984. _PLAYLIST_TITLE = 'Youtube Recommended videos'
  2985. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  2986. IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  2987. _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  2988. _FEED_NAME = 'subscriptions'
  2989. _PLAYLIST_TITLE = 'Youtube Subscriptions'
  2990. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  2991. IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
  2992. _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/history|:ythistory'
  2993. _FEED_NAME = 'history'
  2994. _PLAYLIST_TITLE = 'Youtube History'
  2995. class YoutubeTruncatedURLIE(InfoExtractor):
  2996. IE_NAME = 'youtube:truncated_url'
  2997. IE_DESC = False # Do not list
  2998. _VALID_URL = r'''(?x)
  2999. (?:https?://)?
  3000. (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
  3001. (?:watch\?(?:
  3002. feature=[a-z_]+|
  3003. annotation_id=annotation_[^&]+|
  3004. x-yt-cl=[0-9]+|
  3005. hl=[^&]*|
  3006. t=[0-9]+
  3007. )?
  3008. |
  3009. attribution_link\?a=[^&]+
  3010. )
  3011. $
  3012. '''
  3013. _TESTS = [{
  3014. 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
  3015. 'only_matching': True,
  3016. }, {
  3017. 'url': 'https://www.youtube.com/watch?',
  3018. 'only_matching': True,
  3019. }, {
  3020. 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
  3021. 'only_matching': True,
  3022. }, {
  3023. 'url': 'https://www.youtube.com/watch?feature=foo',
  3024. 'only_matching': True,
  3025. }, {
  3026. 'url': 'https://www.youtube.com/watch?hl=en-GB',
  3027. 'only_matching': True,
  3028. }, {
  3029. 'url': 'https://www.youtube.com/watch?t=2372',
  3030. 'only_matching': True,
  3031. }]
  3032. def _real_extract(self, url):
  3033. raise ExtractorError(
  3034. 'Did you forget to quote the URL? Remember that & is a meta '
  3035. 'character in most shells, so you want to put the URL in quotes, '
  3036. 'like youtube-dl '
  3037. '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  3038. ' or simply youtube-dl BaW_jenozKc .',
  3039. expected=True)
  3040. class YoutubeTruncatedIDIE(InfoExtractor):
  3041. IE_NAME = 'youtube:truncated_id'
  3042. IE_DESC = False # Do not list
  3043. _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
  3044. _TESTS = [{
  3045. 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
  3046. 'only_matching': True,
  3047. }]
  3048. def _real_extract(self, url):
  3049. video_id = self._match_id(url)
  3050. raise ExtractorError(
  3051. 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),
  3052. expected=True)