Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

3178 строки
141KB

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