bunkerweb/utils/ApiCaller.py
2022-06-03 17:24:14 +02:00

45 lines
1.5 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from io import BytesIO
import tarfile
from logger import log
class ApiCaller :
def __init__(self, apis=[]) :
self.__apis = apis
def _set_apis(self, apis) :
self.__apis = apis
def _get_apis(self) :
return self.__apis
def _send_to_apis(self, method, url, files=None, data=None) :
ret = True
for api in self.__apis :
if files is not None :
for file, buffer in files.items() :
buffer.seek(0, 0)
sent, err, status, resp = api.request(method, url, files=files, data=data)
if not sent :
ret = False
log("API", "", "Can't send API request to " + api.get_endpoint() + url + " : " + err)
else :
if status != 200 :
ret = False
log("API", "", "Error while sending API request to " + api.get_endpoint() + url + " : status = " + resp["status"] + ", msg = " + resp["msg"])
else :
log("API", "", "Successfully sent API request to " + api.get_endpoint() + url)
return ret
def _send_files(self, path, url) :
ret = True
tgz = BytesIO()
with tarfile.open(mode="w:gz", fileobj=tgz) as tf :
tf.add(path, arcname=".")
tgz.seek(0, 0)
files = {"archive.tar.gz": tgz}
if not self._send_to_apis("POST", url, files=files) :
ret = False
tgz.close()
return ret