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.

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