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.

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