import all
This commit is contained in:
commit
881baaa1ed
25 files changed
+1779
No files matched your search
@@ -0,0 +1,121 @@
|
||||
import asyncio
|
||||
import json
|
||||
from aiohttp import web
|
||||
from base64 import b64decode
|
||||
from typing import Dict, Any
|
||||
import uuid
|
||||
from time import time
|
||||
import dotenv
|
||||
import os
|
||||
import re
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
Path("./logs/").mkdir(parents=True, exist_ok=True)
|
||||
|
||||
import banner
|
||||
import get_sq_env
|
||||
import asquare as sq
|
||||
from abricksetapi import AsyncBricksetAPI
|
||||
|
||||
lego = AsyncBricksetAPI(debug=True)
|
||||
|
||||
dotenv.load_dotenv()
|
||||
SQUARE_LEGO_CAT_ID = os.environ.get("SQUARE_LEGO_CAT_ID")
|
||||
|
||||
|
||||
from asyncio_throttle.throttler import Throttler
|
||||
|
||||
logger = logging.getLogger("aiohttp.access")
|
||||
logging.basicConfig(
|
||||
filename="./logs/edderkop.log", encoding="utf-8", level=logging.DEBUG
|
||||
)
|
||||
|
||||
UA = re.compile(r"^kopling\/?", re.IGNORECASE)
|
||||
|
||||
|
||||
async def run_update():
|
||||
set_list = await sq.acat2id(SQUARE_LEGO_CAT_ID)
|
||||
for l_set in set_list:
|
||||
print(f"[@DEBUG]{l_set}")
|
||||
l_setinfo = await lego.throttled_get_set(l_set["number"])
|
||||
print(f"[@DEBUG]{l_setinfo}")
|
||||
# await sq.update_itm(l_set, l_setinfo)
|
||||
|
||||
|
||||
def valid_uuid(val):
|
||||
try:
|
||||
uuid.UUID(str(val))
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
async def request_handler(request: web.Request) -> web.Response:
|
||||
"""Handle incoming POST requests with command processing"""
|
||||
try:
|
||||
# Verify request method
|
||||
if request.method != "POST":
|
||||
logger.error(
|
||||
f"{time()}\tInvalid request method from %s at ", request.remote
|
||||
)
|
||||
return web.Response(status=405, text="Method not allowed. Use POST.")
|
||||
|
||||
# Get JSON data from request
|
||||
try:
|
||||
data = await request.json()
|
||||
except json.JSONDecodeError:
|
||||
logger.error("Invalid JSON from %s", request.remote)
|
||||
return web.Response(
|
||||
status=400, text="{time()}\tInvalid JSON in request body"
|
||||
)
|
||||
# Validate Idempotency-Key header
|
||||
if valid_uuid(request.headers.get("Idempotency-Key")) is False:
|
||||
logger.error("{time()}\tInvalid Idempotency-Key from %s", request.remote)
|
||||
return web.Response(status=412, text="412 Headers rejected!")
|
||||
# Validate User-Agent header
|
||||
if not re.match(UA, str(request.headers.get("User-Agent"))):
|
||||
logger.error("{time()}\tInvalid User-Agent from %s", request.remote)
|
||||
return web.Response(status=412, text="412 Headers rejected!")
|
||||
# Validate command exists
|
||||
if "CMD" not in data:
|
||||
logger.error("{time()}\tMissing CMD field from %s", request.remote)
|
||||
return web.Response(status=400, text="Missing CMD field in request")
|
||||
|
||||
# Decode and process command
|
||||
try:
|
||||
decoded_cmd = b64decode(data["CMD"]).decode("utf-8")
|
||||
print(
|
||||
f"""At: {time()}\nReceived command: {decoded_cmd}\nUser-Agent: {request.headers.get('User-Agent')}\nIdempotency-Key: {request.headers.get('Idempotency-Key')}"""
|
||||
)
|
||||
logging.info(
|
||||
f"{time()}\tCommand: {decoded_cmd}\tFrom: {request.remote}\tUA: {request.headers.get('User-Agent')}\tIdempotency-Key: {request.headers.get('Idempotency-Key')}"
|
||||
)
|
||||
|
||||
# Process the command
|
||||
if decoded_cmd == "RUNUPDATE":
|
||||
# Add your command handling logic here
|
||||
await run_update()
|
||||
response_data = {"status": "success", "message": "Update started"}
|
||||
logging.info(f"{time()}\tUpdate command processed successfully")
|
||||
|
||||
return web.json_response(response_data)
|
||||
else:
|
||||
return web.Response(status=400, text=f"Unknown command: {decoded_cmd}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error processing command: {str(e)}")
|
||||
return web.Response(status=500, text=f"Server error: {str(e)}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Request handler error: {str(e)}")
|
||||
return web.Response(status=500, text="Internal server error")
|
||||
|
||||
|
||||
app = web.Application()
|
||||
app.router.add_post("/", request_handler)
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(banner.generate("Edderkop v0.1"))
|
||||
print("Built for PLAY-WELL TEKNOLOGIES by contact@traps.moe\n\n")
|
||||
web.run_app(app, host="localhost", port=7432)
|
||||
Reference in new issue
Block a user