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.

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