Compare commits

...
55 Commits
Author SHA1 Message Date
ari 7020c6aee9 silent 2022-09-07 12:10:25 -04:00
ari 41dc77ff4f silencing invalid errors 2022-09-06 20:53:49 -04:00
ari c5cf8edfd6 update notice 2022-09-06 20:38:18 -04:00
ari 2dca59fa3f update notice 2022-09-06 20:38:07 -04:00
ari df95265af0 update notice 2022-09-06 20:38:00 -04:00
ari 78057939da clean up 2022-09-05 15:11:59 -04:00
ari a4a607768a rename 2022-09-05 15:09:41 -04:00
ari a9b2bdb775 minor refactor 2022-09-05 15:06:28 -04:00
ari eee37346ab v0.7.5 2022-09-02 16:06:34 -04:00
ari 6ee7ce8f70 ignoring non yaml 2022-09-02 15:45:16 -04:00
ari 2dfbc31b5d v0.7.3 2022-09-02 10:36:55 -04:00
ari ab4997494d lint 2022-09-02 10:34:16 -04:00
ari 83b1c85043 correct fix 2022-09-02 10:33:52 -04:00
ari 7526b578ba fixed return values from backend 2022-09-02 10:11:38 -04:00
ari c461640957 fixed storybook 2022-09-02 09:45:32 -04:00
ari fd0a0aa0c4 v0.7.1 2022-09-01 21:23:49 -04:00
ari 3aad35fbce fixed up linting 2022-09-01 17:25:56 -04:00
ari 774ebe482a handling missing ids better + more tranlsations 2022-09-01 17:21:00 -04:00
ari 69a9805c02 added random media player to package 2022-09-01 15:29:37 -04:00
ari 418b9704e7 added desc to dockerfile 2022-09-01 15:29:16 -04:00
ari 6dcbf4d0ed fixed up centering bug 2022-09-01 15:29:16 -04:00
awashingmachineandAri Sosnovsky df2e926711 Adds italian translation (#155)
* Adds italian translation

Adds ita.json

* added to userprofile

Co-authored-by: Ari Sosnovsky <asosnovsky@users.noreply.github.com>
2022-09-01 15:11:25 -04:00
Earion f6df4a0718 Updated French translation (#156)
* Update fra.json

For the record I'm a native french speaker, just wanting to propose my minor contribution

* Update fra.json

small changes
2022-09-01 11:17:34 -04:00
Ari Sosnovsky be5f73bcc7 Update bug_report.md 2022-08-31 22:23:58 -04:00
Ari Sosnovsky 7e9a7061b1 Update bug_report.md 2022-08-31 22:23:49 -04:00
ari 65c0ed1b69 v0.7.0 2022-08-31 22:16:07 -04:00
ari b206c50d80 caching again 2022-08-31 21:58:17 -04:00
ari dacc0730fe using hub 2022-08-31 21:43:06 -04:00
ari b102c6df49 correct grouping 2022-08-31 21:38:35 -04:00
ari d5d8468b78 using dockerhub 2022-08-31 21:37:20 -04:00
ari d6ba4bf3f5 grouping actions 2022-08-31 21:33:05 -04:00
renovate[bot] fff33c79d8 Update dependency @types/react to v18.0.18 (#152)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-08-31 21:26:13 -04:00
renovate[bot] a8b77261db Update dependency @types/jest to v28.1.8 (#151)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-08-31 21:26:03 -04:00
ari bb93e1e322 using ghcr 2022-08-31 21:25:41 -04:00
ari 61270c1528 using bullseye 2022-08-31 21:16:52 -04:00
ari 20b4b4870d trying new image 2022-08-31 19:03:57 -04:00
ari fa6e46aad0 added continue-on-error 2022-08-31 18:51:58 -04:00
ari b07babf178 really old 2022-08-31 16:28:12 -04:00
ari a4be507f1e using older action 2022-08-31 16:22:11 -04:00
ari 1bd41bb879 disabling buildx 2022-08-31 16:15:52 -04:00
ari 7b5258402a using fix 2022-08-31 16:15:19 -04:00
ari 5f28a5da16 removed strange centering 2022-08-31 16:07:05 -04:00
ari f60bbe8ddd added no cache flag 2022-08-31 15:57:10 -04:00
ari f58966c735 lint 2022-08-31 15:46:08 -04:00
ari 499752e02f using in-memory db 2022-08-31 15:44:52 -04:00
ari 00c234541d lint 2022-08-31 15:19:59 -04:00
ari 2918191541 nicer white mode 2022-08-31 15:18:48 -04:00
ari d890c1aa64 functioning profiles 2022-08-31 15:15:30 -04:00
ari 8985312dd2 added language support 2022-08-30 22:03:40 -04:00
ari 03a735b281 settings -> dark/light mode 2022-08-30 21:50:43 -04:00
ari 416d88b965 added user profile api 2022-08-29 12:51:24 -04:00
ari 95ac286b53 added user profile 2022-08-29 12:51:24 -04:00
ari caad458b48 added some initial work on intl 2022-08-29 12:51:24 -04:00
ari 157efa04b1 added some initial work for int 2022-08-29 12:51:24 -04:00
Ari Sosnovsky d4b0c02111 v0.6.3 (#148)
* Update CHANGELOG.md

* Update config.yaml
2022-08-27 14:28:17 -04:00
192 changed files with 3348 additions and 1765 deletions

No files matched your search

+10
View File
@@ -36,4 +36,14 @@ If applicable, add screenshots to help explain your problem.
- Version [e.g. 22] - Version [e.g. 22]
**Additional context** **Additional context**
- Home Assistant Version: [e.g. core-2022.5.4]
- Shortumation Version: [e.g. v0.7.0]
- Homeassistant server type: [e.g. raspberry pi 4 / intel nuc]
Add any other context about the problem here. Add any other context about the problem here.
**Shortumation Logs**
```log
<--- copy here --->
```
+9 -8
View File
@@ -8,6 +8,9 @@ on:
push: push:
branches: branches:
- main - main
concurrency:
group: build-${{ github.event.inputs.version || github.head_ref || github.ref }}
cancel-in-progress: true
jobs: jobs:
metadata: metadata:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -15,12 +18,6 @@ jobs:
outputs: outputs:
version: ${{ steps.version.outputs.VERSION }} version: ${{ steps.version.outputs.VERSION }}
steps: steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.10.0
with:
all_but_latest: true
access_token: ${{ github.token }}
- name: Check out repository - name: Check out repository
uses: actions/checkout@v3 uses: actions/checkout@v3
with: with:
@@ -76,12 +73,14 @@ jobs:
needs: needs:
- metadata - metadata
- build-web - build-web
permissions:
packages: write
strategy: strategy:
matrix: matrix:
arch: arch:
- "aarch64" - "aarch64"
- "amd64" - "amd64"
- "armhf" # see https://github.com/asosnovsky/Shortumation/issues/147 - "armhf"
- "armv7" - "armv7"
- "i386" - "i386"
@@ -89,6 +88,9 @@ jobs:
- name: Check out repository - name: Check out repository
uses: actions/checkout@v3 uses: actions/checkout@v3
# - name: Login to Github Container Registry
# run: echo ${{ github.token }} | docker login ghcr.io -u ${{ github.repository_owner }} --password-stdin
- name: Login to DockerHub - name: Login to DockerHub
uses: docker/login-action@v2.0.0 uses: docker/login-action@v2.0.0
with: with:
@@ -103,7 +105,6 @@ jobs:
- name: ${{ matrix.arch }} / ${{ needs.metadata.outputs.version }} - name: ${{ matrix.arch }} / ${{ needs.metadata.outputs.version }}
uses: home-assistant/builder@master uses: home-assistant/builder@master
continue-on-error: true
with: with:
args: | args: |
--${{ matrix.arch }} \ --${{ matrix.arch }} \
+33 -30
View File
@@ -13,12 +13,16 @@ name: "CodeQL"
on: on:
push: push:
branches: [ "main" ] branches: ["main"]
pull_request: pull_request:
# The branches below must be a subset of the branches above # The branches below must be a subset of the branches above
branches: [ "main" ] branches: ["main"]
schedule: schedule:
- cron: '26 21 * * 2' - cron: "26 21 * * 2"
concurrency:
group: codeql-${{ github.head_ref || github.ref }}
cancel-in-progress: true
jobs: jobs:
analyze: analyze:
@@ -32,41 +36,40 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
language: [ 'javascript', 'python' ] language: ["javascript", "python"]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v3 uses: actions/checkout@v3
# Initializes the CodeQL tools for scanning. # Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL - name: Initialize CodeQL
uses: github/codeql-action/init@v2 uses: github/codeql-action/init@v2
with: with:
languages: ${{ matrix.language }} languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file. # If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file. # By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file. # Prefix the list here with "+" to use these queries and those in the config file.
# Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality # queries: security-extended,security-and-quality
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # ℹ️ Command-line programs to run using the OS shell.
# If this step fails, then you should remove it and run the build manually (see below) # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
- name: Autobuild
uses: github/codeql-action/autobuild@v2
# ℹ️ Command-line programs to run using the OS shell. # If the Autobuild fails above, remove it and uncomment the following three lines.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
# If the Autobuild fails above, remove it and uncomment the following three lines. # - run: |
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. # echo "Run, Build Application using script"
# ./location_of_script_within_repo/buildscript.sh
# - run: | - name: Perform CodeQL Analysis
# echo "Run, Build Application using script" uses: github/codeql-action/analyze@v2
# ./location_of_script_within_repo/buildscript.sh
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
+7 -3
View File
@@ -4,17 +4,21 @@
# #
# Source repository: https://github.com/actions/dependency-review-action # Source repository: https://github.com/actions/dependency-review-action
# Public documentation: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review#dependency-review-enforcement # Public documentation: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review#dependency-review-enforcement
name: 'Dependency Review' name: "Dependency Review"
on: [pull_request] on: [pull_request]
permissions: permissions:
contents: read contents: read
concurrency:
group: deprev-${{ github.head_ref || github.ref }}
cancel-in-progress: true
jobs: jobs:
dependency-review: dependency-review:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: 'Checkout Repository' - name: "Checkout Repository"
uses: actions/checkout@v3 uses: actions/checkout@v3
- name: 'Dependency Review' - name: "Dependency Review"
uses: actions/dependency-review-action@v2 uses: actions/dependency-review-action@v2
+3
View File
@@ -6,6 +6,9 @@ on:
pull_request: pull_request:
branches: branches:
- main - main
concurrency:
group: test-${{ github.head_ref || github.ref }}
cancel-in-progress: true
jobs: jobs:
metadata: metadata:
runs-on: ubuntu-latest runs-on: ubuntu-latest
+27 -134
View File
@@ -1,9 +1,33 @@
# Changelog ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=for-the-badge) # Changelog ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=for-the-badge)
## [0.6.2] - Patches ## [0.7.4] Bugfixes
- Attempting to increasing websocket file limit - Backend now correctly returns unset alias + description
- Support for all !include directives
## [0.7.1] Bugfixes + Italian!
- Added support for automations that do not have an `id`
- Added Italian
- Merged grammar fixes for french
- Fixed up strange centering styling bug
- Replaced more non-multilingual texts with multilingual text
## [0.7.0] Configuration Menu / Light Mode / Lang Support
- Added configuration menu
![image](https://user-images.githubusercontent.com/7451445/187817636-311b5a83-4e08-4b6b-b3b8-2e7086ace136.png)
- Experimental light mode
![image](https://user-images.githubusercontent.com/7451445/187817711-c7a8e23c-b9a4-472b-a348-c1492f3c5d56.png)
- First attempt at a french translation
- No longer using sqllite for automation db
## [0.6.3] - Packages Support & Minor UI improvements
- Full split config support for packages and all advance include directives (i.e. !include_dir_named, !include_dir_merge_list etc)
- Updated metadata box to display origin of the file
- Support for inlined automations!
![image](https://user-images.githubusercontent.com/7451445/187043147-15cea23b-0b64-4484-9c87-747998ea9fe6.png)
## [0.6.1] - v0.6.0 Split Config Support & Better Error handling! ## [0.6.1] - v0.6.0 Split Config Support & Better Error handling!
@@ -20,11 +44,6 @@
- Better global error capture - Better global error capture
![image](https://user-images.githubusercontent.com/7451445/185441268-9dbde36e-b28b-4a13-bd7f-45ae23834e78.png) ![image](https://user-images.githubusercontent.com/7451445/185441268-9dbde36e-b28b-4a13-bd7f-45ae23834e78.png)
## [0.5.3] - Bug Fixes
- Redirecting `/` to `/web` to resolve container install strangeness reported in https://github.com/asosnovsky/Shortumation/issues/125
- Fixed missing flag that caused the automation to explode in https://github.com/asosnovsky/Shortumation/issues/124
## [0.5.2] - Better Controls ## [0.5.2] - Better Controls
- Add automation trigger - Add automation trigger
@@ -45,11 +64,6 @@
- Websockets now live-refresh when updates occur - Websockets now live-refresh when updates occur
## [0.4.0] - Depedency update
- Core dependency updates
- Python port is now dynamically set
## [0.3.4] - Condition/Trigger Editor Upgrades! ## [0.3.4] - Condition/Trigger Editor Upgrades!
- Many condition editor fixes - Many condition editor fixes
@@ -66,19 +80,6 @@
![image](https://user-images.githubusercontent.com/7451445/180238004-4b04f13a-77a2-4c4c-9144-963dbc394bf4.png) ![image](https://user-images.githubusercontent.com/7451445/180238004-4b04f13a-77a2-4c4c-9144-963dbc394bf4.png)
## [0.3.2] - Fixed Addon Image for arm-based devices
- Using hypercon instead of uvicorn (this losses the rust dependency which makes it easier to install on arm)
- Pre-building web assets outside of docker (this takes the image size down and speeds up instaltion of addon)
- Updated build scripts to actually fail installation when build/prep steps fail
- Ensured that builds for all architecture run successfully
- Re-worked github actions (quicker test phases)
## [0.3.1] - Increased Pagination + Restricted Repeat Node
- Increased pagination to display up to 10,000 autos for now
- Repeat node now has types
## [0.3.0] - Complete Refactor of Graphs ## [0.3.0] - Complete Refactor of Graphs
- Added visual support for - Added visual support for
@@ -97,113 +98,5 @@
![image](https://user-images.githubusercontent.com/7451445/179135916-8083aab5-bee1-4d27-b19d-9e000ca012f9.png) ![image](https://user-images.githubusercontent.com/7451445/179135916-8083aab5-bee1-4d27-b19d-9e000ca012f9.png)
## [0.1.22] - Many Visual improvements
- Deprecated several custom components in favor of mui.com
- Device Editor now has support for 99% of diplay types
- Condition Device is implemented
- Improved naming autogen for trigger & choose
## [0.1.21] - Service Editor
- first version of service editor
- reloading automations on save
## [0.1.20] - UI Bugfixes
- Using MUI elements for input time
- Added delay action / wait_on_triggers action
- Added enabled/disabled flag in node editor
- Optional flip vertical during desktop mode
- Fixed up modal clipping
## [0.1.19] - Vertical mobile mode
- in mobile mode we draw the graphs vertically now
## [0.1.17] - Websockets
- Connected to HA main websocket -- now we retrieve real-time information about
- Device names
- Entity names/ids
- Autocomplete for devices and entities
## [0.1.14] - Material UI + Autocomplete
- Brought some Material UI elements for input and text
- Autocomplete for tags
- Using 'id' as alias for trigger (as it seems to break HA otherwise)
- Not using 'alias' for conditions, always auto-generating it (again, this used to break HA)
- Added missing `data` object to service-actions
## [0.1.13] - YAML
- Better YAML
- Rewrote yaml parser/loader to use pyyaml and safe mode
- Cleaned up description vs alias
## [0.1.12] - Less Intense Error Messages
- Added more node-based errors (this way it's easier to see where validations failed)
- Made the validators less strict in order to capture more edge cases that HA supports
- Nicer auto-generated descriptions for some trigger nodes
## [0.1.10] - More Bug Fixes
- Allowing null or undefined values for metadata fields
- Trigger.platform==time will now have the .at property better supported
## [0.1.9] - Fixed up invalid types for various triggers
- Some triggers had invalid types and were causing a false-positive validation
## [0.1.8] - Support for Malformed Automations
- API will no longer error out on missing values or invalid lists
- Frontend has support for displaying bad automations
## [0.1.6] - Mobile Mode
- Improved mobile mode
- Fixed up arrow styles due to typos
- Added selection color
## [0.1.2] - Docker Hub Images
- Publishing images to docker hub is now stable
## [0.0.15] - Publish to dockerhub
- Publishing images to docker hub
## [0.0.14] - Using vanila ha yaml
- Supporing vanilla out of the box HA yaml as oppose to parsing them (no more $smType)
- Conditions have now a more a explicit node
## [0.0.13] - Better Styling with react-flow
- Fixed up styling (using react-flow)
- cleaned up some button styles
## [0.0.12] - Tags
- Added tag management system for automations
## [0.0.11] - Zoom
- Added lazy saving
## [0.0.10] - Zoom
- Introducing Zoom!
## [0.0.9] - First Working Version
- Instalable verion via github
- Initial POC done
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+3 -1
View File
@@ -2,7 +2,7 @@
ARG BUILD_ARCH ARG BUILD_ARCH
# <--- Main Image --> # <--- Main Image -->
FROM python:3.10-slim-buster FROM python:3.10-slim-bullseye
WORKDIR /app WORKDIR /app
# <--- Post-Build Args --> # <--- Post-Build Args -->
@@ -10,6 +10,7 @@ ARG BUILD_VERSION
# <--- Environment Variables --> # <--- Environment Variables -->
ENV BUILD_VERSION $BUILD_VERSION ENV BUILD_VERSION $BUILD_VERSION
ENV BUILD_ARCH $BUILD_ARCH
# <--- System Wide Dependencies --> # <--- System Wide Dependencies -->
ENV LANG C.UTF-8 ENV LANG C.UTF-8
@@ -45,3 +46,4 @@ ENTRYPOINT [ "/app/bin/run.sh" ]
CMD [ "/app" ] CMD [ "/app" ]
LABEL org.opencontainers.image.source https://github.com/asosnovsky/Shortumation LABEL org.opencontainers.image.source https://github.com/asosnovsky/Shortumation
LABEL org.opencontainers.image.description "A better way to write automations in home-assistant without having to install and run a seperate automation engine!"
+25 -15
View File
@@ -1,20 +1,30 @@
get_index # unused function (src/api/app.py:43) get_index # unused function (src/api/app.py:41)
list_autos # unused function (src/api/routes/automations.py:13) list_autos # unused function (src/api/routes/automations.py:14)
insert_auto # unused function (src/api/routes/automations.py:28) insert_auto # unused function (src/api/routes/automations.py:30)
update_auto # unused function (src/api/routes/automations.py:32) update_auto # unused function (src/api/routes/automations.py:35)
delete_auto # unused function (src/api/routes/automations.py:40) delete_auto # unused function (src/api/routes/automations.py:45)
read_details # unused function (src/api/routes/details.py:11) read_details # unused function (src/api/routes/details.py:12)
read_profile # unused function (src/api/routes/details.py:24)
save_profile # unused function (src/api/routes/details.py:28)
read_ping # unused function (src/api/routes/ping.py:10) read_ping # unused function (src/api/routes/ping.py:10)
websocket_endpoint # unused function (src/api/routes/socket.py:13) websocket_endpoint # unused function (src/api/routes/socket.py:13)
params # unused variable (src/api/types.py:16) params # unused variable (src/api/types.py:16)
total_items # unused variable (src/api/types.py:17) total_items # unused variable (src/api/types.py:17)
data # unused variable (src/api/types.py:18) alias # unused variable (src/automations/types.py:36)
trigger_variables # unused variable (src/automations/types.py:13) description # unused variable (src/automations/types.py:37)
trigger # unused variable (src/automations/types.py:15) trigger_variables # unused variable (src/automations/types.py:38)
condition # unused variable (src/automations/types.py:16) mode # unused variable (src/automations/types.py:39)
action # unused variable (src/automations/types.py:17) trigger # unused variable (src/automations/types.py:40)
_.to_json # unused method (src/automations/types.py:45) condition # unused variable (src/automations/types.py:41)
_.automation_tags # unused property (src/hass_config/loader.py:17) action # unused variable (src/automations/types.py:42)
_.to_json # unused method (src/automations/types.py:70)
error_name # unused variable (src/errors.py:22)
error_message # unused variable (src/errors.py:23)
error_traceback # unused variable (src/errors.py:24)
original_error # unused variable (src/errors.py:25)
_.automation_tags # unused property (src/hass_config/loader.py:28)
json_dumps # unused function (src/json_serializer.py:5) json_dumps # unused function (src/json_serializer.py:5)
SecretValue # unused class (src/yaml_serializer/__init__.py:40) theme # unused variable (src/user_profile.py:10)
EnvVar # unused class (src/yaml_serializer/__init__.py:78) lang # unused variable (src/user_profile.py:11)
SecretValue # unused class (src/yaml_serializer/__init__.py:48)
EnvVar # unused class (src/yaml_serializer/__init__.py:186)
+4 -6
View File
@@ -3,13 +3,13 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse from fastapi.responses import RedirectResponse
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from src.automations.manager import AutomationManager
from src.env import API_PREFIX, ORIGIN, ROOT_FOLDER from src.env import API_PREFIX, ORIGIN, ROOT_FOLDER
from src.hass_config.loader import HassConfig
from .routes import automations, details, ping, socket from .routes import automations, details, ping, socket
def make_app(automation_mgr: AutomationManager) -> FastAPI: def make_app(hass_config: HassConfig) -> FastAPI:
app = FastAPI() app = FastAPI()
has_web_folder = (ROOT_FOLDER / "web").exists() has_web_folder = (ROOT_FOLDER / "web").exists()
if has_web_folder: if has_web_folder:
@@ -33,11 +33,9 @@ def make_app(automation_mgr: AutomationManager) -> FastAPI:
) )
app.include_router(ping.router, prefix="/ping") app.include_router(ping.router, prefix="/ping")
app.include_router( app.include_router(
automations.make_automation_router(automation_mgr), prefix=f"{API_PREFIX}/automations" automations.make_automation_router(hass_config), prefix=f"{API_PREFIX}/automations"
)
app.include_router(
details.make_details_router(automation_mgr.hass_config), prefix=f"{API_PREFIX}/details"
) )
app.include_router(details.make_details_router(hass_config), prefix=f"{API_PREFIX}/details")
app.include_router(socket.router, prefix=f"{API_PREFIX}/socket") app.include_router(socket.router, prefix=f"{API_PREFIX}/socket")
@app.get("/") @app.get("/")
+12 -2
View File
@@ -5,13 +5,15 @@ from src.automations.errors import FailedDeletion
from src.automations.manager import AutomationManager from src.automations.manager import AutomationManager
from src.automations.types import Automation, ExtenededAutomation from src.automations.types import Automation, ExtenededAutomation
from src.errors import ErrorSet from src.errors import ErrorSet
from src.hass_config.loader import HassConfig
def make_automation_router(automations: AutomationManager) -> APIRouter: def make_automation_router(hass_config: HassConfig) -> APIRouter:
router = APIRouter() router = APIRouter()
@router.post("/list") @router.post("/list", response_model_exclude_unset=True, response_model_exclude_none=True)
def list_autos(body: ListParams) -> ListData[ExtenededAutomation]: def list_autos(body: ListParams) -> ListData[ExtenededAutomation]:
automations = AutomationManager(hass_config)
try: try:
automations.reload() automations.reload()
return ListData( return ListData(
@@ -27,18 +29,26 @@ def make_automation_router(automations: AutomationManager) -> APIRouter:
@router.post("/item") @router.post("/item")
def insert_auto(body: Automation): def insert_auto(body: Automation):
if body.id is None:
raise HTTPException(status_code=400, detail={"msg": "must contain an id"})
automations = AutomationManager(hass_config)
automations.create(body) automations.create(body)
@router.put("/item") @router.put("/item")
def update_auto(body: ExtenededAutomation): def update_auto(body: ExtenededAutomation):
if body.id is None:
raise HTTPException(status_code=400, detail={"msg": "must contain an id"})
automations = AutomationManager(hass_config)
automations.update(body) automations.update(body)
@router.post("/item/tags") @router.post("/item/tags")
def update_tags(body: UpdateTags): def update_tags(body: UpdateTags):
automations = AutomationManager(hass_config)
automations.update_tags(body.automation_id, body.tags) automations.update_tags(body.automation_id, body.tags)
@router.delete("/item") @router.delete("/item")
def delete_auto(body: ExtenededAutomation): def delete_auto(body: ExtenededAutomation):
automations = AutomationManager(hass_config)
try: try:
automations.delete(body) automations.delete(body)
except FailedDeletion as err: except FailedDeletion as err:
+12 -4
View File
@@ -3,6 +3,7 @@ from fastapi import APIRouter
from src.automations.loader import extract_automation_refs from src.automations.loader import extract_automation_refs
from src.env import BUILD_VERSION, HASSIO_TOKEN, HASSIO_WS from src.env import BUILD_VERSION, HASSIO_TOKEN, HASSIO_WS
from src.hass_config import HassConfig from src.hass_config import HassConfig
from src.user_profile import UserProfile
def make_details_router(hass_config: HassConfig) -> APIRouter: def make_details_router(hass_config: HassConfig) -> APIRouter:
@@ -16,10 +17,17 @@ def make_details_router(hass_config: HassConfig) -> APIRouter:
"hassio_url": HASSIO_WS, "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": { "profile": hass_config.get_profile_path(),
config_key: auto_file "autos": list(map(repr, extract_automation_refs(hass_config))),
for config_key, auto_file in extract_automation_refs(hass_config)
},
} }
@router.get("/profile")
def read_profile():
return UserProfile.from_hass_config(hass_config)
@router.put("/profile")
def save_profile(user_profile: UserProfile):
user_profile.save(hass_config)
return {"saved": hass_config.get_profile_path()}
return router return router
+1 -2
View File
@@ -1,6 +1,5 @@
from src.api.app import make_app from src.api.app import make_app
from src.automations.manager import AutomationManager
from src.hass_config import find_hass_config from src.hass_config import find_hass_config
hass_config = find_hass_config() hass_config = find_hass_config()
app = make_app(AutomationManager(hass_config)) app = make_app(hass_config)
+26 -110
View File
@@ -1,129 +1,45 @@
import base64 from typing import Iterable
import json
import sqlite3
from contextlib import contextmanager
from pathlib import Path
from typing import Iterable, Iterator
from src.logger import get_logger from src.logger import get_logger
from .errors import ( from .errors import DBNoAutomationFound, RepeatedAutomationId
DBDataError,
DBError,
DBNoAutomationFound,
RepeatedAutomationId,
)
from .types import ExtenededAutomation from .types import ExtenededAutomation
logger = get_logger(__file__) logger = get_logger(__file__)
automations_tbl = "autos"
def encode_auto(auto: ExtenededAutomation) -> str:
return base64.b64encode(
json.dumps(auto.to_primitive(include_tags=True)).encode("utf-8")
).decode("utf-8")
def encode_obj(auto: dict | list) -> str:
return base64.b64encode(json.dumps(auto).encode("utf-8")).decode("utf-8")
def decode_auto(
auto_str: str, source_file: str, source_file_type: str, configuration_key: str
) -> ExtenededAutomation:
return ExtenededAutomation(
source_file=source_file,
source_file_type=source_file_type,
configuration_key=decode_obj(configuration_key), # type: ignore
**decode_obj(auto_str),
)
def decode_obj(obj_str: str) -> dict | list:
return json.loads(base64.b64decode(obj_str.encode("utf-8")).decode("utf-8"))
class AutomationDBConnection: class AutomationDBConnection:
def __init__(self, db_file: Path) -> None: def __init__(self) -> None:
self.db_file = db_file self.db: dict[str, ExtenededAutomation] = {}
self.missing_id_db: list[ExtenededAutomation] = []
def reset(self): def reset(self):
self.db_file.unlink(missing_ok=True) self.db = {}
self.create_db() self.missing_id_db = []
@contextmanager
def get_cur(self) -> Iterator[sqlite3.Cursor]:
conn = sqlite3.connect(self.db_file)
cur = conn.cursor()
try:
yield cur
conn.commit()
except sqlite3.DatabaseError as err:
raise DBError(*err.args) from err
finally:
cur.close()
conn.close()
def create_db(self):
with self.get_cur() as cur:
cur.execute(
f"""
CREATE TABLE IF NOT EXISTS {automations_tbl} (
id TEXT NOT NULL PRIMARY KEY,
alias TEXT,
description TEXT,
mode TEXT NOT NULL,
source_file TEXT NOT NULL,
source_file_type TEXT NOT NULL,
configuration_key BLOB NOT NULL,
rest BLOB NOT NULL
);
"""
)
def insert_automations(self, automations: list[ExtenededAutomation]): def insert_automations(self, automations: list[ExtenededAutomation]):
with self.get_cur() as cur: repeated_automations = []
for automation in automations: for automation in automations:
try: if automation.id is None:
cur.execute( self.missing_id_db.append(automation)
f""" elif self.db.get(automation.id, None) is None:
INSERT INTO {automations_tbl} VALUES ( self.db[automation.id] = automation
"{automation.id}", else:
"{automation.alias}", repeated_automations.append(
"{automation.description}", f"automation id '{automation.id}' in '{automation.source_file}' was already seen before. Please check for duplicate automation ids in your files."
"{automation.mode}", )
"{automation.source_file}", if len(repeated_automations) > 0:
"{automation.source_file_type}", raise RepeatedAutomationId(repeated_automations)
"{encode_obj(automation.configuration_key)}",
"{encode_auto(automation)}"
);
""",
)
except sqlite3.IntegrityError as err:
raise RepeatedAutomationId(
f"automation id '{automation.id}' in '{automation.source_file}' was already seen before. Please check for duplicate automation ids in your files."
) from err
def get_automation(self, automation_id: str) -> ExtenededAutomation: def get_automation(self, automation_id: str) -> ExtenededAutomation:
with self.get_cur() as cur: if a := self.db.get(automation_id, None):
cur.execute( return a
f'SELECT rest, source_file, source_file_type, configuration_key FROM {automations_tbl} WHERE id = "{automation_id}"' # nosec raise DBNoAutomationFound(automation_id)
)
objs = cur.fetchone()
if objs is None:
raise DBNoAutomationFound(automation_id)
[rest, source_file, source_file_type, configuration_key] = objs
return decode_auto(rest, source_file, source_file_type, configuration_key)
def list_automations(self, offset: int, limit: int) -> Iterable[ExtenededAutomation]: def list_automations(self, offset: int, limit: int) -> Iterable[ExtenededAutomation]:
with self.get_cur() as cur: for i, auto in enumerate([*self.missing_id_db, *self.db.values()]):
for [rest, source_file, source_file_type, configuration_key] in cur.execute( if i >= offset and i < limit + offset:
f"SELECT rest, source_file, source_file_type, configuration_key FROM {automations_tbl} LIMIT {limit} OFFSET {offset}" # nosec yield auto
):
yield decode_auto(rest, source_file, source_file_type, configuration_key)
def count_automations(self) -> int: def count_automations(self) -> int:
with self.get_cur() as cur: return len(self.db)
return cur.execute(f"SELECT count(id) FROM {automations_tbl}").fetchone()[0] # nosec
+4
View File
@@ -17,6 +17,10 @@ class FailedDeletion(AutomationLoaderException):
pass pass
class InvalidPackage(AutomationLoaderException):
pass
class DBError(Exception): class DBError(Exception):
pass pass
+69 -51
View File
@@ -1,4 +1,3 @@
from itertools import chain
from pathlib import Path from pathlib import Path
from typing import Any, Iterator, Tuple, Union from typing import Any, Iterator, Tuple, Union
@@ -16,7 +15,7 @@ from src.yaml_serializer import (
) )
from ..hass_config.loader import HassConfig from ..hass_config.loader import HassConfig
from .errors import InvalidAutomationFile from .errors import InvalidAutomationFile, InvalidPackage
from .tags import TagManager from .tags import TagManager
from .types import ( from .types import (
AutomationExtractedIter, AutomationExtractedIter,
@@ -46,7 +45,9 @@ def load_and_iter_automations(
elif isinstance(ref, InlineAutomation): elif isinstance(ref, InlineAutomation):
yield from load_automation_inline_ref(hass_config.root_path, tag_manager, ref) yield from load_automation_inline_ref(hass_config.root_path, tag_manager, ref)
else: else:
raise AssertionError(f"ref has an invalid type of {type(ref)} = {ref}") raise logger.error(
AssertionError(f"ref has an invalid type of {type(ref)} = {ref}")
)
except InvalidAutomationFile as e: except InvalidAutomationFile as e:
logger.error(e) logger.error(e)
@@ -56,12 +57,17 @@ def extract_automation_refs(
) -> AutomationExtractedIter: ) -> AutomationExtractedIter:
found = False found = False
for ref in chain( for ref in extract_automation_root_refs(hass_config):
extract_automation_root_refs(hass_config), extract_automation_package_refs(hass_config)
):
found = True found = True
yield ref yield ref
try:
for ref in extract_automation_package_refs(hass_config):
found = True
yield ref
except InvalidPackage as err:
logger.fatal(err)
if not found: if not found:
yield IncludedAutoamtion([""], IncludedYaml(hass_config.root_path / "automations.yaml")) yield IncludedAutoamtion([""], IncludedYaml(hass_config.root_path / "automations.yaml"))
@@ -80,7 +86,7 @@ def extract_automation_root_refs(
source_file=hass_config.get_configuration_path(), source_file=hass_config.get_configuration_path(),
) )
else: else:
logger.warning(f"found an invalid type in {key}!") logger.error(f"found an invalid type in {key}!")
def extract_automation_package_refs(hass_config: HassConfig) -> AutomationExtractedIter: def extract_automation_package_refs(hass_config: HassConfig) -> AutomationExtractedIter:
@@ -93,7 +99,7 @@ def extract_automation_package_refs(hass_config: HassConfig) -> AutomationExtrac
packages, packages,
) )
elif isinstance(packages_config, IncludedYamlDirList): elif isinstance(packages_config, IncludedYamlDirList):
raise AssertionError("cannot configure packages with 'included_dir_list' directive") raise InvalidPackage("cannot configure packages with 'included_dir_list' directive")
elif isinstance(packages_config, IncludedYamlDirNamed): elif isinstance(packages_config, IncludedYamlDirNamed):
packages = packages_config.to_normalized_json(use_path_as_keys=True) packages = packages_config.to_normalized_json(use_path_as_keys=True)
for package_path, package in packages.items(): for package_path, package in packages.items():
@@ -109,7 +115,7 @@ def extract_automation_package_refs(hass_config: HassConfig) -> AutomationExtrac
package_set, package_set,
) in iter(packages_config): ) in iter(packages_config):
if not isinstance(package_set, dict): if not isinstance(package_set, dict):
raise AssertionError( raise InvalidPackage(
f"expected {pacakge_set_path} to be a dictionary but got {type(package_set)}" f"expected {pacakge_set_path} to be a dictionary but got {type(package_set)}"
) )
yield from extract_automation_inline_package_refs( yield from extract_automation_inline_package_refs(
@@ -124,7 +130,7 @@ def extract_automation_package_refs(hass_config: HassConfig) -> AutomationExtrac
packages_config, packages_config,
) )
else: else:
raise AssertionError("configurations.homeassistant.packages must be a dictionary!") raise InvalidPackage("configurations.homeassistant.packages must be a dictionary!")
def extract_automation_inline_package_refs( def extract_automation_inline_package_refs(
@@ -134,44 +140,48 @@ def extract_automation_inline_package_refs(
ignore_package_name=False, ignore_package_name=False,
) -> AutomationExtractedIter: ) -> AutomationExtractedIter:
for package_name, package_data in packages_config.items(): for package_name, package_data in packages_config.items():
if isinstance(package_data, IncludedYaml): logger.info(f"Loading package={package_name}:{type(package_data)} from {package_data}")
package_mapping = package_data.to_normalized_json() try:
yield from extract_automation_from_package( if isinstance(package_data, IncludedYaml):
package_data=package_mapping, package_mapping = package_data.to_normalized_json()
package_name=package_name,
source_file=source_file,
prefix_config_keys=prefix_config_keys,
ignore_package_name=ignore_package_name,
)
elif isinstance(package_data, IncludedYamlDirList):
raise NotImplementedError(package_data)
elif isinstance(package_data, IncludedYamlDirNamed):
for package_key_path in package_data.to_normalized_json(True).keys():
if package_key_path.stem == "automation":
yield IncludedAutoamtion(
configuration_key=[package_name], ref=IncludedYaml(package_key_path)
)
elif isinstance(package_data, IncludedYamlDirMergedNamed):
for data_path, data_set in iter(package_data):
yield from extract_automation_from_package( yield from extract_automation_from_package(
package_data=package_mapping,
package_name=package_name, package_name=package_name,
package_data=data_set, source_file=source_file,
source_file=data_path, prefix_config_keys=prefix_config_keys,
prefix_config_keys=[], ignore_package_name=ignore_package_name,
ignore_package_name=True,
) )
elif isinstance(package_data, dict): elif isinstance(package_data, IncludedYamlDirList):
yield from extract_automation_from_package( raise NotImplementedError(package_data)
package_data=package_data, elif isinstance(package_data, IncludedYamlDirNamed):
package_name=package_name, for package_key_path in package_data.to_normalized_json(True).keys():
source_file=source_file, if package_key_path.stem == "automation":
prefix_config_keys=prefix_config_keys, yield IncludedAutoamtion(
ignore_package_name=ignore_package_name, configuration_key=[package_name], ref=IncludedYaml(package_key_path)
) )
else: elif isinstance(package_data, IncludedYamlDirMergedNamed):
raise AssertionError( for data_path, data_set in iter(package_data):
f"configurations.homeassistant.packages[{package_name}] must be a dictionary!" yield from extract_automation_from_package(
) package_name=package_name,
package_data=data_set,
source_file=data_path,
prefix_config_keys=[],
ignore_package_name=True,
)
elif isinstance(package_data, dict):
yield from extract_automation_from_package(
package_data=package_data,
package_name=package_name,
source_file=source_file,
prefix_config_keys=prefix_config_keys,
ignore_package_name=ignore_package_name,
)
elif package_data is not None:
raise InvalidPackage(
f"configurations.homeassistant.packages.{package_name} must be a dictionary but got {type(package_data)}!"
)
except InvalidPackage as err:
logger.error(err)
def extract_automation_from_package( def extract_automation_from_package(
@@ -236,9 +246,11 @@ def load_automation_inline_ref(
) -> Iterator[ExtenededAutomation]: ) -> Iterator[ExtenededAutomation]:
for auto in inline_automation.automations: for auto in inline_automation.automations:
try: try:
cleaned_automation = clean_automation(auto)
automation_id = cleaned_automation.get("id", None)
yield ExtenededAutomation( yield ExtenededAutomation(
**clean_automation(auto), **cleaned_automation,
tags=tag_manager.get(auto["id"], {}), tags={} if automation_id is None else tag_manager.get(automation_id, {}),
configuration_key=inline_automation.configuration_key, configuration_key=inline_automation.configuration_key,
source_file=str(inline_automation.source_file.resolve().relative_to(root_path)), source_file=str(inline_automation.source_file.resolve().relative_to(root_path)),
source_file_type="inline", source_file_type="inline",
@@ -286,9 +298,11 @@ def load_automation_path(
if isinstance(automations, dict): if isinstance(automations, dict):
try: try:
cleaned_automation = clean_automation(automations)
automation_id = cleaned_automation.get("id", None)
yield ExtenededAutomation( yield ExtenededAutomation(
**clean_automation(automations), **cleaned_automation,
tags=tag_manager.get(automations["id"], {}), tags={} if automation_id is None else tag_manager.get(automation_id, {}),
configuration_key=configuration_key, configuration_key=configuration_key,
source_file=str(automation_path.resolve().relative_to(root_path)), source_file=str(automation_path.resolve().relative_to(root_path)),
source_file_type="obj", source_file_type="obj",
@@ -305,9 +319,11 @@ def load_automation_path(
return return
for automation in automations: for automation in automations:
try: try:
cleaned_automation = clean_automation(automation)
automation_id = cleaned_automation.get("id", None)
yield ExtenededAutomation( yield ExtenededAutomation(
**clean_automation(automation), **cleaned_automation,
tags=tag_manager.get(automation["id"], {}), tags={} if automation_id is None else tag_manager.get(automation_id, {}),
configuration_key=configuration_key, configuration_key=configuration_key,
source_file=str(automation_path.resolve().relative_to(root_path)), source_file=str(automation_path.resolve().relative_to(root_path)),
source_file_type="list", source_file_type="list",
@@ -324,6 +340,8 @@ def load_automation_path(
def clean_automation(auto_raw: dict): def clean_automation(auto_raw: dict):
return { return {
**auto_raw, **auto_raw,
"alias": auto_raw.get("alias", "") or "",
"description": auto_raw.get("description", "") or "",
"condition": ifempty_or_null_then_list(load_conditions(auto_raw.get("condition", []))), "condition": ifempty_or_null_then_list(load_conditions(auto_raw.get("condition", []))),
"action": ifempty_or_null_then_list(load_conditions(auto_raw.get("action", []))), "action": ifempty_or_null_then_list(load_conditions(auto_raw.get("action", []))),
"trigger": ifempty_or_null_then_list(normalize_obj(auto_raw.get("trigger", []))), "trigger": ifempty_or_null_then_list(normalize_obj(auto_raw.get("trigger", []))),
+8 -13
View File
@@ -1,8 +1,6 @@
from pathlib import Path
from tempfile import mktemp
from typing import Optional, Union from typing import Optional, Union
from src.errors import ErrorSet from src.errors import ErrorSet, FormattedError
from src.hass_config.loader import HassConfig from src.hass_config.loader import HassConfig
from src.logger import get_logger from src.logger import get_logger
from src.yaml_serializer import dump_yaml, load_yaml from src.yaml_serializer import dump_yaml, load_yaml
@@ -13,11 +11,7 @@ from .errors import (
DBError, DBError,
InvalidAutomationFile, InvalidAutomationFile,
) )
from .loader import ( from .loader import get_base_automation_key, load_and_iter_automations
get_base_automation_key,
load_and_iter_automations,
load_automation_path,
)
from .tags import TagManager from .tags import TagManager
from .types import Automation, ExtenededAutomation from .types import Automation, ExtenededAutomation
@@ -28,12 +22,9 @@ class AutomationManager:
def __init__( def __init__(
self, self,
hass_config: HassConfig, hass_config: HassConfig,
db_path: Optional[Path] = None,
) -> None: ) -> None:
if db_path is None:
db_path = Path(mktemp()) # nosec
self.hass_config = hass_config self.hass_config = hass_config
self.db = AutomationDBConnection(db_path) self.db = AutomationDBConnection()
self.tag_path = hass_config.get_automation_tags_path() self.tag_path = hass_config.get_automation_tags_path()
self.tag_manager = TagManager() self.tag_manager = TagManager()
self.reload_tags() self.reload_tags()
@@ -66,7 +57,7 @@ class AutomationManager:
if len(batch) >= 0: if len(batch) >= 0:
self.db.insert_automations(batch) self.db.insert_automations(batch)
except DBError as e: except DBError as e:
logger.warning(e) logger.warning(FormattedError.from_error(e))
errors.append(e) errors.append(e)
if len(errors) > 0: if len(errors) > 0:
raise ErrorSet(*errors) raise ErrorSet(*errors)
@@ -93,6 +84,8 @@ class AutomationManager:
) )
def update(self, automation: ExtenededAutomation, create_if_not_found: bool = False): def update(self, automation: ExtenededAutomation, create_if_not_found: bool = False):
if automation.id is None:
raise AssertionError("automation.id must be defined to update!")
automation_path = self.hass_config.root_path / automation.source_file automation_path = self.hass_config.root_path / automation.source_file
if not automation_path.parent.exists(): if not automation_path.parent.exists():
automation_path.parent.mkdir(parents=True) automation_path.parent.mkdir(parents=True)
@@ -159,6 +152,8 @@ class AutomationManager:
self.tag_manager.save(self.tag_path) self.tag_manager.save(self.tag_path)
def delete(self, automation: ExtenededAutomation): def delete(self, automation: ExtenededAutomation):
if automation.id is None:
raise AssertionError("automation.id must be defined to update!")
automation_path = self.hass_config.root_path / automation.source_file automation_path = self.hass_config.root_path / automation.source_file
if automation.source_file_type == "obj": if automation.source_file_type == "obj":
automation_path.unlink(missing_ok=True) automation_path.unlink(missing_ok=True)
+9 -3
View File
@@ -15,20 +15,26 @@ class InlineAutomation(NamedTuple):
source_file: Path source_file: Path
automations: list[dict] automations: list[dict]
def __repr__(self) -> str:
return f"InlineAutomation(configuration_key='{self.configuration_key}', source_file='{self.source_file}')"
class IncludedAutoamtion(NamedTuple): class IncludedAutoamtion(NamedTuple):
configuration_key: ConfigurationKey configuration_key: ConfigurationKey
ref: IncludedYamlDir ref: IncludedYamlDir
def __repr__(self) -> str:
return f"InlineAutomation(configuration_key='{self.configuration_key}', ref='{self.ref}')"
ExtractedAutomation = InlineAutomation | IncludedAutoamtion ExtractedAutomation = InlineAutomation | IncludedAutoamtion
AutomationExtractedIter = Iterator[ExtractedAutomation] AutomationExtractedIter = Iterator[ExtractedAutomation]
class BaseAutomation(BaseModel): class BaseAutomation(BaseModel):
id: str id: Optional[str]
alias: Optional[str] = None alias: str = ""
description: Optional[str] = None description: str = ""
trigger_variables: Optional[dict[str, Union[str, int, bool, float]]] = None trigger_variables: Optional[dict[str, Union[str, int, bool, float]]] = None
mode: str = "single" mode: str = "single"
trigger: list[dict] = [] trigger: list[dict] = []
+23 -1
View File
@@ -1,3 +1,7 @@
import traceback
from typing import NamedTuple
class ErrorSet(Exception): class ErrorSet(Exception):
"""An exception collection exception""" """An exception collection exception"""
@@ -7,6 +11,24 @@ class ErrorSet(Exception):
def gen_message(self): def gen_message(self):
if len(self.errors) > 1: if len(self.errors) > 1:
return "Encountered multiple errors:\n >" + "\n >".join(map(repr, self.errors)) return "Encountered multiple errors:\n >" + "\n >".join(
map(FormattedError.from_error, self.errors)
)
else: else:
return str(self.errors[0].args) return str(self.errors[0].args)
class FormattedError(NamedTuple):
error_name: str
error_message: str
error_traceback: str
original_error: Exception
@classmethod
def from_error(cls, err: Exception):
return cls(
error_name=str(err.__class__.__name__),
error_message=str(err.args),
error_traceback="\n\n".join(traceback.format_tb(err.__traceback__)),
original_error=err,
)
+3
View File
@@ -60,5 +60,8 @@ class HassConfig:
def get_automation_tags_path(self) -> Path: def get_automation_tags_path(self) -> Path:
return self.get_shortumations_path() / "tags.yaml" return self.get_shortumations_path() / "tags.yaml"
def get_profile_path(self) -> Path:
return self.get_shortumations_path() / "profile.yaml"
def get_configuration_path(self) -> Path: def get_configuration_path(self) -> Path:
return self.root_path / "configuration.yaml" return self.root_path / "configuration.yaml"
+24
View File
@@ -0,0 +1,24 @@
from typing import Literal
from pydantic import BaseModel
from src.hass_config import HassConfig
from src.yaml_serializer import dump_yaml, load_yaml
class UserProfile(BaseModel):
theme: Literal["dark", "light"] = "dark"
lang: str = "eng"
@classmethod
def from_hass_config(cls, hass_config: HassConfig):
path = hass_config.get_profile_path()
if path.exists():
with hass_config.get_profile_path().open("r") as fp:
return cls(**load_yaml(fp, hass_config.root_path)) # type: ignore
else:
return cls()
def save(self, hass_config: HassConfig):
with hass_config.get_profile_path().open("w") as fp:
fp.write(dump_yaml(self.dict(), hass_config.root_path))
+10 -3
View File
@@ -1,21 +1,28 @@
from pathlib import Path from pathlib import Path
from typing import Iterator, NamedTuple, Tuple, Union from typing import Iterator, NamedTuple, Tuple
from yaml.nodes import Node from yaml.nodes import Node
from src.logger import get_logger
from .manager import YamlManager from .manager import YamlManager
dump_yaml = YamlManager.dump_yaml dump_yaml = YamlManager.dump_yaml
load_yaml = YamlManager.load_yaml load_yaml = YamlManager.load_yaml
logger = get_logger(__file__)
def load_dir_yaml(folder_or_file: Path) -> Iterator[Tuple[Path, dict | list]]: def load_dir_yaml(folder_or_file: Path) -> Iterator[Tuple[Path, dict | list]]:
if folder_or_file.is_dir(): if folder_or_file.is_dir():
for file in folder_or_file.iterdir(): for file in folder_or_file.iterdir():
yield from load_dir_yaml(file) yield from load_dir_yaml(file)
else: else:
with folder_or_file.open("r") as fp: if folder_or_file.suffix.lower() == ".yaml":
yield folder_or_file, load_yaml(fp, root_path=folder_or_file.parent) with folder_or_file.open("r") as fp:
yield folder_or_file, load_yaml(fp, root_path=folder_or_file.parent)
else:
logger.info(f"Ignoring the file {folder_or_file}")
@YamlManager.as_constructor("!include") @YamlManager.as_constructor("!include")
@@ -0,0 +1,7 @@
# all the packages!
This is really cool :)
- A list item!
<<more thisngs!>>
@@ -1 +1,38 @@
automation: !include ../automations/ui.yaml automation: !include ../automations/ui.yaml
media_player:
- platform: template
media_players:
receiver:
friendly_name: Receiver
current_source_template: "{{ states('input_text.selected_source') }}"
value_template: >
{% if is_state("input_boolean.receiver_on", "on") -%}
on
{%- else -%}
off
{%- endif %}
turn_on:
service: switch.turn_on
data_template:
entity_id: switch.receiver_on
turn_off:
service: switch.turn_on
data_template:
entity_id: switch.receiver_off
volume_up:
service: switch.turn_on
data_template:
entity_id: switch.volume_up
volume_down:
service: switch.turn_on
data_template:
entity_id: switch.vol
input_templates:
source 1:
service: input_boolean.turn_on
data_template:
entity_id: input_boolean.source_1
source 2:
service: input_boolean.turn_on
data_template:
entity_id: input_boolean.source_2
@@ -0,0 +1,7 @@
# all the packages!
This is really cool :)
- A list item!
<<more thisngs!>>
@@ -0,0 +1,7 @@
# all the packages!
This is really cool :)
- A list item!
<<more thisngs!>>
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,30 @@
# Loads default set of integrations. Do not remove.
default_config:
# Text to speech
tts:
- platform: google_translate
# automation manual: !include_dir_list ./automations/include_dir_list
# automation ui: !include automations/ui.yaml
# automation: !include automations/base.yaml
# automation cools: !include_dir_merge_list automations/include_dir_merge_list
script: !include scripts.yaml
scene: !include scenes.yaml
automation:
- alias: inline-auto
description: Example package auto
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
homeassistant:
packages: !include packages.yaml
+16
View File
@@ -0,0 +1,16 @@
ha: !include packages/ha.yaml
sub: !include_dir_merge_named packages/sub
secret_ones:
automation:
- alias: package ha
description: Example package auto
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
@@ -0,0 +1 @@
automation: !include ../automations/ui.yaml
@@ -0,0 +1,7 @@
# all the packages!
This is really cool :)
- A list item!
<<more thisngs!>>
@@ -0,0 +1,13 @@
automation:
- alias: package ha
description: Example package auto
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,2 @@
homeassistant:
packages: !include_dir_named integrations
Whitespace-only changes.
@@ -0,0 +1 @@
automation: !include ../automations.yaml
@@ -0,0 +1 @@
media_player: !include_dir_list ../entities/media_players
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,2 @@
homeassistant:
packages: !include_dir_named integrations
@@ -0,0 +1 @@
automation: !include ../automations.yaml
@@ -0,0 +1 @@
# media_player: !include_dir_list ../entities/media_players
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,2 @@
homeassistant:
packages: !include_dir_named integrations
@@ -0,0 +1 @@
automation: !include ../automations.yaml
@@ -0,0 +1 @@
media_player:
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,2 @@
homeassistant:
packages: !include_dir_named integrations
@@ -0,0 +1 @@
- platform: media
@@ -0,0 +1 @@
automation: !include ../automations.yaml
@@ -0,0 +1,16 @@
- platform: ping
host: 192.168.0.119
name: "Ping Pc Tv"
scan_interval: 10
- platform: ping
host: 192.168.0.181
name: "Ping Living Room Tv"
scan_interval: 10
- platform: ping
host: 192.168.0.100
name: "Ping Printer"
scan_interval: 15
- platform: ping
host: 192.168.0.177
name: "Ping Broadlink"
scan_interval: 15
@@ -0,0 +1 @@
media_player: !include_dir_list ../entities/media_players
+6 -41
View File
@@ -1,27 +1,13 @@
from pathlib import Path
from unittest import TestCase
import yaml import yaml
from fastapi.testclient import TestClient
from src.api.app import make_app
from src.automations.types import Automation, ExtenededAutomation from src.automations.types import Automation, ExtenededAutomation
from tests.utils import ( from tests.utils import (
HA_CONFIG2_EXAMPLE, HA_CONFIG2_EXAMPLE,
HA_CONFIG6_EXAMPLE, HA_CONFIG6_EXAMPLE,
HA_CONFIG10_EXAMPLE, HA_CONFIG10_EXAMPLE,
get_example_automation_loader,
) )
from .util import BaseTestCase
class BaseTestCase(TestCase):
def setUp(self) -> None:
(
self.config_folder,
self.hass_config,
self.automation_loader,
) = get_example_automation_loader()
self.client = TestClient(make_app(self.automation_loader))
class automation_pagination_tests(BaseTestCase): class automation_pagination_tests(BaseTestCase):
@@ -90,20 +76,13 @@ class automation_pagination_tests(BaseTestCase):
class automation_pagination_tests_2(automation_pagination_tests): class automation_pagination_tests_2(automation_pagination_tests):
source_config_path = HA_CONFIG2_EXAMPLE
test_params = { test_params = {
"total": 1, "total": 1,
"subtest2_found_items": 0, "subtest2_found_items": 0,
"subtest1_found_items": 1, "subtest1_found_items": 1,
} }
def setUp(self) -> None:
(
self.config_folder,
self.hass_config,
self.automation_loader,
) = get_example_automation_loader(HA_CONFIG2_EXAMPLE)
self.client = TestClient(make_app(self.automation_loader))
class automation_update_tests(BaseTestCase): class automation_update_tests(BaseTestCase):
test_params = { test_params = {
@@ -270,7 +249,7 @@ class automation_update_tests(BaseTestCase):
) )
autos = resp.json()["data"] autos = resp.json()["data"]
self.assertEqual(resp.json()["totalItems"], self.test_params["total"]) self.assertEqual(resp.json()["totalItems"], self.test_params["total"])
self.assertNotIn("i am new", set([a["id"] for a in autos])) self.assertNotIn("i am new", set([a.get("id", "") for a in autos]))
resp = self.client.post( resp = self.client.post(
"/automations/item", "/automations/item",
json=Automation( json=Automation(
@@ -283,7 +262,7 @@ class automation_update_tests(BaseTestCase):
) )
data = resp.json() data = resp.json()
self.assertEqual(data["totalItems"], self.test_params["total"] + 1) self.assertEqual(data["totalItems"], self.test_params["total"] + 1)
self.assertIn("i am new", set([a["id"] for a in data["data"]])) self.assertIn("i am new", set([a.get("id", "") for a in data["data"]]))
def test_update_some(self): def test_update_some(self):
resp = self.client.post( resp = self.client.post(
@@ -350,6 +329,7 @@ class automation_update_tests(BaseTestCase):
class automation_update_split_config_tests(automation_update_tests): class automation_update_split_config_tests(automation_update_tests):
source_config_path = HA_CONFIG6_EXAMPLE
test_params = { test_params = {
"total": 12, "total": 12,
"modify_item": 3, "modify_item": 3,
@@ -378,30 +358,15 @@ class automation_update_split_config_tests(automation_update_tests):
}, },
} }
def setUp(self) -> None:
(
self.config_folder,
self.hass_config,
self.automation_loader,
) = get_example_automation_loader(HA_CONFIG6_EXAMPLE)
self.client = TestClient(make_app(self.automation_loader))
class automation_update_split_config_and_inline_config_tests(automation_update_tests): class automation_update_split_config_and_inline_config_tests(automation_update_tests):
source_config_path = HA_CONFIG10_EXAMPLE
test_params = { test_params = {
"total": 4, "total": 4,
"modify_item": 0, "modify_item": 0,
"consitency_tests": {}, "consitency_tests": {},
} }
def setUp(self) -> None:
(
self.config_folder,
self.hass_config,
self.automation_loader,
) = get_example_automation_loader(HA_CONFIG10_EXAMPLE)
self.client = TestClient(make_app(self.automation_loader))
class automation_delete_tests(BaseTestCase): class automation_delete_tests(BaseTestCase):
def test_delete_some(self): def test_delete_some(self):
+27
View File
@@ -0,0 +1,27 @@
from tests.unittests.api.util import BaseTestCase
class user_profile_tests(BaseTestCase):
def test_read_empty_profile(self):
resp = self.client.get("/details/profile")
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.json()["theme"], "dark")
self.assertEqual(resp.json()["lang"], "eng")
def test_update_profile(self):
resp = self.client.put("/details/profile", json={"theme": "light", "lang": "fra"})
self.assertEqual(resp.status_code, 200)
resp = self.client.get("/details/profile")
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.json()["theme"], "light")
self.assertEqual(resp.json()["lang"], "fra")
def test_update_invalid_profile(self):
resp = self.client.put("/details/profile", json={"theme": "creamy", "lang": "fra"})
self.assertEqual(resp.status_code, 422)
resp = self.client.get("/details/profile")
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.json()["theme"], "dark")
self.assertEqual(resp.json()["lang"], "eng")
+19
View File
@@ -0,0 +1,19 @@
from unittest import TestCase
from fastapi.testclient import TestClient
from src.api.app import make_app
from tests.utils import HA_CONFIG_EXAMPLE, get_example_automation_loader
class BaseTestCase(TestCase):
source_config_path = HA_CONFIG_EXAMPLE
def setUp(self) -> None:
(
self.config_folder,
self.hass_config,
self.automation_loader,
) = get_example_automation_loader(config_to_copy=self.source_config_path)
self.client = TestClient(make_app(self.hass_config))
+3 -14
View File
@@ -1,23 +1,12 @@
from pathlib import Path from pathlib import Path
from src.automations.errors import DBDataError from src.automations.errors import DBDataError, RepeatedAutomationId
from src.automations.types import ExtenededAutomation from src.automations.types import ExtenededAutomation
from .utils import TestWithDB from .utils import TestWithDB
class db_tests(TestWithDB): class db_tests(TestWithDB):
def test_db_creation(self):
with self.db.get_cur() as cur:
cur.execute("SELECT name FROM sqlite_master WHERE type ='table'")
tables = cur.fetchall()
self.assertListEqual(tables, [("autos",)])
self.db.create_db()
with self.db.get_cur() as cur:
cur.execute("SELECT name FROM sqlite_master WHERE type ='table'")
tables = cur.fetchall()
self.assertListEqual(tables, [("autos",)])
def test_insert_automations(self): def test_insert_automations(self):
originals = [ originals = [
ExtenededAutomation( ExtenededAutomation(
@@ -61,7 +50,7 @@ class db_tests(TestWithDB):
configuration_key=["automation"], configuration_key=["automation"],
), ),
] ]
with self.assertRaises(DBDataError) as err: with self.assertRaises(RepeatedAutomationId):
self.db.insert_automations(originals) self.db.insert_automations(originals)
autos = list(self.db.list_automations(0, 10)) autos = list(self.db.list_automations(0, 10))
self.assertEqual(len(autos), 0) self.assertEqual(len(autos), 1)
@@ -21,6 +21,11 @@ from tests.utils import (
HA_CONFIG10_EXAMPLE, HA_CONFIG10_EXAMPLE,
HA_CONFIG11_EXAMPLE, HA_CONFIG11_EXAMPLE,
HA_CONFIG12_EXAMPLE, HA_CONFIG12_EXAMPLE,
HA_CONFIG13_EXAMPLE,
HA_CONFIG14_EXAMPLE,
HA_CONFIG15_EXAMPLE,
HA_CONFIG16_EXAMPLE,
HA_CONFIG17_EXAMPLE,
HA_CONFIG_EXAMPLE, HA_CONFIG_EXAMPLE,
) )
@@ -160,6 +165,11 @@ class loader_tests(TestCase):
(HA_CONFIG10_EXAMPLE, 3), (HA_CONFIG10_EXAMPLE, 3),
(HA_CONFIG11_EXAMPLE, 3), (HA_CONFIG11_EXAMPLE, 3),
(HA_CONFIG12_EXAMPLE, 4), (HA_CONFIG12_EXAMPLE, 4),
(HA_CONFIG13_EXAMPLE, 4),
(HA_CONFIG14_EXAMPLE, 1),
(HA_CONFIG15_EXAMPLE, 1),
(HA_CONFIG16_EXAMPLE, 1),
(HA_CONFIG17_EXAMPLE, 1),
]: ]:
with self.subTest(config_name=ha_path.name, expected=expected): with self.subTest(config_name=ha_path.name, expected=expected):
hass_config = HassConfig(ha_path) hass_config = HassConfig(ha_path)
@@ -28,7 +28,6 @@ class manager_tests(TestWithDB):
self.config_path = create_copy_of_example_config(ha_config_example) self.config_path = create_copy_of_example_config(ha_config_example)
self.automation_manager = AutomationManager( self.automation_manager = AutomationManager(
HassConfig(self.config_path), HassConfig(self.config_path),
self.db_file,
) )
return self.config_path, self.automation_manager return self.config_path, self.automation_manager
@@ -54,10 +53,6 @@ class manager_tests(TestWithDB):
{"platform": "zone", "entity_id": "person.thor", "zone": "zone.azguard"} {"platform": "zone", "entity_id": "person.thor", "zone": "zone.azguard"}
) )
automation_manager.update(automation) automation_manager.update(automation)
self.assertEqual(
automation_manager.get("sublist3-mlist2").trigger,
[],
)
automation_manager.reload() automation_manager.reload()
self.assertEqual( self.assertEqual(
automation_manager.get("sublist3-mlist2").trigger, automation_manager.get("sublist3-mlist2").trigger,
+1 -12
View File
@@ -1,19 +1,8 @@
from pathlib import Path
from tempfile import mktemp
from unittest import TestCase from unittest import TestCase
from src.automations.db import AutomationDBConnection from src.automations.db import AutomationDBConnection
def make_temp_db():
return AutomationDBConnection(Path(mktemp() + ".db"))
class TestWithDB(TestCase): class TestWithDB(TestCase):
def setUp(self) -> None: def setUp(self) -> None:
self.db = make_temp_db() self.db = AutomationDBConnection()
self.db.create_db()
self.db_file = self.db.db_file
def tearDown(self) -> None:
self.db_file.unlink()
@@ -65,6 +65,52 @@ class dumping_yamls_tests(TestCase):
}, },
) )
def test_load_template_in_yaml(self):
yaml_obj = load_yaml(
io.StringIO(
"""
- id: '1652069225859'
alias: 'Lower the volume'
description: ''
mode: single
trigger:
- platform: state
entity_id: input_number.preferred_temperature
condition: []
action:
- service: media_player.volume_set
data_template:
entity_id: media_player.denon_avr_x2500h
volume_level: '{{ ((states(''input_number.volume_video'')|int)+80)/100 }}'
"""
),
Path.cwd(),
)
self.assertIsInstance(yaml_obj, list)
self.assertEqual(len(yaml_obj), 1)
self.assertDictEqual(
dict(yaml_obj[0]),
{
"id": "1652069225859",
"alias": "Lower the volume",
"description": "",
"mode": "single",
"trigger": [
{"platform": "state", "entity_id": "input_number.preferred_temperature"}
],
"condition": [],
"action": [
{
"service": "media_player.volume_set",
"data_template": {
"entity_id": "media_player.denon_avr_x2500h",
"volume_level": "{{ ((states('input_number.volume_video')|int)+80)/100 }}",
},
}
],
},
)
def test_load_stub(self): def test_load_stub(self):
yaml_obj = load_yaml( yaml_obj = load_yaml(
io.StringIO( io.StringIO(
+5
View File
@@ -22,6 +22,11 @@ HA_CONFIG9_EXAMPLE = SAMPLES_FOLDER / "config-9"
HA_CONFIG10_EXAMPLE = SAMPLES_FOLDER / "config-10" HA_CONFIG10_EXAMPLE = SAMPLES_FOLDER / "config-10"
HA_CONFIG11_EXAMPLE = SAMPLES_FOLDER / "config-11" HA_CONFIG11_EXAMPLE = SAMPLES_FOLDER / "config-11"
HA_CONFIG12_EXAMPLE = SAMPLES_FOLDER / "config-12" HA_CONFIG12_EXAMPLE = SAMPLES_FOLDER / "config-12"
HA_CONFIG13_EXAMPLE = SAMPLES_FOLDER / "config-13"
HA_CONFIG14_EXAMPLE = SAMPLES_FOLDER / "config-14"
HA_CONFIG15_EXAMPLE = SAMPLES_FOLDER / "config-15"
HA_CONFIG16_EXAMPLE = SAMPLES_FOLDER / "config-16"
HA_CONFIG17_EXAMPLE = SAMPLES_FOLDER / "config-17"
def get_example_automation_loader( def get_example_automation_loader(
+2 -2
View File
@@ -1,7 +1,7 @@
name: Shortumation name: Shortumation
version: v0.6.2 version: v0.7.4
slug: shortumation slug: shortumation
image: asosnovsky/shortumation-{arch} image: "asosnovsky/shortumation-{arch}"
url: "https://github.com/asosnovsky/Shortumation" url: "https://github.com/asosnovsky/Shortumation"
description: "A homeassitant addon which provides better UI for automations & scripts." description: "A homeassitant addon which provides better UI for automations & scripts."
arch: arch:
+2
View File
@@ -8,8 +8,10 @@ host_port="$host:$port"
pushd $api_location pushd $api_location
echo "--------------------" echo "--------------------"
echo "BUILD_VERSION = "$BUILD_VERSION echo "BUILD_VERSION = "$BUILD_VERSION
echo "ARCH = "$BUILD_ARCH
echo "HOST = $host_port" echo "HOST = $host_port"
echo "HASSIO_WS = $HASSIO_WS" echo "HASSIO_WS = $HASSIO_WS"
echo $(uname -a)
echo $(python --version) echo $(python --version)
echo "--------------------" echo "--------------------"
python -m hypercorn src.app:app -b $host_port --config /app/hypercorn.toml python -m hypercorn src.app:app -b $host_port --config /app/hypercorn.toml
+2 -2
View File
@@ -9,9 +9,9 @@
"@mui/icons-material": "5.8.4", "@mui/icons-material": "5.8.4",
"@mui/material": "5.8.6", "@mui/material": "5.8.6",
"@mui/styles": "5.8.6", "@mui/styles": "5.8.6",
"@types/jest": "28.1.6", "@types/jest": "28.1.8",
"@types/node": "17.0.36", "@types/node": "17.0.36",
"@types/react": "18.0.15", "@types/react": "18.0.18",
"@types/react-dom": "18.0.6", "@types/react-dom": "18.0.6",
"@types/ws": "8.5.3", "@types/ws": "8.5.3",
"@uiw/react-codemirror": "4.10.4", "@uiw/react-codemirror": "4.10.4",
+7 -10
View File
@@ -1,14 +1,18 @@
import "./App.css"; import "./App.css";
import { Routes, Route, BrowserRouter } from "react-router-dom"; import { Routes, Route, BrowserRouter } from "react-router-dom";
import { AutomationRoute } from "routes/automation"; import { AutomationRoute } from "routes/automation";
import { useConnectedApiService } from "apiService"; import { useConnectedApiService } from "services/api";
import { ErrorBoundary } from "components/ErrorBoundary"; import { ErrorBoundary } from "components/ErrorBoundary";
import { CookiesProvider } from "react-cookie"; import { CookiesProvider } from "react-cookie";
import { Page } from "components/Page"; import { Page } from "components/Page";
const ConnectedAutomationRoute = () => { const ConnectedAutomationRoute = () => {
const api = useConnectedApiService(); const api = useConnectedApiService();
return <AutomationRoute api={api} />; return (
<Page api={api}>
<AutomationRoute api={api} />
</Page>
);
}; };
function App() { function App() {
@@ -18,14 +22,7 @@ function App() {
<CookiesProvider> <CookiesProvider>
<BrowserRouter> <BrowserRouter>
<Routes> <Routes>
<Route <Route path="*" element={<ConnectedAutomationRoute />} />
path="*"
element={
<Page>
<ConnectedAutomationRoute />
</Page>
}
/>
</Routes> </Routes>
</BrowserRouter> </BrowserRouter>
</CookiesProvider> </CookiesProvider>
-28
View File
@@ -1,28 +0,0 @@
import { useEffect } from "react";
import { useDefaultApiState, makeReloadAutomations } from "./util";
import { AutomationAPI } from "./automations";
export type ApiService = ReturnType<typeof useAPIService>;
export const useAPIService = (automationAPI: AutomationAPI) => {
// state
const [state, setState] = useDefaultApiState();
const { reload, wrapCall } = makeReloadAutomations(
automationAPI,
state,
setState
);
// initial load of autos
useEffect(() => {
reload();
// eslint-disable-next-line
}, []);
return {
state,
removeAutomation: wrapCall(automationAPI.remove),
updateAutomation: wrapCall(automationAPI.update),
createAutomation: wrapCall(automationAPI.create),
updateTags: wrapCall(automationAPI.updateTags),
};
};
-40
View File
@@ -1,40 +0,0 @@
import { useState } from "react";
import { ApiState } from "./types";
import { AutomationAPI } from "./automations";
export const useDefaultApiState = () =>
useState<ApiState>({
automations: { ready: false },
});
export const makeReloadAutomations = (
automationAPI: AutomationAPI,
state: ApiState,
setState: (s: ApiState) => void
) => {
const reload = async () => {
let params = { offset: 0, limit: 10000 };
if (state.automations.ready && state.automations.ok) {
params = state.automations.data.params;
}
const resp = await automationAPI.list(params);
setState({
...state,
automations: {
ready: true,
...resp,
},
});
};
const wrapCall = <Call extends (a: any) => Promise<any>>(fcn: Call) => {
return async (args: Parameters<Call>[0]) => {
const resp = await fcn(args);
await reload();
return resp as ReturnType<Call>;
};
};
return {
reload,
wrapCall,
};
};
@@ -14,7 +14,7 @@ const { componentMeta, make } = makeStory({
}) => { }) => {
const [[metadata, tags], setState] = useState([args.metadata, args.tags]); const [[metadata, tags], setState] = useState([args.metadata, args.tags]);
const tagDB = useTagDB( const tagDB = useTagDB(
[{ id: metadata.id, tags: Object.fromEntries(tags) }], metadata.id ? [{ id: metadata.id, tags: Object.fromEntries(tags) }] : [],
(_, t) => setState([metadata, Object.entries(t)]) (_, t) => setState([metadata, Object.entries(t)])
); );
@@ -10,6 +10,7 @@ import { AddIcon, TrashIcon } from "components/Icons";
import InputAutoText from "components/Inputs/InputAutoText"; import InputAutoText from "components/Inputs/InputAutoText";
import { TagDB } from "components/AutomationManager/TagDB"; import { TagDB } from "components/AutomationManager/TagDB";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "services/lang";
export interface AutoInfoBoxProps { export interface AutoInfoBoxProps {
metadata: AutomationMetadata & Partial<AutomationShortumationMetadata>; metadata: AutomationMetadata & Partial<AutomationShortumationMetadata>;
@@ -26,6 +27,7 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
tagDB, tagDB,
}) => { }) => {
// state // state
const langStore = useLang();
const [newTag, setNewTag] = useState<[string, string]>(["", ""]); const [newTag, setNewTag] = useState<[string, string]>(["", ""]);
const [[errorIndex, error], _setError] = useState<[number | "new", string]>([ const [[errorIndex, error], _setError] = useState<[number | "new", string]>([
-1, -1,
@@ -54,12 +56,12 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
); );
const validTagName = (newName: string): string | undefined => { const validTagName = (newName: string): string | undefined => {
if (newName.length <= 0) { if (newName.length <= 0) {
return "Name must be at least 1 character long"; return langStore.get("VALIDATION_AUTOMATION_NAME");
} }
// eslint-disable-next-line // eslint-disable-next-line
for (const [name, _] of tags) { for (const [name, _] of tags) {
if (name.trim() === newName.trim()) { if (name.trim() === newName.trim()) {
return `The tag '${name}' already exists`; return langStore.get("VALIDATION_TAG_EXISTS", { name });
} }
} }
}; };
@@ -101,42 +103,42 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
<div className="automation-editor--info-box"> <div className="automation-editor--info-box">
<div className="automation-editor--info-box-inner"> <div className="automation-editor--info-box-inner">
<InputText <InputText
label="ID" label={langStore.get("ID")}
value={metadata.id} value={metadata.id ?? langStore.get("N/A")}
onChange={onUpdateMetadata("id")} onChange={onUpdateMetadata("id")}
/> />
<InputText <InputText
label="Name" label={langStore.get("NAME")}
value={metadata.alias ?? ""} value={metadata.alias ?? ""}
onChange={onUpdateMetadata("alias")} onChange={onUpdateMetadata("alias")}
/> />
<InputText <InputText
multiline multiline
label="Description" label={langStore.get("DESCRIPTION")}
value={metadata.description ?? ""} value={metadata.description ?? ""}
onChange={onUpdateMetadata("description")} onChange={onUpdateMetadata("description")}
/> />
<InputList <InputList
label="Mode" label={langStore.get("MODE")}
current={metadata.mode} current={metadata.mode}
onChange={onUpdateMetadata("mode")} onChange={onUpdateMetadata("mode")}
options={["parallel", "single", "queued", "restart"]} options={["parallel", "single", "queued", "restart"]}
/> />
<div className="automation-editor--info-box--tags"> <div className="automation-editor--info-box--tags">
<h1>Tags</h1> <h1>{langStore.get("TAGS")}</h1>
<div className="automation-editor--info-box--tag-list"> <div className="automation-editor--info-box--tag-list">
{tags.map(([tagName, tagValue], tagIndex) => ( {tags.map(([tagName, tagValue], tagIndex) => (
<div key={tagIndex} className="automation-editor--info-box--tag"> <div key={tagIndex} className="automation-editor--info-box--tag">
<InputAutoText <InputAutoText
value={tagName} value={tagName}
label="Name" label={langStore.get("NAME")}
onChange={(v) => updateTagName(v, tagIndex)} onChange={(v) => updateTagName(v, tagIndex)}
options={foundNewTagNames} options={foundNewTagNames}
error={errorIndex === tagIndex ? error : undefined} error={errorIndex === tagIndex ? error : undefined}
/> />
<InputAutoText <InputAutoText
value={tagValue} value={tagValue}
label="Tag" label={langStore.get("TAG")}
onChange={(v) => onUpdateTags(v, tagIndex)} onChange={(v) => onUpdateTags(v, tagIndex)}
options={tagDB.getTagValues(tagName)} options={tagDB.getTagValues(tagName)}
error={errorIndex === tagIndex ? error : undefined} error={errorIndex === tagIndex ? error : undefined}
@@ -153,14 +155,14 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
<div className="automation-editor--info-box--tag"> <div className="automation-editor--info-box--tag">
<InputAutoText <InputAutoText
value={newTag[0]} value={newTag[0]}
label="Name" label={langStore.get("NAME")}
onChange={(v) => setNewTag([v, newTag[1]])} onChange={(v) => setNewTag([v, newTag[1]])}
options={foundNewTagNames} options={foundNewTagNames}
error={errorIndex === "new" ? error : undefined} error={errorIndex === "new" ? error : undefined}
/> />
<InputAutoText <InputAutoText
value={newTag[1]} value={newTag[1]}
label="Tag" label={langStore.get("TAG")}
onChange={(v) => setNewTag([newTag[0], v])} onChange={(v) => setNewTag([newTag[0], v])}
options={tagDB.getTagValues(newTag[0])} options={tagDB.getTagValues(newTag[0])}
error={errorIndex === "new" ? error : undefined} error={errorIndex === "new" ? error : undefined}
@@ -1,7 +1,7 @@
import "./index.css"; import "./index.css";
import { AutomationNode, AutomationNodeMapping } from "types/automations"; import { AutomationNode, AutomationNodeMapping } from "types/automations";
import { useHA } from "haService"; import { useHA } from "services/ha";
import { CollectionNodeElement } from "components/DAGGraph/nodes/CollectionNode/CollectionNodeElement"; import { CollectionNodeElement } from "components/DAGGraph/nodes/CollectionNode/CollectionNodeElement";
import { getDescriptionFromAutomationNode } from "utils/formatting"; import { getDescriptionFromAutomationNode } from "utils/formatting";
import { Size } from "components/DAGGraph/elements/types"; import { Size } from "components/DAGGraph/elements/types";
@@ -1,27 +1,25 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { AutomationEditor } from "./index"; import { AutomationEditor } from "./index";
import { useState } from "react"; import { useState } from "react";
import { Page } from "components/Page";
import { useTagDB } from "components/AutomationManager/TagDB"; import { useTagDB } from "components/AutomationManager/TagDB";
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants"; import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
export default { import { makeStory } from "devUtils";
title: "App/AutomationEditor",
component: AutomationEditor,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
dims: DEFAULT_DIMS,
},
} as ComponentMeta<typeof AutomationEditor>;
const Template: ComponentStory<typeof AutomationEditor> = (args) => { const { make, componentMeta } = makeStory({
const [state, setState] = useState(args.automation); Component: AutomationEditor,
return ( meta: {
<Page> title: "App/AutomationEditor",
args: {
dims: DEFAULT_DIMS,
},
},
BaseTemplate: (args) => {
const [state, setState] = useState(args.automation);
return (
<AutomationEditor <AutomationEditor
{...args} {...args}
tagDB={useTagDB( tagDB={useTagDB(
state ? [{ id: state.id, tags: state.tags }] : [], state && state.id ? [{ id: state.id, tags: state.tags }] : [],
() => {} () => {}
)} )}
automation={state} automation={state}
@@ -29,15 +27,15 @@ const Template: ComponentStory<typeof AutomationEditor> = (args) => {
window.setTimeout(() => setState(s), 3000); window.setTimeout(() => setState(s), 3000);
}} }}
/> />
</Page> );
); },
}; });
export const Loading = Template.bind({}); export default componentMeta;
export const Simple = Template.bind({}); export const Loading = make({});
Simple.args = {
...Simple.args, export const Simple = make({
automation: { automation: {
condition: [], condition: [],
tags: { tags: {
@@ -94,11 +92,9 @@ Simple.args = {
}, },
], ],
}, },
}; });
export const EmptyStart = Template.bind({}); export const EmptyStart = make({
EmptyStart.args = {
...EmptyStart.args,
automation: { automation: {
condition: [], condition: [],
tags: {}, tags: {},
@@ -115,22 +111,18 @@ EmptyStart.args = {
trigger: [], trigger: [],
action: [], action: [],
}, },
}; });
export const BadAutomationInvalidMetadata = Template.bind({}); export const BadAutomationInvalidMetadata = make({
BadAutomationInvalidMetadata.args = {
...BadAutomationInvalidMetadata.args,
automation: { automation: {
condition: [], condition: [],
tags: {}, tags: {},
trigger: [], trigger: [],
action: [], action: [],
} as any, } as any,
}; });
export const BadAutomationInvalidTriggers = Template.bind({}); export const BadAutomationInvalidTriggers = make({
BadAutomationInvalidTriggers.args = {
...BadAutomationInvalidTriggers.args,
automation: { automation: {
condition: [], condition: [],
tags: {}, tags: {},
@@ -147,11 +139,9 @@ BadAutomationInvalidTriggers.args = {
trigger: ["haha I am a string"] as any, trigger: ["haha I am a string"] as any,
action: [], action: [],
}, },
}; });
export const BadAutomationInvalidSequence = Template.bind({}); export const BadAutomationInvalidSequence = make({
BadAutomationInvalidSequence.args = {
...BadAutomationInvalidSequence.args,
automation: { automation: {
condition: [], condition: [],
tags: {}, tags: {},
@@ -165,14 +155,12 @@ BadAutomationInvalidSequence.args = {
action: [ action: [
{ {
choose: {}, choose: {},
}, } as any,
], ],
} as any, } as any,
}; });
export const RepeatExample = Template.bind({}); export const RepeatExample = make({
RepeatExample.args = {
...RepeatExample.args,
automation: { automation: {
id: "1654976151462", id: "1654976151462",
alias: "Get out of baby room", alias: "Get out of baby room",
@@ -243,4 +231,4 @@ RepeatExample.args = {
], ],
tags: {}, tags: {},
}, },
}; });
@@ -31,6 +31,9 @@ import { MiniFailure } from "types/validators/helper";
import { AutoInfoBox } from "./AutoInfoBox"; import { AutoInfoBox } from "./AutoInfoBox";
import { useAutomatioEditorState, EditorData } from "./state"; import { useAutomatioEditorState, EditorData } from "./state";
import { useLang } from "services/lang";
import { useSnackbar } from "notistack";
import { Alert } from "@mui/material";
interface Props { interface Props {
automation?: AutomationData | BareAutomationData; automation?: AutomationData | BareAutomationData;
@@ -40,6 +43,8 @@ interface Props {
onDelete: () => void; onDelete: () => void;
tagDB: TagDB; tagDB: TagDB;
isNew?: boolean; isNew?: boolean;
readonly: boolean;
issue?: string;
} }
export const AutomationEditor: FC<Props> = ({ export const AutomationEditor: FC<Props> = ({
dims, dims,
@@ -48,9 +53,12 @@ export const AutomationEditor: FC<Props> = ({
onDelete, onDelete,
onTrigger, onTrigger,
tagDB, tagDB,
isNew, readonly,
issue,
}) => { }) => {
// state // state
const langStore = useLang();
const snackbr = useSnackbar();
const { const {
state, state,
updateSequence, updateSequence,
@@ -61,7 +69,15 @@ export const AutomationEditor: FC<Props> = ({
save, save,
saveAndUpdate, saveAndUpdate,
undo, undo,
} = useAutomatioEditorState(propsAutos, propsOnUpdate); } = useAutomatioEditorState(propsAutos, (auto) => {
if (readonly) {
snackbr.enqueueSnackbar(langStore.get("READONLY_CANNOT_UPDATE"), {
color: "warning",
});
} else {
propsOnUpdate(auto);
}
});
const [infoBoxOpen, setInfoBox] = useState(false); const [infoBoxOpen, setInfoBox] = useState(false);
const [ const [
{ ckFlipped }, { ckFlipped },
@@ -93,7 +109,13 @@ export const AutomationEditor: FC<Props> = ({
); );
} }
return ( return (
<div className={["automation-editor", state.status].join(" ")}> <div
className={[
"automation-editor",
state.status,
readonly ? "readonly" : "",
].join(" ")}
>
{state.status === "saving" && ( {state.status === "saving" && (
<LinearProgress className="linear-loader" /> <LinearProgress className="linear-loader" />
)} )}
@@ -110,13 +132,15 @@ export const AutomationEditor: FC<Props> = ({
state.status, state.status,
].join(" ")} ].join(" ")}
> >
<Button onClick={() => setInfoBox(false)}>Close</Button> <Button onClick={() => setInfoBox(false)}>
{langStore.get("CLOSE")}
</Button>
<Button <Button
className={"automation-editor--flow-wrapper--toolbar--save-btn"} className={"automation-editor--flow-wrapper--toolbar--save-btn"}
onClick={save} onClick={save}
disabled={state.status !== "changed"} disabled={state.status !== "changed" || readonly}
> >
Save <CheckMarkIcon color="#bf4" /> {langStore.get("SAVE")} <CheckMarkIcon color="#bf4" />
</Button> </Button>
</div> </div>
</AutoInfoBox> </AutoInfoBox>
@@ -131,7 +155,7 @@ export const AutomationEditor: FC<Props> = ({
<div className="id">{state.data.id}</div> <div className="id">{state.data.id}</div>
<InputTextView <InputTextView
value={state.data.alias ?? ""} value={state.data.alias ?? ""}
placeholder="Name" placeholder={langStore.get("NAME")}
onChange={(alias) => onChange={(alias) =>
updateMetadata( updateMetadata(
{ {
@@ -145,7 +169,7 @@ export const AutomationEditor: FC<Props> = ({
</span> </span>
<InputList <InputList
fullWidth={false} fullWidth={false}
label="Mode" label={langStore.get("MODE")}
className="automation-editor--flow-wrapper--toolbar--modes" className="automation-editor--flow-wrapper--toolbar--modes"
current={{ current={{
id: state.data.mode, id: state.data.mode,
@@ -165,28 +189,26 @@ export const AutomationEditor: FC<Props> = ({
options={[ options={[
{ {
id: "single", id: "single",
label: "Do not start a new run. Issue a warning.", label: langStore.get("MODE_SIGNLE_LABEL"),
}, },
{ {
id: "parallel", id: "parallel",
label: label: langStore.get("MODE_SIGNLE_PARALLEL"),
"Start a new, independent run in parallel with previous runs.",
}, },
{ {
id: "queued", id: "queued",
label: label: langStore.get("MODE_SIGNLE_QUEUED"),
"Start a new run after all previous runs complete. Runs are guaranteed to execute in the order they were queued.",
}, },
{ {
id: "restart", id: "restart",
label: "Start a new run after first stopping previous run.", label: langStore.get("MODE_SIGNLE_RESTART"),
}, },
]} ]}
/> />
<InputTextView <InputTextView
className="description" className="description"
value={state.data.description ?? ""} value={state.data.description ?? ""}
placeholder="Description" placeholder={langStore.get("DESCRIPTION")}
onChange={(description) => onChange={(description) =>
updateMetadata( updateMetadata(
{ {
@@ -204,7 +226,7 @@ export const AutomationEditor: FC<Props> = ({
onClick={() => setFlipped(!flipped)} onClick={() => setFlipped(!flipped)}
> >
<Icon>{flipped ? "flip_to_front" : "flip_to_back"}</Icon> <Icon>{flipped ? "flip_to_front" : "flip_to_back"}</Icon>
Flip {langStore.get("FLIPP")}
</Button> </Button>
)} )}
{state.status === "changed" && ( {state.status === "changed" && (
@@ -217,9 +239,14 @@ export const AutomationEditor: FC<Props> = ({
onClick={save} onClick={save}
disabled={state.status !== "changed"} disabled={state.status !== "changed"}
> >
Save <CheckMarkIcon color="#bf4" /> {langStore.get("SAVE")} <CheckMarkIcon color="#bf4" />
</Button> </Button>
</div> </div>
{readonly && (
<Alert color="warning">
{langStore.get("READONLY_MODE")} - {issue}
</Alert>
)}
<DAGAutomationGraph <DAGAutomationGraph
action={state.data.action} action={state.data.action}
trigger={state.data.trigger} trigger={state.data.trigger}
@@ -242,26 +269,26 @@ export const AutomationEditor: FC<Props> = ({
// tooltipOpen // tooltipOpen
sx={{ pointerEvents: "auto" }} sx={{ pointerEvents: "auto" }}
icon={<RunIcon />} icon={<RunIcon />}
tooltipTitle={"Trigger"} tooltipTitle={langStore.get("TRIGGER")}
onClick={onTrigger} onClick={onTrigger}
/> />
<SpeedDialAction <SpeedDialAction
// tooltipOpen // tooltipOpen
icon={<DeleteIcon />} icon={<DeleteIcon />}
tooltipTitle={"Delete"} tooltipTitle={langStore.get("DELETE")}
onClick={onDelete} onClick={onDelete}
/> />
<SpeedDialAction <SpeedDialAction
// tooltipOpen // tooltipOpen
icon={<EditIcon />} icon={<EditIcon />}
tooltipTitle={"Metadata"} tooltipTitle={langStore.get("METADATA")}
onClick={() => setInfoBox(!infoBoxOpen)} onClick={() => setInfoBox(!infoBoxOpen)}
/> />
{state.status === "changed" && ( {state.status === "changed" && (
<SpeedDialAction <SpeedDialAction
// tooltipOpen // tooltipOpen
icon={<UndoIcon />} icon={<UndoIcon />}
tooltipTitle={"Undo"} tooltipTitle={langStore.get("UNDO")}
onClick={undo} onClick={undo}
/> />
)} )}
@@ -277,6 +304,7 @@ export const ValidationBox: FC<{
data: EditorData; data: EditorData;
onSave: (d: EditorData) => void; onSave: (d: EditorData) => void;
}> = (props) => { }> = (props) => {
const langStore = useLang();
const [{ failures, data }, setState] = useState({ const [{ failures, data }, setState] = useState({
failures: props.failures, failures: props.failures,
data: props.data, data: props.data,
@@ -305,24 +333,20 @@ export const ValidationBox: FC<{
<div className="automation-editor-failures"> <div className="automation-editor-failures">
<ul> <ul>
{failures.map((f, i) => ( {failures.map((f, i) => (
<> <li key={i}>
<li key={i}> <b>{f.path}</b>:
<b>{f.path}</b>: <ul>
<ul> {f.message.map((m, j) => (
{f.message.map((m, j) => ( <li key={j}>{m}</li>
<li key={j}>{m}</li> ))}
))} </ul>
</ul> </li>
</li>
</>
))} ))}
</ul> </ul>
<span> <span>{langStore.get("VALIDATION_PLEASE_CORRECT_FILE")}</span>
Please correct the automation file manually and then continue! <InputYaml label={langStore.get("RAW")} value={data} onChange={onSave} />
</span>
<InputYaml label="Raw" value={data} onChange={onSave} />
<Button disabled={failures.length > 0} onClick={() => props.onSave(data)}> <Button disabled={failures.length > 0} onClick={() => props.onSave(data)}>
Save {langStore.get("SAVE")}
</Button> </Button>
</div> </div>
); );
@@ -23,6 +23,7 @@ const { make, componentMeta } = makeStory({
id: "1", id: "1",
title: "Example", title: "Example",
entityId: "automation.1", entityId: "automation.1",
readonly: false,
description: "Amazing automation!", description: "Amazing automation!",
tags: {}, tags: {},
state: "on", state: "on",
@@ -38,6 +39,7 @@ const { make, componentMeta } = makeStory({
id: "2", id: "2",
title: "Example 2", title: "Example 2",
entityId: "automation.2", entityId: "automation.2",
readonly: false,
description: "Cool!", description: "Cool!",
state: "on", state: "on",
source_file: "automation.yaml", source_file: "automation.yaml",
@@ -89,6 +91,7 @@ export const Nested = make({
entityId: "automation.1", entityId: "automation.1",
description: "", description: "",
title: "Automation #1", title: "Automation #1",
readonly: false,
state: "on", state: "on",
source_file: "automation.yaml", source_file: "automation.yaml",
source_file_type: "list", source_file_type: "list",
@@ -102,6 +105,7 @@ export const Nested = make({
{ {
id: "2", id: "2",
entityId: "automation.2", entityId: "automation.2",
readonly: false,
description: "another one", description: "another one",
title: "Automation #2", title: "Automation #2",
state: "off", state: "off",
@@ -117,6 +121,7 @@ export const Nested = make({
{ {
id: "3", id: "3",
entityId: "automation.3", entityId: "automation.3",
readonly: false,
description: "bad one", description: "bad one",
title: "Automation #3", title: "Automation #3",
state: "offing", state: "offing",
@@ -153,6 +158,7 @@ export const Nested = make({
}, },
data: [ data: [
{ {
readonly: false,
id: "4", id: "4",
entityId: "automation.4", entityId: "automation.4",
description: "Cool thing", description: "Cool thing",
@@ -1,4 +1,5 @@
import { HassEntities } from "home-assistant-js-websocket"; import { HassEntities } from "home-assistant-js-websocket";
import { LangStore, useLang } from "services/lang";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { AutomationData, BareAutomationData } from "types/automations"; import { AutomationData, BareAutomationData } from "types/automations";
import { defaultAutomation } from "utils/defaults"; import { defaultAutomation } from "utils/defaults";
@@ -10,7 +11,8 @@ export const useAutomationDB = (
configAutomations: AutomationData[], configAutomations: AutomationData[],
tagsDB: TagDB tagsDB: TagDB
) => { ) => {
const autoMap = genMapping(haEntities, configAutomations, tagsDB); const langStore = useLang();
const autoMap = genMapping(haEntities, configAutomations, tagsDB, langStore);
const [newAuto, setNewAuto] = const [newAuto, setNewAuto] =
useState< useState<
null | [AutomationManagerAuto, AutomationData | BareAutomationData] null | [AutomationManagerAuto, AutomationData | BareAutomationData]
@@ -50,17 +52,18 @@ export const useAutomationDB = (
const auto = defaultAutomation(String(Date.now())); const auto = defaultAutomation(String(Date.now()));
setNewAuto([ setNewAuto([
{ {
readonly: false,
id: auto.id, id: auto.id,
entityId: "", entityId: "",
title: auto.alias ?? "", title: auto.alias ?? "",
description: auto.description ?? "", description: auto.description ?? "",
state: "unregistered", state: langStore.get("AUTOMATION_STATE_UNREGISTERED"),
tags: {}, tags: {},
issue: "New Automation", issue: langStore.get("NEW_AUTOMATION"),
isNew: true, isNew: true,
source_file: "n/a", source_file: langStore.get("N/A"),
source_file_type: "n/a", source_file_type: langStore.get("N/A"),
configuration_key: ["n/a"], configuration_key: [],
}, },
auto, auto,
]); ]);
@@ -72,15 +75,21 @@ export const useAutomationDB = (
const genMapping = ( const genMapping = (
haEntities: HassEntities, haEntities: HassEntities,
configAutomations: AutomationData[], configAutomations: AutomationData[],
tagsDB: TagDB tagsDB: TagDB,
langStore: LangStore
) => { ) => {
const configData: Record<string, AutomationData> = configAutomations.reduce( const configDataNoId: AutomationData[] = [];
(all, n) => ({ const configData: Record<string, AutomationData & { id: string }> =
...all, configAutomations.reduce((all, n) => {
[n.id]: n, if (n.id) {
}), return {
{} ...all,
); [n.id]: n,
};
}
configDataNoId.push(n);
return all;
}, {});
const automatioinMap: Record< const automatioinMap: Record<
string, string,
[AutomationManagerAuto, AutomationData | null] [AutomationManagerAuto, AutomationData | null]
@@ -88,12 +97,14 @@ const genMapping = (
Object.entries(haEntities) Object.entries(haEntities)
.filter(([entityId, _]) => entityId.toLowerCase().startsWith("automation.")) .filter(([entityId, _]) => entityId.toLowerCase().startsWith("automation."))
.forEach(([entityId, entityData], i) => { .forEach(([entityId, entityData], i) => {
const autoId = entityData.attributes.id ?? `${entityData.state}-${i}`; const autoId = entityData.attributes.id ?? entityId.split(".")[1];
let title = entityData.attributes.friendly_name ?? ""; let title = entityData.attributes.friendly_name ?? "";
let description = ""; let description = "";
let issue: string | undefined = ["on", "off"].includes(entityData.state) let issue: string | undefined = ["on", "off"].includes(entityData.state)
? undefined ? undefined
: `recived invalid state "${entityData.state}, this could be because you have a lingering automation that was not cleared by homeassistant, try to reboot HA or manually clear this automation from HA Database."`; : langStore.get("ISSUES_INVALID_STATE", {
state: entityData.state,
});
let found: AutomationData | null = null; let found: AutomationData | null = null;
let source_file = "n/a"; let source_file = "n/a";
let source_file_type = "n/a"; let source_file_type = "n/a";
@@ -107,7 +118,7 @@ const genMapping = (
configuration_key = found.configuration_key ?? configuration_key; configuration_key = found.configuration_key ?? configuration_key;
delete configData[autoId]; delete configData[autoId];
} else { } else {
issue = "failed to find this automation in '/config' folder"; issue = langStore.get("ISSUES_FIND_AUTOMATION_IN_CONFIG");
} }
automatioinMap[autoId] = [ automatioinMap[autoId] = [
@@ -122,29 +133,74 @@ const genMapping = (
source_file_type, source_file_type,
configuration_key, configuration_key,
issue, issue,
readonly: found == null,
}, },
found, found,
]; ];
}); });
Object.values(configData).forEach((auto) => { Object.values(configData).forEach((auto, i) => {
automatioinMap[auto.id] = [ automatioinMap[auto.id] = [
{ {
id: auto.id, id: auto.id,
entityId: "", entityId: "",
title: auto.alias ?? "", title: auto.alias ?? "",
description: auto.description ?? "", description: auto.description ?? "",
state: "unregistered", state: langStore.get("AUTOMATION_STATE_UNREGISTERED"),
tags: tagsDB.getTags(auto.id), tags: tagsDB.getTags(auto.id),
source_file: auto.source_file, source_file: auto.source_file,
source_file_type: auto.source_file_type, source_file_type: auto.source_file_type,
configuration_key: auto.configuration_key, configuration_key: auto.configuration_key,
issue: issue: langStore.get("ISSUES_NO_LOAD_AUTOMATION"),
"homeassistant did not load this automation, try to manually reload automations or restart homeassistant.", readonly: false,
}, },
auto, auto,
]; ];
}); });
let failedGeneration: number = 0;
configDataNoId.forEach((auto) => {
let generatedAutoId = `automation_${failedGeneration + 1}`;
if (auto.alias) {
generatedAutoId = auto.alias
.toLowerCase()
.replaceAll(/\W/g, " ")
.trim()
.replaceAll(" ", "_");
} else {
failedGeneration += 1;
}
if (automatioinMap[generatedAutoId]) {
automatioinMap[generatedAutoId] = [
{
...automatioinMap[generatedAutoId][0],
issue: langStore.get("ISSUE_MUST_CONTAIN_A_UNQIUE_ID_TO_EDIT", {
sourceFile: auto.source_file,
}),
readonly: true,
},
auto,
];
} else {
automatioinMap[generatedAutoId] = [
{
id: generatedAutoId,
entityId: "",
title: auto.alias ?? "",
description: auto.description ?? "",
state: langStore.get("AUTOMATION_STATE_UNREGISTERED"),
tags: {},
source_file: auto.source_file,
source_file_type: auto.source_file_type,
configuration_key: auto.configuration_key,
issue: langStore.get("ISSUE_MUST_CONTAIN_A_UNQIUE_ID_TO_EDIT", {
sourceFile: auto.source_file,
}),
readonly: true,
},
auto,
];
}
});
return automatioinMap; return automatioinMap;
}; };
@@ -10,6 +10,7 @@ import {
} from "./state"; } from "./state";
import Alert from "@mui/material/Alert"; import Alert from "@mui/material/Alert";
import { useConfirm } from "material-ui-confirm"; import { useConfirm } from "material-ui-confirm";
import { useLang } from "services/lang";
export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & { export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & {
onAutomationDelete: (aid: string, eid: string) => void; onAutomationDelete: (aid: string, eid: string) => void;
@@ -17,13 +18,14 @@ export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & {
export const AutomationManagerLoaded: FC< export const AutomationManagerLoaded: FC<
PropsWithChildren<AutomationManagerLoadedProps> PropsWithChildren<AutomationManagerLoadedProps>
> = ({ children, ...args }) => { > = ({ children, ...args }) => {
const langStore = useLang();
const state = useAutomationManagerState(args); const state = useAutomationManagerState(args);
const confirm = useConfirm(); const confirm = useConfirm();
const onAutomationDelete = async (aid: string, eid: string) => const onAutomationDelete = async (aid: string, eid: string) =>
confirm({ confirm({
title: "Are you sure you want to delete this automation?", title: langStore.get("CONFIRMATION_DELETE_THIS_AUTOMATION"),
confirmationText: "Delete", confirmationText: langStore.get("DELETE"),
}) })
.then(() => { .then(() => {
args.onAutomationDelete(aid, eid); args.onAutomationDelete(aid, eid);
@@ -48,6 +50,8 @@ export const AutomationManagerLoaded: FC<
{state.currentAutomationId !== null ? ( {state.currentAutomationId !== null ? (
state.currentAutomation ? ( state.currentAutomation ? (
<AutomationEditor <AutomationEditor
readonly={state.currentAutomationIsReadOnly}
issue={state.currentAutomationIssue}
dims={{ dims={{
...DEFAULT_DIMS, ...DEFAULT_DIMS,
flipped: true, flipped: true,
@@ -76,8 +80,9 @@ export const AutomationManagerLoaded: FC<
) : ( ) : (
<div> <div>
<Alert color="warning"> <Alert color="warning">
Failed to find an automation on disk with id{" "} {langStore.get("ISSUE_FAILED_TO_FIND_AUTOMATION_ON_DISK", {
{state.currentAutomationId}. id: state.currentAutomationId,
})}
</Alert> </Alert>
</div> </div>
) )
@@ -7,6 +7,7 @@ import { useAutomationDB } from "./automationDB";
import { useConfirm } from "material-ui-confirm"; import { useConfirm } from "material-ui-confirm";
import { AutomationManagerAutoUpdatable } from "../types"; import { AutomationManagerAutoUpdatable } from "../types";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
import { useLang } from "services/lang";
export type UseAutomationManagerStateArgs = { export type UseAutomationManagerStateArgs = {
configAutomations: AutomationData[]; configAutomations: AutomationData[];
@@ -26,6 +27,7 @@ export const useAutomationManagerState = ({
onAutomationStateChange, onAutomationStateChange,
}: UseAutomationManagerStateArgs) => { }: UseAutomationManagerStateArgs) => {
// state // state
const langStore = useLang();
const confirm = useConfirm(); const confirm = useConfirm();
const snackbr = useSnackbar(); const snackbr = useSnackbar();
const cookies = useAMSCookies(); const cookies = useAMSCookies();
@@ -35,7 +37,11 @@ export const useAutomationManagerState = ({
.map(({ id, tags = {} }) => ({ .map(({ id, tags = {} }) => ({
id, id,
tags, tags,
})), }))
.filter(({ id }) => typeof id === "string") as Array<{
id: string;
tags: Record<string, string>;
}>,
onUpdateTags onUpdateTags
); );
const automationDB = useAutomationDB(hassEntities, configAutomations, tagsDB); const automationDB = useAutomationDB(hassEntities, configAutomations, tagsDB);
@@ -44,10 +50,9 @@ export const useAutomationManagerState = ({
const stillHaveNewAreYouSure = async () => { const stillHaveNewAreYouSure = async () => {
try { try {
await confirm({ await confirm({
content: content: langStore.get("WARNING_SWITCHING_FROM_NONE_SAVE"),
"Selecting another automation will cause you to lose all work done on this new automation. Please save your work on this automation first.", confirmationText: langStore.get("SWITCH_AUTOMATION"),
confirmationText: "Switch Automation", cancellationText: langStore.get("CANCEL"),
cancellationText: "Cancel",
}); });
return true; return true;
} catch (_) { } catch (_) {
@@ -77,6 +82,14 @@ export const useAutomationManagerState = ({
get currentAutomationEntityId(): string | null { get currentAutomationEntityId(): string | null {
return currentAutomation === null ? null : currentAutomation[0].entityId; return currentAutomation === null ? null : currentAutomation[0].entityId;
}, },
get currentAutomationIsReadOnly(): boolean {
return currentAutomation === null ? true : currentAutomation[0].readonly;
},
get currentAutomationIssue(): string | undefined {
return currentAutomation === null
? undefined
: currentAutomation[0].issue;
},
async setSelectedAutomationId(i: string | null, force: boolean = false) { async setSelectedAutomationId(i: string | null, force: boolean = false) {
if (methods.currentAutomationIsNew && !force) { if (methods.currentAutomationIsNew && !force) {
if (!(await stillHaveNewAreYouSure())) { if (!(await stillHaveNewAreYouSure())) {
@@ -93,7 +106,9 @@ export const useAutomationManagerState = ({
} }
} }
const auto = automationDB.addNew(); const auto = automationDB.addNew();
methods.setSelectedAutomationId(auto.id, true); if (auto.id) {
methods.setSelectedAutomationId(auto.id, true);
}
}, },
editorUpdateAutomation(auto: AutomationData | BareAutomationData) { editorUpdateAutomation(auto: AutomationData | BareAutomationData) {
if (methods.currentAutomationIsNew) { if (methods.currentAutomationIsNew) {
@@ -128,9 +143,10 @@ export const useAutomationManagerState = ({
} }
} else { } else {
snackbr.enqueueSnackbar( snackbr.enqueueSnackbar(
`Failed to save automation "${aid}" contents - ${JSON.stringify( langStore.get("ERROR_FAILED_TO_SAVE", {
a aid,
)} -- not found in /config`, contents: JSON.stringify(a),
}),
{ variant: "error" } { variant: "error" }
); );
} }
@@ -12,6 +12,7 @@ import { Button } from "components/Inputs/Buttons/Button";
import InputAutoText from "components/Inputs/InputAutoText"; import InputAutoText from "components/Inputs/InputAutoText";
import { TagDB } from "../TagDB"; import { TagDB } from "../TagDB";
import { useLang } from "services/lang";
export type TagsProps = { export type TagsProps = {
automationId: string; automationId: string;
@@ -29,6 +30,7 @@ export type TagModalState =
}; };
export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => { export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
const langStore = useLang();
const [modalState, setModal] = useState<TagModalState>({ open: false }); const [modalState, setModal] = useState<TagModalState>({ open: false });
const tags = tagsDB.getTags(automationId, true); const tags = tagsDB.getTags(automationId, true);
const onUpdate = (t: Record<string, string>) => const onUpdate = (t: Record<string, string>) =>
@@ -44,7 +46,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
<InputAutoText <InputAutoText
className="name" className="name"
options={tagsDB.getTagNames(Object.keys(tags))} options={tagsDB.getTagNames(Object.keys(tags))}
label="Tag Name" label={langStore.get("TAG_NAME")}
value={modalState.tag[0]} value={modalState.tag[0]}
onChange={(v) => onChange={(v) =>
setModal({ setModal({
@@ -56,7 +58,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
<InputAutoText <InputAutoText
className="value" className="value"
options={tagsDB.getTagValues(modalState.tag[0])} options={tagsDB.getTagValues(modalState.tag[0])}
label="Tag Value" label={langStore.get("TAG_VALUE")}
value={modalState.tag[1]} value={modalState.tag[1]}
onChange={(v) => onChange={(v) =>
setModal({ setModal({
@@ -67,7 +69,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
/> />
<div className="buttons"> <div className="buttons">
<Button onClick={() => setModal({ open: false })} color="info"> <Button onClick={() => setModal({ open: false })} color="info">
Close {langStore.get("CLOSE")}
</Button> </Button>
<Button <Button
disabled={!validTag} disabled={!validTag}
@@ -80,7 +82,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
}} }}
color="success" color="success"
> >
{modalState.isNew ? "Create" : "Save"} {modalState.isNew ? langStore.get("CREATE") : langStore.get("SAVE")}
</Button> </Button>
</div> </div>
</div> </div>
@@ -9,12 +9,16 @@ import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
import SelectIcon from "@mui/icons-material/HighlightAltSharp"; import SelectIcon from "@mui/icons-material/HighlightAltSharp";
import RunIcon from "@mui/icons-material/RunCircleOutlined"; import RunIcon from "@mui/icons-material/RunCircleOutlined";
import Tooltip from "@mui/material/Tooltip";
import Box from "@mui/material/Box";
import Chip from "@mui/material/Chip";
import { InputTextView } from "components/Inputs/InputTextView"; import { InputTextView } from "components/Inputs/InputTextView";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
import { AutomationManagerAuto } from "../types"; import { AutomationManagerAuto } from "../types";
import { Tags } from "./Tags"; import { Tags } from "./Tags";
import { TagDB } from "../TagDB"; import { TagDB } from "../TagDB";
import { Chip, Tooltip } from "@mui/material"; import { useLang } from "services/lang";
export type MetadataBoxProps = AutomationManagerAuto & { export type MetadataBoxProps = AutomationManagerAuto & {
onDelete: () => void; onDelete: () => void;
@@ -28,8 +32,12 @@ export type MetadataBoxProps = AutomationManagerAuto & {
}; };
export const MetadataBox: FC<MetadataBoxProps> = (props) => { export const MetadataBox: FC<MetadataBoxProps> = (props) => {
const isValidState = ["on", "off"].includes(props.state); const isValidState = ["on", "off"].includes(props.state);
const langStore = useLang();
const prettyState = ["on", "off"].includes(props.state)
? langStore.get(`AUTOMATION_STATE_${props.state}`)
: props.state;
return ( return (
<div <Box
className={[ className={[
"automation-manager--metadatabox", "automation-manager--metadatabox",
props.isSelected ? "selected" : "", props.isSelected ? "selected" : "",
@@ -38,7 +46,13 @@ export const MetadataBox: FC<MetadataBoxProps> = (props) => {
> >
<div <div
className="metadatabox--switch" className="metadatabox--switch"
title={!isValidState ? "Invalid state" : `Automation is ${props.state}`} title={
!isValidState
? langStore.get("ERROR_INVALID_AUTOMATION_STATE")
: langStore.get("AUTOMATION_STATE_IS", {
state: prettyState,
})
}
> >
<Switch <Switch
checked={props.state !== "off"} checked={props.state !== "off"}
@@ -53,28 +67,36 @@ export const MetadataBox: FC<MetadataBoxProps> = (props) => {
<div className="metadatabox--title"> <div className="metadatabox--title">
<span className="metadatabox--title--source"> <span className="metadatabox--title--source">
<Tooltip <Tooltip
title={`This automation is located in the file ${props.source_file}. It's currently '${props.state}', it's entity id is '${props.entityId}' and it's automation id is '${props.id}'`} title={langStore.get("AUTOMATION_METADATA_TOOLTIP_TEXT", {
source_file: props.source_file,
state: prettyState,
entityId: props.entityId,
id: props.id,
})}
> >
<Chip <Chip
label={`@${props.source_file} (${props.source_file_type}) - ${ label={`@${props.source_file} (${props.source_file_type}) - ${
props.entityId ?? "n/a" props.entityId ?? langStore.get("N/A")
}`} }`}
className="text-ellipsis" className="text-ellipsis"
/> />
</Tooltip> </Tooltip>
</span> </span>
<Tooltip title={`ID=${props.id}, EntityID=${props.entityId}`}> <InputTextView
<InputTextView titleSlug="AUTOMATION_METADATA_TOOLTIP_SIMPLE"
className="title" titleParams={{
placeholder="Title" id: props.id,
value={props.title} entityId: props.entityId,
onChange={props.onTitleUpdate} }}
disabled={props.isNew} className="title"
/> placeholder={langStore.get("TITLE")}
</Tooltip> value={props.title}
onChange={props.onTitleUpdate}
disabled={props.isNew}
/>
<InputTextView <InputTextView
className="description" className="description"
placeholder="Description" placeholder={langStore.get("DESCRIPTION")}
value={props.description} value={props.description}
onChange={props.onDescriptionUpdate} onChange={props.onDescriptionUpdate}
disabled={props.isNew} disabled={props.isNew}
@@ -90,24 +112,24 @@ export const MetadataBox: FC<MetadataBoxProps> = (props) => {
</div> </div>
<div className="buttons"> <div className="buttons">
<ButtonIcon <ButtonIcon
titleSlug="SELECT_AUTOMATION"
className="select" className="select"
icon={<SelectIcon />} icon={<SelectIcon />}
onClick={props.onSelect} onClick={props.onSelect}
title="Select automation"
/> />
<ButtonIcon <ButtonIcon
titleSlug="TRIGGER_AUTOMATION"
className="run" className="run"
icon={<RunIcon />} icon={<RunIcon />}
onClick={props.onRun} onClick={props.onRun}
title="Trigger automation"
/> />
<ButtonIcon <ButtonIcon
titleSlug="DELETE_AUTOMATION"
className="delete" className="delete"
icon={<DeleteForeverIcon />} icon={<DeleteForeverIcon />}
onClick={props.onDelete} onClick={props.onDelete}
title="Delete automation"
/> />
</div> </div>
</div> </Box>
); );
}; };
@@ -71,6 +71,7 @@ const story = makeStory({
source_file: "automation.yaml", source_file: "automation.yaml",
source_file_type: "list", source_file_type: "list",
configuration_key: ["automation"], configuration_key: ["automation"],
readonly: false,
}, },
]); ]);
setSelAutoId(id); setSelAutoId(id);
@@ -100,6 +101,7 @@ const makeAuto = (
source_file: "automation.yaml", source_file: "automation.yaml",
source_file_type: "list", source_file_type: "list",
configuration_key: ["automation"], configuration_key: ["automation"],
readonly: false,
...data, ...data,
}; };
}; };
@@ -18,6 +18,7 @@ import {
} from "../types"; } from "../types";
import { Button } from "components/Inputs/Buttons/Button"; import { Button } from "components/Inputs/Buttons/Button";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "services/lang";
export type AutomationManagerSidebarProps = { export type AutomationManagerSidebarProps = {
tagsDB: TagDB; tagsDB: TagDB;
@@ -41,6 +42,7 @@ export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
onSelectedAutomationId, onSelectedAutomationId,
...events ...events
}) => { }) => {
const langStore = useLang();
const [searchText, setSearchText] = useState(""); const [searchText, setSearchText] = useState("");
const [selectedTagIdx, setSelectedTagIdx] = useState<number[]>([]); const [selectedTagIdx, setSelectedTagIdx] = useState<number[]>([]);
const [isHidden, setHidden] = useState(false); const [isHidden, setHidden] = useState(false);
@@ -76,9 +78,13 @@ export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
].join(" ")} ].join(" ")}
> >
<div className="automation-manager--sidebar-box--nav"> <div className="automation-manager--sidebar-box--nav">
<InputText label="Search" value={searchText} onChange={setSearchText} /> <InputText
label={langStore.get("SEARCH")}
value={searchText}
onChange={setSearchText}
/>
<InputMultiSelect <InputMultiSelect
label="Tags" label={langStore.get("TAGS")}
selected={selectedTagIdx} selected={selectedTagIdx}
onChange={setSelectedTagIdx} onChange={setSelectedTagIdx}
options={tags} options={tags}
@@ -109,7 +115,7 @@ export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
color="primary" color="primary"
className="add-btn" className="add-btn"
> >
Add {langStore.get("ADD")}
</Button> </Button>
<ButtonIcon <ButtonIcon
className="hide-btn" className="hide-btn"
@@ -38,10 +38,11 @@ const automations: AutomationManagerAuto[] = [
description: a.description ?? "", description: a.description ?? "",
state: "on", state: "on",
tags: a.tags, tags: a.tags,
id: a.id, id: a.id as string,
isSelected: false, isSelected: false,
source_file: "automation.yaml", source_file: "automation.yaml",
source_file_type: "list", source_file_type: "list",
readonly: false,
configuration_key: ["automation"], configuration_key: ["automation"],
})); }));
@@ -51,7 +52,8 @@ const bigList = bigMockAutoList.map<AutomationManagerAuto>((a) => ({
description: a.description ?? "", description: a.description ?? "",
state: "on", state: "on",
tags: a.tags, tags: a.tags,
id: a.id, id: a.id as string,
readonly: false,
isSelected: false, isSelected: false,
source_file: "automation.yaml", source_file: "automation.yaml",
source_file_type: "list", source_file_type: "list",
@@ -1,10 +1,10 @@
import { makeStory } from "devUtils"; import { makeStory } from "devUtils";
import { useMockApiService } from "apiService"; import { useMockApiService } from "services/api";
import { AutomationManager } from "."; import { AutomationManager } from ".";
import { import {
MockHAEntitiesProps, MockHAEntitiesProps,
useMockHAEntities, useMockHAEntities,
} from "haService/HAEntities.mock"; } from "services/ha/HAEntities.mock";
import { AutomationData } from "types/automations"; import { AutomationData } from "types/automations";
import { createMockAuto } from "utils/mocks"; import { createMockAuto } from "utils/mocks";
import { useState } from "react"; import { useState } from "react";
@@ -109,7 +109,7 @@ export const MissingAutoInConfig = make({
entity_id: `automation.${auto1.id}`, entity_id: `automation.${auto1.id}`,
attributes: { attributes: {
id: auto1.id, id: auto1.id,
friendly_name: auto1.alias, friendly_name: auto1.alias ?? auto1.id ?? "",
}, },
context: { id: "", parent_id: null, user_id: null }, context: { id: "", parent_id: null, user_id: null },
last_changed: "", last_changed: "",
@@ -4,8 +4,8 @@ import { FC, useEffect, useRef, useState } from "react";
import LinearProgress from "@mui/material/LinearProgress"; import LinearProgress from "@mui/material/LinearProgress";
import Skeleton from "@mui/material/Skeleton"; import Skeleton from "@mui/material/Skeleton";
import { ApiService } from "apiService/core"; import { ApiService } from "services/api/core";
import { HAEntitiesState } from "haService/HAEntities"; import { HAEntitiesState } from "services/ha/HAEntities";
import { AutomationManagerLoaded } from "./Loaded"; import { AutomationManagerLoaded } from "./Loaded";
import { Alert } from "@mui/material"; import { Alert } from "@mui/material";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
@@ -14,7 +14,8 @@ import { getFailures } from "types/validators/helper";
import * as av from "types/validators/autmation"; import * as av from "types/validators/autmation";
import { useConfirm } from "material-ui-confirm"; import { useConfirm } from "material-ui-confirm";
import InputYaml from "components/Inputs/Base/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import { APIResponse } from "apiService/types"; import { APIResponse } from "services/api/types";
import { useLang } from "services/lang";
export type AutomationManagerProps = { export type AutomationManagerProps = {
onAutomationStateChange: (eid: string, on: boolean) => Promise<any>; onAutomationStateChange: (eid: string, on: boolean) => Promise<any>;
@@ -33,6 +34,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
forceDeleteAutomation: _forceDeleteAutomation, forceDeleteAutomation: _forceDeleteAutomation,
triggerAutomation: _triggerAutomation, triggerAutomation: _triggerAutomation,
}) => { }) => {
const langStore = useLang();
const snackbr = useSnackbar(); const snackbr = useSnackbar();
const confirm = useConfirm(); const confirm = useConfirm();
const validationsShown = useRef(false); const validationsShown = useRef(false);
@@ -52,9 +54,14 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
}) })
.catch((err) => { .catch((err) => {
console.error(err); console.error(err);
snackbr.enqueueSnackbar(errorMessage.replace("{{err}}", String(err)), { snackbr.enqueueSnackbar(
variant: "error", langStore.get(errorMessage, {
}); err: String(err),
}),
{
variant: "error",
}
);
setIsSaving(isSaving.filter((k) => k !== name)); setIsSaving(isSaving.filter((k) => k !== name));
}); });
} }
@@ -68,9 +75,14 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
if (resp.ok) { if (resp.ok) {
refreshAutomations(); refreshAutomations();
} else { } else {
snackbr.enqueueSnackbar(errorMessage.replace("{{err}}", resp.error), { snackbr.enqueueSnackbar(
variant: "error", langStore.get(errorMessage, {
}); err: resp.error,
}),
{
variant: "error",
}
);
} }
} }
}); });
@@ -78,24 +90,26 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
const onAutomationStateChange = (eid: string, on: boolean) => const onAutomationStateChange = (eid: string, on: boolean) =>
wrapPromise( wrapPromise(
"changing automation state", langStore.get("AUTOMATION_MANAGER_STATE_CHANGE"),
'failed to toggle autonation due to "{{err}}"', "AUTOMATION_MANAGER_STATE_CHANGE_FAIL",
() => _onAutomationStateChange(eid, on) () => _onAutomationStateChange(eid, on)
); );
const refreshAutomations = () => const refreshAutomations = () =>
wrapPromise( wrapPromise(
"refreshing automations", langStore.get("AUTOMATION_MANAGER_REFRESH"),
'failed refreshing automations due to "{{err}}"', "AUTOMATION_MANAGER_REFRESH_FAIL",
() => _refreshAutomations() () => _refreshAutomations()
); );
const forceDeleteAutomation = (eid: string) => const forceDeleteAutomation = (eid: string) =>
wrapPromise("deleting automations", 'failed delete due to "{{err}}"', () => wrapPromise(
_forceDeleteAutomation(eid) langStore.get("AUTOMATION_MANAGER_DELETE"),
"AUTOMATION_MANAGER_DELETE_FAIL",
() => _forceDeleteAutomation(eid)
); );
const triggerAutomation = (eid: string) => const triggerAutomation = (eid: string) =>
wrapPromise( wrapPromise(
"triggering automations", langStore.get("AUTOMATION_MANAGER_TRIGGER"),
'failed trigger due to "{{err}}"', "AUTOMATION_MANAGER_TRIGGER_FAIL",
() => _triggerAutomation(eid) () => _triggerAutomation(eid)
); );
@@ -129,7 +143,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
cancellationButtonProps: { cancellationButtonProps: {
style: { display: "none" }, style: { display: "none" },
}, },
title: "Invalid Automations detected!", title: langStore.get("ERROR_INVALID_AUTOMATION_DETECTED"),
content: ( content: (
<> <>
<ol className="invalid-automation-modal-list"> <ol className="invalid-automation-modal-list">
@@ -165,6 +179,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
.catch(console.error); .catch(console.error);
} }
} }
// eslint-disable-next-line
}, [api.state.automations, confirm]); }, [api.state.automations, confirm]);
// handle bad states // handle bad states
@@ -172,8 +187,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
return ( return (
<div className="automation-manager error"> <div className="automation-manager error">
<Alert color="error"> <Alert color="error">
Failed to connect to websocket, please check that your access token is {langStore.get("ERROR_FAILED_CONNECTION_TO_HA")}
properly setup
</Alert>{" "} </Alert>{" "}
<br /> <br />
<code>{JSON.stringify(haEntities.error)}</code> <code>{JSON.stringify(haEntities.error)}</code>
@@ -205,7 +219,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
return ( return (
<div className="automation-manager error"> <div className="automation-manager error">
<Alert color="error"> <Alert color="error">
Failed to load automations from <code>/config</code> {langStore.get("ISSUES_FIND_AUTOMATION_IN_CONFIG")}
</Alert>{" "} </Alert>{" "}
<br /> <br />
<code>{error}</code> <code>{error}</code>
@@ -237,8 +251,8 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
onAutomationStateChange={onAutomationStateChange} onAutomationStateChange={onAutomationStateChange}
onAutomationAdd={(auto) => onAutomationAdd={(auto) =>
wrapApiPromise( wrapApiPromise(
"adding automation", langStore.get("AUTOMATION_MANAGER_ADD"),
"Failed to create automation, recieved error: {{err}}!", "AUTOMATION_MANAGER_ADD_FAIL",
() => api.createAutomation(auto) as any () => api.createAutomation(auto) as any
) )
} }
@@ -258,7 +272,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
} }
if (!deleteSent) { if (!deleteSent) {
snackbr.enqueueSnackbar( snackbr.enqueueSnackbar(
"Failed to delete automation, this may be resolved by a refresh or reboot of Home Assistant", langStore.get("AUTOMATION_MANAGER_DELETE_LIGHT"),
{ {
variant: "error", variant: "error",
} }
@@ -268,15 +282,15 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
}} }}
onAutomationUpdate={(auto) => onAutomationUpdate={(auto) =>
wrapApiPromise( wrapApiPromise(
"updating automation", langStore.get("AUTOMATION_MANAGER_UPDATE"),
"Failed to update automation, recieved error: {{err}}!", "AUTOMATION_MANAGER_UPDATE_FAIL",
() => api.updateAutomation(auto) as any () => api.updateAutomation(auto) as any
) )
} }
onUpdateTags={async (aid, t) => { onUpdateTags={async (aid, t) => {
wrapApiPromise( wrapApiPromise(
"updating tags", langStore.get("AUTOMATION_MANAGER_UPDATE_TAGS"),
"Failed to update tags, recieved error: {{err}}!", "AUTOMATION_MANAGER_UPDATE_TAGS_FAIL",
() => () =>
api.updateTags({ api.updateTags({
automation_id: aid, automation_id: aid,
@@ -12,6 +12,7 @@ export type AutomationManagerAuto = AutomationManagerAutoUpdatable & {
source_file: string; source_file: string;
source_file_type: string; source_file_type: string;
configuration_key: string[]; configuration_key: string[];
readonly: boolean;
}; };
export type AutomationManagerAutoItem = AutomationManagerAuto & { export type AutomationManagerAutoItem = AutomationManagerAuto & {
flags: AutomationManagerItemFlags; flags: AutomationManagerItemFlags;
@@ -0,0 +1,63 @@
import Alert from "@mui/material/Alert";
import Skeleton from "@mui/material/Skeleton";
import { ApiService } from "services/api/core";
import { UserProfile } from "services/api/types";
import { InputList } from "components/Inputs/InputList";
import { useLang } from "services/lang";
import { FC, useState } from "react";
import LinearProgress from "@mui/material/LinearProgress";
export type UserProfileProps = {
api: ApiService;
};
export const UserProfileEditor: FC<UserProfileProps> = ({ api }) => {
const [saving, setIsSaving] = useState(false);
const profile = api.state.userProfile;
const lang = useLang();
if (!profile.ready) {
return (
<div className="user-profile">
<Skeleton />
</div>
);
}
if (!profile.ok) {
return (
<div className="user-profile">
<Alert color="error">{JSON.stringify(profile.error)}</Alert>
</div>
);
}
const update =
<K extends keyof UserProfile, D extends UserProfile[K]>(key: K) =>
(data: D) => {
if (profile.ready) {
setIsSaving(true);
api
.setProfile({
...profile.data,
[key]: data,
})
.then(() => {
setIsSaving(false);
});
}
};
return (
<div className="user-profile">
<InputList
label={lang.get("THEME")}
options={["dark", "light"]}
current={profile.data.theme}
onChange={update("theme")}
/>
<InputList
label={lang.get("LANGUAGE")}
options={["eng", "fra", "ita"]}
current={profile.data.lang}
onChange={update("lang")}
/>
{saving && <LinearProgress />}
</div>
);
};
+50
View File
@@ -0,0 +1,50 @@
.bottom-bar {
width: 100%;
font-size: 0.5em;
display: flex;
align-items: center;
gap: 0.5em;
justify-content: space-between;
}
.bottom-bar>*, .bottom-bar>div>* {
max-height: 1em;
height: 1em;
min-height: 1em;
gap: 0.25em;
}
.bottom-bar #circle {
color: var(--mui-primary-main);
}
.bottom-bar #circle::before {
content: " ";
}
.bottom-bar #circle.error {
color: var(--mui-error-main);
}
.bottom-bar #circle.loaded {
color: var(--mui-success-light);
}
.bottom-bar .settings {
font-size: 0.75em;
padding: 1em 0.5em;
z-index: 10;
}
.bottom-bar .settings svg {
height: 0.5em;
width: 0.5em;
}
.user-profile {
width: 100%;
height: 100%;
min-width: 10em;
min-height: 10em;
}
+42
View File
@@ -0,0 +1,42 @@
import "./index.css";
import { FC, useState } from "react";
import { useHAConnection } from "services/ha/connection";
import { Button } from "components/Inputs/Buttons/Button";
import SettingsSuggestOutlinedIcon from "@mui/icons-material/SettingsSuggestOutlined";
import { useLang } from "services/lang";
import { Modal } from "components/Modal";
import { UserProfileEditor, UserProfileProps } from "./UserProfile";
import { useVersioner } from "services/versioner";
export type BottomBarProps = UserProfileProps;
export const BottomBar: FC<BottomBarProps> = ({ api }) => {
const lang = useLang();
const ha = useHAConnection();
const versionMgr = useVersioner();
const [isOpen, setOpen] = useState(false);
return (
<div className="bottom-bar center row">
<Modal open={isOpen} className="center column">
<UserProfileEditor api={api} />
<Button onClick={() => setOpen(false)}>{lang.get("CLOSE")}</Button>
</Modal>
<span id="connection">
HA{" "}
{ha.status === "loaded"
? lang.get("CONNECTED")
: ha.status === "error"
? lang.get("FAILED")
: lang.get("LOADING")}
<b id="circle" className={ha.status}>
🟢
</b>
</span>
<span>version: {versionMgr.current}</span>
<Button className="settings" onClick={() => setOpen(!isOpen)}>
<SettingsSuggestOutlinedIcon />
{lang.get("USER_PRERENCES")}
</Button>
</div>
);
};
@@ -1,22 +1,17 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react"; import { useState } from "react";
import { AutomationCondition } from "types/automations/conditions"; import { AutomationCondition } from "types/automations/conditions";
import { ConditionNodeBase } from "./ConditionNodeBase"; import { ConditionNodeBase } from "./ConditionNodeBase";
export default { import { makeStory } from "devUtils";
title: "ConditionEditor/NodeBase",
component: ConditionNodeBase,
parameters: { actions: { argTypesRegex: "^on.*" } },
} as ComponentMeta<typeof ConditionNodeBase>;
const Template: ComponentStory<typeof ConditionNodeBase> = ({ const { make, componentMeta } = makeStory({
condition, Component: ConditionNodeBase,
...args meta: {
}) => { title: "ConditionEditor/NodeBase",
const [data, setData] = useState(condition); },
return ( BaseTemplate: ({ condition, ...args }) => {
<Page> const [data, setData] = useState(condition);
return (
<ConditionNodeBase <ConditionNodeBase
{...args} {...args}
condition={data} condition={data}
@@ -24,20 +19,20 @@ const Template: ComponentStory<typeof ConditionNodeBase> = ({
setData(data); setData(data);
}} }}
/> />
</Page> );
); },
}; });
export const TemplateViewer = Template.bind({}); export default componentMeta;
TemplateViewer.args = {
export const TemplateViewer = make({
condition: { condition: {
condition: "template", condition: "template",
value_template: "states('switch.light_kitchen') == 'on'", value_template: "states('switch.light_kitchen') == 'on'",
} as AutomationCondition, } as AutomationCondition,
}; });
export const MultipleThings = Template.bind({}); export const MultipleThings = make({
MultipleThings.args = {
condition: { condition: {
condition: "or", condition: "or",
conditions: [ conditions: [
@@ -62,4 +57,4 @@ MultipleThings.args = {
}, },
], ],
} as AutomationCondition, } as AutomationCondition,
}; });
@@ -6,12 +6,13 @@ import { FC, useState } from "react";
import { AutomationCondition } from "types/automations/conditions"; import { AutomationCondition } from "types/automations/conditions";
import { getSubTypeList } from "utils/automations"; import { getSubTypeList } from "utils/automations";
import { getConditionDefaultValues } from "utils/defaults"; import { getConditionDefaultValues } from "utils/defaults";
import { useHA } from "haService"; import { useHA } from "services/ha";
import InputYaml from "components/Inputs/Base/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import { getViewer } from "./viewRender"; import { getViewer } from "./viewRender";
import { getEditor } from "./editorRender"; import { getEditor } from "./editorRender";
import useWindowSize from "utils/useWindowSize"; import useWindowSize from "utils/useWindowSize";
import { ConditionNodeSettings } from "./ConditionNodeSettings"; import { ConditionNodeSettings } from "./ConditionNodeSettings";
import { useLang } from "services/lang";
export type ConditionNodeBaseProps = { export type ConditionNodeBaseProps = {
condition: AutomationCondition; condition: AutomationCondition;
@@ -24,6 +25,7 @@ export type ConditionNodeBaseViewMode = "edit" | "yaml" | "view";
export const ConditionNodeBase: FC<ConditionNodeBaseProps> = (props) => { export const ConditionNodeBase: FC<ConditionNodeBaseProps> = (props) => {
// state // state
const ha = useHA(); const ha = useHA();
const langStore = useLang();
const { isMobile } = useWindowSize(); const { isMobile } = useWindowSize();
const [{ isEdited, condition }, setCondition] = useState<{ const [{ isEdited, condition }, setCondition] = useState<{
isEdited: boolean; isEdited: boolean;
@@ -61,6 +63,7 @@ export const ConditionNodeBase: FC<ConditionNodeBaseProps> = (props) => {
onChange={updateCondition} onChange={updateCondition}
ha={ha} ha={ha}
initialViewMode="edit" initialViewMode="edit"
langStore={langStore}
/> />
); );
} }
@@ -101,6 +104,7 @@ export const ConditionNodeBase: FC<ConditionNodeBaseProps> = (props) => {
}, },
} as any) } as any)
} }
prettyOptionLabels={false}
/> />
{isMobile && icons} {isMobile && icons}
</div> </div>
@@ -20,7 +20,7 @@ import {
import { genUpdateMethods } from "./nestedUpdater"; import { genUpdateMethods } from "./nestedUpdater";
import { InputTime } from "components/Inputs/Base/InputTime"; import { InputTime } from "components/Inputs/Base/InputTime";
import InputYaml from "components/Inputs/Base/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import { HAService } from "haService"; import { HAService } from "services/ha";
import { DeviceEditor } from "components/DeviceEditor"; import { DeviceEditor } from "components/DeviceEditor";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
import AddIcon from "@mui/icons-material/Add"; import AddIcon from "@mui/icons-material/Add";
@@ -31,6 +31,7 @@ import { prettyName } from "utils/formatting";
import { InputList } from "components/Inputs/InputList"; import { InputList } from "components/Inputs/InputList";
import { Button } from "components/Inputs/Buttons/Button"; import { Button } from "components/Inputs/Buttons/Button";
import { RemoveCircle } from "@mui/icons-material"; import { RemoveCircle } from "@mui/icons-material";
import { LangStore } from "services/lang";
interface Editor<C extends AutomationCondition> interface Editor<C extends AutomationCondition>
extends FC<{ extends FC<{
@@ -38,6 +39,7 @@ interface Editor<C extends AutomationCondition>
onChange: (condition: C) => void; onChange: (condition: C) => void;
ha: HAService; ha: HAService;
initialViewMode: ConditionNodeBaseViewMode; initialViewMode: ConditionNodeBaseViewMode;
langStore: LangStore;
}> {} }> {}
export const getEditor = (condition: AutomationCondition): Editor<any> => { export const getEditor = (condition: AutomationCondition): Editor<any> => {
@@ -70,11 +72,12 @@ export const getEditor = (condition: AutomationCondition): Editor<any> => {
export const TemplateEditor: Editor<TemplateCondition> = ({ export const TemplateEditor: Editor<TemplateCondition> = ({
onChange, onChange,
condition, condition,
langStore,
}) => { }) => {
return ( return (
<> <>
<InputYaml <InputYaml
label="Template" label={langStore.get("TEMPLATE")}
value={condition.value_template} value={condition.value_template}
onChange={(value_template) => onChange={(value_template) =>
onChange({ onChange({
@@ -119,6 +122,7 @@ export const DeviceConditionEditor: Editor<DeviceCondition> = ({
export const NumericStateEditor: Editor<NumericCondition> = ({ export const NumericStateEditor: Editor<NumericCondition> = ({
onChange, onChange,
condition, condition,
langStore,
}) => { }) => {
return ( return (
<> <>
@@ -133,7 +137,7 @@ export const NumericStateEditor: Editor<NumericCondition> = ({
} }
/> />
<InputText <InputText
label="Attribute" label={langStore.get("ATTRIBUTE")}
value={condition.attribute ?? ""} value={condition.attribute ?? ""}
onChange={(attribute) => onChange={(attribute) =>
onChange({ onChange({
@@ -143,7 +147,7 @@ export const NumericStateEditor: Editor<NumericCondition> = ({
} }
/> />
<InputNumber <InputNumber
label="Above" label={langStore.get("ABOVE")}
value={condition.above ? Number(condition.above) : undefined} value={condition.above ? Number(condition.above) : undefined}
onChange={(above) => onChange={(above) =>
onChange({ onChange({
@@ -153,7 +157,7 @@ export const NumericStateEditor: Editor<NumericCondition> = ({
} }
/> />
<InputNumber <InputNumber
label="Below" label={langStore.get("BELOW")}
value={condition.below ? Number(condition.below) : undefined} value={condition.below ? Number(condition.below) : undefined}
onChange={(below) => onChange={(below) =>
onChange({ onChange({
@@ -163,7 +167,7 @@ export const NumericStateEditor: Editor<NumericCondition> = ({
} }
/> />
<InputYaml <InputYaml
label="Template" label={langStore.get("TEMPLATE")}
value={condition.value_template ?? ""} value={condition.value_template ?? ""}
onChange={(value_template) => onChange={(value_template) =>
onChange({ onChange({
@@ -221,6 +225,7 @@ export const StateEditor: Editor<StateCondition> = ({
onChange, onChange,
condition, condition,
ha, ha,
langStore,
}) => { }) => {
const restrictToDomain = const restrictToDomain =
!condition.entity_id || condition.entity_id.length === 0 !condition.entity_id || condition.entity_id.length === 0
@@ -241,7 +246,7 @@ export const StateEditor: Editor<StateCondition> = ({
} }
/> />
<InputAutoComplete <InputAutoComplete
label="Attribute" label={langStore.get("ATTRIBUTE")}
value={condition.attribute ?? ""} value={condition.attribute ?? ""}
options={ha.entities.getAttributes(condition.entity_id)} options={ha.entities.getAttributes(condition.entity_id)}
multiple={false} multiple={false}
@@ -253,11 +258,11 @@ export const StateEditor: Editor<StateCondition> = ({
} }
/> />
<InputText <InputText
label="State" label={langStore.get("STATE")}
value={String(condition.state)} value={String(condition.state)}
placeholder={ha.entities placeholder={ha.entities
.getStates(condition.entity_id, condition.attribute) .getStates(condition.entity_id, condition.attribute)
.join(" or ")} .join(` ${langStore.get("OR").toLowerCase()} `)}
onChange={(state) => onChange={(state) =>
onChange({ onChange({
...condition, ...condition,
@@ -266,7 +271,7 @@ export const StateEditor: Editor<StateCondition> = ({
} }
/> />
<InputTime <InputTime
label="For" label={langStore.get("FOR")}
value={condition.for} value={condition.for}
onChange={(_for) => onChange={(_for) =>
onChange({ onChange({
@@ -280,7 +285,11 @@ export const StateEditor: Editor<StateCondition> = ({
}; };
type TimeEditorShows = "after" | "before" | "weekday"; type TimeEditorShows = "after" | "before" | "weekday";
export const TimeEditor: Editor<TimeCondition> = ({ onChange, condition }) => { export const TimeEditor: Editor<TimeCondition> = ({
onChange,
condition,
langStore,
}) => {
const [shows, setShows] = useState<TimeEditorShows[]>( const [shows, setShows] = useState<TimeEditorShows[]>(
Object.keys(condition).filter((k) => Object.keys(condition).filter((k) =>
["after", "before", "weekday"].includes(k) ["after", "before", "weekday"].includes(k)
@@ -321,19 +330,19 @@ export const TimeEditor: Editor<TimeCondition> = ({ onChange, condition }) => {
<b className="label">{prettyName(show)}</b> <b className="label">{prettyName(show)}</b>
<InputAutoComplete <InputAutoComplete
className="condition-node--time-editor--weekday" className="condition-node--time-editor--weekday"
label="Weekday" label={langStore.get("WEEKDAY")}
value={condition.weekday ?? []} value={condition.weekday ?? []}
multiple={true} multiple={true}
getID={(opt) => opt} getID={(opt) => opt}
getLabel={(opt) => { getLabel={(opt) => {
return { return {
mon: "Monday", mon: langStore.get("DAY_mon"),
tue: "Tuesday", tue: langStore.get("DAY_tue"),
wed: "Wednesday", wed: langStore.get("DAY_wed"),
thu: "Thursday", thu: langStore.get("DAY_thu"),
fri: "Friday", fri: langStore.get("DAY_fri"),
sat: "Saturday", sat: langStore.get("DAY_sat"),
sun: "Sunday", sun: langStore.get("DAY_sun"),
}[opt]; }[opt];
}} }}
onChange={(weekday: any) => onChange={(weekday: any) =>
@@ -362,7 +371,7 @@ export const TimeEditor: Editor<TimeCondition> = ({ onChange, condition }) => {
{shows.length < 3 && ( {shows.length < 3 && (
<InputList <InputList
className="condition-node--time-editor--new" className="condition-node--time-editor--new"
label="Option" label={langStore.get("OPTION")}
options={["after", "before", "weekday"].filter( options={["after", "before", "weekday"].filter(
(k: any) => !shows.includes(k) (k: any) => !shows.includes(k)
)} )}
@@ -378,11 +387,12 @@ export const TimeEditor: Editor<TimeCondition> = ({ onChange, condition }) => {
export const TriggerEditor: Editor<TriggerCondition> = ({ export const TriggerEditor: Editor<TriggerCondition> = ({
onChange, onChange,
condition, condition,
langStore,
}) => { }) => {
return ( return (
<> <>
<InputText <InputText
label="Trigger ID" label={langStore.get("TRIGGER_ID")}
value={condition.id} value={condition.id}
onChange={(id) => onChange={(id) =>
onChange({ onChange({
@@ -395,11 +405,15 @@ export const TriggerEditor: Editor<TriggerCondition> = ({
); );
}; };
export const ZoneEditor: Editor<ZoneCondition> = ({ onChange, condition }) => { export const ZoneEditor: Editor<ZoneCondition> = ({
onChange,
condition,
langStore,
}) => {
return ( return (
<> <>
<InputEntity <InputEntity
label="Zone" label={langStore.get("ZONE")}
value={condition.zone ?? []} value={condition.zone ?? []}
multiple multiple
onChange={(zone) => onChange={(zone) =>
@@ -411,7 +425,7 @@ export const ZoneEditor: Editor<ZoneCondition> = ({ onChange, condition }) => {
restrictToDomain={["zone"]} restrictToDomain={["zone"]}
/> />
<InputEntity <InputEntity
label="Entity with Location" label={langStore.get("ENTITY_WITH_LOCATION")}
value={condition.entity_id} value={condition.entity_id}
multiple multiple
onChange={(entity_id) => onChange={(entity_id) =>
@@ -1,26 +1,22 @@
import { ComponentMeta, ComponentStory } from "@storybook/react"; import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page"; import { MockPage, Page } from "components/Page";
import { useState } from "react"; import { useState } from "react";
import { AutomationCondition } from "types/automations/conditions"; import { AutomationCondition } from "types/automations/conditions";
import { ConditionEditor } from "."; import { ConditionEditor } from ".";
import { makeStory } from "devUtils";
export default { const { make, componentMeta } = makeStory({
title: "ConditionEditor", Component: ConditionEditor,
component: ConditionEditor, meta: {
parameters: { actions: { argTypesRegex: "^on.*" } }, title: "ConditionEditor",
args: { args: {
initialViewMode: "edit", initialViewMode: "edit",
},
}, },
} as ComponentMeta<typeof ConditionEditor>; BaseTemplate: ({ condition, ...args }) => {
const [data, setData] = useState(condition);
const Template: ComponentStory<typeof ConditionEditor> = ({ return (
condition,
...args
}) => {
const [data, setData] = useState(condition);
return (
<Page>
<ConditionEditor <ConditionEditor
{...args} {...args}
condition={data} condition={data}
@@ -28,29 +24,28 @@ const Template: ComponentStory<typeof ConditionEditor> = ({
setData(data); setData(data);
}} }}
/> />
</Page> );
); },
}; });
export const TemplateViewer = Template.bind({}); export default componentMeta;
TemplateViewer.args = {
export const TemplateViewer = make({
condition: { condition: {
condition: "template", condition: "template",
value_template: "states('switch.light_kitchen') == 'on'", value_template: "states('switch.light_kitchen') == 'on'",
} as AutomationCondition, } as AutomationCondition,
}; });
export const NumericStateViewer = Template.bind({}); export const NumericStateViewer = make({
NumericStateViewer.args = {
condition: { condition: {
condition: "numeric_state", condition: "numeric_state",
entity_id: "sensor.humidity_kitchen", entity_id: "sensor.humidity_kitchen",
above: "10", above: "10",
} as AutomationCondition, } as AutomationCondition,
}; });
export const LogicCondition = Template.bind({}); export const LogicCondition = make({
LogicCondition.args = {
condition: { condition: {
condition: "or", condition: "or",
conditions: [ conditions: [
@@ -81,9 +76,8 @@ LogicCondition.args = {
}, },
], ],
} as AutomationCondition, } as AutomationCondition,
}; });
export const TimeCondition = Template.bind({}); export const TimeCondition = make({
TimeCondition.args = {
condition: { condition: {
condition: "or", condition: "or",
conditions: [ conditions: [
@@ -104,7 +98,7 @@ TimeCondition.args = {
}, },
], ],
} as AutomationCondition, } as AutomationCondition,
}; });
export const MultipleConditions: ComponentStory<typeof ConditionEditor> = ( export const MultipleConditions: ComponentStory<typeof ConditionEditor> = (
args args
@@ -134,12 +128,12 @@ export const MultipleConditions: ComponentStory<typeof ConditionEditor> = (
], ],
}); });
return ( return (
<Page> <MockPage>
<ConditionEditor <ConditionEditor
onUpdate={setState} onUpdate={setState}
onDelete={() => {}} onDelete={() => {}}
condition={state} condition={state}
/> />
</Page> </MockPage>
); );
}; };
@@ -1,46 +1,34 @@
import React from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { DAGGraphBoard } from "."; import { DAGGraphBoard } from ".";
import { Page } from "components/Page";
import { SimpleErrorElement } from "components/SimpleErrorElement"; import { SimpleErrorElement } from "components/SimpleErrorElement";
export default { import { makeStory } from "devUtils";
title: "DAGGraph/Board",
component: DAGGraphBoard,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {},
} as ComponentMeta<typeof DAGGraphBoard>;
const Template: ComponentStory<typeof DAGGraphBoard> = (args) => { const { make, componentMeta } = makeStory({
return ( Component: DAGGraphBoard,
<Page> meta: {
<DAGGraphBoard {...args} /> title: "DAGGraph/Board",
</Page> },
); });
};
export const Loading = Template.bind({}); export default componentMeta;
Loading.args = { export const Example = make({});
...Loading.args,
export const Loading = make({
state: { state: {
ready: false, ready: false,
}, },
}; });
export const Errored = Template.bind({}); export const Errored = make({
Errored.args = {
...Loading.args,
state: { state: {
ready: true, ready: true,
data: { data: {
error: <SimpleErrorElement error={new Error("Test")} />, error: <SimpleErrorElement error={new Error("Test")} />,
}, },
}, },
}; });
export const Empty = Template.bind({}); export const Empty = make({
Empty.args = {
...Empty.args,
state: { state: {
ready: true, ready: true,
data: { data: {
@@ -50,11 +38,9 @@ Empty.args = {
}, },
}, },
}, },
}; });
export const Basic = Template.bind({}); export const Basic = make({
Basic.args = {
...Basic.args,
state: { state: {
ready: true, ready: true,
data: { data: {
@@ -88,4 +74,4 @@ Basic.args = {
}, },
}, },
}, },
}; });
@@ -3,7 +3,7 @@ import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page"; import { Page } from "components/Page";
import { DAGGraphBoard } from "components/DAGGraph/board"; import { DAGGraphBoard } from "components/DAGGraph/board";
import { useAutomationNodes } from "./index"; import { useAutomationNodes } from "./index";
import { useHA } from "haService"; import { useHA } from "services/ha";
import { AutomationActionData } from "types/automations"; import { AutomationActionData } from "types/automations";
import { createUpdaterFromAutomationData } from "../updater"; import { createUpdaterFromAutomationData } from "../updater";
import { ModalState } from "../board/types"; import { ModalState } from "../board/types";
+1 -1
View File
@@ -1,6 +1,6 @@
import { FC, useState, ReactNode } from "react"; import { FC, useState, ReactNode } from "react";
import { AutomationSequenceNode } from "types/automations"; import { AutomationSequenceNode } from "types/automations";
import { useHA } from "haService"; import { useHA } from "services/ha";
import { ModalState } from "./board/types"; import { ModalState } from "./board/types";
import { createUpdater } from "./updater"; import { createUpdater } from "./updater";
import { useAutomationNodes } from "./elements"; import { useAutomationNodes } from "./elements";
@@ -1,6 +1,6 @@
import React from "react"; import React from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react"; import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page"; import { MockPage } from "components/Page";
import { ButtonNode } from "./ButtonNode"; import { ButtonNode } from "./ButtonNode";
import { DAGGraphBoard } from "components/DAGGraph/board"; import { DAGGraphBoard } from "components/DAGGraph/board";
import { ButtonNodeMaker } from "."; import { ButtonNodeMaker } from ".";
@@ -25,7 +25,7 @@ const Template: ComponentStory<typeof ButtonNode> = (args) => {
...args, ...args,
}; };
return ( return (
<Page> <MockPage>
<DAGGraphBoard <DAGGraphBoard
closeModal={() => {}} closeModal={() => {}}
state={{ state={{
@@ -80,7 +80,7 @@ const Template: ComponentStory<typeof ButtonNode> = (args) => {
}, },
}} }}
/> />
</Page> </MockPage>
); );
}; };
@@ -13,6 +13,7 @@ import { prettyName } from "utils/formatting";
import DeleteForeverIcon from "@mui/icons-material/DeleteForever"; import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
import { useConfirm } from "material-ui-confirm"; import { useConfirm } from "material-ui-confirm";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
import { useLang } from "services/lang";
export const CollectionNodeElement: FC<PropsWithChildren<CollectionNodeProps>> = export const CollectionNodeElement: FC<PropsWithChildren<CollectionNodeProps>> =
({ ({
@@ -27,6 +28,7 @@ export const CollectionNodeElement: FC<PropsWithChildren<CollectionNodeProps>> =
title, title,
children, children,
}) => { }) => {
const lang = useLang();
const color = convertNodeTypeToSequenceNodeColor(collectionType); const color = convertNodeTypeToSequenceNodeColor(collectionType);
const nodeColor = useSequenceNodeColor(color); const nodeColor = useSequenceNodeColor(color);
const confirm = useConfirm(); const confirm = useConfirm();
@@ -55,14 +57,19 @@ export const CollectionNodeElement: FC<PropsWithChildren<CollectionNodeProps>> =
}) })
.then(() => { .then(() => {
onDelete(); onDelete();
snackbr.enqueueSnackbar("Deleted.", { snackbr.enqueueSnackbar(lang.get("DELETED"), {
variant: "info", variant: "info",
}); });
}) })
.catch(() => .catch(() =>
snackbr.enqueueSnackbar(`Did not delete ${trueTile}.`, { snackbr.enqueueSnackbar(
variant: "info", lang.get("NOT_DELETED_THING", {
}) item: trueTile,
}),
{
variant: "info",
}
)
); );
}} }}
borderless borderless
@@ -1,7 +1,6 @@
import React, { FC } from "react"; import React, { FC } from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react"; import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page"; import { MockPage } from "components/Page";
import { CollectionNode } from "./CollectionNode";
import { DAGGraphBoard } from "components/DAGGraph/board"; import { DAGGraphBoard } from "components/DAGGraph/board";
import { CollectionNodeMaker } from "./index"; import { CollectionNodeMaker } from "./index";
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants"; import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
@@ -19,7 +18,7 @@ type DemoProps = {
}; };
const Demo: FC<DemoProps> = (args) => { const Demo: FC<DemoProps> = (args) => {
return ( return (
<Page> <MockPage>
<DAGGraphBoard <DAGGraphBoard
closeModal={() => {}} closeModal={() => {}}
state={{ state={{
@@ -64,7 +63,7 @@ const Demo: FC<DemoProps> = (args) => {
}, },
}} }}
/> />
</Page> </MockPage>
); );
}; };
@@ -84,7 +83,7 @@ export const Colors: ComponentStory<typeof Demo> = (args) => <Demo {...args} />;
export const Empty: ComponentStory<typeof Demo> = (args) => { export const Empty: ComponentStory<typeof Demo> = (args) => {
return ( return (
<Page> <MockPage>
<DAGGraphBoard <DAGGraphBoard
closeModal={() => {}} closeModal={() => {}}
state={{ state={{
@@ -124,7 +123,7 @@ export const Empty: ComponentStory<typeof Demo> = (args) => {
}, },
}} }}
/> />
</Page> </MockPage>
); );
}; };
@@ -135,7 +134,7 @@ Empty.args = {
export const ReturnTarget: ComponentStory<typeof Demo> = (args) => { export const ReturnTarget: ComponentStory<typeof Demo> = (args) => {
return ( return (
<Page> <MockPage>
<DAGGraphBoard <DAGGraphBoard
closeModal={() => {}} closeModal={() => {}}
state={{ state={{
@@ -222,7 +221,7 @@ export const ReturnTarget: ComponentStory<typeof Demo> = (args) => {
}, },
}} }}
/> />
</Page> </MockPage>
); );
}; };
@@ -123,7 +123,7 @@
position: absolute; position: absolute;
top: -1em; top: -1em;
left: -1em; left: -1em;
background-color: var(--mui-common-black); background-color: var(--mui-background-paper);
border-color: var(--mui-grey-400); border-color: var(--mui-grey-400);
border-style: solid; border-style: solid;
border-width: 0.5px; border-width: 0.5px;
@@ -1,6 +1,6 @@
import React from "react"; import React from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react"; import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page"; import { MockPage } from "components/Page";
import { SequenceNode } from "./SequenceNode"; import { SequenceNode } from "./SequenceNode";
import { DAGGraphBoard } from "components/DAGGraph/board"; import { DAGGraphBoard } from "components/DAGGraph/board";
import { SequenceNodeMaker } from "./index"; import { SequenceNodeMaker } from "./index";
@@ -21,7 +21,7 @@ export default {
const Template: ComponentStory<typeof SequenceNode> = (args) => { const Template: ComponentStory<typeof SequenceNode> = (args) => {
return ( return (
<Page> <MockPage>
<DAGGraphBoard <DAGGraphBoard
closeModal={() => {}} closeModal={() => {}}
state={{ state={{
@@ -46,13 +46,13 @@ const Template: ComponentStory<typeof SequenceNode> = (args) => {
}, },
}} }}
/> />
</Page> </MockPage>
); );
}; };
export const Colors: ComponentStory<typeof SequenceNode> = (args) => { export const Colors: ComponentStory<typeof SequenceNode> = (args) => {
return ( return (
<Page> <MockPage>
<DAGGraphBoard <DAGGraphBoard
closeModal={() => {}} closeModal={() => {}}
state={{ state={{
@@ -85,7 +85,7 @@ export const Colors: ComponentStory<typeof SequenceNode> = (args) => {
}, },
}} }}
/> />
</Page> </MockPage>
); );
}; };
@@ -16,6 +16,7 @@ import InputBoolean from "components/Inputs/Base/InputBoolean";
import { SpeedDial } from "components/SpeedDial"; import { SpeedDial } from "components/SpeedDial";
import { SequenceNodeElementProps } from "./types"; import { SequenceNodeElementProps } from "./types";
import { useSequenceNodeColor } from "./util"; import { useSequenceNodeColor } from "./util";
import { useLang } from "services/lang";
export const SequenceNodeElement: FC< export const SequenceNodeElement: FC<
PropsWithChildren<SequenceNodeElementProps> PropsWithChildren<SequenceNodeElementProps>
@@ -35,6 +36,7 @@ export const SequenceNodeElement: FC<
isClosed, isClosed,
setIsClosed, setIsClosed,
}) => { }) => {
const langStore = useLang();
const confirm = useConfirm(); const confirm = useConfirm();
const snackbr = useSnackbar(); const snackbr = useSnackbar();
const nodeColor = useSequenceNodeColor(color); const nodeColor = useSequenceNodeColor(color);
@@ -89,18 +91,21 @@ export const SequenceNodeElement: FC<
<IconButton <IconButton
onClick={() => { onClick={() => {
confirm({ confirm({
description: "Are you sure you want to delete this node?", description: langStore.get("CONFIRMATION_DELETE_THIS_NODE"),
}) })
.then(() => { .then(() => {
onXClick(); onXClick();
snackbr.enqueueSnackbar("Deleted.", { snackbr.enqueueSnackbar(langStore.get("DELETED"), {
variant: "info", variant: "info",
}); });
}) })
.catch(() => .catch(() =>
snackbr.enqueueSnackbar("Did not delete node.", { snackbr.enqueueSnackbar(
variant: "info", langStore.get("NOT_DELETED_NODE"),
}) {
variant: "info",
}
)
); );
}} }}
size="small" size="small"
+12 -5
View File
@@ -6,8 +6,9 @@ import { InputDevice } from "components/Inputs/AutoComplete/InputDevice";
import { InputDeviceCapabilties } from "components/Inputs/AutoComplete/InputDeviceCapabilties"; import { InputDeviceCapabilties } from "components/Inputs/AutoComplete/InputDeviceCapabilties";
import { InputEntity } from "components/Inputs/AutoComplete/InputEntities"; import { InputEntity } from "components/Inputs/AutoComplete/InputEntities";
import { cleanUpUndefined } from "utils/helpers"; import { cleanUpUndefined } from "utils/helpers";
import { DeviceBaseType, DeviceTypeCapability } from "haService/types"; import { DeviceBaseType, DeviceTypeCapability } from "services/ha/types";
import { AutomationDeviceState } from "types/automations/common"; import { AutomationDeviceState } from "types/automations/common";
import { useLang } from "services/lang";
export type DeviceEditorProps<DBT extends DeviceBaseType> = { export type DeviceEditorProps<DBT extends DeviceBaseType> = {
type: "action" | "condition" | "trigger"; type: "action" | "condition" | "trigger";
@@ -23,6 +24,8 @@ export function DeviceEditor<DBT extends DeviceBaseType>({
caps, caps,
options, options,
}: DeviceEditorProps<DBT>) { }: DeviceEditorProps<DBT>) {
// state
const langStore = useLang();
// aliases // aliases
const update = (upd: Partial<AutomationDeviceState & Record<string, any>>) => const update = (upd: Partial<AutomationDeviceState & Record<string, any>>) =>
setState( setState(
@@ -40,13 +43,13 @@ export function DeviceEditor<DBT extends DeviceBaseType>({
<> <>
<InputDevice <InputDevice
key="devices" key="devices"
label="Device" label={langStore.get("DEVICE")}
value={state.device_id ?? ""} value={state.device_id ?? ""}
onChange={(device_id) => setState({ device_id: device_id ?? "" })} onChange={(device_id) => setState({ device_id: device_id ?? "" })}
/> />
<InputAutoComplete <InputAutoComplete
key="action" key="action"
label="Action" label={langStore.get("ACTION")}
multiple={false} multiple={false}
value={actionId} value={actionId}
options={Object.keys(options).map((k) => options[k])} options={Object.keys(options).map((k) => options[k])}
@@ -67,7 +70,7 @@ export function DeviceEditor<DBT extends DeviceBaseType>({
{entities.length > 0 && ( {entities.length > 0 && (
<InputEntity <InputEntity
key={"entities" + state.device_id} key={"entities" + state.device_id}
label="Entity" label={langStore.get("ENTITY")}
value={state.entity_id ?? ""} value={state.entity_id ?? ""}
multiple={false} multiple={false}
onChange={(entity_id) => onChange={(entity_id) =>
@@ -85,7 +88,11 @@ export function DeviceEditor<DBT extends DeviceBaseType>({
/> />
)} )}
{Object.keys(options).length + entities.length === 0 && ( {Object.keys(options).length + entities.length === 0 && (
<>This device has no {type}s.</> <>
{langStore.get("WARNING_DEVICE_NO_TYPES", {
type: `${type}s`,
})}
</>
)} )}
</> </>
); );
@@ -1,35 +1,43 @@
import React, { FC } from "react"; import React, { FC } from "react";
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { ErrorBoundary } from "."; import { ErrorBoundary } from ".";
import { Page } from "components/Page";
import { makeStory } from "devUtils";
import { MockPage } from "components/Page";
import { ComponentStory } from "@storybook/react";
export default { const { make, componentMeta } = makeStory({
title: 'ErrorBoundary', Component: () => <div>Example</div>,
meta: {
title: "ErrorBoundary",
component: ErrorBoundary, component: ErrorBoundary,
parameters: { actions: { argTypesRegex: '^on.*' } }, },
args: { });
}
} as ComponentMeta<typeof ErrorBoundary>
export const ErrorThrown: ComponentStory<typeof ErrorBoundary> = args => { export default componentMeta;
const BadComponent: FC = () => { export const Example = make({});
throw new Error("!!!")
}
return <Page>
<ErrorBoundary>
<BadComponent />
</ErrorBoundary>
</Page>
}
export const NoError: ComponentStory<typeof ErrorBoundary> = args => { export const ErrorThrown: ComponentStory<typeof ErrorBoundary> = (args) => {
const GoodComponent: FC = () => { const BadComponent: FC = () => {
return <span>All Good.</span> throw new Error("!!!");
} };
return <Page> return (
<ErrorBoundary> <MockPage>
<GoodComponent /> <ErrorBoundary>
</ErrorBoundary> <BadComponent />
</Page> </ErrorBoundary>
} </MockPage>
);
};
export const NoError: ComponentStory<typeof ErrorBoundary> = (args) => {
const GoodComponent: FC = () => {
return <span>All Good.</span>;
};
return (
<MockPage>
<ErrorBoundary>
<GoodComponent />
</ErrorBoundary>
</MockPage>
);
};
Loaded 100 of 192 files, more files were not shown because too many files have changed in this diff. Show more