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