67 lines
2.5 KiB
Python
67 lines
2.5 KiB
Python
"""Read-only daily calendar instances through the existing LarkAgentX session."""
|
||
|
||
from __future__ import annotations
|
||
|
||
from datetime import date, datetime, time, timedelta
|
||
from typing import Any
|
||
from zoneinfo import ZoneInfo
|
||
|
||
|
||
class CalendarError(RuntimeError):
|
||
"""Calendar retrieval failed without exposing event contents."""
|
||
|
||
|
||
def fetch_calendar_events(
|
||
client: Any, target_day: date, tz: ZoneInfo
|
||
) -> list[dict[str, Any]]:
|
||
"""Return normalized primary-calendar instances for one natural day."""
|
||
start = datetime.combine(target_day, time.min, tzinfo=tz)
|
||
end = start + timedelta(days=1)
|
||
try:
|
||
primary = client.api("calendars.GetUserPrimaryCalendarRequest", {}) or {}
|
||
calendar_id = str((primary.get("calendar") or {}).get("id") or "")
|
||
if not calendar_id:
|
||
raise CalendarError("未找到主日历 ID。")
|
||
response = client.api(
|
||
"calendarevents.QueryInstanceRequest",
|
||
{
|
||
"calendarIds": [calendar_id],
|
||
"startTime": int(start.timestamp()),
|
||
"endTime": int(end.timestamp()),
|
||
"needsBriefEvents": True,
|
||
},
|
||
) or {}
|
||
except CalendarError:
|
||
raise
|
||
except Exception as error:
|
||
raise CalendarError(f"日历请求失败({type(error).__name__})。") from error
|
||
|
||
event_map = response.get("events") or {}
|
||
events = []
|
||
for instance in response.get("calendarEventInstance") or []:
|
||
event = event_map.get(str(instance.get("eventRefId") or ""), {})
|
||
locations = event.get("locations") or []
|
||
location_names = [
|
||
str(location.get("name") or "")
|
||
for location in locations
|
||
if isinstance(location, dict) and location.get("name")
|
||
]
|
||
events.append(
|
||
{
|
||
"summary": str(event.get("summary") or "未命名会议"),
|
||
"begin": datetime.fromtimestamp(
|
||
int(instance["beginTime"]), tz
|
||
).isoformat(timespec="seconds"),
|
||
"end": datetime.fromtimestamp(
|
||
int(instance["endTime"]), tz
|
||
).isoformat(timespec="seconds"),
|
||
"location": ";".join(location_names),
|
||
"cancelled": bool(event.get("isDeleted")),
|
||
"url": str(
|
||
event.get("meetingMinuteUrl") or event.get("url") or ""
|
||
),
|
||
}
|
||
)
|
||
events.sort(key=lambda event: (event["begin"], event["summary"]))
|
||
return events
|