[external/curl] respect more downloader options and display progress
[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 import re
7
8 from .common import FileDownloader
9 from ..compat import compat_setenv
10 from ..postprocessor.ffmpeg import FFmpegPostProcessor, EXT_TO_OUT_FORMATS
11 from ..utils import (
12     cli_option,
13     cli_valueless_option,
14     cli_bool_option,
15     cli_configuration_args,
16     encodeFilename,
17     encodeArgument,
18     handle_youtubedl_headers,
19     check_executable,
20 )
21
22
23 class ExternalFD(FileDownloader):
24     def real_download(self, filename, info_dict):
25         self.report_destination(filename)
26         tmpfilename = self.temp_name(filename)
27
28         retval = self._call_downloader(tmpfilename, info_dict)
29         if retval == 0:
30             fsize = os.path.getsize(encodeFilename(tmpfilename))
31             self.to_screen('\r[%s] Downloaded %s bytes' % (self.get_basename(), fsize))
32             self.try_rename(tmpfilename, filename)
33             self._hook_progress({
34                 'downloaded_bytes': fsize,
35                 'total_bytes': fsize,
36                 'filename': filename,
37                 'status': 'finished',
38             })
39             return True
40         else:
41             self.to_stderr('\n')
42             self.report_error('%s exited with code %d' % (
43                 self.get_basename(), retval))
44             return False
45
46     @classmethod
47     def get_basename(cls):
48         return cls.__name__[:-2].lower()
49
50     @property
51     def exe(self):
52         return self.params.get('external_downloader')
53
54     @classmethod
55     def available(cls):
56         return check_executable(cls.get_basename(), [cls.AVAILABLE_OPT])
57
58     @classmethod
59     def supports(cls, info_dict):
60         return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps')
61
62     @classmethod
63     def can_download(cls, info_dict):
64         return cls.available() and cls.supports(info_dict)
65
66     def _option(self, command_option, param):
67         return cli_option(self.params, command_option, param)
68
69     def _bool_option(self, command_option, param, true_value='true', false_value='false', separator=None):
70         return cli_bool_option(self.params, command_option, param, true_value, false_value, separator)
71
72     def _valueless_option(self, command_option, param, expected_value=True):
73         return cli_valueless_option(self.params, command_option, param, expected_value)
74
75     def _configuration_args(self, default=[]):
76         return cli_configuration_args(self.params, 'external_downloader_args', default)
77
78     def _call_downloader(self, tmpfilename, info_dict):
79         """ Either overwrite this or implement _make_cmd """
80         cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
81
82         self._debug_cmd(cmd)
83
84         p = subprocess.Popen(
85             cmd, stderr=subprocess.PIPE)
86         _, stderr = p.communicate()
87         if p.returncode != 0:
88             self.to_stderr(stderr.decode('utf-8', 'replace'))
89         return p.returncode
90
91
92 class CurlFD(ExternalFD):
93     AVAILABLE_OPT = '-V'
94
95     def _make_cmd(self, tmpfilename, info_dict):
96         cmd = [self.exe, '--location', '-o', tmpfilename]
97         for key, val in info_dict['http_headers'].items():
98             cmd += ['--header', '%s: %s' % (key, val)]
99         cmd += self._bool_option('--continue-at', 'continuedl', '-', '0')
100         cmd += self._valueless_option('--silent', 'noprogress')
101         cmd += self._valueless_option('--verbose', 'verbose')
102         cmd += self._option('--limit-rate', 'ratelimit')
103         cmd += self._option('--retry', 'retries')
104         cmd += self._option('--max-filesize', 'max_filesize')
105         cmd += self._option('--interface', 'source_address')
106         cmd += self._option('--proxy', 'proxy')
107         cmd += self._valueless_option('--insecure', 'nocheckcertificate')
108         cmd += self._configuration_args()
109         cmd += ['--', info_dict['url']]
110         return cmd
111
112     def _call_downloader(self, tmpfilename, info_dict):
113         cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
114
115         self._debug_cmd(cmd)
116
117         p = subprocess.Popen(cmd)
118         p.communicate()
119         return p.returncode
120
121
122 class AxelFD(ExternalFD):
123     AVAILABLE_OPT = '-V'
124
125     def _make_cmd(self, tmpfilename, info_dict):
126         cmd = [self.exe, '-o', tmpfilename]
127         for key, val in info_dict['http_headers'].items():
128             cmd += ['-H', '%s: %s' % (key, val)]
129         cmd += self._configuration_args()
130         cmd += ['--', info_dict['url']]
131         return cmd
132
133
134 class WgetFD(ExternalFD):
135     AVAILABLE_OPT = '--version'
136
137     def _make_cmd(self, tmpfilename, info_dict):
138         cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies']
139         for key, val in info_dict['http_headers'].items():
140             cmd += ['--header', '%s: %s' % (key, val)]
141         cmd += self._option('--bind-address', 'source_address')
142         cmd += self._option('--proxy', 'proxy')
143         cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate')
144         cmd += self._configuration_args()
145         cmd += ['--', info_dict['url']]
146         return cmd
147
148
149 class Aria2cFD(ExternalFD):
150     AVAILABLE_OPT = '-v'
151
152     def _make_cmd(self, tmpfilename, info_dict):
153         cmd = [self.exe, '-c']
154         cmd += self._configuration_args([
155             '--min-split-size', '1M', '--max-connection-per-server', '4'])
156         dn = os.path.dirname(tmpfilename)
157         if dn:
158             cmd += ['--dir', dn]
159         cmd += ['--out', os.path.basename(tmpfilename)]
160         for key, val in info_dict['http_headers'].items():
161             cmd += ['--header', '%s: %s' % (key, val)]
162         cmd += self._option('--interface', 'source_address')
163         cmd += self._option('--all-proxy', 'proxy')
164         cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
165         cmd += ['--', info_dict['url']]
166         return cmd
167
168
169 class HttpieFD(ExternalFD):
170     @classmethod
171     def available(cls):
172         return check_executable('http', ['--version'])
173
174     def _make_cmd(self, tmpfilename, info_dict):
175         cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
176         for key, val in info_dict['http_headers'].items():
177             cmd += ['%s:%s' % (key, val)]
178         return cmd
179
180
181 class FFmpegFD(ExternalFD):
182     @classmethod
183     def supports(cls, info_dict):
184         return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps', 'm3u8', 'rtsp', 'rtmp', 'mms')
185
186     @classmethod
187     def available(cls):
188         return FFmpegPostProcessor().available
189
190     def _call_downloader(self, tmpfilename, info_dict):
191         url = info_dict['url']
192         ffpp = FFmpegPostProcessor(downloader=self)
193         if not ffpp.available:
194             self.report_error('m3u8 download detected but ffmpeg or avconv could not be found. Please install one.')
195             return False
196         ffpp.check_version()
197
198         args = [ffpp.executable, '-y']
199
200         args += self._configuration_args()
201
202         # start_time = info_dict.get('start_time') or 0
203         # if start_time:
204         #     args += ['-ss', compat_str(start_time)]
205         # end_time = info_dict.get('end_time')
206         # if end_time:
207         #     args += ['-t', compat_str(end_time - start_time)]
208
209         if info_dict['http_headers'] and re.match(r'^https?://', url):
210             # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
211             # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
212             headers = handle_youtubedl_headers(info_dict['http_headers'])
213             args += [
214                 '-headers',
215                 ''.join('%s: %s\r\n' % (key, val) for key, val in headers.items())]
216
217         env = None
218         proxy = self.params.get('proxy')
219         if proxy:
220             if not re.match(r'^[\da-zA-Z]+://', proxy):
221                 proxy = 'http://%s' % proxy
222             # Since December 2015 ffmpeg supports -http_proxy option (see
223             # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
224             # We could switch to the following code if we are able to detect version properly
225             # args += ['-http_proxy', proxy]
226             env = os.environ.copy()
227             compat_setenv('HTTP_PROXY', proxy, env=env)
228             compat_setenv('http_proxy', proxy, env=env)
229
230         protocol = info_dict.get('protocol')
231
232         if protocol == 'rtmp':
233             player_url = info_dict.get('player_url')
234             page_url = info_dict.get('page_url')
235             app = info_dict.get('app')
236             play_path = info_dict.get('play_path')
237             tc_url = info_dict.get('tc_url')
238             flash_version = info_dict.get('flash_version')
239             live = info_dict.get('rtmp_live', False)
240             if player_url is not None:
241                 args += ['-rtmp_swfverify', player_url]
242             if page_url is not None:
243                 args += ['-rtmp_pageurl', page_url]
244             if app is not None:
245                 args += ['-rtmp_app', app]
246             if play_path is not None:
247                 args += ['-rtmp_playpath', play_path]
248             if tc_url is not None:
249                 args += ['-rtmp_tcurl', tc_url]
250             if flash_version is not None:
251                 args += ['-rtmp_flashver', flash_version]
252             if live:
253                 args += ['-rtmp_live', 'live']
254
255         args += ['-i', url, '-c', 'copy']
256         if protocol in ('m3u8', 'm3u8_native'):
257             if self.params.get('hls_use_mpegts', False) or tmpfilename == '-':
258                 args += ['-f', 'mpegts']
259             else:
260                 args += ['-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
261         elif protocol == 'rtmp':
262             args += ['-f', 'flv']
263         else:
264             args += ['-f', EXT_TO_OUT_FORMATS.get(info_dict['ext'], info_dict['ext'])]
265
266         args = [encodeArgument(opt) for opt in args]
267         args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
268
269         self._debug_cmd(args)
270
271         proc = subprocess.Popen(args, stdin=subprocess.PIPE, env=env)
272         try:
273             retval = proc.wait()
274         except KeyboardInterrupt:
275             # subprocces.run would send the SIGKILL signal to ffmpeg and the
276             # mp4 file couldn't be played, but if we ask ffmpeg to quit it
277             # produces a file that is playable (this is mostly useful for live
278             # streams). Note that Windows is not affected and produces playable
279             # files (see https://github.com/rg3/youtube-dl/issues/8300).
280             if sys.platform != 'win32':
281                 proc.communicate(b'q')
282             raise
283         return retval
284
285
286 class AVconvFD(FFmpegFD):
287     pass
288
289 _BY_NAME = dict(
290     (klass.get_basename(), klass)
291     for name, klass in globals().items()
292     if name.endswith('FD') and name != 'ExternalFD'
293 )
294
295
296 def list_external_downloaders():
297     return sorted(_BY_NAME.keys())
298
299
300 def get_external_downloader(external_downloader):
301     """ Given the name of the executable, see whether we support the given
302         downloader . """
303     # Drop .exe extension on Windows
304     bn = os.path.splitext(os.path.basename(external_downloader))[0]
305     return _BY_NAME[bn]