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.

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