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.

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