Remove CalendarEventDevice which was deprecated in 2022.5 (#77809)

This commit is contained in:
Allen Porter 2022-09-04 22:25:43 -07:00 committed by GitHub
parent 6044e2b054
commit ddf668d1cb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 7 additions and 146 deletions

View file

@ -189,71 +189,6 @@ def is_offset_reached(
return start + offset_time <= dt.now(start.tzinfo)
class CalendarEventDevice(Entity):
"""Legacy API for calendar event entities."""
def __init_subclass__(cls, **kwargs: Any) -> None:
"""Print deprecation warning."""
super().__init_subclass__(**kwargs)
_LOGGER.warning(
"CalendarEventDevice is deprecated, modify %s to extend CalendarEntity",
cls.__name__,
)
@property
def event(self) -> dict[str, Any] | None:
"""Return the next upcoming event."""
raise NotImplementedError()
@final
@property
def state_attributes(self) -> dict[str, Any] | None:
"""Return the entity state attributes."""
if (event := self.event) is None:
return None
event = normalize_event(event)
return {
"message": event["message"],
"all_day": event["all_day"],
"start_time": event["start"],
"end_time": event["end"],
"location": event["location"],
"description": event["description"],
}
@final
@property
def state(self) -> str:
"""Return the state of the calendar event."""
if (event := self.event) is None:
return STATE_OFF
event = normalize_event(event)
start = event["dt_start"]
end = event["dt_end"]
if start is None or end is None:
return STATE_OFF
now = dt.now()
if start <= now < end:
return STATE_ON
return STATE_OFF
async def async_get_events(
self,
hass: HomeAssistant,
start_date: datetime.datetime,
end_date: datetime.datetime,
) -> list[dict[str, Any]]:
"""Return calendar events within a datetime range."""
raise NotImplementedError()
class CalendarEntity(Entity):
"""Base class for calendar event entities."""
@ -314,10 +249,14 @@ class CalendarEventView(http.HomeAssistantView):
async def get(self, request: web.Request, entity_id: str) -> web.Response:
"""Return calendar events."""
entity = self.component.get_entity(entity_id)
if not (entity := self.component.get_entity(entity_id)) or not isinstance(
entity, CalendarEntity
):
return web.Response(status=HTTPStatus.BAD_REQUEST)
start = request.query.get("start")
end = request.query.get("end")
if start is None or end is None or entity is None:
if start is None or end is None:
return web.Response(status=HTTPStatus.BAD_REQUEST)
try:
start_date = dt.parse_datetime(start)
@ -327,16 +266,6 @@ class CalendarEventView(http.HomeAssistantView):
if start_date is None or end_date is None:
return web.Response(status=HTTPStatus.BAD_REQUEST)
# Compatibility shim for old API
if isinstance(entity, CalendarEventDevice):
event_list = await entity.async_get_events(
request.app["hass"], start_date, end_date
)
return self.json(event_list)
if not isinstance(entity, CalendarEntity):
return web.Response(status=HTTPStatus.BAD_REQUEST)
try:
calendar_event_list = await entity.async_get_events(
request.app["hass"], start_date, end_date

View file

@ -1,16 +1,9 @@
"""Demo platform that has two fake binary sensors."""
from __future__ import annotations
import copy
import datetime
from typing import Any
from homeassistant.components.calendar import (
CalendarEntity,
CalendarEvent,
CalendarEventDevice,
get_date,
)
from homeassistant.components.calendar import CalendarEntity, CalendarEvent
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
@ -28,7 +21,6 @@ def setup_platform(
[
DemoCalendar(calendar_data_future(), "Calendar 1"),
DemoCalendar(calendar_data_current(), "Calendar 2"),
LegacyDemoCalendar("Calendar 3"),
]
)
@ -76,41 +68,3 @@ class DemoCalendar(CalendarEntity):
) -> list[CalendarEvent]:
"""Return calendar events within a datetime range."""
return [self._event]
class LegacyDemoCalendar(CalendarEventDevice):
"""Calendar for exercising shim API."""
def __init__(self, name: str) -> None:
"""Initialize demo calendar."""
self._attr_name = name
one_hour_from_now = dt_util.now() + datetime.timedelta(minutes=30)
self._event = {
"start": {"dateTime": one_hour_from_now.isoformat()},
"end": {
"dateTime": (
one_hour_from_now + datetime.timedelta(minutes=60)
).isoformat()
},
"summary": "Future Event",
"description": "Future Description",
"location": "Future Location",
}
@property
def event(self) -> dict[str, Any]:
"""Return the next upcoming event."""
return self._event
async def async_get_events(
self,
hass: HomeAssistant,
start_date: datetime.datetime,
end_date: datetime.datetime,
) -> list[dict[str, Any]]:
"""Get all events in a specific time frame."""
event = copy.copy(self.event)
event["title"] = event["summary"]
event["start"] = get_date(event["start"]).isoformat()
event["end"] = get_date(event["end"]).isoformat()
return [event]

View file

@ -66,26 +66,4 @@ async def test_calendars_http_api(hass, hass_client):
assert data == [
{"entity_id": "calendar.calendar_1", "name": "Calendar 1"},
{"entity_id": "calendar.calendar_2", "name": "Calendar 2"},
{"entity_id": "calendar.calendar_3", "name": "Calendar 3"},
]
async def test_events_http_api_shim(hass, hass_client):
"""Test the legacy shim calendar demo view."""
await async_setup_component(hass, "calendar", {"calendar": {"platform": "demo"}})
await hass.async_block_till_done()
client = await hass_client()
response = await client.get("/api/calendars/calendar.calendar_3")
assert response.status == HTTPStatus.BAD_REQUEST
start = dt_util.now()
end = start + timedelta(days=1)
response = await client.get(
"/api/calendars/calendar.calendar_1?start={}&end={}".format(
start.isoformat(), end.isoformat()
)
)
assert response.status == HTTPStatus.OK
events = await response.json()
assert events[0]["summary"] == "Future Event"
assert events[0]["description"] == "Future Description"
assert events[0]["location"] == "Future Location"