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.

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