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.

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