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.

2428 lines
109 KiB

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