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.

2736 lines
121 KiB

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