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.

1771 lines
77 KiB

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