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.

1668 lines
73 KiB

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