Initial Commit

This commit is contained in:
2026-06-11 11:50:50 -04:00
commit d4a69c41be
2748 changed files with 80489 additions and 0 deletions
+377
View File
@@ -0,0 +1,377 @@
import asyncio
from homeassistant.components import frontend, http, panel_custom
from homeassistant.const import (
CONF_DEFAULT,
CONF_HEADERS,
CONF_ICON,
CONF_MODE,
CONF_NAME,
CONF_PATH,
CONF_URL,
)
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
import os
import re
import time
from typing import TYPE_CHECKING, cast
import voluptuous as vol
from yarl import URL
from .const import (
DOMAIN,
LOGGER as _LOGGER,
API_BASE,
URL_BASE,
WorkMode,
UIMode,
RewriteMode,
ConfMode,
)
from .config import IngressStore, IngressCfg, RewriteCfg
from .ingress import IngressView, std_header_name
from .websocket_api import async_register_websocket_api
if TYPE_CHECKING:
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.config_entries import ConfigEntry
from typing import Any, Final, TypedDict
from .client import IngressClient
class DomainData(TypedDict):
client: IngressClient
config: IngressStore
panels: set[str]
VERSION = ""
CONNECT_TIMEOUT = 20
CONF_TITLE: "Final" = "title"
CONF_MATCH: "Final" = "match"
CONF_REPLACE: "Final" = "replace"
CONF_INDEX: "Final" = "index"
CONF_PARENT: "Final" = "parent"
CONF_WORK_MODE: "Final" = "work_mode"
CONF_UI_MODE: "Final" = "ui_mode"
CONF_REWRITE: "Final" = "rewrite"
CONF_COOKIE_NAME: "Final" = "cookie_name"
CONF_EXPIRE_TIME: "Final" = "expire_time"
CONF_STATIC_TOKEN: "Final" = "static_token"
CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: cv.schema_with_slug_keys(
vol.Schema(
{
vol.Optional(panel_custom.CONF_REQUIRE_ADMIN, default=False): cv.boolean,
vol.Optional(CONF_TITLE): cv.string,
vol.Optional(CONF_ICON): cv.icon,
vol.Required(CONF_URL): vol.Any(
cv.string,
vol.Schema(
{
vol.Required(CONF_MATCH): cv.string,
vol.Required(CONF_REPLACE): cv.string,
vol.Required(CONF_DEFAULT): cv.string,
}
),
),
vol.Optional(CONF_INDEX, default=""): cv.string,
vol.Optional(CONF_PARENT): cv.string,
vol.Optional(CONF_WORK_MODE, default=WorkMode.INGRESS): vol.In(list(WorkMode)),
vol.Optional(CONF_UI_MODE, default=UIMode.NORMAL): vol.In(list(UIMode)),
vol.Optional(CONF_HEADERS): vol.Schema({str: cv.string}),
vol.Optional(CONF_REWRITE): [
vol.Schema(
{
vol.Required(CONF_MODE): vol.In(list(RewriteMode)),
vol.Optional(CONF_PATH): cv.string,
vol.Optional(CONF_NAME): cv.string,
vol.Required(CONF_MATCH): cv.string,
vol.Required(CONF_REPLACE): cv.string,
}
)
],
vol.Optional(CONF_COOKIE_NAME): cv.string,
vol.Optional(CONF_STATIC_TOKEN): cv.string,
vol.Optional(CONF_EXPIRE_TIME): cv.positive_int,
}
)
),
},
extra=vol.ALLOW_EXTRA,
)
async def async_setup(hass: "HomeAssistant", config) -> bool:
# init once
data = await _async_init(hass)
# init config entry
entries = hass.config_entries.async_entries(DOMAIN)
if not entries:
hass.async_create_task(
hass.config_entries.flow.async_init(DOMAIN, context={"source": "import"})
)
# init yaml mode
if not entries or entries[0].data[CONF_MODE] == ConfMode.YAML:
await setup_domain(hass, data, config)
return True
async def async_setup_entry(hass: "HomeAssistant", entry: "ConfigEntry") -> bool:
if entry.data[CONF_MODE] != ConfMode.AGENT:
return True
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from .client import create_client
from .client.exceptions import ClientException
# init client
client = create_client(hass, entry.data[CONF_URL], async_get_clientsession(hass))
client.on_client_event("ready", on_remote_ready)
# get config
config = None
try:
async with asyncio.timeout(CONNECT_TIMEOUT):
await client.connect()
config = await get_remote_config(hass, client)
except ClientException as err:
raise ConfigEntryNotReady("Failed to connect to ingress agent") from err
except Exception as err:
_LOGGER.exception("Failed to connect to ingress agent")
raise ConfigEntryNotReady("Unknown error connecting to the ingress agent") from err
finally:
if config is None:
client.disconnect()
entry.async_on_unload(
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, lambda e: client.disconnect())
)
# setup config
data: DomainData = hass.data[DOMAIN]
data["client"] = client
await setup_domain(hass, data, config)
return True
async def on_remote_ready(hass: "HomeAssistant", client: "IngressClient", _: "Any"):
await client.send_command({"type": "subscribe"})
async def get_remote_config(hass: "HomeAssistant", client: "IngressClient") -> dict[str, "Any"]:
# TODO
return {DOMAIN: {}}
async def async_unload_entry(hass: "HomeAssistant", entry: "ConfigEntry") -> bool:
client: IngressClient
if client := hass.data[DOMAIN].pop("client", None):
client.disconnect()
return True
async def setup_domain(hass: "HomeAssistant", data: "DomainData", config) -> None:
# clean
for name in data["panels"]:
frontend.async_remove_panel(hass, name)
data["panels"].clear()
data["config"].clear()
# parse config
config, panels = _parse_config(hass, config)
# add ingress
now = int(time.time())
for cfg in config:
data["config"].add_ingress(cfg, now)
# add panels
data["panels"].update(panels)
await asyncio.gather(*(panel_custom.async_register_panel(hass, **v) for v in panels.values()))
async def _async_init(hass: "HomeAssistant") -> "DomainData":
"""Init DomainData and service once."""
data: DomainData = hass.data.setdefault(DOMAIN, {})
if "config" not in cast(dict, data):
from homeassistant.const import SERVICE_RELOAD
from homeassistant.helpers.reload import async_integration_yaml_config
from homeassistant.helpers.service import async_register_admin_service
# get version
global VERSION
VERSION = await get_version(hass, DOMAIN)
# register static url
static_dir = os.path.join(os.path.dirname(__file__), "www")
await _async_register_static_paths(hass.http, [(URL_BASE, static_dir, False)])
# register ingress view
config = IngressStore()
hass.http.register_view(IngressView(hass, config, async_get_clientsession(hass)))
# register websocket api
await async_register_websocket_api(hass)
# register reload config
async def reload_config(call: "ServiceCall"):
data: DomainData = hass.data[DOMAIN]
if client := data.get("client"):
config = await get_remote_config(hass, client)
else:
config = await async_integration_yaml_config(hass, DOMAIN)
await setup_domain(hass, data, config or {})
hass.bus.async_fire(f"event_{DOMAIN}_reloaded", context=call.context)
async_register_admin_service(hass, DOMAIN, SERVICE_RELOAD, reload_config)
# init data
data.update(config=config, panels=set())
return data
async def get_version(hass: "HomeAssistant", domain: str) -> str:
version = "unknown"
try:
from homeassistant.loader import async_get_integration
integration = await async_get_integration(hass, domain)
version = integration.version or version
except Exception:
pass
return version
async def _async_register_static_paths(hass_http: "http.HomeAssistantHTTP", configs):
if hasattr(hass_http, "async_register_static_paths"):
await hass_http.async_register_static_paths([http.StaticPathConfig(*c) for c in configs])
else:
for c in configs:
hass_http.register_static_path(*c)
def _parse_config(
hass: "HomeAssistant", config
) -> tuple[list[IngressCfg], dict[str, dict[str, "Any"]]]:
cfgs: list[IngressCfg] = []
panels: dict[str, dict[str, Any]] = {}
ingresses, children = {}, []
placeholder = "$http_x_ingress_path"
entrypoint = f"{URL_BASE}/entrypoint.js?v={VERSION}"
for name, data in config.get(DOMAIN, {}).items():
cfg: dict[str, Any]
ingress_cfg = None
work_mode = data[CONF_WORK_MODE]
url, front_url = data[CONF_URL], {}
if isinstance(url, dict):
url, front_url = url[CONF_DEFAULT], url
if work_mode not in (WorkMode.IFRAME, WorkMode.CUSTOM):
# init backend config
ingress_cfg = dict(mode=work_mode, name=name, entry=name)
ingress_path, sub_path = f"{API_BASE}/{name}", ""
if work_mode != WorkMode.HASSIO:
url = url.replace(placeholder, ingress_path).rstrip("/")
if "://" not in url:
url = f"http://{url}"
pos = url.find("/", url.index("://") + 3)
if pos > 0:
url, sub_path = url[:pos], url[pos:]
headers = {}
for k, v in data.get(CONF_HEADERS, {}).items():
headers[std_header_name(k)] = v.replace(placeholder, ingress_path)
ingress_cfg.update(
origin=URL(url),
sub_path=sub_path,
headers=headers,
cookie_name=data.get(CONF_COOKIE_NAME),
expire_time=data.get(CONF_EXPIRE_TIME),
static_token=data.get(CONF_STATIC_TOKEN),
)
url += sub_path
if work_mode in (WorkMode.INGRESS, WorkMode.SUBAPP):
rewrites: list[RewriteCfg] = []
if rewrite := data.get(CONF_REWRITE):
ingress_path = re.escape(ingress_path)
for item in rewrite:
item[CONF_REPLACE] = item[CONF_REPLACE].replace(
placeholder, ingress_path
)
rewrites.append(RewriteCfg(**item))
ingress_cfg.update(rewrites=rewrites)
ingress_cfg = IngressCfg(**ingress_cfg)
cfgs.append(ingress_cfg)
# init frontend config
cfg = {"token": ingress_cfg.token, "index": data[CONF_INDEX].lstrip("/")}
if work_mode == WorkMode.AUTH:
cfg["url"] = front_url
cfg["field"] = ingress_cfg.cookie_name
elif work_mode == WorkMode.HASSIO:
cfg["addon"] = url
elif work_mode == WorkMode.INGRESS:
ingresses[name] = ingress_cfg
else:
cfg = {"url": front_url}
if data[CONF_INDEX]:
url = url.rstrip("/")
cfg["index"] = data[CONF_INDEX].lstrip("/")
if front_url.get(CONF_MATCH):
front_url[CONF_DEFAULT] = url
elif "url" in cfg:
cfg["url"] = url
cfg["ui_mode"] = work_mode if work_mode == WorkMode.CUSTOM else data[CONF_UI_MODE]
title, icon = data.get(CONF_TITLE), data.get(CONF_ICON)
if parent := data.get(CONF_PARENT):
if name.startswith(parent) and name[len(parent) : len(parent) + 1] == "_":
name = name[len(parent) + 1 :]
if ingress_cfg:
ingress_cfg.entry = f"{parent}/{name}"
if title:
cfg["title"] = title
if icon:
cfg["icon"] = icon
children.append((name, parent, cfg, ingress_cfg))
continue
panels[name] = dict(
webcomponent_name="ha-panel-ingress",
js_url=entrypoint,
frontend_url_path=name,
sidebar_title=title,
sidebar_icon=icon,
require_admin=data[panel_custom.CONF_REQUIRE_ADMIN],
embed_iframe=False,
config=cfg,
)
for child, parent, cfg, ingress_cfg in children:
if ingress_cfg and ingress_cfg.mode == WorkMode.SUBAPP:
if parent not in ingresses:
_LOGGER.error(
"parent ingress[%s] not found, skip subapp[%s]!", parent, ingress_cfg.name
)
continue
# ingress: add subapp to parent's sub_apps
pi_cfg = ingresses[parent]
if not pi_cfg.sub_apps:
pi_cfg.sub_apps = []
pi_cfg.sub_apps.append(ingress_cfg)
# panel: use parent's parent if parent is a child panel
if parent not in panels:
parent = pi_cfg.entry.partition("/")
parent, child = parent[0], f"{parent[2]}-{child}"
ingress_cfg.entry = f"{parent}/{child}"
if parent not in panels:
_LOGGER.error("parent panel[%s] not found, skip child panel[%s]!", parent, child)
continue
# panel: add child to parent's children
panels[parent]["config"].setdefault("children", {})[child] = cfg
return cfgs, panels
@@ -0,0 +1,8 @@
import aiohttp
from .auth import IngressAuth
from .client import IngressClient, T
def create_client(ctx: T, server_url: str, websession: aiohttp.ClientSession) -> IngressClient[T]:
return IngressClient(ctx, IngressAuth(server_url, websession))
+22
View File
@@ -0,0 +1,22 @@
import aiohttp
class IngressAuth:
def __init__(self, server_url: str, websession: aiohttp.ClientSession) -> None:
self._server_url = server_url
self._websession = websession
@property
def ws_url(self):
return f"ws{self._server_url[4:]}/ws"
@property
def websession(self):
return self._websession
@property
def access_token(self):
return ""
async def refresh(self):
pass
+239
View File
@@ -0,0 +1,239 @@
import asyncio
from typing import Any, Generic, TypeVar, TYPE_CHECKING, cast
from .connection import WebsocketConnection
from .exceptions import (
InvalidMessage,
InvalidAuth,
ConnectionLost,
ClientException,
ResultException,
)
from .helpers import LOGGER, json_loads, json_dumps, to_dict
if TYPE_CHECKING:
from collections.abc import Callable, Awaitable, AsyncGenerator
from .auth import IngressAuth
type ClientEventListener[T] = Callable[[T, "IngressClient", Any], Awaitable[None] | None]
type BinaryHandler[T] = Callable[[T, "IngressClient", bytes], Awaitable[None] | None]
type EventHandler[T] = Callable[[T, "IngressClient", dict[str, Any]], Awaitable[None] | None]
type EventSubscriber[T] = tuple[EventHandler[T], tuple[str] | None, tuple[str] | None]
MSG_TYPE_AUTH = "auth"
MSG_TYPE_AUTH_OK = "auth_ok"
MSG_TYPE_AUTH_INVALID = "auth_invalid"
MSG_TYPE_RESULT = "result"
MSG_TYPE_EVENT = "event"
T = TypeVar("T")
class IngressClient(Generic[T]):
"""Manage an Ingress server remotely."""
def __init__(self, ctx: T, auth: "IngressAuth"):
self._ctx = ctx
self.auth = auth
self._conn = WebsocketConnection(auth.ws_url, auth.websession)
self._event_listeners: dict[str, list[ClientEventListener[T]]] = {}
self._binary_handlers: dict[int, BinaryHandler[T]] = {}
self._subscribers: list[EventSubscriber[T]] = []
self._result_futures: dict[int | None, asyncio.Future[Any]] = {}
self._receive_task: asyncio.Task | None = None
def on_client_event(
self, event_type: str, callback: "ClientEventListener[T]"
) -> "Callable[[], None]":
listeners = self._event_listeners.setdefault(event_type, [])
listeners.append(callback)
return lambda: listeners.remove(callback)
def _fire_event(self, event_type: str, event_data: Any = None) -> None:
async def fire_event():
for callback in self._event_listeners.get(event_type, []):
if asyncio.iscoroutinefunction(callback):
await callback(self._ctx, self, event_data)
else:
callback(self._ctx, self, event_data)
self._loop.create_task(fire_event())
def register_binary(self, id: int, handler: "BinaryHandler[T]"):
if handler:
self._binary_handlers[id] = handler
else:
self._binary_handlers.pop(id, None)
def subscribe(
self,
cb_func: "EventHandler[T]",
ev_type: str | tuple[str] | None = None,
ev_id: str | tuple[str] | None = None,
) -> "Callable[[], None]":
"""Add callback to event listeners. Returns function to remove the listener."""
subscriber: EventSubscriber[T] = (
cb_func,
((ev_type,) if isinstance(ev_type, str) else ev_type),
((ev_id,) if isinstance(ev_id, str) else ev_id),
)
self._subscribers.append(subscriber)
return lambda: self._subscribers.remove(subscriber)
def _handle_event(self, msg: dict[str, Any]) -> None:
async def handle_event():
ev_type, ev_id = msg.get("ev_type"), msg.get("ev_id")
for cb_func, ev_types, ev_ids in self._subscribers:
if ev_types is not None and ev_type not in ev_types:
continue
if ev_ids is not None and ev_id not in ev_ids:
continue
if asyncio.iscoroutinefunction(cb_func):
await cb_func(self._ctx, self, msg)
else:
cb_func(self._ctx, self, msg)
self._loop.create_task(handle_event())
async def receive_message(self) -> "AsyncGenerator[dict[str, Any]]":
"""Receive the next message from the server."""
try:
while True:
if not (data := await self._conn.receive_message()):
continue
if not isinstance(data, bytes):
break
if not (handler := self._binary_handlers.get(data[0])):
if data[0] in b"[{":
break
raise InvalidMessage(f"Received invalid binary: {data[0]}")
handler(self._ctx, self, data[1:])
msg = json_loads(data)
except (TypeError, ValueError) as err:
raise InvalidMessage(f"Received invalid json: {err}") from err
for msg in msg if isinstance(msg, list) else [msg]:
if not isinstance(msg, dict) or not msg.get("type"):
LOGGER.warning("Received invalid msg: %s", msg)
continue
LOGGER.debug("Received message: %s", msg)
yield cast(dict[str, Any], msg)
async def send_message(self, obj: Any) -> None:
"""Send a message to the server."""
msg = json_dumps(obj)
LOGGER.debug("Publishing message: %s", msg)
await self._conn.send_message(msg)
async def _connect(self) -> bool:
"""Connect to the server."""
if not (await self._conn.connect()):
return False
server_info = None
try:
await self.send_message({"type": MSG_TYPE_AUTH, "token": self.auth.access_token})
while not self._stop_called and server_info is None:
async for msg in self.receive_message():
msg_type = msg["type"]
if msg_type == MSG_TYPE_AUTH_OK:
server_info = msg
break
elif msg_type == MSG_TYPE_AUTH_INVALID:
raise InvalidAuth
finally:
if server_info is None:
await self._conn.disconnect()
self._binary_handlers.clear()
self._msg_id = 0
return True
async def reconnect(self) -> None:
for future in self._result_futures.values():
future.set_exception(ConnectionLost)
self._result_futures.clear()
self._fire_event("disconnected")
while not self._stop_called:
await self._conn.disconnect()
try:
await self._connect()
self._fire_event("ready")
break
except InvalidAuth as err:
raise
except ClientException:
await asyncio.sleep(5)
async def connect(self) -> bool:
async def receive_task():
client_event = None
try:
while not self._stop_called:
try:
async for msg in self.receive_message():
await self._handle_message(msg)
except InvalidMessage as err:
LOGGER.warning(err)
except ConnectionLost:
await self.reconnect()
except InvalidAuth as err:
client_event = ("reconnect-error", err)
finally:
await self._conn.disconnect()
self._receive_task = None
if client_event:
self._fire_event(*client_event)
if self._receive_task is not None:
return False
self._stop_called = False
await self._connect()
self._loop = asyncio.get_running_loop()
self._receive_task = self._loop.create_task(receive_task())
self._fire_event("ready")
return True
def disconnect(self):
"""Disconnect the client."""
self._stop_called = True
for future in self._result_futures.values():
future.cancel()
self._result_futures.clear()
async def send_command(
self, cmd: Any, wait: bool = True, return_exceptions: bool = False
) -> Any | list[Any] | None:
is_list = isinstance(cmd, (list, tuple))
msgs = [to_dict(i) for i in cmd] if is_list else [to_dict(cmd)]
futures: list[asyncio.Future[Any]] = []
for msg in msgs:
if msg.get("type") in (MSG_TYPE_RESULT, MSG_TYPE_EVENT):
continue
self._msg_id += 1
msg["id"] = self._msg_id
if wait:
futures.append(self._loop.create_future())
self._result_futures[msg["id"]] = futures[-1]
await self.send_message(msgs[0] if len(msgs) == 1 else msgs)
if wait:
result = await asyncio.gather(*futures, return_exceptions=return_exceptions)
return result if is_list else result[0]
async def _handle_message(self, msg: dict[str, Any]):
msg_type = msg["type"]
if msg_type == MSG_TYPE_RESULT:
future = self._result_futures.pop(msg.get("id"), None)
if future is None:
pass
elif not msg.get("fail"):
future.set_result(msg.get("result"))
else:
err = msg.get("error", {})
future.set_exception(ResultException(err.get("code"), err.get("msg")))
elif msg_type == MSG_TYPE_EVENT:
self._handle_event(msg)
@@ -0,0 +1,70 @@
import aiohttp
from aiohttp import WSMsgType
from typing import cast
from .exceptions import CannotConnect, ConnectionLost, InvalidMessage
from .helpers import LOGGER
class WebsocketConnection:
"""Websocket connection to server."""
def __init__(self, server_url: str, websession: aiohttp.ClientSession):
self._server_url = server_url
self._websession = websession
self._client: aiohttp.ClientWebSocketResponse | None = None
@property
def connected(self) -> bool:
"""Return if we're currently connected."""
return self._client is not None and not self._client.closed
async def connect(self) -> bool:
"""Connect to the websocket server."""
if self.connected:
return False
LOGGER.debug("Trying to connect")
try:
self._client = await self._websession.ws_connect(
self._server_url, heartbeat=55, compress=15, max_msg_size=0
)
except (aiohttp.WSServerHandshakeError, aiohttp.ClientError) as err:
raise CannotConnect(err) from err
return True
async def disconnect(self) -> bool:
"""Disconnect the client."""
LOGGER.debug("Closing client connection")
if self._client is None:
return False
await self._client.close()
self._client = None
return True
async def receive_message(self) -> str | bytes:
"""Receive the next message from the server (or raise on error)."""
assert self._client
ws_msg = await self._client.receive()
if ws_msg.type == WSMsgType.TEXT:
return cast(str, ws_msg.data)
elif ws_msg.type == WSMsgType.BINARY:
return cast(bytes, ws_msg.data)
elif ws_msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):
raise ConnectionLost
elif ws_msg.type == WSMsgType.ERROR:
raise ConnectionLost(ws_msg.data)
else:
raise InvalidMessage(f"Received unknown type message: {ws_msg.type}")
async def send_message(self, msg: str | bytes, binary: bool = False) -> None:
"""Send a message to the server."""
if not self.connected:
raise ConnectionLost
assert self._client
await self._client.send_frame(
msg.encode() if isinstance(msg, str) else msg,
WSMsgType.BINARY if binary else WSMsgType.TEXT,
)
@@ -0,0 +1,33 @@
"""Client-specific exceptions."""
class ClientException(Exception):
"""Generic exception."""
def __init__(self, error: str | Exception | None = None):
if error is not None:
super().__init__(error if isinstance(error, str) else str(error))
class CannotConnect(ClientException):
"""Exception raised when failed to connect the client."""
class InvalidAuth(ClientException):
"""Exception raised when authenticate failed."""
class ConnectionLost(ClientException):
"""Exception raised when the connection is lost."""
class InvalidMessage(ClientException):
"""Exception raised when an invalid message is received."""
class ResultException(Exception):
"""Result exception."""
def __init__(self, code: str, msg: str) -> None:
self.code = code
self.msg = msg
@@ -0,0 +1,53 @@
from dataclasses import is_dataclass, asdict
import logging
import orjson
from typing import Any
# logger
LOGGER = logging.getLogger(__package__)
# json helpers
def omit_none(obj: Any) -> Any:
"""Omit dict none fields."""
return _omit_none(obj) if isinstance(obj, dict) else obj
def _omit_none(obj: dict):
for k in [k for k, v in obj.items() if v is None]:
del obj[k]
for v in obj.values():
if isinstance(v, dict):
_omit_none(v)
return obj
def to_dict(obj: Any) -> dict:
"""Convert obj(msg) to dict."""
if isinstance(obj, dict):
pass
elif callable(to_dict := getattr(obj, "to_dict", None)):
obj = to_dict()
elif is_dataclass(obj) and not isinstance(obj, type):
obj = asdict(obj)
else:
raise TypeError(f"Type can not to_dict: {type(obj).__name__}")
return _omit_none(obj)
def _json_dumps_default(obj: Any) -> Any:
"""orjson.dumps default handler."""
if callable(to_dict := getattr(obj, "to_dict", None)):
return omit_none(to_dict())
if is_dataclass(obj) and not isinstance(obj, type):
return _omit_none(asdict(obj))
raise TypeError(f"Type is not JSON serializable: {type(obj).__name__}")
json_loads = orjson.loads
def json_dumps(obj: Any, option: int = 0) -> bytes:
option |= orjson.OPT_PASSTHROUGH_DATACLASS
return orjson.dumps(omit_none(obj), default=_json_dumps_default, option=option)
+167
View File
@@ -0,0 +1,167 @@
import base64
from homeassistant.components.frontend import EVENT_PANELS_UPDATED # type: ignore
import os
import re
import time
from typing import TYPE_CHECKING
from .const import LOGGER as _LOGGER
if TYPE_CHECKING:
from homeassistant.core import HomeAssistant
from typing import TypedDict
from yarl import URL
from .const import WorkMode, RewriteMode
class Token(TypedDict):
value: str
expire: int
class UserInfo(TypedDict):
id: str
name: str | None
username: str | None
class RewriteCfg:
mode: "RewriteMode"
path = ""
name = ""
match: str
replace: str
def __init__(self, **kwargs):
self.__dict__.update(
(k, v) for k, v in kwargs.items() if v is not None and v != getattr(self, k, None)
)
class IngressCfg:
mode: "WorkMode"
name: str
entry: str
origin: "URL"
sub_path = ""
headers = {}
cookie_name = "ingress_token"
_cookie_name_re = None
expire_time = 3600
static_token = ""
rewrites: list[RewriteCfg] = []
sub_apps: list["IngressCfg"] = []
def __init__(self, **kwargs):
self.__dict__.update(
(k, v) for k, v in kwargs.items() if v is not None and v != getattr(self, k, None)
)
self.token: "Token" = {"value": "", "expire": 0}
def remove_token_from_cookie(self, cookie):
if (cookie_re := self._cookie_name_re) is None:
cookie_re = _init_cookie_name_re(self.cookie_name)
self._cookie_name_re = cookie_re
cookie = cookie_re.sub("", cookie).strip("; ")
return USER_TOKEN_COOKIE_RE.sub("", cookie).strip("; ")
class IngressStore:
"""ingress configs."""
def __init__(self):
self._configs: dict[str, IngressCfg] = {}
self._tokens: dict[str, IngressCfg] = {}
self._user_tokens: dict[str, dict] = {}
def clear(self):
self._configs.clear()
self._tokens.clear()
self._user_tokens.clear()
def get(self, name: str) -> IngressCfg | None:
return self._configs.get(name)
def del_ingress(self, name: str) -> IngressCfg | None:
if cfg := self._configs.pop(name, None):
self._tokens.pop(cfg.token["value"], None)
return cfg
def add_ingress(self, cfg: IngressCfg, now: int):
self.del_ingress(cfg.name)
cfg.token["value"] = ""
self.new_token(cfg, now)
self._configs[cfg.name] = cfg
def new_token(self, cfg: IngressCfg, now: int) -> str:
if cfg.static_token:
token = f"t-{cfg.static_token}"
old = self._tokens.get(token)
if old and old is not cfg:
_LOGGER.error(
"static_token conflict with %s, use dynamic for %s!", old.name, cfg.name
)
del cfg.static_token
while not cfg.static_token:
token = base64.urlsafe_b64encode(os.urandom(33)).decode()
if token not in self._tokens:
break
tkcfg = cfg.token
self._tokens.pop(tkcfg.get("value"), None)
self._tokens[token] = cfg
tkcfg["value"] = token
tkcfg["expire"] = now + cfg.expire_time
return token
def check_token(
self, hass: "HomeAssistant", token: str, refresh=True
) -> tuple[IngressCfg | None, str]:
cfg = self._tokens.get(token)
if cfg and refresh:
# token valid, check refresh
now = int(time.time())
if now >= cfg.token["expire"]:
token = self.new_token(cfg, now)
hass.bus.async_fire(EVENT_PANELS_UPDATED)
return cfg, token
def generate_user_token(self, user_info: dict) -> str:
"""Generate a token associated with user info."""
now = int(time.time())
for token in [k for k, v in self._user_tokens.items() if now >= v["expire"]]:
self._user_tokens.pop(token, None)
while True:
token = base64.urlsafe_b64encode(os.urandom(33)).decode()
if token not in self._user_tokens:
break
self._user_tokens[token] = {"user_info": user_info, "expire": now + USER_TOKEN_VALIDITY}
return token
def check_user_token(self, token: str) -> "UserInfo | None":
"""Check if a token is valid and return associated user info."""
entry = self._user_tokens.get(token)
if not entry:
return None
now = int(time.time())
if now >= entry["expire"]:
# Token expired, remove it
self._user_tokens.pop(token, None)
return None
# Refresh expiration
entry["expire"] = now + USER_TOKEN_VALIDITY
return entry["user_info"]
def user_cookie_name(self) -> str:
return USER_TOKEN_COOKIE_NAME
def cookie_name(self, name: str) -> str:
cfg = self._configs.get(name)
return cfg.cookie_name if cfg else IngressCfg.cookie_name
def _init_cookie_name_re(cookie_name):
return re.compile(rf"(?:^|;\s*){re.escape(cookie_name)}=[^;]*(?=;|$)")
USER_TOKEN_VALIDITY = 300
USER_TOKEN_COOKIE_NAME = "ha_ingress_session"
USER_TOKEN_COOKIE_RE = _init_cookie_name_re(USER_TOKEN_COOKIE_NAME)
+88
View File
@@ -0,0 +1,88 @@
from homeassistant import config_entries
from homeassistant.const import CONF_MODE, CONF_URL
from typing import Any
import voluptuous as vol
from .const import DOMAIN, ConfMode
CONNECT_TIMEOUT = 10
DEFAULT_URL = "ha-ingress:8080"
DEFAULT_TITLE = "Ingress"
class IngressConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Ingress config flow."""
VERSION = 1
def __init__(self) -> None:
self._data = {}
async def async_step_user(self, user_input: dict[str, Any] | None = None):
"""Handle a flow initialized by the user."""
if user_input is not None:
self._data[CONF_MODE] = user_input[CONF_MODE]
if self._data[CONF_MODE] == ConfMode.AGENT:
return await self.async_step_my_agent()
return await self.async_step_my_setup()
conf_mode = self._data.get(CONF_MODE, ConfMode.AGENT)
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{vol.Required(CONF_MODE, default=conf_mode): vol.In(list(ConfMode))}
),
)
async def async_step_my_agent(self, user_input: dict[str, Any] | None = None):
errors = {}
url = self._data.get(CONF_URL, DEFAULT_URL)
if user_input is not None:
import asyncio
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .client import create_client
from .client.exceptions import ClientException, InvalidAuth
try:
# connect to validate the url
if not (url := user_input[CONF_URL].strip().rstrip("/")):
raise ClientException
if "://" not in url:
url = f"http://{url}"
client = create_client(None, url, async_get_clientsession(self.hass))
try:
async with asyncio.timeout(CONNECT_TIMEOUT):
await client.connect()
finally:
client.disconnect()
# url is valid
self._data[CONF_URL] = url
return await self.async_step_my_setup()
except InvalidAuth:
errors["base"] = "invalid_auth"
except ClientException as err:
errors["base"] = "cannot_connect"
return self.async_show_form(
step_id="my_agent",
data_schema=vol.Schema({vol.Required(CONF_URL, default=url): str}),
errors=errors,
)
async def async_step_my_setup(self):
if entries := self._async_current_entries():
entry = entries[0]
self.hass.config_entries.async_update_entry(entry, data=self._data)
await self.hass.config_entries.async_reload(entry.entry_id)
return self.async_abort(reason="reconfigure_successful")
return self.async_create_entry(title=DEFAULT_TITLE, data=self._data)
async def async_step_reconfigure(self, user_input: dict[str, Any] | None = None):
"""Handle a reconfiguration flow initialized by the user."""
self._data.update(self._get_reconfigure_entry().data)
return await self.async_step_user()
async def async_step_import(self, user_input: dict[str, Any] | None = None):
self._data[CONF_MODE] = ConfMode.YAML
return await self.async_step_my_setup()
+48
View File
@@ -0,0 +1,48 @@
"""Ingress const variables."""
try:
from enum import StrEnum # type: ignore
except ImportError:
from enum import Enum
class StrEnum(str, Enum):
pass
import logging
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Final
DOMAIN: "Final" = "ingress"
LOGGER: "Final" = logging.getLogger(__package__)
API_BASE: "Final" = "/api/ingress"
URL_BASE: "Final" = "/files/ingress"
class WorkMode(StrEnum):
INGRESS = "ingress"
SUBAPP = "subapp"
IFRAME = "iframe"
AUTH = "auth"
HASSIO = "hassio"
CUSTOM = "custom"
class UIMode(StrEnum):
NORMAL = "normal"
TOOLBAR = "toolbar"
REPLACE = "replace"
class RewriteMode(StrEnum):
HEADER = "header"
BODY = "body"
class ConfMode(StrEnum):
AGENT = "agent"
YAML = "yaml"
+472
View File
@@ -0,0 +1,472 @@
import aiohttp
from aiohttp import hdrs, web, WSMsgType
from aiohttp.helpers import must_be_empty_body
import asyncio
from functools import lru_cache
from homeassistant.components import frontend, http
from ipaddress import ip_address
import json
from multidict import CIMultiDict
import re
from typing import TYPE_CHECKING, cast
from urllib.parse import urlencode, quote
from yarl import URL
from .const import DOMAIN, LOGGER as _LOGGER, API_BASE, URL_BASE, WorkMode, UIMode, RewriteMode
if TYPE_CHECKING:
from homeassistant.core import HomeAssistant
from typing import Any, Callable, Iterable
from .config import IngressStore, IngressCfg, RewriteCfg, UserInfo
X_INGRESS_NAME = "X-Ingress-Name"
X_ORIGINAL_URL = "X-Original-Url"
X_HASS_ORIGIN = "X-Hass-Origin"
X_INGRESS_PATH = "X-Ingress-Path"
X_INGRESS_SUBPATH = "X-Ingress-Subpath"
HEADER_AUTO_PH = "$auto"
HEADER_USER_ID_PH = "$user_id"
HEADER_USER_NAME_PH = "$user_name"
HEADER_USERNAME_PH = "$username"
INGRESS_MODES = (WorkMode.INGRESS, WorkMode.SUBAPP)
METH_ALLOW_REDIRECT = (hdrs.METH_GET, hdrs.METH_HEAD)
INIT_HEADERS_FILTER = {
hdrs.CONTENT_LENGTH,
hdrs.CONTENT_ENCODING,
hdrs.TRANSFER_ENCODING,
hdrs.SEC_WEBSOCKET_EXTENSIONS,
hdrs.SEC_WEBSOCKET_PROTOCOL,
hdrs.SEC_WEBSOCKET_VERSION,
hdrs.SEC_WEBSOCKET_KEY,
}
RESPONSE_HEADERS_FILTER = {
hdrs.TRANSFER_ENCODING,
hdrs.CONTENT_LENGTH,
hdrs.CONTENT_TYPE,
hdrs.CONTENT_ENCODING,
}
MAX_SIMPLE_REQUEST_SIZE = 4194000
DISABLED_TIMEOUT = aiohttp.ClientTimeout(total=None)
class IngressView(http.HomeAssistantView): # type: ignore
"""ingress view to handle request."""
name = "api:ingress:proxy"
url = API_BASE + "/{name}/{path:.*}"
requires_auth = False
def __init__(
self, hass: "HomeAssistant", config: "IngressStore", websession: aiohttp.ClientSession
):
self._hass = hass
self._config = config
self._websession = websession
async def _handle_auth(self, request: web.Request) -> web.Response:
# check required header
name = request.headers.get(X_INGRESS_NAME)
url = request.headers.get(X_ORIGINAL_URL)
if not name or not url:
raise web.HTTPNotFound
# check ingress_token from query
url = URL(url)
cookie_name = self._config.cookie_name(name)
if cookie_name in url.query:
cfg, token = self._config.check_token(self._hass, url.query[cookie_name])
if cfg:
# valid, remove ingressToken if has X-Hass-Origin else return 200
hass_origin = request.headers.get(X_HASS_ORIGIN)
if hass_origin and request.method in METH_ALLOW_REDIRECT:
query = url.query.copy()
query.pop(cookie_name)
resp = web.HTTPUnauthorized(headers={hdrs.LOCATION: str(url.with_query(query))})
else:
resp = web.Response(headers=cfg.headers)
resp.set_cookie(cfg.cookie_name, token, httponly=True)
return resp
# check ingress_token from cookie
token = request.cookies.get(cookie_name, "")
if cfg := self._config.check_token(self._hass, token, False)[0]:
# valid, return 200
return web.Response(headers=cfg.headers)
# cookie invalid, try redirect to entry
if cfg := self._config.get(name):
params = {"replace": ""}
root = cfg.sub_path + "/"
if url.path.startswith(root):
url = URL.build(
path=url.path[len(root) :], query_string=url.query_string, fragment=url.fragment
)
params["index"] = str(url)
hass_origin = request.headers.get(X_HASS_ORIGIN, "")
url = f"{hass_origin}/{cfg.entry}?{urlencode(params)}"
raise web.HTTPUnauthorized(headers={hdrs.LOCATION: url})
raise web.HTTPNotFound
async def _handle_redirect(self, cfg: "IngressCfg", path: str) -> web.Response | None:
# find frontend config
hass_data, token = self._hass.data, cfg.token
def get_front_config():
def get_config(config: dict[str, "Any"]):
fields = ("url", "index")
config = {k: config[k] for k in fields if k in config}
if "index" in config:
config["index"] = path.lstrip("/")
config["ui_mode"] = UIMode.REPLACE
return config
for panel in hass_data[DOMAIN]["panels"]:
panel = hass_data[frontend.DATA_PANELS].get(panel)
if not panel:
continue
if panel.config.get("token") is token:
return get_config(panel.config)
for child in panel.config.get("children", {}).values():
if child.get("token") is token:
return get_config(child)
if not (config := get_front_config()):
return
# redirect to target url
html = f"""\
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<script async src="{URL_BASE}/entrypoint.js"></script>
<script>(async () => {{
await customElements.whenDefined("ha-panel-ingress");
document.querySelector("ha-panel-ingress").setProperties({{panel: {{
config: {json.dumps(config)},
}}}});
}})();</script>
</head>
<body><ha-panel-ingress></ha-panel-ingress></body>
</html>
"""
return web.Response(text=html, content_type="text/html")
async def _handle(
self, request: web.Request, name: str, path: str
) -> web.Response | web.StreamResponse | web.WebSocketResponse:
if name == "_" and path == "auth":
return await self._handle_auth(request)
cfg, token = self._config.check_token(self._hass, name)
if cfg and request.method in METH_ALLOW_REDIRECT:
# only redirect when get or head method
url = f"{API_BASE}/{cfg.name}/"
path = quote(path) + (f"?{request.query_string}" if request.query_string else "")
resp = web.HTTPFound(url + path)
# set self cookie
resp.set_cookie(cfg.cookie_name, token, path=url, httponly=True)
# set subapp's cookies
for cfg in cfg.sub_apps:
resp.headers.add(
hdrs.SET_COOKIE,
f"{cfg.cookie_name}={cfg.token['value']}; HttpOnly; Path={API_BASE}/{cfg.name}/",
)
raise resp
if not cfg:
token = request.cookies.get(self._config.cookie_name(name), "")
cfg = self._config.check_token(self._hass, token, False)[0]
user: UserInfo | None = None
if cfg and cfg.mode in INGRESS_MODES:
user = self._config.check_user_token(
request.cookies.get(self._config.user_cookie_name(), "")
)
if not user and not cfg.static_token:
cfg = None
if not cfg or cfg.mode not in INGRESS_MODES:
# cookie invalid, try redirect to entry
if cfg := cfg or self._config.get(name):
path = quote(path) + (f"?{request.query_string}" if request.query_string else "")
if cfg.mode == WorkMode.AUTH:
if (resp := await self._handle_redirect(cfg, path)) is not None:
return resp
path = urlencode({"replace": "", "index": path})
raise web.HTTPFound(f"/{cfg.entry}?{path}")
raise web.HTTPNotFound
url = _create_url(cfg, path)
try:
# Websocket
if _is_websocket(request):
return await self._handle_websocket(request, cfg, user, url)
# Request
return await self._handle_request(request, cfg, user, url)
except aiohttp.ClientError as err:
_LOGGER.debug("Ingress error with %s / %s: %s", cfg.name, url, err)
raise web.HTTPBadGateway from None
get = _handle
post = _handle
put = _handle
delete = _handle
patch = _handle
# options = _handle
head = _handle
async def _handle_websocket(
self, request: web.Request, cfg: "IngressCfg", user: "UserInfo | None", url: URL
) -> web.WebSocketResponse:
"""Ingress route for websocket."""
req_protocols: Iterable[str]
if hdrs.SEC_WEBSOCKET_PROTOCOL in request.headers:
req_protocols = [
str(proto.strip())
for proto in request.headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(",")
]
else:
req_protocols = ()
ws_server = web.WebSocketResponse(protocols=req_protocols, autoclose=False, autoping=False)
await ws_server.prepare(request)
# Support GET query
if request.query_string:
url = url.with_query(request.query_string)
# Start proxy
async with self._websession.ws_connect(
url,
headers=_init_header(request, cfg, user),
protocols=req_protocols,
autoclose=False,
autoping=False,
) as ws_client:
# Proxy requests
ws_client = cast(web.WebSocketResponse, ws_client)
await asyncio.wait(
[
asyncio.create_task(_websocket_forward(ws_server, ws_client)),
asyncio.create_task(_websocket_forward(ws_client, ws_server)),
],
return_when=asyncio.FIRST_COMPLETED,
)
return ws_server
async def _handle_request(
self, request: web.Request, cfg: "IngressCfg", user: "UserInfo | None", url: URL
) -> web.Response | web.StreamResponse:
"""Ingress route for request."""
data = request.content
if not request.body_exists or (
(clen := request.headers.get(hdrs.CONTENT_LENGTH))
and (clen := int(clen)) <= MAX_SIMPLE_REQUEST_SIZE
):
data = await data.read()
async with self._websession.request(
request.method,
url,
headers=_init_header(request, cfg, user),
params=request.query,
allow_redirects=False,
data=data,
timeout=DISABLED_TIMEOUT,
skip_auto_headers={hdrs.CONTENT_TYPE},
) as result:
headers = _response_header(result)
if ctype := result.headers.get(hdrs.CONTENT_TYPE):
ctype = ctype.partition(";")[0].strip()
else:
ctype = "application/octet-stream"
rewrite_body = None
if cfg.rewrites:
path = url.path
for rule in cfg.rewrites:
if rule.path and not re.match(rule.path, path, re.I):
continue
if rule.mode == RewriteMode.HEADER:
for name, value in headers.items():
if rule.name and not re.match(rule.name, name, re.I):
continue
for i in range(len(value)):
value[i] = re.sub(rule.match, rule.replace, value[i])
elif rule.mode == RewriteMode.BODY:
if rule.name and not re.match(rule.name, ctype, re.I):
continue
rewrite_body = _make_rewrite(rule, rewrite_body)
headers = CIMultiDict((k, v) for k, vs in headers.items() for v in vs if v)
# Simple request
if rewrite_body or must_be_empty_body(request.method, result.status):
# Return Response
body = await result.read()
if rewrite_body:
body = rewrite_body(body)
return web.Response(
headers=headers, status=result.status, content_type=ctype, body=body
)
# Stream response
response = web.StreamResponse(status=result.status, headers=headers)
response.content_type = ctype
try:
await response.prepare(request)
async for data, _ in result.content.iter_chunks():
await response.write(data)
except (aiohttp.ClientError, aiohttp.ClientPayloadError, ConnectionResetError) as err:
_LOGGER.debug("Stream error with %s / %s: %s", cfg.name, url, err)
return response
def _make_rewrite(
rule: "RewriteCfg", rewrite_body: "Callable[[bytes], bytes] | None"
) -> "Callable[[bytes], bytes]":
if rewrite_body is None:
rewrite_body = lambda body: body
return lambda body: re.sub(rule.match.encode(), rule.replace.encode(), rewrite_body(body))
@lru_cache
def _create_url(cfg: "IngressCfg", path: str) -> URL:
"""Create URL to service."""
base_path = f"{cfg.sub_path}/"
try:
url = cfg.origin.join(URL(base_path + quote(path.lstrip("/"))))
except ValueError as err:
raise web.HTTPBadRequest from err
if not url.path.startswith(base_path):
raise web.HTTPBadRequest
return url
@lru_cache(maxsize=32)
def _forwarded_for_header(forward_for: str | None, peer_name: str) -> str:
"""Create X-Forwarded-For header."""
connected_ip = ip_address(peer_name)
return f"{forward_for}, {connected_ip!s}" if forward_for else f"{connected_ip!s}"
def _init_header(
request: web.Request, cfg: "IngressCfg", user: "UserInfo | None"
) -> dict[str, str]:
"""Create initial header."""
headers: dict[str, str] = {}
for name, value in request.headers.items():
name = std_header_name(name)
if name in INIT_HEADERS_FILTER:
continue
if name == hdrs.COOKIE:
if not (value := cfg.remove_token_from_cookie(value)):
continue
headers[name] = value
for name, value in cfg.headers.items():
if value == HEADER_USERNAME_PH:
if value := user["username"] if user else None:
headers[name] = value
elif value == HEADER_USER_ID_PH:
if value := user["id"] if user else None:
headers[name] = value
elif value == HEADER_USER_NAME_PH:
if value := user["name"] if user else None:
headers[name] = value
elif value != HEADER_AUTO_PH:
headers[name] = value
# Ingress information
headers[X_INGRESS_PATH] = f"{API_BASE}/{cfg.name}"
headers[X_INGRESS_SUBPATH] = cfg.sub_path
# Set X-Forwarded-For
assert request.transport
if (peername := request.transport.get_extra_info("peername")) is None:
_LOGGER.error("Can't set forward_for header, missing peername")
raise web.HTTPBadRequest
headers[hdrs.X_FORWARDED_FOR] = _forwarded_for_header(
request.headers.get(hdrs.X_FORWARDED_FOR), peername[0]
)
# Set X-Forwarded-Host
if not (forward_host := request.headers.get(hdrs.X_FORWARDED_HOST)):
forward_host = request.host
headers[hdrs.X_FORWARDED_HOST] = forward_host
# Set X-Forwarded-Proto
if not (forward_proto := request.headers.get(hdrs.X_FORWARDED_PROTO)):
forward_proto = request.scheme
headers[hdrs.X_FORWARDED_PROTO] = forward_proto
# Replace Origin placeholder
if hdrs.ORIGIN in headers and cfg.headers.get(hdrs.ORIGIN) == HEADER_AUTO_PH:
headers[hdrs.ORIGIN] = f"{forward_proto}://{forward_host}"
return headers
def _response_header(response: aiohttp.ClientResponse) -> dict[str, list[str]]:
"""Create response header."""
headers: dict[str, list[str]] = {}
for name, value in response.headers.items():
name = std_header_name(name)
if name in RESPONSE_HEADERS_FILTER:
continue
headers.setdefault(name, []).append(value)
return headers
def _is_websocket(request: web.Request) -> bool:
"""Return True if request is a websocket."""
headers = request.headers
return bool(
"upgrade" in headers.get(hdrs.CONNECTION, "").lower()
and headers.get(hdrs.UPGRADE, "").lower() == "websocket"
)
async def _websocket_forward(ws_from: web.WebSocketResponse, ws_to: web.WebSocketResponse) -> None:
"""Handle websocket message directly."""
try:
async for msg in ws_from:
if msg.type is WSMsgType.TEXT:
await ws_to.send_str(msg.data)
elif msg.type is WSMsgType.BINARY:
await ws_to.send_bytes(msg.data)
elif msg.type is WSMsgType.PING:
await ws_to.ping()
elif msg.type is WSMsgType.PONG:
await ws_to.pong()
elif ws_to.closed:
await ws_to.close(code=ws_to.close_code, message=msg.extra) # type: ignore
except RuntimeError:
_LOGGER.debug("Ingress Websocket runtime error")
except ConnectionResetError:
_LOGGER.debug("Ingress Websocket Connection Reset")
def _init():
from multidict import istr
special_hdrs = {}
for name in dir(hdrs):
if type(value := getattr(hdrs, name)) != istr or (key := value.title()) == value:
continue
special_hdrs[key] = value
def std_header_name(name: str):
name = name.title()
return special_hdrs.get(name, name)
return std_header_name
std_header_name = _init()
+13
View File
@@ -0,0 +1,13 @@
{
"domain": "ingress",
"name": "Ingress",
"after_dependencies": ["panel_custom"],
"codeowners": ["@lovelylain"],
"config_flow": true,
"dependencies": ["http"],
"documentation": "https://github.com/lovelylain/hass_ingress",
"iot_class": "local_push",
"issue_tracker": "https://github.com/lovelylain/hass_ingress/issues",
"single_config_entry": true,
"version": "1.3.0"
}
+27
View File
@@ -0,0 +1,27 @@
{
"config": {
"step": {
"user": {
"title": "Ingress",
"description": "Select configuration mode.\nagent: Configure with ui, requires running an agent.\nyaml: Manually edit configuration.yaml file.",
"data": {
"mode": "Configuration mode"
}
},
"my_agent": {
"title": "Ingress agent",
"description": "Enter the URL to your already running ingress agent. If you do not have the ingress agent running, you should install it first.",
"data": {
"url": "URL of the ingress agent"
}
}
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]"
},
"abort": {
"reconfigure_successful": "[%key:common::config_flow::abort::reconfigure_successful%]"
}
}
}
@@ -0,0 +1,27 @@
{
"config": {
"abort": {
"reconfigure_successful": "Re-configuration was successful"
},
"error": {
"cannot_connect": "Failed to connect",
"invalid_auth": "Invalid authentication"
},
"step": {
"my_agent": {
"data": {
"url": "URL of the ingress agent"
},
"description": "Enter the URL to your already running ingress agent. If you do not have the ingress agent running, you should install it first.",
"title": "Ingress agent"
},
"user": {
"data": {
"mode": "Configuration mode"
},
"description": "Select configuration mode.\nagent: Configure with ui, requires running an agent.\nyaml: Manually edit configuration.yaml file.",
"title": "Ingress"
}
}
}
}
@@ -0,0 +1,27 @@
{
"config": {
"abort": {
"reconfigure_successful": "重新配置成功"
},
"error": {
"cannot_connect": "连接失败",
"invalid_auth": "身份验证无效"
},
"step": {
"my_agent": {
"data": {
"url": "ingress agent 的 URL"
},
"description": "输入已运行的 ingress agent 的 URL,如果您没有运行,则应首先安​​装并运行它。",
"title": "Ingress agent"
},
"user": {
"data": {
"mode": "配置模式"
},
"description": "选择配置模式。\nagent: 使用 ui 配置,需要运行 agent。\nyaml: 手动编辑 configuration.yaml 文件.",
"title": "Ingress"
}
}
}
}
@@ -0,0 +1,88 @@
"""WebSocket API for token generation and refresh."""
from homeassistant.components.websocket_api.const import (
ERR_INVALID_FORMAT,
ERR_UNAUTHORIZED,
ERR_UNKNOWN_ERROR,
)
from typing import TYPE_CHECKING
import voluptuous as vol
from .config import IngressStore
from .const import DOMAIN, LOGGER as _LOGGER
if TYPE_CHECKING:
from homeassistant.core import HomeAssistant
from homeassistant.components.websocket_api.connection import ActiveConnection
from typing import Any, Final
WS_API_PREFIX: "Final" = "ha-ingress"
def handle_generate_token(
hass: "HomeAssistant", connection: "ActiveConnection", msg: dict[str, "Any"]
):
"""Handle generate token command."""
try:
# Get user_id from the authenticated WebSocket connection context
user = connection.user
if not user:
connection.send_error(msg["id"], ERR_UNAUTHORIZED, "User not authenticated")
return
username = None
for credential in user.credentials:
if credential.auth_provider_type == "homeassistant":
username = credential.data.get("username")
break
config: IngressStore = hass.data[DOMAIN]["config"]
token = config.generate_user_token({"id": user.id, "name": user.name, "username": username})
connection.send_result(msg["id"], {"session": token})
except Exception as err:
_LOGGER.error("Error generating token: %s", err)
connection.send_error(msg["id"], ERR_UNKNOWN_ERROR, str(err))
def handle_refresh_token(
hass: "HomeAssistant", connection: "ActiveConnection", msg: dict[str, "Any"]
):
"""Handle refresh token command."""
try:
token = msg.get("session")
if not token:
connection.send_error(msg["id"], ERR_INVALID_FORMAT, "Missing token")
return
config: IngressStore = hass.data[DOMAIN]["config"]
user_info = config.check_user_token(token)
if not user_info:
raise ValueError("Invalid or expired token")
connection.send_result(msg["id"], {"user_id": user_info["id"]})
except Exception as err:
_LOGGER.debug("Error refreshing token: %s", err)
connection.send_error(msg["id"], ERR_UNKNOWN_ERROR, str(err))
async def async_register_websocket_api(hass: "HomeAssistant"):
"""Register WebSocket API."""
from homeassistant.components.websocket_api import async_register_command
from homeassistant.components.websocket_api.decorators import websocket_command
define = websocket_command(
{
vol.Required("type"): "ha-ingress/session",
}
)
async_register_command(hass, define(handle_generate_token))
define = websocket_command(
{
vol.Required("type"): "ha-ingress/validate_session",
vol.Required("session"): str,
}
)
async_register_command(hass, define(handle_refresh_token))
File diff suppressed because one or more lines are too long
@@ -0,0 +1,903 @@
/**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const N = globalThis, q = N.ShadowRoot && (N.ShadyCSS === void 0 || N.ShadyCSS.nativeShadow) && "adoptedStyleSheets" in Document.prototype && "replace" in CSSStyleSheet.prototype, ot = Symbol(), J = /* @__PURE__ */ new WeakMap();
let ft = class {
constructor(t, e, s) {
if (this._$cssResult$ = !0, s !== ot) throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");
this.cssText = t, this.t = e;
}
get styleSheet() {
let t = this.o;
const e = this.t;
if (q && t === void 0) {
const s = e !== void 0 && e.length === 1;
s && (t = J.get(e)), t === void 0 && ((this.o = t = new CSSStyleSheet()).replaceSync(this.cssText), s && J.set(e, t));
}
return t;
}
toString() {
return this.cssText;
}
};
const gt = (r) => new ft(typeof r == "string" ? r : r + "", void 0, ot), mt = (r, t) => {
if (q) r.adoptedStyleSheets = t.map((e) => e instanceof CSSStyleSheet ? e : e.styleSheet);
else for (const e of t) {
const s = document.createElement("style"), i = N.litNonce;
i !== void 0 && s.setAttribute("nonce", i), s.textContent = e.cssText, r.appendChild(s);
}
}, K = q ? (r) => r : (r) => r instanceof CSSStyleSheet ? ((t) => {
let e = "";
for (const s of t.cssRules) e += s.cssText;
return gt(e);
})(r) : r;
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const { is: At, defineProperty: bt, getOwnPropertyDescriptor: vt, getOwnPropertyNames: yt, getOwnPropertySymbols: wt, getPrototypeOf: Et } = Object, g = globalThis, F = g.trustedTypes, St = F ? F.emptyScript : "", z = g.reactiveElementPolyfillSupport, C = (r, t) => r, W = { toAttribute(r, t) {
switch (t) {
case Boolean:
r = r ? St : null;
break;
case Object:
case Array:
r = r == null ? r : JSON.stringify(r);
}
return r;
}, fromAttribute(r, t) {
let e = r;
switch (t) {
case Boolean:
e = r !== null;
break;
case Number:
e = r === null ? null : Number(r);
break;
case Object:
case Array:
try {
e = JSON.parse(r);
} catch {
e = null;
}
}
return e;
} }, nt = (r, t) => !At(r, t), Q = { attribute: !0, type: String, converter: W, reflect: !1, hasChanged: nt };
Symbol.metadata ?? (Symbol.metadata = Symbol("metadata")), g.litPropertyMetadata ?? (g.litPropertyMetadata = /* @__PURE__ */ new WeakMap());
class y extends HTMLElement {
static addInitializer(t) {
this._$Ei(), (this.l ?? (this.l = [])).push(t);
}
static get observedAttributes() {
return this.finalize(), this._$Eh && [...this._$Eh.keys()];
}
static createProperty(t, e = Q) {
if (e.state && (e.attribute = !1), this._$Ei(), this.elementProperties.set(t, e), !e.noAccessor) {
const s = Symbol(), i = this.getPropertyDescriptor(t, s, e);
i !== void 0 && bt(this.prototype, t, i);
}
}
static getPropertyDescriptor(t, e, s) {
const { get: i, set: o } = vt(this.prototype, t) ?? { get() {
return this[e];
}, set(n) {
this[e] = n;
} };
return { get() {
return i == null ? void 0 : i.call(this);
}, set(n) {
const h = i == null ? void 0 : i.call(this);
o.call(this, n), this.requestUpdate(t, h, s);
}, configurable: !0, enumerable: !0 };
}
static getPropertyOptions(t) {
return this.elementProperties.get(t) ?? Q;
}
static _$Ei() {
if (this.hasOwnProperty(C("elementProperties"))) return;
const t = Et(this);
t.finalize(), t.l !== void 0 && (this.l = [...t.l]), this.elementProperties = new Map(t.elementProperties);
}
static finalize() {
if (this.hasOwnProperty(C("finalized"))) return;
if (this.finalized = !0, this._$Ei(), this.hasOwnProperty(C("properties"))) {
const e = this.properties, s = [...yt(e), ...wt(e)];
for (const i of s) this.createProperty(i, e[i]);
}
const t = this[Symbol.metadata];
if (t !== null) {
const e = litPropertyMetadata.get(t);
if (e !== void 0) for (const [s, i] of e) this.elementProperties.set(s, i);
}
this._$Eh = /* @__PURE__ */ new Map();
for (const [e, s] of this.elementProperties) {
const i = this._$Eu(e, s);
i !== void 0 && this._$Eh.set(i, e);
}
this.elementStyles = this.finalizeStyles(this.styles);
}
static finalizeStyles(t) {
const e = [];
if (Array.isArray(t)) {
const s = new Set(t.flat(1 / 0).reverse());
for (const i of s) e.unshift(K(i));
} else t !== void 0 && e.push(K(t));
return e;
}
static _$Eu(t, e) {
const s = e.attribute;
return s === !1 ? void 0 : typeof s == "string" ? s : typeof t == "string" ? t.toLowerCase() : void 0;
}
constructor() {
super(), this._$Ep = void 0, this.isUpdatePending = !1, this.hasUpdated = !1, this._$Em = null, this._$Ev();
}
_$Ev() {
var t;
this._$ES = new Promise((e) => this.enableUpdating = e), this._$AL = /* @__PURE__ */ new Map(), this._$E_(), this.requestUpdate(), (t = this.constructor.l) == null || t.forEach((e) => e(this));
}
addController(t) {
var e;
(this._$EO ?? (this._$EO = /* @__PURE__ */ new Set())).add(t), this.renderRoot !== void 0 && this.isConnected && ((e = t.hostConnected) == null || e.call(t));
}
removeController(t) {
var e;
(e = this._$EO) == null || e.delete(t);
}
_$E_() {
const t = /* @__PURE__ */ new Map(), e = this.constructor.elementProperties;
for (const s of e.keys()) this.hasOwnProperty(s) && (t.set(s, this[s]), delete this[s]);
t.size > 0 && (this._$Ep = t);
}
createRenderRoot() {
const t = this.shadowRoot ?? this.attachShadow(this.constructor.shadowRootOptions);
return mt(t, this.constructor.elementStyles), t;
}
connectedCallback() {
var t;
this.renderRoot ?? (this.renderRoot = this.createRenderRoot()), this.enableUpdating(!0), (t = this._$EO) == null || t.forEach((e) => {
var s;
return (s = e.hostConnected) == null ? void 0 : s.call(e);
});
}
enableUpdating(t) {
}
disconnectedCallback() {
var t;
(t = this._$EO) == null || t.forEach((e) => {
var s;
return (s = e.hostDisconnected) == null ? void 0 : s.call(e);
});
}
attributeChangedCallback(t, e, s) {
this._$AK(t, s);
}
_$EC(t, e) {
var o;
const s = this.constructor.elementProperties.get(t), i = this.constructor._$Eu(t, s);
if (i !== void 0 && s.reflect === !0) {
const n = (((o = s.converter) == null ? void 0 : o.toAttribute) !== void 0 ? s.converter : W).toAttribute(e, s.type);
this._$Em = t, n == null ? this.removeAttribute(i) : this.setAttribute(i, n), this._$Em = null;
}
}
_$AK(t, e) {
var o;
const s = this.constructor, i = s._$Eh.get(t);
if (i !== void 0 && this._$Em !== i) {
const n = s.getPropertyOptions(i), h = typeof n.converter == "function" ? { fromAttribute: n.converter } : ((o = n.converter) == null ? void 0 : o.fromAttribute) !== void 0 ? n.converter : W;
this._$Em = i, this[i] = h.fromAttribute(e, n.type), this._$Em = null;
}
}
requestUpdate(t, e, s) {
if (t !== void 0) {
if (s ?? (s = this.constructor.getPropertyOptions(t)), !(s.hasChanged ?? nt)(this[t], e)) return;
this.P(t, e, s);
}
this.isUpdatePending === !1 && (this._$ES = this._$ET());
}
P(t, e, s) {
this._$AL.has(t) || this._$AL.set(t, e), s.reflect === !0 && this._$Em !== t && (this._$Ej ?? (this._$Ej = /* @__PURE__ */ new Set())).add(t);
}
async _$ET() {
this.isUpdatePending = !0;
try {
await this._$ES;
} catch (e) {
Promise.reject(e);
}
const t = this.scheduleUpdate();
return t != null && await t, !this.isUpdatePending;
}
scheduleUpdate() {
return this.performUpdate();
}
performUpdate() {
var s;
if (!this.isUpdatePending) return;
if (!this.hasUpdated) {
if (this.renderRoot ?? (this.renderRoot = this.createRenderRoot()), this._$Ep) {
for (const [o, n] of this._$Ep) this[o] = n;
this._$Ep = void 0;
}
const i = this.constructor.elementProperties;
if (i.size > 0) for (const [o, n] of i) n.wrapped !== !0 || this._$AL.has(o) || this[o] === void 0 || this.P(o, this[o], n);
}
let t = !1;
const e = this._$AL;
try {
t = this.shouldUpdate(e), t ? (this.willUpdate(e), (s = this._$EO) == null || s.forEach((i) => {
var o;
return (o = i.hostUpdate) == null ? void 0 : o.call(i);
}), this.update(e)) : this._$EU();
} catch (i) {
throw t = !1, this._$EU(), i;
}
t && this._$AE(e);
}
willUpdate(t) {
}
_$AE(t) {
var e;
(e = this._$EO) == null || e.forEach((s) => {
var i;
return (i = s.hostUpdated) == null ? void 0 : i.call(s);
}), this.hasUpdated || (this.hasUpdated = !0, this.firstUpdated(t)), this.updated(t);
}
_$EU() {
this._$AL = /* @__PURE__ */ new Map(), this.isUpdatePending = !1;
}
get updateComplete() {
return this.getUpdateComplete();
}
getUpdateComplete() {
return this._$ES;
}
shouldUpdate(t) {
return !0;
}
update(t) {
this._$Ej && (this._$Ej = this._$Ej.forEach((e) => this._$EC(e, this[e]))), this._$EU();
}
updated(t) {
}
firstUpdated(t) {
}
}
y.elementStyles = [], y.shadowRootOptions = { mode: "open" }, y[C("elementProperties")] = /* @__PURE__ */ new Map(), y[C("finalized")] = /* @__PURE__ */ new Map(), z == null || z({ ReactiveElement: y }), (g.reactiveElementVersions ?? (g.reactiveElementVersions = [])).push("2.0.4");
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const P = globalThis, R = P.trustedTypes, G = R ? R.createPolicy("lit-html", { createHTML: (r) => r }) : void 0, at = "$lit$", f = `lit$${Math.random().toFixed(9).slice(2)}$`, ht = "?" + f, Ct = `<${ht}>`, v = document, x = () => v.createComment(""), T = (r) => r === null || typeof r != "object" && typeof r != "function", Z = Array.isArray, Pt = (r) => Z(r) || typeof (r == null ? void 0 : r[Symbol.iterator]) == "function", B = `[
\f\r]`, S = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g, X = /-->/g, tt = />/g, m = RegExp(`>|${B}(?:([^\\s"'>=/]+)(${B}*=${B}*(?:[^
\f\r"'\`<>=]|("|')|))|$)`, "g"), et = /'/g, st = /"/g, lt = /^(?:script|style|textarea|title)$/i, Ht = (r) => (t, ...e) => ({ _$litType$: r, strings: t, values: e }), u = Ht(1), w = Symbol.for("lit-noChange"), c = Symbol.for("lit-nothing"), it = /* @__PURE__ */ new WeakMap(), b = v.createTreeWalker(v, 129);
function ct(r, t) {
if (!Z(r) || !r.hasOwnProperty("raw")) throw Error("invalid template strings array");
return G !== void 0 ? G.createHTML(t) : t;
}
const xt = (r, t) => {
const e = r.length - 1, s = [];
let i, o = t === 2 ? "<svg>" : t === 3 ? "<math>" : "", n = S;
for (let h = 0; h < e; h++) {
const a = r[h];
let d, p, l = -1, $ = 0;
for (; $ < a.length && (n.lastIndex = $, p = n.exec(a), p !== null); ) $ = n.lastIndex, n === S ? p[1] === "!--" ? n = X : p[1] !== void 0 ? n = tt : p[2] !== void 0 ? (lt.test(p[2]) && (i = RegExp("</" + p[2], "g")), n = m) : p[3] !== void 0 && (n = m) : n === m ? p[0] === ">" ? (n = i ?? S, l = -1) : p[1] === void 0 ? l = -2 : (l = n.lastIndex - p[2].length, d = p[1], n = p[3] === void 0 ? m : p[3] === '"' ? st : et) : n === st || n === et ? n = m : n === X || n === tt ? n = S : (n = m, i = void 0);
const _ = n === m && r[h + 1].startsWith("/>") ? " " : "";
o += n === S ? a + Ct : l >= 0 ? (s.push(d), a.slice(0, l) + at + a.slice(l) + f + _) : a + f + (l === -2 ? h : _);
}
return [ct(r, o + (r[e] || "<?>") + (t === 2 ? "</svg>" : t === 3 ? "</math>" : "")), s];
};
class U {
constructor({ strings: t, _$litType$: e }, s) {
let i;
this.parts = [];
let o = 0, n = 0;
const h = t.length - 1, a = this.parts, [d, p] = xt(t, e);
if (this.el = U.createElement(d, s), b.currentNode = this.el.content, e === 2 || e === 3) {
const l = this.el.content.firstChild;
l.replaceWith(...l.childNodes);
}
for (; (i = b.nextNode()) !== null && a.length < h; ) {
if (i.nodeType === 1) {
if (i.hasAttributes()) for (const l of i.getAttributeNames()) if (l.endsWith(at)) {
const $ = p[n++], _ = i.getAttribute(l).split(f), M = /([.?@])?(.*)/.exec($);
a.push({ type: 1, index: o, name: M[2], strings: _, ctor: M[1] === "." ? Ut : M[1] === "?" ? kt : M[1] === "@" ? Mt : L }), i.removeAttribute(l);
} else l.startsWith(f) && (a.push({ type: 6, index: o }), i.removeAttribute(l));
if (lt.test(i.tagName)) {
const l = i.textContent.split(f), $ = l.length - 1;
if ($ > 0) {
i.textContent = R ? R.emptyScript : "";
for (let _ = 0; _ < $; _++) i.append(l[_], x()), b.nextNode(), a.push({ type: 2, index: ++o });
i.append(l[$], x());
}
}
} else if (i.nodeType === 8) if (i.data === ht) a.push({ type: 2, index: o });
else {
let l = -1;
for (; (l = i.data.indexOf(f, l + 1)) !== -1; ) a.push({ type: 7, index: o }), l += f.length - 1;
}
o++;
}
}
static createElement(t, e) {
const s = v.createElement("template");
return s.innerHTML = t, s;
}
}
function E(r, t, e = r, s) {
var n, h;
if (t === w) return t;
let i = s !== void 0 ? (n = e._$Co) == null ? void 0 : n[s] : e._$Cl;
const o = T(t) ? void 0 : t._$litDirective$;
return (i == null ? void 0 : i.constructor) !== o && ((h = i == null ? void 0 : i._$AO) == null || h.call(i, !1), o === void 0 ? i = void 0 : (i = new o(r), i._$AT(r, e, s)), s !== void 0 ? (e._$Co ?? (e._$Co = []))[s] = i : e._$Cl = i), i !== void 0 && (t = E(r, i._$AS(r, t.values), i, s)), t;
}
class Tt {
constructor(t, e) {
this._$AV = [], this._$AN = void 0, this._$AD = t, this._$AM = e;
}
get parentNode() {
return this._$AM.parentNode;
}
get _$AU() {
return this._$AM._$AU;
}
u(t) {
const { el: { content: e }, parts: s } = this._$AD, i = ((t == null ? void 0 : t.creationScope) ?? v).importNode(e, !0);
b.currentNode = i;
let o = b.nextNode(), n = 0, h = 0, a = s[0];
for (; a !== void 0; ) {
if (n === a.index) {
let d;
a.type === 2 ? d = new k(o, o.nextSibling, this, t) : a.type === 1 ? d = new a.ctor(o, a.name, a.strings, this, t) : a.type === 6 && (d = new Nt(o, this, t)), this._$AV.push(d), a = s[++h];
}
n !== (a == null ? void 0 : a.index) && (o = b.nextNode(), n++);
}
return b.currentNode = v, i;
}
p(t) {
let e = 0;
for (const s of this._$AV) s !== void 0 && (s.strings !== void 0 ? (s._$AI(t, s, e), e += s.strings.length - 2) : s._$AI(t[e])), e++;
}
}
class k {
get _$AU() {
var t;
return ((t = this._$AM) == null ? void 0 : t._$AU) ?? this._$Cv;
}
constructor(t, e, s, i) {
this.type = 2, this._$AH = c, this._$AN = void 0, this._$AA = t, this._$AB = e, this._$AM = s, this.options = i, this._$Cv = (i == null ? void 0 : i.isConnected) ?? !0;
}
get parentNode() {
let t = this._$AA.parentNode;
const e = this._$AM;
return e !== void 0 && (t == null ? void 0 : t.nodeType) === 11 && (t = e.parentNode), t;
}
get startNode() {
return this._$AA;
}
get endNode() {
return this._$AB;
}
_$AI(t, e = this) {
t = E(this, t, e), T(t) ? t === c || t == null || t === "" ? (this._$AH !== c && this._$AR(), this._$AH = c) : t !== this._$AH && t !== w && this._(t) : t._$litType$ !== void 0 ? this.$(t) : t.nodeType !== void 0 ? this.T(t) : Pt(t) ? this.k(t) : this._(t);
}
O(t) {
return this._$AA.parentNode.insertBefore(t, this._$AB);
}
T(t) {
this._$AH !== t && (this._$AR(), this._$AH = this.O(t));
}
_(t) {
this._$AH !== c && T(this._$AH) ? this._$AA.nextSibling.data = t : this.T(v.createTextNode(t)), this._$AH = t;
}
$(t) {
var o;
const { values: e, _$litType$: s } = t, i = typeof s == "number" ? this._$AC(t) : (s.el === void 0 && (s.el = U.createElement(ct(s.h, s.h[0]), this.options)), s);
if (((o = this._$AH) == null ? void 0 : o._$AD) === i) this._$AH.p(e);
else {
const n = new Tt(i, this), h = n.u(this.options);
n.p(e), this.T(h), this._$AH = n;
}
}
_$AC(t) {
let e = it.get(t.strings);
return e === void 0 && it.set(t.strings, e = new U(t)), e;
}
k(t) {
Z(this._$AH) || (this._$AH = [], this._$AR());
const e = this._$AH;
let s, i = 0;
for (const o of t) i === e.length ? e.push(s = new k(this.O(x()), this.O(x()), this, this.options)) : s = e[i], s._$AI(o), i++;
i < e.length && (this._$AR(s && s._$AB.nextSibling, i), e.length = i);
}
_$AR(t = this._$AA.nextSibling, e) {
var s;
for ((s = this._$AP) == null ? void 0 : s.call(this, !1, !0, e); t && t !== this._$AB; ) {
const i = t.nextSibling;
t.remove(), t = i;
}
}
setConnected(t) {
var e;
this._$AM === void 0 && (this._$Cv = t, (e = this._$AP) == null || e.call(this, t));
}
}
class L {
get tagName() {
return this.element.tagName;
}
get _$AU() {
return this._$AM._$AU;
}
constructor(t, e, s, i, o) {
this.type = 1, this._$AH = c, this._$AN = void 0, this.element = t, this.name = e, this._$AM = i, this.options = o, s.length > 2 || s[0] !== "" || s[1] !== "" ? (this._$AH = Array(s.length - 1).fill(new String()), this.strings = s) : this._$AH = c;
}
_$AI(t, e = this, s, i) {
const o = this.strings;
let n = !1;
if (o === void 0) t = E(this, t, e, 0), n = !T(t) || t !== this._$AH && t !== w, n && (this._$AH = t);
else {
const h = t;
let a, d;
for (t = o[0], a = 0; a < o.length - 1; a++) d = E(this, h[s + a], e, a), d === w && (d = this._$AH[a]), n || (n = !T(d) || d !== this._$AH[a]), d === c ? t = c : t !== c && (t += (d ?? "") + o[a + 1]), this._$AH[a] = d;
}
n && !i && this.j(t);
}
j(t) {
t === c ? this.element.removeAttribute(this.name) : this.element.setAttribute(this.name, t ?? "");
}
}
class Ut extends L {
constructor() {
super(...arguments), this.type = 3;
}
j(t) {
this.element[this.name] = t === c ? void 0 : t;
}
}
class kt extends L {
constructor() {
super(...arguments), this.type = 4;
}
j(t) {
this.element.toggleAttribute(this.name, !!t && t !== c);
}
}
class Mt extends L {
constructor(t, e, s, i, o) {
super(t, e, s, i, o), this.type = 5;
}
_$AI(t, e = this) {
if ((t = E(this, t, e, 0) ?? c) === w) return;
const s = this._$AH, i = t === c && s !== c || t.capture !== s.capture || t.once !== s.once || t.passive !== s.passive, o = t !== c && (s === c || i);
i && this.element.removeEventListener(this.name, this, s), o && this.element.addEventListener(this.name, this, t), this._$AH = t;
}
handleEvent(t) {
var e;
typeof this._$AH == "function" ? this._$AH.call(((e = this.options) == null ? void 0 : e.host) ?? this.element, t) : this._$AH.handleEvent(t);
}
}
class Nt {
constructor(t, e, s) {
this.element = t, this.type = 6, this._$AN = void 0, this._$AM = e, this.options = s;
}
get _$AU() {
return this._$AM._$AU;
}
_$AI(t) {
E(this, t);
}
}
const D = P.litHtmlPolyfillSupport;
D == null || D(U, k), (P.litHtmlVersions ?? (P.litHtmlVersions = [])).push("3.2.1");
const dt = (r, t, e) => {
const s = (e == null ? void 0 : e.renderBefore) ?? t;
let i = s._$litPart$;
if (i === void 0) {
const o = (e == null ? void 0 : e.renderBefore) ?? null;
s._$litPart$ = i = new k(t.insertBefore(x(), o), o, void 0, e ?? {});
}
return i._$AI(r), i;
};
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
let O = class extends y {
constructor() {
super(...arguments), this.renderOptions = { host: this }, this._$Do = void 0;
}
createRenderRoot() {
var e;
const t = super.createRenderRoot();
return (e = this.renderOptions).renderBefore ?? (e.renderBefore = t.firstChild), t;
}
update(t) {
const e = this.render();
this.hasUpdated || (this.renderOptions.isConnected = this.isConnected), super.update(t), this._$Do = dt(e, this.renderRoot, this.renderOptions);
}
connectedCallback() {
var t;
super.connectedCallback(), (t = this._$Do) == null || t.setConnected(!0);
}
disconnectedCallback() {
var t;
super.disconnectedCallback(), (t = this._$Do) == null || t.setConnected(!1);
}
render() {
return w;
}
};
var rt;
O._$litElement$ = !0, O.finalized = !0, (rt = globalThis.litElementHydrateSupport) == null || rt.call(globalThis, { LitElement: O });
const I = globalThis.litElementPolyfillSupport;
I == null || I({ LitElement: O });
(globalThis.litElementVersions ?? (globalThis.litElementVersions = [])).push("4.1.1");
/**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const Ot = (r) => r.strings === void 0;
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const Rt = { ATTRIBUTE: 1, CHILD: 2, PROPERTY: 3, BOOLEAN_ATTRIBUTE: 4, EVENT: 5, ELEMENT: 6 }, Vt = (r) => (...t) => ({ _$litDirective$: r, values: t });
class Lt {
constructor(t) {
}
get _$AU() {
return this._$AM._$AU;
}
_$AT(t, e, s) {
this._$Ct = t, this._$AM = e, this._$Ci = s;
}
_$AS(t, e) {
return this.update(t, e);
}
update(t, e) {
return this.render(...e);
}
}
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const H = (r, t) => {
var s;
const e = r._$AN;
if (e === void 0) return !1;
for (const i of e) (s = i._$AO) == null || s.call(i, t, !1), H(i, t);
return !0;
}, V = (r) => {
let t, e;
do {
if ((t = r._$AM) === void 0) break;
e = t._$AN, e.delete(r), r = t;
} while ((e == null ? void 0 : e.size) === 0);
}, pt = (r) => {
for (let t; t = r._$AM; r = t) {
let e = t._$AN;
if (e === void 0) t._$AN = e = /* @__PURE__ */ new Set();
else if (e.has(r)) break;
e.add(r), Dt(t);
}
};
function zt(r) {
this._$AN !== void 0 ? (V(this), this._$AM = r, pt(this)) : this._$AM = r;
}
function Bt(r, t = !1, e = 0) {
const s = this._$AH, i = this._$AN;
if (i !== void 0 && i.size !== 0) if (t) if (Array.isArray(s)) for (let o = e; o < s.length; o++) H(s[o], !1), V(s[o]);
else s != null && (H(s, !1), V(s));
else H(this, r);
}
const Dt = (r) => {
r.type == Rt.CHILD && (r._$AP ?? (r._$AP = Bt), r._$AQ ?? (r._$AQ = zt));
};
class It extends Lt {
constructor() {
super(...arguments), this._$AN = void 0;
}
_$AT(t, e, s) {
super._$AT(t, e, s), pt(this), this.isConnected = t._$AU;
}
_$AO(t, e = !0) {
var s, i;
t !== this.isConnected && (this.isConnected = t, t ? (s = this.reconnected) == null || s.call(this) : (i = this.disconnected) == null || i.call(this)), e && (H(this, t), V(this));
}
setValue(t) {
if (Ot(this._$Ct)) this._$Ct._$AI(t, this);
else {
const e = [...this._$Ct._$AH];
e[this._$Ci] = t, this._$Ct._$AI(e, this, 0);
}
}
disconnected() {
}
reconnected() {
}
}
/**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const jt = () => new Yt();
class Yt {
}
const j = /* @__PURE__ */ new WeakMap(), Wt = Vt(class extends It {
render(r) {
return c;
}
update(r, [t]) {
var s;
const e = t !== this.Y;
return e && this.Y !== void 0 && this.rt(void 0), (e || this.lt !== this.ct) && (this.Y = t, this.ht = (s = r.options) == null ? void 0 : s.host, this.rt(this.ct = r.element)), c;
}
rt(r) {
if (this.isConnected || (r = void 0), typeof this.Y == "function") {
const t = this.ht ?? globalThis;
let e = j.get(t);
e === void 0 && (e = /* @__PURE__ */ new WeakMap(), j.set(t, e)), e.get(this.Y) !== void 0 && this.Y.call(this.ht, void 0), e.set(this.Y, r), r !== void 0 && this.Y.call(this.ht, r);
} else this.Y.value = r;
}
get lt() {
var r, t;
return typeof this.Y == "function" ? (r = j.get(this.ht ?? globalThis)) == null ? void 0 : r.get(this.Y) : (t = this.Y) == null ? void 0 : t.value;
}
disconnected() {
this.lt === this.ct && this.rt(void 0);
}
reconnected() {
this.rt(this.ct);
}
});
/**
* @license
* Copyright 2018 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const A = (r) => r ?? c;
var qt = "M2,21V19H20V21H2M20,8V5H18V8H20M20,3A2,2 0 0,1 22,5V8A2,2 0 0,1 20,10H18V13A4,4 0 0,1 14,17H8A4,4 0 0,1 4,13V3H20M16,5H6V13A2,2 0 0,0 8,15H14A2,2 0 0,0 16,13V5Z";
const Y = window.__ingressSession, ut = "ha-tabs", $t = "sl-tab-group", Zt = "ha-tab-group", Jt = document.createElement("ha-panel-custom").navigate, Kt = async (r, t, e) => {
for (let s = 0; s < 2; ++s) {
for (const i of t)
if (customElements.get(i))
return i;
s === 0 && await r(t[0], e);
}
return "";
};
let _t;
class Ft extends HTMLElement {
setConfig(t) {
return this.style.height = "100vh", this.attachShadow({ mode: "open" }), this._views = Object.entries(t.children).filter(([, e]) => (e.title || e.icon) && e.ui_mode !== "replace").map(([e, s]) => (s.name = e, s)), this._iframes = this._views.map(() => jt()), this._curView = 0, this._props = {}, this;
}
connectedCallback() {
this._isHassio && Y.init(this._props.hass);
}
disconnectedCallback() {
this._isHassio && Y.fini();
}
setProperties(t) {
if (t.route) {
const e = (t.route.path || "").split("/", 3)[2], s = this._views.findIndex((i) => i.name === e);
s >= 0 && (this._curView = s);
}
t = Object.assign(this._props, t), dt(this._render(t), this.shadowRoot), this.showPage();
}
async showPage(t) {
var o, n;
if (t = Number(t ?? this._curView), !(t >= 0 && t < this._views.length))
return;
if (t !== this._curView) {
const h = this._iframes[this._curView].value;
h.style.display = "none";
}
this._curView = t;
const e = this._views[t], s = this._iframes[t].value;
if (!s.src) {
const h = e.url;
await this._fixAppShow(h), s.src = h;
}
s.style.display = "";
const i = `/_/${e.name}`;
i !== ((o = this._props.route) == null ? void 0 : o.path) && Jt(`${(n = this._props.route) == null ? void 0 : n.prefix}${i}`);
}
async _fixAppShow(t) {
let e = new URL(t, location.origin);
if (e.origin === location.origin) {
if (!this._isHassio && e.pathname.startsWith("/api/hassio_ingress/")) {
await Y.init(this._props.hass), this._isHassio = !0;
return;
} else if (!e.pathname.startsWith("/api/ingress/")) return;
try {
if (!window.externalApp && !window.webkit) return;
const s = await fetch(e.href);
if (!s.ok || !s.redirected || (e = new URL(s.url), e.origin !== location.origin || !e.searchParams.has("replace"))) return;
const i = document.createElement("partial-panel-resolver");
i.hass = this._props.hass, i.route = { prefix: "", path: e.pathname };
const o = this.shadowRoot;
o.appendChild(i), await new Promise((n) => setTimeout(n, 1e3)), o.removeChild(i);
} catch {
}
}
}
_render(t) {
switch (_t) {
case ut:
return this._render1(t);
case $t:
return this._render2(t);
default:
return this._render3(t);
}
}
_render1(t) {
return u`<style>
ha-tabs {
--paper-tabs-selection-bar-color: var(
--app-header-selection-bar-color,
var(--app-header-text-color, #fff)
);
text-transform: uppercase;
}
iframe {
border: 0;
width: 100%;
height: 100%;
background-color: var(--primary-background-color);
}
</style>
<hass-subpage main-page .hass=${t.hass} .narrow=${t.narrow}>
<ha-tabs
slot="header"
scrollable
.selected=${this._curView}
@iron-activate=${(e) => this.showPage(e.detail.selected)}
>
${this._views.map(
(e) => u`<paper-tab aria-label=${A(e.title)}>
${e.icon ? u`<ha-icon title=${A(e.title)} .icon=${e.icon}></ha-icon>` : e.title || ""}
</paper-tab>`
)}
</ha-tabs>
${this._render_iframes()}
</hass-subpage>`;
}
_render_iframes() {
return u`<a
slot="toolbar-icon"
href="https://buymeacoffee.com/lovelylain"
target="_blank"
rel="noreferrer"
>
<ha-icon-button .label=${"Donate"} .path=${qt}></ha-icon-button>
</a>
${this._views.map(
(t, e) => u`<iframe
${Wt(this._iframes[e])}
title=${A(t.title)}
style="display: none;"
allow="fullscreen"
></iframe>`
)}`;
}
_render2(t) {
return u`<style>
sl-tab-group {
--ha-tab-indicator-color: var(
--app-header-selection-bar-color,
var(--app-header-text-color, white)
);
--ha-tab-active-text-color: var(--app-header-text-color, white);
--ha-tab-track-color: transparent;
align-self: flex-end;
flex-grow: 1;
min-width: 0;
height: 100%;
}
sl-tab-group::part(nav) {
padding: 0;
}
sl-tab-group::part(scroll-button) {
background-color: var(--app-header-background-color);
background: linear-gradient(90deg, var(--app-header-background-color), transparent);
z-index: 1;
}
sl-tab-group::part(scroll-button--end) {
background: linear-gradient(270deg, var(--app-header-background-color), transparent);
}
iframe {
border: 0;
width: 100%;
height: 100%;
background-color: var(--primary-background-color);
}
</style>
<hass-subpage main-page .hass=${t.hass} .narrow=${t.narrow}>
<sl-tab-group slot="header" @sl-tab-show=${(e) => this.showPage(e.detail.name)}>
${this._views.map(
(e, s) => u`<sl-tab
slot="nav"
aria-label=${A(e.title)}
panel=${s}
.active=${this._curView === s}
>
${e.icon ? u`<ha-icon title=${A(e.title)} .icon=${e.icon}></ha-icon>` : e.title || ""}
</sl-tab>`
)}
</sl-tab-group>
${this._render_iframes()}
</hass-subpage>`;
}
_render3(t) {
return u`<style>
ha-tab-group {
--ha-tab-indicator-color: var(
--app-header-selection-bar-color,
var(--app-header-text-color, white)
);
--ha-tab-active-text-color: var(--app-header-text-color, white);
--ha-tab-track-color: transparent;
align-self: flex-end;
flex-grow: 1;
min-width: 0;
height: 100%;
}
ha-tab-group::part(nav) {
padding: 0;
}
ha-tab-group::part(scroll-button) {
background-color: var(--app-header-background-color);
background: linear-gradient(90deg, var(--app-header-background-color), transparent);
z-index: 1;
}
ha-tab-group::part(scroll-button--end) {
background: linear-gradient(270deg, var(--app-header-background-color), transparent);
}
iframe {
border: 0;
width: 100%;
height: 100%;
background-color: var(--primary-background-color);
}
</style>
<hass-subpage main-page .hass=${t.hass} .narrow=${t.narrow}>
<ha-tab-group slot="header" @wa-tab-show=${(e) => this.showPage(e.detail.name)}>
${this._views.map(
(e, s) => u`<ha-tab-group-tab
slot="nav"
aria-label=${A(e.title)}
panel=${s}
.active=${this._curView === s}
>
${e.icon ? u`<ha-icon title=${A(e.title)} .icon=${e.icon}></ha-icon>` : e.title || ""}
</ha-tab-group-tab>`
)}
</ha-tab-group>
${this._render_iframes()}
</hass-subpage>`;
}
}
customElements.define("ha-tabs-ingress", Ft);
const Xt = async (r) => {
const { ensureHaElem: t } = r;
return await t("hass-subpage", "iframe"), _t = await Kt(
t,
[Zt, $t, ut],
"lovelace"
), document.createElement("ha-tabs-ingress").setConfig(r);
};
export {
Xt as default
};
+48
View File
@@ -0,0 +1,48 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<style>
body {
margin: 0;
height: 100vh;
overflow: hidden;
}
iframe {
border: 0;
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<script>
(() => {
const urlParams = new URLSearchParams(window.location.search);
let url = urlParams.get("ingress");
if (!url) return;
let interval = +urlParams.get("refresh");
document.querySelector("body").innerHTML = '<iframe allow="fullscreen"></iframe>';
const iframe = document.querySelector("iframe");
if (/^\/api\/hassio_ingress\/[^/]+/.test(url)) {
if (!(interval >= 5)) interval = 300;
iframe.src = url;
setInterval(() => {
fetch(url, { redirect: "manual" });
}, interval * 1000);
} else if (/^\w+(?:$|\/)/.test(url)) {
url = `/api/ingress/${url}${url.indexOf("/") === -1 ? "/" : ""}`;
iframe.src = url;
if (interval >= 5) {
setInterval(() => {
iframe.src = url;
}, interval * 1000);
}
}
iframe.addEventListener("load", () => {
document.title = iframe.contentDocument.title;
});
})();
</script>
</body>
</html>