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.

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