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.

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