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.

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