Skip to content

Commit

Permalink
fix(init): fix js and yaml load
Browse files Browse the repository at this point in the history
  • Loading branch information
Lebe1ge committed Oct 15, 2024
1 parent a3ce83d commit 2a3a51b
Show file tree
Hide file tree
Showing 5 changed files with 94 additions and 30 deletions.
61 changes: 35 additions & 26 deletions custom_components/linus_dashboard/__init__.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
"""Linus Dashboard integration for Home Assistant."""

import logging
import os
from pathlib import Path

from homeassistant.components.frontend import (
add_extra_js_url,
async_register_built_in_panel,
async_remove_panel,
)
from homeassistant.components.http import StaticPathConfig
from homeassistant.components.lovelace import _register_panel
from homeassistant.components.lovelace.dashboard import LovelaceYAML
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant

from custom_components.linus_dashboard import utils
from custom_components.linus_dashboard.const import URL_PANEL

_LOGGER = logging.getLogger(__name__)

DOMAIN = "linus_dashboard"
Expand All @@ -20,47 +24,52 @@ async def async_setup(hass: HomeAssistant, _config: dict) -> bool:
"""Set up Linus Dashboard."""
_LOGGER.info("Setting up Linus Dashboard")
hass.data.setdefault(DOMAIN, {})

return True


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Linus Dashboard from a config entry."""
_LOGGER.info("Setting up Linus Dashboard entry")

# Path to the YAML file for the dashboard
dashboard_path = os.path.join(
hass.config.path(f"custom_components/{DOMAIN}/lovelace/ui-lovelace.yaml")
)

# Path to the JavaScript file for the strategy
strategy_js_url = f"/{DOMAIN}/js/linus-strategy.js"
strategy_js_path = hass.config.path(
f"custom_components/{DOMAIN}/js/linus-strategy.js"
strategy_js_path = Path(__file__).parent / "js/linus-strategy.js"

await hass.http.async_register_static_paths(
[
StaticPathConfig(
strategy_js_url, str(strategy_js_path), cache_headers=False
),
]
)
hass.http.register_static_path(strategy_js_url, strategy_js_path, False)

# Add the JavaScript file as a frontend resource
add_extra_js_url(hass, strategy_js_url)
# fix from https://github.com/hmmbob/WebRTC/blob/a0783df2e5426118599edc50bfd0466b1b0f0716/custom_components/webrtc/__init__.py#L83
version = getattr(hass.data["integrations"][DOMAIN], "version", 0)
await utils.init_resource(hass, f"/{DOMAIN}/js/linus-strategy.js", str(version))

# Use a unique name for the panel to avoid conflicts
sidebar_title = "Linus Dashboard"
sidebar_icon = "mdi:bow-tie"
panel_url = DOMAIN
async_register_built_in_panel(
hass,
panel_url,
sidebar_title,
sidebar_icon,
config={
"mode": "yaml",
"icon": sidebar_icon,
"title": sidebar_title,
"filename": dashboard_path,
},
filename_path = Path(__file__).parent / "lovelace/ui-lovelace.yaml"

dashboard_config = {
"mode": "yaml",
"icon": sidebar_icon,
"title": sidebar_title,
"filename": str(filename_path),
"show_in_sidebar": True,
"require_admin": False,
}

hass.data["lovelace"]["dashboards"][URL_PANEL] = LovelaceYAML(
hass, URL_PANEL, dashboard_config
)

_register_panel(hass, URL_PANEL, "yaml", dashboard_config, False)

# Store the entry
hass.data[DOMAIN][entry.entry_id] = panel_url
hass.data[DOMAIN][entry.entry_id] = URL_PANEL
return True


Expand Down
6 changes: 4 additions & 2 deletions custom_components/linus_dashboard/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

LOGGER: Logger = getLogger(__package__)

NAME = "Linus Dahboard"
DOMAIN = "linus_dashboard"
ATTRIBUTION = "Data provided by http://jsonplaceholder.typicode.com/"

VERSION = "0.0.1"
ICON = "mdi:bow-tie"

URL_PANEL = "linus_dashboard_panel"
53 changes: 53 additions & 0 deletions custom_components/linus_dashboard/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""Utility functions for Linus Dashboard custom components."""

import logging

from homeassistant.components.frontend import add_extra_js_url
from homeassistant.components.lovelace.resources import ResourceStorageCollection
from homeassistant.core import HomeAssistant

_LOGGER = logging.getLogger(__name__)


async def init_resource(hass: HomeAssistant, url: str, ver: str) -> bool:
"""
Add extra JS module for lovelace mode YAML and new lovelace resource
for mode GUI. It's better to add extra JS for all modes, because it has
random url to avoid problems with the cache. But chromecast don't support
extra JS urls and can't load custom card.
"""

resources: ResourceStorageCollection = hass.data["lovelace"]["resources"]
# force load storage
await resources.async_get_info()

url2 = f"{url}?v={ver}"

for item in resources.async_items():
if not item.get("url", "").startswith(url):
continue

# no need to update
if item["url"].endswith(ver):
return False

_LOGGER.debug(f"Update lovelace resource to: {url2}")

if isinstance(resources, ResourceStorageCollection):
await resources.async_update_item(
item["id"], {"res_type": "module", "url": url2}
)
else:
# not the best solution, but what else can we do
item["url"] = url2

return True

if isinstance(resources, ResourceStorageCollection):
_LOGGER.debug(f"Add new lovelace resource: {url2}")
await resources.async_create_item({"res_type": "module", "url": url2})
else:
_LOGGER.debug(f"Add extra JS module: {url2}")
add_extra_js_url(hass, url2)

return True
2 changes: 1 addition & 1 deletion hacs.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "Linus dashboard",
"hide_default_branch": true,
"homeassistant": "2024.6.0",
"homeassistant": "2024.10.0",
"render_readme": true
}
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
colorlog==6.8.2
homeassistant==2024.6.0
homeassistant==2024.10.2
pip>=21.3.1
ruff==0.6.7

0 comments on commit 2a3a51b

Please sign in to comment.