trying to just redirect ws
This commit is contained in:
1 parent
e6e51be5a5
commit
079f353dbf
8 files changed
+114
-60
No files matched your search
@@ -9,9 +9,7 @@ WORKDIR /app
|
|||||||
ARG BUILD_VERSION
|
ARG BUILD_VERSION
|
||||||
|
|
||||||
# <--- Environment Variables -->
|
# <--- Environment Variables -->
|
||||||
ENV HASSIO_TOKEN ""
|
|
||||||
ENV BUILD_VERSION $BUILD_VERSION
|
ENV BUILD_VERSION $BUILD_VERSION
|
||||||
ENV HASS_URL "http://supervisor/"
|
|
||||||
|
|
||||||
# <--- System Wide Dependencies -->
|
# <--- System Wide Dependencies -->
|
||||||
ENV LANG C.UTF-8
|
ENV LANG C.UTF-8
|
||||||
|
|||||||
+2
-1
@@ -5,7 +5,7 @@ from fastapi.staticfiles import StaticFiles
|
|||||||
from src.automations.manager import AutomationManager
|
from src.automations.manager import AutomationManager
|
||||||
from src.env import ORIGIN, ROOT_FOLDER
|
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:
|
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(ping.router, prefix="/ping")
|
||||||
app.include_router(automations.make_automation_router(automation_mgr), prefix="/automations")
|
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(details.make_details_router(automation_mgr.hass_config), prefix="/details")
|
||||||
|
app.include_router(socket.router, prefix="/socket")
|
||||||
return app
|
return app
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
from fastapi import APIRouter
|
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
|
from src.hass_config import HassConfig
|
||||||
|
|
||||||
|
|
||||||
@@ -12,7 +12,7 @@ def make_details_router(hass_config: HassConfig) -> APIRouter:
|
|||||||
return {
|
return {
|
||||||
"version": BUILD_VERSION,
|
"version": BUILD_VERSION,
|
||||||
"hassio_token": HASSIO_TOKEN,
|
"hassio_token": HASSIO_TOKEN,
|
||||||
"hass_url": HASS_URL,
|
"hassio_url": HASSIO_WS,
|
||||||
"config": hass_config.get_configuration_path(),
|
"config": hass_config.get_configuration_path(),
|
||||||
"tags": hass_config.get_automation_tags_path(),
|
"tags": hass_config.get_automation_tags_path(),
|
||||||
"autos": hass_config.get_automation_path(),
|
"autos": hass_config.get_automation_path(),
|
||||||
|
|||||||
@@ -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(),
|
||||||
|
)
|
||||||
+2
-2
@@ -4,7 +4,7 @@ from decouple import Csv, config
|
|||||||
|
|
||||||
ROOT_FOLDER = Path(__file__).parent.parent.absolute()
|
ROOT_FOLDER = Path(__file__).parent.parent.absolute()
|
||||||
BUILD_VERSION = config("BUILD_VERSION", "0.0.0")
|
BUILD_VERSION = config("BUILD_VERSION", "0.0.0")
|
||||||
HASSIO_TOKEN = config("HASSIO_TOKEN", "")
|
HASSIO_TOKEN = config("SUPERVISOR_TOKEN", "")
|
||||||
HASS_URL = config("HASS_URL", "/")
|
HASSIO_WS = config("HASSIO_WS", "ws://supervisor/core/websocket")
|
||||||
LOG_LEVEL = config("LOG_LEVEL", "INFO")
|
LOG_LEVEL = config("LOG_LEVEL", "INFO")
|
||||||
ORIGIN = config("ORIGIN", cast=Csv(), default="*")
|
ORIGIN = config("ORIGIN", cast=Csv(), default="*")
|
||||||
@@ -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()
|
||||||
@@ -5,15 +5,15 @@ import { useAPIService } from './core';
|
|||||||
import { useMockAPI } from "./mock";
|
import { useMockAPI } from "./mock";
|
||||||
|
|
||||||
const locationPrefixWeb = window.location.pathname.match(/(.+)\/web/i);
|
const locationPrefixWeb = window.location.pathname.match(/(.+)\/web/i);
|
||||||
const baseURL = process.env.NODE_ENV === 'development' ?
|
const baseURL = new URL(
|
||||||
"http://localhost:8000" :
|
process.env.NODE_ENV === 'development' ?
|
||||||
(!locationPrefixWeb ? '' : locationPrefixWeb[1]);
|
"http://localhost:8000" :
|
||||||
|
(!locationPrefixWeb ? '' : locationPrefixWeb[1])
|
||||||
export const remoteDetailsAPI = makeRemoteAPI(
|
|
||||||
baseURL + "/details"
|
|
||||||
);
|
);
|
||||||
|
export const wsURL = baseURL + "socket"
|
||||||
|
console.log({ baseURL, wsURL })
|
||||||
export const remoteAutoAPI = makeRemoteAPI(
|
export const remoteAutoAPI = makeRemoteAPI(
|
||||||
baseURL + "/automations"
|
baseURL + "automations"
|
||||||
);
|
);
|
||||||
export const useConnectedApiService = () => useAPIService(
|
export const useConnectedApiService = () => useAPIService(
|
||||||
makeAutomationAPI(remoteAutoAPI)
|
makeAutomationAPI(remoteAutoAPI)
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {
|
|||||||
ERR_INVALID_HTTPS_TO_HTTP,
|
ERR_INVALID_HTTPS_TO_HTTP,
|
||||||
createConnection as _createConnection,
|
createConnection as _createConnection,
|
||||||
} from "home-assistant-js-websocket";
|
} from "home-assistant-js-websocket";
|
||||||
import { remoteDetailsAPI } from 'apiService';
|
import { wsURL } from 'apiService';
|
||||||
|
|
||||||
export type HAConnection = {
|
export type HAConnection = {
|
||||||
status: 'loading'
|
status: 'loading'
|
||||||
@@ -43,60 +43,18 @@ const translateErrorCodes = (errorCode: number) => {
|
|||||||
return errorCode;
|
return errorCode;
|
||||||
}
|
}
|
||||||
|
|
||||||
type ReturnedToken = {
|
|
||||||
hassURL: string;
|
|
||||||
longToken: string
|
|
||||||
} | {
|
|
||||||
hassURL: string;
|
|
||||||
hassioToken: string
|
|
||||||
} | {
|
|
||||||
error: any;
|
|
||||||
}
|
|
||||||
const getToken = async (): Promise<ReturnedToken> => {
|
|
||||||
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 createConnection = async () => {
|
||||||
const tokens = await getToken();
|
|
||||||
try {
|
try {
|
||||||
if ('hassioToken' in tokens) {
|
return _createConnection({
|
||||||
return _createConnection({
|
auth: createLongLivedTokenAuth(wsURL, 'xxx'),
|
||||||
auth: createLongLivedTokenAuth(tokens.hassURL, tokens.hassioToken),
|
});
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// eslint-disable-next-line
|
// eslint-disable-next-line
|
||||||
throw {
|
throw {
|
||||||
originalError: JSON.stringify(error),
|
originalError: JSON.stringify(error),
|
||||||
message: translateErrorCodes(error as any),
|
message: translateErrorCodes(error as any),
|
||||||
tokens,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
throw tokens
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function startHAConnection() {
|
async function startHAConnection() {
|
||||||
|
|||||||
Reference in new issue
Block a user