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.

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