Files
Lark-Snooper/snooper_calendar.py
2026-11-12 23:36:01 +08:00

90 lines
3.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""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 resolve_calendar_links(config: dict[str, Any]) -> dict[str, str]:
"""Validate manual date|summary to meeting-link mappings."""
links = config.get("calendar", {}).get("meeting_links", {})
if links is None:
return {}
if not isinstance(links, dict):
raise CalendarError("YAML 的 calendar.meeting_links 必须是映射。")
resolved = {}
for key, url in links.items():
if not isinstance(key, str) or not isinstance(url, str):
raise CalendarError("会议链接的键和 URL 必须是字符串。")
if not url.startswith(("https://", "http://")):
raise CalendarError("会议链接必须是 HTTP(S) URL。")
resolved[key] = url
return resolved
def fetch_calendar_events(
client: Any,
target_day: date,
tz: ZoneInfo,
meeting_links: dict[str, str] | None = None,
) -> 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")
]
summary = str(event.get("summary") or "未命名会议")
native_url = str(event.get("meetingMinuteUrl") or event.get("url") or "")
manual_url = (meeting_links or {}).get(
f"{target_day.isoformat()}|{summary}", ""
)
events.append(
{
"summary": summary,
"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": native_url or manual_url,
}
)
events.sort(key=lambda event: (event["begin"], event["summary"]))
return events