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.

1497 lines
67 KiB

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