From 079f353dbfc1b2b01ad21d741d2b53a3753f8336 Mon Sep 17 00:00:00 2001 From: Ari Date: Sat, 4 Jun 2022 15:45:14 -0400 Subject: [PATCH] trying to just redirect ws --- Dockerfile | 2 - api/src/api/app.py | 3 +- api/src/api/routes/details.py | 4 +- api/src/api/routes/socket.py | 27 ++++++++++++ api/src/env.py | 4 +- api/src/ws_redirect/__init__.py | 70 ++++++++++++++++++++++++++++++ webapp/src/apiService/index.ts | 14 +++--- webapp/src/haService/connection.ts | 50 ++------------------- 8 files changed, 114 insertions(+), 60 deletions(-) create mode 100644 api/src/api/routes/socket.py create mode 100644 api/src/ws_redirect/__init__.py diff --git a/Dockerfile b/Dockerfile index 54e29ab..2259aac 100644 --- a/Dockerfile +++ b/Dockerfile @@ -9,9 +9,7 @@ WORKDIR /app ARG BUILD_VERSION # <--- Environment Variables --> -ENV HASSIO_TOKEN "" ENV BUILD_VERSION $BUILD_VERSION -ENV HASS_URL "http://supervisor/" # <--- System Wide Dependencies --> ENV LANG C.UTF-8 diff --git a/api/src/api/app.py b/api/src/api/app.py index e81a7f0..47ff9d6 100644 --- a/api/src/api/app.py +++ b/api/src/api/app.py @@ -5,7 +5,7 @@ from fastapi.staticfiles import StaticFiles from src.automations.manager import AutomationManager from src.env import ORIGIN, ROOT_FOLDER -from .routes import automations, details, ping +from .routes import automations, details, ping, socket def make_app(automation_mgr: AutomationManager) -> FastAPI: @@ -31,4 +31,5 @@ def make_app(automation_mgr: AutomationManager) -> FastAPI: app.include_router(ping.router, prefix="/ping") app.include_router(automations.make_automation_router(automation_mgr), prefix="/automations") app.include_router(details.make_details_router(automation_mgr.hass_config), prefix="/details") + app.include_router(socket.router, prefix="/socket") return app diff --git a/api/src/api/routes/details.py b/api/src/api/routes/details.py index f07cae3..2163795 100644 --- a/api/src/api/routes/details.py +++ b/api/src/api/routes/details.py @@ -1,6 +1,6 @@ from fastapi import APIRouter -from src.env import BUILD_VERSION, HASS_URL, HASSIO_TOKEN +from src.env import BUILD_VERSION, HASSIO_WS, HASSIO_TOKEN from src.hass_config import HassConfig @@ -12,7 +12,7 @@ def make_details_router(hass_config: HassConfig) -> APIRouter: return { "version": BUILD_VERSION, "hassio_token": HASSIO_TOKEN, - "hass_url": HASS_URL, + "hassio_url": HASSIO_WS, "config": hass_config.get_configuration_path(), "tags": hass_config.get_automation_tags_path(), "autos": hass_config.get_automation_path(), diff --git a/api/src/api/routes/socket.py b/api/src/api/routes/socket.py new file mode 100644 index 0000000..d4521db --- /dev/null +++ b/api/src/api/routes/socket.py @@ -0,0 +1,27 @@ +import asyncio +import json +from fastapi import APIRouter, WebSocket +from src.ws_redirect import WSRedirector + +router = APIRouter() + + +@router.websocket("/api/websocket") +async def websocket_endpoint(websocket: WebSocket): + async def on_message(ws: WSRedirector, msg: str): + await websocket.send_text(msg) + + conn = WSRedirector( + on_message=on_message, + ) + + async def wait_for_data(): + while True: + await conn.send(await websocket.receive_text()) + + await websocket.accept() + + await asyncio.gather( + conn.start(), + wait_for_data(), + ) diff --git a/api/src/env.py b/api/src/env.py index b584673..d27e95e 100644 --- a/api/src/env.py +++ b/api/src/env.py @@ -4,7 +4,7 @@ from decouple import Csv, config ROOT_FOLDER = Path(__file__).parent.parent.absolute() BUILD_VERSION = config("BUILD_VERSION", "0.0.0") -HASSIO_TOKEN = config("HASSIO_TOKEN", "") -HASS_URL = config("HASS_URL", "/") +HASSIO_TOKEN = config("SUPERVISOR_TOKEN", "") +HASSIO_WS = config("HASSIO_WS", "ws://supervisor/core/websocket") LOG_LEVEL = config("LOG_LEVEL", "INFO") ORIGIN = config("ORIGIN", cast=Csv(), default="*") diff --git a/api/src/ws_redirect/__init__.py b/api/src/ws_redirect/__init__.py new file mode 100644 index 0000000..798a55d --- /dev/null +++ b/api/src/ws_redirect/__init__.py @@ -0,0 +1,70 @@ +import json +import websockets + +from typing import Callable, Coroutine, Optional +from http import HTTPStatus + +from websockets.client import ClientConnection +from fastapi.exceptions import HTTPException + +from src.logger import logger +from src.env import HASSIO_TOKEN, HASSIO_WS + +OnMessage = Callable[[dict], Coroutine] + + +class WSRedirectorError(HTTPException): + def __init__(self, status_code: int) -> None: + super().__init__(status_code, detail={"message": str(self.__class__.__name__)}) + + +class WSDisconnectedMessage(WSRedirectorError): + def __init__(self) -> None: + super().__init__(status_code=HTTPStatus.FAILED_DEPENDENCY) + + +class WSRedirector: + def __init__( + self, + on_message: OnMessage, + token: str = HASSIO_TOKEN, + host: str = HASSIO_WS, + ) -> None: + self._host = host + self._token = token + self._on_message = on_message + self._authenticated = False + self._client: Optional[ClientConnection] = None + self._close: bool = False + + @property + def is_closed(self): + return self._close + + @property + def is_authenticated(self): + return self._authenticated + + async def send(self, msg: str): + if self._client: + return await self._client.send(msg) + # else: + # raise WSDisconnectedMessage() + + async def start(self): + async with websockets.connect(self._host) as websocket: + self._client = websocket + await websocket.send(json.dumps({"type": "auth", "access_token": self._token})) + while not self.is_closed: + msg = await websocket.recv() + logger.debug(f"WS:MSG: {msg}") + await self.process_message(msg) + + async def process_message(self, msg: str): + await self._on_message(self, msg) + + def close(self): + self._close = True + + def __del__(self): + self.close() diff --git a/webapp/src/apiService/index.ts b/webapp/src/apiService/index.ts index e573fde..e308587 100644 --- a/webapp/src/apiService/index.ts +++ b/webapp/src/apiService/index.ts @@ -5,15 +5,15 @@ import { useAPIService } from './core'; import { useMockAPI } from "./mock"; const locationPrefixWeb = window.location.pathname.match(/(.+)\/web/i); -const baseURL = process.env.NODE_ENV === 'development' ? - "http://localhost:8000" : - (!locationPrefixWeb ? '' : locationPrefixWeb[1]); - -export const remoteDetailsAPI = makeRemoteAPI( - baseURL + "/details" +const baseURL = new URL( + process.env.NODE_ENV === 'development' ? + "http://localhost:8000" : + (!locationPrefixWeb ? '' : locationPrefixWeb[1]) ); +export const wsURL = baseURL + "socket" +console.log({ baseURL, wsURL }) export const remoteAutoAPI = makeRemoteAPI( - baseURL + "/automations" + baseURL + "automations" ); export const useConnectedApiService = () => useAPIService( makeAutomationAPI(remoteAutoAPI) diff --git a/webapp/src/haService/connection.ts b/webapp/src/haService/connection.ts index 039cf5c..76f7112 100644 --- a/webapp/src/haService/connection.ts +++ b/webapp/src/haService/connection.ts @@ -9,7 +9,7 @@ import { ERR_INVALID_HTTPS_TO_HTTP, createConnection as _createConnection, } from "home-assistant-js-websocket"; -import { remoteDetailsAPI } from 'apiService'; +import { wsURL } from 'apiService'; export type HAConnection = { status: 'loading' @@ -43,60 +43,18 @@ const translateErrorCodes = (errorCode: number) => { return errorCode; } -type ReturnedToken = { - hassURL: string; - longToken: string -} | { - hassURL: string; - hassioToken: string -} | { - error: any; -} -const getToken = async (): Promise => { - const data = await remoteDetailsAPI.makeCall({ - "path": "/", - "method": "GET", - }); - if (!data.ok) { - return { - error: { - message: "Failed to get token from api.", - originalError: data.error, - } - } - } - const hassURL = data.data.hass_url; - const hassioToken = data.data.hassio_token; - if (!hassioToken) { - return { - error: { - message: [ - "Missing HASSIO Token, Please make sure the token is correctly passing to the container!", - "Make sure the token `HASSIO_TOKEN` and `HASS_URL` are set properly." - ].join('\n'), - } - } - } - return { hassioToken, hassURL } -} - const createConnection = async () => { - const tokens = await getToken(); try { - if ('hassioToken' in tokens) { - return _createConnection({ - auth: createLongLivedTokenAuth(tokens.hassURL, tokens.hassioToken), - }); - } + return _createConnection({ + auth: createLongLivedTokenAuth(wsURL, 'xxx'), + }); } catch (error) { // eslint-disable-next-line throw { originalError: JSON.stringify(error), message: translateErrorCodes(error as any), - tokens, } } - throw tokens } async function startHAConnection() {