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.

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