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.

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