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.

1636 lines
71 KiB

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