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.

2517 lines
113 KiB

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