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.

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