external.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  80. stdout, stderr = p.communicate()
  81. if p.returncode != 0:
  82. self.to_stderr(stderr)
  83. return p.returncode
  84. class WgetFD(ExternalFD):
  85. def _make_cmd(self, tmpfilename, info_dict):
  86. cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies']
  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. _BY_NAME = dict(
  92. (klass.get_basename(), klass)
  93. for name, klass in globals().items()
  94. if name.endswith('FD') and name != 'ExternalFD'
  95. )
  96. def list_external_downloaders():
  97. return sorted(_BY_NAME.keys())
  98. def get_external_downloader(external_downloader):
  99. """ Given the name of the executable, see whether we support the given
  100. downloader . """
  101. bn = os.path.basename(external_downloader)
  102. return _BY_NAME[bn]