api/endpoints/xc.py

60 lines
2.3 KiB
Python
Raw Normal View History

2024-08-19 11:42:23 -04:00
#!/usr/bin/env python3.12
2025-02-11 20:01:07 -05:00
import logging
2025-01-11 20:59:10 -05:00
from fastapi import FastAPI, Request, HTTPException
2024-08-19 11:42:23 -04:00
from pydantic import BaseModel
from aiohttp import ClientSession, ClientTimeout
2025-02-11 11:19:52 -05:00
from .constructors import ValidXCRequest
2025-02-11 20:01:07 -05:00
# pylint: disable=invalid-name
2024-11-29 15:33:12 -05:00
2024-08-19 11:42:23 -04:00
class XC(FastAPI):
"""XC (CrossComm) Endpoints"""
2025-02-11 20:01:07 -05:00
def __init__(self, app: FastAPI, util, constants, glob_state) -> None: # pylint: disable=super-init-not-called
2024-08-19 11:42:23 -04:00
self.app = app
self.util = util
self.constants = constants
self.glob_state = glob_state
2024-11-29 15:33:12 -05:00
2025-02-11 20:01:07 -05:00
self.endpoints: dict = {
2024-08-19 11:42:23 -04:00
"xc": self.xc_handler,
}
2024-11-29 15:33:12 -05:00
2024-08-19 11:42:23 -04:00
for endpoint, handler in self.endpoints.items():
2025-01-29 15:48:47 -05:00
app.add_api_route(f"/{endpoint}", handler, methods=["POST"],
include_in_schema=False)
2024-11-29 15:33:12 -05:00
2025-02-11 20:01:07 -05:00
async def xc_handler(self, data: ValidXCRequest, request: Request) -> dict:
"""Handle XC Commands"""
2024-08-19 11:42:23 -04:00
2025-02-05 20:23:06 -05:00
try:
2025-02-11 20:01:07 -05:00
key: str = data.key
bid: int = data.bid
cmd: str = data.cmd
cmd_data: dict = data.data
2025-02-05 20:25:28 -05:00
if not self.util.check_key(path=request.url.path, req_type=0, key=key):
2025-02-05 20:23:06 -05:00
raise HTTPException(status_code=403, detail="Unauthorized")
2025-02-11 20:01:07 -05:00
BID_ADDR_MAP: dict = {
2025-02-05 20:25:28 -05:00
0: '10.10.10.101:5991', # Patrick (a.k.a. Thomas a.k.a. Aces)
# TODO: add Havoc?
2025-02-05 20:23:06 -05:00
}
if not bid in BID_ADDR_MAP:
return {
'err': True,
'errorText': 'Invalid bot id'
}
2025-02-11 20:01:07 -05:00
bot_api_url: str = f'http://{BID_ADDR_MAP[bid]}/'
2025-02-05 20:23:06 -05:00
async with ClientSession() as session:
async with await session.post(f"{bot_api_url}{cmd}", json=cmd_data, headers={
'Content-Type': 'application/json; charset=utf-8'
}, timeout=ClientTimeout(connect=5, sock_read=5)) as request:
2025-02-11 20:01:07 -05:00
response: dict = await request.json()
2025-02-05 20:23:06 -05:00
return {
'success': True,
'response': response
}
2025-02-11 20:01:07 -05:00
except Exception as e:
logging.debug("Error: %s", str(e))