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.

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