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