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.

1548 lines
68 KiB

11 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 traceback
  8. from .common import InfoExtractor, SearchInfoExtractor
  9. from .subtitles import SubtitlesInfoExtractor
  10. from ..jsinterp import JSInterpreter
  11. from ..swfinterp import SWFInterpreter
  12. from ..utils import (
  13. compat_chr,
  14. compat_parse_qs,
  15. compat_urllib_parse,
  16. compat_urllib_request,
  17. compat_urlparse,
  18. compat_str,
  19. clean_html,
  20. get_element_by_id,
  21. get_element_by_attribute,
  22. ExtractorError,
  23. int_or_none,
  24. PagedList,
  25. unescapeHTML,
  26. unified_strdate,
  27. orderedSet,
  28. uppercase_escape,
  29. )
  30. class YoutubeBaseInfoExtractor(InfoExtractor):
  31. """Provide base functions for Youtube extractors"""
  32. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  33. _TWOFACTOR_URL = 'https://accounts.google.com/SecondFactor'
  34. _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  35. _AGE_URL = 'https://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  36. _NETRC_MACHINE = 'youtube'
  37. # If True it will raise an error if no login info is provided
  38. _LOGIN_REQUIRED = False
  39. def _set_language(self):
  40. return bool(self._download_webpage(
  41. self._LANG_URL, None,
  42. note=u'Setting language', errnote='unable to set language',
  43. fatal=False))
  44. def _login(self):
  45. """
  46. Attempt to log in to YouTube.
  47. True is returned if successful or skipped.
  48. False is returned if login failed.
  49. If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
  50. """
  51. (username, password) = self._get_login_info()
  52. # No authentication to be performed
  53. if username is None:
  54. if self._LOGIN_REQUIRED:
  55. raise ExtractorError(u'No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  56. return True
  57. login_page = self._download_webpage(
  58. self._LOGIN_URL, None,
  59. note=u'Downloading login page',
  60. errnote=u'unable to fetch login page', fatal=False)
  61. if login_page is False:
  62. return
  63. galx = self._search_regex(r'(?s)<input.+?name="GALX".+?value="(.+?)"',
  64. login_page, 'Login GALX parameter')
  65. # Log in
  66. login_form_strs = {
  67. 'continue': 'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  68. 'Email': username,
  69. 'GALX': galx,
  70. 'Passwd': password,
  71. 'PersistentCookie': 'yes',
  72. '_utf8': '',
  73. 'bgresponse': 'js_disabled',
  74. 'checkConnection': '',
  75. 'checkedDomains': 'youtube',
  76. 'dnConn': '',
  77. 'pstMsg': '0',
  78. 'rmShown': '1',
  79. 'secTok': '',
  80. 'signIn': 'Sign in',
  81. 'timeStmp': '',
  82. 'service': 'youtube',
  83. 'uilel': '3',
  84. 'hl': 'en_US',
  85. }
  86. # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
  87. # chokes on unicode
  88. login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
  89. login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
  90. req = compat_urllib_request.Request(self._LOGIN_URL, login_data)
  91. login_results = self._download_webpage(
  92. req, None,
  93. note=u'Logging in', errnote=u'unable to log in', fatal=False)
  94. if login_results is False:
  95. return False
  96. if re.search(r'id="errormsg_0_Passwd"', login_results) is not None:
  97. raise ExtractorError(u'Please use your account password and a two-factor code instead of an application-specific password.', expected=True)
  98. # Two-Factor
  99. # TODO add SMS and phone call support - these require making a request and then prompting the user
  100. if re.search(r'(?i)<form[^>]* id="gaia_secondfactorform"', login_results) is not None:
  101. tfa_code = self._get_tfa_info()
  102. if tfa_code is None:
  103. self._downloader.report_warning(u'Two-factor authentication required. Provide it with --twofactor <code>')
  104. self._downloader.report_warning(u'(Note that only TOTP (Google Authenticator App) codes work at this time.)')
  105. return False
  106. # Unlike the first login form, secTok and timeStmp are both required for the TFA form
  107. match = re.search(r'id="secTok"\n\s+value=\'(.+)\'/>', login_results, re.M | re.U)
  108. if match is None:
  109. self._downloader.report_warning(u'Failed to get secTok - did the page structure change?')
  110. secTok = match.group(1)
  111. match = re.search(r'id="timeStmp"\n\s+value=\'(.+)\'/>', login_results, re.M | re.U)
  112. if match is None:
  113. self._downloader.report_warning(u'Failed to get timeStmp - did the page structure change?')
  114. timeStmp = match.group(1)
  115. tfa_form_strs = {
  116. 'continue': 'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  117. 'smsToken': '',
  118. 'smsUserPin': tfa_code,
  119. 'smsVerifyPin': 'Verify',
  120. 'PersistentCookie': 'yes',
  121. 'checkConnection': '',
  122. 'checkedDomains': 'youtube',
  123. 'pstMsg': '1',
  124. 'secTok': secTok,
  125. 'timeStmp': timeStmp,
  126. 'service': 'youtube',
  127. 'hl': 'en_US',
  128. }
  129. tfa_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in tfa_form_strs.items())
  130. tfa_data = compat_urllib_parse.urlencode(tfa_form).encode('ascii')
  131. tfa_req = compat_urllib_request.Request(self._TWOFACTOR_URL, tfa_data)
  132. tfa_results = self._download_webpage(
  133. tfa_req, None,
  134. note=u'Submitting TFA code', errnote=u'unable to submit tfa', fatal=False)
  135. if tfa_results is False:
  136. return False
  137. if re.search(r'(?i)<form[^>]* id="gaia_secondfactorform"', tfa_results) is not None:
  138. self._downloader.report_warning(u'Two-factor code expired. Please try again, or use a one-use backup code instead.')
  139. return False
  140. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', tfa_results) is not None:
  141. self._downloader.report_warning(u'unable to log in - did the page structure change?')
  142. return False
  143. if re.search(r'smsauth-interstitial-reviewsettings', tfa_results) is not None:
  144. self._downloader.report_warning(u'Your Google account has a security notice. Please log in on your web browser, resolve the notice, and try again.')
  145. return False
  146. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  147. self._downloader.report_warning(u'unable to log in: bad username or password')
  148. return False
  149. return True
  150. def _confirm_age(self):
  151. age_form = {
  152. 'next_url': '/',
  153. 'action_confirm': 'Confirm',
  154. }
  155. req = compat_urllib_request.Request(self._AGE_URL,
  156. compat_urllib_parse.urlencode(age_form).encode('ascii'))
  157. self._download_webpage(
  158. req, None,
  159. note=u'Confirming age', errnote=u'Unable to confirm age')
  160. return True
  161. def _real_initialize(self):
  162. if self._downloader is None:
  163. return
  164. if not self._set_language():
  165. return
  166. if not self._login():
  167. return
  168. self._confirm_age()
  169. class YoutubeIE(YoutubeBaseInfoExtractor, SubtitlesInfoExtractor):
  170. IE_DESC = 'YouTube.com'
  171. _VALID_URL = r"""(?x)^
  172. (
  173. (?:https?://|//) # http(s):// or protocol-independent URL
  174. (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
  175. (?:www\.)?deturl\.com/www\.youtube\.com/|
  176. (?:www\.)?pwnyoutube\.com/|
  177. (?:www\.)?yourepeat\.com/|
  178. tube\.majestyc\.net/|
  179. youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
  180. (?:.*?\#/)? # handle anchor (#/) redirect urls
  181. (?: # the various things that can precede the ID:
  182. (?:(?:v|embed|e)/) # v/ or embed/ or e/
  183. |(?: # or the v= param in all its forms
  184. (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  185. (?:\?|\#!?) # the params delimiter ? or # or #!
  186. (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
  187. v=
  188. )
  189. ))
  190. |youtu\.be/ # just youtu.be/xxxx
  191. |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
  192. )
  193. )? # all until now is optional -> you can pass the naked ID
  194. ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  195. (?!.*?&list=) # combined list/video URLs are handled by the playlist IE
  196. (?(1).+)? # if we found the ID, everything can follow
  197. $"""
  198. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  199. _formats = {
  200. '5': {'ext': 'flv', 'width': 400, 'height': 240},
  201. '6': {'ext': 'flv', 'width': 450, 'height': 270},
  202. '13': {'ext': '3gp'},
  203. '17': {'ext': '3gp', 'width': 176, 'height': 144},
  204. '18': {'ext': 'mp4', 'width': 640, 'height': 360},
  205. '22': {'ext': 'mp4', 'width': 1280, 'height': 720},
  206. '34': {'ext': 'flv', 'width': 640, 'height': 360},
  207. '35': {'ext': 'flv', 'width': 854, 'height': 480},
  208. '36': {'ext': '3gp', 'width': 320, 'height': 240},
  209. '37': {'ext': 'mp4', 'width': 1920, 'height': 1080},
  210. '38': {'ext': 'mp4', 'width': 4096, 'height': 3072},
  211. '43': {'ext': 'webm', 'width': 640, 'height': 360},
  212. '44': {'ext': 'webm', 'width': 854, 'height': 480},
  213. '45': {'ext': 'webm', 'width': 1280, 'height': 720},
  214. '46': {'ext': 'webm', 'width': 1920, 'height': 1080},
  215. # 3d videos
  216. '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'preference': -20},
  217. '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'preference': -20},
  218. '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'preference': -20},
  219. '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'preference': -20},
  220. '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'preference': -20},
  221. '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'preference': -20},
  222. '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'preference': -20},
  223. # Apple HTTP Live Streaming
  224. '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
  225. '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'preference': -10},
  226. '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'preference': -10},
  227. '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'preference': -10},
  228. '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'preference': -10},
  229. '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
  230. '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'preference': -10},
  231. # DASH mp4 video
  232. '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  233. '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  234. '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  235. '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  236. '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  237. '138': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  238. '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  239. '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  240. # Dash mp4 audio
  241. '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 48, 'preference': -50},
  242. '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 128, 'preference': -50},
  243. '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 256, 'preference': -50},
  244. # Dash webm
  245. '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  246. '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  247. '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  248. '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  249. '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  250. '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  251. '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  252. '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  253. '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  254. '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  255. '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  256. '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  257. '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  258. '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  259. '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  260. # Dash webm audio
  261. '171': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 128, 'preference': -50},
  262. '172': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 256, 'preference': -50},
  263. # RTMP (unnamed)
  264. '_rtmp': {'protocol': 'rtmp'},
  265. }
  266. IE_NAME = 'youtube'
  267. _TESTS = [
  268. {
  269. u"url": u"http://www.youtube.com/watch?v=BaW_jenozKc",
  270. u"file": u"BaW_jenozKc.mp4",
  271. u"info_dict": {
  272. u"title": u"youtube-dl test video \"'/\\ä↭𝕐",
  273. u"uploader": u"Philipp Hagemeister",
  274. u"uploader_id": u"phihag",
  275. u"upload_date": u"20121002",
  276. u"description": u"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. u"categories": [u'Science & Technology'],
  278. 'like_count': int,
  279. 'dislike_count': int,
  280. }
  281. },
  282. {
  283. u"url": u"http://www.youtube.com/watch?v=UxxajLWwzqY",
  284. u"file": u"UxxajLWwzqY.mp4",
  285. u"note": u"Test generic use_cipher_signature video (#897)",
  286. u"info_dict": {
  287. u"upload_date": u"20120506",
  288. u"title": u"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]",
  289. u"description": u"md5:fea86fda2d5a5784273df5c7cc994d9f",
  290. u"uploader": u"Icona Pop",
  291. u"uploader_id": u"IconaPop"
  292. }
  293. },
  294. {
  295. u"url": u"https://www.youtube.com/watch?v=07FYdnEawAQ",
  296. u"file": u"07FYdnEawAQ.mp4",
  297. u"note": u"Test VEVO video with age protection (#956)",
  298. u"info_dict": {
  299. u"upload_date": u"20130703",
  300. u"title": u"Justin Timberlake - Tunnel Vision (Explicit)",
  301. u"description": u"md5:64249768eec3bc4276236606ea996373",
  302. u"uploader": u"justintimberlakeVEVO",
  303. u"uploader_id": u"justintimberlakeVEVO"
  304. }
  305. },
  306. {
  307. u"url": u"//www.YouTube.com/watch?v=yZIXLfi8CZQ",
  308. u"file": u"yZIXLfi8CZQ.mp4",
  309. u"note": u"Embed-only video (#1746)",
  310. u"info_dict": {
  311. u"upload_date": u"20120608",
  312. u"title": u"Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012",
  313. u"description": u"md5:09b78bd971f1e3e289601dfba15ca4f7",
  314. u"uploader": u"SET India",
  315. u"uploader_id": u"setindia"
  316. }
  317. },
  318. {
  319. u"url": u"http://www.youtube.com/watch?v=a9LDPn-MO4I",
  320. u"file": u"a9LDPn-MO4I.m4a",
  321. u"note": u"256k DASH audio (format 141) via DASH manifest",
  322. u"info_dict": {
  323. u"upload_date": "20121002",
  324. u"uploader_id": "8KVIDEO",
  325. u"description": '',
  326. u"uploader": "8KVIDEO",
  327. u"title": "UHDTV TEST 8K VIDEO.mp4"
  328. },
  329. u"params": {
  330. u"youtube_include_dash_manifest": True,
  331. u"format": "141",
  332. },
  333. },
  334. # DASH manifest with encrypted signature
  335. {
  336. 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
  337. 'info_dict': {
  338. 'id': 'IB3lcPjvWLA',
  339. 'ext': 'm4a',
  340. 'title': 'Afrojack - The Spark ft. Spree Wilson',
  341. 'description': 'md5:9717375db5a9a3992be4668bbf3bc0a8',
  342. 'uploader': 'AfrojackVEVO',
  343. 'uploader_id': 'AfrojackVEVO',
  344. 'upload_date': '20131011',
  345. },
  346. u"params": {
  347. 'youtube_include_dash_manifest': True,
  348. 'format': '141',
  349. },
  350. },
  351. ]
  352. def __init__(self, *args, **kwargs):
  353. super(YoutubeIE, self).__init__(*args, **kwargs)
  354. self._player_cache = {}
  355. def report_video_info_webpage_download(self, video_id):
  356. """Report attempt to download video info webpage."""
  357. self.to_screen(u'%s: Downloading video info webpage' % video_id)
  358. def report_information_extraction(self, video_id):
  359. """Report attempt to extract video information."""
  360. self.to_screen(u'%s: Extracting video information' % video_id)
  361. def report_unavailable_format(self, video_id, format):
  362. """Report extracted video URL."""
  363. self.to_screen(u'%s: Format %s not available' % (video_id, format))
  364. def report_rtmp_download(self):
  365. """Indicate the download will use the RTMP protocol."""
  366. self.to_screen(u'RTMP download detected')
  367. def _signature_cache_id(self, example_sig):
  368. """ Return a string representation of a signature """
  369. return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
  370. def _extract_signature_function(self, video_id, player_url, example_sig):
  371. id_m = re.match(
  372. r'.*-(?P<id>[a-zA-Z0-9_-]+)(?:/watch_as3|/html5player)?\.(?P<ext>[a-z]+)$',
  373. player_url)
  374. if not id_m:
  375. raise ExtractorError('Cannot identify player %r' % player_url)
  376. player_type = id_m.group('ext')
  377. player_id = id_m.group('id')
  378. # Read from filesystem cache
  379. func_id = '%s_%s_%s' % (
  380. player_type, player_id, self._signature_cache_id(example_sig))
  381. assert os.path.basename(func_id) == func_id
  382. cache_spec = self._downloader.cache.load(u'youtube-sigfuncs', func_id)
  383. if cache_spec is not None:
  384. return lambda s: ''.join(s[i] for i in cache_spec)
  385. if player_type == 'js':
  386. code = self._download_webpage(
  387. player_url, video_id,
  388. note=u'Downloading %s player %s' % (player_type, player_id),
  389. errnote=u'Download of %s failed' % player_url)
  390. res = self._parse_sig_js(code)
  391. elif player_type == 'swf':
  392. urlh = self._request_webpage(
  393. player_url, video_id,
  394. note=u'Downloading %s player %s' % (player_type, player_id),
  395. errnote=u'Download of %s failed' % player_url)
  396. code = urlh.read()
  397. res = self._parse_sig_swf(code)
  398. else:
  399. assert False, 'Invalid player type %r' % player_type
  400. if cache_spec is None:
  401. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  402. cache_res = res(test_string)
  403. cache_spec = [ord(c) for c in cache_res]
  404. self._downloader.cache.store(u'youtube-sigfuncs', func_id, cache_spec)
  405. return res
  406. def _print_sig_code(self, func, example_sig):
  407. def gen_sig_code(idxs):
  408. def _genslice(start, end, step):
  409. starts = '' if start == 0 else str(start)
  410. ends = (u':%d' % (end+step)) if end + step >= 0 else ':'
  411. steps = '' if step == 1 else (u':%d' % step)
  412. return 's[%s%s%s]' % (starts, ends, steps)
  413. step = None
  414. start = '(Never used)' # Quelch pyflakes warnings - start will be
  415. # set as soon as step is set
  416. for i, prev in zip(idxs[1:], idxs[:-1]):
  417. if step is not None:
  418. if i - prev == step:
  419. continue
  420. yield _genslice(start, prev, step)
  421. step = None
  422. continue
  423. if i - prev in [-1, 1]:
  424. step = i - prev
  425. start = prev
  426. continue
  427. else:
  428. yield 's[%d]' % prev
  429. if step is None:
  430. yield 's[%d]' % i
  431. else:
  432. yield _genslice(start, i, step)
  433. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  434. cache_res = func(test_string)
  435. cache_spec = [ord(c) for c in cache_res]
  436. expr_code = ' + '.join(gen_sig_code(cache_spec))
  437. signature_id_tuple = '(%s)' % (
  438. ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
  439. code = (u'if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
  440. ' return %s\n') % (signature_id_tuple, expr_code)
  441. self.to_screen(u'Extracted signature function:\n' + code)
  442. def _parse_sig_js(self, jscode):
  443. funcname = self._search_regex(
  444. r'signature=([$a-zA-Z]+)', jscode,
  445. 'Initial JS player signature function name')
  446. jsi = JSInterpreter(jscode)
  447. initial_function = jsi.extract_function(funcname)
  448. return lambda s: initial_function([s])
  449. def _parse_sig_swf(self, file_contents):
  450. swfi = SWFInterpreter(file_contents)
  451. TARGET_CLASSNAME = 'SignatureDecipher'
  452. searched_class = swfi.extract_class(TARGET_CLASSNAME)
  453. initial_function = swfi.extract_function(searched_class, 'decipher')
  454. return lambda s: initial_function([s])
  455. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  456. """Turn the encrypted s field into a working signature"""
  457. if player_url is None:
  458. raise ExtractorError(u'Cannot decrypt signature without player_url')
  459. if player_url.startswith(u'//'):
  460. player_url = 'https:' + player_url
  461. try:
  462. player_id = (player_url, self._signature_cache_id(s))
  463. if player_id not in self._player_cache:
  464. func = self._extract_signature_function(
  465. video_id, player_url, s
  466. )
  467. self._player_cache[player_id] = func
  468. func = self._player_cache[player_id]
  469. if self._downloader.params.get('youtube_print_sig_code'):
  470. self._print_sig_code(func, s)
  471. return func(s)
  472. except Exception as e:
  473. tb = traceback.format_exc()
  474. raise ExtractorError(
  475. 'Signature extraction failed: ' + tb, cause=e)
  476. def _get_available_subtitles(self, video_id, webpage):
  477. try:
  478. sub_list = self._download_webpage(
  479. 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  480. video_id, note=False)
  481. except ExtractorError as err:
  482. self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
  483. return {}
  484. lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  485. sub_lang_list = {}
  486. for l in lang_list:
  487. lang = l[1]
  488. if lang in sub_lang_list:
  489. continue
  490. params = compat_urllib_parse.urlencode({
  491. 'lang': lang,
  492. 'v': video_id,
  493. 'fmt': self._downloader.params.get('subtitlesformat', 'srt'),
  494. 'name': unescapeHTML(l[0]).encode('utf-8'),
  495. })
  496. url = 'https://www.youtube.com/api/timedtext?' + params
  497. sub_lang_list[lang] = url
  498. if not sub_lang_list:
  499. self._downloader.report_warning(u'video doesn\'t have subtitles')
  500. return {}
  501. return sub_lang_list
  502. def _get_available_automatic_caption(self, video_id, webpage):
  503. """We need the webpage for getting the captions url, pass it as an
  504. argument to speed up the process."""
  505. sub_format = self._downloader.params.get('subtitlesformat', 'srt')
  506. self.to_screen(u'%s: Looking for automatic captions' % video_id)
  507. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  508. err_msg = 'Couldn\'t find automatic captions for %s' % video_id
  509. if mobj is None:
  510. self._downloader.report_warning(err_msg)
  511. return {}
  512. player_config = json.loads(mobj.group(1))
  513. try:
  514. args = player_config[u'args']
  515. caption_url = args[u'ttsurl']
  516. timestamp = args[u'timestamp']
  517. # We get the available subtitles
  518. list_params = compat_urllib_parse.urlencode({
  519. 'type': 'list',
  520. 'tlangs': 1,
  521. 'asrs': 1,
  522. })
  523. list_url = caption_url + '&' + list_params
  524. caption_list = self._download_xml(list_url, video_id)
  525. original_lang_node = caption_list.find('track')
  526. if original_lang_node is None or original_lang_node.attrib.get('kind') != 'asr' :
  527. self._downloader.report_warning(u'Video doesn\'t have automatic captions')
  528. return {}
  529. original_lang = original_lang_node.attrib['lang_code']
  530. sub_lang_list = {}
  531. for lang_node in caption_list.findall('target'):
  532. sub_lang = lang_node.attrib['lang_code']
  533. params = compat_urllib_parse.urlencode({
  534. 'lang': original_lang,
  535. 'tlang': sub_lang,
  536. 'fmt': sub_format,
  537. 'ts': timestamp,
  538. 'kind': 'asr',
  539. })
  540. sub_lang_list[sub_lang] = caption_url + '&' + params
  541. return sub_lang_list
  542. # An extractor error can be raise by the download process if there are
  543. # no automatic captions but there are subtitles
  544. except (KeyError, ExtractorError):
  545. self._downloader.report_warning(err_msg)
  546. return {}
  547. @classmethod
  548. def extract_id(cls, url):
  549. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  550. if mobj is None:
  551. raise ExtractorError(u'Invalid URL: %s' % url)
  552. video_id = mobj.group(2)
  553. return video_id
  554. def _extract_from_m3u8(self, manifest_url, video_id):
  555. url_map = {}
  556. def _get_urls(_manifest):
  557. lines = _manifest.split('\n')
  558. urls = filter(lambda l: l and not l.startswith('#'),
  559. lines)
  560. return urls
  561. manifest = self._download_webpage(manifest_url, video_id, 'Downloading formats manifest')
  562. formats_urls = _get_urls(manifest)
  563. for format_url in formats_urls:
  564. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  565. url_map[itag] = format_url
  566. return url_map
  567. def _extract_annotations(self, video_id):
  568. url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
  569. return self._download_webpage(url, video_id, note=u'Searching for annotations.', errnote=u'Unable to download video annotations.')
  570. def _real_extract(self, url):
  571. proto = (
  572. 'http' if self._downloader.params.get('prefer_insecure', False)
  573. else 'https')
  574. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  575. mobj = re.search(self._NEXT_URL_RE, url)
  576. if mobj:
  577. url = proto + '://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  578. video_id = self.extract_id(url)
  579. # Get video webpage
  580. url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  581. video_webpage = self._download_webpage(url, video_id)
  582. # Attempt to extract SWF player URL
  583. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  584. if mobj is not None:
  585. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  586. else:
  587. player_url = None
  588. # Get video info
  589. self.report_video_info_webpage_download(video_id)
  590. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  591. self.report_age_confirmation()
  592. age_gate = True
  593. # We simulate the access to the video from www.youtube.com/v/{video_id}
  594. # this can be viewed without login into Youtube
  595. data = compat_urllib_parse.urlencode({
  596. 'video_id': video_id,
  597. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  598. 'sts': self._search_regex(
  599. r'"sts"\s*:\s*(\d+)', video_webpage, 'sts'),
  600. })
  601. video_info_url = proto + '://www.youtube.com/get_video_info?' + data
  602. video_info_webpage = self._download_webpage(video_info_url, video_id,
  603. note=False,
  604. errnote='unable to download video info webpage')
  605. video_info = compat_parse_qs(video_info_webpage)
  606. else:
  607. age_gate = False
  608. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  609. video_info_url = (proto + '://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  610. % (video_id, el_type))
  611. video_info_webpage = self._download_webpage(video_info_url, video_id,
  612. note=False,
  613. errnote='unable to download video info webpage')
  614. video_info = compat_parse_qs(video_info_webpage)
  615. if 'token' in video_info:
  616. break
  617. if 'token' not in video_info:
  618. if 'reason' in video_info:
  619. raise ExtractorError(
  620. 'YouTube said: %s' % video_info['reason'][0],
  621. expected=True, video_id=video_id)
  622. else:
  623. raise ExtractorError(
  624. '"token" parameter not in video info for unknown reason',
  625. video_id=video_id)
  626. if 'view_count' in video_info:
  627. view_count = int(video_info['view_count'][0])
  628. else:
  629. view_count = None
  630. # Check for "rental" videos
  631. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  632. raise ExtractorError(u'"rental" videos not supported')
  633. # Start extracting information
  634. self.report_information_extraction(video_id)
  635. # uploader
  636. if 'author' not in video_info:
  637. raise ExtractorError(u'Unable to extract uploader name')
  638. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  639. # uploader_id
  640. video_uploader_id = None
  641. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  642. if mobj is not None:
  643. video_uploader_id = mobj.group(1)
  644. else:
  645. self._downloader.report_warning(u'unable to extract uploader nickname')
  646. # title
  647. if 'title' in video_info:
  648. video_title = video_info['title'][0]
  649. else:
  650. self._downloader.report_warning(u'Unable to extract video title')
  651. video_title = '_'
  652. # thumbnail image
  653. # We try first to get a high quality image:
  654. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  655. video_webpage, re.DOTALL)
  656. if m_thumb is not None:
  657. video_thumbnail = m_thumb.group(1)
  658. elif 'thumbnail_url' not in video_info:
  659. self._downloader.report_warning(u'unable to extract video thumbnail')
  660. video_thumbnail = None
  661. else: # don't panic if we can't find it
  662. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  663. # upload date
  664. upload_date = None
  665. mobj = re.search(r'(?s)id="eow-date.*?>(.*?)</span>', video_webpage)
  666. if mobj is None:
  667. mobj = re.search(
  668. r'(?s)id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live) on (.*?)</strong>',
  669. video_webpage)
  670. if mobj is not None:
  671. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  672. upload_date = unified_strdate(upload_date)
  673. m_cat_container = self._search_regex(
  674. r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>',
  675. video_webpage, 'categories', fatal=False)
  676. if m_cat_container:
  677. category = self._html_search_regex(
  678. r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
  679. default=None)
  680. video_categories = None if category is None else [category]
  681. else:
  682. video_categories = None
  683. # description
  684. video_description = get_element_by_id("eow-description", video_webpage)
  685. if video_description:
  686. video_description = re.sub(r'''(?x)
  687. <a\s+
  688. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  689. title="([^"]+)"\s+
  690. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  691. class="yt-uix-redirect-link"\s*>
  692. [^<]+
  693. </a>
  694. ''', r'\1', video_description)
  695. video_description = clean_html(video_description)
  696. else:
  697. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  698. if fd_mobj:
  699. video_description = unescapeHTML(fd_mobj.group(1))
  700. else:
  701. video_description = ''
  702. def _extract_count(count_name):
  703. count = self._search_regex(
  704. r'id="watch-%s"[^>]*>.*?([\d,]+)\s*</span>' % re.escape(count_name),
  705. video_webpage, count_name, default=None)
  706. if count is not None:
  707. return int(count.replace(',', ''))
  708. return None
  709. like_count = _extract_count(u'like')
  710. dislike_count = _extract_count(u'dislike')
  711. # subtitles
  712. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  713. if self._downloader.params.get('listsubtitles', False):
  714. self._list_available_subtitles(video_id, video_webpage)
  715. return
  716. if 'length_seconds' not in video_info:
  717. self._downloader.report_warning(u'unable to extract video duration')
  718. video_duration = None
  719. else:
  720. video_duration = int(compat_urllib_parse.unquote_plus(video_info['length_seconds'][0]))
  721. # annotations
  722. video_annotations = None
  723. if self._downloader.params.get('writeannotations', False):
  724. video_annotations = self._extract_annotations(video_id)
  725. # Decide which formats to download
  726. try:
  727. mobj = re.search(r';ytplayer\.config\s*=\s*({.*?});', video_webpage)
  728. if not mobj:
  729. raise ValueError('Could not find vevo ID')
  730. json_code = uppercase_escape(mobj.group(1))
  731. ytplayer_config = json.loads(json_code)
  732. args = ytplayer_config['args']
  733. # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
  734. # this signatures are encrypted
  735. if 'url_encoded_fmt_stream_map' not in args:
  736. raise ValueError(u'No stream_map present') # caught below
  737. re_signature = re.compile(r'[&,]s=')
  738. m_s = re_signature.search(args['url_encoded_fmt_stream_map'])
  739. if m_s is not None:
  740. self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
  741. video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
  742. m_s = re_signature.search(args.get('adaptive_fmts', ''))
  743. if m_s is not None:
  744. if 'adaptive_fmts' in video_info:
  745. video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts']
  746. else:
  747. video_info['adaptive_fmts'] = [args['adaptive_fmts']]
  748. except ValueError:
  749. pass
  750. def _map_to_format_list(urlmap):
  751. formats = []
  752. for itag, video_real_url in urlmap.items():
  753. dct = {
  754. 'format_id': itag,
  755. 'url': video_real_url,
  756. 'player_url': player_url,
  757. }
  758. if itag in self._formats:
  759. dct.update(self._formats[itag])
  760. formats.append(dct)
  761. return formats
  762. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  763. self.report_rtmp_download()
  764. formats = [{
  765. 'format_id': '_rtmp',
  766. 'protocol': 'rtmp',
  767. 'url': video_info['conn'][0],
  768. 'player_url': player_url,
  769. }]
  770. elif len(video_info.get('url_encoded_fmt_stream_map', [])) >= 1 or len(video_info.get('adaptive_fmts', [])) >= 1:
  771. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts',[''])[0]
  772. if 'rtmpe%3Dyes' in encoded_url_map:
  773. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  774. url_map = {}
  775. for url_data_str in encoded_url_map.split(','):
  776. url_data = compat_parse_qs(url_data_str)
  777. if 'itag' not in url_data or 'url' not in url_data:
  778. continue
  779. format_id = url_data['itag'][0]
  780. url = url_data['url'][0]
  781. if 'sig' in url_data:
  782. url += '&signature=' + url_data['sig'][0]
  783. elif 's' in url_data:
  784. encrypted_sig = url_data['s'][0]
  785. if not age_gate:
  786. jsplayer_url_json = self._search_regex(
  787. r'"assets":.+?"js":\s*("[^"]+")',
  788. video_webpage, 'JS player URL')
  789. player_url = json.loads(jsplayer_url_json)
  790. if player_url is None:
  791. player_url_json = self._search_regex(
  792. r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
  793. video_webpage, 'age gate player URL')
  794. player_url = json.loads(player_url_json)
  795. if self._downloader.params.get('verbose'):
  796. if player_url is None:
  797. player_version = 'unknown'
  798. player_desc = 'unknown'
  799. else:
  800. if player_url.endswith('swf'):
  801. player_version = self._search_regex(
  802. r'-(.+?)(?:/watch_as3)?\.swf$', player_url,
  803. 'flash player', fatal=False)
  804. player_desc = 'flash player %s' % player_version
  805. else:
  806. player_version = self._search_regex(
  807. r'html5player-([^/]+?)(?:/html5player)?\.js',
  808. player_url,
  809. 'html5 player', fatal=False)
  810. player_desc = 'html5 player %s' % player_version
  811. parts_sizes = self._signature_cache_id(encrypted_sig)
  812. self.to_screen(u'{%s} signature length %s, %s' %
  813. (format_id, parts_sizes, player_desc))
  814. signature = self._decrypt_signature(
  815. encrypted_sig, video_id, player_url, age_gate)
  816. url += '&signature=' + signature
  817. if 'ratebypass' not in url:
  818. url += '&ratebypass=yes'
  819. url_map[format_id] = url
  820. formats = _map_to_format_list(url_map)
  821. elif video_info.get('hlsvp'):
  822. manifest_url = video_info['hlsvp'][0]
  823. url_map = self._extract_from_m3u8(manifest_url, video_id)
  824. formats = _map_to_format_list(url_map)
  825. else:
  826. raise ExtractorError(u'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
  827. # Look for the DASH manifest
  828. if (self._downloader.params.get('youtube_include_dash_manifest', False)):
  829. try:
  830. # The DASH manifest used needs to be the one from the original video_webpage.
  831. # The one found in get_video_info seems to be using different signatures.
  832. # However, in the case of an age restriction there won't be any embedded dashmpd in the video_webpage.
  833. # Luckily, it seems, this case uses some kind of default signature (len == 86), so the
  834. # combination of get_video_info and the _static_decrypt_signature() decryption fallback will work here.
  835. if age_gate:
  836. dash_manifest_url = video_info.get('dashmpd')[0]
  837. else:
  838. dash_manifest_url = ytplayer_config['args']['dashmpd']
  839. def decrypt_sig(mobj):
  840. s = mobj.group(1)
  841. dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
  842. return '/signature/%s' % dec_s
  843. dash_manifest_url = re.sub(r'/s/([\w\.]+)', decrypt_sig, dash_manifest_url)
  844. dash_doc = self._download_xml(
  845. dash_manifest_url, video_id,
  846. note=u'Downloading DASH manifest',
  847. errnote=u'Could not download DASH manifest')
  848. for r in dash_doc.findall(u'.//{urn:mpeg:DASH:schema:MPD:2011}Representation'):
  849. url_el = r.find('{urn:mpeg:DASH:schema:MPD:2011}BaseURL')
  850. if url_el is None:
  851. continue
  852. format_id = r.attrib['id']
  853. video_url = url_el.text
  854. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength'))
  855. f = {
  856. 'format_id': format_id,
  857. 'url': video_url,
  858. 'width': int_or_none(r.attrib.get('width')),
  859. 'tbr': int_or_none(r.attrib.get('bandwidth'), 1000),
  860. 'asr': int_or_none(r.attrib.get('audioSamplingRate')),
  861. 'filesize': filesize,
  862. }
  863. try:
  864. existing_format = next(
  865. fo for fo in formats
  866. if fo['format_id'] == format_id)
  867. except StopIteration:
  868. f.update(self._formats.get(format_id, {}))
  869. formats.append(f)
  870. else:
  871. existing_format.update(f)
  872. except (ExtractorError, KeyError) as e:
  873. self.report_warning(u'Skipping DASH manifest: %s' % e, video_id)
  874. self._sort_formats(formats)
  875. return {
  876. 'id': video_id,
  877. 'uploader': video_uploader,
  878. 'uploader_id': video_uploader_id,
  879. 'upload_date': upload_date,
  880. 'title': video_title,
  881. 'thumbnail': video_thumbnail,
  882. 'description': video_description,
  883. 'categories': video_categories,
  884. 'subtitles': video_subtitles,
  885. 'duration': video_duration,
  886. 'age_limit': 18 if age_gate else 0,
  887. 'annotations': video_annotations,
  888. 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
  889. 'view_count': view_count,
  890. 'like_count': like_count,
  891. 'dislike_count': dislike_count,
  892. 'formats': formats,
  893. }
  894. class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
  895. IE_DESC = 'YouTube.com playlists'
  896. _VALID_URL = r"""(?x)(?:
  897. (?:https?://)?
  898. (?:\w+\.)?
  899. youtube\.com/
  900. (?:
  901. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  902. \? (?:.*?&)*? (?:p|a|list)=
  903. | p/
  904. )
  905. (
  906. (?:PL|LL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,}
  907. # Top tracks, they can also include dots
  908. |(?:MC)[\w\.]*
  909. )
  910. .*
  911. |
  912. ((?:PL|LL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,})
  913. )"""
  914. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
  915. _MORE_PAGES_INDICATOR = r'data-link-type="next"'
  916. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)'
  917. IE_NAME = 'youtube:playlist'
  918. _TESTS = [{
  919. 'url': 'https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  920. 'info_dict': {
  921. 'title': 'ytdl test PL',
  922. },
  923. 'playlist_count': 3,
  924. }, {
  925. 'url': 'https://www.youtube.com/playlist?list=PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  926. 'info_dict': {
  927. 'title': 'YDL_Empty_List',
  928. },
  929. 'playlist_count': 0,
  930. }, {
  931. 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
  932. 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  933. 'info_dict': {
  934. 'title': '29C3: Not my department',
  935. },
  936. 'playlist_count': 95,
  937. }, {
  938. 'note': 'issue #673',
  939. 'url': 'PLBB231211A4F62143',
  940. 'info_dict': {
  941. 'title': 'Team Fortress 2 (Class-based LP)',
  942. },
  943. 'playlist_mincount': 26,
  944. }, {
  945. 'note': 'Large playlist',
  946. 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
  947. 'info_dict': {
  948. 'title': 'Uploads from Cauchemar',
  949. },
  950. 'playlist_mincount': 799,
  951. }, {
  952. 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  953. 'info_dict': {
  954. 'title': 'YDL_safe_search',
  955. },
  956. 'playlist_count': 2,
  957. }]
  958. def _real_initialize(self):
  959. self._login()
  960. def _ids_to_results(self, ids):
  961. return [
  962. self.url_result(vid_id, 'Youtube', video_id=vid_id)
  963. for vid_id in ids]
  964. def _extract_mix(self, playlist_id):
  965. # The mixes are generated from a a single video
  966. # the id of the playlist is just 'RD' + video_id
  967. url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
  968. webpage = self._download_webpage(
  969. url, playlist_id, 'Downloading Youtube mix')
  970. search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
  971. title_span = (
  972. search_title('playlist-title') or
  973. search_title('title long-title') or
  974. search_title('title'))
  975. title = clean_html(title_span)
  976. ids = orderedSet(re.findall(
  977. r'''(?xs)data-video-username=".*?".*?
  978. href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id),
  979. webpage))
  980. url_results = self._ids_to_results(ids)
  981. return self.playlist_result(url_results, playlist_id, title)
  982. def _real_extract(self, url):
  983. # Extract playlist id
  984. mobj = re.match(self._VALID_URL, url)
  985. if mobj is None:
  986. raise ExtractorError(u'Invalid URL: %s' % url)
  987. playlist_id = mobj.group(1) or mobj.group(2)
  988. # Check if it's a video-specific URL
  989. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  990. if 'v' in query_dict:
  991. video_id = query_dict['v'][0]
  992. if self._downloader.params.get('noplaylist'):
  993. self.to_screen(u'Downloading just video %s because of --no-playlist' % video_id)
  994. return self.url_result(video_id, 'Youtube', video_id=video_id)
  995. else:
  996. self.to_screen(u'Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  997. if playlist_id.startswith('RD'):
  998. # Mixes require a custom extraction process
  999. return self._extract_mix(playlist_id)
  1000. if playlist_id.startswith('TL'):
  1001. raise ExtractorError(u'For downloading YouTube.com top lists, use '
  1002. 'the "yttoplist" keyword, for example "youtube-dl \'yttoplist:music:Top Tracks\'"', expected=True)
  1003. url = self._TEMPLATE_URL % playlist_id
  1004. page = self._download_webpage(url, playlist_id)
  1005. more_widget_html = content_html = page
  1006. # Check if the playlist exists or is private
  1007. if re.search(r'<div class="yt-alert-message">[^<]*?(The|This) playlist (does not exist|is private)[^<]*?</div>', page) is not None:
  1008. raise ExtractorError(
  1009. 'The playlist doesn\'t exist or is private, use --username or '
  1010. '--netrc to access it.',
  1011. expected=True)
  1012. # Extract the video ids from the playlist pages
  1013. ids = []
  1014. for page_num in itertools.count(1):
  1015. matches = re.finditer(self._VIDEO_RE, content_html)
  1016. # We remove the duplicates and the link with index 0
  1017. # (it's not the first video of the playlist)
  1018. new_ids = orderedSet(m.group('id') for m in matches if m.group('index') != '0')
  1019. ids.extend(new_ids)
  1020. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  1021. if not mobj:
  1022. break
  1023. more = self._download_json(
  1024. 'https://youtube.com/%s' % mobj.group('more'), playlist_id,
  1025. 'Downloading page #%s' % page_num,
  1026. transform_source=uppercase_escape)
  1027. content_html = more['content_html']
  1028. more_widget_html = more['load_more_widget_html']
  1029. playlist_title = self._html_search_regex(
  1030. r'(?s)<h1 class="pl-header-title[^"]*">\s*(.*?)\s*</h1>',
  1031. page, 'title')
  1032. url_results = self._ids_to_results(ids)
  1033. return self.playlist_result(url_results, playlist_id, playlist_title)
  1034. class YoutubeTopListIE(YoutubePlaylistIE):
  1035. IE_NAME = 'youtube:toplist'
  1036. IE_DESC = (u'YouTube.com top lists, "yttoplist:{channel}:{list title}"'
  1037. ' (Example: "yttoplist:music:Top Tracks")')
  1038. _VALID_URL = r'yttoplist:(?P<chann>.*?):(?P<title>.*?)$'
  1039. _TESTS = []
  1040. def _real_extract(self, url):
  1041. mobj = re.match(self._VALID_URL, url)
  1042. channel = mobj.group('chann')
  1043. title = mobj.group('title')
  1044. query = compat_urllib_parse.urlencode({'title': title})
  1045. playlist_re = 'href="([^"]+?%s.*?)"' % re.escape(query)
  1046. channel_page = self._download_webpage('https://www.youtube.com/%s' % channel, title)
  1047. link = self._html_search_regex(playlist_re, channel_page, 'list')
  1048. url = compat_urlparse.urljoin('https://www.youtube.com/', link)
  1049. video_re = r'data-index="\d+".*?data-video-id="([0-9A-Za-z_-]{11})"'
  1050. ids = []
  1051. # sometimes the webpage doesn't contain the videos
  1052. # retry until we get them
  1053. for i in itertools.count(0):
  1054. msg = 'Downloading Youtube mix'
  1055. if i > 0:
  1056. msg += ', retry #%d' % i
  1057. webpage = self._download_webpage(url, title, msg)
  1058. ids = orderedSet(re.findall(video_re, webpage))
  1059. if ids:
  1060. break
  1061. url_results = self._ids_to_results(ids)
  1062. return self.playlist_result(url_results, playlist_title=title)
  1063. class YoutubeChannelIE(InfoExtractor):
  1064. IE_DESC = 'YouTube.com channels'
  1065. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
  1066. _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
  1067. _MORE_PAGES_URL = 'https://www.youtube.com/c4_browse_ajax?action_load_more_videos=1&flow=list&paging=%s&view=0&sort=da&channel_id=%s'
  1068. IE_NAME = 'youtube:channel'
  1069. def extract_videos_from_page(self, page):
  1070. ids_in_page = []
  1071. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  1072. if mobj.group(1) not in ids_in_page:
  1073. ids_in_page.append(mobj.group(1))
  1074. return ids_in_page
  1075. def _real_extract(self, url):
  1076. # Extract channel id
  1077. mobj = re.match(self._VALID_URL, url)
  1078. if mobj is None:
  1079. raise ExtractorError(u'Invalid URL: %s' % url)
  1080. # Download channel page
  1081. channel_id = mobj.group(1)
  1082. video_ids = []
  1083. url = 'https://www.youtube.com/channel/%s/videos' % channel_id
  1084. channel_page = self._download_webpage(url, channel_id)
  1085. autogenerated = re.search(r'''(?x)
  1086. class="[^"]*?(?:
  1087. channel-header-autogenerated-label|
  1088. yt-channel-title-autogenerated
  1089. )[^"]*"''', channel_page) is not None
  1090. if autogenerated:
  1091. # The videos are contained in a single page
  1092. # the ajax pages can't be used, they are empty
  1093. video_ids = self.extract_videos_from_page(channel_page)
  1094. else:
  1095. # Download all channel pages using the json-based channel_ajax query
  1096. for pagenum in itertools.count(1):
  1097. url = self._MORE_PAGES_URL % (pagenum, channel_id)
  1098. page = self._download_json(
  1099. url, channel_id, note=u'Downloading page #%s' % pagenum,
  1100. transform_source=uppercase_escape)
  1101. ids_in_page = self.extract_videos_from_page(page['content_html'])
  1102. video_ids.extend(ids_in_page)
  1103. if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
  1104. break
  1105. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1106. url_entries = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1107. for video_id in video_ids]
  1108. return self.playlist_result(url_entries, channel_id)
  1109. class YoutubeUserIE(InfoExtractor):
  1110. IE_DESC = 'YouTube.com user videos (URL or "ytuser" keyword)'
  1111. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch|results)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
  1112. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/users/%s'
  1113. _GDATA_PAGE_SIZE = 50
  1114. _GDATA_URL = 'https://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
  1115. IE_NAME = 'youtube:user'
  1116. @classmethod
  1117. def suitable(cls, url):
  1118. # Don't return True if the url can be extracted with other youtube
  1119. # extractor, the regex would is too permissive and it would match.
  1120. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  1121. if any(ie.suitable(url) for ie in other_ies): return False
  1122. else: return super(YoutubeUserIE, cls).suitable(url)
  1123. def _real_extract(self, url):
  1124. # Extract username
  1125. mobj = re.match(self._VALID_URL, url)
  1126. if mobj is None:
  1127. raise ExtractorError(u'Invalid URL: %s' % url)
  1128. username = mobj.group(1)
  1129. # Download video ids using YouTube Data API. Result size per
  1130. # query is limited (currently to 50 videos) so we need to query
  1131. # page by page until there are no video ids - it means we got
  1132. # all of them.
  1133. def download_page(pagenum):
  1134. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1135. gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
  1136. page = self._download_webpage(
  1137. gdata_url, username,
  1138. 'Downloading video ids from %d to %d' % (
  1139. start_index, start_index + self._GDATA_PAGE_SIZE))
  1140. try:
  1141. response = json.loads(page)
  1142. except ValueError as err:
  1143. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  1144. if 'entry' not in response['feed']:
  1145. return
  1146. # Extract video identifiers
  1147. entries = response['feed']['entry']
  1148. for entry in entries:
  1149. title = entry['title']['$t']
  1150. video_id = entry['id']['$t'].split('/')[-1]
  1151. yield {
  1152. '_type': 'url',
  1153. 'url': video_id,
  1154. 'ie_key': 'Youtube',
  1155. 'id': video_id,
  1156. 'title': title,
  1157. }
  1158. url_results = PagedList(download_page, self._GDATA_PAGE_SIZE)
  1159. return self.playlist_result(url_results, playlist_title=username)
  1160. class YoutubeSearchIE(SearchInfoExtractor):
  1161. IE_DESC = 'YouTube.com searches'
  1162. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1163. _MAX_RESULTS = 1000
  1164. IE_NAME = 'youtube:search'
  1165. _SEARCH_KEY = 'ytsearch'
  1166. def _get_n_results(self, query, n):
  1167. """Get a specified number of results for a query"""
  1168. video_ids = []
  1169. pagenum = 0
  1170. limit = n
  1171. PAGE_SIZE = 50
  1172. while (PAGE_SIZE * pagenum) < limit:
  1173. result_url = self._API_URL % (
  1174. compat_urllib_parse.quote_plus(query.encode('utf-8')),
  1175. (PAGE_SIZE * pagenum) + 1)
  1176. data_json = self._download_webpage(
  1177. result_url, video_id=u'query "%s"' % query,
  1178. note=u'Downloading page %s' % (pagenum + 1),
  1179. errnote=u'Unable to download API page')
  1180. data = json.loads(data_json)
  1181. api_response = data['data']
  1182. if 'items' not in api_response:
  1183. raise ExtractorError(
  1184. '[youtube] No video results', expected=True)
  1185. new_ids = list(video['id'] for video in api_response['items'])
  1186. video_ids += new_ids
  1187. limit = min(n, api_response['totalItems'])
  1188. pagenum += 1
  1189. if len(video_ids) > n:
  1190. video_ids = video_ids[:n]
  1191. videos = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1192. for video_id in video_ids]
  1193. return self.playlist_result(videos, query)
  1194. class YoutubeSearchDateIE(YoutubeSearchIE):
  1195. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  1196. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc&orderby=published'
  1197. _SEARCH_KEY = 'ytsearchdate'
  1198. IE_DESC = 'YouTube.com searches, newest videos first'
  1199. class YoutubeSearchURLIE(InfoExtractor):
  1200. IE_DESC = 'YouTube.com search URLs'
  1201. IE_NAME = 'youtube:search_url'
  1202. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?search_query=(?P<query>[^&]+)(?:[&]|$)'
  1203. def _real_extract(self, url):
  1204. mobj = re.match(self._VALID_URL, url)
  1205. query = compat_urllib_parse.unquote_plus(mobj.group('query'))
  1206. webpage = self._download_webpage(url, query)
  1207. result_code = self._search_regex(
  1208. r'(?s)<ol class="item-section"(.*?)</ol>', webpage, 'result HTML')
  1209. part_codes = re.findall(
  1210. r'(?s)<h3 class="yt-lockup-title">(.*?)</h3>', result_code)
  1211. entries = []
  1212. for part_code in part_codes:
  1213. part_title = self._html_search_regex(
  1214. [r'(?s)title="([^"]+)"', r'>([^<]+)</a>'], part_code, 'item title', fatal=False)
  1215. part_url_snippet = self._html_search_regex(
  1216. r'(?s)href="([^"]+)"', part_code, 'item URL')
  1217. part_url = compat_urlparse.urljoin(
  1218. 'https://www.youtube.com/', part_url_snippet)
  1219. entries.append({
  1220. '_type': 'url',
  1221. 'url': part_url,
  1222. 'title': part_title,
  1223. })
  1224. return {
  1225. '_type': 'playlist',
  1226. 'entries': entries,
  1227. 'title': query,
  1228. }
  1229. class YoutubeShowIE(InfoExtractor):
  1230. IE_DESC = 'YouTube.com (multi-season) shows'
  1231. _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
  1232. IE_NAME = 'youtube:show'
  1233. def _real_extract(self, url):
  1234. mobj = re.match(self._VALID_URL, url)
  1235. show_name = mobj.group(1)
  1236. webpage = self._download_webpage(url, show_name, 'Downloading show webpage')
  1237. # There's one playlist for each season of the show
  1238. m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
  1239. self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
  1240. return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
  1241. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  1242. """
  1243. Base class for extractors that fetch info from
  1244. http://www.youtube.com/feed_ajax
  1245. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  1246. """
  1247. _LOGIN_REQUIRED = True
  1248. # use action_load_personal_feed instead of action_load_system_feed
  1249. _PERSONAL_FEED = False
  1250. @property
  1251. def _FEED_TEMPLATE(self):
  1252. action = 'action_load_system_feed'
  1253. if self._PERSONAL_FEED:
  1254. action = 'action_load_personal_feed'
  1255. return 'https://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
  1256. @property
  1257. def IE_NAME(self):
  1258. return 'youtube:%s' % self._FEED_NAME
  1259. def _real_initialize(self):
  1260. self._login()
  1261. def _real_extract(self, url):
  1262. feed_entries = []
  1263. paging = 0
  1264. for i in itertools.count(1):
  1265. info = self._download_json(self._FEED_TEMPLATE % paging,
  1266. '%s feed' % self._FEED_NAME,
  1267. 'Downloading page %s' % i)
  1268. feed_html = info.get('feed_html') or info.get('content_html')
  1269. load_more_widget_html = info.get('load_more_widget_html') or feed_html
  1270. m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
  1271. ids = orderedSet(m.group(1) for m in m_ids)
  1272. feed_entries.extend(
  1273. self.url_result(video_id, 'Youtube', video_id=video_id)
  1274. for video_id in ids)
  1275. mobj = re.search(
  1276. r'data-uix-load-more-href="/?[^"]+paging=(?P<paging>\d+)',
  1277. load_more_widget_html)
  1278. if mobj is None:
  1279. break
  1280. paging = mobj.group('paging')
  1281. return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
  1282. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  1283. IE_DESC = 'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
  1284. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  1285. _FEED_NAME = 'recommended'
  1286. _PLAYLIST_TITLE = 'Youtube Recommended videos'
  1287. class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
  1288. IE_DESC = 'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
  1289. _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
  1290. _FEED_NAME = 'watch_later'
  1291. _PLAYLIST_TITLE = 'Youtube Watch Later'
  1292. _PERSONAL_FEED = True
  1293. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  1294. IE_DESC = 'Youtube watch history, "ythistory" keyword (requires authentication)'
  1295. _VALID_URL = 'https?://www\.youtube\.com/feed/history|:ythistory'
  1296. _FEED_NAME = 'history'
  1297. _PERSONAL_FEED = True
  1298. _PLAYLIST_TITLE = 'Youtube Watch History'
  1299. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  1300. IE_NAME = 'youtube:favorites'
  1301. IE_DESC = 'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
  1302. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  1303. _LOGIN_REQUIRED = True
  1304. def _real_extract(self, url):
  1305. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  1306. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, 'favourites playlist id')
  1307. return self.url_result(playlist_id, 'YoutubePlaylist')
  1308. class YoutubeSubscriptionsIE(YoutubePlaylistIE):
  1309. IE_NAME = 'youtube:subscriptions'
  1310. IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  1311. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  1312. _TESTS = []
  1313. def _real_extract(self, url):
  1314. title = 'Youtube Subscriptions'
  1315. page = self._download_webpage('https://www.youtube.com/feed/subscriptions', title)
  1316. # The extraction process is the same as for playlists, but the regex
  1317. # for the video ids doesn't contain an index
  1318. ids = []
  1319. more_widget_html = content_html = page
  1320. for page_num in itertools.count(1):
  1321. matches = re.findall(r'href="\s*/watch\?v=([0-9A-Za-z_-]{11})', content_html)
  1322. new_ids = orderedSet(matches)
  1323. ids.extend(new_ids)
  1324. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  1325. if not mobj:
  1326. break
  1327. more = self._download_json(
  1328. 'https://youtube.com/%s' % mobj.group('more'), title,
  1329. 'Downloading page #%s' % page_num,
  1330. transform_source=uppercase_escape)
  1331. content_html = more['content_html']
  1332. more_widget_html = more['load_more_widget_html']
  1333. return {
  1334. '_type': 'playlist',
  1335. 'title': title,
  1336. 'entries': self._ids_to_results(ids),
  1337. }
  1338. class YoutubeTruncatedURLIE(InfoExtractor):
  1339. IE_NAME = 'youtube:truncated_url'
  1340. IE_DESC = False # Do not list
  1341. _VALID_URL = r'''(?x)
  1342. (?:https?://)?[^/]+/watch\?(?:
  1343. feature=[a-z_]+|
  1344. annotation_id=annotation_[^&]+
  1345. )?$|
  1346. (?:https?://)?(?:www\.)?youtube\.com/attribution_link\?a=[^&]+$
  1347. '''
  1348. _TESTS = [{
  1349. 'url': 'http://www.youtube.com/watch?annotation_id=annotation_3951667041',
  1350. 'only_matching': True,
  1351. }, {
  1352. 'url': 'http://www.youtube.com/watch?',
  1353. 'only_matching': True,
  1354. }]
  1355. def _real_extract(self, url):
  1356. raise ExtractorError(
  1357. 'Did you forget to quote the URL? Remember that & is a meta '
  1358. 'character in most shells, so you want to put the URL in quotes, '
  1359. 'like youtube-dl '
  1360. '"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  1361. ' or simply youtube-dl BaW_jenozKc .',
  1362. expected=True)