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.

1133 lines
49 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. import collections
  5. import errno
  6. import io
  7. import json
  8. import os
  9. import platform
  10. import re
  11. import shutil
  12. import subprocess
  13. import socket
  14. import sys
  15. import time
  16. import traceback
  17. if os.name == 'nt':
  18. import ctypes
  19. from .utils import (
  20. compat_cookiejar,
  21. compat_http_client,
  22. compat_str,
  23. compat_urllib_error,
  24. compat_urllib_request,
  25. ContentTooShortError,
  26. date_from_str,
  27. DateRange,
  28. determine_ext,
  29. DownloadError,
  30. encodeFilename,
  31. ExtractorError,
  32. format_bytes,
  33. formatSeconds,
  34. get_term_width,
  35. locked_file,
  36. make_HTTPS_handler,
  37. MaxDownloadsReached,
  38. PostProcessingError,
  39. platform_name,
  40. preferredencoding,
  41. SameFileError,
  42. sanitize_filename,
  43. subtitles_filename,
  44. takewhile_inclusive,
  45. UnavailableVideoError,
  46. url_basename,
  47. write_json_file,
  48. write_string,
  49. YoutubeDLHandler,
  50. )
  51. from .extractor import get_info_extractor, gen_extractors
  52. from .FileDownloader import FileDownloader
  53. from .version import __version__
  54. class YoutubeDL(object):
  55. """YoutubeDL class.
  56. YoutubeDL objects are the ones responsible of downloading the
  57. actual video file and writing it to disk if the user has requested
  58. it, among some other tasks. In most cases there should be one per
  59. program. As, given a video URL, the downloader doesn't know how to
  60. extract all the needed information, task that InfoExtractors do, it
  61. has to pass the URL to one of them.
  62. For this, YoutubeDL objects have a method that allows
  63. InfoExtractors to be registered in a given order. When it is passed
  64. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  65. finds that reports being able to handle it. The InfoExtractor extracts
  66. all the information about the video or videos the URL refers to, and
  67. YoutubeDL process the extracted information, possibly using a File
  68. Downloader to download the video.
  69. YoutubeDL objects accept a lot of parameters. In order not to saturate
  70. the object constructor with arguments, it receives a dictionary of
  71. options instead. These options are available through the params
  72. attribute for the InfoExtractors to use. The YoutubeDL also
  73. registers itself as the downloader in charge for the InfoExtractors
  74. that are added to it, so this is a "mutual registration".
  75. Available options:
  76. username: Username for authentication purposes.
  77. password: Password for authentication purposes.
  78. videopassword: Password for acces a video.
  79. usenetrc: Use netrc for authentication instead.
  80. verbose: Print additional info to stdout.
  81. quiet: Do not print messages to stdout.
  82. forceurl: Force printing final URL.
  83. forcetitle: Force printing title.
  84. forceid: Force printing ID.
  85. forcethumbnail: Force printing thumbnail URL.
  86. forcedescription: Force printing description.
  87. forcefilename: Force printing final filename.
  88. forceduration: Force printing duration.
  89. forcejson: Force printing info_dict as JSON.
  90. simulate: Do not download the video files.
  91. format: Video format code.
  92. format_limit: Highest quality format to try.
  93. outtmpl: Template for output names.
  94. restrictfilenames: Do not allow "&" and spaces in file names
  95. ignoreerrors: Do not stop on download errors.
  96. nooverwrites: Prevent overwriting files.
  97. playliststart: Playlist item to start at.
  98. playlistend: Playlist item to end at.
  99. matchtitle: Download only matching titles.
  100. rejecttitle: Reject downloads for matching titles.
  101. logger: Log messages to a logging.Logger instance.
  102. logtostderr: Log messages to stderr instead of stdout.
  103. writedescription: Write the video description to a .description file
  104. writeinfojson: Write the video description to a .info.json file
  105. writeannotations: Write the video annotations to a .annotations.xml file
  106. writethumbnail: Write the thumbnail image to a file
  107. writesubtitles: Write the video subtitles to a file
  108. writeautomaticsub: Write the automatic subtitles to a file
  109. allsubtitles: Downloads all the subtitles of the video
  110. (requires writesubtitles or writeautomaticsub)
  111. listsubtitles: Lists all available subtitles for the video
  112. subtitlesformat: Subtitle format [srt/sbv/vtt] (default=srt)
  113. subtitleslangs: List of languages of the subtitles to download
  114. keepvideo: Keep the video file after post-processing
  115. daterange: A DateRange object, download only if the upload_date is in the range.
  116. skip_download: Skip the actual download of the video file
  117. cachedir: Location of the cache files in the filesystem.
  118. None to disable filesystem cache.
  119. noplaylist: Download single video instead of a playlist if in doubt.
  120. age_limit: An integer representing the user's age in years.
  121. Unsuitable videos for the given age are skipped.
  122. min_views: An integer representing the minimum view count the video
  123. must have in order to not be skipped.
  124. Videos without view count information are always
  125. downloaded. None for no limit.
  126. max_views: An integer representing the maximum view count.
  127. Videos that are more popular than that are not
  128. downloaded.
  129. Videos without view count information are always
  130. downloaded. None for no limit.
  131. download_archive: File name of a file where all downloads are recorded.
  132. Videos already present in the file are not downloaded
  133. again.
  134. cookiefile: File name where cookies should be read from and dumped to.
  135. nocheckcertificate:Do not verify SSL certificates
  136. proxy: URL of the proxy server to use
  137. socket_timeout: Time to wait for unresponsive hosts, in seconds
  138. bidi_workaround: Work around buggy terminals without bidirectional text
  139. support, using fridibi
  140. The following parameters are not used by YoutubeDL itself, they are used by
  141. the FileDownloader:
  142. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  143. noresizebuffer, retries, continuedl, noprogress, consoletitle
  144. """
  145. params = None
  146. _ies = []
  147. _pps = []
  148. _download_retcode = None
  149. _num_downloads = None
  150. _screen_file = None
  151. def __init__(self, params=None):
  152. """Create a FileDownloader object with the given options."""
  153. self._ies = []
  154. self._ies_instances = {}
  155. self._pps = []
  156. self._progress_hooks = []
  157. self._download_retcode = 0
  158. self._num_downloads = 0
  159. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  160. self._err_file = sys.stderr
  161. self.params = {} if params is None else params
  162. if params.get('bidi_workaround', False):
  163. try:
  164. import pty
  165. master, slave = pty.openpty()
  166. width = get_term_width()
  167. if width is None:
  168. width_args = []
  169. else:
  170. width_args = ['-w', str(width)]
  171. sp_kwargs = dict(
  172. stdin=subprocess.PIPE,
  173. stdout=slave,
  174. stderr=self._err_file)
  175. try:
  176. self._output_process = subprocess.Popen(
  177. ['bidiv'] + width_args, **sp_kwargs
  178. )
  179. except OSError:
  180. self._output_process = subprocess.Popen(
  181. ['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
  182. self._output_channel = os.fdopen(master, 'rb')
  183. except OSError as ose:
  184. if ose.errno == 2:
  185. self.report_warning(u'Could not find fribidi executable, ignoring --bidi-workaround . Make sure that fribidi is an executable file in one of the directories in your $PATH.')
  186. else:
  187. raise
  188. if (sys.version_info >= (3,) and sys.platform != 'win32' and
  189. sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  190. and not params['restrictfilenames']):
  191. # On Python 3, the Unicode filesystem API will throw errors (#1474)
  192. self.report_warning(
  193. u'Assuming --restrict-filenames since file system encoding '
  194. u'cannot encode all charactes. '
  195. u'Set the LC_ALL environment variable to fix this.')
  196. self.params['restrictfilenames'] = True
  197. self.fd = FileDownloader(self, self.params)
  198. if '%(stitle)s' in self.params.get('outtmpl', ''):
  199. self.report_warning(u'%(stitle)s is deprecated. Use the %(title)s and the --restrict-filenames flag(which also secures %(uploader)s et al) instead.')
  200. self._setup_opener()
  201. def add_info_extractor(self, ie):
  202. """Add an InfoExtractor object to the end of the list."""
  203. self._ies.append(ie)
  204. self._ies_instances[ie.ie_key()] = ie
  205. ie.set_downloader(self)
  206. def get_info_extractor(self, ie_key):
  207. """
  208. Get an instance of an IE with name ie_key, it will try to get one from
  209. the _ies list, if there's no instance it will create a new one and add
  210. it to the extractor list.
  211. """
  212. ie = self._ies_instances.get(ie_key)
  213. if ie is None:
  214. ie = get_info_extractor(ie_key)()
  215. self.add_info_extractor(ie)
  216. return ie
  217. def add_default_info_extractors(self):
  218. """
  219. Add the InfoExtractors returned by gen_extractors to the end of the list
  220. """
  221. for ie in gen_extractors():
  222. self.add_info_extractor(ie)
  223. def add_post_processor(self, pp):
  224. """Add a PostProcessor object to the end of the chain."""
  225. self._pps.append(pp)
  226. pp.set_downloader(self)
  227. def _bidi_workaround(self, message):
  228. if not hasattr(self, '_output_channel'):
  229. return message
  230. assert hasattr(self, '_output_process')
  231. assert type(message) == type(u'')
  232. line_count = message.count(u'\n') + 1
  233. self._output_process.stdin.write((message + u'\n').encode('utf-8'))
  234. self._output_process.stdin.flush()
  235. res = u''.join(self._output_channel.readline().decode('utf-8')
  236. for _ in range(line_count))
  237. return res[:-len(u'\n')]
  238. def to_screen(self, message, skip_eol=False):
  239. """Print message to stdout if not in quiet mode."""
  240. return self.to_stdout(message, skip_eol, check_quiet=True)
  241. def to_stdout(self, message, skip_eol=False, check_quiet=False):
  242. """Print message to stdout if not in quiet mode."""
  243. if self.params.get('logger'):
  244. self.params['logger'].debug(message)
  245. elif not check_quiet or not self.params.get('quiet', False):
  246. message = self._bidi_workaround(message)
  247. terminator = [u'\n', u''][skip_eol]
  248. output = message + terminator
  249. write_string(output, self._screen_file)
  250. def to_stderr(self, message):
  251. """Print message to stderr."""
  252. assert type(message) == type(u'')
  253. if self.params.get('logger'):
  254. self.params['logger'].error(message)
  255. else:
  256. message = self._bidi_workaround(message)
  257. output = message + u'\n'
  258. write_string(output, self._err_file)
  259. def to_console_title(self, message):
  260. if not self.params.get('consoletitle', False):
  261. return
  262. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  263. # c_wchar_p() might not be necessary if `message` is
  264. # already of type unicode()
  265. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  266. elif 'TERM' in os.environ:
  267. write_string(u'\033]0;%s\007' % message, self._screen_file)
  268. def save_console_title(self):
  269. if not self.params.get('consoletitle', False):
  270. return
  271. if 'TERM' in os.environ:
  272. # Save the title on stack
  273. write_string(u'\033[22;0t', self._screen_file)
  274. def restore_console_title(self):
  275. if not self.params.get('consoletitle', False):
  276. return
  277. if 'TERM' in os.environ:
  278. # Restore the title from stack
  279. write_string(u'\033[23;0t', self._screen_file)
  280. def __enter__(self):
  281. self.save_console_title()
  282. return self
  283. def __exit__(self, *args):
  284. self.restore_console_title()
  285. if self.params.get('cookiefile') is not None:
  286. self.cookiejar.save()
  287. def trouble(self, message=None, tb=None):
  288. """Determine action to take when a download problem appears.
  289. Depending on if the downloader has been configured to ignore
  290. download errors or not, this method may throw an exception or
  291. not when errors are found, after printing the message.
  292. tb, if given, is additional traceback information.
  293. """
  294. if message is not None:
  295. self.to_stderr(message)
  296. if self.params.get('verbose'):
  297. if tb is None:
  298. if sys.exc_info()[0]: # if .trouble has been called from an except block
  299. tb = u''
  300. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  301. tb += u''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  302. tb += compat_str(traceback.format_exc())
  303. else:
  304. tb_data = traceback.format_list(traceback.extract_stack())
  305. tb = u''.join(tb_data)
  306. self.to_stderr(tb)
  307. if not self.params.get('ignoreerrors', False):
  308. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  309. exc_info = sys.exc_info()[1].exc_info
  310. else:
  311. exc_info = sys.exc_info()
  312. raise DownloadError(message, exc_info)
  313. self._download_retcode = 1
  314. def report_warning(self, message):
  315. '''
  316. Print the message to stderr, it will be prefixed with 'WARNING:'
  317. If stderr is a tty file the 'WARNING:' will be colored
  318. '''
  319. if self._err_file.isatty() and os.name != 'nt':
  320. _msg_header = u'\033[0;33mWARNING:\033[0m'
  321. else:
  322. _msg_header = u'WARNING:'
  323. warning_message = u'%s %s' % (_msg_header, message)
  324. self.to_stderr(warning_message)
  325. def report_error(self, message, tb=None):
  326. '''
  327. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  328. in red if stderr is a tty file.
  329. '''
  330. if self._err_file.isatty() and os.name != 'nt':
  331. _msg_header = u'\033[0;31mERROR:\033[0m'
  332. else:
  333. _msg_header = u'ERROR:'
  334. error_message = u'%s %s' % (_msg_header, message)
  335. self.trouble(error_message, tb)
  336. def report_file_already_downloaded(self, file_name):
  337. """Report file has already been fully downloaded."""
  338. try:
  339. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  340. except UnicodeEncodeError:
  341. self.to_screen(u'[download] The file has already been downloaded')
  342. def increment_downloads(self):
  343. """Increment the ordinal that assigns a number to each file."""
  344. self._num_downloads += 1
  345. def prepare_filename(self, info_dict):
  346. """Generate the output filename."""
  347. try:
  348. template_dict = dict(info_dict)
  349. template_dict['epoch'] = int(time.time())
  350. autonumber_size = self.params.get('autonumber_size')
  351. if autonumber_size is None:
  352. autonumber_size = 5
  353. autonumber_templ = u'%0' + str(autonumber_size) + u'd'
  354. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  355. if template_dict.get('playlist_index') is not None:
  356. template_dict['playlist_index'] = u'%05d' % template_dict['playlist_index']
  357. sanitize = lambda k, v: sanitize_filename(
  358. compat_str(v),
  359. restricted=self.params.get('restrictfilenames'),
  360. is_id=(k == u'id'))
  361. template_dict = dict((k, sanitize(k, v))
  362. for k, v in template_dict.items()
  363. if v is not None)
  364. template_dict = collections.defaultdict(lambda: u'NA', template_dict)
  365. tmpl = os.path.expanduser(self.params['outtmpl'])
  366. filename = tmpl % template_dict
  367. return filename
  368. except ValueError as err:
  369. self.report_error(u'Error in output template: ' + str(err) + u' (encoding: ' + repr(preferredencoding()) + ')')
  370. return None
  371. def _match_entry(self, info_dict):
  372. """ Returns None iff the file should be downloaded """
  373. video_title = info_dict.get('title', info_dict.get('id', u'video'))
  374. if 'title' in info_dict:
  375. # This can happen when we're just evaluating the playlist
  376. title = info_dict['title']
  377. matchtitle = self.params.get('matchtitle', False)
  378. if matchtitle:
  379. if not re.search(matchtitle, title, re.IGNORECASE):
  380. return u'"' + title + '" title did not match pattern "' + matchtitle + '"'
  381. rejecttitle = self.params.get('rejecttitle', False)
  382. if rejecttitle:
  383. if re.search(rejecttitle, title, re.IGNORECASE):
  384. return u'"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  385. date = info_dict.get('upload_date', None)
  386. if date is not None:
  387. dateRange = self.params.get('daterange', DateRange())
  388. if date not in dateRange:
  389. return u'%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  390. view_count = info_dict.get('view_count', None)
  391. if view_count is not None:
  392. min_views = self.params.get('min_views')
  393. if min_views is not None and view_count < min_views:
  394. return u'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  395. max_views = self.params.get('max_views')
  396. if max_views is not None and view_count > max_views:
  397. return u'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  398. age_limit = self.params.get('age_limit')
  399. if age_limit is not None:
  400. if age_limit < info_dict.get('age_limit', 0):
  401. return u'Skipping "' + title + '" because it is age restricted'
  402. if self.in_download_archive(info_dict):
  403. return u'%s has already been recorded in archive' % video_title
  404. return None
  405. @staticmethod
  406. def add_extra_info(info_dict, extra_info):
  407. '''Set the keys from extra_info in info dict if they are missing'''
  408. for key, value in extra_info.items():
  409. info_dict.setdefault(key, value)
  410. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  411. process=True):
  412. '''
  413. Returns a list with a dictionary for each video we find.
  414. If 'download', also downloads the videos.
  415. extra_info is a dict containing the extra values to add to each result
  416. '''
  417. if ie_key:
  418. ies = [self.get_info_extractor(ie_key)]
  419. else:
  420. ies = self._ies
  421. for ie in ies:
  422. if not ie.suitable(url):
  423. continue
  424. if not ie.working():
  425. self.report_warning(u'The program functionality for this site has been marked as broken, '
  426. u'and will probably not work.')
  427. try:
  428. ie_result = ie.extract(url)
  429. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  430. break
  431. if isinstance(ie_result, list):
  432. # Backwards compatibility: old IE result format
  433. ie_result = {
  434. '_type': 'compat_list',
  435. 'entries': ie_result,
  436. }
  437. self.add_extra_info(ie_result,
  438. {
  439. 'extractor': ie.IE_NAME,
  440. 'webpage_url': url,
  441. 'webpage_url_basename': url_basename(url),
  442. 'extractor_key': ie.ie_key(),
  443. })
  444. if process:
  445. return self.process_ie_result(ie_result, download, extra_info)
  446. else:
  447. return ie_result
  448. except ExtractorError as de: # An error we somewhat expected
  449. self.report_error(compat_str(de), de.format_traceback())
  450. break
  451. except Exception as e:
  452. if self.params.get('ignoreerrors', False):
  453. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  454. break
  455. else:
  456. raise
  457. else:
  458. self.report_error(u'no suitable InfoExtractor: %s' % url)
  459. def process_ie_result(self, ie_result, download=True, extra_info={}):
  460. """
  461. Take the result of the ie(may be modified) and resolve all unresolved
  462. references (URLs, playlist items).
  463. It will also download the videos if 'download'.
  464. Returns the resolved ie_result.
  465. """
  466. result_type = ie_result.get('_type', 'video') # If not given we suppose it's a video, support the default old system
  467. if result_type == 'video':
  468. self.add_extra_info(ie_result, extra_info)
  469. return self.process_video_result(ie_result, download=download)
  470. elif result_type == 'url':
  471. # We have to add extra_info to the results because it may be
  472. # contained in a playlist
  473. return self.extract_info(ie_result['url'],
  474. download,
  475. ie_key=ie_result.get('ie_key'),
  476. extra_info=extra_info)
  477. elif result_type == 'url_transparent':
  478. # Use the information from the embedding page
  479. info = self.extract_info(
  480. ie_result['url'], ie_key=ie_result.get('ie_key'),
  481. extra_info=extra_info, download=False, process=False)
  482. def make_result(embedded_info):
  483. new_result = ie_result.copy()
  484. for f in ('_type', 'url', 'ext', 'player_url', 'formats',
  485. 'entries', 'urlhandle', 'ie_key', 'duration',
  486. 'subtitles', 'annotations', 'format',
  487. 'thumbnail', 'thumbnails'):
  488. if f in new_result:
  489. del new_result[f]
  490. if f in embedded_info:
  491. new_result[f] = embedded_info[f]
  492. return new_result
  493. new_result = make_result(info)
  494. assert new_result.get('_type') != 'url_transparent'
  495. if new_result.get('_type') == 'compat_list':
  496. new_result['entries'] = [
  497. make_result(e) for e in new_result['entries']]
  498. return self.process_ie_result(
  499. new_result, download=download, extra_info=extra_info)
  500. elif result_type == 'playlist':
  501. # We process each entry in the playlist
  502. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  503. self.to_screen(u'[download] Downloading playlist: %s' % playlist)
  504. playlist_results = []
  505. n_all_entries = len(ie_result['entries'])
  506. playliststart = self.params.get('playliststart', 1) - 1
  507. playlistend = self.params.get('playlistend', None)
  508. # For backwards compatibility, interpret -1 as whole list
  509. if playlistend == -1:
  510. playlistend = None
  511. entries = ie_result['entries'][playliststart:playlistend]
  512. n_entries = len(entries)
  513. self.to_screen(
  514. u"[%s] playlist '%s': Collected %d video ids (downloading %d of them)" %
  515. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  516. for i, entry in enumerate(entries, 1):
  517. self.to_screen(u'[download] Downloading video #%s of %s' % (i, n_entries))
  518. extra = {
  519. 'playlist': playlist,
  520. 'playlist_index': i + playliststart,
  521. 'extractor': ie_result['extractor'],
  522. 'webpage_url': ie_result['webpage_url'],
  523. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  524. 'extractor_key': ie_result['extractor_key'],
  525. }
  526. reason = self._match_entry(entry)
  527. if reason is not None:
  528. self.to_screen(u'[download] ' + reason)
  529. continue
  530. entry_result = self.process_ie_result(entry,
  531. download=download,
  532. extra_info=extra)
  533. playlist_results.append(entry_result)
  534. ie_result['entries'] = playlist_results
  535. return ie_result
  536. elif result_type == 'compat_list':
  537. def _fixup(r):
  538. self.add_extra_info(r,
  539. {
  540. 'extractor': ie_result['extractor'],
  541. 'webpage_url': ie_result['webpage_url'],
  542. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  543. 'extractor_key': ie_result['extractor_key'],
  544. })
  545. return r
  546. ie_result['entries'] = [
  547. self.process_ie_result(_fixup(r), download, extra_info)
  548. for r in ie_result['entries']
  549. ]
  550. return ie_result
  551. else:
  552. raise Exception('Invalid result type: %s' % result_type)
  553. def select_format(self, format_spec, available_formats):
  554. if format_spec == 'best' or format_spec is None:
  555. return available_formats[-1]
  556. elif format_spec == 'worst':
  557. return available_formats[0]
  558. else:
  559. extensions = [u'mp4', u'flv', u'webm', u'3gp']
  560. if format_spec in extensions:
  561. filter_f = lambda f: f['ext'] == format_spec
  562. else:
  563. filter_f = lambda f: f['format_id'] == format_spec
  564. matches = list(filter(filter_f, available_formats))
  565. if matches:
  566. return matches[-1]
  567. return None
  568. def process_video_result(self, info_dict, download=True):
  569. assert info_dict.get('_type', 'video') == 'video'
  570. if 'playlist' not in info_dict:
  571. # It isn't part of a playlist
  572. info_dict['playlist'] = None
  573. info_dict['playlist_index'] = None
  574. # This extractors handle format selection themselves
  575. if info_dict['extractor'] in [u'Youku']:
  576. if download:
  577. self.process_info(info_dict)
  578. return info_dict
  579. # We now pick which formats have to be downloaded
  580. if info_dict.get('formats') is None:
  581. # There's only one format available
  582. formats = [info_dict]
  583. else:
  584. formats = info_dict['formats']
  585. # We check that all the formats have the format and format_id fields
  586. for (i, format) in enumerate(formats):
  587. if format.get('format_id') is None:
  588. format['format_id'] = compat_str(i)
  589. if format.get('format') is None:
  590. format['format'] = u'{id} - {res}{note}'.format(
  591. id=format['format_id'],
  592. res=self.format_resolution(format),
  593. note=u' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  594. )
  595. # Automatically determine file extension if missing
  596. if 'ext' not in format:
  597. format['ext'] = determine_ext(format['url'])
  598. format_limit = self.params.get('format_limit', None)
  599. if format_limit:
  600. formats = list(takewhile_inclusive(
  601. lambda f: f['format_id'] != format_limit, formats
  602. ))
  603. if self.params.get('prefer_free_formats'):
  604. def _free_formats_key(f):
  605. try:
  606. ext_ord = [u'flv', u'mp4', u'webm'].index(f['ext'])
  607. except ValueError:
  608. ext_ord = -1
  609. # We only compare the extension if they have the same height and width
  610. return (f.get('height') if f.get('height') is not None else -1,
  611. f.get('width') if f.get('width') is not None else -1,
  612. ext_ord)
  613. formats = sorted(formats, key=_free_formats_key)
  614. info_dict['formats'] = formats
  615. if self.params.get('listformats', None):
  616. self.list_formats(info_dict)
  617. return
  618. req_format = self.params.get('format', 'best')
  619. if req_format is None:
  620. req_format = 'best'
  621. formats_to_download = []
  622. # The -1 is for supporting YoutubeIE
  623. if req_format in ('-1', 'all'):
  624. formats_to_download = formats
  625. else:
  626. # We can accept formats requestd in the format: 34/5/best, we pick
  627. # the first that is available, starting from left
  628. req_formats = req_format.split('/')
  629. for rf in req_formats:
  630. selected_format = self.select_format(rf, formats)
  631. if selected_format is not None:
  632. formats_to_download = [selected_format]
  633. break
  634. if not formats_to_download:
  635. raise ExtractorError(u'requested format not available',
  636. expected=True)
  637. if download:
  638. if len(formats_to_download) > 1:
  639. self.to_screen(u'[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  640. for format in formats_to_download:
  641. new_info = dict(info_dict)
  642. new_info.update(format)
  643. self.process_info(new_info)
  644. # We update the info dict with the best quality format (backwards compatibility)
  645. info_dict.update(formats_to_download[-1])
  646. return info_dict
  647. def process_info(self, info_dict):
  648. """Process a single resolved IE result."""
  649. assert info_dict.get('_type', 'video') == 'video'
  650. #We increment the download the download count here to match the previous behaviour.
  651. self.increment_downloads()
  652. info_dict['fulltitle'] = info_dict['title']
  653. if len(info_dict['title']) > 200:
  654. info_dict['title'] = info_dict['title'][:197] + u'...'
  655. # Keep for backwards compatibility
  656. info_dict['stitle'] = info_dict['title']
  657. if not 'format' in info_dict:
  658. info_dict['format'] = info_dict['ext']
  659. reason = self._match_entry(info_dict)
  660. if reason is not None:
  661. self.to_screen(u'[download] ' + reason)
  662. return
  663. max_downloads = self.params.get('max_downloads')
  664. if max_downloads is not None:
  665. if self._num_downloads > int(max_downloads):
  666. raise MaxDownloadsReached()
  667. filename = self.prepare_filename(info_dict)
  668. # Forced printings
  669. if self.params.get('forcetitle', False):
  670. self.to_stdout(info_dict['fulltitle'])
  671. if self.params.get('forceid', False):
  672. self.to_stdout(info_dict['id'])
  673. if self.params.get('forceurl', False):
  674. # For RTMP URLs, also include the playpath
  675. self.to_stdout(info_dict['url'] + info_dict.get('play_path', u''))
  676. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  677. self.to_stdout(info_dict['thumbnail'])
  678. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  679. self.to_stdout(info_dict['description'])
  680. if self.params.get('forcefilename', False) and filename is not None:
  681. self.to_stdout(filename)
  682. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  683. self.to_stdout(formatSeconds(info_dict['duration']))
  684. if self.params.get('forceformat', False):
  685. self.to_stdout(info_dict['format'])
  686. if self.params.get('forcejson', False):
  687. info_dict['_filename'] = filename
  688. self.to_stdout(json.dumps(info_dict))
  689. # Do nothing else if in simulate mode
  690. if self.params.get('simulate', False):
  691. return
  692. if filename is None:
  693. return
  694. try:
  695. dn = os.path.dirname(encodeFilename(filename))
  696. if dn != '' and not os.path.exists(dn):
  697. os.makedirs(dn)
  698. except (OSError, IOError) as err:
  699. self.report_error(u'unable to create directory ' + compat_str(err))
  700. return
  701. if self.params.get('writedescription', False):
  702. descfn = filename + u'.description'
  703. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  704. self.to_screen(u'[info] Video description is already present')
  705. else:
  706. try:
  707. self.to_screen(u'[info] Writing video description to: ' + descfn)
  708. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  709. descfile.write(info_dict['description'])
  710. except (KeyError, TypeError):
  711. self.report_warning(u'There\'s no description to write.')
  712. except (OSError, IOError):
  713. self.report_error(u'Cannot write description file ' + descfn)
  714. return
  715. if self.params.get('writeannotations', False):
  716. annofn = filename + u'.annotations.xml'
  717. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  718. self.to_screen(u'[info] Video annotations are already present')
  719. else:
  720. try:
  721. self.to_screen(u'[info] Writing video annotations to: ' + annofn)
  722. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  723. annofile.write(info_dict['annotations'])
  724. except (KeyError, TypeError):
  725. self.report_warning(u'There are no annotations to write.')
  726. except (OSError, IOError):
  727. self.report_error(u'Cannot write annotations file: ' + annofn)
  728. return
  729. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  730. self.params.get('writeautomaticsub')])
  731. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  732. # subtitles download errors are already managed as troubles in relevant IE
  733. # that way it will silently go on when used with unsupporting IE
  734. subtitles = info_dict['subtitles']
  735. sub_format = self.params.get('subtitlesformat', 'srt')
  736. for sub_lang in subtitles.keys():
  737. sub = subtitles[sub_lang]
  738. if sub is None:
  739. continue
  740. try:
  741. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  742. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  743. self.to_screen(u'[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  744. else:
  745. self.to_screen(u'[info] Writing video subtitles to: ' + sub_filename)
  746. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  747. subfile.write(sub)
  748. except (OSError, IOError):
  749. self.report_error(u'Cannot write subtitles file ' + descfn)
  750. return
  751. if self.params.get('writeinfojson', False):
  752. infofn = os.path.splitext(filename)[0] + u'.info.json'
  753. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  754. self.to_screen(u'[info] Video description metadata is already present')
  755. else:
  756. self.to_screen(u'[info] Writing video description metadata as JSON to: ' + infofn)
  757. try:
  758. json_info_dict = dict((k, v) for k, v in info_dict.items() if not k in ['urlhandle'])
  759. write_json_file(json_info_dict, encodeFilename(infofn))
  760. except (OSError, IOError):
  761. self.report_error(u'Cannot write metadata to JSON file ' + infofn)
  762. return
  763. if self.params.get('writethumbnail', False):
  764. if info_dict.get('thumbnail') is not None:
  765. thumb_format = determine_ext(info_dict['thumbnail'], u'jpg')
  766. thumb_filename = os.path.splitext(filename)[0] + u'.' + thumb_format
  767. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  768. self.to_screen(u'[%s] %s: Thumbnail is already present' %
  769. (info_dict['extractor'], info_dict['id']))
  770. else:
  771. self.to_screen(u'[%s] %s: Downloading thumbnail ...' %
  772. (info_dict['extractor'], info_dict['id']))
  773. try:
  774. uf = compat_urllib_request.urlopen(info_dict['thumbnail'])
  775. with open(thumb_filename, 'wb') as thumbf:
  776. shutil.copyfileobj(uf, thumbf)
  777. self.to_screen(u'[%s] %s: Writing thumbnail to: %s' %
  778. (info_dict['extractor'], info_dict['id'], thumb_filename))
  779. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  780. self.report_warning(u'Unable to download thumbnail "%s": %s' %
  781. (info_dict['thumbnail'], compat_str(err)))
  782. if not self.params.get('skip_download', False):
  783. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  784. success = True
  785. else:
  786. try:
  787. success = self.fd._do_download(filename, info_dict)
  788. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  789. self.report_error(u'unable to download video data: %s' % str(err))
  790. return
  791. except (OSError, IOError) as err:
  792. raise UnavailableVideoError(err)
  793. except (ContentTooShortError, ) as err:
  794. self.report_error(u'content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  795. return
  796. if success:
  797. try:
  798. self.post_process(filename, info_dict)
  799. except (PostProcessingError) as err:
  800. self.report_error(u'postprocessing: %s' % str(err))
  801. return
  802. self.record_download_archive(info_dict)
  803. def download(self, url_list):
  804. """Download a given list of URLs."""
  805. if (len(url_list) > 1 and
  806. '%' not in self.params['outtmpl']
  807. and self.params.get('max_downloads') != 1):
  808. raise SameFileError(self.params['outtmpl'])
  809. for url in url_list:
  810. try:
  811. #It also downloads the videos
  812. self.extract_info(url)
  813. except UnavailableVideoError:
  814. self.report_error(u'unable to download video')
  815. except MaxDownloadsReached:
  816. self.to_screen(u'[info] Maximum number of downloaded files reached.')
  817. raise
  818. return self._download_retcode
  819. def download_with_info_file(self, info_filename):
  820. with io.open(info_filename, 'r', encoding='utf-8') as f:
  821. info = json.load(f)
  822. try:
  823. self.process_ie_result(info, download=True)
  824. except DownloadError:
  825. webpage_url = info.get('webpage_url')
  826. if webpage_url is not None:
  827. self.report_warning(u'The info failed to download, trying with "%s"' % webpage_url)
  828. return self.download([webpage_url])
  829. else:
  830. raise
  831. return self._download_retcode
  832. def post_process(self, filename, ie_info):
  833. """Run all the postprocessors on the given file."""
  834. info = dict(ie_info)
  835. info['filepath'] = filename
  836. keep_video = None
  837. for pp in self._pps:
  838. try:
  839. keep_video_wish, new_info = pp.run(info)
  840. if keep_video_wish is not None:
  841. if keep_video_wish:
  842. keep_video = keep_video_wish
  843. elif keep_video is None:
  844. # No clear decision yet, let IE decide
  845. keep_video = keep_video_wish
  846. except PostProcessingError as e:
  847. self.report_error(e.msg)
  848. if keep_video is False and not self.params.get('keepvideo', False):
  849. try:
  850. self.to_screen(u'Deleting original file %s (pass -k to keep)' % filename)
  851. os.remove(encodeFilename(filename))
  852. except (IOError, OSError):
  853. self.report_warning(u'Unable to remove downloaded video file')
  854. def _make_archive_id(self, info_dict):
  855. # Future-proof against any change in case
  856. # and backwards compatibility with prior versions
  857. extractor = info_dict.get('extractor_key')
  858. if extractor is None:
  859. if 'id' in info_dict:
  860. extractor = info_dict.get('ie_key') # key in a playlist
  861. if extractor is None:
  862. return None # Incomplete video information
  863. return extractor.lower() + u' ' + info_dict['id']
  864. def in_download_archive(self, info_dict):
  865. fn = self.params.get('download_archive')
  866. if fn is None:
  867. return False
  868. vid_id = self._make_archive_id(info_dict)
  869. if vid_id is None:
  870. return False # Incomplete video information
  871. try:
  872. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  873. for line in archive_file:
  874. if line.strip() == vid_id:
  875. return True
  876. except IOError as ioe:
  877. if ioe.errno != errno.ENOENT:
  878. raise
  879. return False
  880. def record_download_archive(self, info_dict):
  881. fn = self.params.get('download_archive')
  882. if fn is None:
  883. return
  884. vid_id = self._make_archive_id(info_dict)
  885. assert vid_id
  886. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  887. archive_file.write(vid_id + u'\n')
  888. @staticmethod
  889. def format_resolution(format, default='unknown'):
  890. if format.get('vcodec') == 'none':
  891. return 'audio only'
  892. if format.get('_resolution') is not None:
  893. return format['_resolution']
  894. if format.get('height') is not None:
  895. if format.get('width') is not None:
  896. res = u'%sx%s' % (format['width'], format['height'])
  897. else:
  898. res = u'%sp' % format['height']
  899. else:
  900. res = default
  901. return res
  902. def list_formats(self, info_dict):
  903. def format_note(fdict):
  904. res = u''
  905. if fdict.get('format_note') is not None:
  906. res += fdict['format_note'] + u' '
  907. if (fdict.get('vcodec') is not None and
  908. fdict.get('vcodec') != 'none'):
  909. res += u'%-5s' % fdict['vcodec']
  910. elif fdict.get('vbr') is not None:
  911. res += u'video'
  912. if fdict.get('vbr') is not None:
  913. res += u'@%4dk' % fdict['vbr']
  914. if fdict.get('acodec') is not None:
  915. if res:
  916. res += u', '
  917. res += u'%-5s' % fdict['acodec']
  918. elif fdict.get('abr') is not None:
  919. if res:
  920. res += u', '
  921. res += 'audio'
  922. if fdict.get('abr') is not None:
  923. res += u'@%3dk' % fdict['abr']
  924. if fdict.get('filesize') is not None:
  925. if res:
  926. res += u', '
  927. res += format_bytes(fdict['filesize'])
  928. return res
  929. def line(format, idlen=20):
  930. return ((u'%-' + compat_str(idlen + 1) + u's%-10s%-12s%s') % (
  931. format['format_id'],
  932. format['ext'],
  933. self.format_resolution(format),
  934. format_note(format),
  935. ))
  936. formats = info_dict.get('formats', [info_dict])
  937. idlen = max(len(u'format code'),
  938. max(len(f['format_id']) for f in formats))
  939. formats_s = [line(f, idlen) for f in formats]
  940. if len(formats) > 1:
  941. formats_s[0] += (' ' if format_note(formats[0]) else '') + '(worst)'
  942. formats_s[-1] += (' ' if format_note(formats[-1]) else '') + '(best)'
  943. header_line = line({
  944. 'format_id': u'format code', 'ext': u'extension',
  945. '_resolution': u'resolution', 'format_note': u'note'}, idlen=idlen)
  946. self.to_screen(u'[info] Available formats for %s:\n%s\n%s' %
  947. (info_dict['id'], header_line, u"\n".join(formats_s)))
  948. def urlopen(self, req):
  949. """ Start an HTTP download """
  950. return self._opener.open(req)
  951. def print_debug_header(self):
  952. if not self.params.get('verbose'):
  953. return
  954. write_string(u'[debug] youtube-dl version ' + __version__ + u'\n')
  955. try:
  956. sp = subprocess.Popen(
  957. ['git', 'rev-parse', '--short', 'HEAD'],
  958. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  959. cwd=os.path.dirname(os.path.abspath(__file__)))
  960. out, err = sp.communicate()
  961. out = out.decode().strip()
  962. if re.match('[0-9a-f]+', out):
  963. write_string(u'[debug] Git HEAD: ' + out + u'\n')
  964. except:
  965. try:
  966. sys.exc_clear()
  967. except:
  968. pass
  969. write_string(u'[debug] Python version %s - %s' %
  970. (platform.python_version(), platform_name()) + u'\n')
  971. proxy_map = {}
  972. for handler in self._opener.handlers:
  973. if hasattr(handler, 'proxies'):
  974. proxy_map.update(handler.proxies)
  975. write_string(u'[debug] Proxy map: ' + compat_str(proxy_map) + u'\n')
  976. def _setup_opener(self):
  977. timeout_val = self.params.get('socket_timeout')
  978. timeout = 600 if timeout_val is None else float(timeout_val)
  979. opts_cookiefile = self.params.get('cookiefile')
  980. opts_proxy = self.params.get('proxy')
  981. if opts_cookiefile is None:
  982. self.cookiejar = compat_cookiejar.CookieJar()
  983. else:
  984. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  985. opts_cookiefile)
  986. if os.access(opts_cookiefile, os.R_OK):
  987. self.cookiejar.load()
  988. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  989. self.cookiejar)
  990. if opts_proxy is not None:
  991. if opts_proxy == '':
  992. proxies = {}
  993. else:
  994. proxies = {'http': opts_proxy, 'https': opts_proxy}
  995. else:
  996. proxies = compat_urllib_request.getproxies()
  997. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  998. if 'http' in proxies and 'https' not in proxies:
  999. proxies['https'] = proxies['http']
  1000. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1001. https_handler = make_HTTPS_handler(
  1002. self.params.get('nocheckcertificate', False))
  1003. opener = compat_urllib_request.build_opener(
  1004. https_handler, proxy_handler, cookie_processor, YoutubeDLHandler())
  1005. # Delete the default user-agent header, which would otherwise apply in
  1006. # cases where our custom HTTP handler doesn't come into play
  1007. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1008. opener.addheaders = []
  1009. self._opener = opener
  1010. # TODO remove this global modification
  1011. compat_urllib_request.install_opener(opener)
  1012. socket.setdefaulttimeout(timeout)