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.

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