Add Home Assistant integration

This commit is contained in:
raucao committed 2026-10-08 19:24:02 +02:00
1 parent e8a8adf846
commit 75a2a65e20
17 files changed
+1453 -3

No files matched your search

@@ -0,0 +1,262 @@
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { service } from '@ember/service';
import { on } from '@ember/modifier';
import {
HomeAssistantAuthError,
HomeAssistantConnectionError,
} from '../../../services/home-assistant';
import {
normalizeHomeAssistantUrl,
profileUrl,
integrationKey,
} from '../../../config/home-assistant';
export default class SettingsIntegrationsHomeAssistantForm extends Component {
@service homeAssistant;
@service notifications;
@service sites;
@service storage;
@tracked urlDraft = null;
@tracked nameDraft = null;
@tracked token = '';
@tracked error = null;
@tracked submitting = false;
get integration() {
return this.args.props?.integration;
}
get isEdit() {
return this.args.props?.mode === 'edit';
}
get url() {
return this.urlDraft ?? this.integration?.url ?? '';
}
get name() {
return this.nameDraft ?? this.integration?.name ?? '';
}
get profileUrl() {
return profileUrl(this.url);
}
get title() {
return this.isEdit ? 'Edit Home Assistant' : 'Add Home Assistant';
}
get submitLabel() {
return this.isEdit ? 'Save' : 'Connect';
}
@action
updateUrl(event) {
this.urlDraft = event.target.value;
this.error = null;
}
@action
updateName(event) {
this.nameDraft = event.target.value;
this.error = null;
}
@action
updateToken(event) {
this.token = event.target.value;
this.error = null;
}
@action
async handleSubmit(event) {
event.preventDefault();
this.error = null;
const instanceUrl = normalizeHomeAssistantUrl(this.url);
if (!instanceUrl) {
this.error = 'Please enter a valid Home Assistant URL';
return;
}
// On edit a blank token keeps the stored one, so users can update the host
// without re-entering the token.
const token = this.token.trim() || this.integration?.token;
if (!token) {
this.error = 'Please enter a long-lived access token';
return;
}
this.submitting = true;
try {
// Opening the socket and reading the counts doubles as a check that the
// token is valid and that the instance serves the WebSocket API.
await this.homeAssistant.fetchSummary({ url: instanceUrl, token });
} catch (err) {
this.error = this.classifyError(err);
return;
} finally {
this.submitting = false;
}
// Key each instance by host so several instances can be connected. Editing
// keeps the existing key even if the host changes.
const key = this.integration?.id ?? integrationKey(instanceUrl);
// A blank name clears the custom label, unlike the token which is kept.
const name = this.name.trim() || undefined;
// Only the credential fields are persisted; the edit row also carries
// display-only fields (avatar, labels) that must not be stored.
await this.storage.set('integrations', key, {
type: 'homeassistant',
status: 'active',
url: instanceUrl,
token,
name,
createdAt: this.integration?.createdAt ?? Date.now(),
});
await this.sites.reload();
this.notifications.startPolling();
this.args.close?.();
}
classifyError(err) {
if (err instanceof HomeAssistantAuthError) {
return 'Invalid access token';
}
if (err instanceof HomeAssistantConnectionError) {
return err.message;
}
return 'Unable to verify your Home Assistant instance';
}
<template>
<div class="p-6">
<h3
id="modal-title"
class="text-base font-semibold leading-6 text-gray-900"
>{{this.title}}</h3>
<div class="mt-2">
<p class="text-sm text-gray-500">
Connect a Home Assistant instance to see your notification count on
the dashboard.
</p>
</div>
<form {{on "submit" this.handleSubmit}} class="mt-5">
<div class="space-y-5">
<div>
<label
for="homeassistant-url"
class="block text-sm font-medium leading-6 text-gray-900"
>
Server URL
</label>
<div class="mt-2">
<input
type="text"
inputmode="url"
id="homeassistant-url"
name="url"
value={{this.url}}
{{on "input" this.updateUrl}}
placeholder="homeassistant.example.com:8123"
class="block w-full rounded-md border-0 px-3 py-2 text-sm text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-indigo-600"
/>
</div>
<p class="mt-2 text-sm text-gray-500">
The URL of your Home Assistant instance.
</p>
</div>
<div>
<label
for="homeassistant-token"
class="block text-sm font-medium leading-6 text-gray-900"
>
Long-lived access token
</label>
<div class="mt-2">
<input
type="password"
id="homeassistant-token"
name="token"
autocomplete="off"
value={{this.token}}
{{on "input" this.updateToken}}
placeholder={{if this.isEdit "Leave blank to keep current" ""}}
class="block w-full rounded-md border-0 px-3 py-2 text-sm text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-indigo-600"
/>
</div>
<p class="mt-2 text-sm text-gray-500">
Create a token in
{{#if this.profileUrl}}
<a
href={{this.profileUrl}}
target="_blank"
rel="noopener noreferrer"
class="text-indigo-600 hover:text-indigo-500"
>your instance's profile settings</a>.
{{else}}
your instance's profile settings.
{{/if}}
</p>
</div>
<div>
<label
for="homeassistant-name"
class="block text-sm font-medium leading-6 text-gray-900"
>
Name
</label>
<div class="mt-2">
<input
type="text"
id="homeassistant-name"
name="name"
autocomplete="off"
value={{this.name}}
{{on "input" this.updateName}}
placeholder="Optional"
class="block w-full rounded-md border-0 px-3 py-2 text-sm text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-indigo-600"
/>
</div>
<p class="mt-2 text-sm text-gray-500">
Optional. Shown on the dashboard tile instead of the host name.
</p>
</div>
{{#if this.error}}
<p class="text-sm text-red-600">{{this.error}}</p>
{{/if}}
</div>
<div class="mt-5 sm:mt-6 flex gap-3">
<button
type="submit"
disabled={{this.submitting}}
class="inline-flex w-full justify-center rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 disabled:opacity-50"
>
{{this.submitLabel}}
</button>
<button
type="button"
{{on "click" @close}}
class="inline-flex w-full justify-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50"
>
Cancel
</button>
</div>
</form>
</div>
</template>
}
+53
View File
@@ -0,0 +1,53 @@
export const HOME_ASSISTANT_ICON_URL = '/img/icons/home-assistant.png';
// The bundled mark is a white glyph on a transparent, padded background, so it
// is rendered on the Home Assistant blue.
export const HOME_ASSISTANT_ICON_BACKGROUND = '#18bcf2';
// Home Assistant is always self-hosted, so there is no default instance. The
// URL is normalized to a bare origin; installs under a subpath are not
// supported (the origin is all we keep).
export function normalizeHomeAssistantUrl(input) {
let value = (input ?? '').trim();
if (!value || /\s/.test(value)) {
return null;
}
if (!/^https?:\/\//i.test(value)) {
value = `https://${value}`;
}
try {
return new URL(value).origin;
} catch {
return null;
}
}
// The WebSocket API endpoint. Home Assistant authenticates on the socket with
// the access token sent in the first message, so no headers are involved and
// the browser can open it directly.
export function websocketUrl(instanceUrl) {
const origin = normalizeHomeAssistantUrl(instanceUrl);
if (!origin) {
return null;
}
const socketOrigin = origin.replace(/^http/i, 'ws');
return `${socketOrigin}/api/websocket`;
}
// Where the user creates a long-lived access token for this instance. On
// current Home Assistant these live under the profile's Security section.
export function profileUrl(instanceUrl) {
const origin = normalizeHomeAssistantUrl(instanceUrl);
return origin ? `${origin}/profile/security` : null;
}
// Storage key for a connected instance, unique per host (including port) so
// several Home Assistant instances can be connected side by side.
export function integrationKey(instanceUrl) {
const origin = normalizeHomeAssistantUrl(instanceUrl);
return origin ? `homeassistant-${new URL(origin).host}` : null;
}
+2
View File
@@ -3,6 +3,7 @@ import BitcoinForm from '../components/settings/integrations/bitcoin-form.gjs';
import FeedbinForm from '../components/settings/integrations/feedbin-form.gjs';
import GithubForm from '../components/settings/integrations/github-form.gjs';
import GiteaForm from '../components/settings/integrations/gitea-form.gjs';
import HomeAssistantForm from '../components/settings/integrations/home-assistant-form.gjs';
const FORMS = {
discourse: DiscourseForm,
@@ -10,6 +11,7 @@ const FORMS = {
feedbin: FeedbinForm,
github: GithubForm,
gitea: GiteaForm,
homeassistant: HomeAssistantForm,
};
export function formFor(type) {
+16
View File
@@ -1,5 +1,9 @@
import { GITHUB_ICON_BACKGROUND, GITHUB_ICON_URL } from './github';
import { GITEA_ICON_BACKGROUND, GITEA_ICON_URL } from './gitea';
import {
HOME_ASSISTANT_ICON_URL,
HOME_ASSISTANT_ICON_BACKGROUND,
} from './home-assistant';
const PENCIL_ICON_PATH =
'm16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10';
@@ -73,6 +77,18 @@ export const INTEGRATIONS = [
hasSettings: true,
reconnectable: false,
},
{
id: 'homeassistant',
label: 'Home Assistant',
description: 'Notifications from your Home Assistant instances',
colorClass: 'bg-[#18BCF2]',
iconUrl: HOME_ASSISTANT_ICON_URL,
themeColor: HOME_ASSISTANT_ICON_BACKGROUND,
available: true,
supportsMultiple: true,
hasSettings: true,
reconnectable: false,
},
];
export function integrationFor(type) {
+5
View File
@@ -14,4 +14,9 @@ export const SITE_GROUPS = [
label: 'Feedbin',
integrationTypes: ['feedbin'],
},
{
id: 'home-assistant',
label: 'Home Assistant',
integrationTypes: ['homeassistant'],
},
];
+261
View File
@@ -0,0 +1,261 @@
import Service from '@ember/service';
import { websocketUrl } from '../config/home-assistant';
export const HOME_ASSISTANT_SOCKET_TIMEOUT = 10000;
// The INSTALL bit on an update entity's `supported_features`. Used to mirror
// Home Assistant's own "can install" check when counting pending updates.
const UPDATE_FEATURE_INSTALL = 1;
export class HomeAssistantAuthError extends Error {
constructor(message = 'Home Assistant rejected the access token') {
super(message);
this.name = 'HomeAssistantAuthError';
}
}
export class HomeAssistantConnectionError extends Error {
constructor(message = 'Unable to reach Home Assistant') {
super(message);
this.name = 'HomeAssistantConnectionError';
}
}
// Counts pending updates from a `subscribe_entities` init event. The event is
// keyed by entity id with compressed states (`s` is the state, `a` the
// attributes), and already filtered server-side to the `update` domain.
export function updateCountFromEntities(event) {
const entities = event?.a ?? {};
return Object.values(entities).filter((state) => {
if (state?.s !== 'on') {
return false;
}
const features = state?.a?.supported_features;
return (
typeof features !== 'number' || (features & UPDATE_FEATURE_INSTALL) !== 0
);
}).length;
}
// Talks to a single Home Assistant instance over a short-lived WebSocket. Each
// poll opens the socket, authenticates with the long-lived access token, asks
// for persistent notifications, repair issues and pending updates, then closes.
// Reports each count separately and offers a single `fetchSummary` that sums
// them for the dashboard badge.
export default class HomeAssistantService extends Service {
createSocket(url) {
return new WebSocket(url);
}
async fetchSummary(integration, options = {}) {
const breakdown = await this.fetchBreakdown(integration, options);
return {
...breakdown,
unreadCount:
breakdown.persistentCount +
breakdown.repairsCount +
breakdown.updatesCount,
};
}
async fetchBreakdown(
integration,
{ timeout = HOME_ASSISTANT_SOCKET_TIMEOUT } = {}
) {
const url = websocketUrl(integration?.url);
const token = integration?.token;
if (!url || !token) {
throw new HomeAssistantConnectionError(
'Home Assistant is not configured'
);
}
const socket = this.createSocket(url);
return this.collect(socket, token, timeout);
}
collect(socket, token, timeout) {
return new Promise((resolve, reject) => {
const pending = new Map();
let nextId = 1;
let authSent = false;
let finished = false;
const cleanup = () => {
clearTimeout(timer);
socket.removeEventListener('message', onMessage);
socket.removeEventListener('error', onError);
socket.removeEventListener('close', onClose);
socket.removeEventListener('open', onOpen);
try {
socket.close();
} catch {
// The socket may already be closed.
}
};
const fail = (error) => {
if (finished) {
return;
}
finished = true;
cleanup();
reject(error);
};
const succeed = (value) => {
if (finished) {
return;
}
finished = true;
cleanup();
resolve(value);
};
const timer = setTimeout(() => {
fail(new HomeAssistantConnectionError('Home Assistant timed out'));
}, timeout);
const authenticate = () => {
if (authSent) {
return;
}
authSent = true;
socket.send(JSON.stringify({ type: 'auth', access_token: token }));
};
const send = (type, extra = {}) => {
const id = nextId;
nextId += 1;
socket.send(JSON.stringify({ id, type, ...extra }));
return id;
};
// A plain command resolves on its matching `result` message.
const command = (type, extra) =>
new Promise((commandResolve, commandReject) => {
const id = send(type, extra);
pending.set(id, {
resolve: (result) => {
pending.delete(id);
commandResolve(result);
},
reject: (error) => {
pending.delete(id);
commandReject(error);
},
});
});
// A subscription acknowledges with a `result` (ignored) and delivers its
// payload in a follow-up `event`, which is what we resolve on.
const subscription = (type, extra) =>
new Promise((subscriptionResolve, subscriptionReject) => {
const id = send(type, extra);
pending.set(id, {
onEvent: (event) => {
pending.delete(id);
subscriptionResolve(event);
},
resolve: () => {},
reject: (error) => {
pending.delete(id);
subscriptionReject(error);
},
});
});
const start = async () => {
try {
const [persistent, repairs, updateEvent] = await Promise.all([
command('persistent_notification/get'),
// Repair issues are only exposed to some users; a missing list must
// not take down the whole badge.
command('repairs/list_issues').catch(() => ({ issues: [] })),
subscription('subscribe_entities', {
include: { domains: ['update'] },
}),
]);
succeed({
persistentCount: Array.isArray(persistent) ? persistent.length : 0,
repairsCount: (repairs?.issues ?? []).filter(
(issue) => !issue.ignored
).length,
updatesCount: updateCountFromEntities(updateEvent),
});
} catch (error) {
fail(error);
}
};
const onOpen = () => authenticate();
const onError = () =>
fail(
new HomeAssistantConnectionError('Home Assistant connection failed')
);
const onClose = () =>
fail(
new HomeAssistantConnectionError(
'Home Assistant closed the connection'
)
);
const onMessage = (event) => {
let message;
try {
message = JSON.parse(event.data);
} catch {
return;
}
switch (message.type) {
case 'auth_required':
authenticate();
return;
case 'auth_invalid':
fail(new HomeAssistantAuthError());
return;
case 'auth_ok':
start();
return;
case 'result': {
const entry = pending.get(message.id);
if (!entry) {
return;
}
if (message.success === false) {
entry.reject(
new HomeAssistantConnectionError(
message.error?.message ?? 'Home Assistant returned an error'
)
);
return;
}
entry.resolve(message.result);
return;
}
case 'event': {
const entry = pending.get(message.id);
entry?.onEvent?.(message.event);
return;
}
default:
}
};
socket.addEventListener('message', onMessage);
socket.addEventListener('error', onError);
socket.addEventListener('close', onClose);
socket.addEventListener('open', onOpen);
});
}
}
+34 -1
View File
@@ -120,6 +120,37 @@ const ADAPTERS = {
return this.sites.removeSource(instance.id);
},
},
homeassistant: {
instances() {
return this.sites.all
.filter((site) => site.type === 'homeassistant')
.map((site) => {
const state = this.notifications.stateFor(site);
const integration = this.sites.integrationFor(site.id);
return {
id: site.id,
type: 'homeassistant',
label: site.label,
icon: site.icon,
status: 'active',
// Passed through so the edit form can prefill the host, custom
// name, and keep the stored token when the token field is blank.
url: integration?.url,
name: integration?.name,
token: integration?.token,
error: state.error,
errorType: state.errorType,
// Home Assistant uses a long-lived access token, so fixing a
// rejected credential happens through the Settings form.
canReconnect: false,
};
});
},
remove(instance) {
return this.sites.removeSource(instance.id);
},
},
bitcoin: {
instances() {
if (!this.bitcoin.enabled) {
@@ -168,7 +199,9 @@ export default class IntegrationsService extends Service {
this.instancesFor(integration.id).map((instance) => ({
...instance,
type: integration.id,
label: integration.label,
// Prefer a per-instance custom name (e.g. Home Assistant) over the
// shared registry label.
label: instance.name ?? integration.label,
byline: displayUrl(instance.url) || integration.description,
colorClass: integration.colorClass,
iconPath: integration.iconPath,
+46 -2
View File
@@ -15,6 +15,10 @@ import {
notificationsCountUrl,
unreadCountFromResponse,
} from '../config/gitea';
import {
HomeAssistantAuthError,
HomeAssistantConnectionError,
} from './home-assistant';
export const NOTIFICATIONS_DEFAULT_INTERVAL = 60000;
@@ -110,27 +114,52 @@ async function fetchGiteaNotifications(integration, http) {
};
}
// Home Assistant exposes persistent notifications and repair issues over its
// WebSocket API, and pending updates as `update` entities. The `home-assistant`
// service does all of that over a short-lived socket and returns a summed
// count, so the adapter is a thin pass-through.
async function fetchHomeAssistantNotifications(
integration,
http,
homeAssistant
) {
const { unreadCount } = await homeAssistant.fetchSummary(integration);
return {
unreadCount,
notifications: [],
};
}
const ADAPTERS = {
discourse: fetchDiscourseNotifications,
feedbin: fetchFeedbinNotifications,
github: fetchGithubNotifications,
gitea: fetchGiteaNotifications,
homeassistant: fetchHomeAssistantNotifications,
};
// Per-integration wording for classified failures; anything not listed falls
// back to the generic forum wording.
const FORUM_LABELS = { github: 'GitHub', gitea: 'Gitea', feedbin: 'Feedbin' };
const FORUM_LABELS = {
github: 'GitHub',
gitea: 'Gitea',
feedbin: 'Feedbin',
homeassistant: 'Home Assistant',
};
const UNAUTHORIZED_MESSAGES = {
github: 'Update GitHub token',
gitea: 'Update Gitea token',
feedbin: 'Update Feedbin credentials',
homeassistant: 'Update Home Assistant token',
};
const UNREACHABLE_MESSAGES = {
github: 'GitHub blocked — enable CORS or open the GitHub host',
gitea: 'Gitea blocked — enable CORS on the instance or open it',
feedbin: 'Feedbin blocked — enable CORS or open feedbin.com',
homeassistant: 'Home Assistant blocked — check the URL or open it',
};
function defaultState(type) {
@@ -147,6 +176,7 @@ function defaultState(type) {
export default class NotificationsService extends Service {
@service sites;
@service http;
@service homeAssistant;
@tracked states = {};
@@ -210,7 +240,8 @@ export default class NotificationsService extends Service {
try {
const result = await adapter(
this.sites.integrationFor(site.id),
this.http
this.http,
this.homeAssistant
);
this.setState(site.id, {
status: 'ready',
@@ -231,6 +262,19 @@ export default class NotificationsService extends Service {
classifyError(err, site) {
const type = site?.type;
if (err instanceof HomeAssistantAuthError) {
return {
errorType: 'unauthorized',
error: UNAUTHORIZED_MESSAGES[type] ?? 'Update Home Assistant token',
};
}
if (err instanceof HomeAssistantConnectionError) {
return {
errorType: 'unreachable',
error: UNREACHABLE_MESSAGES[type] ?? err.message,
};
}
if (err instanceof HttpError) {
if (err.errorType === 'not_logged_in') {
return {
+23
View File
@@ -10,6 +10,10 @@ import {
isGithubDotCom,
} from '../config/github';
import { GITEA_ICON_BACKGROUND, GITEA_ICON_URL } from '../config/gitea';
import {
HOME_ASSISTANT_ICON_BACKGROUND,
HOME_ASSISTANT_ICON_URL,
} from '../config/home-assistant';
import { normalizeOrigin } from './site-icons';
function labelForUrl(url) {
@@ -140,6 +144,25 @@ export default class SitesService extends Service {
};
}
// Home Assistant is always self-hosted and does not expose a discoverable
// site icon, so it uses the bundled mark. Leaving `url` unset keeps
// `resolveIcons` from probing the instance with an icon request.
if (integration.type === 'homeassistant') {
return {
id: key,
type: 'homeassistant',
groupId: this.groupIdForType('homeassistant'),
label: integration.name?.trim() || labelForUrl(integration.url),
url: undefined,
href: `${integration.url}/`,
icon: {
dataUrl: HOME_ASSISTANT_ICON_URL,
maskable: true,
themeColor: HOME_ASSISTANT_ICON_BACKGROUND,
},
};
}
return {
id: key,
type: integration.type,
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

@@ -85,6 +85,17 @@ module(
assert.dom('[data-add="github"]').doesNotHaveAttribute('disabled');
assert.dom('[data-add="gitea"] img[src="/img/icons/gitea.png"]').exists();
assert.dom('[data-add="gitea"]').doesNotHaveAttribute('disabled');
assert.dom().containsText('Home Assistant');
assert
.dom()
.containsText('Notifications from your Home Assistant instances');
assert
.dom(
'[data-add="homeassistant"] img[src="/img/icons/home-assistant.png"]'
)
.exists();
assert.dom('[data-add="homeassistant"]').doesNotHaveAttribute('disabled');
});
test('clicking an integration opens its add form', async function (assert) {
@@ -0,0 +1,262 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render, fillIn, triggerEvent } from '@ember/test-helpers';
import HomeAssistant from 'dashtab/components/settings/integrations/home-assistant-form';
import { HomeAssistantAuthError } from 'dashtab/services/home-assistant';
function registerServices(owner, overrides = {}) {
const homeAssistant = overrides.homeAssistant ?? {
fetchSummary: async () => ({}),
};
const storage = overrides.storage ?? { set: async () => {} };
const sites = overrides.sites ?? { reload: async () => {} };
const notifications = overrides.notifications ?? { startPolling: () => {} };
owner.register('service:home-assistant', homeAssistant, {
instantiate: false,
});
owner.register('service:storage', storage, { instantiate: false });
owner.register('service:sites', sites, { instantiate: false });
owner.register('service:notifications', notifications, {
instantiate: false,
});
}
module(
'Integration | Component | settings/integrations/home-assistant-form',
function (hooks) {
setupRenderingTest(hooks);
test('it renders the token form without a default URL', async function (assert) {
registerServices(this.owner);
const noop = () => {};
await render(<template><HomeAssistant @close={{noop}} /></template>);
assert.dom().containsText('Add Home Assistant');
assert.dom('#homeassistant-url').exists().hasValue('');
assert.dom('#homeassistant-token').exists();
assert.dom('#homeassistant-name').exists().hasValue('');
assert.dom('form').exists();
});
test('it links to the profile settings once a URL is entered', async function (assert) {
registerServices(this.owner);
const noop = () => {};
await render(<template><HomeAssistant @close={{noop}} /></template>);
assert
.dom('a[href="https://ha.example.com:8123/profile/security"]')
.doesNotExist();
await fillIn('#homeassistant-url', 'ha.example.com:8123');
assert
.dom('a[href="https://ha.example.com:8123/profile/security"]')
.exists()
.hasAttribute('target', '_blank');
});
test('submitting validates and stores the credentials under a host key', async function (assert) {
const verified = [];
const saved = [];
let reloaded = false;
let polling = false;
let closed = false;
registerServices(this.owner, {
homeAssistant: {
fetchSummary: async (integration) => {
verified.push(integration);
return { unreadCount: 0 };
},
},
storage: {
set: async (namespace, key, value) =>
saved.push({ namespace, key, value }),
},
sites: {
reload: async () => {
reloaded = true;
},
},
notifications: {
startPolling: () => {
polling = true;
},
},
});
const closeDialog = () => {
closed = true;
};
await render(
<template><HomeAssistant @close={{closeDialog}} /></template>
);
await fillIn('#homeassistant-url', 'ha.example.com:8123');
await fillIn('#homeassistant-token', 'llat_secret');
await fillIn('#homeassistant-name', ' Home ');
await triggerEvent('form', 'submit');
assert.strictEqual(verified.length, 1);
assert.strictEqual(verified[0].url, 'https://ha.example.com:8123');
assert.strictEqual(verified[0].token, 'llat_secret');
assert.strictEqual(saved.length, 1);
assert.strictEqual(saved[0].namespace, 'integrations');
assert.strictEqual(saved[0].key, 'homeassistant-ha.example.com:8123');
assert.strictEqual(saved[0].value.type, 'homeassistant');
assert.strictEqual(saved[0].value.status, 'active');
assert.strictEqual(saved[0].value.url, 'https://ha.example.com:8123');
assert.strictEqual(saved[0].value.token, 'llat_secret');
assert.strictEqual(saved[0].value.name, 'Home');
assert.true(reloaded);
assert.true(polling);
assert.true(closed);
});
test('it omits the name when left blank', async function (assert) {
const saved = [];
registerServices(this.owner, {
homeAssistant: {
fetchSummary: async () => ({ unreadCount: 0 }),
},
storage: {
set: async (namespace, key, value) =>
saved.push({ namespace, key, value }),
},
});
const noop = () => {};
await render(<template><HomeAssistant @close={{noop}} /></template>);
await fillIn('#homeassistant-url', 'ha.example.com:8123');
await fillIn('#homeassistant-token', 'llat_secret');
await triggerEvent('form', 'submit');
assert.strictEqual(saved.length, 1);
assert.strictEqual(saved[0].value.name, undefined);
});
test('it rejects an invalid server URL', async function (assert) {
const verified = [];
registerServices(this.owner, {
homeAssistant: {
fetchSummary: async (...args) => verified.push(args),
},
});
const noop = () => {};
await render(<template><HomeAssistant @close={{noop}} /></template>);
await fillIn('#homeassistant-url', 'not a valid url');
await fillIn('#homeassistant-token', 'llat_secret');
await triggerEvent('form', 'submit');
assert.dom('#homeassistant-url').hasValue('not a valid url');
assert.dom().containsText('Please enter a valid Home Assistant URL');
assert.strictEqual(verified.length, 0);
});
test('it reports an invalid token without storing it', async function (assert) {
const saved = [];
let closed = false;
registerServices(this.owner, {
homeAssistant: {
fetchSummary: async () => {
throw new HomeAssistantAuthError();
},
},
storage: {
set: async (...args) => saved.push(args),
},
});
const closeDialog = () => {
closed = true;
};
await render(
<template><HomeAssistant @close={{closeDialog}} /></template>
);
await fillIn('#homeassistant-url', 'ha.example.com:8123');
await fillIn('#homeassistant-token', 'bad');
await triggerEvent('form', 'submit');
assert.dom().containsText('Invalid access token');
assert.strictEqual(saved.length, 0);
assert.false(closed);
});
test('it requires a server URL and token', async function (assert) {
registerServices(this.owner);
const noop = () => {};
await render(<template><HomeAssistant @close={{noop}} /></template>);
await triggerEvent('form', 'submit');
assert.dom().containsText('Please enter a valid Home Assistant URL');
await fillIn('#homeassistant-url', 'ha.example.com:8123');
await triggerEvent('form', 'submit');
assert.dom().containsText('Please enter a long-lived access token');
});
test('edit mode prefills the host and keeps the stored token and key', async function (assert) {
const verified = [];
const saved = [];
registerServices(this.owner, {
homeAssistant: {
fetchSummary: async (integration) => {
verified.push(integration);
return { unreadCount: 0 };
},
},
storage: {
set: async (namespace, key, value) =>
saved.push({ namespace, key, value }),
},
});
this.props = {
mode: 'edit',
integration: {
id: 'homeassistant-ha.example.com:8123',
url: 'https://ha.example.com:8123',
token: 'OLDT0KEN',
name: 'Home',
colorClass: 'bg-[#18BCF2]',
},
};
const noop = () => {};
await render(
<template>
<HomeAssistant @props={{this.props}} @close={{noop}} />
</template>
);
assert.dom().containsText('Edit Home Assistant');
assert.dom('#homeassistant-url').hasValue('https://ha.example.com:8123');
assert.dom('#homeassistant-name').hasValue('Home');
await triggerEvent('form', 'submit');
assert.strictEqual(verified.length, 1);
assert.strictEqual(verified[0].token, 'OLDT0KEN');
assert.strictEqual(saved.length, 1);
assert.strictEqual(saved[0].key, 'homeassistant-ha.example.com:8123');
assert.strictEqual(saved[0].value.url, 'https://ha.example.com:8123');
assert.strictEqual(saved[0].value.token, 'OLDT0KEN');
assert.strictEqual(saved[0].value.name, 'Home');
assert.strictEqual(saved[0].value.colorClass, undefined);
});
}
);
+59
View File
@@ -0,0 +1,59 @@
import { module, test } from 'qunit';
import {
integrationKey,
normalizeHomeAssistantUrl,
profileUrl,
websocketUrl,
} from 'dashtab/config/home-assistant';
module('Unit | Config | home-assistant', function () {
test('normalizeHomeAssistantUrl normalizes input and rejects junk', function (assert) {
assert.strictEqual(
normalizeHomeAssistantUrl('ha.example.com:8123'),
'https://ha.example.com:8123'
);
assert.strictEqual(
normalizeHomeAssistantUrl('https://ha.example.com:8123/'),
'https://ha.example.com:8123'
);
assert.strictEqual(
normalizeHomeAssistantUrl('http://192.168.1.10:8123'),
'http://192.168.1.10:8123'
);
assert.strictEqual(normalizeHomeAssistantUrl(''), null);
assert.strictEqual(normalizeHomeAssistantUrl(' '), null);
assert.strictEqual(normalizeHomeAssistantUrl('not a valid url'), null);
});
test('websocketUrl switches the scheme and appends the socket path', function (assert) {
assert.strictEqual(
websocketUrl('https://ha.example.com:8123'),
'wss://ha.example.com:8123/api/websocket'
);
assert.strictEqual(
websocketUrl('http://192.168.1.10:8123'),
'ws://192.168.1.10:8123/api/websocket'
);
assert.strictEqual(websocketUrl(''), null);
});
test('profileUrl points at the token page', function (assert) {
assert.strictEqual(
profileUrl('https://ha.example.com:8123'),
'https://ha.example.com:8123/profile/security'
);
assert.strictEqual(profileUrl(''), null);
});
test('integrationKey is unique per host and port', function (assert) {
assert.strictEqual(
integrationKey('https://ha.example.com'),
'homeassistant-ha.example.com'
);
assert.strictEqual(
integrationKey('https://ha.example.com:8123'),
'homeassistant-ha.example.com:8123'
);
assert.strictEqual(integrationKey(''), null);
});
});
+214
View File
@@ -0,0 +1,214 @@
import { module, test } from 'qunit';
import { setupTest } from 'dashtab/tests/helpers';
import {
HomeAssistantAuthError,
HomeAssistantConnectionError,
updateCountFromEntities,
} from 'dashtab/services/home-assistant';
class FakeSocket {
constructor() {
this.sent = [];
this.listeners = { message: [], error: [], close: [], open: [] };
this.closed = false;
}
addEventListener(type, handler) {
this.listeners[type].push(handler);
}
removeEventListener(type, handler) {
this.listeners[type] = this.listeners[type].filter(
(candidate) => candidate !== handler
);
}
send(data) {
this.sent.push(JSON.parse(data));
}
close() {
this.closed = true;
}
emit(type, event = {}) {
for (const handler of [...this.listeners[type]]) {
handler(event);
}
}
emitMessage(message) {
this.emit('message', { data: JSON.stringify(message) });
}
find(type) {
return this.sent.find((message) => message.type === type);
}
}
module('Unit | Service | home-assistant', function (hooks) {
setupTest(hooks);
function setup(overrides = {}) {
const service = this.owner.lookup('service:home-assistant');
const socket = new FakeSocket();
service.createSocket = () => socket;
return { service, socket, ...overrides };
}
test('it exists', function (assert) {
assert.ok(this.owner.lookup('service:home-assistant'));
});
test('updateCountFromEntities counts installable pending updates', function (assert) {
const event = {
a: {
'update.a': { s: 'on', a: { supported_features: 1 } },
'update.b': { s: 'off', a: { supported_features: 1 } },
'update.c': { s: 'on', a: { supported_features: 0 } },
'update.d': { s: 'on', a: {} },
},
};
assert.strictEqual(updateCountFromEntities(event), 2);
assert.strictEqual(updateCountFromEntities(null), 0);
});
test('fetchSummary sums persistent, repair and update counts', async function (assert) {
const { service, socket } = setup.call(this);
const promise = service.fetchSummary({
url: 'https://ha.example.com:8123',
token: 'tok',
});
socket.emit('open');
const auth = socket.find('auth');
assert.deepEqual(auth, { type: 'auth', access_token: 'tok' });
socket.emitMessage({ type: 'auth_ok' });
const persistent = socket.find('persistent_notification/get');
const repairs = socket.find('repairs/list_issues');
const subscription = socket.find('subscribe_entities');
assert.ok(persistent);
assert.ok(repairs);
assert.deepEqual(subscription.include, { domains: ['update'] });
socket.emitMessage({
id: persistent.id,
type: 'result',
success: true,
result: [{ notification_id: 'a' }, { notification_id: 'b' }],
});
socket.emitMessage({
id: repairs.id,
type: 'result',
success: true,
result: { issues: [{ ignored: false }, { ignored: true }] },
});
socket.emitMessage({
id: subscription.id,
type: 'result',
success: true,
result: null,
});
socket.emitMessage({
id: subscription.id,
type: 'event',
event: {
a: {
'update.a': { s: 'on', a: { supported_features: 1 } },
'update.b': { s: 'off', a: { supported_features: 1 } },
},
},
});
assert.deepEqual(await promise, {
persistentCount: 2,
repairsCount: 1,
updatesCount: 1,
unreadCount: 4,
});
assert.true(socket.closed);
});
test('fetchSummary tolerates a missing repair list', async function (assert) {
const { service, socket } = setup.call(this);
const promise = service.fetchSummary({
url: 'https://ha.example.com:8123',
token: 'tok',
});
socket.emitMessage({ type: 'auth_required' });
socket.emitMessage({ type: 'auth_ok' });
const persistent = socket.find('persistent_notification/get');
const repairs = socket.find('repairs/list_issues');
const subscription = socket.find('subscribe_entities');
socket.emitMessage({
id: persistent.id,
type: 'result',
success: true,
result: [],
});
socket.emitMessage({
id: repairs.id,
type: 'result',
success: false,
error: { message: 'Unauthorized' },
});
socket.emitMessage({
id: subscription.id,
type: 'result',
success: true,
result: null,
});
socket.emitMessage({
id: subscription.id,
type: 'event',
event: { a: {} },
});
const summary = await promise;
assert.strictEqual(summary.repairsCount, 0);
assert.strictEqual(summary.unreadCount, 0);
});
test('fetchSummary rejects an invalid token', async function (assert) {
const { service, socket } = setup.call(this);
const promise = service.fetchSummary({
url: 'https://ha.example.com:8123',
token: 'bad',
});
socket.emitMessage({ type: 'auth_required' });
socket.emitMessage({ type: 'auth_invalid' });
await assert.rejects(promise, HomeAssistantAuthError);
});
test('fetchSummary reports a configuration error without a token', async function (assert) {
const { service } = setup.call(this);
await assert.rejects(
service.fetchSummary({ url: 'https://ha.example.com:8123' }),
HomeAssistantConnectionError
);
});
test('fetchSummary times out when the socket never responds', async function (assert) {
const { service } = setup.call(this);
await assert.rejects(
service.fetchSummary(
{ url: 'https://ha.example.com:8123', token: 'tok' },
{ timeout: 5 }
),
HomeAssistantConnectionError
);
});
});
+58
View File
@@ -77,6 +77,9 @@ module('Unit | Service | integrations', function (hooks) {
const bitcoinEntry = service.all.find((entry) => entry.id === 'bitcoin');
const github = service.all.find((entry) => entry.id === 'github');
const gitea = service.all.find((entry) => entry.id === 'gitea');
const homeassistant = service.all.find(
(entry) => entry.id === 'homeassistant'
);
assert.true(discourse.supportsMultiple);
assert.false(discourse.hasSettings);
@@ -101,6 +104,13 @@ module('Unit | Service | integrations', function (hooks) {
assert.false(gitea.reconnectable);
assert.strictEqual(gitea.themeColor, '#ffffff');
assert.strictEqual(gitea.instances.length, 0);
assert.true(homeassistant.available);
assert.true(homeassistant.supportsMultiple);
assert.true(homeassistant.hasSettings);
assert.false(homeassistant.reconnectable);
assert.strictEqual(homeassistant.themeColor, '#18bcf2');
assert.strictEqual(homeassistant.instances.length, 0);
});
test('rows is empty when nothing is connected', function (assert) {
@@ -290,4 +300,52 @@ module('Unit | Service | integrations', function (hooks) {
assert.strictEqual(gitea.instances[0].token, 'token-a');
assert.false(gitea.instances[0].canReconnect);
});
test('homeassistant adapter exposes every connected instance without reconnect', async function (assert) {
const sites = new FakeSitesService();
sites.all = [
{
id: 'homeassistant-ha.example.com:8123',
type: 'homeassistant',
label: 'ha.example.com:8123',
href: 'https://ha.example.com:8123/',
},
];
sites.records = {
'homeassistant-ha.example.com:8123': {
url: 'https://ha.example.com:8123',
token: 'token-a',
name: 'Home',
},
};
register(this.owner, { sites });
const service = this.owner.lookup('service:integrations');
const homeassistant = service.all.find(
(entry) => entry.id === 'homeassistant'
);
assert.true(homeassistant.supportsMultiple);
assert.true(homeassistant.hasSettings);
assert.false(homeassistant.reconnectable);
assert.strictEqual(homeassistant.instances.length, 1);
assert.strictEqual(
homeassistant.instances[0].id,
'homeassistant-ha.example.com:8123'
);
assert.strictEqual(
homeassistant.instances[0].url,
'https://ha.example.com:8123'
);
assert.strictEqual(homeassistant.instances[0].name, 'Home');
assert.strictEqual(homeassistant.instances[0].token, 'token-a');
assert.false(homeassistant.instances[0].canReconnect);
const row = service.rows.find(
(entry) => entry.id === 'homeassistant-ha.example.com:8123'
);
assert.strictEqual(row.label, 'Home');
assert.strictEqual(row.byline, 'ha.example.com:8123');
});
});
+97
View File
@@ -1,5 +1,9 @@
import { module, test } from 'qunit';
import { setupTest } from 'dashtab/tests/helpers';
import {
HomeAssistantAuthError,
HomeAssistantConnectionError,
} from 'dashtab/services/home-assistant';
module('Unit | Service | notifications', function (hooks) {
setupTest(hooks);
@@ -67,6 +71,7 @@ module('Unit | Service | notifications', function (hooks) {
assert.true(service.isPollable({ type: 'feedbin' }));
assert.true(service.isPollable({ type: 'github' }));
assert.true(service.isPollable({ type: 'gitea' }));
assert.true(service.isPollable({ type: 'homeassistant' }));
assert.false(service.isPollable({ type: 'unknown' }));
service.stopPolling();
@@ -716,4 +721,96 @@ module('Unit | Service | notifications', function (hooks) {
service.stopPolling();
assert.strictEqual(service.intervalId, null);
});
test('fetchSite reads the Home Assistant summed count', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'homeassistant-ha.example.com', {
type: 'homeassistant',
status: 'active',
url: 'https://ha.example.com:8123',
token: 'token',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
let requested;
service.homeAssistant.fetchSummary = async (integration) => {
requested = integration;
return { unreadCount: 4 };
};
const [site] = service.sites.all;
await service.fetchSite(site);
assert.strictEqual(requested.url, 'https://ha.example.com:8123');
assert.strictEqual(requested.token, 'token');
const state = service.stateFor(site);
assert.strictEqual(state.status, 'ready');
assert.strictEqual(state.unreadCount, 4);
assert.deepEqual(state.items, []);
service.stopPolling();
});
test('fetchSite flags an invalid Home Assistant token', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'homeassistant-ha.example.com', {
type: 'homeassistant',
status: 'active',
url: 'https://ha.example.com:8123',
token: 'stale',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
service.homeAssistant.fetchSummary = async () => {
throw new HomeAssistantAuthError();
};
const [site] = service.sites.all;
await service.fetchSite(site);
const state = service.stateFor(site);
assert.strictEqual(state.status, 'error');
assert.strictEqual(state.errorType, 'unauthorized');
assert.strictEqual(state.error, 'Update Home Assistant token');
service.stopPolling();
});
test('fetchSite flags an unreachable Home Assistant instance', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'homeassistant-ha.example.com', {
type: 'homeassistant',
status: 'active',
url: 'https://ha.example.com:8123',
token: 'token',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
service.homeAssistant.fetchSummary = async () => {
throw new HomeAssistantConnectionError();
};
const [site] = service.sites.all;
await service.fetchSite(site);
const state = service.stateFor(site);
assert.strictEqual(state.status, 'error');
assert.strictEqual(state.errorType, 'unreachable');
assert.strictEqual(
state.error,
'Home Assistant blocked — check the URL or open it'
);
service.stopPolling();
});
});
+50
View File
@@ -200,6 +200,56 @@ module('Unit | Service | sites', function (hooks) {
);
});
test('load builds a Home Assistant site keyed by host and links to the root', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'homeassistant-ha.example.com:8123', {
type: 'homeassistant',
status: 'active',
url: 'https://ha.example.com:8123',
token: 'llat_token',
});
const service = this.owner.lookup('service:sites');
await service.ready;
assert.strictEqual(service.all.length, 1);
const [item] = service.all;
assert.strictEqual(item.id, 'homeassistant-ha.example.com:8123');
assert.strictEqual(item.label, 'ha.example.com');
assert.strictEqual(item.groupId, 'home-assistant');
assert.strictEqual(item.href, 'https://ha.example.com:8123/');
assert.notOk(item.url);
assert.deepEqual(item.icon, {
dataUrl: '/img/icons/home-assistant.png',
maskable: true,
themeColor: '#18bcf2',
});
const groups = service.groups;
assert.strictEqual(groups.length, 1);
assert.strictEqual(groups[0].id, 'home-assistant');
assert.strictEqual(groups[0].label, 'Home Assistant');
});
test('a Home Assistant custom name overrides the host label', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'homeassistant-ha.example.com:8123', {
type: 'homeassistant',
status: 'active',
url: 'https://ha.example.com:8123',
token: 'llat_token',
name: ' Home ',
});
const service = this.owner.lookup('service:sites');
await service.ready;
const [item] = service.all;
assert.strictEqual(item.label, 'Home');
assert.strictEqual(item.href, 'https://ha.example.com:8123/');
});
test('integrationFor exposes the raw record for a site', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'discourse-abc', {