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.

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