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.

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