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.

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