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.

1633 lines
72 KiB

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