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.

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