[downloader/external] Simplify
[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         command_part = []
50         source_address = self.ydl.params.get('source_address')
51         if source_address:
52             command_part = [command_option, source_address]
53         return command_part
54
55     def _call_downloader(self, tmpfilename, info_dict):
56         """ Either overwrite this or implement _make_cmd """
57         cmd = self._make_cmd(tmpfilename, info_dict)
58
59         if sys.platform == 'win32' and sys.version_info < (3, 0):
60             # Windows subprocess module does not actually support Unicode
61             # on Python 2.x
62             # See http://stackoverflow.com/a/9951851/35070
63             subprocess_encoding = sys.getfilesystemencoding()
64             cmd = [a.encode(subprocess_encoding, 'ignore') for a in cmd]
65         else:
66             subprocess_encoding = None
67         self._debug_cmd(cmd, subprocess_encoding)
68
69         p = subprocess.Popen(
70             cmd, stderr=subprocess.PIPE)
71         _, stderr = p.communicate()
72         if p.returncode != 0:
73             self.to_stderr(stderr)
74         return p.returncode
75
76
77 class CurlFD(ExternalFD):
78     def _make_cmd(self, tmpfilename, info_dict):
79         cmd = [self.exe, '-o', tmpfilename]
80         for key, val in info_dict['http_headers'].items():
81             cmd += ['--header', '%s: %s' % (key, val)]
82         cmd += self._source_address('--interface')
83         cmd += ['--', info_dict['url']]
84         return cmd
85
86
87 class WgetFD(ExternalFD):
88     def _make_cmd(self, tmpfilename, info_dict):
89         cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies']
90         for key, val in info_dict['http_headers'].items():
91             cmd += ['--header', '%s: %s' % (key, val)]
92         cmd += self._source_address('--bind-address')
93         cmd += ['--', info_dict['url']]
94         return cmd
95
96
97 class Aria2cFD(ExternalFD):
98     def _make_cmd(self, tmpfilename, info_dict):
99         cmd = [
100             self.exe, '-c',
101             '--min-split-size', '1M', '--max-connection-per-server', '4']
102         dn = os.path.dirname(tmpfilename)
103         if dn:
104             cmd += ['--dir', dn]
105         cmd += ['--out', os.path.basename(tmpfilename)]
106         for key, val in info_dict['http_headers'].items():
107             cmd += ['--header', '%s: %s' % (key, val)]
108         cmd += self._source_address('--interface')
109         cmd += ['--', info_dict['url']]
110         return cmd
111
112 _BY_NAME = dict(
113     (klass.get_basename(), klass)
114     for name, klass in globals().items()
115     if name.endswith('FD') and name != 'ExternalFD'
116 )
117
118
119 def list_external_downloaders():
120     return sorted(_BY_NAME.keys())
121
122
123 def get_external_downloader(external_downloader):
124     """ Given the name of the executable, see whether we support the given
125         downloader . """
126     bn = os.path.basename(external_downloader)
127     return _BY_NAME[bn]