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.

2354 lines
106 KiB

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