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.

2300 lines
104 KiB

Switch codebase to use sanitized_Request instead of compat_urllib_request.Request [downloader/dash] Use sanitized_Request [downloader/http] Use sanitized_Request [atresplayer] Use sanitized_Request [bambuser] Use sanitized_Request [bliptv] Use sanitized_Request [brightcove] Use sanitized_Request [cbs] Use sanitized_Request [ceskatelevize] Use sanitized_Request [collegerama] Use sanitized_Request [extractor/common] Use sanitized_Request [crunchyroll] Use sanitized_Request [dailymotion] Use sanitized_Request [dcn] Use sanitized_Request [dramafever] Use sanitized_Request [dumpert] Use sanitized_Request [eitb] Use sanitized_Request [escapist] Use sanitized_Request [everyonesmixtape] Use sanitized_Request [extremetube] Use sanitized_Request [facebook] Use sanitized_Request [fc2] Use sanitized_Request [flickr] Use sanitized_Request [4tube] Use sanitized_Request [gdcvault] Use sanitized_Request [extractor/generic] Use sanitized_Request [hearthisat] Use sanitized_Request [hotnewhiphop] Use sanitized_Request [hypem] Use sanitized_Request [iprima] Use sanitized_Request [ivi] Use sanitized_Request [keezmovies] Use sanitized_Request [letv] Use sanitized_Request [lynda] Use sanitized_Request [metacafe] Use sanitized_Request [minhateca] Use sanitized_Request [miomio] Use sanitized_Request [meovideo] Use sanitized_Request [mofosex] Use sanitized_Request [moniker] Use sanitized_Request [mooshare] Use sanitized_Request [movieclips] Use sanitized_Request [mtv] Use sanitized_Request [myvideo] Use sanitized_Request [neteasemusic] Use sanitized_Request [nfb] Use sanitized_Request [niconico] Use sanitized_Request [noco] Use sanitized_Request [nosvideo] Use sanitized_Request [novamov] Use sanitized_Request [nowness] Use sanitized_Request [nuvid] Use sanitized_Request [played] Use sanitized_Request [pluralsight] Use sanitized_Request [pornhub] Use sanitized_Request [pornotube] Use sanitized_Request [primesharetv] Use sanitized_Request [promptfile] Use sanitized_Request [qqmusic] Use sanitized_Request [rtve] Use sanitized_Request [safari] Use sanitized_Request [sandia] Use sanitized_Request [shared] Use sanitized_Request [sharesix] Use sanitized_Request [sina] Use sanitized_Request [smotri] Use sanitized_Request [sohu] Use sanitized_Request [spankwire] Use sanitized_Request [sportdeutschland] Use sanitized_Request [streamcloud] Use sanitized_Request [streamcz] Use sanitized_Request [tapely] Use sanitized_Request [tube8] Use sanitized_Request [tubitv] Use sanitized_Request [twitch] Use sanitized_Request [twitter] Use sanitized_Request [udemy] Use sanitized_Request [vbox7] Use sanitized_Request [veoh] Use sanitized_Request [vessel] Use sanitized_Request [vevo] Use sanitized_Request [viddler] Use sanitized_Request [videomega] Use sanitized_Request [viewvster] Use sanitized_Request [viki] Use sanitized_Request [vk] Use sanitized_Request [vodlocker] Use sanitized_Request [voicerepublic] Use sanitized_Request [wistia] Use sanitized_Request [xfileshare] Use sanitized_Request [xtube] Use sanitized_Request [xvideos] Use sanitized_Request [yandexmusic] Use sanitized_Request [youku] Use sanitized_Request [youporn] Use sanitized_Request [youtube] Use sanitized_Request [patreon] Use sanitized_Request [extractor/common] Remove unused import [nfb] PEP 8
9 years ago
10 years ago
Switch codebase to use sanitized_Request instead of compat_urllib_request.Request [downloader/dash] Use sanitized_Request [downloader/http] Use sanitized_Request [atresplayer] Use sanitized_Request [bambuser] Use sanitized_Request [bliptv] Use sanitized_Request [brightcove] Use sanitized_Request [cbs] Use sanitized_Request [ceskatelevize] Use sanitized_Request [collegerama] Use sanitized_Request [extractor/common] Use sanitized_Request [crunchyroll] Use sanitized_Request [dailymotion] Use sanitized_Request [dcn] Use sanitized_Request [dramafever] Use sanitized_Request [dumpert] Use sanitized_Request [eitb] Use sanitized_Request [escapist] Use sanitized_Request [everyonesmixtape] Use sanitized_Request [extremetube] Use sanitized_Request [facebook] Use sanitized_Request [fc2] Use sanitized_Request [flickr] Use sanitized_Request [4tube] Use sanitized_Request [gdcvault] Use sanitized_Request [extractor/generic] Use sanitized_Request [hearthisat] Use sanitized_Request [hotnewhiphop] Use sanitized_Request [hypem] Use sanitized_Request [iprima] Use sanitized_Request [ivi] Use sanitized_Request [keezmovies] Use sanitized_Request [letv] Use sanitized_Request [lynda] Use sanitized_Request [metacafe] Use sanitized_Request [minhateca] Use sanitized_Request [miomio] Use sanitized_Request [meovideo] Use sanitized_Request [mofosex] Use sanitized_Request [moniker] Use sanitized_Request [mooshare] Use sanitized_Request [movieclips] Use sanitized_Request [mtv] Use sanitized_Request [myvideo] Use sanitized_Request [neteasemusic] Use sanitized_Request [nfb] Use sanitized_Request [niconico] Use sanitized_Request [noco] Use sanitized_Request [nosvideo] Use sanitized_Request [novamov] Use sanitized_Request [nowness] Use sanitized_Request [nuvid] Use sanitized_Request [played] Use sanitized_Request [pluralsight] Use sanitized_Request [pornhub] Use sanitized_Request [pornotube] Use sanitized_Request [primesharetv] Use sanitized_Request [promptfile] Use sanitized_Request [qqmusic] Use sanitized_Request [rtve] Use sanitized_Request [safari] Use sanitized_Request [sandia] Use sanitized_Request [shared] Use sanitized_Request [sharesix] Use sanitized_Request [sina] Use sanitized_Request [smotri] Use sanitized_Request [sohu] Use sanitized_Request [spankwire] Use sanitized_Request [sportdeutschland] Use sanitized_Request [streamcloud] Use sanitized_Request [streamcz] Use sanitized_Request [tapely] Use sanitized_Request [tube8] Use sanitized_Request [tubitv] Use sanitized_Request [twitch] Use sanitized_Request [twitter] Use sanitized_Request [udemy] Use sanitized_Request [vbox7] Use sanitized_Request [veoh] Use sanitized_Request [vessel] Use sanitized_Request [vevo] Use sanitized_Request [viddler] Use sanitized_Request [videomega] Use sanitized_Request [viewvster] Use sanitized_Request [viki] Use sanitized_Request [vk] Use sanitized_Request [vodlocker] Use sanitized_Request [voicerepublic] Use sanitized_Request [wistia] Use sanitized_Request [xfileshare] Use sanitized_Request [xtube] Use sanitized_Request [xvideos] Use sanitized_Request [yandexmusic] Use sanitized_Request [youku] Use sanitized_Request [youporn] Use sanitized_Request [youtube] Use sanitized_Request [patreon] Use sanitized_Request [extractor/common] Remove unused import [nfb] PEP 8
9 years ago
Switch codebase to use sanitized_Request instead of compat_urllib_request.Request [downloader/dash] Use sanitized_Request [downloader/http] Use sanitized_Request [atresplayer] Use sanitized_Request [bambuser] Use sanitized_Request [bliptv] Use sanitized_Request [brightcove] Use sanitized_Request [cbs] Use sanitized_Request [ceskatelevize] Use sanitized_Request [collegerama] Use sanitized_Request [extractor/common] Use sanitized_Request [crunchyroll] Use sanitized_Request [dailymotion] Use sanitized_Request [dcn] Use sanitized_Request [dramafever] Use sanitized_Request [dumpert] Use sanitized_Request [eitb] Use sanitized_Request [escapist] Use sanitized_Request [everyonesmixtape] Use sanitized_Request [extremetube] Use sanitized_Request [facebook] Use sanitized_Request [fc2] Use sanitized_Request [flickr] Use sanitized_Request [4tube] Use sanitized_Request [gdcvault] Use sanitized_Request [extractor/generic] Use sanitized_Request [hearthisat] Use sanitized_Request [hotnewhiphop] Use sanitized_Request [hypem] Use sanitized_Request [iprima] Use sanitized_Request [ivi] Use sanitized_Request [keezmovies] Use sanitized_Request [letv] Use sanitized_Request [lynda] Use sanitized_Request [metacafe] Use sanitized_Request [minhateca] Use sanitized_Request [miomio] Use sanitized_Request [meovideo] Use sanitized_Request [mofosex] Use sanitized_Request [moniker] Use sanitized_Request [mooshare] Use sanitized_Request [movieclips] Use sanitized_Request [mtv] Use sanitized_Request [myvideo] Use sanitized_Request [neteasemusic] Use sanitized_Request [nfb] Use sanitized_Request [niconico] Use sanitized_Request [noco] Use sanitized_Request [nosvideo] Use sanitized_Request [novamov] Use sanitized_Request [nowness] Use sanitized_Request [nuvid] Use sanitized_Request [played] Use sanitized_Request [pluralsight] Use sanitized_Request [pornhub] Use sanitized_Request [pornotube] Use sanitized_Request [primesharetv] Use sanitized_Request [promptfile] Use sanitized_Request [qqmusic] Use sanitized_Request [rtve] Use sanitized_Request [safari] Use sanitized_Request [sandia] Use sanitized_Request [shared] Use sanitized_Request [sharesix] Use sanitized_Request [sina] Use sanitized_Request [smotri] Use sanitized_Request [sohu] Use sanitized_Request [spankwire] Use sanitized_Request [sportdeutschland] Use sanitized_Request [streamcloud] Use sanitized_Request [streamcz] Use sanitized_Request [tapely] Use sanitized_Request [tube8] Use sanitized_Request [tubitv] Use sanitized_Request [twitch] Use sanitized_Request [twitter] Use sanitized_Request [udemy] Use sanitized_Request [vbox7] Use sanitized_Request [veoh] Use sanitized_Request [vessel] Use sanitized_Request [vevo] Use sanitized_Request [viddler] Use sanitized_Request [videomega] Use sanitized_Request [viewvster] Use sanitized_Request [viki] Use sanitized_Request [vk] Use sanitized_Request [vodlocker] Use sanitized_Request [voicerepublic] Use sanitized_Request [wistia] Use sanitized_Request [xfileshare] Use sanitized_Request [xtube] Use sanitized_Request [xvideos] Use sanitized_Request [yandexmusic] Use sanitized_Request [youku] Use sanitized_Request [youporn] Use sanitized_Request [youtube] Use sanitized_Request [patreon] Use sanitized_Request [extractor/common] Remove unused import [nfb] PEP 8
9 years ago
10 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_parse_qs,
  16. compat_urllib_parse,
  17. compat_urllib_parse_unquote,
  18. compat_urllib_parse_unquote_plus,
  19. compat_urllib_parse_urlparse,
  20. compat_urlparse,
  21. compat_str,
  22. )
  23. from ..utils import (
  24. clean_html,
  25. encode_dict,
  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_duration,
  35. remove_quotes,
  36. remove_start,
  37. sanitized_Request,
  38. smuggle_url,
  39. str_to_int,
  40. unescapeHTML,
  41. unified_strdate,
  42. unsmuggle_url,
  43. uppercase_escape,
  44. ISO3166Utils,
  45. )
  46. class YoutubeBaseInfoExtractor(InfoExtractor):
  47. """Provide base functions for Youtube extractors"""
  48. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  49. _TWOFACTOR_URL = 'https://accounts.google.com/signin/challenge'
  50. _NETRC_MACHINE = 'youtube'
  51. # If True it will raise an error if no login info is provided
  52. _LOGIN_REQUIRED = False
  53. def _set_language(self):
  54. self._set_cookie(
  55. '.youtube.com', 'PREF', 'f1=50000000&hl=en',
  56. # YouTube sets the expire time to about two months
  57. expire_time=time.time() + 2 * 30 * 24 * 3600)
  58. def _ids_to_results(self, ids):
  59. return [
  60. self.url_result(vid_id, 'Youtube', video_id=vid_id)
  61. for vid_id in ids]
  62. def _login(self):
  63. """
  64. Attempt to log in to YouTube.
  65. True is returned if successful or skipped.
  66. False is returned if login failed.
  67. If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
  68. """
  69. (username, password) = self._get_login_info()
  70. # No authentication to be performed
  71. if username is None:
  72. if self._LOGIN_REQUIRED:
  73. raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  74. return True
  75. login_page = self._download_webpage(
  76. self._LOGIN_URL, None,
  77. note='Downloading login page',
  78. errnote='unable to fetch login page', fatal=False)
  79. if login_page is False:
  80. return
  81. galx = self._search_regex(r'(?s)<input.+?name="GALX".+?value="(.+?)"',
  82. login_page, 'Login GALX parameter')
  83. # Log in
  84. login_form_strs = {
  85. 'continue': 'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  86. 'Email': username,
  87. 'GALX': galx,
  88. 'Passwd': password,
  89. 'PersistentCookie': 'yes',
  90. '_utf8': '',
  91. 'bgresponse': 'js_disabled',
  92. 'checkConnection': '',
  93. 'checkedDomains': 'youtube',
  94. 'dnConn': '',
  95. 'pstMsg': '0',
  96. 'rmShown': '1',
  97. 'secTok': '',
  98. 'signIn': 'Sign in',
  99. 'timeStmp': '',
  100. 'service': 'youtube',
  101. 'uilel': '3',
  102. 'hl': 'en_US',
  103. }
  104. login_data = compat_urllib_parse.urlencode(encode_dict(login_form_strs)).encode('ascii')
  105. req = sanitized_Request(self._LOGIN_URL, login_data)
  106. login_results = self._download_webpage(
  107. req, None,
  108. note='Logging in', errnote='unable to log in', fatal=False)
  109. if login_results is False:
  110. return False
  111. if re.search(r'id="errormsg_0_Passwd"', login_results) is not None:
  112. raise ExtractorError('Please use your account password and a two-factor code instead of an application-specific password.', expected=True)
  113. # Two-Factor
  114. # TODO add SMS and phone call support - these require making a request and then prompting the user
  115. if re.search(r'(?i)<form[^>]* id="challenge"', login_results) is not None:
  116. tfa_code = self._get_tfa_info('2-step verification code')
  117. if not tfa_code:
  118. self._downloader.report_warning(
  119. 'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
  120. '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
  121. return False
  122. tfa_code = remove_start(tfa_code, 'G-')
  123. tfa_form_strs = self._form_hidden_inputs('challenge', login_results)
  124. tfa_form_strs.update({
  125. 'Pin': tfa_code,
  126. 'TrustDevice': 'on',
  127. })
  128. tfa_data = compat_urllib_parse.urlencode(encode_dict(tfa_form_strs)).encode('ascii')
  129. tfa_req = sanitized_Request(self._TWOFACTOR_URL, tfa_data)
  130. tfa_results = self._download_webpage(
  131. tfa_req, None,
  132. note='Submitting TFA code', errnote='unable to submit tfa', fatal=False)
  133. if tfa_results is False:
  134. return False
  135. if re.search(r'(?i)<form[^>]* id="challenge"', tfa_results) is not None:
  136. self._downloader.report_warning('Two-factor code expired or invalid. Please try again, or use a one-use backup code instead.')
  137. return False
  138. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', tfa_results) is not None:
  139. self._downloader.report_warning('unable to log in - did the page structure change?')
  140. return False
  141. if re.search(r'smsauth-interstitial-reviewsettings', tfa_results) is not None:
  142. self._downloader.report_warning('Your Google account has a security notice. Please log in on your web browser, resolve the notice, and try again.')
  143. return False
  144. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  145. self._downloader.report_warning('unable to log in: bad username or password')
  146. return False
  147. return True
  148. def _real_initialize(self):
  149. if self._downloader is None:
  150. return
  151. self._set_language()
  152. if not self._login():
  153. return
  154. class YoutubeEntryListBaseInfoExtractor(YoutubeBaseInfoExtractor):
  155. # Extract entries from page with "Load more" button
  156. def _entries(self, page, playlist_id):
  157. more_widget_html = content_html = page
  158. for page_num in itertools.count(1):
  159. for entry in self._process_page(content_html):
  160. yield entry
  161. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  162. if not mobj:
  163. break
  164. more = self._download_json(
  165. 'https://youtube.com/%s' % mobj.group('more'), playlist_id,
  166. 'Downloading page #%s' % page_num,
  167. transform_source=uppercase_escape)
  168. content_html = more['content_html']
  169. if not content_html.strip():
  170. # Some webpages show a "Load more" button but they don't
  171. # have more videos
  172. break
  173. more_widget_html = more['load_more_widget_html']
  174. class YoutubePlaylistBaseInfoExtractor(YoutubeEntryListBaseInfoExtractor):
  175. def _process_page(self, content):
  176. for video_id, video_title in self.extract_videos_from_page(content):
  177. yield self.url_result(video_id, 'Youtube', video_id, video_title)
  178. def extract_videos_from_page(self, page):
  179. ids_in_page = []
  180. titles_in_page = []
  181. for mobj in re.finditer(self._VIDEO_RE, page):
  182. # The link with index 0 is not the first video of the playlist (not sure if still actual)
  183. if 'index' in mobj.groupdict() and mobj.group('id') == '0':
  184. continue
  185. video_id = mobj.group('id')
  186. video_title = unescapeHTML(mobj.group('title'))
  187. if video_title:
  188. video_title = video_title.strip()
  189. try:
  190. idx = ids_in_page.index(video_id)
  191. if video_title and not titles_in_page[idx]:
  192. titles_in_page[idx] = video_title
  193. except ValueError:
  194. ids_in_page.append(video_id)
  195. titles_in_page.append(video_title)
  196. return zip(ids_in_page, titles_in_page)
  197. class YoutubePlaylistsBaseInfoExtractor(YoutubeEntryListBaseInfoExtractor):
  198. def _process_page(self, content):
  199. for playlist_id in orderedSet(re.findall(r'href="/?playlist\?list=([0-9A-Za-z-_]{10,})"', content)):
  200. yield self.url_result(
  201. 'https://www.youtube.com/playlist?list=%s' % playlist_id, 'YoutubePlaylist')
  202. def _real_extract(self, url):
  203. playlist_id = self._match_id(url)
  204. webpage = self._download_webpage(url, playlist_id)
  205. title = self._og_search_title(webpage, fatal=False)
  206. return self.playlist_result(self._entries(webpage, playlist_id), playlist_id, title)
  207. class YoutubeIE(YoutubeBaseInfoExtractor):
  208. IE_DESC = 'YouTube.com'
  209. _VALID_URL = r"""(?x)^
  210. (
  211. (?:https?://|//) # http(s):// or protocol-independent URL
  212. (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
  213. (?:www\.)?deturl\.com/www\.youtube\.com/|
  214. (?:www\.)?pwnyoutube\.com/|
  215. (?:www\.)?yourepeat\.com/|
  216. tube\.majestyc\.net/|
  217. youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
  218. (?:.*?\#/)? # handle anchor (#/) redirect urls
  219. (?: # the various things that can precede the ID:
  220. (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
  221. |(?: # or the v= param in all its forms
  222. (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  223. (?:\?|\#!?) # the params delimiter ? or # or #!
  224. (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&amp;v=V36LpHqtcDY)
  225. v=
  226. )
  227. ))
  228. |(?:
  229. youtu\.be| # just youtu.be/xxxx
  230. vid\.plus # or vid.plus/xxxx
  231. )/
  232. |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
  233. )
  234. )? # all until now is optional -> you can pass the naked ID
  235. ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  236. (?!.*?&list=) # combined list/video URLs are handled by the playlist IE
  237. (?(1).+)? # if we found the ID, everything can follow
  238. $"""
  239. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  240. _formats = {
  241. '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
  242. '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
  243. '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'},
  244. '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'},
  245. '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'},
  246. '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  247. '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  248. '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  249. # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
  250. '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'},
  251. '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  252. '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  253. '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
  254. '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
  255. '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
  256. '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
  257. '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  258. '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  259. # 3D videos
  260. '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
  261. '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
  262. '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
  263. '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
  264. '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20},
  265. '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
  266. '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
  267. # Apple HTTP Live Streaming
  268. '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  269. '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
  270. '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
  271. '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
  272. '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
  273. '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  274. '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10},
  275. # DASH mp4 video
  276. '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264', 'preference': -40},
  277. '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264', 'preference': -40},
  278. '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264', 'preference': -40},
  279. '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'preference': -40},
  280. '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'preference': -40},
  281. '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264', 'preference': -40}, # Height can vary (https://github.com/rg3/youtube-dl/issues/4559)
  282. '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264', 'preference': -40},
  283. '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264', 'preference': -40},
  284. '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60, 'preference': -40},
  285. '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60, 'preference': -40},
  286. '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264', 'preference': -40},
  287. # Dash mp4 audio
  288. '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'preference': -50, 'container': 'm4a_dash'},
  289. '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'preference': -50, 'container': 'm4a_dash'},
  290. '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'preference': -50, 'container': 'm4a_dash'},
  291. # Dash webm
  292. '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  293. '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  294. '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  295. '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  296. '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  297. '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  298. '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9', 'preference': -40},
  299. '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  300. '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  301. '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  302. '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  303. '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  304. '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  305. '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  306. '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  307. # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
  308. '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  309. '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60, 'preference': -40},
  310. '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60, 'preference': -40},
  311. '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60, 'preference': -40},
  312. '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  313. '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60, 'preference': -40},
  314. # Dash webm audio
  315. '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128, 'preference': -50},
  316. '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256, 'preference': -50},
  317. # Dash webm audio with opus inside
  318. '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50, 'preference': -50},
  319. '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70, 'preference': -50},
  320. '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160, 'preference': -50},
  321. # RTMP (unnamed)
  322. '_rtmp': {'protocol': 'rtmp'},
  323. }
  324. _SUBTITLE_FORMATS = ('ttml', 'vtt')
  325. IE_NAME = 'youtube'
  326. _TESTS = [
  327. {
  328. 'url': 'http://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
  329. 'info_dict': {
  330. 'id': 'BaW_jenozKc',
  331. 'ext': 'mp4',
  332. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  333. 'uploader': 'Philipp Hagemeister',
  334. 'uploader_id': 'phihag',
  335. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/phihag',
  336. 'upload_date': '20121002',
  337. 'license': 'Standard YouTube License',
  338. '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 .',
  339. 'categories': ['Science & Technology'],
  340. 'tags': ['youtube-dl'],
  341. 'like_count': int,
  342. 'dislike_count': int,
  343. 'start_time': 1,
  344. 'end_time': 9,
  345. }
  346. },
  347. {
  348. 'url': 'http://www.youtube.com/watch?v=UxxajLWwzqY',
  349. 'note': 'Test generic use_cipher_signature video (#897)',
  350. 'info_dict': {
  351. 'id': 'UxxajLWwzqY',
  352. 'ext': 'mp4',
  353. 'upload_date': '20120506',
  354. 'title': 'Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]',
  355. 'alt_title': 'I Love It (feat. Charli XCX)',
  356. 'description': 'md5:f3ceb5ef83a08d95b9d146f973157cc8',
  357. 'tags': ['Icona Pop i love it', 'sweden', 'pop music', 'big beat records', 'big beat', 'charli',
  358. 'xcx', 'charli xcx', 'girls', 'hbo', 'i love it', "i don't care", 'icona', 'pop',
  359. 'iconic ep', 'iconic', 'love', 'it'],
  360. 'uploader': 'Icona Pop',
  361. 'uploader_id': 'IconaPop',
  362. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/IconaPop',
  363. 'license': 'Standard YouTube License',
  364. 'creator': 'Icona Pop',
  365. }
  366. },
  367. {
  368. 'url': 'https://www.youtube.com/watch?v=07FYdnEawAQ',
  369. 'note': 'Test VEVO video with age protection (#956)',
  370. 'info_dict': {
  371. 'id': '07FYdnEawAQ',
  372. 'ext': 'mp4',
  373. 'upload_date': '20130703',
  374. 'title': 'Justin Timberlake - Tunnel Vision (Explicit)',
  375. 'alt_title': 'Tunnel Vision',
  376. 'description': 'md5:64249768eec3bc4276236606ea996373',
  377. 'uploader': 'justintimberlakeVEVO',
  378. 'uploader_id': 'justintimberlakeVEVO',
  379. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/justintimberlakeVEVO',
  380. 'license': 'Standard YouTube License',
  381. 'creator': 'Justin Timberlake',
  382. 'age_limit': 18,
  383. }
  384. },
  385. {
  386. 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
  387. 'note': 'Embed-only video (#1746)',
  388. 'info_dict': {
  389. 'id': 'yZIXLfi8CZQ',
  390. 'ext': 'mp4',
  391. 'upload_date': '20120608',
  392. 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
  393. 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
  394. 'uploader': 'SET India',
  395. 'uploader_id': 'setindia',
  396. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/setindia',
  397. 'license': 'Standard YouTube License',
  398. 'age_limit': 18,
  399. }
  400. },
  401. {
  402. 'url': 'http://www.youtube.com/watch?v=BaW_jenozKc&v=UxxajLWwzqY',
  403. 'note': 'Use the first video ID in the URL',
  404. 'info_dict': {
  405. 'id': 'BaW_jenozKc',
  406. 'ext': 'mp4',
  407. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  408. 'uploader': 'Philipp Hagemeister',
  409. 'uploader_id': 'phihag',
  410. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/phihag',
  411. 'upload_date': '20121002',
  412. 'license': 'Standard YouTube License',
  413. '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 .',
  414. 'categories': ['Science & Technology'],
  415. 'tags': ['youtube-dl'],
  416. 'like_count': int,
  417. 'dislike_count': int,
  418. },
  419. 'params': {
  420. 'skip_download': True,
  421. },
  422. },
  423. {
  424. 'url': 'http://www.youtube.com/watch?v=a9LDPn-MO4I',
  425. 'note': '256k DASH audio (format 141) via DASH manifest',
  426. 'info_dict': {
  427. 'id': 'a9LDPn-MO4I',
  428. 'ext': 'm4a',
  429. 'upload_date': '20121002',
  430. 'uploader_id': '8KVIDEO',
  431. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/8KVIDEO',
  432. 'description': '',
  433. 'uploader': '8KVIDEO',
  434. 'license': 'Standard YouTube License',
  435. 'title': 'UHDTV TEST 8K VIDEO.mp4'
  436. },
  437. 'params': {
  438. 'youtube_include_dash_manifest': True,
  439. 'format': '141',
  440. },
  441. },
  442. # DASH manifest with encrypted signature
  443. {
  444. 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
  445. 'info_dict': {
  446. 'id': 'IB3lcPjvWLA',
  447. 'ext': 'm4a',
  448. 'title': 'Afrojack, Spree Wilson - The Spark ft. Spree Wilson',
  449. 'description': 'md5:12e7067fa6735a77bdcbb58cb1187d2d',
  450. 'uploader': 'AfrojackVEVO',
  451. 'uploader_id': 'AfrojackVEVO',
  452. 'upload_date': '20131011',
  453. 'license': 'Standard YouTube License',
  454. },
  455. 'params': {
  456. 'youtube_include_dash_manifest': True,
  457. 'format': '141',
  458. },
  459. },
  460. # JS player signature function name containing $
  461. {
  462. 'url': 'https://www.youtube.com/watch?v=nfWlot6h_JM',
  463. 'info_dict': {
  464. 'id': 'nfWlot6h_JM',
  465. 'ext': 'm4a',
  466. 'title': 'Taylor Swift - Shake It Off',
  467. 'alt_title': 'Shake It Off',
  468. 'description': 'md5:95f66187cd7c8b2c13eb78e1223b63c3',
  469. 'uploader': 'TaylorSwiftVEVO',
  470. 'uploader_id': 'TaylorSwiftVEVO',
  471. 'upload_date': '20140818',
  472. 'license': 'Standard YouTube License',
  473. 'creator': 'Taylor Swift',
  474. },
  475. 'params': {
  476. 'youtube_include_dash_manifest': True,
  477. 'format': '141',
  478. },
  479. },
  480. # Controversy video
  481. {
  482. 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
  483. 'info_dict': {
  484. 'id': 'T4XJQO3qol8',
  485. 'ext': 'mp4',
  486. 'upload_date': '20100909',
  487. 'uploader': 'The Amazing Atheist',
  488. 'uploader_id': 'TheAmazingAtheist',
  489. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/TheAmazingAtheist',
  490. 'license': 'Standard YouTube License',
  491. 'title': 'Burning Everyone\'s Koran',
  492. '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',
  493. }
  494. },
  495. # Normal age-gate video (No vevo, embed allowed)
  496. {
  497. 'url': 'http://youtube.com/watch?v=HtVdAasjOgU',
  498. 'info_dict': {
  499. 'id': 'HtVdAasjOgU',
  500. 'ext': 'mp4',
  501. 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
  502. 'description': 're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
  503. 'uploader': 'The Witcher',
  504. 'uploader_id': 'WitcherGame',
  505. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/WitcherGame',
  506. 'upload_date': '20140605',
  507. 'license': 'Standard YouTube License',
  508. 'age_limit': 18,
  509. },
  510. },
  511. # Age-gate video with encrypted signature
  512. {
  513. 'url': 'http://www.youtube.com/watch?v=6kLq3WMV1nU',
  514. 'info_dict': {
  515. 'id': '6kLq3WMV1nU',
  516. 'ext': 'mp4',
  517. 'title': 'Dedication To My Ex (Miss That) (Lyric Video)',
  518. 'description': 'md5:33765bb339e1b47e7e72b5490139bb41',
  519. 'uploader': 'LloydVEVO',
  520. 'uploader_id': 'LloydVEVO',
  521. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/LloydVEVO',
  522. 'upload_date': '20110629',
  523. 'license': 'Standard YouTube License',
  524. 'age_limit': 18,
  525. },
  526. },
  527. # video_info is None (https://github.com/rg3/youtube-dl/issues/4421)
  528. {
  529. 'url': '__2ABJjxzNo',
  530. 'info_dict': {
  531. 'id': '__2ABJjxzNo',
  532. 'ext': 'mp4',
  533. 'upload_date': '20100430',
  534. 'uploader_id': 'deadmau5',
  535. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/deadmau5',
  536. 'creator': 'deadmau5',
  537. 'description': 'md5:12c56784b8032162bb936a5f76d55360',
  538. 'uploader': 'deadmau5',
  539. 'license': 'Standard YouTube License',
  540. 'title': 'Deadmau5 - Some Chords (HD)',
  541. 'alt_title': 'Some Chords',
  542. },
  543. 'expected_warnings': [
  544. 'DASH manifest missing',
  545. ]
  546. },
  547. # Olympics (https://github.com/rg3/youtube-dl/issues/4431)
  548. {
  549. 'url': 'lqQg6PlCWgI',
  550. 'info_dict': {
  551. 'id': 'lqQg6PlCWgI',
  552. 'ext': 'mp4',
  553. 'upload_date': '20150827',
  554. 'uploader_id': 'olympic',
  555. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/olympic',
  556. 'license': 'Standard YouTube License',
  557. 'description': 'HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
  558. 'uploader': 'Olympics',
  559. 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
  560. },
  561. 'params': {
  562. 'skip_download': 'requires avconv',
  563. }
  564. },
  565. # Non-square pixels
  566. {
  567. 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
  568. 'info_dict': {
  569. 'id': '_b-2C3KPAM0',
  570. 'ext': 'mp4',
  571. 'stretched_ratio': 16 / 9.,
  572. 'upload_date': '20110310',
  573. 'uploader_id': 'AllenMeow',
  574. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/AllenMeow',
  575. 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
  576. 'uploader': '孫艾倫',
  577. 'license': 'Standard YouTube License',
  578. 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
  579. },
  580. },
  581. # url_encoded_fmt_stream_map is empty string
  582. {
  583. 'url': 'qEJwOuvDf7I',
  584. 'info_dict': {
  585. 'id': 'qEJwOuvDf7I',
  586. 'ext': 'webm',
  587. 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
  588. 'description': '',
  589. 'upload_date': '20150404',
  590. 'uploader_id': 'spbelect',
  591. 'uploader': 'Наблюдатели Петербурга',
  592. },
  593. 'params': {
  594. 'skip_download': 'requires avconv',
  595. },
  596. 'skip': 'This live event has ended.',
  597. },
  598. # Extraction from multiple DASH manifests (https://github.com/rg3/youtube-dl/pull/6097)
  599. {
  600. 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
  601. 'info_dict': {
  602. 'id': 'FIl7x6_3R5Y',
  603. 'ext': 'mp4',
  604. 'title': 'md5:7b81415841e02ecd4313668cde88737a',
  605. 'description': 'md5:116377fd2963b81ec4ce64b542173306',
  606. 'upload_date': '20150625',
  607. 'uploader_id': 'dorappi2000',
  608. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/dorappi2000',
  609. 'uploader': 'dorappi2000',
  610. 'license': 'Standard YouTube License',
  611. 'formats': 'mincount:33',
  612. },
  613. },
  614. # DASH manifest with segment_list
  615. {
  616. 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
  617. 'md5': '8ce563a1d667b599d21064e982ab9e31',
  618. 'info_dict': {
  619. 'id': 'CsmdDsKjzN8',
  620. 'ext': 'mp4',
  621. 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
  622. 'uploader': 'Airtek',
  623. 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
  624. 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
  625. 'license': 'Standard YouTube License',
  626. 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
  627. },
  628. 'params': {
  629. 'youtube_include_dash_manifest': True,
  630. 'format': '135', # bestvideo
  631. }
  632. },
  633. {
  634. # Multifeed videos (multiple cameras), URL is for Main Camera
  635. 'url': 'https://www.youtube.com/watch?v=jqWvoWXjCVs',
  636. 'info_dict': {
  637. 'id': 'jqWvoWXjCVs',
  638. 'title': 'teamPGP: Rocket League Noob Stream',
  639. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  640. },
  641. 'playlist': [{
  642. 'info_dict': {
  643. 'id': 'jqWvoWXjCVs',
  644. 'ext': 'mp4',
  645. 'title': 'teamPGP: Rocket League Noob Stream (Main Camera)',
  646. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  647. 'upload_date': '20150721',
  648. 'uploader': 'Beer Games Beer',
  649. 'uploader_id': 'beergamesbeer',
  650. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
  651. 'license': 'Standard YouTube License',
  652. },
  653. }, {
  654. 'info_dict': {
  655. 'id': '6h8e8xoXJzg',
  656. 'ext': 'mp4',
  657. 'title': 'teamPGP: Rocket League Noob Stream (kreestuh)',
  658. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  659. 'upload_date': '20150721',
  660. 'uploader': 'Beer Games Beer',
  661. 'uploader_id': 'beergamesbeer',
  662. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
  663. 'license': 'Standard YouTube License',
  664. },
  665. }, {
  666. 'info_dict': {
  667. 'id': 'PUOgX5z9xZw',
  668. 'ext': 'mp4',
  669. 'title': 'teamPGP: Rocket League Noob Stream (grizzle)',
  670. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  671. 'upload_date': '20150721',
  672. 'uploader': 'Beer Games Beer',
  673. 'uploader_id': 'beergamesbeer',
  674. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
  675. 'license': 'Standard YouTube License',
  676. },
  677. }, {
  678. 'info_dict': {
  679. 'id': 'teuwxikvS5k',
  680. 'ext': 'mp4',
  681. 'title': 'teamPGP: Rocket League Noob Stream (zim)',
  682. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  683. 'upload_date': '20150721',
  684. 'uploader': 'Beer Games Beer',
  685. 'uploader_id': 'beergamesbeer',
  686. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
  687. 'license': 'Standard YouTube License',
  688. },
  689. }],
  690. 'params': {
  691. 'skip_download': True,
  692. },
  693. },
  694. {
  695. # Multifeed video with comma in title (see https://github.com/rg3/youtube-dl/issues/8536)
  696. 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
  697. 'info_dict': {
  698. 'id': 'gVfLd0zydlo',
  699. 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
  700. },
  701. 'playlist_count': 2,
  702. },
  703. {
  704. 'url': 'http://vid.plus/FlRa-iH7PGw',
  705. 'only_matching': True,
  706. },
  707. {
  708. # Title with JS-like syntax "};" (see https://github.com/rg3/youtube-dl/issues/7468)
  709. # Also tests cut-off URL expansion in video description (see
  710. # https://github.com/rg3/youtube-dl/issues/1892,
  711. # https://github.com/rg3/youtube-dl/issues/8164)
  712. 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
  713. 'info_dict': {
  714. 'id': 'lsguqyKfVQg',
  715. 'ext': 'mp4',
  716. 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
  717. 'alt_title': 'Dark Walk',
  718. 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
  719. 'upload_date': '20151119',
  720. 'uploader_id': 'IronSoulElf',
  721. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/IronSoulElf',
  722. 'uploader': 'IronSoulElf',
  723. 'license': 'Standard YouTube License',
  724. 'creator': 'Todd Haberman, Daniel Law Heath & Aaron Kaplan',
  725. },
  726. 'params': {
  727. 'skip_download': True,
  728. },
  729. },
  730. {
  731. # Tags with '};' (see https://github.com/rg3/youtube-dl/issues/7468)
  732. 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
  733. 'only_matching': True,
  734. },
  735. {
  736. # Video with yt:stretch=17:0
  737. 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
  738. 'info_dict': {
  739. 'id': 'Q39EVAstoRM',
  740. 'ext': 'mp4',
  741. 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
  742. 'description': 'md5:ee18a25c350637c8faff806845bddee9',
  743. 'upload_date': '20151107',
  744. 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
  745. 'uploader': 'CH GAMER DROID',
  746. },
  747. 'params': {
  748. 'skip_download': True,
  749. },
  750. },
  751. {
  752. # Video licensed under Creative Commons
  753. 'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
  754. 'info_dict': {
  755. 'id': 'M4gD1WSo5mA',
  756. 'ext': 'mp4',
  757. 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
  758. 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
  759. 'upload_date': '20150127',
  760. 'uploader_id': 'BerkmanCenter',
  761. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/user/BerkmanCenter',
  762. 'uploader': 'BerkmanCenter',
  763. 'license': 'Creative Commons Attribution license (reuse allowed)',
  764. },
  765. 'params': {
  766. 'skip_download': True,
  767. },
  768. },
  769. {
  770. # Channel-like uploader_url
  771. 'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
  772. 'info_dict': {
  773. 'id': 'eQcmzGIKrzg',
  774. 'ext': 'mp4',
  775. 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
  776. 'description': 'md5:dda0d780d5a6e120758d1711d062a867',
  777. 'upload_date': '20151119',
  778. 'uploader': 'Bernie 2016',
  779. 'uploader_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
  780. 'uploader_url': 're:https?://(?:www\.)?youtube\.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
  781. 'license': 'Creative Commons Attribution license (reuse allowed)',
  782. },
  783. 'params': {
  784. 'skip_download': True,
  785. },
  786. },
  787. {
  788. 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;amp;v=V36LpHqtcDY',
  789. 'only_matching': True,
  790. }
  791. ]
  792. def __init__(self, *args, **kwargs):
  793. super(YoutubeIE, self).__init__(*args, **kwargs)
  794. self._player_cache = {}
  795. def report_video_info_webpage_download(self, video_id):
  796. """Report attempt to download video info webpage."""
  797. self.to_screen('%s: Downloading video info webpage' % video_id)
  798. def report_information_extraction(self, video_id):
  799. """Report attempt to extract video information."""
  800. self.to_screen('%s: Extracting video information' % video_id)
  801. def report_unavailable_format(self, video_id, format):
  802. """Report extracted video URL."""
  803. self.to_screen('%s: Format %s not available' % (video_id, format))
  804. def report_rtmp_download(self):
  805. """Indicate the download will use the RTMP protocol."""
  806. self.to_screen('RTMP download detected')
  807. def _signature_cache_id(self, example_sig):
  808. """ Return a string representation of a signature """
  809. return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
  810. def _extract_signature_function(self, video_id, player_url, example_sig):
  811. id_m = re.match(
  812. r'.*?-(?P<id>[a-zA-Z0-9_-]+)(?:/watch_as3|/html5player(?:-new)?|/base)?\.(?P<ext>[a-z]+)$',
  813. player_url)
  814. if not id_m:
  815. raise ExtractorError('Cannot identify player %r' % player_url)
  816. player_type = id_m.group('ext')
  817. player_id = id_m.group('id')
  818. # Read from filesystem cache
  819. func_id = '%s_%s_%s' % (
  820. player_type, player_id, self._signature_cache_id(example_sig))
  821. assert os.path.basename(func_id) == func_id
  822. cache_spec = self._downloader.cache.load('youtube-sigfuncs', func_id)
  823. if cache_spec is not None:
  824. return lambda s: ''.join(s[i] for i in cache_spec)
  825. download_note = (
  826. 'Downloading player %s' % player_url
  827. if self._downloader.params.get('verbose') else
  828. 'Downloading %s player %s' % (player_type, player_id)
  829. )
  830. if player_type == 'js':
  831. code = self._download_webpage(
  832. player_url, video_id,
  833. note=download_note,
  834. errnote='Download of %s failed' % player_url)
  835. res = self._parse_sig_js(code)
  836. elif player_type == 'swf':
  837. urlh = self._request_webpage(
  838. player_url, video_id,
  839. note=download_note,
  840. errnote='Download of %s failed' % player_url)
  841. code = urlh.read()
  842. res = self._parse_sig_swf(code)
  843. else:
  844. assert False, 'Invalid player type %r' % player_type
  845. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  846. cache_res = res(test_string)
  847. cache_spec = [ord(c) for c in cache_res]
  848. self._downloader.cache.store('youtube-sigfuncs', func_id, cache_spec)
  849. return res
  850. def _print_sig_code(self, func, example_sig):
  851. def gen_sig_code(idxs):
  852. def _genslice(start, end, step):
  853. starts = '' if start == 0 else str(start)
  854. ends = (':%d' % (end + step)) if end + step >= 0 else ':'
  855. steps = '' if step == 1 else (':%d' % step)
  856. return 's[%s%s%s]' % (starts, ends, steps)
  857. step = None
  858. # Quelch pyflakes warnings - start will be set when step is set
  859. start = '(Never used)'
  860. for i, prev in zip(idxs[1:], idxs[:-1]):
  861. if step is not None:
  862. if i - prev == step:
  863. continue
  864. yield _genslice(start, prev, step)
  865. step = None
  866. continue
  867. if i - prev in [-1, 1]:
  868. step = i - prev
  869. start = prev
  870. continue
  871. else:
  872. yield 's[%d]' % prev
  873. if step is None:
  874. yield 's[%d]' % i
  875. else:
  876. yield _genslice(start, i, step)
  877. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  878. cache_res = func(test_string)
  879. cache_spec = [ord(c) for c in cache_res]
  880. expr_code = ' + '.join(gen_sig_code(cache_spec))
  881. signature_id_tuple = '(%s)' % (
  882. ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
  883. code = ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
  884. ' return %s\n') % (signature_id_tuple, expr_code)
  885. self.to_screen('Extracted signature function:\n' + code)
  886. def _parse_sig_js(self, jscode):
  887. funcname = self._search_regex(
  888. r'\.sig\|\|([a-zA-Z0-9$]+)\(', jscode,
  889. 'Initial JS player signature function name')
  890. jsi = JSInterpreter(jscode)
  891. initial_function = jsi.extract_function(funcname)
  892. return lambda s: initial_function([s])
  893. def _parse_sig_swf(self, file_contents):
  894. swfi = SWFInterpreter(file_contents)
  895. TARGET_CLASSNAME = 'SignatureDecipher'
  896. searched_class = swfi.extract_class(TARGET_CLASSNAME)
  897. initial_function = swfi.extract_function(searched_class, 'decipher')
  898. return lambda s: initial_function([s])
  899. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  900. """Turn the encrypted s field into a working signature"""
  901. if player_url is None:
  902. raise ExtractorError('Cannot decrypt signature without player_url')
  903. if player_url.startswith('//'):
  904. player_url = 'https:' + player_url
  905. try:
  906. player_id = (player_url, self._signature_cache_id(s))
  907. if player_id not in self._player_cache:
  908. func = self._extract_signature_function(
  909. video_id, player_url, s
  910. )
  911. self._player_cache[player_id] = func
  912. func = self._player_cache[player_id]
  913. if self._downloader.params.get('youtube_print_sig_code'):
  914. self._print_sig_code(func, s)
  915. return func(s)
  916. except Exception as e:
  917. tb = traceback.format_exc()
  918. raise ExtractorError(
  919. 'Signature extraction failed: ' + tb, cause=e)
  920. def _get_subtitles(self, video_id, webpage):
  921. try:
  922. subs_doc = self._download_xml(
  923. 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  924. video_id, note=False)
  925. except ExtractorError as err:
  926. self._downloader.report_warning('unable to download video subtitles: %s' % error_to_compat_str(err))
  927. return {}
  928. sub_lang_list = {}
  929. for track in subs_doc.findall('track'):
  930. lang = track.attrib['lang_code']
  931. if lang in sub_lang_list:
  932. continue
  933. sub_formats = []
  934. for ext in self._SUBTITLE_FORMATS:
  935. params = compat_urllib_parse.urlencode({
  936. 'lang': lang,
  937. 'v': video_id,
  938. 'fmt': ext,
  939. 'name': track.attrib['name'].encode('utf-8'),
  940. })
  941. sub_formats.append({
  942. 'url': 'https://www.youtube.com/api/timedtext?' + params,
  943. 'ext': ext,
  944. })
  945. sub_lang_list[lang] = sub_formats
  946. if not sub_lang_list:
  947. self._downloader.report_warning('video doesn\'t have subtitles')
  948. return {}
  949. return sub_lang_list
  950. def _get_ytplayer_config(self, video_id, webpage):
  951. patterns = (
  952. # User data may contain arbitrary character sequences that may affect
  953. # JSON extraction with regex, e.g. when '};' is contained the second
  954. # regex won't capture the whole JSON. Yet working around by trying more
  955. # concrete regex first keeping in mind proper quoted string handling
  956. # to be implemented in future that will replace this workaround (see
  957. # https://github.com/rg3/youtube-dl/issues/7468,
  958. # https://github.com/rg3/youtube-dl/pull/7599)
  959. r';ytplayer\.config\s*=\s*({.+?});ytplayer',
  960. r';ytplayer\.config\s*=\s*({.+?});',
  961. )
  962. config = self._search_regex(
  963. patterns, webpage, 'ytplayer.config', default=None)
  964. if config:
  965. return self._parse_json(
  966. uppercase_escape(config), video_id, fatal=False)
  967. def _get_automatic_captions(self, video_id, webpage):
  968. """We need the webpage for getting the captions url, pass it as an
  969. argument to speed up the process."""
  970. self.to_screen('%s: Looking for automatic captions' % video_id)
  971. player_config = self._get_ytplayer_config(video_id, webpage)
  972. err_msg = 'Couldn\'t find automatic captions for %s' % video_id
  973. if not player_config:
  974. self._downloader.report_warning(err_msg)
  975. return {}
  976. try:
  977. args = player_config['args']
  978. caption_url = args.get('ttsurl')
  979. if caption_url:
  980. timestamp = args['timestamp']
  981. # We get the available subtitles
  982. list_params = compat_urllib_parse.urlencode({
  983. 'type': 'list',
  984. 'tlangs': 1,
  985. 'asrs': 1,
  986. })
  987. list_url = caption_url + '&' + list_params
  988. caption_list = self._download_xml(list_url, video_id)
  989. original_lang_node = caption_list.find('track')
  990. if original_lang_node is None:
  991. self._downloader.report_warning('Video doesn\'t have automatic captions')
  992. return {}
  993. original_lang = original_lang_node.attrib['lang_code']
  994. caption_kind = original_lang_node.attrib.get('kind', '')
  995. sub_lang_list = {}
  996. for lang_node in caption_list.findall('target'):
  997. sub_lang = lang_node.attrib['lang_code']
  998. sub_formats = []
  999. for ext in self._SUBTITLE_FORMATS:
  1000. params = compat_urllib_parse.urlencode({
  1001. 'lang': original_lang,
  1002. 'tlang': sub_lang,
  1003. 'fmt': ext,
  1004. 'ts': timestamp,
  1005. 'kind': caption_kind,
  1006. })
  1007. sub_formats.append({
  1008. 'url': caption_url + '&' + params,
  1009. 'ext': ext,
  1010. })
  1011. sub_lang_list[sub_lang] = sub_formats
  1012. return sub_lang_list
  1013. # Some videos don't provide ttsurl but rather caption_tracks and
  1014. # caption_translation_languages (e.g. 20LmZk1hakA)
  1015. caption_tracks = args['caption_tracks']
  1016. caption_translation_languages = args['caption_translation_languages']
  1017. caption_url = compat_parse_qs(caption_tracks.split(',')[0])['u'][0]
  1018. parsed_caption_url = compat_urlparse.urlparse(caption_url)
  1019. caption_qs = compat_parse_qs(parsed_caption_url.query)
  1020. sub_lang_list = {}
  1021. for lang in caption_translation_languages.split(','):
  1022. lang_qs = compat_parse_qs(compat_urllib_parse_unquote_plus(lang))
  1023. sub_lang = lang_qs.get('lc', [None])[0]
  1024. if not sub_lang:
  1025. continue
  1026. sub_formats = []
  1027. for ext in self._SUBTITLE_FORMATS:
  1028. caption_qs.update({
  1029. 'tlang': [sub_lang],
  1030. 'fmt': [ext],
  1031. })
  1032. sub_url = compat_urlparse.urlunparse(parsed_caption_url._replace(
  1033. query=compat_urllib_parse.urlencode(caption_qs, True)))
  1034. sub_formats.append({
  1035. 'url': sub_url,
  1036. 'ext': ext,
  1037. })
  1038. sub_lang_list[sub_lang] = sub_formats
  1039. return sub_lang_list
  1040. # An extractor error can be raise by the download process if there are
  1041. # no automatic captions but there are subtitles
  1042. except (KeyError, ExtractorError):
  1043. self._downloader.report_warning(err_msg)
  1044. return {}
  1045. def _mark_watched(self, video_id, video_info):
  1046. playback_url = video_info.get('videostats_playback_base_url', [None])[0]
  1047. if not playback_url:
  1048. return
  1049. parsed_playback_url = compat_urlparse.urlparse(playback_url)
  1050. qs = compat_urlparse.parse_qs(parsed_playback_url.query)
  1051. # cpn generation algorithm is reverse engineered from base.js.
  1052. # In fact it works even with dummy cpn.
  1053. CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
  1054. cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
  1055. qs.update({
  1056. 'ver': ['2'],
  1057. 'cpn': [cpn],
  1058. })
  1059. playback_url = compat_urlparse.urlunparse(
  1060. parsed_playback_url._replace(query=compat_urllib_parse.urlencode(qs, True)))
  1061. self._download_webpage(
  1062. playback_url, video_id, 'Marking watched',
  1063. 'Unable to mark watched', fatal=False)
  1064. @classmethod
  1065. def extract_id(cls, url):
  1066. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  1067. if mobj is None:
  1068. raise ExtractorError('Invalid URL: %s' % url)
  1069. video_id = mobj.group(2)
  1070. return video_id
  1071. def _extract_from_m3u8(self, manifest_url, video_id):
  1072. url_map = {}
  1073. def _get_urls(_manifest):
  1074. lines = _manifest.split('\n')
  1075. urls = filter(lambda l: l and not l.startswith('#'),
  1076. lines)
  1077. return urls
  1078. manifest = self._download_webpage(manifest_url, video_id, 'Downloading formats manifest')
  1079. formats_urls = _get_urls(manifest)
  1080. for format_url in formats_urls:
  1081. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  1082. url_map[itag] = format_url
  1083. return url_map
  1084. def _extract_annotations(self, video_id):
  1085. url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
  1086. return self._download_webpage(url, video_id, note='Searching for annotations.', errnote='Unable to download video annotations.')
  1087. def _real_extract(self, url):
  1088. url, smuggled_data = unsmuggle_url(url, {})
  1089. proto = (
  1090. 'http' if self._downloader.params.get('prefer_insecure', False)
  1091. else 'https')
  1092. start_time = None
  1093. end_time = None
  1094. parsed_url = compat_urllib_parse_urlparse(url)
  1095. for component in [parsed_url.fragment, parsed_url.query]:
  1096. query = compat_parse_qs(component)
  1097. if start_time is None and 't' in query:
  1098. start_time = parse_duration(query['t'][0])
  1099. if start_time is None and 'start' in query:
  1100. start_time = parse_duration(query['start'][0])
  1101. if end_time is None and 'end' in query:
  1102. end_time = parse_duration(query['end'][0])
  1103. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  1104. mobj = re.search(self._NEXT_URL_RE, url)
  1105. if mobj:
  1106. url = proto + '://www.youtube.com/' + compat_urllib_parse_unquote(mobj.group(1)).lstrip('/')
  1107. video_id = self.extract_id(url)
  1108. # Get video webpage
  1109. url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1&bpctr=9999999999' % video_id
  1110. video_webpage = self._download_webpage(url, video_id)
  1111. # Attempt to extract SWF player URL
  1112. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  1113. if mobj is not None:
  1114. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  1115. else:
  1116. player_url = None
  1117. dash_mpds = []
  1118. def add_dash_mpd(video_info):
  1119. dash_mpd = video_info.get('dashmpd')
  1120. if dash_mpd and dash_mpd[0] not in dash_mpds:
  1121. dash_mpds.append(dash_mpd[0])
  1122. # Get video info
  1123. embed_webpage = None
  1124. is_live = None
  1125. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  1126. age_gate = True
  1127. # We simulate the access to the video from www.youtube.com/v/{video_id}
  1128. # this can be viewed without login into Youtube
  1129. url = proto + '://www.youtube.com/embed/%s' % video_id
  1130. embed_webpage = self._download_webpage(url, video_id, 'Downloading embed webpage')
  1131. data = compat_urllib_parse.urlencode({
  1132. 'video_id': video_id,
  1133. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  1134. 'sts': self._search_regex(
  1135. r'"sts"\s*:\s*(\d+)', embed_webpage, 'sts', default=''),
  1136. })
  1137. video_info_url = proto + '://www.youtube.com/get_video_info?' + data
  1138. video_info_webpage = self._download_webpage(
  1139. video_info_url, video_id,
  1140. note='Refetching age-gated info webpage',
  1141. errnote='unable to download video info webpage')
  1142. video_info = compat_parse_qs(video_info_webpage)
  1143. add_dash_mpd(video_info)
  1144. else:
  1145. age_gate = False
  1146. video_info = None
  1147. # Try looking directly into the video webpage
  1148. ytplayer_config = self._get_ytplayer_config(video_id, video_webpage)
  1149. if ytplayer_config:
  1150. args = ytplayer_config['args']
  1151. if args.get('url_encoded_fmt_stream_map'):
  1152. # Convert to the same format returned by compat_parse_qs
  1153. video_info = dict((k, [v]) for k, v in args.items())
  1154. add_dash_mpd(video_info)
  1155. if args.get('livestream') == '1' or args.get('live_playback') == 1:
  1156. is_live = True
  1157. if not video_info or self._downloader.params.get('youtube_include_dash_manifest', True):
  1158. # We also try looking in get_video_info since it may contain different dashmpd
  1159. # URL that points to a DASH manifest with possibly different itag set (some itags
  1160. # are missing from DASH manifest pointed by webpage's dashmpd, some - from DASH
  1161. # manifest pointed by get_video_info's dashmpd).
  1162. # The general idea is to take a union of itags of both DASH manifests (for example
  1163. # video with such 'manifest behavior' see https://github.com/rg3/youtube-dl/issues/6093)
  1164. self.report_video_info_webpage_download(video_id)
  1165. for el_type in ['&el=info', '&el=embedded', '&el=detailpage', '&el=vevo', '']:
  1166. video_info_url = (
  1167. '%s://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  1168. % (proto, video_id, el_type))
  1169. video_info_webpage = self._download_webpage(
  1170. video_info_url,
  1171. video_id, note=False,
  1172. errnote='unable to download video info webpage')
  1173. get_video_info = compat_parse_qs(video_info_webpage)
  1174. if get_video_info.get('use_cipher_signature') != ['True']:
  1175. add_dash_mpd(get_video_info)
  1176. if not video_info:
  1177. video_info = get_video_info
  1178. if 'token' in get_video_info:
  1179. # Different get_video_info requests may report different results, e.g.
  1180. # some may report video unavailability, but some may serve it without
  1181. # any complaint (see https://github.com/rg3/youtube-dl/issues/7362,
  1182. # the original webpage as well as el=info and el=embedded get_video_info
  1183. # requests report video unavailability due to geo restriction while
  1184. # el=detailpage succeeds and returns valid data). This is probably
  1185. # due to YouTube measures against IP ranges of hosting providers.
  1186. # Working around by preferring the first succeeded video_info containing
  1187. # the token if no such video_info yet was found.
  1188. if 'token' not in video_info:
  1189. video_info = get_video_info
  1190. break
  1191. if 'token' not in video_info:
  1192. if 'reason' in video_info:
  1193. if 'The uploader has not made this video available in your country.' in video_info['reason']:
  1194. regions_allowed = self._html_search_meta('regionsAllowed', video_webpage, default=None)
  1195. if regions_allowed:
  1196. raise ExtractorError('YouTube said: This video is available in %s only' % (
  1197. ', '.join(map(ISO3166Utils.short2full, regions_allowed.split(',')))),
  1198. expected=True)
  1199. raise ExtractorError(
  1200. 'YouTube said: %s' % video_info['reason'][0],
  1201. expected=True, video_id=video_id)
  1202. else:
  1203. raise ExtractorError(
  1204. '"token" parameter not in video info for unknown reason',
  1205. video_id=video_id)
  1206. # title
  1207. if 'title' in video_info:
  1208. video_title = video_info['title'][0]
  1209. else:
  1210. self._downloader.report_warning('Unable to extract video title')
  1211. video_title = '_'
  1212. # description
  1213. video_description = get_element_by_id("eow-description", video_webpage)
  1214. if video_description:
  1215. video_description = re.sub(r'''(?x)
  1216. <a\s+
  1217. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  1218. (?:title|href)="([^"]+)"\s+
  1219. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  1220. class="(?:yt-uix-redirect-link|yt-uix-sessionlink[^"]*)"[^>]*>
  1221. [^<]+\.{3}\s*
  1222. </a>
  1223. ''', r'\1', video_description)
  1224. video_description = clean_html(video_description)
  1225. else:
  1226. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  1227. if fd_mobj:
  1228. video_description = unescapeHTML(fd_mobj.group(1))
  1229. else:
  1230. video_description = ''
  1231. if 'multifeed_metadata_list' in video_info and not smuggled_data.get('force_singlefeed', False):
  1232. if not self._downloader.params.get('noplaylist'):
  1233. entries = []
  1234. feed_ids = []
  1235. multifeed_metadata_list = video_info['multifeed_metadata_list'][0]
  1236. for feed in multifeed_metadata_list.split(','):
  1237. # Unquote should take place before split on comma (,) since textual
  1238. # fields may contain comma as well (see
  1239. # https://github.com/rg3/youtube-dl/issues/8536)
  1240. feed_data = compat_parse_qs(compat_urllib_parse_unquote_plus(feed))
  1241. entries.append({
  1242. '_type': 'url_transparent',
  1243. 'ie_key': 'Youtube',
  1244. 'url': smuggle_url(
  1245. '%s://www.youtube.com/watch?v=%s' % (proto, feed_data['id'][0]),
  1246. {'force_singlefeed': True}),
  1247. 'title': '%s (%s)' % (video_title, feed_data['title'][0]),
  1248. })
  1249. feed_ids.append(feed_data['id'][0])
  1250. self.to_screen(
  1251. 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
  1252. % (', '.join(feed_ids), video_id))
  1253. return self.playlist_result(entries, video_id, video_title, video_description)
  1254. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1255. if 'view_count' in video_info:
  1256. view_count = int(video_info['view_count'][0])
  1257. else:
  1258. view_count = None
  1259. # Check for "rental" videos
  1260. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  1261. raise ExtractorError('"rental" videos not supported')
  1262. # Start extracting information
  1263. self.report_information_extraction(video_id)
  1264. # uploader
  1265. if 'author' not in video_info:
  1266. raise ExtractorError('Unable to extract uploader name')
  1267. video_uploader = compat_urllib_parse_unquote_plus(video_info['author'][0])
  1268. # uploader_id
  1269. video_uploader_id = None
  1270. video_uploader_url = None
  1271. mobj = re.search(
  1272. r'<link itemprop="url" href="(?P<uploader_url>https?://www.youtube.com/(?:user|channel)/(?P<uploader_id>[^"]+))">',
  1273. video_webpage)
  1274. if mobj is not None:
  1275. video_uploader_id = mobj.group('uploader_id')
  1276. video_uploader_url = mobj.group('uploader_url')
  1277. else:
  1278. self._downloader.report_warning('unable to extract uploader nickname')
  1279. # thumbnail image
  1280. # We try first to get a high quality image:
  1281. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  1282. video_webpage, re.DOTALL)
  1283. if m_thumb is not None:
  1284. video_thumbnail = m_thumb.group(1)
  1285. elif 'thumbnail_url' not in video_info:
  1286. self._downloader.report_warning('unable to extract video thumbnail')
  1287. video_thumbnail = None
  1288. else: # don't panic if we can't find it
  1289. video_thumbnail = compat_urllib_parse_unquote_plus(video_info['thumbnail_url'][0])
  1290. # upload date
  1291. upload_date = self._html_search_meta(
  1292. 'datePublished', video_webpage, 'upload date', default=None)
  1293. if not upload_date:
  1294. upload_date = self._search_regex(
  1295. [r'(?s)id="eow-date.*?>(.*?)</span>',
  1296. r'id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live|Started) on (.+?)</strong>'],
  1297. video_webpage, 'upload date', default=None)
  1298. if upload_date:
  1299. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  1300. upload_date = unified_strdate(upload_date)
  1301. video_license = self._html_search_regex(
  1302. r'<h4[^>]+class="title"[^>]*>\s*License\s*</h4>\s*<ul[^>]*>\s*<li>(.+?)</li',
  1303. video_webpage, 'license', default=None)
  1304. m_music = re.search(
  1305. r'<h4[^>]+class="title"[^>]*>\s*Music\s*</h4>\s*<ul[^>]*>\s*<li>(?P<title>.+?) by (?P<creator>.+?)(?:\(.+?\))?</li',
  1306. video_webpage)
  1307. if m_music:
  1308. video_alt_title = remove_quotes(unescapeHTML(m_music.group('title')))
  1309. video_creator = clean_html(m_music.group('creator'))
  1310. else:
  1311. video_alt_title = video_creator = None
  1312. m_cat_container = self._search_regex(
  1313. r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>',
  1314. video_webpage, 'categories', default=None)
  1315. if m_cat_container:
  1316. category = self._html_search_regex(
  1317. r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
  1318. default=None)
  1319. video_categories = None if category is None else [category]
  1320. else:
  1321. video_categories = None
  1322. video_tags = [
  1323. unescapeHTML(m.group('content'))
  1324. for m in re.finditer(self._meta_regex('og:video:tag'), video_webpage)]
  1325. def _extract_count(count_name):
  1326. return str_to_int(self._search_regex(
  1327. r'-%s-button[^>]+><span[^>]+class="yt-uix-button-content"[^>]*>([\d,]+)</span>'
  1328. % re.escape(count_name),
  1329. video_webpage, count_name, default=None))
  1330. like_count = _extract_count('like')
  1331. dislike_count = _extract_count('dislike')
  1332. # subtitles
  1333. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  1334. automatic_captions = self.extract_automatic_captions(video_id, video_webpage)
  1335. if 'length_seconds' not in video_info:
  1336. self._downloader.report_warning('unable to extract video duration')
  1337. video_duration = None
  1338. else:
  1339. video_duration = int(compat_urllib_parse_unquote_plus(video_info['length_seconds'][0]))
  1340. # annotations
  1341. video_annotations = None
  1342. if self._downloader.params.get('writeannotations', False):
  1343. video_annotations = self._extract_annotations(video_id)
  1344. def _map_to_format_list(urlmap):
  1345. formats = []
  1346. for itag, video_real_url in urlmap.items():
  1347. dct = {
  1348. 'format_id': itag,
  1349. 'url': video_real_url,
  1350. 'player_url': player_url,
  1351. }
  1352. if itag in self._formats:
  1353. dct.update(self._formats[itag])
  1354. formats.append(dct)
  1355. return formats
  1356. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1357. self.report_rtmp_download()
  1358. formats = [{
  1359. 'format_id': '_rtmp',
  1360. 'protocol': 'rtmp',
  1361. 'url': video_info['conn'][0],
  1362. 'player_url': player_url,
  1363. }]
  1364. elif len(video_info.get('url_encoded_fmt_stream_map', [''])[0]) >= 1 or len(video_info.get('adaptive_fmts', [''])[0]) >= 1:
  1365. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts', [''])[0]
  1366. if 'rtmpe%3Dyes' in encoded_url_map:
  1367. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  1368. formats_spec = {}
  1369. fmt_list = video_info.get('fmt_list', [''])[0]
  1370. if fmt_list:
  1371. for fmt in fmt_list.split(','):
  1372. spec = fmt.split('/')
  1373. if len(spec) > 1:
  1374. width_height = spec[1].split('x')
  1375. if len(width_height) == 2:
  1376. formats_spec[spec[0]] = {
  1377. 'resolution': spec[1],
  1378. 'width': int_or_none(width_height[0]),
  1379. 'height': int_or_none(width_height[1]),
  1380. }
  1381. formats = []
  1382. for url_data_str in encoded_url_map.split(','):
  1383. url_data = compat_parse_qs(url_data_str)
  1384. if 'itag' not in url_data or 'url' not in url_data:
  1385. continue
  1386. format_id = url_data['itag'][0]
  1387. url = url_data['url'][0]
  1388. if 'sig' in url_data:
  1389. url += '&signature=' + url_data['sig'][0]
  1390. elif 's' in url_data:
  1391. encrypted_sig = url_data['s'][0]
  1392. ASSETS_RE = r'"assets":.+?"js":\s*("[^"]+")'
  1393. jsplayer_url_json = self._search_regex(
  1394. ASSETS_RE,
  1395. embed_webpage if age_gate else video_webpage,
  1396. 'JS player URL (1)', default=None)
  1397. if not jsplayer_url_json and not age_gate:
  1398. # We need the embed website after all
  1399. if embed_webpage is None:
  1400. embed_url = proto + '://www.youtube.com/embed/%s' % video_id
  1401. embed_webpage = self._download_webpage(
  1402. embed_url, video_id, 'Downloading embed webpage')
  1403. jsplayer_url_json = self._search_regex(
  1404. ASSETS_RE, embed_webpage, 'JS player URL')
  1405. player_url = json.loads(jsplayer_url_json)
  1406. if player_url is None:
  1407. player_url_json = self._search_regex(
  1408. r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
  1409. video_webpage, 'age gate player URL')
  1410. player_url = json.loads(player_url_json)
  1411. if self._downloader.params.get('verbose'):
  1412. if player_url is None:
  1413. player_version = 'unknown'
  1414. player_desc = 'unknown'
  1415. else:
  1416. if player_url.endswith('swf'):
  1417. player_version = self._search_regex(
  1418. r'-(.+?)(?:/watch_as3)?\.swf$', player_url,
  1419. 'flash player', fatal=False)
  1420. player_desc = 'flash player %s' % player_version
  1421. else:
  1422. player_version = self._search_regex(
  1423. [r'html5player-([^/]+?)(?:/html5player(?:-new)?)?\.js', r'(?:www|player)-([^/]+)/base\.js'],
  1424. player_url,
  1425. 'html5 player', fatal=False)
  1426. player_desc = 'html5 player %s' % player_version
  1427. parts_sizes = self._signature_cache_id(encrypted_sig)
  1428. self.to_screen('{%s} signature length %s, %s' %
  1429. (format_id, parts_sizes, player_desc))
  1430. signature = self._decrypt_signature(
  1431. encrypted_sig, video_id, player_url, age_gate)
  1432. url += '&signature=' + signature
  1433. if 'ratebypass' not in url:
  1434. url += '&ratebypass=yes'
  1435. dct = {
  1436. 'format_id': format_id,
  1437. 'url': url,
  1438. 'player_url': player_url,
  1439. }
  1440. if format_id in self._formats:
  1441. dct.update(self._formats[format_id])
  1442. if format_id in formats_spec:
  1443. dct.update(formats_spec[format_id])
  1444. # Some itags are not included in DASH manifest thus corresponding formats will
  1445. # lack metadata (see https://github.com/rg3/youtube-dl/pull/5993).
  1446. # Trying to extract metadata from url_encoded_fmt_stream_map entry.
  1447. mobj = re.search(r'^(?P<width>\d+)[xX](?P<height>\d+)$', url_data.get('size', [''])[0])
  1448. width, height = (int(mobj.group('width')), int(mobj.group('height'))) if mobj else (None, None)
  1449. more_fields = {
  1450. 'filesize': int_or_none(url_data.get('clen', [None])[0]),
  1451. 'tbr': float_or_none(url_data.get('bitrate', [None])[0], 1000),
  1452. 'width': width,
  1453. 'height': height,
  1454. 'fps': int_or_none(url_data.get('fps', [None])[0]),
  1455. 'format_note': url_data.get('quality_label', [None])[0] or url_data.get('quality', [None])[0],
  1456. }
  1457. for key, value in more_fields.items():
  1458. if value:
  1459. dct[key] = value
  1460. type_ = url_data.get('type', [None])[0]
  1461. if type_:
  1462. type_split = type_.split(';')
  1463. kind_ext = type_split[0].split('/')
  1464. if len(kind_ext) == 2:
  1465. kind, _ = kind_ext
  1466. dct['ext'] = mimetype2ext(type_split[0])
  1467. if kind in ('audio', 'video'):
  1468. codecs = None
  1469. for mobj in re.finditer(
  1470. r'(?P<key>[a-zA-Z_-]+)=(?P<quote>["\']?)(?P<val>.+?)(?P=quote)(?:;|$)', type_):
  1471. if mobj.group('key') == 'codecs':
  1472. codecs = mobj.group('val')
  1473. break
  1474. if codecs:
  1475. codecs = codecs.split(',')
  1476. if len(codecs) == 2:
  1477. acodec, vcodec = codecs[1], codecs[0]
  1478. else:
  1479. acodec, vcodec = (codecs[0], 'none') if kind == 'audio' else ('none', codecs[0])
  1480. dct.update({
  1481. 'acodec': acodec,
  1482. 'vcodec': vcodec,
  1483. })
  1484. formats.append(dct)
  1485. elif video_info.get('hlsvp'):
  1486. manifest_url = video_info['hlsvp'][0]
  1487. url_map = self._extract_from_m3u8(manifest_url, video_id)
  1488. formats = _map_to_format_list(url_map)
  1489. # Accept-Encoding header causes failures in live streams on Youtube and Youtube Gaming
  1490. for a_format in formats:
  1491. a_format.setdefault('http_headers', {})['Youtubedl-no-compression'] = 'True'
  1492. else:
  1493. unavailable_message = self._html_search_regex(
  1494. r'(?s)<h1[^>]+id="unavailable-message"[^>]*>(.+?)</h1>',
  1495. video_webpage, 'unavailable message', default=None)
  1496. if unavailable_message:
  1497. raise ExtractorError(unavailable_message, expected=True)
  1498. raise ExtractorError('no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
  1499. # Look for the DASH manifest
  1500. if self._downloader.params.get('youtube_include_dash_manifest', True):
  1501. dash_mpd_fatal = True
  1502. for mpd_url in dash_mpds:
  1503. dash_formats = {}
  1504. try:
  1505. def decrypt_sig(mobj):
  1506. s = mobj.group(1)
  1507. dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
  1508. return '/signature/%s' % dec_s
  1509. mpd_url = re.sub(r'/s/([a-fA-F0-9\.]+)', decrypt_sig, mpd_url)
  1510. for df in self._extract_mpd_formats(
  1511. mpd_url, video_id, fatal=dash_mpd_fatal,
  1512. formats_dict=self._formats):
  1513. # Do not overwrite DASH format found in some previous DASH manifest
  1514. if df['format_id'] not in dash_formats:
  1515. dash_formats[df['format_id']] = df
  1516. # Additional DASH manifests may end up in HTTP Error 403 therefore
  1517. # allow them to fail without bug report message if we already have
  1518. # some DASH manifest succeeded. This is temporary workaround to reduce
  1519. # burst of bug reports until we figure out the reason and whether it
  1520. # can be fixed at all.
  1521. dash_mpd_fatal = False
  1522. except (ExtractorError, KeyError) as e:
  1523. self.report_warning(
  1524. 'Skipping DASH manifest: %r' % e, video_id)
  1525. if dash_formats:
  1526. # Remove the formats we found through non-DASH, they
  1527. # contain less info and it can be wrong, because we use
  1528. # fixed values (for example the resolution). See
  1529. # https://github.com/rg3/youtube-dl/issues/5774 for an
  1530. # example.
  1531. formats = [f for f in formats if f['format_id'] not in dash_formats.keys()]
  1532. formats.extend(dash_formats.values())
  1533. # Check for malformed aspect ratio
  1534. stretched_m = re.search(
  1535. r'<meta\s+property="og:video:tag".*?content="yt:stretch=(?P<w>[0-9]+):(?P<h>[0-9]+)">',
  1536. video_webpage)
  1537. if stretched_m:
  1538. w = float(stretched_m.group('w'))
  1539. h = float(stretched_m.group('h'))
  1540. # yt:stretch may hold invalid ratio data (e.g. for Q39EVAstoRM ratio is 17:0).
  1541. # We will only process correct ratios.
  1542. if w > 0 and h > 0:
  1543. ratio = w / h
  1544. for f in formats:
  1545. if f.get('vcodec') != 'none':
  1546. f['stretched_ratio'] = ratio
  1547. self._sort_formats(formats)
  1548. self.mark_watched(video_id, video_info)
  1549. return {
  1550. 'id': video_id,
  1551. 'uploader': video_uploader,
  1552. 'uploader_id': video_uploader_id,
  1553. 'uploader_url': video_uploader_url,
  1554. 'upload_date': upload_date,
  1555. 'license': video_license,
  1556. 'creator': video_creator,
  1557. 'title': video_title,
  1558. 'alt_title': video_alt_title,
  1559. 'thumbnail': video_thumbnail,
  1560. 'description': video_description,
  1561. 'categories': video_categories,
  1562. 'tags': video_tags,
  1563. 'subtitles': video_subtitles,
  1564. 'automatic_captions': automatic_captions,
  1565. 'duration': video_duration,
  1566. 'age_limit': 18 if age_gate else 0,
  1567. 'annotations': video_annotations,
  1568. 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
  1569. 'view_count': view_count,
  1570. 'like_count': like_count,
  1571. 'dislike_count': dislike_count,
  1572. 'average_rating': float_or_none(video_info.get('avg_rating', [None])[0]),
  1573. 'formats': formats,
  1574. 'is_live': is_live,
  1575. 'start_time': start_time,
  1576. 'end_time': end_time,
  1577. }
  1578. class YoutubePlaylistIE(YoutubePlaylistBaseInfoExtractor):
  1579. IE_DESC = 'YouTube.com playlists'
  1580. _VALID_URL = r"""(?x)(?:
  1581. (?:https?://)?
  1582. (?:\w+\.)?
  1583. youtube\.com/
  1584. (?:
  1585. (?:course|view_play_list|my_playlists|artist|playlist|watch|embed/videoseries)
  1586. \? (?:.*?[&;])*? (?:p|a|list)=
  1587. | p/
  1588. )
  1589. (
  1590. (?:PL|LL|EC|UU|FL|RD|UL)?[0-9A-Za-z-_]{10,}
  1591. # Top tracks, they can also include dots
  1592. |(?:MC)[\w\.]*
  1593. )
  1594. .*
  1595. |
  1596. ((?:PL|LL|EC|UU|FL|RD|UL)[0-9A-Za-z-_]{10,})
  1597. )"""
  1598. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
  1599. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)(?:[^>]+>(?P<title>[^<]+))?'
  1600. IE_NAME = 'youtube:playlist'
  1601. _TESTS = [{
  1602. 'url': 'https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  1603. 'info_dict': {
  1604. 'title': 'ytdl test PL',
  1605. 'id': 'PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  1606. },
  1607. 'playlist_count': 3,
  1608. }, {
  1609. 'url': 'https://www.youtube.com/playlist?list=PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  1610. 'info_dict': {
  1611. 'id': 'PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  1612. 'title': 'YDL_Empty_List',
  1613. },
  1614. 'playlist_count': 0,
  1615. }, {
  1616. 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
  1617. 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  1618. 'info_dict': {
  1619. 'title': '29C3: Not my department',
  1620. 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  1621. },
  1622. 'playlist_count': 95,
  1623. }, {
  1624. 'note': 'issue #673',
  1625. 'url': 'PLBB231211A4F62143',
  1626. 'info_dict': {
  1627. 'title': '[OLD]Team Fortress 2 (Class-based LP)',
  1628. 'id': 'PLBB231211A4F62143',
  1629. },
  1630. 'playlist_mincount': 26,
  1631. }, {
  1632. 'note': 'Large playlist',
  1633. 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
  1634. 'info_dict': {
  1635. 'title': 'Uploads from Cauchemar',
  1636. 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
  1637. },
  1638. 'playlist_mincount': 799,
  1639. }, {
  1640. 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  1641. 'info_dict': {
  1642. 'title': 'YDL_safe_search',
  1643. 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  1644. },
  1645. 'playlist_count': 2,
  1646. }, {
  1647. 'note': 'embedded',
  1648. 'url': 'http://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  1649. 'playlist_count': 4,
  1650. 'info_dict': {
  1651. 'title': 'JODA15',
  1652. 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  1653. }
  1654. }, {
  1655. 'note': 'Embedded SWF player',
  1656. 'url': 'http://www.youtube.com/p/YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ?hl=en_US&fs=1&rel=0',
  1657. 'playlist_count': 4,
  1658. 'info_dict': {
  1659. 'title': 'JODA7',
  1660. 'id': 'YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ',
  1661. }
  1662. }, {
  1663. 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
  1664. 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
  1665. 'info_dict': {
  1666. 'title': 'Uploads from Interstellar Movie',
  1667. 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
  1668. },
  1669. 'playlist_mincout': 21,
  1670. }]
  1671. def _real_initialize(self):
  1672. self._login()
  1673. def _extract_mix(self, playlist_id):
  1674. # The mixes are generated from a single video
  1675. # the id of the playlist is just 'RD' + video_id
  1676. url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
  1677. webpage = self._download_webpage(
  1678. url, playlist_id, 'Downloading Youtube mix')
  1679. search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
  1680. title_span = (
  1681. search_title('playlist-title') or
  1682. search_title('title long-title') or
  1683. search_title('title'))
  1684. title = clean_html(title_span)
  1685. ids = orderedSet(re.findall(
  1686. r'''(?xs)data-video-username=".*?".*?
  1687. href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id),
  1688. webpage))
  1689. url_results = self._ids_to_results(ids)
  1690. return self.playlist_result(url_results, playlist_id, title)
  1691. def _extract_playlist(self, playlist_id):
  1692. url = self._TEMPLATE_URL % playlist_id
  1693. page = self._download_webpage(url, playlist_id)
  1694. for match in re.findall(r'<div class="yt-alert-message">([^<]+)</div>', page):
  1695. match = match.strip()
  1696. # Check if the playlist exists or is private
  1697. if re.match(r'[^<]*(The|This) playlist (does not exist|is private)[^<]*', match):
  1698. raise ExtractorError(
  1699. 'The playlist doesn\'t exist or is private, use --username or '
  1700. '--netrc to access it.',
  1701. expected=True)
  1702. elif re.match(r'[^<]*Invalid parameters[^<]*', match):
  1703. raise ExtractorError(
  1704. 'Invalid parameters. Maybe URL is incorrect.',
  1705. expected=True)
  1706. elif re.match(r'[^<]*Choose your language[^<]*', match):
  1707. continue
  1708. else:
  1709. self.report_warning('Youtube gives an alert message: ' + match)
  1710. playlist_title = self._html_search_regex(
  1711. r'(?s)<h1 class="pl-header-title[^"]*"[^>]*>\s*(.*?)\s*</h1>',
  1712. page, 'title')
  1713. return self.playlist_result(self._entries(page, playlist_id), playlist_id, playlist_title)
  1714. def _check_download_just_video(self, url, playlist_id):
  1715. # Check if it's a video-specific URL
  1716. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  1717. if 'v' in query_dict:
  1718. video_id = query_dict['v'][0]
  1719. if self._downloader.params.get('noplaylist'):
  1720. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1721. return self.url_result(video_id, 'Youtube', video_id=video_id)
  1722. else:
  1723. self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  1724. def _real_extract(self, url):
  1725. # Extract playlist id
  1726. mobj = re.match(self._VALID_URL, url)
  1727. if mobj is None:
  1728. raise ExtractorError('Invalid URL: %s' % url)
  1729. playlist_id = mobj.group(1) or mobj.group(2)
  1730. video = self._check_download_just_video(url, playlist_id)
  1731. if video:
  1732. return video
  1733. if playlist_id.startswith('RD') or playlist_id.startswith('UL'):
  1734. # Mixes require a custom extraction process
  1735. return self._extract_mix(playlist_id)
  1736. return self._extract_playlist(playlist_id)
  1737. class YoutubeChannelIE(YoutubePlaylistBaseInfoExtractor):
  1738. IE_DESC = 'YouTube.com channels'
  1739. _VALID_URL = r'https?://(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/(?P<id>[0-9A-Za-z_-]+)'
  1740. _TEMPLATE_URL = 'https://www.youtube.com/channel/%s/videos'
  1741. _VIDEO_RE = r'(?:title="(?P<title>[^"]+)"[^>]+)?href="/watch\?v=(?P<id>[0-9A-Za-z_-]+)&?'
  1742. IE_NAME = 'youtube:channel'
  1743. _TESTS = [{
  1744. 'note': 'paginated channel',
  1745. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
  1746. 'playlist_mincount': 91,
  1747. 'info_dict': {
  1748. 'id': 'UUKfVa3S1e4PHvxWcwyMMg8w',
  1749. 'title': 'Uploads from lex will',
  1750. }
  1751. }, {
  1752. 'note': 'Age restricted channel',
  1753. # from https://www.youtube.com/user/DeusExOfficial
  1754. 'url': 'https://www.youtube.com/channel/UCs0ifCMCm1icqRbqhUINa0w',
  1755. 'playlist_mincount': 64,
  1756. 'info_dict': {
  1757. 'id': 'UUs0ifCMCm1icqRbqhUINa0w',
  1758. 'title': 'Uploads from Deus Ex',
  1759. },
  1760. }]
  1761. @classmethod
  1762. def suitable(cls, url):
  1763. return False if YoutubePlaylistsIE.suitable(url) else super(YoutubeChannelIE, cls).suitable(url)
  1764. def _real_extract(self, url):
  1765. channel_id = self._match_id(url)
  1766. url = self._TEMPLATE_URL % channel_id
  1767. # Channel by page listing is restricted to 35 pages of 30 items, i.e. 1050 videos total (see #5778)
  1768. # Workaround by extracting as a playlist if managed to obtain channel playlist URL
  1769. # otherwise fallback on channel by page extraction
  1770. channel_page = self._download_webpage(
  1771. url + '?view=57', channel_id,
  1772. 'Downloading channel page', fatal=False)
  1773. if channel_page is False:
  1774. channel_playlist_id = False
  1775. else:
  1776. channel_playlist_id = self._html_search_meta(
  1777. 'channelId', channel_page, 'channel id', default=None)
  1778. if not channel_playlist_id:
  1779. channel_playlist_id = self._search_regex(
  1780. r'data-(?:channel-external-|yt)id="([^"]+)"',
  1781. channel_page, 'channel id', default=None)
  1782. if channel_playlist_id and channel_playlist_id.startswith('UC'):
  1783. playlist_id = 'UU' + channel_playlist_id[2:]
  1784. return self.url_result(
  1785. compat_urlparse.urljoin(url, '/playlist?list=%s' % playlist_id), 'YoutubePlaylist')
  1786. channel_page = self._download_webpage(url, channel_id, 'Downloading page #1')
  1787. autogenerated = re.search(r'''(?x)
  1788. class="[^"]*?(?:
  1789. channel-header-autogenerated-label|
  1790. yt-channel-title-autogenerated
  1791. )[^"]*"''', channel_page) is not None
  1792. if autogenerated:
  1793. # The videos are contained in a single page
  1794. # the ajax pages can't be used, they are empty
  1795. entries = [
  1796. self.url_result(
  1797. video_id, 'Youtube', video_id=video_id,
  1798. video_title=video_title)
  1799. for video_id, video_title in self.extract_videos_from_page(channel_page)]
  1800. return self.playlist_result(entries, channel_id)
  1801. return self.playlist_result(self._entries(channel_page, channel_id), channel_id)
  1802. class YoutubeUserIE(YoutubeChannelIE):
  1803. IE_DESC = 'YouTube.com user videos (URL or "ytuser" keyword)'
  1804. _VALID_URL = r'(?:(?:https?://(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch|results)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)(?P<id>[A-Za-z0-9_-]+)'
  1805. _TEMPLATE_URL = 'https://www.youtube.com/user/%s/videos'
  1806. IE_NAME = 'youtube:user'
  1807. _TESTS = [{
  1808. 'url': 'https://www.youtube.com/user/TheLinuxFoundation',
  1809. 'playlist_mincount': 320,
  1810. 'info_dict': {
  1811. 'title': 'TheLinuxFoundation',
  1812. }
  1813. }, {
  1814. 'url': 'ytuser:phihag',
  1815. 'only_matching': True,
  1816. }]
  1817. @classmethod
  1818. def suitable(cls, url):
  1819. # Don't return True if the url can be extracted with other youtube
  1820. # extractor, the regex would is too permissive and it would match.
  1821. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  1822. if any(ie.suitable(url) for ie in other_ies):
  1823. return False
  1824. else:
  1825. return super(YoutubeUserIE, cls).suitable(url)
  1826. class YoutubePlaylistsIE(YoutubePlaylistsBaseInfoExtractor):
  1827. IE_DESC = 'YouTube.com user/channel playlists'
  1828. _VALID_URL = r'https?://(?:\w+\.)?youtube\.com/(?:user|channel)/(?P<id>[^/]+)/playlists'
  1829. IE_NAME = 'youtube:playlists'
  1830. _TESTS = [{
  1831. 'url': 'http://www.youtube.com/user/ThirstForScience/playlists',
  1832. 'playlist_mincount': 4,
  1833. 'info_dict': {
  1834. 'id': 'ThirstForScience',
  1835. 'title': 'Thirst for Science',
  1836. },
  1837. }, {
  1838. # with "Load more" button
  1839. 'url': 'http://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
  1840. 'playlist_mincount': 70,
  1841. 'info_dict': {
  1842. 'id': 'igorkle1',
  1843. 'title': 'Игорь Клейнер',
  1844. },
  1845. }, {
  1846. 'url': 'https://www.youtube.com/channel/UCiU1dHvZObB2iP6xkJ__Icw/playlists',
  1847. 'playlist_mincount': 17,
  1848. 'info_dict': {
  1849. 'id': 'UCiU1dHvZObB2iP6xkJ__Icw',
  1850. 'title': 'Chem Player',
  1851. },
  1852. }]
  1853. class YoutubeSearchIE(SearchInfoExtractor, YoutubePlaylistIE):
  1854. IE_DESC = 'YouTube.com searches'
  1855. # there doesn't appear to be a real limit, for example if you search for
  1856. # 'python' you get more than 8.000.000 results
  1857. _MAX_RESULTS = float('inf')
  1858. IE_NAME = 'youtube:search'
  1859. _SEARCH_KEY = 'ytsearch'
  1860. _EXTRA_QUERY_ARGS = {}
  1861. _TESTS = []
  1862. def _get_n_results(self, query, n):
  1863. """Get a specified number of results for a query"""
  1864. videos = []
  1865. limit = n
  1866. for pagenum in itertools.count(1):
  1867. url_query = {
  1868. 'search_query': query.encode('utf-8'),
  1869. 'page': pagenum,
  1870. 'spf': 'navigate',
  1871. }
  1872. url_query.update(self._EXTRA_QUERY_ARGS)
  1873. result_url = 'https://www.youtube.com/results?' + compat_urllib_parse.urlencode(url_query)
  1874. data = self._download_json(
  1875. result_url, video_id='query "%s"' % query,
  1876. note='Downloading page %s' % pagenum,
  1877. errnote='Unable to download API page')
  1878. html_content = data[1]['body']['content']
  1879. if 'class="search-message' in html_content:
  1880. raise ExtractorError(
  1881. '[youtube] No video results', expected=True)
  1882. new_videos = self._ids_to_results(orderedSet(re.findall(
  1883. r'href="/watch\?v=(.{11})', html_content)))
  1884. videos += new_videos
  1885. if not new_videos or len(videos) > limit:
  1886. break
  1887. if len(videos) > n:
  1888. videos = videos[:n]
  1889. return self.playlist_result(videos, query)
  1890. class YoutubeSearchDateIE(YoutubeSearchIE):
  1891. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  1892. _SEARCH_KEY = 'ytsearchdate'
  1893. IE_DESC = 'YouTube.com searches, newest videos first'
  1894. _EXTRA_QUERY_ARGS = {'search_sort': 'video_date_uploaded'}
  1895. class YoutubeSearchURLIE(InfoExtractor):
  1896. IE_DESC = 'YouTube.com search URLs'
  1897. IE_NAME = 'youtube:search_url'
  1898. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?P<query>[^&]+)(?:[&]|$)'
  1899. _TESTS = [{
  1900. 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
  1901. 'playlist_mincount': 5,
  1902. 'info_dict': {
  1903. 'title': 'youtube-dl test video',
  1904. }
  1905. }, {
  1906. 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
  1907. 'only_matching': True,
  1908. }]
  1909. def _real_extract(self, url):
  1910. mobj = re.match(self._VALID_URL, url)
  1911. query = compat_urllib_parse_unquote_plus(mobj.group('query'))
  1912. webpage = self._download_webpage(url, query)
  1913. result_code = self._search_regex(
  1914. r'(?s)<ol[^>]+class="item-section"(.*?)</ol>', webpage, 'result HTML')
  1915. part_codes = re.findall(
  1916. r'(?s)<h3[^>]+class="[^"]*yt-lockup-title[^"]*"[^>]*>(.*?)</h3>', result_code)
  1917. entries = []
  1918. for part_code in part_codes:
  1919. part_title = self._html_search_regex(
  1920. [r'(?s)title="([^"]+)"', r'>([^<]+)</a>'], part_code, 'item title', fatal=False)
  1921. part_url_snippet = self._html_search_regex(
  1922. r'(?s)href="([^"]+)"', part_code, 'item URL')
  1923. part_url = compat_urlparse.urljoin(
  1924. 'https://www.youtube.com/', part_url_snippet)
  1925. entries.append({
  1926. '_type': 'url',
  1927. 'url': part_url,
  1928. 'title': part_title,
  1929. })
  1930. return {
  1931. '_type': 'playlist',
  1932. 'entries': entries,
  1933. 'title': query,
  1934. }
  1935. class YoutubeShowIE(YoutubePlaylistsBaseInfoExtractor):
  1936. IE_DESC = 'YouTube.com (multi-season) shows'
  1937. _VALID_URL = r'https?://www\.youtube\.com/show/(?P<id>[^?#]*)'
  1938. IE_NAME = 'youtube:show'
  1939. _TESTS = [{
  1940. 'url': 'https://www.youtube.com/show/airdisasters',
  1941. 'playlist_mincount': 5,
  1942. 'info_dict': {
  1943. 'id': 'airdisasters',
  1944. 'title': 'Air Disasters',
  1945. }
  1946. }]
  1947. def _real_extract(self, url):
  1948. playlist_id = self._match_id(url)
  1949. return super(YoutubeShowIE, self)._real_extract(
  1950. 'https://www.youtube.com/show/%s/playlists' % playlist_id)
  1951. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  1952. """
  1953. Base class for feed extractors
  1954. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  1955. """
  1956. _LOGIN_REQUIRED = True
  1957. @property
  1958. def IE_NAME(self):
  1959. return 'youtube:%s' % self._FEED_NAME
  1960. def _real_initialize(self):
  1961. self._login()
  1962. def _real_extract(self, url):
  1963. page = self._download_webpage(
  1964. 'https://www.youtube.com/feed/%s' % self._FEED_NAME, self._PLAYLIST_TITLE)
  1965. # The extraction process is the same as for playlists, but the regex
  1966. # for the video ids doesn't contain an index
  1967. ids = []
  1968. more_widget_html = content_html = page
  1969. for page_num in itertools.count(1):
  1970. matches = re.findall(r'href="\s*/watch\?v=([0-9A-Za-z_-]{11})', content_html)
  1971. # 'recommended' feed has infinite 'load more' and each new portion spins
  1972. # the same videos in (sometimes) slightly different order, so we'll check
  1973. # for unicity and break when portion has no new videos
  1974. new_ids = filter(lambda video_id: video_id not in ids, orderedSet(matches))
  1975. if not new_ids:
  1976. break
  1977. ids.extend(new_ids)
  1978. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  1979. if not mobj:
  1980. break
  1981. more = self._download_json(
  1982. 'https://youtube.com/%s' % mobj.group('more'), self._PLAYLIST_TITLE,
  1983. 'Downloading page #%s' % page_num,
  1984. transform_source=uppercase_escape)
  1985. content_html = more['content_html']
  1986. more_widget_html = more['load_more_widget_html']
  1987. return self.playlist_result(
  1988. self._ids_to_results(ids), playlist_title=self._PLAYLIST_TITLE)
  1989. class YoutubeWatchLaterIE(YoutubePlaylistIE):
  1990. IE_NAME = 'youtube:watchlater'
  1991. IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
  1992. _VALID_URL = r'https?://www\.youtube\.com/(?:feed/watch_later|(?:playlist|watch)\?(?:.+&)?list=WL)|:ytwatchlater'
  1993. _TESTS = [{
  1994. 'url': 'https://www.youtube.com/playlist?list=WL',
  1995. 'only_matching': True,
  1996. }, {
  1997. 'url': 'https://www.youtube.com/watch?v=bCNU9TrbiRk&index=1&list=WL',
  1998. 'only_matching': True,
  1999. }]
  2000. def _real_extract(self, url):
  2001. video = self._check_download_just_video(url, 'WL')
  2002. if video:
  2003. return video
  2004. return self._extract_playlist('WL')
  2005. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  2006. IE_NAME = 'youtube:favorites'
  2007. IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
  2008. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  2009. _LOGIN_REQUIRED = True
  2010. def _real_extract(self, url):
  2011. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  2012. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, 'favourites playlist id')
  2013. return self.url_result(playlist_id, 'YoutubePlaylist')
  2014. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  2015. IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
  2016. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  2017. _FEED_NAME = 'recommended'
  2018. _PLAYLIST_TITLE = 'Youtube Recommended videos'
  2019. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  2020. IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  2021. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  2022. _FEED_NAME = 'subscriptions'
  2023. _PLAYLIST_TITLE = 'Youtube Subscriptions'
  2024. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  2025. IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
  2026. _VALID_URL = 'https?://www\.youtube\.com/feed/history|:ythistory'
  2027. _FEED_NAME = 'history'
  2028. _PLAYLIST_TITLE = 'Youtube History'
  2029. class YoutubeTruncatedURLIE(InfoExtractor):
  2030. IE_NAME = 'youtube:truncated_url'
  2031. IE_DESC = False # Do not list
  2032. _VALID_URL = r'''(?x)
  2033. (?:https?://)?
  2034. (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
  2035. (?:watch\?(?:
  2036. feature=[a-z_]+|
  2037. annotation_id=annotation_[^&]+|
  2038. x-yt-cl=[0-9]+|
  2039. hl=[^&]*|
  2040. t=[0-9]+
  2041. )?
  2042. |
  2043. attribution_link\?a=[^&]+
  2044. )
  2045. $
  2046. '''
  2047. _TESTS = [{
  2048. 'url': 'http://www.youtube.com/watch?annotation_id=annotation_3951667041',
  2049. 'only_matching': True,
  2050. }, {
  2051. 'url': 'http://www.youtube.com/watch?',
  2052. 'only_matching': True,
  2053. }, {
  2054. 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
  2055. 'only_matching': True,
  2056. }, {
  2057. 'url': 'https://www.youtube.com/watch?feature=foo',
  2058. 'only_matching': True,
  2059. }, {
  2060. 'url': 'https://www.youtube.com/watch?hl=en-GB',
  2061. 'only_matching': True,
  2062. }, {
  2063. 'url': 'https://www.youtube.com/watch?t=2372',
  2064. 'only_matching': True,
  2065. }]
  2066. def _real_extract(self, url):
  2067. raise ExtractorError(
  2068. 'Did you forget to quote the URL? Remember that & is a meta '
  2069. 'character in most shells, so you want to put the URL in quotes, '
  2070. 'like youtube-dl '
  2071. '"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  2072. ' or simply youtube-dl BaW_jenozKc .',
  2073. expected=True)
  2074. class YoutubeTruncatedIDIE(InfoExtractor):
  2075. IE_NAME = 'youtube:truncated_id'
  2076. IE_DESC = False # Do not list
  2077. _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
  2078. _TESTS = [{
  2079. 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
  2080. 'only_matching': True,
  2081. }]
  2082. def _real_extract(self, url):
  2083. video_id = self._match_id(url)
  2084. raise ExtractorError(
  2085. 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),
  2086. expected=True)