|
| 1 | +from ctfcli.core.api import API |
| 2 | +from ctfcli.core.exceptions import InstanceConfigException |
| 3 | + |
| 4 | + |
| 5 | +class ServerConfig: |
| 6 | + @staticmethod |
| 7 | + def get(key: str) -> str: |
| 8 | + api = API() |
| 9 | + resp = api.get(f"/api/v1/configs/{key}") |
| 10 | + if resp.ok is False: |
| 11 | + raise InstanceConfigException( |
| 12 | + f"Could not get config {key=} because '{resp.content}' with {resp.status_code}" |
| 13 | + ) |
| 14 | + resp = resp.json() |
| 15 | + return resp["data"]["value"] |
| 16 | + |
| 17 | + @staticmethod |
| 18 | + def set(key: str, value: str) -> bool: |
| 19 | + api = API() |
| 20 | + data = { |
| 21 | + "value": value, |
| 22 | + } |
| 23 | + resp = api.patch(f"/api/v1/configs/{key}", json=data) |
| 24 | + if resp.ok is False: |
| 25 | + raise InstanceConfigException( |
| 26 | + f"Could not get config {key=} because '{resp.content}' with {resp.status_code}" |
| 27 | + ) |
| 28 | + resp = resp.json() |
| 29 | + |
| 30 | + return resp["success"] |
| 31 | + |
| 32 | + @staticmethod |
| 33 | + def getall(): |
| 34 | + api = API() |
| 35 | + resp = api.get("/api/v1/configs") |
| 36 | + if resp.ok is False: |
| 37 | + raise InstanceConfigException(f"Could not get configs because '{resp.content}' with {resp.status_code}") |
| 38 | + resp = resp.json() |
| 39 | + configs = resp["data"] |
| 40 | + |
| 41 | + config = {} |
| 42 | + for c in configs: |
| 43 | + # Ignore alembic_version configs as they are managed by plugins |
| 44 | + if c["key"].endswith("alembic_version") is False: |
| 45 | + config[c["key"]] = c["value"] |
| 46 | + |
| 47 | + # Not much point in saving internal configs |
| 48 | + del config["ctf_version"] |
| 49 | + del config["version_latest"] |
| 50 | + del config["next_update_check"] |
| 51 | + del config["setup"] |
| 52 | + |
| 53 | + return config |
| 54 | + |
| 55 | + @staticmethod |
| 56 | + def setall(configs) -> list[str]: |
| 57 | + failed = [] |
| 58 | + for k, v in configs.items(): |
| 59 | + try: |
| 60 | + ServerConfig.set(key=k, value=v) |
| 61 | + except InstanceConfigException: |
| 62 | + failed.append(k) |
| 63 | + return failed |
0 commit comments