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.

1155 lines
50 KiB

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