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.

2636 lines
118 KiB

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