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.

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