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