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