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.

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