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.

2601 lines
117 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'(["\'])signature\1\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  966. r'\.sig\|\|(?P<sig>[a-zA-Z0-9$]+)\('),
  967. jscode, 'Initial JS player signature function name', group='sig')
  968. jsi = JSInterpreter(jscode)
  969. initial_function = jsi.extract_function(funcname)
  970. return lambda s: initial_function([s])
  971. def _parse_sig_swf(self, file_contents):
  972. swfi = SWFInterpreter(file_contents)
  973. TARGET_CLASSNAME = 'SignatureDecipher'
  974. searched_class = swfi.extract_class(TARGET_CLASSNAME)
  975. initial_function = swfi.extract_function(searched_class, 'decipher')
  976. return lambda s: initial_function([s])
  977. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  978. """Turn the encrypted s field into a working signature"""
  979. if player_url is None:
  980. raise ExtractorError('Cannot decrypt signature without player_url')
  981. if player_url.startswith('//'):
  982. player_url = 'https:' + player_url
  983. elif not re.match(r'https?://', player_url):
  984. player_url = compat_urlparse.urljoin(
  985. 'https://www.youtube.com', player_url)
  986. try:
  987. player_id = (player_url, self._signature_cache_id(s))
  988. if player_id not in self._player_cache:
  989. func = self._extract_signature_function(
  990. video_id, player_url, s
  991. )
  992. self._player_cache[player_id] = func
  993. func = self._player_cache[player_id]
  994. if self._downloader.params.get('youtube_print_sig_code'):
  995. self._print_sig_code(func, s)
  996. return func(s)
  997. except Exception as e:
  998. tb = traceback.format_exc()
  999. raise ExtractorError(
  1000. 'Signature extraction failed: ' + tb, cause=e)
  1001. def _get_subtitles(self, video_id, webpage):
  1002. try:
  1003. subs_doc = self._download_xml(
  1004. 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  1005. video_id, note=False)
  1006. except ExtractorError as err:
  1007. self._downloader.report_warning('unable to download video subtitles: %s' % error_to_compat_str(err))
  1008. return {}
  1009. sub_lang_list = {}
  1010. for track in subs_doc.findall('track'):
  1011. lang = track.attrib['lang_code']
  1012. if lang in sub_lang_list:
  1013. continue
  1014. sub_formats = []
  1015. for ext in self._SUBTITLE_FORMATS:
  1016. params = compat_urllib_parse_urlencode({
  1017. 'lang': lang,
  1018. 'v': video_id,
  1019. 'fmt': ext,
  1020. 'name': track.attrib['name'].encode('utf-8'),
  1021. })
  1022. sub_formats.append({
  1023. 'url': 'https://www.youtube.com/api/timedtext?' + params,
  1024. 'ext': ext,
  1025. })
  1026. sub_lang_list[lang] = sub_formats
  1027. if not sub_lang_list:
  1028. self._downloader.report_warning('video doesn\'t have subtitles')
  1029. return {}
  1030. return sub_lang_list
  1031. def _get_ytplayer_config(self, video_id, webpage):
  1032. patterns = (
  1033. # User data may contain arbitrary character sequences that may affect
  1034. # JSON extraction with regex, e.g. when '};' is contained the second
  1035. # regex won't capture the whole JSON. Yet working around by trying more
  1036. # concrete regex first keeping in mind proper quoted string handling
  1037. # to be implemented in future that will replace this workaround (see
  1038. # https://github.com/rg3/youtube-dl/issues/7468,
  1039. # https://github.com/rg3/youtube-dl/pull/7599)
  1040. r';ytplayer\.config\s*=\s*({.+?});ytplayer',
  1041. r';ytplayer\.config\s*=\s*({.+?});',
  1042. )
  1043. config = self._search_regex(
  1044. patterns, webpage, 'ytplayer.config', default=None)
  1045. if config:
  1046. return self._parse_json(
  1047. uppercase_escape(config), video_id, fatal=False)
  1048. def _get_automatic_captions(self, video_id, webpage):
  1049. """We need the webpage for getting the captions url, pass it as an
  1050. argument to speed up the process."""
  1051. self.to_screen('%s: Looking for automatic captions' % video_id)
  1052. player_config = self._get_ytplayer_config(video_id, webpage)
  1053. err_msg = 'Couldn\'t find automatic captions for %s' % video_id
  1054. if not player_config:
  1055. self._downloader.report_warning(err_msg)
  1056. return {}
  1057. try:
  1058. args = player_config['args']
  1059. caption_url = args.get('ttsurl')
  1060. if caption_url:
  1061. timestamp = args['timestamp']
  1062. # We get the available subtitles
  1063. list_params = compat_urllib_parse_urlencode({
  1064. 'type': 'list',
  1065. 'tlangs': 1,
  1066. 'asrs': 1,
  1067. })
  1068. list_url = caption_url + '&' + list_params
  1069. caption_list = self._download_xml(list_url, video_id)
  1070. original_lang_node = caption_list.find('track')
  1071. if original_lang_node is None:
  1072. self._downloader.report_warning('Video doesn\'t have automatic captions')
  1073. return {}
  1074. original_lang = original_lang_node.attrib['lang_code']
  1075. caption_kind = original_lang_node.attrib.get('kind', '')
  1076. sub_lang_list = {}
  1077. for lang_node in caption_list.findall('target'):
  1078. sub_lang = lang_node.attrib['lang_code']
  1079. sub_formats = []
  1080. for ext in self._SUBTITLE_FORMATS:
  1081. params = compat_urllib_parse_urlencode({
  1082. 'lang': original_lang,
  1083. 'tlang': sub_lang,
  1084. 'fmt': ext,
  1085. 'ts': timestamp,
  1086. 'kind': caption_kind,
  1087. })
  1088. sub_formats.append({
  1089. 'url': caption_url + '&' + params,
  1090. 'ext': ext,
  1091. })
  1092. sub_lang_list[sub_lang] = sub_formats
  1093. return sub_lang_list
  1094. # Some videos don't provide ttsurl but rather caption_tracks and
  1095. # caption_translation_languages (e.g. 20LmZk1hakA)
  1096. caption_tracks = args['caption_tracks']
  1097. caption_translation_languages = args['caption_translation_languages']
  1098. caption_url = compat_parse_qs(caption_tracks.split(',')[0])['u'][0]
  1099. parsed_caption_url = compat_urllib_parse_urlparse(caption_url)
  1100. caption_qs = compat_parse_qs(parsed_caption_url.query)
  1101. sub_lang_list = {}
  1102. for lang in caption_translation_languages.split(','):
  1103. lang_qs = compat_parse_qs(compat_urllib_parse_unquote_plus(lang))
  1104. sub_lang = lang_qs.get('lc', [None])[0]
  1105. if not sub_lang:
  1106. continue
  1107. sub_formats = []
  1108. for ext in self._SUBTITLE_FORMATS:
  1109. caption_qs.update({
  1110. 'tlang': [sub_lang],
  1111. 'fmt': [ext],
  1112. })
  1113. sub_url = compat_urlparse.urlunparse(parsed_caption_url._replace(
  1114. query=compat_urllib_parse_urlencode(caption_qs, True)))
  1115. sub_formats.append({
  1116. 'url': sub_url,
  1117. 'ext': ext,
  1118. })
  1119. sub_lang_list[sub_lang] = sub_formats
  1120. return sub_lang_list
  1121. # An extractor error can be raise by the download process if there are
  1122. # no automatic captions but there are subtitles
  1123. except (KeyError, ExtractorError):
  1124. self._downloader.report_warning(err_msg)
  1125. return {}
  1126. def _mark_watched(self, video_id, video_info):
  1127. playback_url = video_info.get('videostats_playback_base_url', [None])[0]
  1128. if not playback_url:
  1129. return
  1130. parsed_playback_url = compat_urlparse.urlparse(playback_url)
  1131. qs = compat_urlparse.parse_qs(parsed_playback_url.query)
  1132. # cpn generation algorithm is reverse engineered from base.js.
  1133. # In fact it works even with dummy cpn.
  1134. CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
  1135. cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
  1136. qs.update({
  1137. 'ver': ['2'],
  1138. 'cpn': [cpn],
  1139. })
  1140. playback_url = compat_urlparse.urlunparse(
  1141. parsed_playback_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
  1142. self._download_webpage(
  1143. playback_url, video_id, 'Marking watched',
  1144. 'Unable to mark watched', fatal=False)
  1145. @classmethod
  1146. def extract_id(cls, url):
  1147. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  1148. if mobj is None:
  1149. raise ExtractorError('Invalid URL: %s' % url)
  1150. video_id = mobj.group(2)
  1151. return video_id
  1152. def _extract_from_m3u8(self, manifest_url, video_id):
  1153. url_map = {}
  1154. def _get_urls(_manifest):
  1155. lines = _manifest.split('\n')
  1156. urls = filter(lambda l: l and not l.startswith('#'),
  1157. lines)
  1158. return urls
  1159. manifest = self._download_webpage(manifest_url, video_id, 'Downloading formats manifest')
  1160. formats_urls = _get_urls(manifest)
  1161. for format_url in formats_urls:
  1162. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  1163. url_map[itag] = format_url
  1164. return url_map
  1165. def _extract_annotations(self, video_id):
  1166. url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
  1167. return self._download_webpage(url, video_id, note='Searching for annotations.', errnote='Unable to download video annotations.')
  1168. def _real_extract(self, url):
  1169. url, smuggled_data = unsmuggle_url(url, {})
  1170. proto = (
  1171. 'http' if self._downloader.params.get('prefer_insecure', False)
  1172. else 'https')
  1173. start_time = None
  1174. end_time = None
  1175. parsed_url = compat_urllib_parse_urlparse(url)
  1176. for component in [parsed_url.fragment, parsed_url.query]:
  1177. query = compat_parse_qs(component)
  1178. if start_time is None and 't' in query:
  1179. start_time = parse_duration(query['t'][0])
  1180. if start_time is None and 'start' in query:
  1181. start_time = parse_duration(query['start'][0])
  1182. if end_time is None and 'end' in query:
  1183. end_time = parse_duration(query['end'][0])
  1184. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  1185. mobj = re.search(self._NEXT_URL_RE, url)
  1186. if mobj:
  1187. url = proto + '://www.youtube.com/' + compat_urllib_parse_unquote(mobj.group(1)).lstrip('/')
  1188. video_id = self.extract_id(url)
  1189. # Get video webpage
  1190. url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1&bpctr=9999999999' % video_id
  1191. video_webpage = self._download_webpage(url, video_id)
  1192. # Attempt to extract SWF player URL
  1193. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  1194. if mobj is not None:
  1195. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  1196. else:
  1197. player_url = None
  1198. dash_mpds = []
  1199. def add_dash_mpd(video_info):
  1200. dash_mpd = video_info.get('dashmpd')
  1201. if dash_mpd and dash_mpd[0] not in dash_mpds:
  1202. dash_mpds.append(dash_mpd[0])
  1203. # Get video info
  1204. embed_webpage = None
  1205. is_live = None
  1206. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  1207. age_gate = True
  1208. # We simulate the access to the video from www.youtube.com/v/{video_id}
  1209. # this can be viewed without login into Youtube
  1210. url = proto + '://www.youtube.com/embed/%s' % video_id
  1211. embed_webpage = self._download_webpage(url, video_id, 'Downloading embed webpage')
  1212. data = compat_urllib_parse_urlencode({
  1213. 'video_id': video_id,
  1214. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  1215. 'sts': self._search_regex(
  1216. r'"sts"\s*:\s*(\d+)', embed_webpage, 'sts', default=''),
  1217. })
  1218. video_info_url = proto + '://www.youtube.com/get_video_info?' + data
  1219. video_info_webpage = self._download_webpage(
  1220. video_info_url, video_id,
  1221. note='Refetching age-gated info webpage',
  1222. errnote='unable to download video info webpage')
  1223. video_info = compat_parse_qs(video_info_webpage)
  1224. add_dash_mpd(video_info)
  1225. else:
  1226. age_gate = False
  1227. video_info = None
  1228. # Try looking directly into the video webpage
  1229. ytplayer_config = self._get_ytplayer_config(video_id, video_webpage)
  1230. if ytplayer_config:
  1231. args = ytplayer_config['args']
  1232. if args.get('url_encoded_fmt_stream_map'):
  1233. # Convert to the same format returned by compat_parse_qs
  1234. video_info = dict((k, [v]) for k, v in args.items())
  1235. add_dash_mpd(video_info)
  1236. # Rental video is not rented but preview is available (e.g.
  1237. # https://www.youtube.com/watch?v=yYr8q0y5Jfg,
  1238. # https://github.com/rg3/youtube-dl/issues/10532)
  1239. if not video_info and args.get('ypc_vid'):
  1240. return self.url_result(
  1241. args['ypc_vid'], YoutubeIE.ie_key(), video_id=args['ypc_vid'])
  1242. if args.get('livestream') == '1' or args.get('live_playback') == 1:
  1243. is_live = True
  1244. if not video_info or self._downloader.params.get('youtube_include_dash_manifest', True):
  1245. # We also try looking in get_video_info since it may contain different dashmpd
  1246. # URL that points to a DASH manifest with possibly different itag set (some itags
  1247. # are missing from DASH manifest pointed by webpage's dashmpd, some - from DASH
  1248. # manifest pointed by get_video_info's dashmpd).
  1249. # The general idea is to take a union of itags of both DASH manifests (for example
  1250. # video with such 'manifest behavior' see https://github.com/rg3/youtube-dl/issues/6093)
  1251. self.report_video_info_webpage_download(video_id)
  1252. for el_type in ['&el=info', '&el=embedded', '&el=detailpage', '&el=vevo', '']:
  1253. video_info_url = (
  1254. '%s://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  1255. % (proto, video_id, el_type))
  1256. video_info_webpage = self._download_webpage(
  1257. video_info_url,
  1258. video_id, note=False,
  1259. errnote='unable to download video info webpage')
  1260. get_video_info = compat_parse_qs(video_info_webpage)
  1261. if get_video_info.get('use_cipher_signature') != ['True']:
  1262. add_dash_mpd(get_video_info)
  1263. if not video_info:
  1264. video_info = get_video_info
  1265. if 'token' in get_video_info:
  1266. # Different get_video_info requests may report different results, e.g.
  1267. # some may report video unavailability, but some may serve it without
  1268. # any complaint (see https://github.com/rg3/youtube-dl/issues/7362,
  1269. # the original webpage as well as el=info and el=embedded get_video_info
  1270. # requests report video unavailability due to geo restriction while
  1271. # el=detailpage succeeds and returns valid data). This is probably
  1272. # due to YouTube measures against IP ranges of hosting providers.
  1273. # Working around by preferring the first succeeded video_info containing
  1274. # the token if no such video_info yet was found.
  1275. if 'token' not in video_info:
  1276. video_info = get_video_info
  1277. break
  1278. if 'token' not in video_info:
  1279. if 'reason' in video_info:
  1280. if 'The uploader has not made this video available in your country.' in video_info['reason']:
  1281. regions_allowed = self._html_search_meta('regionsAllowed', video_webpage, default=None)
  1282. if regions_allowed:
  1283. raise ExtractorError('YouTube said: This video is available in %s only' % (
  1284. ', '.join(map(ISO3166Utils.short2full, regions_allowed.split(',')))),
  1285. expected=True)
  1286. raise ExtractorError(
  1287. 'YouTube said: %s' % video_info['reason'][0],
  1288. expected=True, video_id=video_id)
  1289. else:
  1290. raise ExtractorError(
  1291. '"token" parameter not in video info for unknown reason',
  1292. video_id=video_id)
  1293. # title
  1294. if 'title' in video_info:
  1295. video_title = video_info['title'][0]
  1296. else:
  1297. self._downloader.report_warning('Unable to extract video title')
  1298. video_title = '_'
  1299. # description
  1300. video_description = get_element_by_id("eow-description", video_webpage)
  1301. if video_description:
  1302. video_description = re.sub(r'''(?x)
  1303. <a\s+
  1304. (?:[a-zA-Z-]+="[^"]*"\s+)*?
  1305. (?:title|href)="([^"]+)"\s+
  1306. (?:[a-zA-Z-]+="[^"]*"\s+)*?
  1307. class="[^"]*"[^>]*>
  1308. [^<]+\.{3}\s*
  1309. </a>
  1310. ''', r'\1', video_description)
  1311. video_description = clean_html(video_description)
  1312. else:
  1313. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  1314. if fd_mobj:
  1315. video_description = unescapeHTML(fd_mobj.group(1))
  1316. else:
  1317. video_description = ''
  1318. if 'multifeed_metadata_list' in video_info and not smuggled_data.get('force_singlefeed', False):
  1319. if not self._downloader.params.get('noplaylist'):
  1320. entries = []
  1321. feed_ids = []
  1322. multifeed_metadata_list = video_info['multifeed_metadata_list'][0]
  1323. for feed in multifeed_metadata_list.split(','):
  1324. # Unquote should take place before split on comma (,) since textual
  1325. # fields may contain comma as well (see
  1326. # https://github.com/rg3/youtube-dl/issues/8536)
  1327. feed_data = compat_parse_qs(compat_urllib_parse_unquote_plus(feed))
  1328. entries.append({
  1329. '_type': 'url_transparent',
  1330. 'ie_key': 'Youtube',
  1331. 'url': smuggle_url(
  1332. '%s://www.youtube.com/watch?v=%s' % (proto, feed_data['id'][0]),
  1333. {'force_singlefeed': True}),
  1334. 'title': '%s (%s)' % (video_title, feed_data['title'][0]),
  1335. })
  1336. feed_ids.append(feed_data['id'][0])
  1337. self.to_screen(
  1338. 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
  1339. % (', '.join(feed_ids), video_id))
  1340. return self.playlist_result(entries, video_id, video_title, video_description)
  1341. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1342. if 'view_count' in video_info:
  1343. view_count = int(video_info['view_count'][0])
  1344. else:
  1345. view_count = None
  1346. # Check for "rental" videos
  1347. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  1348. raise ExtractorError('"rental" videos not supported')
  1349. # Start extracting information
  1350. self.report_information_extraction(video_id)
  1351. # uploader
  1352. if 'author' not in video_info:
  1353. raise ExtractorError('Unable to extract uploader name')
  1354. video_uploader = compat_urllib_parse_unquote_plus(video_info['author'][0])
  1355. # uploader_id
  1356. video_uploader_id = None
  1357. video_uploader_url = None
  1358. mobj = re.search(
  1359. r'<link itemprop="url" href="(?P<uploader_url>https?://www.youtube.com/(?:user|channel)/(?P<uploader_id>[^"]+))">',
  1360. video_webpage)
  1361. if mobj is not None:
  1362. video_uploader_id = mobj.group('uploader_id')
  1363. video_uploader_url = mobj.group('uploader_url')
  1364. else:
  1365. self._downloader.report_warning('unable to extract uploader nickname')
  1366. # thumbnail image
  1367. # We try first to get a high quality image:
  1368. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  1369. video_webpage, re.DOTALL)
  1370. if m_thumb is not None:
  1371. video_thumbnail = m_thumb.group(1)
  1372. elif 'thumbnail_url' not in video_info:
  1373. self._downloader.report_warning('unable to extract video thumbnail')
  1374. video_thumbnail = None
  1375. else: # don't panic if we can't find it
  1376. video_thumbnail = compat_urllib_parse_unquote_plus(video_info['thumbnail_url'][0])
  1377. # upload date
  1378. upload_date = self._html_search_meta(
  1379. 'datePublished', video_webpage, 'upload date', default=None)
  1380. if not upload_date:
  1381. upload_date = self._search_regex(
  1382. [r'(?s)id="eow-date.*?>(.*?)</span>',
  1383. r'id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live|Started) on (.+?)</strong>'],
  1384. video_webpage, 'upload date', default=None)
  1385. if upload_date:
  1386. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  1387. upload_date = unified_strdate(upload_date)
  1388. video_license = self._html_search_regex(
  1389. r'<h4[^>]+class="title"[^>]*>\s*License\s*</h4>\s*<ul[^>]*>\s*<li>(.+?)</li',
  1390. video_webpage, 'license', default=None)
  1391. m_music = re.search(
  1392. r'<h4[^>]+class="title"[^>]*>\s*Music\s*</h4>\s*<ul[^>]*>\s*<li>(?P<title>.+?) by (?P<creator>.+?)(?:\(.+?\))?</li',
  1393. video_webpage)
  1394. if m_music:
  1395. video_alt_title = remove_quotes(unescapeHTML(m_music.group('title')))
  1396. video_creator = clean_html(m_music.group('creator'))
  1397. else:
  1398. video_alt_title = video_creator = None
  1399. m_episode = re.search(
  1400. r'<div[^>]+id="watch7-headline"[^>]*>\s*<span[^>]*>.*?>(?P<series>[^<]+)</a></b>\s*S(?P<season>\d+)\s*•\s*E(?P<episode>\d+)</span>',
  1401. video_webpage)
  1402. if m_episode:
  1403. series = m_episode.group('series')
  1404. season_number = int(m_episode.group('season'))
  1405. episode_number = int(m_episode.group('episode'))
  1406. else:
  1407. series = season_number = episode_number = None
  1408. m_cat_container = self._search_regex(
  1409. r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>',
  1410. video_webpage, 'categories', default=None)
  1411. if m_cat_container:
  1412. category = self._html_search_regex(
  1413. r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
  1414. default=None)
  1415. video_categories = None if category is None else [category]
  1416. else:
  1417. video_categories = None
  1418. video_tags = [
  1419. unescapeHTML(m.group('content'))
  1420. for m in re.finditer(self._meta_regex('og:video:tag'), video_webpage)]
  1421. def _extract_count(count_name):
  1422. return str_to_int(self._search_regex(
  1423. r'-%s-button[^>]+><span[^>]+class="yt-uix-button-content"[^>]*>([\d,]+)</span>'
  1424. % re.escape(count_name),
  1425. video_webpage, count_name, default=None))
  1426. like_count = _extract_count('like')
  1427. dislike_count = _extract_count('dislike')
  1428. # subtitles
  1429. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  1430. automatic_captions = self.extract_automatic_captions(video_id, video_webpage)
  1431. video_duration = try_get(
  1432. video_info, lambda x: int_or_none(x['length_seconds'][0]))
  1433. if not video_duration:
  1434. video_duration = parse_duration(self._html_search_meta(
  1435. 'duration', video_webpage, 'video duration'))
  1436. # annotations
  1437. video_annotations = None
  1438. if self._downloader.params.get('writeannotations', False):
  1439. video_annotations = self._extract_annotations(video_id)
  1440. def _map_to_format_list(urlmap):
  1441. formats = []
  1442. for itag, video_real_url in urlmap.items():
  1443. dct = {
  1444. 'format_id': itag,
  1445. 'url': video_real_url,
  1446. 'player_url': player_url,
  1447. }
  1448. if itag in self._formats:
  1449. dct.update(self._formats[itag])
  1450. formats.append(dct)
  1451. return formats
  1452. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1453. self.report_rtmp_download()
  1454. formats = [{
  1455. 'format_id': '_rtmp',
  1456. 'protocol': 'rtmp',
  1457. 'url': video_info['conn'][0],
  1458. 'player_url': player_url,
  1459. }]
  1460. elif len(video_info.get('url_encoded_fmt_stream_map', [''])[0]) >= 1 or len(video_info.get('adaptive_fmts', [''])[0]) >= 1:
  1461. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts', [''])[0]
  1462. if 'rtmpe%3Dyes' in encoded_url_map:
  1463. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  1464. formats_spec = {}
  1465. fmt_list = video_info.get('fmt_list', [''])[0]
  1466. if fmt_list:
  1467. for fmt in fmt_list.split(','):
  1468. spec = fmt.split('/')
  1469. if len(spec) > 1:
  1470. width_height = spec[1].split('x')
  1471. if len(width_height) == 2:
  1472. formats_spec[spec[0]] = {
  1473. 'resolution': spec[1],
  1474. 'width': int_or_none(width_height[0]),
  1475. 'height': int_or_none(width_height[1]),
  1476. }
  1477. formats = []
  1478. for url_data_str in encoded_url_map.split(','):
  1479. url_data = compat_parse_qs(url_data_str)
  1480. if 'itag' not in url_data or 'url' not in url_data:
  1481. continue
  1482. format_id = url_data['itag'][0]
  1483. url = url_data['url'][0]
  1484. if 'sig' in url_data:
  1485. url += '&signature=' + url_data['sig'][0]
  1486. elif 's' in url_data:
  1487. encrypted_sig = url_data['s'][0]
  1488. ASSETS_RE = r'"assets":.+?"js":\s*("[^"]+")'
  1489. jsplayer_url_json = self._search_regex(
  1490. ASSETS_RE,
  1491. embed_webpage if age_gate else video_webpage,
  1492. 'JS player URL (1)', default=None)
  1493. if not jsplayer_url_json and not age_gate:
  1494. # We need the embed website after all
  1495. if embed_webpage is None:
  1496. embed_url = proto + '://www.youtube.com/embed/%s' % video_id
  1497. embed_webpage = self._download_webpage(
  1498. embed_url, video_id, 'Downloading embed webpage')
  1499. jsplayer_url_json = self._search_regex(
  1500. ASSETS_RE, embed_webpage, 'JS player URL')
  1501. player_url = json.loads(jsplayer_url_json)
  1502. if player_url is None:
  1503. player_url_json = self._search_regex(
  1504. r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
  1505. video_webpage, 'age gate player URL')
  1506. player_url = json.loads(player_url_json)
  1507. if self._downloader.params.get('verbose'):
  1508. if player_url is None:
  1509. player_version = 'unknown'
  1510. player_desc = 'unknown'
  1511. else:
  1512. if player_url.endswith('swf'):
  1513. player_version = self._search_regex(
  1514. r'-(.+?)(?:/watch_as3)?\.swf$', player_url,
  1515. 'flash player', fatal=False)
  1516. player_desc = 'flash player %s' % player_version
  1517. else:
  1518. player_version = self._search_regex(
  1519. [r'html5player-([^/]+?)(?:/html5player(?:-new)?)?\.js', r'(?:www|player)-([^/]+)/base\.js'],
  1520. player_url,
  1521. 'html5 player', fatal=False)
  1522. player_desc = 'html5 player %s' % player_version
  1523. parts_sizes = self._signature_cache_id(encrypted_sig)
  1524. self.to_screen('{%s} signature length %s, %s' %
  1525. (format_id, parts_sizes, player_desc))
  1526. signature = self._decrypt_signature(
  1527. encrypted_sig, video_id, player_url, age_gate)
  1528. url += '&signature=' + signature
  1529. if 'ratebypass' not in url:
  1530. url += '&ratebypass=yes'
  1531. dct = {
  1532. 'format_id': format_id,
  1533. 'url': url,
  1534. 'player_url': player_url,
  1535. }
  1536. if format_id in self._formats:
  1537. dct.update(self._formats[format_id])
  1538. if format_id in formats_spec:
  1539. dct.update(formats_spec[format_id])
  1540. # Some itags are not included in DASH manifest thus corresponding formats will
  1541. # lack metadata (see https://github.com/rg3/youtube-dl/pull/5993).
  1542. # Trying to extract metadata from url_encoded_fmt_stream_map entry.
  1543. mobj = re.search(r'^(?P<width>\d+)[xX](?P<height>\d+)$', url_data.get('size', [''])[0])
  1544. width, height = (int(mobj.group('width')), int(mobj.group('height'))) if mobj else (None, None)
  1545. more_fields = {
  1546. 'filesize': int_or_none(url_data.get('clen', [None])[0]),
  1547. 'tbr': float_or_none(url_data.get('bitrate', [None])[0], 1000),
  1548. 'width': width,
  1549. 'height': height,
  1550. 'fps': int_or_none(url_data.get('fps', [None])[0]),
  1551. 'format_note': url_data.get('quality_label', [None])[0] or url_data.get('quality', [None])[0],
  1552. }
  1553. for key, value in more_fields.items():
  1554. if value:
  1555. dct[key] = value
  1556. type_ = url_data.get('type', [None])[0]
  1557. if type_:
  1558. type_split = type_.split(';')
  1559. kind_ext = type_split[0].split('/')
  1560. if len(kind_ext) == 2:
  1561. kind, _ = kind_ext
  1562. dct['ext'] = mimetype2ext(type_split[0])
  1563. if kind in ('audio', 'video'):
  1564. codecs = None
  1565. for mobj in re.finditer(
  1566. r'(?P<key>[a-zA-Z_-]+)=(?P<quote>["\']?)(?P<val>.+?)(?P=quote)(?:;|$)', type_):
  1567. if mobj.group('key') == 'codecs':
  1568. codecs = mobj.group('val')
  1569. break
  1570. if codecs:
  1571. codecs = codecs.split(',')
  1572. if len(codecs) == 2:
  1573. acodec, vcodec = codecs[1], codecs[0]
  1574. else:
  1575. acodec, vcodec = (codecs[0], 'none') if kind == 'audio' else ('none', codecs[0])
  1576. dct.update({
  1577. 'acodec': acodec,
  1578. 'vcodec': vcodec,
  1579. })
  1580. formats.append(dct)
  1581. elif video_info.get('hlsvp'):
  1582. manifest_url = video_info['hlsvp'][0]
  1583. url_map = self._extract_from_m3u8(manifest_url, video_id)
  1584. formats = _map_to_format_list(url_map)
  1585. # Accept-Encoding header causes failures in live streams on Youtube and Youtube Gaming
  1586. for a_format in formats:
  1587. a_format.setdefault('http_headers', {})['Youtubedl-no-compression'] = 'True'
  1588. else:
  1589. unavailable_message = self._html_search_regex(
  1590. r'(?s)<h1[^>]+id="unavailable-message"[^>]*>(.+?)</h1>',
  1591. video_webpage, 'unavailable message', default=None)
  1592. if unavailable_message:
  1593. raise ExtractorError(unavailable_message, expected=True)
  1594. raise ExtractorError('no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
  1595. # Look for the DASH manifest
  1596. if self._downloader.params.get('youtube_include_dash_manifest', True):
  1597. dash_mpd_fatal = True
  1598. for mpd_url in dash_mpds:
  1599. dash_formats = {}
  1600. try:
  1601. def decrypt_sig(mobj):
  1602. s = mobj.group(1)
  1603. dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
  1604. return '/signature/%s' % dec_s
  1605. mpd_url = re.sub(r'/s/([a-fA-F0-9\.]+)', decrypt_sig, mpd_url)
  1606. for df in self._extract_mpd_formats(
  1607. mpd_url, video_id, fatal=dash_mpd_fatal,
  1608. formats_dict=self._formats):
  1609. # Do not overwrite DASH format found in some previous DASH manifest
  1610. if df['format_id'] not in dash_formats:
  1611. dash_formats[df['format_id']] = df
  1612. # Additional DASH manifests may end up in HTTP Error 403 therefore
  1613. # allow them to fail without bug report message if we already have
  1614. # some DASH manifest succeeded. This is temporary workaround to reduce
  1615. # burst of bug reports until we figure out the reason and whether it
  1616. # can be fixed at all.
  1617. dash_mpd_fatal = False
  1618. except (ExtractorError, KeyError) as e:
  1619. self.report_warning(
  1620. 'Skipping DASH manifest: %r' % e, video_id)
  1621. if dash_formats:
  1622. # Remove the formats we found through non-DASH, they
  1623. # contain less info and it can be wrong, because we use
  1624. # fixed values (for example the resolution). See
  1625. # https://github.com/rg3/youtube-dl/issues/5774 for an
  1626. # example.
  1627. formats = [f for f in formats if f['format_id'] not in dash_formats.keys()]
  1628. formats.extend(dash_formats.values())
  1629. # Check for malformed aspect ratio
  1630. stretched_m = re.search(
  1631. r'<meta\s+property="og:video:tag".*?content="yt:stretch=(?P<w>[0-9]+):(?P<h>[0-9]+)">',
  1632. video_webpage)
  1633. if stretched_m:
  1634. w = float(stretched_m.group('w'))
  1635. h = float(stretched_m.group('h'))
  1636. # yt:stretch may hold invalid ratio data (e.g. for Q39EVAstoRM ratio is 17:0).
  1637. # We will only process correct ratios.
  1638. if w > 0 and h > 0:
  1639. ratio = w / h
  1640. for f in formats:
  1641. if f.get('vcodec') != 'none':
  1642. f['stretched_ratio'] = ratio
  1643. self._sort_formats(formats)
  1644. self.mark_watched(video_id, video_info)
  1645. return {
  1646. 'id': video_id,
  1647. 'uploader': video_uploader,
  1648. 'uploader_id': video_uploader_id,
  1649. 'uploader_url': video_uploader_url,
  1650. 'upload_date': upload_date,
  1651. 'license': video_license,
  1652. 'creator': video_creator,
  1653. 'title': video_title,
  1654. 'alt_title': video_alt_title,
  1655. 'thumbnail': video_thumbnail,
  1656. 'description': video_description,
  1657. 'categories': video_categories,
  1658. 'tags': video_tags,
  1659. 'subtitles': video_subtitles,
  1660. 'automatic_captions': automatic_captions,
  1661. 'duration': video_duration,
  1662. 'age_limit': 18 if age_gate else 0,
  1663. 'annotations': video_annotations,
  1664. 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
  1665. 'view_count': view_count,
  1666. 'like_count': like_count,
  1667. 'dislike_count': dislike_count,
  1668. 'average_rating': float_or_none(video_info.get('avg_rating', [None])[0]),
  1669. 'formats': formats,
  1670. 'is_live': is_live,
  1671. 'start_time': start_time,
  1672. 'end_time': end_time,
  1673. 'series': series,
  1674. 'season_number': season_number,
  1675. 'episode_number': episode_number,
  1676. }
  1677. class YoutubeSharedVideoIE(InfoExtractor):
  1678. _VALID_URL = r'(?:https?:)?//(?:www\.)?youtube\.com/shared\?.*\bci=(?P<id>[0-9A-Za-z_-]{11})'
  1679. IE_NAME = 'youtube:shared'
  1680. _TEST = {
  1681. 'url': 'https://www.youtube.com/shared?ci=1nEzmT-M4fU',
  1682. 'info_dict': {
  1683. 'id': 'uPDB5I9wfp8',
  1684. 'ext': 'webm',
  1685. 'title': 'Pocoyo: 90 minutos de episódios completos Português para crianças - PARTE 3',
  1686. 'description': 'md5:d9e4d9346a2dfff4c7dc4c8cec0f546d',
  1687. 'upload_date': '20160219',
  1688. 'uploader': 'Pocoyo - Português (BR)',
  1689. 'uploader_id': 'PocoyoBrazil',
  1690. },
  1691. 'add_ie': ['Youtube'],
  1692. 'params': {
  1693. # There are already too many Youtube downloads
  1694. 'skip_download': True,
  1695. },
  1696. }
  1697. def _real_extract(self, url):
  1698. video_id = self._match_id(url)
  1699. webpage = self._download_webpage(url, video_id)
  1700. real_video_id = self._html_search_meta(
  1701. 'videoId', webpage, 'YouTube video id', fatal=True)
  1702. return self.url_result(real_video_id, YoutubeIE.ie_key())
  1703. class YoutubePlaylistIE(YoutubePlaylistBaseInfoExtractor):
  1704. IE_DESC = 'YouTube.com playlists'
  1705. _VALID_URL = r"""(?x)(?:
  1706. (?:https?://)?
  1707. (?:\w+\.)?
  1708. (?:
  1709. youtube\.com/
  1710. (?:
  1711. (?:course|view_play_list|my_playlists|artist|playlist|watch|embed/videoseries)
  1712. \? (?:.*?[&;])*? (?:p|a|list)=
  1713. | p/
  1714. )|
  1715. youtu\.be/[0-9A-Za-z_-]{11}\?.*?\blist=
  1716. )
  1717. (
  1718. (?:PL|LL|EC|UU|FL|RD|UL|TL)?[0-9A-Za-z-_]{10,}
  1719. # Top tracks, they can also include dots
  1720. |(?:MC)[\w\.]*
  1721. )
  1722. .*
  1723. |
  1724. ((?:PL|LL|EC|UU|FL|RD|UL|TL)[0-9A-Za-z-_]{10,})
  1725. )"""
  1726. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s&disable_polymer=true'
  1727. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)(?:[^>]+>(?P<title>[^<]+))?'
  1728. IE_NAME = 'youtube:playlist'
  1729. _TESTS = [{
  1730. 'url': 'https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  1731. 'info_dict': {
  1732. 'title': 'ytdl test PL',
  1733. 'id': 'PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  1734. },
  1735. 'playlist_count': 3,
  1736. }, {
  1737. 'url': 'https://www.youtube.com/playlist?list=PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  1738. 'info_dict': {
  1739. 'id': 'PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  1740. 'title': 'YDL_Empty_List',
  1741. },
  1742. 'playlist_count': 0,
  1743. 'skip': 'This playlist is private',
  1744. }, {
  1745. 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
  1746. 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  1747. 'info_dict': {
  1748. 'title': '29C3: Not my department',
  1749. 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  1750. },
  1751. 'playlist_count': 95,
  1752. }, {
  1753. 'note': 'issue #673',
  1754. 'url': 'PLBB231211A4F62143',
  1755. 'info_dict': {
  1756. 'title': '[OLD]Team Fortress 2 (Class-based LP)',
  1757. 'id': 'PLBB231211A4F62143',
  1758. },
  1759. 'playlist_mincount': 26,
  1760. }, {
  1761. 'note': 'Large playlist',
  1762. 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
  1763. 'info_dict': {
  1764. 'title': 'Uploads from Cauchemar',
  1765. 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
  1766. },
  1767. 'playlist_mincount': 799,
  1768. }, {
  1769. 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  1770. 'info_dict': {
  1771. 'title': 'YDL_safe_search',
  1772. 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  1773. },
  1774. 'playlist_count': 2,
  1775. 'skip': 'This playlist is private',
  1776. }, {
  1777. 'note': 'embedded',
  1778. 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  1779. 'playlist_count': 4,
  1780. 'info_dict': {
  1781. 'title': 'JODA15',
  1782. 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  1783. }
  1784. }, {
  1785. 'note': 'Embedded SWF player',
  1786. 'url': 'https://www.youtube.com/p/YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ?hl=en_US&fs=1&rel=0',
  1787. 'playlist_count': 4,
  1788. 'info_dict': {
  1789. 'title': 'JODA7',
  1790. 'id': 'YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ',
  1791. }
  1792. }, {
  1793. 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
  1794. 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
  1795. 'info_dict': {
  1796. 'title': 'Uploads from Interstellar Movie',
  1797. 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
  1798. },
  1799. 'playlist_mincount': 21,
  1800. }, {
  1801. # Playlist URL that does not actually serve a playlist
  1802. 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
  1803. 'info_dict': {
  1804. 'id': 'FqZTN594JQw',
  1805. 'ext': 'webm',
  1806. 'title': "Smiley's People 01 detective, Adventure Series, Action",
  1807. 'uploader': 'STREEM',
  1808. 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
  1809. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
  1810. 'upload_date': '20150526',
  1811. 'license': 'Standard YouTube License',
  1812. 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
  1813. 'categories': ['People & Blogs'],
  1814. 'tags': list,
  1815. 'like_count': int,
  1816. 'dislike_count': int,
  1817. },
  1818. 'params': {
  1819. 'skip_download': True,
  1820. },
  1821. 'add_ie': [YoutubeIE.ie_key()],
  1822. }, {
  1823. 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
  1824. 'info_dict': {
  1825. 'id': 'yeWKywCrFtk',
  1826. 'ext': 'mp4',
  1827. 'title': 'Small Scale Baler and Braiding Rugs',
  1828. 'uploader': 'Backus-Page House Museum',
  1829. 'uploader_id': 'backuspagemuseum',
  1830. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
  1831. 'upload_date': '20161008',
  1832. 'license': 'Standard YouTube License',
  1833. 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
  1834. 'categories': ['Nonprofits & Activism'],
  1835. 'tags': list,
  1836. 'like_count': int,
  1837. 'dislike_count': int,
  1838. },
  1839. 'params': {
  1840. 'noplaylist': True,
  1841. 'skip_download': True,
  1842. },
  1843. }, {
  1844. 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
  1845. 'only_matching': True,
  1846. }, {
  1847. 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
  1848. 'only_matching': True,
  1849. }]
  1850. def _real_initialize(self):
  1851. self._login()
  1852. def _extract_mix(self, playlist_id):
  1853. # The mixes are generated from a single video
  1854. # the id of the playlist is just 'RD' + video_id
  1855. ids = []
  1856. last_id = playlist_id[-11:]
  1857. for n in itertools.count(1):
  1858. url = 'https://youtube.com/watch?v=%s&list=%s' % (last_id, playlist_id)
  1859. webpage = self._download_webpage(
  1860. url, playlist_id, 'Downloading page {0} of Youtube mix'.format(n))
  1861. new_ids = orderedSet(re.findall(
  1862. r'''(?xs)data-video-username=".*?".*?
  1863. href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id),
  1864. webpage))
  1865. # Fetch new pages until all the videos are repeated, it seems that
  1866. # there are always 51 unique videos.
  1867. new_ids = [_id for _id in new_ids if _id not in ids]
  1868. if not new_ids:
  1869. break
  1870. ids.extend(new_ids)
  1871. last_id = ids[-1]
  1872. url_results = self._ids_to_results(ids)
  1873. search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
  1874. title_span = (
  1875. search_title('playlist-title') or
  1876. search_title('title long-title') or
  1877. search_title('title'))
  1878. title = clean_html(title_span)
  1879. return self.playlist_result(url_results, playlist_id, title)
  1880. def _extract_playlist(self, playlist_id):
  1881. url = self._TEMPLATE_URL % playlist_id
  1882. page = self._download_webpage(url, playlist_id)
  1883. # the yt-alert-message now has tabindex attribute (see https://github.com/rg3/youtube-dl/issues/11604)
  1884. for match in re.findall(r'<div class="yt-alert-message"[^>]*>([^<]+)</div>', page):
  1885. match = match.strip()
  1886. # Check if the playlist exists or is private
  1887. mobj = re.match(r'[^<]*(?:The|This) playlist (?P<reason>does not exist|is private)[^<]*', match)
  1888. if mobj:
  1889. reason = mobj.group('reason')
  1890. message = 'This playlist %s' % reason
  1891. if 'private' in reason:
  1892. message += ', use --username or --netrc to access it'
  1893. message += '.'
  1894. raise ExtractorError(message, expected=True)
  1895. elif re.match(r'[^<]*Invalid parameters[^<]*', match):
  1896. raise ExtractorError(
  1897. 'Invalid parameters. Maybe URL is incorrect.',
  1898. expected=True)
  1899. elif re.match(r'[^<]*Choose your language[^<]*', match):
  1900. continue
  1901. else:
  1902. self.report_warning('Youtube gives an alert message: ' + match)
  1903. playlist_title = self._html_search_regex(
  1904. r'(?s)<h1 class="pl-header-title[^"]*"[^>]*>\s*(.*?)\s*</h1>',
  1905. page, 'title', default=None)
  1906. has_videos = True
  1907. if not playlist_title:
  1908. try:
  1909. # Some playlist URLs don't actually serve a playlist (e.g.
  1910. # https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4)
  1911. next(self._entries(page, playlist_id))
  1912. except StopIteration:
  1913. has_videos = False
  1914. return has_videos, self.playlist_result(
  1915. self._entries(page, playlist_id), playlist_id, playlist_title)
  1916. def _check_download_just_video(self, url, playlist_id):
  1917. # Check if it's a video-specific URL
  1918. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  1919. video_id = query_dict.get('v', [None])[0] or self._search_regex(
  1920. r'(?:^|//)youtu\.be/([0-9A-Za-z_-]{11})', url,
  1921. 'video id', default=None)
  1922. if video_id:
  1923. if self._downloader.params.get('noplaylist'):
  1924. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1925. return video_id, self.url_result(video_id, 'Youtube', video_id=video_id)
  1926. else:
  1927. self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  1928. return video_id, None
  1929. return None, None
  1930. def _real_extract(self, url):
  1931. # Extract playlist id
  1932. mobj = re.match(self._VALID_URL, url)
  1933. if mobj is None:
  1934. raise ExtractorError('Invalid URL: %s' % url)
  1935. playlist_id = mobj.group(1) or mobj.group(2)
  1936. video_id, video = self._check_download_just_video(url, playlist_id)
  1937. if video:
  1938. return video
  1939. if playlist_id.startswith(('RD', 'UL', 'PU')):
  1940. # Mixes require a custom extraction process
  1941. return self._extract_mix(playlist_id)
  1942. has_videos, playlist = self._extract_playlist(playlist_id)
  1943. if has_videos or not video_id:
  1944. return playlist
  1945. # Some playlist URLs don't actually serve a playlist (see
  1946. # https://github.com/rg3/youtube-dl/issues/10537).
  1947. # Fallback to plain video extraction if there is a video id
  1948. # along with playlist id.
  1949. return self.url_result(video_id, 'Youtube', video_id=video_id)
  1950. class YoutubeChannelIE(YoutubePlaylistBaseInfoExtractor):
  1951. IE_DESC = 'YouTube.com channels'
  1952. _VALID_URL = r'https?://(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/(?P<id>[0-9A-Za-z_-]+)'
  1953. _TEMPLATE_URL = 'https://www.youtube.com/channel/%s/videos'
  1954. _VIDEO_RE = r'(?:title="(?P<title>[^"]+)"[^>]+)?href="/watch\?v=(?P<id>[0-9A-Za-z_-]+)&?'
  1955. IE_NAME = 'youtube:channel'
  1956. _TESTS = [{
  1957. 'note': 'paginated channel',
  1958. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
  1959. 'playlist_mincount': 91,
  1960. 'info_dict': {
  1961. 'id': 'UUKfVa3S1e4PHvxWcwyMMg8w',
  1962. 'title': 'Uploads from lex will',
  1963. }
  1964. }, {
  1965. 'note': 'Age restricted channel',
  1966. # from https://www.youtube.com/user/DeusExOfficial
  1967. 'url': 'https://www.youtube.com/channel/UCs0ifCMCm1icqRbqhUINa0w',
  1968. 'playlist_mincount': 64,
  1969. 'info_dict': {
  1970. 'id': 'UUs0ifCMCm1icqRbqhUINa0w',
  1971. 'title': 'Uploads from Deus Ex',
  1972. },
  1973. }]
  1974. @classmethod
  1975. def suitable(cls, url):
  1976. return (False if YoutubePlaylistsIE.suitable(url) or YoutubeLiveIE.suitable(url)
  1977. else super(YoutubeChannelIE, cls).suitable(url))
  1978. def _build_template_url(self, url, channel_id):
  1979. return self._TEMPLATE_URL % channel_id
  1980. def _real_extract(self, url):
  1981. channel_id = self._match_id(url)
  1982. url = self._build_template_url(url, channel_id)
  1983. # Channel by page listing is restricted to 35 pages of 30 items, i.e. 1050 videos total (see #5778)
  1984. # Workaround by extracting as a playlist if managed to obtain channel playlist URL
  1985. # otherwise fallback on channel by page extraction
  1986. channel_page = self._download_webpage(
  1987. url + '?view=57', channel_id,
  1988. 'Downloading channel page', fatal=False)
  1989. if channel_page is False:
  1990. channel_playlist_id = False
  1991. else:
  1992. channel_playlist_id = self._html_search_meta(
  1993. 'channelId', channel_page, 'channel id', default=None)
  1994. if not channel_playlist_id:
  1995. channel_url = self._html_search_meta(
  1996. ('al:ios:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad'),
  1997. channel_page, 'channel url', default=None)
  1998. if channel_url:
  1999. channel_playlist_id = self._search_regex(
  2000. r'vnd\.youtube://user/([0-9A-Za-z_-]+)',
  2001. channel_url, 'channel id', default=None)
  2002. if channel_playlist_id and channel_playlist_id.startswith('UC'):
  2003. playlist_id = 'UU' + channel_playlist_id[2:]
  2004. return self.url_result(
  2005. compat_urlparse.urljoin(url, '/playlist?list=%s' % playlist_id), 'YoutubePlaylist')
  2006. channel_page = self._download_webpage(url, channel_id, 'Downloading page #1')
  2007. autogenerated = re.search(r'''(?x)
  2008. class="[^"]*?(?:
  2009. channel-header-autogenerated-label|
  2010. yt-channel-title-autogenerated
  2011. )[^"]*"''', channel_page) is not None
  2012. if autogenerated:
  2013. # The videos are contained in a single page
  2014. # the ajax pages can't be used, they are empty
  2015. entries = [
  2016. self.url_result(
  2017. video_id, 'Youtube', video_id=video_id,
  2018. video_title=video_title)
  2019. for video_id, video_title in self.extract_videos_from_page(channel_page)]
  2020. return self.playlist_result(entries, channel_id)
  2021. try:
  2022. next(self._entries(channel_page, channel_id))
  2023. except StopIteration:
  2024. alert_message = self._html_search_regex(
  2025. r'(?s)<div[^>]+class=(["\']).*?\byt-alert-message\b.*?\1[^>]*>(?P<alert>[^<]+)</div>',
  2026. channel_page, 'alert', default=None, group='alert')
  2027. if alert_message:
  2028. raise ExtractorError('Youtube said: %s' % alert_message, expected=True)
  2029. return self.playlist_result(self._entries(channel_page, channel_id), channel_id)
  2030. class YoutubeUserIE(YoutubeChannelIE):
  2031. IE_DESC = 'YouTube.com user videos (URL or "ytuser" keyword)'
  2032. _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_-]+)'
  2033. _TEMPLATE_URL = 'https://www.youtube.com/%s/%s/videos'
  2034. IE_NAME = 'youtube:user'
  2035. _TESTS = [{
  2036. 'url': 'https://www.youtube.com/user/TheLinuxFoundation',
  2037. 'playlist_mincount': 320,
  2038. 'info_dict': {
  2039. 'id': 'UUfX55Sx5hEFjoC3cNs6mCUQ',
  2040. 'title': 'Uploads from The Linux Foundation',
  2041. }
  2042. }, {
  2043. # Only available via https://www.youtube.com/c/12minuteathlete/videos
  2044. # but not https://www.youtube.com/user/12minuteathlete/videos
  2045. 'url': 'https://www.youtube.com/c/12minuteathlete/videos',
  2046. 'playlist_mincount': 249,
  2047. 'info_dict': {
  2048. 'id': 'UUVjM-zV6_opMDx7WYxnjZiQ',
  2049. 'title': 'Uploads from 12 Minute Athlete',
  2050. }
  2051. }, {
  2052. 'url': 'ytuser:phihag',
  2053. 'only_matching': True,
  2054. }, {
  2055. 'url': 'https://www.youtube.com/c/gametrailers',
  2056. 'only_matching': True,
  2057. }, {
  2058. 'url': 'https://www.youtube.com/gametrailers',
  2059. 'only_matching': True,
  2060. }, {
  2061. # This channel is not available.
  2062. 'url': 'https://www.youtube.com/user/kananishinoSMEJ/videos',
  2063. 'only_matching': True,
  2064. }]
  2065. @classmethod
  2066. def suitable(cls, url):
  2067. # Don't return True if the url can be extracted with other youtube
  2068. # extractor, the regex would is too permissive and it would match.
  2069. other_yt_ies = iter(klass for (name, klass) in globals().items() if name.startswith('Youtube') and name.endswith('IE') and klass is not cls)
  2070. if any(ie.suitable(url) for ie in other_yt_ies):
  2071. return False
  2072. else:
  2073. return super(YoutubeUserIE, cls).suitable(url)
  2074. def _build_template_url(self, url, channel_id):
  2075. mobj = re.match(self._VALID_URL, url)
  2076. return self._TEMPLATE_URL % (mobj.group('user') or 'user', mobj.group('id'))
  2077. class YoutubeLiveIE(YoutubeBaseInfoExtractor):
  2078. IE_DESC = 'YouTube.com live streams'
  2079. _VALID_URL = r'(?P<base_url>https?://(?:\w+\.)?youtube\.com/(?:(?:user|channel|c)/)?(?P<id>[^/]+))/live'
  2080. IE_NAME = 'youtube:live'
  2081. _TESTS = [{
  2082. 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
  2083. 'info_dict': {
  2084. 'id': 'a48o2S1cPoo',
  2085. 'ext': 'mp4',
  2086. 'title': 'The Young Turks - Live Main Show',
  2087. 'uploader': 'The Young Turks',
  2088. 'uploader_id': 'TheYoungTurks',
  2089. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
  2090. 'upload_date': '20150715',
  2091. 'license': 'Standard YouTube License',
  2092. 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
  2093. 'categories': ['News & Politics'],
  2094. 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
  2095. 'like_count': int,
  2096. 'dislike_count': int,
  2097. },
  2098. 'params': {
  2099. 'skip_download': True,
  2100. },
  2101. }, {
  2102. 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
  2103. 'only_matching': True,
  2104. }, {
  2105. 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
  2106. 'only_matching': True,
  2107. }, {
  2108. 'url': 'https://www.youtube.com/TheYoungTurks/live',
  2109. 'only_matching': True,
  2110. }]
  2111. def _real_extract(self, url):
  2112. mobj = re.match(self._VALID_URL, url)
  2113. channel_id = mobj.group('id')
  2114. base_url = mobj.group('base_url')
  2115. webpage = self._download_webpage(url, channel_id, fatal=False)
  2116. if webpage:
  2117. page_type = self._og_search_property(
  2118. 'type', webpage, 'page type', default=None)
  2119. video_id = self._html_search_meta(
  2120. 'videoId', webpage, 'video id', default=None)
  2121. if page_type == 'video' and video_id and re.match(r'^[0-9A-Za-z_-]{11}$', video_id):
  2122. return self.url_result(video_id, YoutubeIE.ie_key())
  2123. return self.url_result(base_url)
  2124. class YoutubePlaylistsIE(YoutubePlaylistsBaseInfoExtractor):
  2125. IE_DESC = 'YouTube.com user/channel playlists'
  2126. _VALID_URL = r'https?://(?:\w+\.)?youtube\.com/(?:user|channel)/(?P<id>[^/]+)/playlists'
  2127. IE_NAME = 'youtube:playlists'
  2128. _TESTS = [{
  2129. 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
  2130. 'playlist_mincount': 4,
  2131. 'info_dict': {
  2132. 'id': 'ThirstForScience',
  2133. 'title': 'Thirst for Science',
  2134. },
  2135. }, {
  2136. # with "Load more" button
  2137. 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
  2138. 'playlist_mincount': 70,
  2139. 'info_dict': {
  2140. 'id': 'igorkle1',
  2141. 'title': 'Игорь Клейнер',
  2142. },
  2143. }, {
  2144. 'url': 'https://www.youtube.com/channel/UCiU1dHvZObB2iP6xkJ__Icw/playlists',
  2145. 'playlist_mincount': 17,
  2146. 'info_dict': {
  2147. 'id': 'UCiU1dHvZObB2iP6xkJ__Icw',
  2148. 'title': 'Chem Player',
  2149. },
  2150. }]
  2151. class YoutubeSearchIE(SearchInfoExtractor, YoutubePlaylistIE):
  2152. IE_DESC = 'YouTube.com searches'
  2153. # there doesn't appear to be a real limit, for example if you search for
  2154. # 'python' you get more than 8.000.000 results
  2155. _MAX_RESULTS = float('inf')
  2156. IE_NAME = 'youtube:search'
  2157. _SEARCH_KEY = 'ytsearch'
  2158. _EXTRA_QUERY_ARGS = {}
  2159. _TESTS = []
  2160. def _get_n_results(self, query, n):
  2161. """Get a specified number of results for a query"""
  2162. videos = []
  2163. limit = n
  2164. url_query = {
  2165. 'search_query': query.encode('utf-8'),
  2166. }
  2167. url_query.update(self._EXTRA_QUERY_ARGS)
  2168. result_url = 'https://www.youtube.com/results?' + compat_urllib_parse_urlencode(url_query)
  2169. for pagenum in itertools.count(1):
  2170. data = self._download_json(
  2171. result_url, video_id='query "%s"' % query,
  2172. note='Downloading page %s' % pagenum,
  2173. errnote='Unable to download API page',
  2174. query={'spf': 'navigate'})
  2175. html_content = data[1]['body']['content']
  2176. if 'class="search-message' in html_content:
  2177. raise ExtractorError(
  2178. '[youtube] No video results', expected=True)
  2179. new_videos = self._ids_to_results(orderedSet(re.findall(
  2180. r'href="/watch\?v=(.{11})', html_content)))
  2181. videos += new_videos
  2182. if not new_videos or len(videos) > limit:
  2183. break
  2184. next_link = self._html_search_regex(
  2185. r'href="(/results\?[^"]*\bsp=[^"]+)"[^>]*>\s*<span[^>]+class="[^"]*\byt-uix-button-content\b[^"]*"[^>]*>Next',
  2186. html_content, 'next link', default=None)
  2187. if next_link is None:
  2188. break
  2189. result_url = compat_urlparse.urljoin('https://www.youtube.com/', next_link)
  2190. if len(videos) > n:
  2191. videos = videos[:n]
  2192. return self.playlist_result(videos, query)
  2193. class YoutubeSearchDateIE(YoutubeSearchIE):
  2194. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  2195. _SEARCH_KEY = 'ytsearchdate'
  2196. IE_DESC = 'YouTube.com searches, newest videos first'
  2197. _EXTRA_QUERY_ARGS = {'search_sort': 'video_date_uploaded'}
  2198. class YoutubeSearchURLIE(YoutubePlaylistBaseInfoExtractor):
  2199. IE_DESC = 'YouTube.com search URLs'
  2200. IE_NAME = 'youtube:search_url'
  2201. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?P<query>[^&]+)(?:[&]|$)'
  2202. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})(?:[^"]*"[^>]+\btitle="(?P<title>[^"]+))?'
  2203. _TESTS = [{
  2204. 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
  2205. 'playlist_mincount': 5,
  2206. 'info_dict': {
  2207. 'title': 'youtube-dl test video',
  2208. }
  2209. }, {
  2210. 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
  2211. 'only_matching': True,
  2212. }]
  2213. def _real_extract(self, url):
  2214. mobj = re.match(self._VALID_URL, url)
  2215. query = compat_urllib_parse_unquote_plus(mobj.group('query'))
  2216. webpage = self._download_webpage(url, query)
  2217. return self.playlist_result(self._process_page(webpage), playlist_title=query)
  2218. class YoutubeShowIE(YoutubePlaylistsBaseInfoExtractor):
  2219. IE_DESC = 'YouTube.com (multi-season) shows'
  2220. _VALID_URL = r'https?://(?:www\.)?youtube\.com/show/(?P<id>[^?#]*)'
  2221. IE_NAME = 'youtube:show'
  2222. _TESTS = [{
  2223. 'url': 'https://www.youtube.com/show/airdisasters',
  2224. 'playlist_mincount': 5,
  2225. 'info_dict': {
  2226. 'id': 'airdisasters',
  2227. 'title': 'Air Disasters',
  2228. }
  2229. }]
  2230. def _real_extract(self, url):
  2231. playlist_id = self._match_id(url)
  2232. return super(YoutubeShowIE, self)._real_extract(
  2233. 'https://www.youtube.com/show/%s/playlists' % playlist_id)
  2234. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  2235. """
  2236. Base class for feed extractors
  2237. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  2238. """
  2239. _LOGIN_REQUIRED = True
  2240. @property
  2241. def IE_NAME(self):
  2242. return 'youtube:%s' % self._FEED_NAME
  2243. def _real_initialize(self):
  2244. self._login()
  2245. def _real_extract(self, url):
  2246. page = self._download_webpage(
  2247. 'https://www.youtube.com/feed/%s' % self._FEED_NAME, self._PLAYLIST_TITLE)
  2248. # The extraction process is the same as for playlists, but the regex
  2249. # for the video ids doesn't contain an index
  2250. ids = []
  2251. more_widget_html = content_html = page
  2252. for page_num in itertools.count(1):
  2253. matches = re.findall(r'href="\s*/watch\?v=([0-9A-Za-z_-]{11})', content_html)
  2254. # 'recommended' feed has infinite 'load more' and each new portion spins
  2255. # the same videos in (sometimes) slightly different order, so we'll check
  2256. # for unicity and break when portion has no new videos
  2257. new_ids = filter(lambda video_id: video_id not in ids, orderedSet(matches))
  2258. if not new_ids:
  2259. break
  2260. ids.extend(new_ids)
  2261. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  2262. if not mobj:
  2263. break
  2264. more = self._download_json(
  2265. 'https://youtube.com/%s' % mobj.group('more'), self._PLAYLIST_TITLE,
  2266. 'Downloading page #%s' % page_num,
  2267. transform_source=uppercase_escape)
  2268. content_html = more['content_html']
  2269. more_widget_html = more['load_more_widget_html']
  2270. return self.playlist_result(
  2271. self._ids_to_results(ids), playlist_title=self._PLAYLIST_TITLE)
  2272. class YoutubeWatchLaterIE(YoutubePlaylistIE):
  2273. IE_NAME = 'youtube:watchlater'
  2274. IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
  2275. _VALID_URL = r'https?://(?:www\.)?youtube\.com/(?:feed/watch_later|(?:playlist|watch)\?(?:.+&)?list=WL)|:ytwatchlater'
  2276. _TESTS = [{
  2277. 'url': 'https://www.youtube.com/playlist?list=WL',
  2278. 'only_matching': True,
  2279. }, {
  2280. 'url': 'https://www.youtube.com/watch?v=bCNU9TrbiRk&index=1&list=WL',
  2281. 'only_matching': True,
  2282. }]
  2283. def _real_extract(self, url):
  2284. _, video = self._check_download_just_video(url, 'WL')
  2285. if video:
  2286. return video
  2287. _, playlist = self._extract_playlist('WL')
  2288. return playlist
  2289. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  2290. IE_NAME = 'youtube:favorites'
  2291. IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
  2292. _VALID_URL = r'https?://(?:www\.)?youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  2293. _LOGIN_REQUIRED = True
  2294. def _real_extract(self, url):
  2295. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  2296. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, 'favourites playlist id')
  2297. return self.url_result(playlist_id, 'YoutubePlaylist')
  2298. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  2299. IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
  2300. _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  2301. _FEED_NAME = 'recommended'
  2302. _PLAYLIST_TITLE = 'Youtube Recommended videos'
  2303. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  2304. IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  2305. _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  2306. _FEED_NAME = 'subscriptions'
  2307. _PLAYLIST_TITLE = 'Youtube Subscriptions'
  2308. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  2309. IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
  2310. _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/history|:ythistory'
  2311. _FEED_NAME = 'history'
  2312. _PLAYLIST_TITLE = 'Youtube History'
  2313. class YoutubeTruncatedURLIE(InfoExtractor):
  2314. IE_NAME = 'youtube:truncated_url'
  2315. IE_DESC = False # Do not list
  2316. _VALID_URL = r'''(?x)
  2317. (?:https?://)?
  2318. (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
  2319. (?:watch\?(?:
  2320. feature=[a-z_]+|
  2321. annotation_id=annotation_[^&]+|
  2322. x-yt-cl=[0-9]+|
  2323. hl=[^&]*|
  2324. t=[0-9]+
  2325. )?
  2326. |
  2327. attribution_link\?a=[^&]+
  2328. )
  2329. $
  2330. '''
  2331. _TESTS = [{
  2332. 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
  2333. 'only_matching': True,
  2334. }, {
  2335. 'url': 'https://www.youtube.com/watch?',
  2336. 'only_matching': True,
  2337. }, {
  2338. 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
  2339. 'only_matching': True,
  2340. }, {
  2341. 'url': 'https://www.youtube.com/watch?feature=foo',
  2342. 'only_matching': True,
  2343. }, {
  2344. 'url': 'https://www.youtube.com/watch?hl=en-GB',
  2345. 'only_matching': True,
  2346. }, {
  2347. 'url': 'https://www.youtube.com/watch?t=2372',
  2348. 'only_matching': True,
  2349. }]
  2350. def _real_extract(self, url):
  2351. raise ExtractorError(
  2352. 'Did you forget to quote the URL? Remember that & is a meta '
  2353. 'character in most shells, so you want to put the URL in quotes, '
  2354. 'like youtube-dl '
  2355. '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  2356. ' or simply youtube-dl BaW_jenozKc .',
  2357. expected=True)
  2358. class YoutubeTruncatedIDIE(InfoExtractor):
  2359. IE_NAME = 'youtube:truncated_id'
  2360. IE_DESC = False # Do not list
  2361. _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
  2362. _TESTS = [{
  2363. 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
  2364. 'only_matching': True,
  2365. }]
  2366. def _real_extract(self, url):
  2367. video_id = self._match_id(url)
  2368. raise ExtractorError(
  2369. 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),
  2370. expected=True)