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