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.

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