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.

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