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
134 KiB

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