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.

2432 lines
110 KiB

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