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.

1967 lines
87 KiB

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