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.

1632 lines
71 KiB

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