Files
lsl-shell/lib.py

83 lines
2.2 KiB
Python
Raw Normal View History

from json.decoder import JSONDecodeError
from typing import Dict
import requests
class InvalidResponseError(Exception):
pass
class ErrorReceived(Exception):
pass
def send_cmd(url: str, secret_key: str, cmd: str) -> Dict:
"""Send a command to the endpoint and return the response."""
data = {"secret_key": secret_key, "command": cmd}
try:
2020-04-13 23:15:15 +02:00
response = requests.post(url, json=data, verify=False, timeout=5)
2020-04-13 15:57:44 +02:00
response.raise_for_status()
except requests.exceptions.HTTPError as e:
2020-04-13 16:03:34 +02:00
code = e.response.status_code
2020-04-13 23:15:15 +02:00
if code == 423 or code == 401:
error_message = e.response.json().get("error")
2020-04-13 16:51:51 +02:00
elif code == 504:
2020-04-13 23:15:15 +02:00
error_message = e.response.content.decode("UTF-8")
2020-04-13 20:22:37 +02:00
elif code == 404:
2020-04-13 23:15:15 +02:00
error_message = "Endpoint URL not found"
2020-04-13 20:22:37 +02:00
elif code == 500:
2020-04-13 23:15:15 +02:00
error_message = "Internal SL server error"
2020-04-13 15:57:44 +02:00
else:
raise e
2020-04-13 23:15:15 +02:00
e.args = (error_message,)
raise e
2020-04-13 16:00:17 +02:00
try:
response_data = response.json()
2020-04-13 23:15:15 +02:00
except JSONDecodeError as e:
e.args = ("Response contains invalid json",)
raise e
2020-04-13 16:00:17 +02:00
error = response_data.get("error", None)
if error:
2020-04-13 23:15:15 +02:00
raise ErrorReceived(error)
return response_data
def connect(url: str, secret_key: str) -> str:
"""Connect to the given URL.
Returns the UUID of the endpoint."""
uuid = send_cmd(url, secret_key, "connect").get("uuid", None)
if not uuid:
2020-04-14 00:29:32 +02:00
raise InvalidResponseError("Endpoint did not return its UUID")
return uuid
def disconnect(url: str, secret_key: str) -> bool:
"""Disconnect from the endpoint.
Returns True if the endpoint responded with an acknlowledgement."""
try:
result = send_cmd(url, secret_key, "disconnect").get("result", None)
if result == "disconnected":
return True
except JSONDecodeError:
pass
return False
def get_available_commands(url: str, secret_key: str) -> Dict:
"""Get a list of available commands from the endpoint."""
cmds = send_cmd(url, secret_key, "get_commands").get("available_commands", None)
if not cmds:
2020-04-14 00:29:32 +02:00
raise InvalidResponseError("Endpoint did not return command list")
return cmds