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

3027 lines
134KB

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