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.

2258 lines
101 KiB

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