external.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. from __future__ import unicode_literals
  2. import os.path
  3. import subprocess
  4. from .common import FileDownloader
  5. from ..utils import (
  6. encodeFilename,
  7. encodeArgument,
  8. )
  9. class ExternalFD(FileDownloader):
  10. def real_download(self, filename, info_dict):
  11. self.report_destination(filename)
  12. tmpfilename = self.temp_name(filename)
  13. retval = self._call_downloader(tmpfilename, info_dict)
  14. if retval == 0:
  15. fsize = os.path.getsize(encodeFilename(tmpfilename))
  16. self.to_screen('\r[%s] Downloaded %s bytes' % (self.get_basename(), fsize))
  17. self.try_rename(tmpfilename, filename)
  18. self._hook_progress({
  19. 'downloaded_bytes': fsize,
  20. 'total_bytes': fsize,
  21. 'filename': filename,
  22. 'status': 'finished',
  23. })
  24. return True
  25. else:
  26. self.to_stderr('\n')
  27. self.report_error('%s exited with code %d' % (
  28. self.get_basename(), retval))
  29. return False
  30. @classmethod
  31. def get_basename(cls):
  32. return cls.__name__[:-2].lower()
  33. @property
  34. def exe(self):
  35. return self.params.get('external_downloader')
  36. @classmethod
  37. def supports(cls, info_dict):
  38. return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps')
  39. def _option(self, command_option, param):
  40. param = self.params.get(param)
  41. if param is None:
  42. return []
  43. return [command_option, param]
  44. def _bool_option(self, command_option, param, true_value='true', false_value='false', separator=None):
  45. param = self.params.get(param)
  46. if not isinstance(param, bool):
  47. return []
  48. if separator:
  49. return [command_option + separator + (true_value if param else false_value)]
  50. return [command_option, true_value if param else false_value]
  51. def _valueless_option(self, command_option, param, expected_value=True):
  52. param = self.params.get(param)
  53. return [command_option] if param == expected_value else []
  54. def _configuration_args(self, default=[]):
  55. ex_args = self.params.get('external_downloader_args')
  56. if ex_args is None:
  57. return default
  58. assert isinstance(ex_args, list)
  59. return ex_args
  60. def _call_downloader(self, tmpfilename, info_dict):
  61. """ Either overwrite this or implement _make_cmd """
  62. cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
  63. self._debug_cmd(cmd)
  64. p = subprocess.Popen(
  65. cmd, stderr=subprocess.PIPE)
  66. _, stderr = p.communicate()
  67. if p.returncode != 0:
  68. self.to_stderr(stderr)
  69. return p.returncode
  70. class CurlFD(ExternalFD):
  71. def _make_cmd(self, tmpfilename, info_dict):
  72. cmd = [self.exe, '--location', '-o', tmpfilename]
  73. for key, val in info_dict['http_headers'].items():
  74. cmd += ['--header', '%s: %s' % (key, val)]
  75. cmd += self._option('--interface', 'source_address')
  76. cmd += self._option('--proxy', 'proxy')
  77. cmd += self._valueless_option('--insecure', 'nocheckcertificate')
  78. cmd += self._configuration_args()
  79. cmd += ['--', info_dict['url']]
  80. return cmd
  81. class AxelFD(ExternalFD):
  82. def _make_cmd(self, tmpfilename, info_dict):
  83. cmd = [self.exe, '-o', tmpfilename]
  84. for key, val in info_dict['http_headers'].items():
  85. cmd += ['-H', '%s: %s' % (key, val)]
  86. cmd += self._configuration_args()
  87. cmd += ['--', info_dict['url']]
  88. return cmd
  89. class WgetFD(ExternalFD):
  90. def _make_cmd(self, tmpfilename, info_dict):
  91. cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies']
  92. for key, val in info_dict['http_headers'].items():
  93. cmd += ['--header', '%s: %s' % (key, val)]
  94. cmd += self._option('--bind-address', 'source_address')
  95. cmd += self._option('--proxy', 'proxy')
  96. cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate')
  97. cmd += self._configuration_args()
  98. cmd += ['--', info_dict['url']]
  99. return cmd
  100. class Aria2cFD(ExternalFD):
  101. def _make_cmd(self, tmpfilename, info_dict):
  102. cmd = [self.exe, '-c']
  103. cmd += self._configuration_args([
  104. '--min-split-size', '1M', '--max-connection-per-server', '4'])
  105. dn = os.path.dirname(tmpfilename)
  106. if dn:
  107. cmd += ['--dir', dn]
  108. cmd += ['--out', os.path.basename(tmpfilename)]
  109. for key, val in info_dict['http_headers'].items():
  110. cmd += ['--header', '%s: %s' % (key, val)]
  111. cmd += self._option('--interface', 'source_address')
  112. cmd += self._option('--all-proxy', 'proxy')
  113. cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
  114. cmd += ['--', info_dict['url']]
  115. return cmd
  116. class HttpieFD(ExternalFD):
  117. def _make_cmd(self, tmpfilename, info_dict):
  118. cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
  119. for key, val in info_dict['http_headers'].items():
  120. cmd += ['%s:%s' % (key, val)]
  121. return cmd
  122. _BY_NAME = dict(
  123. (klass.get_basename(), klass)
  124. for name, klass in globals().items()
  125. if name.endswith('FD') and name != 'ExternalFD'
  126. )
  127. def list_external_downloaders():
  128. return sorted(_BY_NAME.keys())
  129. def get_external_downloader(external_downloader):
  130. """ Given the name of the executable, see whether we support the given
  131. downloader . """
  132. # Drop .exe extension on Windows
  133. bn = os.path.splitext(os.path.basename(external_downloader))[0]
  134. return _BY_NAME[bn]