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.

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