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