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.

2837 lines
125 KiB

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