]> jfr.im git - yt-dlp.git/blob - yt_dlp/downloader/external.py
Refactor (See desc)
[yt-dlp.git] / yt_dlp / 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 try:
10 from Crypto.Cipher import AES
11 can_decrypt_frag = True
12 except ImportError:
13 can_decrypt_frag = False
14
15 from .common import FileDownloader
16 from ..compat import (
17 compat_setenv,
18 compat_str,
19 )
20 from ..postprocessor.ffmpeg import FFmpegPostProcessor, EXT_TO_OUT_FORMATS
21 from ..utils import (
22 cli_option,
23 cli_valueless_option,
24 cli_bool_option,
25 cli_configuration_args,
26 encodeFilename,
27 error_to_compat_str,
28 encodeArgument,
29 handle_youtubedl_headers,
30 check_executable,
31 is_outdated_version,
32 process_communicate_or_kill,
33 sanitized_Request,
34 sanitize_open,
35 )
36
37
38 class ExternalFD(FileDownloader):
39 SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps')
40
41 def real_download(self, filename, info_dict):
42 self.report_destination(filename)
43 tmpfilename = self.temp_name(filename)
44
45 try:
46 started = time.time()
47 retval = self._call_downloader(tmpfilename, info_dict)
48 except KeyboardInterrupt:
49 if not info_dict.get('is_live'):
50 raise
51 # Live stream downloading cancellation should be considered as
52 # correct and expected termination thus all postprocessing
53 # should take place
54 retval = 0
55 self.to_screen('[%s] Interrupted by user' % self.get_basename())
56
57 if retval == 0:
58 status = {
59 'filename': filename,
60 'status': 'finished',
61 'elapsed': time.time() - started,
62 }
63 if filename != '-':
64 fsize = os.path.getsize(encodeFilename(tmpfilename))
65 self.to_screen('\r[%s] Downloaded %s bytes' % (self.get_basename(), fsize))
66 self.try_rename(tmpfilename, filename)
67 status.update({
68 'downloaded_bytes': fsize,
69 'total_bytes': fsize,
70 })
71 self._hook_progress(status)
72 return True
73 else:
74 self.to_stderr('\n')
75 self.report_error('%s exited with code %d' % (
76 self.get_basename(), retval))
77 return False
78
79 @classmethod
80 def get_basename(cls):
81 return cls.__name__[:-2].lower()
82
83 @property
84 def exe(self):
85 return self.params.get('external_downloader')
86
87 @classmethod
88 def available(cls, path=None):
89 return check_executable(path or cls.get_basename(), [cls.AVAILABLE_OPT])
90
91 @classmethod
92 def supports(cls, info_dict):
93 return info_dict['protocol'] in cls.SUPPORTED_PROTOCOLS
94
95 @classmethod
96 def can_download(cls, info_dict, path=None):
97 return cls.available(path) and cls.supports(info_dict)
98
99 def _option(self, command_option, param):
100 return cli_option(self.params, command_option, param)
101
102 def _bool_option(self, command_option, param, true_value='true', false_value='false', separator=None):
103 return cli_bool_option(self.params, command_option, param, true_value, false_value, separator)
104
105 def _valueless_option(self, command_option, param, expected_value=True):
106 return cli_valueless_option(self.params, command_option, param, expected_value)
107
108 def _configuration_args(self, *args, **kwargs):
109 return cli_configuration_args(
110 self.params.get('external_downloader_args'),
111 [self.get_basename(), 'default'],
112 *args, **kwargs)
113
114 def _call_downloader(self, tmpfilename, info_dict):
115 """ Either overwrite this or implement _make_cmd """
116 cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
117
118 self._debug_cmd(cmd)
119
120 p = subprocess.Popen(
121 cmd, stderr=subprocess.PIPE)
122 _, stderr = process_communicate_or_kill(p)
123 if p.returncode != 0:
124 self.to_stderr(stderr.decode('utf-8', 'replace'))
125
126 if 'fragments' in info_dict:
127 file_list = []
128 dest, _ = sanitize_open(tmpfilename, 'wb')
129 for i, fragment in enumerate(info_dict['fragments']):
130 file = '%s-Frag%d' % (tmpfilename, i)
131 decrypt_info = fragment.get('decrypt_info')
132 src, _ = sanitize_open(file, 'rb')
133 if decrypt_info:
134 if decrypt_info['METHOD'] == 'AES-128':
135 iv = decrypt_info.get('IV')
136 decrypt_info['KEY'] = decrypt_info.get('KEY') or self.ydl.urlopen(
137 self._prepare_url(info_dict, info_dict.get('_decryption_key_url') or decrypt_info['URI'])).read()
138 encrypted_data = src.read()
139 decrypted_data = AES.new(
140 decrypt_info['KEY'], AES.MODE_CBC, iv).decrypt(encrypted_data)
141 dest.write(decrypted_data)
142 else:
143 fragment_data = src.read()
144 dest.write(fragment_data)
145 else:
146 fragment_data = src.read()
147 dest.write(fragment_data)
148 src.close()
149 file_list.append(file)
150 dest.close()
151 if not self.params.get('keep_fragments', False):
152 for file_path in file_list:
153 try:
154 os.remove(file_path)
155 except OSError as ose:
156 self.report_error("Unable to delete file %s; %s" % (file_path, error_to_compat_str(ose)))
157 try:
158 file_path = '%s.frag.urls' % tmpfilename
159 os.remove(file_path)
160 except OSError as ose:
161 self.report_error("Unable to delete file %s; %s" % (file_path, error_to_compat_str(ose)))
162
163 return p.returncode
164
165 def _prepare_url(self, info_dict, url):
166 headers = info_dict.get('http_headers')
167 return sanitized_Request(url, None, headers) if headers else url
168
169
170 class CurlFD(ExternalFD):
171 AVAILABLE_OPT = '-V'
172
173 def _make_cmd(self, tmpfilename, info_dict):
174 cmd = [self.exe, '--location', '-o', tmpfilename]
175 if info_dict.get('http_headers') is not None:
176 for key, val in info_dict['http_headers'].items():
177 cmd += ['--header', '%s: %s' % (key, val)]
178
179 cmd += self._bool_option('--continue-at', 'continuedl', '-', '0')
180 cmd += self._valueless_option('--silent', 'noprogress')
181 cmd += self._valueless_option('--verbose', 'verbose')
182 cmd += self._option('--limit-rate', 'ratelimit')
183 retry = self._option('--retry', 'retries')
184 if len(retry) == 2:
185 if retry[1] in ('inf', 'infinite'):
186 retry[1] = '2147483647'
187 cmd += retry
188 cmd += self._option('--max-filesize', 'max_filesize')
189 cmd += self._option('--interface', 'source_address')
190 cmd += self._option('--proxy', 'proxy')
191 cmd += self._valueless_option('--insecure', 'nocheckcertificate')
192 cmd += self._configuration_args()
193 cmd += ['--', info_dict['url']]
194 return cmd
195
196 def _call_downloader(self, tmpfilename, info_dict):
197 cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
198
199 self._debug_cmd(cmd)
200
201 # curl writes the progress to stderr so don't capture it.
202 p = subprocess.Popen(cmd)
203 process_communicate_or_kill(p)
204 return p.returncode
205
206
207 class AxelFD(ExternalFD):
208 AVAILABLE_OPT = '-V'
209
210 def _make_cmd(self, tmpfilename, info_dict):
211 cmd = [self.exe, '-o', tmpfilename]
212 if info_dict.get('http_headers') is not None:
213 for key, val in info_dict['http_headers'].items():
214 cmd += ['-H', '%s: %s' % (key, val)]
215 cmd += self._configuration_args()
216 cmd += ['--', info_dict['url']]
217 return cmd
218
219
220 class WgetFD(ExternalFD):
221 AVAILABLE_OPT = '--version'
222
223 def _make_cmd(self, tmpfilename, info_dict):
224 cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies']
225 if info_dict.get('http_headers') is not None:
226 for key, val in info_dict['http_headers'].items():
227 cmd += ['--header', '%s: %s' % (key, val)]
228 cmd += self._option('--limit-rate', 'ratelimit')
229 retry = self._option('--tries', 'retries')
230 if len(retry) == 2:
231 if retry[1] in ('inf', 'infinite'):
232 retry[1] = '0'
233 cmd += retry
234 cmd += self._option('--bind-address', 'source_address')
235 cmd += self._option('--proxy', 'proxy')
236 cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate')
237 cmd += self._configuration_args()
238 cmd += ['--', info_dict['url']]
239 return cmd
240
241
242 class Aria2cFD(ExternalFD):
243 AVAILABLE_OPT = '-v'
244 SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps', 'frag_urls')
245
246 @staticmethod
247 def supports_manifest(manifest):
248 UNSUPPORTED_FEATURES = [
249 r'#EXT-X-BYTERANGE', # playlists composed of byte ranges of media files [1]
250 # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.2
251 ]
252 check_results = (not re.search(feature, manifest) for feature in UNSUPPORTED_FEATURES)
253 return all(check_results)
254
255 def _make_cmd(self, tmpfilename, info_dict):
256 cmd = [self.exe, '-c']
257 dn = os.path.dirname(tmpfilename)
258 if 'fragments' not in info_dict:
259 cmd += ['--out', os.path.basename(tmpfilename)]
260 verbose_level_args = ['--console-log-level=warn', '--summary-interval=0']
261 cmd += self._configuration_args(['--file-allocation=none', '-x16', '-j16', '-s16'] + verbose_level_args)
262 if dn:
263 cmd += ['--dir', dn]
264 if info_dict.get('http_headers') is not None:
265 for key, val in info_dict['http_headers'].items():
266 cmd += ['--header', '%s: %s' % (key, val)]
267 cmd += self._option('--interface', 'source_address')
268 cmd += self._option('--all-proxy', 'proxy')
269 cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
270 cmd += self._bool_option('--remote-time', 'updatetime', 'true', 'false', '=')
271 cmd += ['--auto-file-renaming=false']
272 if 'fragments' in info_dict:
273 cmd += verbose_level_args
274 cmd += ['--uri-selector', 'inorder', '--download-result=hide']
275 url_list_file = '%s.frag.urls' % tmpfilename
276 url_list = []
277 for i, fragment in enumerate(info_dict['fragments']):
278 tmpsegmentname = '%s-Frag%d' % (os.path.basename(tmpfilename), i)
279 url_list.append('%s\n\tout=%s' % (fragment['url'], tmpsegmentname))
280 stream, _ = sanitize_open(url_list_file, 'wb')
281 stream.write('\n'.join(url_list).encode('utf-8'))
282 stream.close()
283
284 cmd += ['-i', url_list_file]
285 else:
286 cmd += ['--', info_dict['url']]
287 return cmd
288
289
290 class HttpieFD(ExternalFD):
291 @classmethod
292 def available(cls, path=None):
293 return check_executable(path or 'http', ['--version'])
294
295 def _make_cmd(self, tmpfilename, info_dict):
296 cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
297
298 if info_dict.get('http_headers') is not None:
299 for key, val in info_dict['http_headers'].items():
300 cmd += ['%s:%s' % (key, val)]
301 return cmd
302
303
304 class FFmpegFD(ExternalFD):
305 SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps', 'm3u8', 'rtsp', 'rtmp', 'mms')
306
307 @classmethod
308 def available(cls, path=None): # path is ignored for ffmpeg
309 return FFmpegPostProcessor().available
310
311 def _call_downloader(self, tmpfilename, info_dict):
312 url = info_dict['url']
313 ffpp = FFmpegPostProcessor(downloader=self)
314 if not ffpp.available:
315 self.report_error('m3u8 download detected but ffmpeg could not be found. Please install')
316 return False
317 ffpp.check_version()
318
319 args = [ffpp.executable, '-y']
320
321 for log_level in ('quiet', 'verbose'):
322 if self.params.get(log_level, False):
323 args += ['-loglevel', log_level]
324 break
325
326 seekable = info_dict.get('_seekable')
327 if seekable is not None:
328 # setting -seekable prevents ffmpeg from guessing if the server
329 # supports seeking(by adding the header `Range: bytes=0-`), which
330 # can cause problems in some cases
331 # https://github.com/ytdl-org/youtube-dl/issues/11800#issuecomment-275037127
332 # http://trac.ffmpeg.org/ticket/6125#comment:10
333 args += ['-seekable', '1' if seekable else '0']
334
335 args += self._configuration_args()
336
337 # start_time = info_dict.get('start_time') or 0
338 # if start_time:
339 # args += ['-ss', compat_str(start_time)]
340 # end_time = info_dict.get('end_time')
341 # if end_time:
342 # args += ['-t', compat_str(end_time - start_time)]
343
344 if info_dict.get('http_headers') is not None and re.match(r'^https?://', url):
345 # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
346 # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
347 headers = handle_youtubedl_headers(info_dict['http_headers'])
348 args += [
349 '-headers',
350 ''.join('%s: %s\r\n' % (key, val) for key, val in headers.items())]
351
352 env = None
353 proxy = self.params.get('proxy')
354 if proxy:
355 if not re.match(r'^[\da-zA-Z]+://', proxy):
356 proxy = 'http://%s' % proxy
357
358 if proxy.startswith('socks'):
359 self.report_warning(
360 '%s does not support SOCKS proxies. Downloading is likely to fail. '
361 'Consider adding --hls-prefer-native to your command.' % self.get_basename())
362
363 # Since December 2015 ffmpeg supports -http_proxy option (see
364 # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
365 # We could switch to the following code if we are able to detect version properly
366 # args += ['-http_proxy', proxy]
367 env = os.environ.copy()
368 compat_setenv('HTTP_PROXY', proxy, env=env)
369 compat_setenv('http_proxy', proxy, env=env)
370
371 protocol = info_dict.get('protocol')
372
373 if protocol == 'rtmp':
374 player_url = info_dict.get('player_url')
375 page_url = info_dict.get('page_url')
376 app = info_dict.get('app')
377 play_path = info_dict.get('play_path')
378 tc_url = info_dict.get('tc_url')
379 flash_version = info_dict.get('flash_version')
380 live = info_dict.get('rtmp_live', False)
381 conn = info_dict.get('rtmp_conn')
382 if player_url is not None:
383 args += ['-rtmp_swfverify', player_url]
384 if page_url is not None:
385 args += ['-rtmp_pageurl', page_url]
386 if app is not None:
387 args += ['-rtmp_app', app]
388 if play_path is not None:
389 args += ['-rtmp_playpath', play_path]
390 if tc_url is not None:
391 args += ['-rtmp_tcurl', tc_url]
392 if flash_version is not None:
393 args += ['-rtmp_flashver', flash_version]
394 if live:
395 args += ['-rtmp_live', 'live']
396 if isinstance(conn, list):
397 for entry in conn:
398 args += ['-rtmp_conn', entry]
399 elif isinstance(conn, compat_str):
400 args += ['-rtmp_conn', conn]
401
402 args += ['-i', url, '-c', 'copy']
403
404 if self.params.get('test', False):
405 args += ['-fs', compat_str(self._TEST_FILE_SIZE)]
406
407 if protocol in ('m3u8', 'm3u8_native'):
408 use_mpegts = (tmpfilename == '-') or self.params.get('hls_use_mpegts')
409 if use_mpegts is None:
410 use_mpegts = info_dict.get('is_live')
411 if use_mpegts:
412 args += ['-f', 'mpegts']
413 else:
414 args += ['-f', 'mp4']
415 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')):
416 args += ['-bsf:a', 'aac_adtstoasc']
417 elif protocol == 'rtmp':
418 args += ['-f', 'flv']
419 else:
420 args += ['-f', EXT_TO_OUT_FORMATS.get(info_dict['ext'], info_dict['ext'])]
421
422 args = [encodeArgument(opt) for opt in args]
423 args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
424
425 self._debug_cmd(args)
426
427 proc = subprocess.Popen(args, stdin=subprocess.PIPE, env=env)
428 try:
429 retval = proc.wait()
430 except BaseException as e:
431 # subprocces.run would send the SIGKILL signal to ffmpeg and the
432 # mp4 file couldn't be played, but if we ask ffmpeg to quit it
433 # produces a file that is playable (this is mostly useful for live
434 # streams). Note that Windows is not affected and produces playable
435 # files (see https://github.com/ytdl-org/youtube-dl/issues/8300).
436 if isinstance(e, KeyboardInterrupt) and sys.platform != 'win32':
437 process_communicate_or_kill(proc, b'q')
438 else:
439 proc.kill()
440 proc.wait()
441 raise
442 return retval
443
444
445 class AVconvFD(FFmpegFD):
446 pass
447
448
449 _BY_NAME = dict(
450 (klass.get_basename(), klass)
451 for name, klass in globals().items()
452 if name.endswith('FD') and name != 'ExternalFD'
453 )
454
455
456 def list_external_downloaders():
457 return sorted(_BY_NAME.keys())
458
459
460 def get_external_downloader(external_downloader):
461 """ Given the name of the executable, see whether we support the given
462 downloader . """
463 # Drop .exe extension on Windows
464 bn = os.path.splitext(os.path.basename(external_downloader))[0]
465 return _BY_NAME[bn]