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.

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