Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to import calendar events from an iCalendar file #20645

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/data/calendar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,24 @@ export const deleteCalendarEvent = (
recurrence_id,
recurrence_range,
});

export const uploadCalendarFile = async (
hass: HomeAssistant,
entityId: string,
file: File
) => {
const fd = new FormData();
fd.append("file", file);
fd.append("entity_id", entityId);
const resp = await hass.fetchWithAuth("/api/calendars/import", {
method: "POST",
body: fd,
});
if (resp.status === 413) {
throw new Error(`Uploaded file is too large (${file.name})`);
} else if (resp.status !== 200) {
throw new Error("Unknown error");
}
const data = await resp.json();
return data.file_id;
};
188 changes: 188 additions & 0 deletions src/panels/calendar/dialog-import-calendar-events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
import "@material/mwc-button";
import { CSSResultGroup, LitElement, css, html, nothing } from "lit";
import { property, state } from "lit/decorators";
import { mdiFileUpload } from "@mdi/js";
import { fireEvent } from "../../common/dom/fire_event";
import "../../components/entity/state-info";
import "../../components/ha-alert";
import "../../components/ha-date-input";
import { createCloseHeading } from "../../components/ha-dialog";
import "../../components/ha-time-input";
import { haStyleDialog } from "../../resources/styles";
import { showAlertDialog } from "../../dialogs/generic/show-dialog-box";
import { HomeAssistant } from "../../types";
import "../lovelace/components/hui-generic-entity-row";
import { stopPropagation } from "../../common/dom/stop_propagation";
import { ImportCalendarEventsDialogParams } from "./show-dialog-import-calendar-events";
import { uploadCalendarFile } from "../../data/calendar";

class DialogImportCalendarEvents extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;

@state() private _params?: ImportCalendarEventsDialogParams;

@state() private _calendarFile?: File;

@state() private _selectedCalendarEntityId: string = "";

@state() private _uploading = false;

@state() private _error?: string;

public async showDialog(
params: ImportCalendarEventsDialogParams
): Promise<void> {
this._params = params;
}

private closeDialog(): void {
this._params = undefined;
this._selectedCalendarEntityId = "";
this._calendarFile = undefined;
fireEvent(this, "dialog-closed", { dialog: this.localName });
}

protected render() {
if (!this._params) {
return nothing;
}
return html`
<ha-dialog
open
@closed=${this.closeDialog}
scrimClickAction
escapeKeyAction
.heading=${createCloseHeading(
this.hass,
this.hass.localize("ui.components.calendar.import_events.title")
)}
>
<div class="content">
${this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: ""}
<ha-select
.label=${this.hass.localize(
"ui.components.calendar.import_events.select_label"
)}
@selected=${this._setCalendar}
@closed=${stopPropagation}
fixedMenuPosition
naturalMenuWidth
.value=${this._selectedCalendarEntityId!}
>
${this._params.calendars.map(
(item) => html`
<mwc-list-item .value=${item.entity_id || ""}>
${item.name}
</mwc-list-item>
`
)}
</ha-select>
<ha-file-upload
.hass=${this.hass}
.uploading=${this._uploading}
.icon=${mdiFileUpload}
.label=${this.hass.localize(
"ui.components.calendar.import_events.label"
)}
.supports=${this.hass.localize(
"ui.components.calendar.import_events.supported_formats"
)}
.value=${this._calendarFile}
accept="text/calendar"
@file-picked=${this._setCalendarFile}
@change=${this._handleFileCleared}
></ha-file-upload>
</div>
<mwc-button
slot="primaryAction"
@click=${this._beginFileSubmit}
.disabled=${this._calendarFile === undefined ||
this._uploading ||
!this._selectedCalendarEntityId}
>
${this.hass.localize(
"ui.components.calendar.import_events.upload_button"
)}
</mwc-button>
</ha-dialog>
`;
}

private _setCalendar(ev): void {
const entityId = ev.target.value;
this._selectedCalendarEntityId = entityId;
}

private async _setCalendarFile(ev) {
this._calendarFile = ev.detail.files![0];
}

private async _beginFileSubmit() {
this._uploading = true;

try {
const fileId = await uploadCalendarFile(
this.hass,
this._selectedCalendarEntityId,
this._calendarFile!
);
fireEvent(this, "value-changed", { value: fileId });
} catch (err: any) {
showAlertDialog(this, {
text: this.hass.localize(
"ui.components.calendar.import_events.upload_failed",
{
reason: err.message || err,
}
),
});
} finally {
this._uploading = false;
this._calendarFile = undefined;
this.closeDialog();
}
}

private _handleFileCleared() {
this._calendarFile = undefined;
}

static get styles(): CSSResultGroup {
return [
haStyleDialog,
css`
state-info {
line-height: 40px;
}
ha-svg-icon {
width: 40px;
margin-right: 8px;
margin-inline-end: 8px;
margin-inline-start: initial;
direction: var(--direction);
vertical-align: top;
}
ha-file-upload {
margin-top: 16px;
}
.buttons {
display: flex;
justify-content: flex-end;
}
`,
];
}
}

declare global {
interface HTMLElementTagNameMap {
"dialog-import-calendar-events": DialogImportCalendarEvents;
}
}

customElements.define(
"dialog-import-calendar-events",
DialogImportCalendarEvents
);
16 changes: 15 additions & 1 deletion src/panels/calendar/ha-panel-calendar.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ResizeController } from "@lit-labs/observers/resize-controller";
import "@material/mwc-list";
import type { RequestSelectedDetail } from "@material/mwc-list/mwc-list-item";
import { mdiChevronDown, mdiPlus, mdiRefresh } from "@mdi/js";
import { mdiChevronDown, mdiPlus, mdiRefresh, mdiUpload } from "@mdi/js";
import {
CSSResultGroup,
LitElement,
Expand All @@ -20,6 +20,7 @@
import "../../components/ha-button-menu";
import "../../components/ha-card";
import "../../components/ha-check-list-item";
import "../../components/ha-file-upload";
import "../../components/ha-icon-button";
import type { HaListItem } from "../../components/ha-list-item";
import "../../components/ha-menu-button";
Expand All @@ -34,6 +35,7 @@
} from "../../data/calendar";
import { fetchIntegrationManifest } from "../../data/integration";
import { showConfigFlowDialog } from "../../dialogs/config-flow/show-dialog-config-flow";
import { showImportCalendarEventsDialog } from "./show-dialog-import-calendar-events";
import { haStyle } from "../../resources/styles";
import type { CalendarViewChanged, HomeAssistant } from "../../types";
import "./ha-full-calendar";
Expand Down Expand Up @@ -166,6 +168,14 @@
: html`<div slot="title">
${this.hass.localize("ui.components.calendar.my_calendars")}
</div>`}
<ha-icon-button
slot="actionItems"
.path=${mdiUpload}
.label=${this.hass.localize(
"ui.components.calendar.import_calendar.label"

Check failure on line 175 in src/panels/calendar/ha-panel-calendar.ts

View workflow job for this annotation

GitHub Actions / Lint and check format

Argument of type '"ui.components.calendar.import_calendar.label"' is not assignable to parameter of type 'LocalizeKeys'.
)}
@click=${this._importCalendarEvents}
></ha-icon-button>
<ha-icon-button
slot="actionItems"
.path=${mdiRefresh}
Expand Down Expand Up @@ -257,6 +267,10 @@
});
}

private async _importCalendarEvents(): Promise<void> {
showImportCalendarEventsDialog(this, { calendars: this._calendars });
}

private async _handleViewChanged(
ev: HASSDomEvent<CalendarViewChanged>
): Promise<void> {
Expand Down
20 changes: 20 additions & 0 deletions src/panels/calendar/show-dialog-import-calendar-events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { fireEvent } from "../../common/dom/fire_event";
import { Calendar } from "../../data/calendar";

export interface ImportCalendarEventsDialogParams {
calendars: Calendar[];
}

export const loadImportCalendarEventsDialog = () =>
import("./dialog-import-calendar-events");

export const showImportCalendarEventsDialog = (
element: HTMLElement,
detailParams: ImportCalendarEventsDialogParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-import-calendar-events",
dialogImport: loadImportCalendarEventsDialog,
dialogParams: detailParams,
});
};
9 changes: 9 additions & 0 deletions src/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -883,6 +883,15 @@
"create_calendar": "Create calendar",
"today": "Today",
"event_retrieval_error": "Could not retrieve events for calendars:",
"import_events": {
"label": "Import event information",
"select_label": "Add to calendar",
"supported_formats": "Supports iCal (.ics) format",
"title": "Import event information",
"unsupported_format": "Unsupported format, please choose an ICS file.",
"upload_failed": "Upload failed",
"upload_button": "Upload"
},
"event": {
"add": "Add event",
"delete": "Delete event",
Expand Down