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.

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