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.

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