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.

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