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.

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