forked from home-assistant/frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
calendar.ts
80 lines (68 loc) · 1.97 KB
/
calendar.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import type { HomeAssistant, Calendar, CalendarEvent } from "../types";
import { computeDomain } from "../common/entity/compute_domain";
import { HA_COLOR_PALETTE } from "../common/const";
import { computeStateName } from "../common/entity/compute_state_name";
export const fetchCalendarEvents = async (
hass: HomeAssistant,
start: Date,
end: Date,
calendars: Calendar[]
): Promise<CalendarEvent[]> => {
const params = encodeURI(
`?start=${start.toISOString()}&end=${end.toISOString()}`
);
const calEvents: CalendarEvent[] = [];
const promises: Promise<any>[] = [];
calendars.forEach((cal) => {
promises.push(
hass.callApi<CalendarEvent[]>(
"GET",
`calendars/${cal.entity_id}${params}`
)
);
});
const results = await Promise.all(promises);
results.forEach((result, idx) => {
const cal = calendars[idx];
result.forEach((ev) => {
const eventStart = getCalendarDate(ev.start);
if (!eventStart) {
return;
}
const eventEnd = getCalendarDate(ev.end);
const event: CalendarEvent = {
start: eventStart,
end: eventEnd,
title: ev.summary,
summary: ev.summary,
backgroundColor: cal.backgroundColor,
borderColor: cal.backgroundColor,
calendar: cal.entity_id,
};
calEvents.push(event);
});
});
return calEvents;
};
const getCalendarDate = (dateObj: any): string | undefined => {
if (typeof dateObj === "string") {
return dateObj;
}
if (dateObj.dateTime) {
return dateObj.dateTime;
}
if (dateObj.date) {
return dateObj.date;
}
return undefined;
};
export const getCalendars = (hass: HomeAssistant): Calendar[] => {
return Object.keys(hass.states)
.filter((eid) => computeDomain(eid) === "calendar")
.sort()
.map((eid, idx) => ({
entity_id: eid,
name: computeStateName(hass.states[eid]),
backgroundColor: `#${HA_COLOR_PALETTE[idx % HA_COLOR_PALETTE.length]}`,
}));
};