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.

154 lines
4.6 KiB

  1. from __future__ import unicode_literals
  2. import os.path
  3. import subprocess
  4. import sys
  5. from .common import FileDownloader
  6. from ..utils import (
  7. encodeFilename,
  8. std_headers,
  9. )
  10. class ExternalFD(FileDownloader):
  11. def real_download(self, filename, info_dict):
  12. self.report_destination(filename)
  13. tmpfilename = self.temp_name(filename)
  14. retval = self._call_downloader(tmpfilename, info_dict)
  15. if retval == 0:
  16. fsize = os.path.getsize(encodeFilename(tmpfilename))
  17. self.to_screen('\r[%s] Downloaded %s bytes' % (self.get_basename(), fsize))
  18. self.try_rename(tmpfilename, filename)
  19. self._hook_progress({
  20. 'downloaded_bytes': fsize,
  21. 'total_bytes': fsize,
  22. 'filename': filename,
  23. 'status': 'finished',
  24. })
  25. return True
  26. else:
  27. self.to_stderr('\n')
  28. self.report_error('%s exited with code %d' % (
  29. self.get_basename(), retval))
  30. return False
  31. @classmethod
  32. def get_basename(cls):
  33. return cls.__name__[:-2].lower()
  34. @property
  35. def exe(self):
  36. return self.params.get('external_downloader')
  37. @classmethod
  38. def supports(cls, info_dict):
  39. return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps')
  40. def _calc_headers(self, info_dict):
  41. res = std_headers.copy()
  42. ua = info_dict.get('user_agent')
  43. if ua is not None:
  44. res['User-Agent'] = ua
  45. cookies = self._calc_cookies(info_dict)
  46. if cookies:
  47. res['Cookie'] = cookies
  48. return res
  49. def _calc_cookies(self, info_dict):
  50. class _PseudoRequest(object):
  51. def __init__(self, url):
  52. self.url = url
  53. self.headers = {}
  54. self.unverifiable = False
  55. def add_unredirected_header(self, k, v):
  56. self.headers[k] = v
  57. def get_full_url(self):
  58. return self.url
  59. def is_unverifiable(self):
  60. return self.unverifiable
  61. def has_header(self, h):
  62. return h in self.headers
  63. pr = _PseudoRequest(info_dict['url'])
  64. self.ydl.cookiejar.add_cookie_header(pr)
  65. return pr.headers.get('Cookie')
  66. def _call_downloader(self, tmpfilename, info_dict):
  67. """ Either overwrite this or implement _make_cmd """
  68. cmd = self._make_cmd(tmpfilename, info_dict)
  69. if sys.platform == 'win32' and sys.version_info < (3, 0):
  70. # Windows subprocess module does not actually support Unicode
  71. # on Python 2.x
  72. # See http://stackoverflow.com/a/9951851/35070
  73. subprocess_encoding = sys.getfilesystemencoding()
  74. cmd = [a.encode(subprocess_encoding, 'ignore') for a in cmd]
  75. else:
  76. subprocess_encoding = None
  77. self._debug_cmd(cmd, subprocess_encoding)
  78. p = subprocess.Popen(
  79. cmd, stderr=subprocess.PIPE)
  80. _, stderr = p.communicate()
  81. if p.returncode != 0:
  82. self.to_stderr(stderr)
  83. return p.returncode
  84. class CurlFD(ExternalFD):
  85. def _make_cmd(self, tmpfilename, info_dict):
  86. cmd = [self.exe, '-o', tmpfilename]
  87. for key, val in self._calc_headers(info_dict).items():
  88. cmd += ['--header', '%s: %s' % (key, val)]
  89. cmd += ['--', info_dict['url']]
  90. return cmd
  91. class WgetFD(ExternalFD):
  92. def _make_cmd(self, tmpfilename, info_dict):
  93. cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies']
  94. for key, val in self._calc_headers(info_dict).items():
  95. cmd += ['--header', '%s: %s' % (key, val)]
  96. cmd += ['--', info_dict['url']]
  97. return cmd
  98. class Aria2cFD(ExternalFD):
  99. def _make_cmd(self, tmpfilename, info_dict):
  100. cmd = [
  101. self.exe, '-c',
  102. '--min-split-size', '1M', '--max-connection-per-server', '4']
  103. dn = os.path.dirname(tmpfilename)
  104. if dn:
  105. cmd += ['--dir', dn]
  106. cmd += ['--out', os.path.basename(tmpfilename)]
  107. for key, val in self._calc_headers(info_dict).items():
  108. cmd += ['--header', '%s: %s' % (key, val)]
  109. cmd += ['--', info_dict['url']]
  110. return cmd
  111. _BY_NAME = dict(
  112. (klass.get_basename(), klass)
  113. for name, klass in globals().items()
  114. if name.endswith('FD') and name != 'ExternalFD'
  115. )
  116. def list_external_downloaders():
  117. return sorted(_BY_NAME.keys())
  118. def get_external_downloader(external_downloader):
  119. """ Given the name of the executable, see whether we support the given
  120. downloader . """
  121. bn = os.path.basename(external_downloader)
  122. return _BY_NAME[bn]