Add UI for network mounts (#16357)

Co-authored-by: Franck Nijhof <git@frenck.dev>
This commit is contained in:
Joakim Sørensen 2023-05-08 10:18:09 +02:00 committed by GitHub
parent 8f75c314f5
commit 36a87da1fe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 650 additions and 23 deletions

View File

@ -0,0 +1,113 @@
import { HomeAssistant } from "../../types";
export enum SupervisorMountType {
BIND = "bind",
CIFS = "cifs",
NFS = "nfs",
}
export enum SupervisorMountUsage {
BACKUP = "backup",
MEDIA = "media",
}
export enum SupervisorMountState {
ACTIVE = "active",
FAILED = "failed",
UNKNOWN = "unknown",
}
interface SupervisorMountBase {
name: string;
usage: SupervisorMountUsage;
type: SupervisorMountType;
server: string;
port: number;
}
export interface SupervisorMountResponse extends SupervisorMountBase {
state: SupervisorMountState | null;
}
export interface SupervisorNFSMount extends SupervisorMountResponse {
type: SupervisorMountType.NFS;
path: string;
}
export interface SupervisorCIFSMount extends SupervisorMountResponse {
type: SupervisorMountType.CIFS;
share: string;
}
export type SupervisorMount = SupervisorNFSMount | SupervisorCIFSMount;
export type SupervisorNFSMountRequestParams = SupervisorNFSMount;
export interface SupervisorCIFSMountRequestParams extends SupervisorCIFSMount {
username?: string;
password?: string;
}
export type SupervisorMountRequestParams =
| SupervisorNFSMountRequestParams
| SupervisorCIFSMountRequestParams;
export interface SupervisorMounts {
mounts: SupervisorMount[];
}
export const fetchSupervisorMounts = async (
hass: HomeAssistant
): Promise<SupervisorMounts> =>
hass.callWS({
type: "supervisor/api",
endpoint: `/mounts`,
method: "get",
timeout: null,
});
export const createSupervisorMount = async (
hass: HomeAssistant,
data: SupervisorMountRequestParams
): Promise<void> =>
hass.callWS({
type: "supervisor/api",
endpoint: `/mounts`,
method: "post",
timeout: null,
data,
});
export const updateSupervisorMount = async (
hass: HomeAssistant,
data: Partial<SupervisorMountRequestParams>
): Promise<void> =>
hass.callWS({
type: "supervisor/api",
endpoint: `/mounts/${data.name}`,
method: "put",
timeout: null,
data,
});
export const removeSupervisorMount = async (
hass: HomeAssistant,
name: string
): Promise<void> =>
hass.callWS({
type: "supervisor/api",
endpoint: `/mounts/${name}`,
method: "delete",
timeout: null,
});
export const reloadSupervisorMount = async (
hass: HomeAssistant,
data: SupervisorMount
): Promise<void> =>
hass.callWS({
type: "supervisor/api",
endpoint: `/mounts/${data.name}/reload`,
method: "post",
timeout: null,
});

View File

@ -0,0 +1,283 @@
import { css, CSSResultGroup, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { fireEvent } from "../../../common/dom/fire_event";
import "../../../components/ha-form/ha-form";
import { extractApiErrorMessage } from "../../../data/hassio/common";
import {
createSupervisorMount,
removeSupervisorMount,
SupervisorMountRequestParams,
SupervisorMountType,
SupervisorMountUsage,
updateSupervisorMount,
} from "../../../data/supervisor/mounts";
import { haStyle, haStyleDialog } from "../../../resources/styles";
import { HomeAssistant } from "../../../types";
import { MountViewDialogParams } from "./show-dialog-view-mount";
import { LocalizeFunc } from "../../../common/translations/localize";
import type { SchemaUnion } from "../../../components/ha-form/types";
const mountSchema = memoizeOne(
(
localize: LocalizeFunc,
existing?: boolean,
mountType?: SupervisorMountType
) =>
[
{
name: "name",
required: true,
disabled: existing,
selector: { text: {} },
},
{
name: "usage",
required: true,
type: "select",
options: [
[
SupervisorMountUsage.BACKUP,
localize(
"ui.panel.config.storage.network_mounts.mount_usage.backup"
),
],
[
SupervisorMountUsage.MEDIA,
localize(
"ui.panel.config.storage.network_mounts.mount_usage.media"
),
],
] as const,
},
{
name: "server",
required: true,
selector: { text: {} },
},
{
name: "type",
required: true,
type: "select",
options: [
[
SupervisorMountType.CIFS,
localize("ui.panel.config.storage.network_mounts.mount_type.cifs"),
],
[
SupervisorMountType.NFS,
localize("ui.panel.config.storage.network_mounts.mount_type.nfs"),
],
],
},
...(mountType === "nfs"
? ([
{
name: "path",
required: true,
selector: { text: {} },
},
] as const)
: mountType === "cifs"
? ([
{
name: "share",
required: true,
selector: { text: {} },
},
{
name: "username",
required: false,
selector: { text: {} },
},
{
name: "password",
required: false,
selector: { text: { type: "password" } },
},
] as const)
: ([] as const)),
] as const
);
@customElement("dialog-mount-view")
class ViewMountDialog extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private _data?: SupervisorMountRequestParams;
@state() private _waiting?: boolean;
@state() private _error?: string;
@state() private _validationError?: Record<string, string>;
@state() private _existing?: boolean;
@state() private _reloadMounts?: () => void;
public async showDialog(
dialogParams: MountViewDialogParams
): Promise<Promise<void>> {
this._data = dialogParams.mount;
this._existing = dialogParams.mount !== undefined;
this._reloadMounts = dialogParams.reloadMounts;
}
public closeDialog(): void {
this._data = undefined;
this._waiting = undefined;
this._error = undefined;
this._validationError = undefined;
this._existing = undefined;
this._reloadMounts = undefined;
fireEvent(this, "dialog-closed", { dialog: this.localName });
}
protected render() {
if (this._existing === undefined) {
return nothing;
}
return html`
<ha-dialog
open
scrimClickAction
escapeKeyAction
.heading=${this._existing
? this.hass.localize(
"ui.panel.config.storage.network_mounts.update_title"
)
: this.hass.localize(
"ui.panel.config.storage.network_mounts.add_title"
)}
@closed=${this.closeDialog}
>
${this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: nothing}
<ha-form
.data=${this._data}
.schema=${mountSchema(
this.hass.localize,
this._existing,
this._data?.type
)}
.error=${this._validationError}
.computeLabel=${this._computeLabelCallback}
.computeHelper=${this._computeHelperCallback}
.computeError=${this._computeErrorCallback}
@value-changed=${this._valueChanged}
dialogInitialFocus
></ha-form>
<div slot="secondaryAction">
<mwc-button @click=${this.closeDialog} dialogInitialFocus>
${this.hass.localize("ui.common.cancel")}
</mwc-button>
${this._existing
? html`<mwc-button @click=${this._deleteMount} class="delete-btn">
${this.hass.localize("ui.common.delete")}
</mwc-button>`
: nothing}
</div>
<mwc-button
.disabled=${this._waiting}
slot="primaryAction"
@click=${this._connectMount}
>
${this._existing
? this.hass.localize(
"ui.panel.config.storage.network_mounts.update"
)
: this.hass.localize(
"ui.panel.config.storage.network_mounts.connect"
)}
</mwc-button>
</ha-dialog>
`;
}
private _computeLabelCallback = (
// @ts-ignore
schema: SchemaUnion<ReturnType<typeof mountSchema>>
): string =>
this.hass.localize(
`ui.panel.config.storage.network_mounts.options.${schema.name}.title`
);
private _computeHelperCallback = (
// @ts-ignore
schema: SchemaUnion<ReturnType<typeof mountSchema>>
): string =>
this.hass.localize(
`ui.panel.config.storage.network_mounts.options.${schema.name}.description`
);
private _computeErrorCallback = (error: string): string =>
this.hass.localize(
// @ts-ignore
`ui.panel.config.storage.network_mounts.errors.${error}`
) || error;
private _valueChanged(ev: CustomEvent) {
this._validationError = {};
this._data = ev.detail.value;
if (this._data?.name && !/^\w+$/.test(this._data.name)) {
this._validationError.name = "invalid_name";
}
}
private async _connectMount() {
this._error = undefined;
this._waiting = true;
try {
if (this._existing) {
await updateSupervisorMount(this.hass, this._data!);
} else {
await createSupervisorMount(this.hass, this._data!);
}
} catch (err: any) {
this._error = extractApiErrorMessage(err);
this._waiting = false;
return;
}
if (this._reloadMounts) {
this._reloadMounts();
}
this.closeDialog();
}
private async _deleteMount() {
this._error = undefined;
this._waiting = true;
try {
await removeSupervisorMount(this.hass, this._data!.name);
} catch (err: any) {
this._error = extractApiErrorMessage(err);
this._waiting = false;
return;
}
if (this._reloadMounts) {
this._reloadMounts();
}
this.closeDialog();
}
static get styles(): CSSResultGroup {
return [
haStyle,
haStyleDialog,
css`
.delete-btn {
--mdc-theme-primary: var(--error-color);
}
`,
];
}
}
declare global {
interface HTMLElementTagNameMap {
"dialog-mount-view": ViewMountDialog;
}
}

View File

@ -1,11 +1,31 @@
import { mdiDotsVertical } from "@mdi/js";
import { css, html, LitElement, PropertyValues, TemplateResult } from "lit";
import "@material/mwc-list";
import { mdiBackupRestore, mdiNas, mdiPlayBox, mdiReload } from "@mdi/js";
import {
LitElement,
PropertyValues,
TemplateResult,
css,
html,
nothing,
} from "lit";
import { customElement, property, state } from "lit/decorators";
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
import "../../../components/ha-alert";
import "../../../components/ha-button-menu";
import "../../../components/ha-icon-button";
import "../../../components/ha-metric";
import { fetchHassioHostInfo, HassioHostInfo } from "../../../data/hassio/host";
import "../../../components/ha-svg-icon";
import { extractApiErrorMessage } from "../../../data/hassio/common";
import { HassioHostInfo, fetchHassioHostInfo } from "../../../data/hassio/host";
import {
SupervisorMount,
SupervisorMountState,
SupervisorMountType,
SupervisorMountUsage,
fetchSupervisorMounts,
reloadSupervisorMount,
} from "../../../data/supervisor/mounts";
import { showAlertDialog } from "../../../dialogs/generic/show-dialog-box";
import "../../../layouts/hass-subpage";
import type { HomeAssistant, Route } from "../../../types";
import {
@ -14,6 +34,7 @@ import {
} from "../../../util/calculate";
import "../core/ha-config-analytics";
import { showMoveDatadiskDialog } from "./show-dialog-move-datadisk";
import { showMountViewDialog } from "./show-dialog-view-mount";
@customElement("ha-config-section-storage")
class HaConfigSectionStorage extends LitElement {
@ -27,6 +48,8 @@ class HaConfigSectionStorage extends LitElement {
@state() private _hostInfo?: HassioHostInfo;
@state() private _mounts?: SupervisorMount[];
protected firstUpdated(changedProps: PropertyValues) {
super.firstUpdated(changedProps);
if (isComponentLoaded(this.hass, "hassio")) {
@ -42,22 +65,6 @@ class HaConfigSectionStorage extends LitElement {
.narrow=${this.narrow}
.header=${this.hass.localize("ui.panel.config.storage.caption")}
>
${this._hostInfo
? html`
<ha-button-menu slot="toolbar-icon">
<ha-icon-button
slot="trigger"
.label=${this.hass.localize("ui.common.menu")}
.path=${mdiDotsVertical}
></ha-icon-button>
<mwc-list-item @click=${this._moveDatadisk}>
${this.hass.localize(
"ui.panel.config.storage.datadisk.title"
)}
</mwc-list-item>
</ha-button-menu>
`
: ""}
<div class="content">
${this._error
? html`
@ -68,7 +75,12 @@ class HaConfigSectionStorage extends LitElement {
: ""}
${this._hostInfo
? html`
<ha-card outlined>
<ha-card
outlined
.header=${this.hass.localize(
"ui.panel.config.storage.disk_metrics"
)}
>
<div class="card-content">
<ha-metric
.heading=${this.hass.localize(
@ -97,9 +109,80 @@ class HaConfigSectionStorage extends LitElement {
`
: ""}
</div>
${this._hostInfo
? html`<div class="card-actions">
<mwc-button @click=${this._moveDatadisk}>
${this.hass.localize(
"ui.panel.config.storage.datadisk.title"
)}
</mwc-button>
</div>`
: nothing}
</ha-card>
`
: ""}
<ha-card
outlined
.header=${this.hass.localize(
"ui.panel.config.storage.network_mounts.title"
)}
>
${this._mounts?.length
? html`<mwc-list>
${this._mounts.map(
(mount) => html`
<ha-list-item
graphic="avatar"
.mount=${mount}
twoline
.hasMeta=${mount.state !== SupervisorMountState.ACTIVE}
@click=${this._changeMount}
>
<div slot="graphic">
<ha-svg-icon
.path=${mount.usage === SupervisorMountUsage.MEDIA
? mdiPlayBox
: mdiBackupRestore}
></ha-svg-icon>
</div>
<span class="mount-state-${mount.state || "unknown"}">
${mount.name}
</span>
<span slot="secondary">
${mount.server}${mount.port
? `:${mount.port}`
: nothing}${mount.type === SupervisorMountType.NFS
? mount.path
: ` :${mount.share}`}
</span>
<ha-icon-button
class="reload-btn"
slot="meta"
.mount=${mount}
@click=${this._reloadMount}
.path=${mdiReload}
></ha-icon-button>
</ha-list-item>
`
)}
</mwc-list>`
: html` <div class="no-mounts">
<ha-svg-icon .path=${mdiNas}></ha-svg-icon>
<p>
${this.hass.localize(
"ui.panel.config.storage.network_mounts.no_mounts"
)}
</p>
</div>`}
<div class="card-actions">
<mwc-button @click=${this._addMount}>
${this.hass.localize(
"ui.panel.config.storage.network_mounts.add_title"
)}
</mwc-button>
</div>
</ha-card>
</div>
</hass-subpage>
`;
@ -107,7 +190,10 @@ class HaConfigSectionStorage extends LitElement {
private async _load() {
try {
this._hostInfo = await fetchHassioHostInfo(this.hass);
[this._hostInfo] = await Promise.all([
fetchHassioHostInfo(this.hass),
this._reloadMounts(),
]);
} catch (err: any) {
this._error = err.message || err;
}
@ -119,6 +205,47 @@ class HaConfigSectionStorage extends LitElement {
});
}
private async _reloadMount(ev: Event): Promise<void> {
ev.stopPropagation();
const mount: SupervisorMount = (ev.currentTarget as any).mount;
try {
await reloadSupervisorMount(this.hass, mount);
} catch (err: any) {
showAlertDialog(this, {
title: this.hass.localize(
"ui.panel.config.storage.network_mounts.errors.reload",
{ mount: mount.name }
),
text: extractApiErrorMessage(err),
});
return;
}
await this._reloadMounts();
}
private _addMount(): void {
showMountViewDialog(this, { reloadMounts: this._reloadMounts });
}
private _changeMount(ev: Event): void {
ev.stopPropagation();
showMountViewDialog(this, {
mount: (ev.currentTarget as any).mount,
reloadMounts: this._reloadMounts,
});
}
private async _reloadMounts(): Promise<void> {
try {
const allMounts = await fetchSupervisorMounts(this.hass);
this._mounts = allMounts.mounts.filter((mount) =>
[SupervisorMountType.CIFS, SupervisorMountType.NFS].includes(mount.type)
);
} catch (err: any) {
this._error = err.message || err;
}
}
private _getUsedSpace = (used: number, total: number) =>
roundWithOneDecimal(getValueInPercentage(used, 0, total));
@ -130,7 +257,7 @@ class HaConfigSectionStorage extends LitElement {
}
ha-card {
max-width: 600px;
margin: 0 auto;
margin: 0 auto 12px;
justify-content: space-between;
flex-direction: column;
display: flex;
@ -140,6 +267,34 @@ class HaConfigSectionStorage extends LitElement {
justify-content: space-between;
flex-direction: column;
}
.mount-state-failed {
color: var(--error-color);
}
.mount-state-unknown {
color: var(--warning-color);
}
.reload-btn {
float: right;
position: relative;
top: -10px;
right: 10px;
}
.no-mounts {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
}
.no-mounts ha-svg-icon {
background-color: var(--light-primary-color);
color: var(--secondary-text-color);
padding: 16px;
border-radius: 50%;
margin-bottom: 8px;
}
`;
}

View File

@ -0,0 +1,18 @@
import { fireEvent } from "../../../common/dom/fire_event";
import { SupervisorMount } from "../../../data/supervisor/mounts";
export interface MountViewDialogParams {
mount?: SupervisorMount;
reloadMounts: () => void;
}
export const showMountViewDialog = (
element: HTMLElement,
dialogParams: MountViewDialogParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-mount-view",
dialogImport: () => import("./dialog-mount-view"),
dialogParams,
});
};

View File

@ -478,7 +478,10 @@
}
}
},
"stt-picker": { "stt": "Speech-to-text", "none": "None" },
"stt-picker": {
"stt": "Speech-to-text",
"none": "None"
},
"related-filter-menu": {
"filter": "Filter",
"filter_by_entity": "Filter by entity",
@ -3970,6 +3973,7 @@
"description": "{percent_used} used - {free_space} free",
"used_space": "Used Space",
"emmc_lifetime_used": "eMMC Lifetime Used",
"disk_metrics": "Disk metrics",
"datadisk": {
"title": "Move data disk",
"description": "You are currently using ''{current_path}'' as data disk. Moving the data disk will reboot your device and it's estimated to take {time} minutes. Your Home Assistant installation will not be accessible during this period. Do not disconnect the power during the move!",
@ -3983,6 +3987,60 @@
"cancel": "[%key:ui::common::cancel%]",
"failed_to_move": "Failed to move data disk",
"move": "Move"
},
"network_mounts": {
"title": "Network storage",
"add_title": "Add network storage",
"update_title": "Update network storage",
"no_mounts": "No connected network storage",
"mount_usage": {
"backup": "Backup",
"media": "Media"
},
"mount_type": {
"nfs": "Network File Share (NFS)",
"cifs": "Samba/Windows (CIFS)"
},
"options": {
"name": {
"title": "Name",
"description": "This name will be shown to you in the UI, and will also be the name of the folder created on your system"
},
"share": {
"title": "Remote share",
"description": "This is the name of the share you created on your storage server"
},
"server": {
"title": "Server",
"description": "This is the domain name (FQDN) or IP address of the storage server you want to connect to"
},
"path": {
"title": "Remote share path",
"description": "This is the path of the remote share on your storage server"
},
"type": {
"title": "Protocol",
"description": "This determines how to communicate with the storage server"
},
"usage": {
"title": "Usage",
"description": "This determines how the share is intended to be used"
},
"username": {
"title": "Username",
"description": "This is your username for the samba share"
},
"password": {
"title": "Password",
"description": "This is your password for the samba share"
}
},
"connect": "Connect",
"update": "Update",
"errors": {
"reload": "Could not reload mount {mount}",
"invalid_name": "Invalid name, can only contain alphanumeric characters and underscores"
}
}
},
"system_health": {