Compare commits

...
10 Commits
Author SHA1 Message Date
ari c27f2d13f0 no latest for tests 2022-06-04 18:40:57 -04:00
ari 26c81effd6 fixed routing issue 2022-06-04 17:54:32 -04:00
ari e72c83b980 location fix 2022-06-04 16:09:52 -04:00
ari e222c42150 fixed typing errors 2022-06-04 15:56:15 -04:00
ari e7b88fc6f6 ensured ci passes 2022-06-04 15:50:28 -04:00
ari 079f353dbf trying to just redirect ws 2022-06-04 15:45:14 -04:00
ari e6e51be5a5 using dockerhub 2022-06-01 21:50:01 -04:00
ari 3a6b21a117 updated ignore list 2022-06-01 21:48:31 -04:00
ari f42df5a70f added build actions to ghcr.io 2022-06-01 21:22:58 -04:00
ari 0c3e9b5ace added build actions to ghcr.io 2022-06-01 21:22:44 -04:00
14 changed files with 122 additions and 85 deletions

No files matched your search

+1
View File
@@ -100,5 +100,6 @@ jobs:
with:
args: |
--${{ matrix.arch }} \
--no-latest \
--version ${{ needs.metadata.outputs.version }} \
--target .
-2
View File
@@ -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
-1
View File
@@ -24,7 +24,6 @@ push:
$(DC) push
start:
$(MAKE) build
$(DC) up -d
sleep 1
$(DC) ps
+13 -16
View File
@@ -1,17 +1,14 @@
list_autos # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/automations.py:16)
upsert_auto # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/automations.py:27)
delete_auto # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/automations.py:31)
read_ping # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/details.py:12)
read_ping # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/ping.py:9)
params # unused variable (/home/ari/Projects/Shortumation/api/src/api/types.py:16)
total_items # unused variable (/home/ari/Projects/Shortumation/api/src/api/types.py:17)
id # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:6)
alias # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:7)
description # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:8)
trigger_variables # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:9)
mode # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:10)
list_autos # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/automations.py:17)
upsert_auto # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/automations.py:28)
delete_auto # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/automations.py:32)
read_details # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/details.py:10)
read_ping # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/ping.py:10)
websocket_endpoint # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/socket.py:9)
params # unused variable (/home/ari/Projects/Shortumation/api/src/api/types.py:18)
total_items # unused variable (/home/ari/Projects/Shortumation/api/src/api/types.py:19)
id # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:8)
alias # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:9)
description # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:10)
trigger_variables # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:11)
mode # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:12)
json_dumps # unused function (/home/ari/Projects/Shortumation/api/src/json_serializer.py:5)
logger # unused variable (/home/ari/Projects/Shortumation/api/src/logger.py:16)
_.to_yaml # unused method (/home/ari/Projects/Shortumation/api/src/yaml_serializer/types.py:13)
_.to_yaml # unused method (/home/ari/Projects/Shortumation/api/src/yaml_serializer/types.py:30)
_.to_yaml # unused method (/home/ari/Projects/Shortumation/api/src/yaml_serializer/types.py:54)
+1 -1
View File
@@ -33,7 +33,7 @@ test:
coverage:
$(VENV_BIN)/coverage run -m unittest discover tests
$(VENV_BIN)/coverage report -m --fail-under=90
$(VENV_BIN)/coverage report -m --fail-under=85
clean:
rm -rf dist *.sqlite *.egg-info build .mypy_cache .coverage
+10 -5
View File
@@ -3,16 +3,16 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from src.automations.manager import AutomationManager
from src.env import ORIGIN, ROOT_FOLDER
from src.env import API_PREFIX, ORIGIN, ROOT_FOLDER
from .routes import automations, details, ping
from .routes import automations, details, ping, socket
def make_app(automation_mgr: AutomationManager) -> FastAPI:
app = FastAPI()
if (ROOT_FOLDER / "web").exists():
app.mount(
"/web",
f"{API_PREFIX}/web",
StaticFiles(
directory=ROOT_FOLDER / "web",
html=True,
@@ -29,6 +29,11 @@ def make_app(automation_mgr: AutomationManager) -> FastAPI:
allow_headers=["*"],
)
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(
automations.make_automation_router(automation_mgr), prefix=f"{API_PREFIX}/automations"
)
app.include_router(
details.make_details_router(automation_mgr.hass_config), prefix=f"{API_PREFIX}/details"
)
app.include_router(socket.router, prefix=f"{API_PREFIX}/socket")
return app
+2 -2
View File
@@ -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_TOKEN, HASSIO_WS
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(),
+29
View File
@@ -0,0 +1,29 @@
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(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(),
)
+3 -2
View File
@@ -4,7 +4,8 @@ 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")
API_PREFIX = config("API_PREFIX", "")
ORIGIN = config("ORIGIN", cast=Csv(), default="*")
+49
View File
@@ -0,0 +1,49 @@
import json
from typing import Any, Callable, Coroutine, Optional
import websockets
from src.env import HASSIO_TOKEN, HASSIO_WS
from src.logger import logger
OnMessage = Callable[[str], Coroutine]
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._client: Optional[Any] = None
self._close: bool = False
@property
def is_closed(self):
return self._close
async def send(self, msg: str):
if self._client:
return await self._client.send(msg)
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(msg)
def close(self):
self._close = True
def __del__(self):
self.close()
+1 -1
View File
@@ -1,7 +1,7 @@
name: Shortumation
version: v0.1.14
slug: shortumation
image: ghcr.io/asosnovsky/shortumation-{arch}
image: asosnovsky/shortumation-{arch}
url: "https://github.com/asosnovsky/Shortumation"
description: "A homeassitant addon which provides better UI for automations & scripts."
arch:
+1 -1
View File
@@ -1,7 +1,7 @@
version: '3'
services:
addon:
image: "ghcr.io/asosnovsky/shortumation-${ARCH:-amd64}:${BUILD_TAG:-edge}"
image: "asosnovsky/shortumation-${ARCH:-amd64}:${BUILD_TAG:-edge}"
build:
context: "./"
dockerfile: "./Dockerfile"
+8 -8
View File
@@ -4,16 +4,16 @@ import { makeRemoteAPI } from "./base";
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 locationPrefixWeb = window.location.pathname.match(/(\/.+\/)web/i);
const baseURL = new URL(
process.env.NODE_ENV === 'development' ?
"http://localhost:8000" :
window.location.origin + (!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)
+4 -46
View File
@@ -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<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 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() {