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.

2349 lines
106 KiB

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