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.

1142 lines
49 KiB

11 years ago
11 years ago
11 years ago
11 years ago
  1. # coding: utf-8
  2. import json
  3. import netrc
  4. import re
  5. import socket
  6. import itertools
  7. from .common import InfoExtractor, SearchInfoExtractor
  8. from .subtitles import SubtitlesInfoExtractor
  9. from ..utils import (
  10. compat_http_client,
  11. compat_parse_qs,
  12. compat_urllib_error,
  13. compat_urllib_parse,
  14. compat_urllib_request,
  15. compat_str,
  16. clean_html,
  17. get_element_by_id,
  18. ExtractorError,
  19. unescapeHTML,
  20. unified_strdate,
  21. orderedSet,
  22. )
  23. class YoutubeBaseInfoExtractor(InfoExtractor):
  24. """Provide base functions for Youtube extractors"""
  25. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  26. _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  27. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  28. _NETRC_MACHINE = 'youtube'
  29. # If True it will raise an error if no login info is provided
  30. _LOGIN_REQUIRED = False
  31. def report_lang(self):
  32. """Report attempt to set language."""
  33. self.to_screen(u'Setting language')
  34. def _set_language(self):
  35. request = compat_urllib_request.Request(self._LANG_URL)
  36. try:
  37. self.report_lang()
  38. compat_urllib_request.urlopen(request).read()
  39. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  40. self._downloader.report_warning(u'unable to set language: %s' % compat_str(err))
  41. return False
  42. return True
  43. def _login(self):
  44. (username, password) = self._get_login_info()
  45. # No authentication to be performed
  46. if username is None:
  47. if self._LOGIN_REQUIRED:
  48. raise ExtractorError(u'No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  49. return False
  50. request = compat_urllib_request.Request(self._LOGIN_URL)
  51. try:
  52. login_page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  53. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  54. self._downloader.report_warning(u'unable to fetch login page: %s' % compat_str(err))
  55. return False
  56. galx = None
  57. dsh = None
  58. match = re.search(re.compile(r'<input.+?name="GALX".+?value="(.+?)"', re.DOTALL), login_page)
  59. if match:
  60. galx = match.group(1)
  61. match = re.search(re.compile(r'<input.+?name="dsh".+?value="(.+?)"', re.DOTALL), login_page)
  62. if match:
  63. dsh = match.group(1)
  64. # Log in
  65. login_form_strs = {
  66. u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  67. u'Email': username,
  68. u'GALX': galx,
  69. u'Passwd': password,
  70. u'PersistentCookie': u'yes',
  71. u'_utf8': u'',
  72. u'bgresponse': u'js_disabled',
  73. u'checkConnection': u'',
  74. u'checkedDomains': u'youtube',
  75. u'dnConn': u'',
  76. u'dsh': dsh,
  77. u'pstMsg': u'0',
  78. u'rmShown': u'1',
  79. u'secTok': u'',
  80. u'signIn': u'Sign in',
  81. u'timeStmp': u'',
  82. u'service': u'youtube',
  83. u'uilel': u'3',
  84. u'hl': u'en_US',
  85. }
  86. # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
  87. # chokes on unicode
  88. login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
  89. login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
  90. request = compat_urllib_request.Request(self._LOGIN_URL, login_data)
  91. try:
  92. self.report_login()
  93. login_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  94. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  95. self._downloader.report_warning(u'unable to log in: bad username or password')
  96. return False
  97. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  98. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  99. return False
  100. return True
  101. def _confirm_age(self):
  102. age_form = {
  103. 'next_url': '/',
  104. 'action_confirm': 'Confirm',
  105. }
  106. request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
  107. try:
  108. self.report_age_confirmation()
  109. compat_urllib_request.urlopen(request).read().decode('utf-8')
  110. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  111. raise ExtractorError(u'Unable to confirm age: %s' % compat_str(err))
  112. return True
  113. def _real_initialize(self):
  114. if self._downloader is None:
  115. return
  116. if not self._set_language():
  117. return
  118. if not self._login():
  119. return
  120. self._confirm_age()
  121. class YoutubeIE(YoutubeBaseInfoExtractor, SubtitlesInfoExtractor):
  122. IE_DESC = u'YouTube.com'
  123. _VALID_URL = r"""^
  124. (
  125. (?:https?://)? # http(s):// (optional)
  126. (?:(?:(?:(?:\w+\.)?youtube(?:-nocookie)?\.com/|
  127. tube\.majestyc\.net/) # the various hostnames, with wildcard subdomains
  128. (?:.*?\#/)? # handle anchor (#/) redirect urls
  129. (?: # the various things that can precede the ID:
  130. (?:(?:v|embed|e)/) # v/ or embed/ or e/
  131. |(?: # or the v= param in all its forms
  132. (?:(?:watch|movie)(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  133. (?:\?|\#!?) # the params delimiter ? or # or #!
  134. (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
  135. v=
  136. )
  137. ))
  138. |youtu\.be/ # just youtu.be/xxxx
  139. )
  140. )? # all until now is optional -> you can pass the naked ID
  141. ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  142. (?(1).+)? # if we found the ID, everything can follow
  143. $"""
  144. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  145. # Listed in order of quality
  146. _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '36', '17', '13',
  147. # Apple HTTP Live Streaming
  148. '96', '95', '94', '93', '92', '132', '151',
  149. # 3D
  150. '85', '84', '102', '83', '101', '82', '100',
  151. # Dash video
  152. '138', '137', '248', '136', '247', '135', '246',
  153. '245', '244', '134', '243', '133', '242', '160',
  154. # Dash audio
  155. '141', '172', '140', '171', '139',
  156. ]
  157. _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '36', '17', '13',
  158. # Apple HTTP Live Streaming
  159. '96', '95', '94', '93', '92', '132', '151',
  160. # 3D
  161. '85', '102', '84', '101', '83', '100', '82',
  162. # Dash video
  163. '138', '248', '137', '247', '136', '246', '245',
  164. '244', '135', '243', '134', '242', '133', '160',
  165. # Dash audio
  166. '172', '141', '171', '140', '139',
  167. ]
  168. _video_formats_map = {
  169. 'flv': ['35', '34', '6', '5'],
  170. '3gp': ['36', '17', '13'],
  171. 'mp4': ['38', '37', '22', '18'],
  172. 'webm': ['46', '45', '44', '43'],
  173. }
  174. _video_extensions = {
  175. '13': '3gp',
  176. '17': '3gp',
  177. '18': 'mp4',
  178. '22': 'mp4',
  179. '36': '3gp',
  180. '37': 'mp4',
  181. '38': 'mp4',
  182. '43': 'webm',
  183. '44': 'webm',
  184. '45': 'webm',
  185. '46': 'webm',
  186. # 3d videos
  187. '82': 'mp4',
  188. '83': 'mp4',
  189. '84': 'mp4',
  190. '85': 'mp4',
  191. '100': 'webm',
  192. '101': 'webm',
  193. '102': 'webm',
  194. # Apple HTTP Live Streaming
  195. '92': 'mp4',
  196. '93': 'mp4',
  197. '94': 'mp4',
  198. '95': 'mp4',
  199. '96': 'mp4',
  200. '132': 'mp4',
  201. '151': 'mp4',
  202. # Dash mp4
  203. '133': 'mp4',
  204. '134': 'mp4',
  205. '135': 'mp4',
  206. '136': 'mp4',
  207. '137': 'mp4',
  208. '138': 'mp4',
  209. '139': 'mp4',
  210. '140': 'mp4',
  211. '141': 'mp4',
  212. '160': 'mp4',
  213. # Dash webm
  214. '171': 'webm',
  215. '172': 'webm',
  216. '242': 'webm',
  217. '243': 'webm',
  218. '244': 'webm',
  219. '245': 'webm',
  220. '246': 'webm',
  221. '247': 'webm',
  222. '248': 'webm',
  223. }
  224. _video_dimensions = {
  225. '5': '240x400',
  226. '6': '???',
  227. '13': '???',
  228. '17': '144x176',
  229. '18': '360x640',
  230. '22': '720x1280',
  231. '34': '360x640',
  232. '35': '480x854',
  233. '36': '240x320',
  234. '37': '1080x1920',
  235. '38': '3072x4096',
  236. '43': '360x640',
  237. '44': '480x854',
  238. '45': '720x1280',
  239. '46': '1080x1920',
  240. '82': '360p',
  241. '83': '480p',
  242. '84': '720p',
  243. '85': '1080p',
  244. '92': '240p',
  245. '93': '360p',
  246. '94': '480p',
  247. '95': '720p',
  248. '96': '1080p',
  249. '100': '360p',
  250. '101': '480p',
  251. '102': '720p',
  252. '132': '240p',
  253. '151': '72p',
  254. '133': '240p',
  255. '134': '360p',
  256. '135': '480p',
  257. '136': '720p',
  258. '137': '1080p',
  259. '138': '>1080p',
  260. '139': '48k',
  261. '140': '128k',
  262. '141': '256k',
  263. '160': '192p',
  264. '171': '128k',
  265. '172': '256k',
  266. '242': '240p',
  267. '243': '360p',
  268. '244': '480p',
  269. '245': '480p',
  270. '246': '480p',
  271. '247': '720p',
  272. '248': '1080p',
  273. }
  274. _special_itags = {
  275. '82': '3D',
  276. '83': '3D',
  277. '84': '3D',
  278. '85': '3D',
  279. '100': '3D',
  280. '101': '3D',
  281. '102': '3D',
  282. '133': 'DASH Video',
  283. '134': 'DASH Video',
  284. '135': 'DASH Video',
  285. '136': 'DASH Video',
  286. '137': 'DASH Video',
  287. '138': 'DASH Video',
  288. '139': 'DASH Audio',
  289. '140': 'DASH Audio',
  290. '141': 'DASH Audio',
  291. '160': 'DASH Video',
  292. '171': 'DASH Audio',
  293. '172': 'DASH Audio',
  294. '242': 'DASH Video',
  295. '243': 'DASH Video',
  296. '244': 'DASH Video',
  297. '245': 'DASH Video',
  298. '246': 'DASH Video',
  299. '247': 'DASH Video',
  300. '248': 'DASH Video',
  301. }
  302. IE_NAME = u'youtube'
  303. _TESTS = [
  304. {
  305. u"url": u"http://www.youtube.com/watch?v=BaW_jenozKc",
  306. u"file": u"BaW_jenozKc.mp4",
  307. u"info_dict": {
  308. u"title": u"youtube-dl test video \"'/\\ä↭𝕐",
  309. u"uploader": u"Philipp Hagemeister",
  310. u"uploader_id": u"phihag",
  311. u"upload_date": u"20121002",
  312. u"description": u"test chars: \"'/\\ä↭𝕐\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de ."
  313. }
  314. },
  315. {
  316. u"url": u"http://www.youtube.com/watch?v=1ltcDfZMA3U",
  317. u"file": u"1ltcDfZMA3U.flv",
  318. u"note": u"Test VEVO video (#897)",
  319. u"info_dict": {
  320. u"upload_date": u"20070518",
  321. u"title": u"Maps - It Will Find You",
  322. u"description": u"Music video by Maps performing It Will Find You.",
  323. u"uploader": u"MuteUSA",
  324. u"uploader_id": u"MuteUSA"
  325. }
  326. },
  327. {
  328. u"url": u"http://www.youtube.com/watch?v=UxxajLWwzqY",
  329. u"file": u"UxxajLWwzqY.mp4",
  330. u"note": u"Test generic use_cipher_signature video (#897)",
  331. u"info_dict": {
  332. u"upload_date": u"20120506",
  333. u"title": u"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]",
  334. u"description": u"md5:3e2666e0a55044490499ea45fe9037b7",
  335. u"uploader": u"Icona Pop",
  336. u"uploader_id": u"IconaPop"
  337. }
  338. },
  339. {
  340. u"url": u"https://www.youtube.com/watch?v=07FYdnEawAQ",
  341. u"file": u"07FYdnEawAQ.mp4",
  342. u"note": u"Test VEVO video with age protection (#956)",
  343. u"info_dict": {
  344. u"upload_date": u"20130703",
  345. u"title": u"Justin Timberlake - Tunnel Vision (Explicit)",
  346. u"description": u"md5:64249768eec3bc4276236606ea996373",
  347. u"uploader": u"justintimberlakeVEVO",
  348. u"uploader_id": u"justintimberlakeVEVO"
  349. }
  350. },
  351. {
  352. u'url': u'https://www.youtube.com/watch?v=TGi3HqYrWHE',
  353. u'file': u'TGi3HqYrWHE.mp4',
  354. u'note': u'm3u8 video',
  355. u'info_dict': {
  356. u'title': u'Triathlon - Men - London 2012 Olympic Games',
  357. u'description': u'- Men - TR02 - Triathlon - 07 August 2012 - London 2012 Olympic Games',
  358. u'uploader': u'olympic',
  359. u'upload_date': u'20120807',
  360. u'uploader_id': u'olympic',
  361. },
  362. u'params': {
  363. u'skip_download': True,
  364. },
  365. },
  366. ]
  367. @classmethod
  368. def suitable(cls, url):
  369. """Receives a URL and returns True if suitable for this IE."""
  370. if YoutubePlaylistIE.suitable(url): return False
  371. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  372. def report_video_webpage_download(self, video_id):
  373. """Report attempt to download video webpage."""
  374. self.to_screen(u'%s: Downloading video webpage' % video_id)
  375. def report_video_info_webpage_download(self, video_id):
  376. """Report attempt to download video info webpage."""
  377. self.to_screen(u'%s: Downloading video info webpage' % video_id)
  378. def report_information_extraction(self, video_id):
  379. """Report attempt to extract video information."""
  380. self.to_screen(u'%s: Extracting video information' % video_id)
  381. def report_unavailable_format(self, video_id, format):
  382. """Report extracted video URL."""
  383. self.to_screen(u'%s: Format %s not available' % (video_id, format))
  384. def report_rtmp_download(self):
  385. """Indicate the download will use the RTMP protocol."""
  386. self.to_screen(u'RTMP download detected')
  387. def _decrypt_signature(self, s):
  388. """Turn the encrypted s field into a working signature"""
  389. if len(s) == 92:
  390. return s[25] + s[3:25] + s[0] + s[26:42] + s[79] + s[43:79] + s[91] + s[80:83]
  391. elif len(s) == 90:
  392. return s[25] + s[3:25] + s[2] + s[26:40] + s[77] + s[41:77] + s[89] + s[78:81]
  393. elif len(s) == 89:
  394. return s[84:78:-1] + s[87] + s[77:60:-1] + s[0] + s[59:3:-1]
  395. elif len(s) == 88:
  396. return s[7:28] + s[87] + s[29:45] + s[55] + s[46:55] + s[2] + s[56:87] + s[28]
  397. elif len(s) == 87:
  398. return s[6:27] + s[4] + s[28:39] + s[27] + s[40:59] + s[2] + s[60:]
  399. elif len(s) == 86:
  400. return s[5:34] + s[0] + s[35:38] + s[3] + s[39:45] + s[38] + s[46:53] + s[73] + s[54:73] + s[85] + s[74:85] + s[53]
  401. elif len(s) == 85:
  402. return s[40] + s[82:43:-1] + s[22] + s[42:40:-1] + s[83] + s[39:22:-1] + s[0] + s[21:2:-1]
  403. elif len(s) == 84:
  404. return s[81:36:-1] + s[0] + s[35:2:-1]
  405. elif len(s) == 83:
  406. return s[81:64:-1] + s[82] + s[63:52:-1] + s[45] + s[51:45:-1] + s[1] + s[44:1:-1] + s[0]
  407. elif len(s) == 82:
  408. return s[1:19] + s[0] + s[20:68] + s[19] + s[69:82]
  409. elif len(s) == 81:
  410. return s[56] + s[79:56:-1] + s[41] + s[55:41:-1] + s[80] + s[40:34:-1] + s[0] + s[33:29:-1] + s[34] + s[28:9:-1] + s[29] + s[8:0:-1] + s[9]
  411. elif len(s) == 80:
  412. return s[1:19] + s[0] + s[20:68] + s[19] + s[69:80]
  413. elif len(s) == 79:
  414. return s[54] + s[77:54:-1] + s[39] + s[53:39:-1] + s[78] + s[38:34:-1] + s[0] + s[33:29:-1] + s[34] + s[28:9:-1] + s[29] + s[8:0:-1] + s[9]
  415. else:
  416. raise ExtractorError(u'Unable to decrypt signature, key length %d not supported; retrying might work' % (len(s)))
  417. def _decrypt_signature_age_gate(self, s):
  418. # The videos with age protection use another player, so the algorithms
  419. # can be different.
  420. if len(s) == 86:
  421. return s[2:63] + s[82] + s[64:82] + s[63]
  422. else:
  423. # Fallback to the other algortihms
  424. return self._decrypt_signature(s)
  425. def _get_available_subtitles(self, video_id):
  426. try:
  427. sub_list = self._download_webpage(
  428. 'http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  429. video_id, note=False)
  430. except ExtractorError as err:
  431. self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
  432. return {}
  433. lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  434. sub_lang_list = {}
  435. for l in lang_list:
  436. lang = l[1]
  437. params = compat_urllib_parse.urlencode({
  438. 'lang': lang,
  439. 'v': video_id,
  440. 'fmt': self._downloader.params.get('subtitlesformat'),
  441. })
  442. url = u'http://www.youtube.com/api/timedtext?' + params
  443. sub_lang_list[lang] = url
  444. if not sub_lang_list:
  445. self._downloader.report_warning(u'video doesn\'t have subtitles')
  446. return {}
  447. return sub_lang_list
  448. def _request_automatic_caption(self, video_id, webpage):
  449. """We need the webpage for getting the captions url, pass it as an
  450. argument to speed up the process."""
  451. sub_lang = (self._downloader.params.get('subtitleslangs') or ['en'])[0]
  452. sub_format = self._downloader.params.get('subtitlesformat')
  453. self.to_screen(u'%s: Looking for automatic captions' % video_id)
  454. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  455. err_msg = u'Couldn\'t find automatic captions for "%s"' % sub_lang
  456. if mobj is None:
  457. self._downloader.report_warning(err_msg)
  458. return {}
  459. player_config = json.loads(mobj.group(1))
  460. try:
  461. args = player_config[u'args']
  462. caption_url = args[u'ttsurl']
  463. timestamp = args[u'timestamp']
  464. params = compat_urllib_parse.urlencode({
  465. 'lang': 'en',
  466. 'tlang': sub_lang,
  467. 'fmt': sub_format,
  468. 'ts': timestamp,
  469. 'kind': 'asr',
  470. })
  471. subtitles_url = caption_url + '&' + params
  472. sub = self._download_webpage(subtitles_url, video_id, u'Downloading automatic captions')
  473. return {sub_lang: sub}
  474. # An extractor error can be raise by the download process if there are
  475. # no automatic captions but there are subtitles
  476. except (KeyError, ExtractorError):
  477. self._downloader.report_warning(err_msg)
  478. return {}
  479. def _print_formats(self, formats):
  480. print('Available formats:')
  481. for x in formats:
  482. print('%s\t:\t%s\t[%s]%s' %(x, self._video_extensions.get(x, 'flv'),
  483. self._video_dimensions.get(x, '???'),
  484. ' ('+self._special_itags[x]+')' if x in self._special_itags else ''))
  485. def _extract_id(self, url):
  486. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  487. if mobj is None:
  488. raise ExtractorError(u'Invalid URL: %s' % url)
  489. video_id = mobj.group(2)
  490. return video_id
  491. def _get_video_url_list(self, url_map):
  492. """
  493. Transform a dictionary in the format {itag:url} to a list of (itag, url)
  494. with the requested formats.
  495. """
  496. req_format = self._downloader.params.get('format', None)
  497. format_limit = self._downloader.params.get('format_limit', None)
  498. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  499. if format_limit is not None and format_limit in available_formats:
  500. format_list = available_formats[available_formats.index(format_limit):]
  501. else:
  502. format_list = available_formats
  503. existing_formats = [x for x in format_list if x in url_map]
  504. if len(existing_formats) == 0:
  505. raise ExtractorError(u'no known formats available for video')
  506. if self._downloader.params.get('listformats', None):
  507. self._print_formats(existing_formats)
  508. return
  509. if req_format is None or req_format == 'best':
  510. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  511. elif req_format == 'worst':
  512. video_url_list = [(existing_formats[-1], url_map[existing_formats[-1]])] # worst quality
  513. elif req_format in ('-1', 'all'):
  514. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  515. else:
  516. # Specific formats. We pick the first in a slash-delimeted sequence.
  517. # Format can be specified as itag or 'mp4' or 'flv' etc. We pick the highest quality
  518. # available in the specified format. For example,
  519. # if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  520. # if '1/mp4/3/4' is requested and '1' and '5' (is a mp4) are available, we pick '1'.
  521. # if '1/mp4/3/4' is requested and '4' and '5' (is a mp4) are available, we pick '5'.
  522. req_formats = req_format.split('/')
  523. video_url_list = None
  524. for rf in req_formats:
  525. if rf in url_map:
  526. video_url_list = [(rf, url_map[rf])]
  527. break
  528. if rf in self._video_formats_map:
  529. for srf in self._video_formats_map[rf]:
  530. if srf in url_map:
  531. video_url_list = [(srf, url_map[srf])]
  532. break
  533. else:
  534. continue
  535. break
  536. if video_url_list is None:
  537. raise ExtractorError(u'requested format not available')
  538. return video_url_list
  539. def _extract_from_m3u8(self, manifest_url, video_id):
  540. url_map = {}
  541. def _get_urls(_manifest):
  542. lines = _manifest.split('\n')
  543. urls = filter(lambda l: l and not l.startswith('#'),
  544. lines)
  545. return urls
  546. manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
  547. formats_urls = _get_urls(manifest)
  548. for format_url in formats_urls:
  549. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  550. url_map[itag] = format_url
  551. return url_map
  552. def _real_extract(self, url):
  553. if re.match(r'(?:https?://)?[^/]+/watch\?feature=[a-z_]+$', url):
  554. self._downloader.report_warning(u'Did you forget to quote the URL? Remember that & is a meta-character in most shells, so you want to put the URL in quotes, like youtube-dl \'http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc\' (or simply youtube-dl BaW_jenozKc ).')
  555. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  556. mobj = re.search(self._NEXT_URL_RE, url)
  557. if mobj:
  558. url = 'https://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  559. video_id = self._extract_id(url)
  560. # Get video webpage
  561. self.report_video_webpage_download(video_id)
  562. url = 'https://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  563. request = compat_urllib_request.Request(url)
  564. try:
  565. video_webpage_bytes = compat_urllib_request.urlopen(request).read()
  566. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  567. raise ExtractorError(u'Unable to download video webpage: %s' % compat_str(err))
  568. video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
  569. # Attempt to extract SWF player URL
  570. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  571. if mobj is not None:
  572. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  573. else:
  574. player_url = None
  575. # Get video info
  576. self.report_video_info_webpage_download(video_id)
  577. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  578. self.report_age_confirmation()
  579. age_gate = True
  580. # We simulate the access to the video from www.youtube.com/v/{video_id}
  581. # this can be viewed without login into Youtube
  582. data = compat_urllib_parse.urlencode({'video_id': video_id,
  583. 'el': 'embedded',
  584. 'gl': 'US',
  585. 'hl': 'en',
  586. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  587. 'asv': 3,
  588. 'sts':'1588',
  589. })
  590. video_info_url = 'https://www.youtube.com/get_video_info?' + data
  591. video_info_webpage = self._download_webpage(video_info_url, video_id,
  592. note=False,
  593. errnote='unable to download video info webpage')
  594. video_info = compat_parse_qs(video_info_webpage)
  595. else:
  596. age_gate = False
  597. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  598. video_info_url = ('https://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  599. % (video_id, el_type))
  600. video_info_webpage = self._download_webpage(video_info_url, video_id,
  601. note=False,
  602. errnote='unable to download video info webpage')
  603. video_info = compat_parse_qs(video_info_webpage)
  604. if 'token' in video_info:
  605. break
  606. if 'token' not in video_info:
  607. if 'reason' in video_info:
  608. raise ExtractorError(u'YouTube said: %s' % video_info['reason'][0], expected=True)
  609. else:
  610. raise ExtractorError(u'"token" parameter not in video info for unknown reason')
  611. # Check for "rental" videos
  612. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  613. raise ExtractorError(u'"rental" videos not supported')
  614. # Start extracting information
  615. self.report_information_extraction(video_id)
  616. # uploader
  617. if 'author' not in video_info:
  618. raise ExtractorError(u'Unable to extract uploader name')
  619. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  620. # uploader_id
  621. video_uploader_id = None
  622. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  623. if mobj is not None:
  624. video_uploader_id = mobj.group(1)
  625. else:
  626. self._downloader.report_warning(u'unable to extract uploader nickname')
  627. # title
  628. if 'title' not in video_info:
  629. raise ExtractorError(u'Unable to extract video title')
  630. video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
  631. # thumbnail image
  632. # We try first to get a high quality image:
  633. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  634. video_webpage, re.DOTALL)
  635. if m_thumb is not None:
  636. video_thumbnail = m_thumb.group(1)
  637. elif 'thumbnail_url' not in video_info:
  638. self._downloader.report_warning(u'unable to extract video thumbnail')
  639. video_thumbnail = ''
  640. else: # don't panic if we can't find it
  641. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  642. # upload date
  643. upload_date = None
  644. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  645. if mobj is not None:
  646. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  647. upload_date = unified_strdate(upload_date)
  648. # description
  649. video_description = get_element_by_id("eow-description", video_webpage)
  650. if video_description:
  651. video_description = clean_html(video_description)
  652. else:
  653. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  654. if fd_mobj:
  655. video_description = unescapeHTML(fd_mobj.group(1))
  656. else:
  657. video_description = u''
  658. # subtitles
  659. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  660. if self._downloader.params.get('listsubtitles', False):
  661. self._list_available_subtitles(video_id)
  662. return
  663. if 'length_seconds' not in video_info:
  664. self._downloader.report_warning(u'unable to extract video duration')
  665. video_duration = ''
  666. else:
  667. video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
  668. # Decide which formats to download
  669. try:
  670. mobj = re.search(r';ytplayer.config = ({.*?});', video_webpage)
  671. if not mobj:
  672. raise ValueError('Could not find vevo ID')
  673. info = json.loads(mobj.group(1))
  674. args = info['args']
  675. # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
  676. # this signatures are encrypted
  677. m_s = re.search(r'[&,]s=', args['url_encoded_fmt_stream_map'])
  678. if m_s is not None:
  679. self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
  680. video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
  681. m_s = re.search(r'[&,]s=', args.get('adaptive_fmts', u''))
  682. if m_s is not None:
  683. if 'url_encoded_fmt_stream_map' in video_info:
  684. video_info['url_encoded_fmt_stream_map'][0] += ',' + args['adaptive_fmts']
  685. else:
  686. video_info['url_encoded_fmt_stream_map'] = [args['adaptive_fmts']]
  687. elif 'adaptive_fmts' in video_info:
  688. if 'url_encoded_fmt_stream_map' in video_info:
  689. video_info['url_encoded_fmt_stream_map'][0] += ',' + video_info['adaptive_fmts'][0]
  690. else:
  691. video_info['url_encoded_fmt_stream_map'] = video_info['adaptive_fmts']
  692. except ValueError:
  693. pass
  694. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  695. self.report_rtmp_download()
  696. video_url_list = [(None, video_info['conn'][0])]
  697. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  698. if 'rtmpe%3Dyes' in video_info['url_encoded_fmt_stream_map'][0]:
  699. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  700. url_map = {}
  701. for url_data_str in video_info['url_encoded_fmt_stream_map'][0].split(','):
  702. url_data = compat_parse_qs(url_data_str)
  703. if 'itag' in url_data and 'url' in url_data:
  704. url = url_data['url'][0]
  705. if 'sig' in url_data:
  706. url += '&signature=' + url_data['sig'][0]
  707. elif 's' in url_data:
  708. if self._downloader.params.get('verbose'):
  709. s = url_data['s'][0]
  710. if age_gate:
  711. player_version = self._search_regex(r'ad3-(.+?)\.swf',
  712. video_info['ad3_module'][0] if 'ad3_module' in video_info else 'NOT FOUND',
  713. 'flash player', fatal=False)
  714. player = 'flash player %s' % player_version
  715. else:
  716. player = u'html5 player %s' % self._search_regex(r'html5player-(.+?)\.js', video_webpage,
  717. 'html5 player', fatal=False)
  718. parts_sizes = u'.'.join(compat_str(len(part)) for part in s.split('.'))
  719. self.to_screen(u'encrypted signature length %d (%s), itag %s, %s' %
  720. (len(s), parts_sizes, url_data['itag'][0], player))
  721. encrypted_sig = url_data['s'][0]
  722. if age_gate:
  723. signature = self._decrypt_signature_age_gate(encrypted_sig)
  724. else:
  725. signature = self._decrypt_signature(encrypted_sig)
  726. url += '&signature=' + signature
  727. if 'ratebypass' not in url:
  728. url += '&ratebypass=yes'
  729. url_map[url_data['itag'][0]] = url
  730. video_url_list = self._get_video_url_list(url_map)
  731. if not video_url_list:
  732. return
  733. elif video_info.get('hlsvp'):
  734. manifest_url = video_info['hlsvp'][0]
  735. url_map = self._extract_from_m3u8(manifest_url, video_id)
  736. video_url_list = self._get_video_url_list(url_map)
  737. if not video_url_list:
  738. return
  739. else:
  740. raise ExtractorError(u'no conn or url_encoded_fmt_stream_map information found in video info')
  741. results = []
  742. for format_param, video_real_url in video_url_list:
  743. # Extension
  744. video_extension = self._video_extensions.get(format_param, 'flv')
  745. video_format = '{0} - {1}{2}'.format(format_param if format_param else video_extension,
  746. self._video_dimensions.get(format_param, '???'),
  747. ' ('+self._special_itags[format_param]+')' if format_param in self._special_itags else '')
  748. results.append({
  749. 'id': video_id,
  750. 'url': video_real_url,
  751. 'uploader': video_uploader,
  752. 'uploader_id': video_uploader_id,
  753. 'upload_date': upload_date,
  754. 'title': video_title,
  755. 'ext': video_extension,
  756. 'format': video_format,
  757. 'thumbnail': video_thumbnail,
  758. 'description': video_description,
  759. 'player_url': player_url,
  760. 'subtitles': video_subtitles,
  761. 'duration': video_duration
  762. })
  763. return results
  764. class YoutubePlaylistIE(InfoExtractor):
  765. IE_DESC = u'YouTube.com playlists'
  766. _VALID_URL = r"""(?:
  767. (?:https?://)?
  768. (?:\w+\.)?
  769. youtube\.com/
  770. (?:
  771. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  772. \? (?:.*?&)*? (?:p|a|list)=
  773. | p/
  774. )
  775. ((?:PL|EC|UU|FL)?[0-9A-Za-z-_]{10,})
  776. .*
  777. |
  778. ((?:PL|EC|UU|FL)[0-9A-Za-z-_]{10,})
  779. )"""
  780. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/playlists/%s?max-results=%i&start-index=%i&v=2&alt=json&safeSearch=none'
  781. _MAX_RESULTS = 50
  782. IE_NAME = u'youtube:playlist'
  783. @classmethod
  784. def suitable(cls, url):
  785. """Receives a URL and returns True if suitable for this IE."""
  786. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  787. def _real_extract(self, url):
  788. # Extract playlist id
  789. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  790. if mobj is None:
  791. raise ExtractorError(u'Invalid URL: %s' % url)
  792. # Download playlist videos from API
  793. playlist_id = mobj.group(1) or mobj.group(2)
  794. videos = []
  795. for page_num in itertools.count(1):
  796. start_index = self._MAX_RESULTS * (page_num - 1) + 1
  797. if start_index >= 1000:
  798. self._downloader.report_warning(u'Max number of results reached')
  799. break
  800. url = self._TEMPLATE_URL % (playlist_id, self._MAX_RESULTS, start_index)
  801. page = self._download_webpage(url, playlist_id, u'Downloading page #%s' % page_num)
  802. try:
  803. response = json.loads(page)
  804. except ValueError as err:
  805. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  806. if 'feed' not in response:
  807. raise ExtractorError(u'Got a malformed response from YouTube API')
  808. playlist_title = response['feed']['title']['$t']
  809. if 'entry' not in response['feed']:
  810. # Number of videos is a multiple of self._MAX_RESULTS
  811. break
  812. for entry in response['feed']['entry']:
  813. index = entry['yt$position']['$t']
  814. if 'media$group' in entry and 'yt$videoid' in entry['media$group']:
  815. videos.append((
  816. index,
  817. 'https://www.youtube.com/watch?v=' + entry['media$group']['yt$videoid']['$t']
  818. ))
  819. videos = [v[1] for v in sorted(videos)]
  820. url_results = [self.url_result(vurl, 'Youtube') for vurl in videos]
  821. return [self.playlist_result(url_results, playlist_id, playlist_title)]
  822. class YoutubeChannelIE(InfoExtractor):
  823. IE_DESC = u'YouTube.com channels'
  824. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
  825. _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
  826. _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
  827. _MORE_PAGES_URL = 'http://www.youtube.com/c4_browse_ajax?action_load_more_videos=1&flow=list&paging=%s&view=0&sort=da&channel_id=%s'
  828. IE_NAME = u'youtube:channel'
  829. def extract_videos_from_page(self, page):
  830. ids_in_page = []
  831. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  832. if mobj.group(1) not in ids_in_page:
  833. ids_in_page.append(mobj.group(1))
  834. return ids_in_page
  835. def _real_extract(self, url):
  836. # Extract channel id
  837. mobj = re.match(self._VALID_URL, url)
  838. if mobj is None:
  839. raise ExtractorError(u'Invalid URL: %s' % url)
  840. # Download channel page
  841. channel_id = mobj.group(1)
  842. video_ids = []
  843. pagenum = 1
  844. url = self._TEMPLATE_URL % (channel_id, pagenum)
  845. page = self._download_webpage(url, channel_id,
  846. u'Downloading page #%s' % pagenum)
  847. # Extract video identifiers
  848. ids_in_page = self.extract_videos_from_page(page)
  849. video_ids.extend(ids_in_page)
  850. # Download any subsequent channel pages using the json-based channel_ajax query
  851. if self._MORE_PAGES_INDICATOR in page:
  852. for pagenum in itertools.count(1):
  853. url = self._MORE_PAGES_URL % (pagenum, channel_id)
  854. page = self._download_webpage(url, channel_id,
  855. u'Downloading page #%s' % pagenum)
  856. page = json.loads(page)
  857. ids_in_page = self.extract_videos_from_page(page['content_html'])
  858. video_ids.extend(ids_in_page)
  859. if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
  860. break
  861. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  862. urls = ['http://www.youtube.com/watch?v=%s' % id for id in video_ids]
  863. url_entries = [self.url_result(eurl, 'Youtube') for eurl in urls]
  864. return [self.playlist_result(url_entries, channel_id)]
  865. class YoutubeUserIE(InfoExtractor):
  866. IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
  867. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?)|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
  868. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  869. _GDATA_PAGE_SIZE = 50
  870. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
  871. IE_NAME = u'youtube:user'
  872. @classmethod
  873. def suitable(cls, url):
  874. # Don't return True if the url can be extracted with other youtube
  875. # extractor, the regex would is too permissive and it would match.
  876. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  877. if any(ie.suitable(url) for ie in other_ies): return False
  878. else: return super(YoutubeUserIE, cls).suitable(url)
  879. def _real_extract(self, url):
  880. # Extract username
  881. mobj = re.match(self._VALID_URL, url)
  882. if mobj is None:
  883. raise ExtractorError(u'Invalid URL: %s' % url)
  884. username = mobj.group(1)
  885. # Download video ids using YouTube Data API. Result size per
  886. # query is limited (currently to 50 videos) so we need to query
  887. # page by page until there are no video ids - it means we got
  888. # all of them.
  889. video_ids = []
  890. for pagenum in itertools.count(0):
  891. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  892. gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
  893. page = self._download_webpage(gdata_url, username,
  894. u'Downloading video ids from %d to %d' % (start_index, start_index + self._GDATA_PAGE_SIZE))
  895. try:
  896. response = json.loads(page)
  897. except ValueError as err:
  898. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  899. # Extract video identifiers
  900. ids_in_page = []
  901. for entry in response['feed']['entry']:
  902. ids_in_page.append(entry['id']['$t'].split('/')[-1])
  903. video_ids.extend(ids_in_page)
  904. # A little optimization - if current page is not
  905. # "full", ie. does not contain PAGE_SIZE video ids then
  906. # we can assume that this page is the last one - there
  907. # are no more ids on further pages - no need to query
  908. # again.
  909. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  910. break
  911. urls = ['http://www.youtube.com/watch?v=%s' % video_id for video_id in video_ids]
  912. url_results = [self.url_result(rurl, 'Youtube') for rurl in urls]
  913. return [self.playlist_result(url_results, playlist_title = username)]
  914. class YoutubeSearchIE(SearchInfoExtractor):
  915. IE_DESC = u'YouTube.com searches'
  916. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  917. _MAX_RESULTS = 1000
  918. IE_NAME = u'youtube:search'
  919. _SEARCH_KEY = 'ytsearch'
  920. def report_download_page(self, query, pagenum):
  921. """Report attempt to download search page with given number."""
  922. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  923. def _get_n_results(self, query, n):
  924. """Get a specified number of results for a query"""
  925. video_ids = []
  926. pagenum = 0
  927. limit = n
  928. while (50 * pagenum) < limit:
  929. self.report_download_page(query, pagenum+1)
  930. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  931. request = compat_urllib_request.Request(result_url)
  932. try:
  933. data = compat_urllib_request.urlopen(request).read().decode('utf-8')
  934. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  935. raise ExtractorError(u'Unable to download API page: %s' % compat_str(err))
  936. api_response = json.loads(data)['data']
  937. if not 'items' in api_response:
  938. raise ExtractorError(u'[youtube] No video results')
  939. new_ids = list(video['id'] for video in api_response['items'])
  940. video_ids += new_ids
  941. limit = min(n, api_response['totalItems'])
  942. pagenum += 1
  943. if len(video_ids) > n:
  944. video_ids = video_ids[:n]
  945. videos = [self.url_result('http://www.youtube.com/watch?v=%s' % id, 'Youtube') for id in video_ids]
  946. return self.playlist_result(videos, query)
  947. class YoutubeShowIE(InfoExtractor):
  948. IE_DESC = u'YouTube.com (multi-season) shows'
  949. _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
  950. IE_NAME = u'youtube:show'
  951. def _real_extract(self, url):
  952. mobj = re.match(self._VALID_URL, url)
  953. show_name = mobj.group(1)
  954. webpage = self._download_webpage(url, show_name, u'Downloading show webpage')
  955. # There's one playlist for each season of the show
  956. m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
  957. self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
  958. return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
  959. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  960. """
  961. Base class for extractors that fetch info from
  962. http://www.youtube.com/feed_ajax
  963. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  964. """
  965. _LOGIN_REQUIRED = True
  966. _PAGING_STEP = 30
  967. # use action_load_personal_feed instead of action_load_system_feed
  968. _PERSONAL_FEED = False
  969. @property
  970. def _FEED_TEMPLATE(self):
  971. action = 'action_load_system_feed'
  972. if self._PERSONAL_FEED:
  973. action = 'action_load_personal_feed'
  974. return 'http://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
  975. @property
  976. def IE_NAME(self):
  977. return u'youtube:%s' % self._FEED_NAME
  978. def _real_initialize(self):
  979. self._login()
  980. def _real_extract(self, url):
  981. feed_entries = []
  982. # The step argument is available only in 2.7 or higher
  983. for i in itertools.count(0):
  984. paging = i*self._PAGING_STEP
  985. info = self._download_webpage(self._FEED_TEMPLATE % paging,
  986. u'%s feed' % self._FEED_NAME,
  987. u'Downloading page %s' % i)
  988. info = json.loads(info)
  989. feed_html = info['feed_html']
  990. m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
  991. ids = orderedSet(m.group(1) for m in m_ids)
  992. feed_entries.extend(self.url_result(id, 'Youtube') for id in ids)
  993. if info['paging'] is None:
  994. break
  995. return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
  996. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  997. IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword(requires authentication)'
  998. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  999. _FEED_NAME = 'subscriptions'
  1000. _PLAYLIST_TITLE = u'Youtube Subscriptions'
  1001. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  1002. IE_DESC = u'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
  1003. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  1004. _FEED_NAME = 'recommended'
  1005. _PLAYLIST_TITLE = u'Youtube Recommended videos'
  1006. class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
  1007. IE_DESC = u'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
  1008. _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
  1009. _FEED_NAME = 'watch_later'
  1010. _PLAYLIST_TITLE = u'Youtube Watch Later'
  1011. _PAGING_STEP = 100
  1012. _PERSONAL_FEED = True
  1013. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  1014. IE_NAME = u'youtube:favorites'
  1015. IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
  1016. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  1017. _LOGIN_REQUIRED = True
  1018. def _real_extract(self, url):
  1019. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  1020. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, u'favourites playlist id')
  1021. return self.url_result(playlist_id, 'YoutubePlaylist')