From bc773154c630469957f18c9db081f8cfe01f3ca2 Mon Sep 17 00:00:00 2001 From: Ari Date: Wed, 1 Jun 2022 21:17:16 -0400 Subject: [PATCH] all the latest socket work --- .dockerignore | 9 +- Dockerfile | 3 +- api/Makefile | 1 - api/src/api/routes/details.py | 8 +- api/src/env.py | 2 + config.yaml | 2 +- docker-compose.build.yaml | 2 +- docker-compose.test.yaml | 3 + docker/bin/run.sh | 2 - webapp/package.json | 4 +- webapp/src/apiService/base.ts | 9 +- webapp/src/apiService/index.ts | 15 ++- webapp/src/apiService/types.ts | 2 +- .../AutomationEditor/AutoInfoBox.tsx | 2 +- webapp/src/components/Page/index.tsx | 5 +- webapp/src/haService/connection.ts | 97 ++++++++++++------- webapp/src/index.tsx | 8 ++ webapp/yarn.lock | 4 +- 18 files changed, 117 insertions(+), 61 deletions(-) diff --git a/.dockerignore b/.dockerignore index 6a83179..7675024 100644 --- a/.dockerignore +++ b/.dockerignore @@ -3,4 +3,11 @@ webapp/build webapp/.storybook webapp/.vscode webapp/.env.local -webapp/tmux.sh \ No newline at end of file +webapp/tmux.sh +api/.env +api/.coverage +api/venv +api/build +api/.mypy_cache +api/.vscode +api/.coverage \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index b2aa918..54e29ab 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,8 +10,8 @@ ARG BUILD_VERSION # <--- Environment Variables --> ENV HASSIO_TOKEN "" -ENV SUPERVISOR_TOKEN "" ENV BUILD_VERSION $BUILD_VERSION +ENV HASS_URL "http://supervisor/" # <--- System Wide Dependencies --> ENV LANG C.UTF-8 @@ -52,3 +52,4 @@ LABEL \ ENTRYPOINT [ "/app/bin/run.sh" ] CMD [ "/app" ] +LABEL org.opencontainers.image.source https://github.com/asosnovsky/Shortumation diff --git a/api/Makefile b/api/Makefile index 8d5e632..00c297c 100644 --- a/api/Makefile +++ b/api/Makefile @@ -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 diff --git a/api/src/api/routes/details.py b/api/src/api/routes/details.py index c0ce390..f07cae3 100644 --- a/api/src/api/routes/details.py +++ b/api/src/api/routes/details.py @@ -1,8 +1,6 @@ -from datetime import datetime - from fastapi import APIRouter -from src.env import BUILD_VERSION +from src.env import BUILD_VERSION, HASS_URL, HASSIO_TOKEN 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, + "hass_url": HASS_URL, "config": hass_config.get_configuration_path(), "tags": hass_config.get_automation_tags_path(), "autos": hass_config.get_automation_path(), diff --git a/api/src/env.py b/api/src/env.py index 458f76d..b584673 100644 --- a/api/src/env.py +++ b/api/src/env.py @@ -4,5 +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", "/") LOG_LEVEL = config("LOG_LEVEL", "INFO") ORIGIN = config("ORIGIN", cast=Csv(), default="*") diff --git a/config.yaml b/config.yaml index e6d955c..7848d71 100644 --- a/config.yaml +++ b/config.yaml @@ -1,7 +1,7 @@ name: Shortumation version: v0.1.14 slug: shortumation -image: asosnovsky/shortumation-{arch} +image: ghcr.io/asosnovsky/shortumation-{arch} url: "https://github.com/asosnovsky/Shortumation" description: "A homeassitant addon which provides better UI for automations & scripts." arch: diff --git a/docker-compose.build.yaml b/docker-compose.build.yaml index c4c9093..f2d365e 100644 --- a/docker-compose.build.yaml +++ b/docker-compose.build.yaml @@ -1,7 +1,7 @@ version: '3' services: addon: - image: "asosnovsky/shortumation-${ARCH:-amd64}:${BUILD_TAG:-edge}" + image: "ghcr.io/asosnovsky/shortumation-${ARCH:-amd64}:${BUILD_TAG:-edge}" build: context: "./" dockerfile: "./Dockerfile" diff --git a/docker-compose.test.yaml b/docker-compose.test.yaml index 7941afd..3c74cc6 100644 --- a/docker-compose.test.yaml +++ b/docker-compose.test.yaml @@ -3,5 +3,8 @@ services: addon: volumes: - "./sample_config:/config" + - "./api/tests:/app/tests" ports: - "8000:8000" + env_file: + - api/.env diff --git a/docker/bin/run.sh b/docker/bin/run.sh index 322ecfa..5a1e3a3 100755 --- a/docker/bin/run.sh +++ b/docker/bin/run.sh @@ -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 diff --git a/webapp/package.json b/webapp/package.json index 3ce7ea1..0620159 100644 --- a/webapp/package.json +++ b/webapp/package.json @@ -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" ] -} \ No newline at end of file +} diff --git a/webapp/src/apiService/base.ts b/webapp/src/apiService/base.ts index 012fd66..361ec1e 100644 --- a/webapp/src/apiService/base.ts +++ b/webapp/src/apiService/base.ts @@ -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; if (reply.status === 200) { response = { diff --git a/webapp/src/apiService/index.ts b/webapp/src/apiService/index.ts index 6dc8a6b..e573fde 100644 --- a/webapp/src/apiService/index.ts +++ b/webapp/src/apiService/index.ts @@ -5,13 +5,18 @@ 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" +); +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)) diff --git a/webapp/src/apiService/types.ts b/webapp/src/apiService/types.ts index bf08a32..1793950 100644 --- a/webapp/src/apiService/types.ts +++ b/webapp/src/apiService/types.ts @@ -7,7 +7,7 @@ export interface ListParams { } export type APIRequest = { path: string; - method?: "POST" | "DELETE", + method?: "POST" | "DELETE" | "GET", data?: D; }; diff --git a/webapp/src/components/AutomationEditor/AutoInfoBox.tsx b/webapp/src/components/AutomationEditor/AutoInfoBox.tsx index 05cd085..afd6111 100644 --- a/webapp/src/components/AutomationEditor/AutoInfoBox.tsx +++ b/webapp/src/components/AutomationEditor/AutoInfoBox.tsx @@ -103,7 +103,7 @@ export const AutoInfoBox: FC = ({

Tags

- {tags.map(([tagName, tagValue], tagIndex) =>
+ {tags.map(([tagName, tagValue], tagIndex) =>
{ 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 }); - } - try { - auth = await getAuth(); - return auth - } catch (err) { - if (err !== ERR_HASS_HOST_REQUIRED) { - throw err +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, + } } } - try { - auth = await getAuth({ hassUrl: HASS_URL }); - return auth - } catch (err) { - throw err + 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), + }); + } + } catch (error) { + // eslint-disable-next-line + throw { + originalError: JSON.stringify(error), + message: translateErrorCodes(error as any), + tokens, + } + } + throw tokens } 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); diff --git a/webapp/src/index.tsx b/webapp/src/index.tsx index 8a4f2d5..e64eb07 100644 --- a/webapp/src/index.tsx +++ b/webapp/src/index.tsx @@ -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( +// +// ); \ No newline at end of file diff --git a/webapp/yarn.lock b/webapp/yarn.lock index ba75d08..bdee25a 100644 --- a/webapp/yarn.lock +++ b/webapp/yarn.lock @@ -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==