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.

1508 lines
67 KiB

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