from fastapi import FastAPI from fastapi.requests import Request from fastapi.responses import Response, JSONResponse, StreamingResponse from fastapi.exceptions import HTTPException from extra.NodeDTO import NodeDTO import traceback class WebExtension: app: FastAPI def __init__(self, core): self.core = core self.app = core.app self.dbService = core.dbService @self.app.get(f"{self.core.context}/ping") async def pong(request:Request): return {"pong": True} @self.app.get(f"{self.core.context}/status") async def status(request:Request): return { "status": self.core.meshState, "last_packet_catch": self.core.last_packet_catch } @self.app.get(f"{self.core.context}/auth/code") async def sendCodeToNode(request:Request, num: int): #в сообщение одноразовый код и юзер агент кто слал, так-же чтобы не спапили по фингерпринту один код в минуту if num: node = await self.dbService.oneNode(num) if node: code = self.core.authManager.request_auth(num) await self.core.devices[0].sendMsgToDM(f"Auth code: {code}", num) return {"status": f"Code sended to {node['long_name']}"} raise HTTPException(status_code=400) @self.app.get(f"{self.core.context}/auth/code/check") async def acceptCodeFromNode(request:Request, code: int): #если такой код есть то авторизуем пользователя, иначе шлем н***й if code: try: num = self.core.authManager.accept_code(code) respond = self.core.authManager.setAuth(JSONResponse({"status":True}), num) return respond except: return {"status": False} return {"status": False} @self.app.get(f"{self.core.context}/auth/logout") async def clearSession(request:Request): return self.core.authManager.setAuth(JSONResponse({"status":True}), 0, True) @self.app.get(f"{self.core.context}/auth/me") @self.core.authManager.authRequest() async def userNode(request:Request): userNum = request.cookies.get(self.core.authManager.NUM, None) userNode = await self.dbService.oneNode(userNum) if userNum is not None: return NodeDTO(userNode) else: return {} @self.app.get(self.core.context+"/tile/{z}/{x}/{y}.png") @self.core.authManager.authRequest() async def grabTile(request:Request, z:int, x:int, y:int): try: img = await self.core.tileManager.grabTile(z, x, y) headers = { "Cache-Control": f"public, max-age={86400*7}" } return Response(content=img, headers=headers, media_type="image/png") except: traceback.print_exc() raise HTTPException(status_code=404, detail="not found tile") @self.app.get(f"{self.core.context}/devices") async def devicesList(): response = [] count = 1 for hash in self.core.devicesUuidHashToUuid.keys(): obj = { "hash": hash, "default": hash == self.core.defaultDeviceUUIDHash, "name": "amongus" if count == 1 else "atlanta"#todo } response.append(obj) count += 1 return response