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.

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