Compare commits

...
11 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
ari bc773154c6 all the latest socket work 2022-06-01 21:17:16 -04:00
22 changed files with 178 additions and 85 deletions

No files matched your search

+8 -1
View File
@@ -3,4 +3,11 @@ webapp/build
webapp/.storybook
webapp/.vscode
webapp/.env.local
webapp/tmux.sh
webapp/tmux.sh
api/.env
api/.coverage
api/venv
api/build
api/.mypy_cache
api/.vscode
api/.coverage
+1
View File
@@ -100,5 +100,6 @@ jobs:
with:
args: |
--${{ matrix.arch }} \
--no-latest \
--version ${{ needs.metadata.outputs.version }} \
--target .
+1 -2
View File
@@ -9,8 +9,6 @@ WORKDIR /app
ARG BUILD_VERSION
# <--- Environment Variables -->
ENV HASSIO_TOKEN ""
ENV SUPERVISOR_TOKEN ""
ENV BUILD_VERSION $BUILD_VERSION
# <--- System Wide Dependencies -->
@@ -52,3 +50,4 @@ LABEL \
ENTRYPOINT [ "/app/bin/run.sh" ]
CMD [ "/app" ]
LABEL org.opencontainers.image.source https://github.com/asosnovsky/Shortumation
-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 -2
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
@@ -43,5 +43,4 @@ clean:
run-local:
rm -f web
ln -s ../webapp/build web
cd ../webapp && yarn build
USE_EXAMPLE_REPO=1 $(VENV_BIN)/uvicorn src.app:app --reload
+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
+4 -4
View File
@@ -1,8 +1,6 @@
from datetime import datetime
from fastapi import APIRouter
from src.env import BUILD_VERSION
from src.env import BUILD_VERSION, HASSIO_TOKEN, HASSIO_WS
from src.hass_config import HassConfig
@@ -10,9 +8,11 @@ def make_details_router(hass_config: HassConfig) -> APIRouter:
router = APIRouter()
@router.get("/")
def read_ping():
def read_details():
return {
"version": BUILD_VERSION,
"hassio_token": HASSIO_TOKEN,
"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
View File
@@ -4,5 +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("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()
+3
View File
@@ -3,5 +3,8 @@ services:
addon:
volumes:
- "./sample_config:/config"
- "./api/tests:/app/tests"
ports:
- "8000:8000"
env_file:
- api/.env
-2
View File
@@ -5,8 +5,6 @@ api_location=${1}
pushd $api_location
echo "--------------------"
echo "BUILD_VERSION = "$BUILD_VERSION
echo "HASSIO_TOKEN = "$HASSIO_TOKEN
echo "SUPERVISOR_TOKEN = "$SUPERVISOR_TOKEN
echo $(python --version)
echo "--------------------"
python -m uvicorn src.app:app --host "0.0.0.0" --port 8000
+3 -1
View File
@@ -12,6 +12,7 @@
"@types/node": "^17.0.36",
"@types/react": "^18.0.9",
"@types/react-dom": "^18.0.5",
"@types/ws": "^8.5.3",
"@uiw/react-codemirror": "^4.7.0",
"autosuggest-highlight": "^3.2.1",
"home-assistant-js-websocket": "^7.1.0",
@@ -27,6 +28,7 @@
"theming": "^3.3.0",
"typescript": "^4.1.2",
"web-vitals": "^2.1.4",
"ws": "^8.7.0",
"yarn": "^1.22.17"
},
"scripts": {
@@ -94,4 +96,4 @@
"node_modules",
"src"
]
}
}
+6 -3
View File
@@ -10,13 +10,16 @@ export const makeRemoteAPI = (baseURL: string): API => ({
data = {}
}) {
try {
const reply = await fetch(baseURL + path, {
const payload: RequestInit = {
method,
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data),
});
};
if (method !== 'GET') {
payload["body"] = JSON.stringify(data);
}
const reply = await fetch(baseURL + path, payload);
let response: APIResponse<any>;
if (reply.status === 200) {
response = {
+12 -7
View File
@@ -4,14 +4,19 @@ import { makeRemoteAPI } from "./base";
import { useAPIService } from './core';
import { useMockAPI } from "./mock";
const locationPrefixWeb = window.location.pathname.match(/(.+)\/web/i);
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"
);
export const useConnectedApiService = () => useAPIService(
makeAutomationAPI(makeRemoteAPI(
process.env.NODE_ENV === 'development' ?
"http://localhost:8000/automations" :
(!locationPrefixWeb ? '' : locationPrefixWeb[1]) + "/automations"
))
makeAutomationAPI(remoteAutoAPI)
);
export const useMockApiService = (initialAutos: AutomationData[]) => useAPIService(
makeAutomationAPI(useMockAPI(initialAutos))
+1 -1
View File
@@ -7,7 +7,7 @@ export interface ListParams {
}
export type APIRequest<D> = {
path: string;
method?: "POST" | "DELETE",
method?: "POST" | "DELETE" | "GET",
data?: D;
};
@@ -103,7 +103,7 @@ export const AutoInfoBox: FC<Props> = ({
<div className="automation-editor--info-box--tags">
<h1>Tags</h1>
<div className="automation-editor--info-box--tag-list">
{tags.map(([tagName, tagValue], tagIndex) => <div className="automation-editor--info-box--tag">
{tags.map(([tagName, tagValue], tagIndex) => <div key={tagIndex} className="automation-editor--info-box--tag">
<InputAutoText
value={tagName}
label="Name"
+4 -1
View File
@@ -40,8 +40,11 @@ export const InternalPage: FC<{
if (snackbarKeyHAConKey.current) {
snackbar.closeSnackbar(snackbarKeyHAConKey.current)
}
snackbarKeyHAConKey.current = snackbar.enqueueSnackbar(`Connected to HA!`, {
"variant": "success",
})
}
}, [conn.status])
}, [conn, snackbar])
return <main className="page" style={{
color: theme.palette.text.primary,
+19 -36
View File
@@ -1,20 +1,16 @@
import { useState, useEffect, useRef } from 'react';
import {
getAuth,
createConnection,
ERR_HASS_HOST_REQUIRED,
createLongLivedTokenAuth,
Auth,
Connection,
ERR_CANNOT_CONNECT,
ERR_CONNECTION_LOST,
ERR_INVALID_AUTH,
ERR_INVALID_HTTPS_TO_HTTP,
createConnection as _createConnection,
} from "home-assistant-js-websocket";
import { wsURL } from 'apiService';
const HASS_URL = process.env.REACT_APP_HASS_URL as string;
const HASS_TOKEN = process.env.REACT_APP_HASS_TOKEN;
const HASS_SUPERVISOR_TOKEN = process.env.REACT_APP_SUPERVISOR_TOKEN as string;
export type HAConnection = {
status: 'loading'
} | {
@@ -47,52 +43,39 @@ const translateErrorCodes = (errorCode: number) => {
return errorCode;
}
const createAuth = async () => {
let auth: Auth
if (HASS_TOKEN) {
return createLongLivedTokenAuth(HASS_URL, HASS_TOKEN);
}
if (HASS_SUPERVISOR_TOKEN) {
return await getAuth({ hassUrl: HASS_URL, authCode: HASS_SUPERVISOR_TOKEN });
}
const createConnection = async () => {
try {
auth = await getAuth();
return auth
} catch (err) {
if (err !== ERR_HASS_HOST_REQUIRED) {
throw err
return _createConnection({
auth: createLongLivedTokenAuth(wsURL, 'xxx'),
});
} catch (error) {
// eslint-disable-next-line
throw {
originalError: JSON.stringify(error),
message: translateErrorCodes(error as any),
}
}
try {
auth = await getAuth({ hassUrl: HASS_URL });
return auth
} catch (err) {
throw err
}
}
async function startHAConnection() {
let connection: Connection;
try {
const auth = await createAuth();
const connection = await createConnection({ auth });
haConnection = {
status: 'loaded',
connection,
}
return haConnection;
connection = await createConnection();
} catch (error) {
haConnection = {
status: 'error',
error: {
originalError: JSON.stringify(error),
message: translateErrorCodes(error as any),
hassToken: !HASS_TOKEN ? "no" : "yes",
hasSuperToken: !HASS_SUPERVISOR_TOKEN ? "no" : "yes",
url: HASS_URL,
},
}
}
throw error
}
haConnection = {
status: 'loaded',
connection,
}
return haConnection;
}
startHAConnection().then(console.log).catch(console.error);
+8
View File
@@ -15,3 +15,11 @@ ReactDOM.render(
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
// import { createRoot } from 'react-dom/client';
// const container = document.getElementById('root');
// const root = createRoot(container!);
// root.render(<React.StrictMode>
// <App />
// </React.StrictMode>);
+2 -2
View File
@@ -3995,7 +3995,7 @@
anymatch "^3.0.0"
source-map "^0.6.0"
"@types/ws@^8.5.1":
"@types/ws@^8.5.1", "@types/ws@^8.5.3":
version "8.5.3"
resolved "https://registry.yarnpkg.com/@types/ws/-/ws-8.5.3.tgz#7d25a1ffbecd3c4f2d35068d0b283c037003274d"
integrity sha512-6YOoWjruKj1uLf3INHH7D3qTXwFfEsg1kf3c0uDdSBJwfa/llkwIjrAGV7j7mVgGNbzTQ3HiHKKDXl6bJPD97w==
@@ -15767,7 +15767,7 @@ ws@^7.4.6:
resolved "https://registry.yarnpkg.com/ws/-/ws-7.5.8.tgz#ac2729881ab9e7cbaf8787fe3469a48c5c7f636a"
integrity sha512-ri1Id1WinAX5Jqn9HejiGb8crfRio0Qgu8+MtL36rlTA6RLsMdWt1Az/19A2Qij6uSHUMphEFaTKa4WG+UNHNw==
ws@^8.2.3, ws@^8.4.2:
ws@^8.2.3, ws@^8.4.2, ws@^8.7.0:
version "8.7.0"
resolved "https://registry.yarnpkg.com/ws/-/ws-8.7.0.tgz#eaf9d874b433aa00c0e0d8752532444875db3957"
integrity sha512-c2gsP0PRwcLFzUiA8Mkr37/MI7ilIlHQxaEAtd0uNMbVMoy8puJyafRlm0bV9MbGSabUPeLrRRaqIBcFcA2Pqg==