"""Read-only daily calendar instances through the existing LarkAgentX session.""" from __future__ import annotations import re 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.""" AI_NOTES_CHAT_ID = "7391681490647744513" AI_NOTES_URL_RE = re.compile( r"https://[A-Za-z0-9.-]+\.feishu\.cn/(?:docx|minutes)/[A-Za-z0-9]+(?:\?[^\s\x00-\x1f]*)?" ) 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_ai_notes_links( client: Any, target_day: date, tz: ZoneInfo, chat_id: str = AI_NOTES_CHAT_ID, storage: Any = None, ) -> list[dict[str, Any]]: """Fetch AI Notes Assistant links for the target day and adjacent days. Returns a list of {"url": str, "create_time": int, "topic": str} sorted by create_time. Prefers local storage when available; falls back to network pull. """ start = datetime.combine(target_day - timedelta(days=1), time.min, tzinfo=tz) end = datetime.combine(target_day + timedelta(days=2), time.min, tzinfo=tz) start_ts = int(start.timestamp()) end_ts = int(end.timestamp()) links = [] seen_urls: set[str] = set() # Prefer local storage cache if storage is not None: try: from sqlalchemy import text with storage.engine.connect() as conn: result = conn.execute( text( "SELECT content, content_data, create_time FROM messages " "WHERE chat_id = :chat_id AND create_time >= :start AND create_time < :end " "ORDER BY create_time" ), {"chat_id": chat_id, "start": start_ts, "end": end_ts}, ) for content, content_data, ts in result: # Search content and content_data separately to avoid mixing with JSON for text_to_search in (str(content or ""), str(content_data or "")): for match in AI_NOTES_URL_RE.finditer(text_to_search): url = match.group(0) if url not in seen_urls: seen_urls.add(url) links.append({"url": url, "create_time": int(ts), "topic": ""}) except Exception: pass # Fall back to network if storage read fails # If we found links locally but they lack topics, try to enrich from network if links and any(not link.get("topic") for link in links): try: network_links = _fetch_ai_notes_links_from_network(client, target_day, tz, chat_id, storage) # Merge network topics into local links by URL topic_map = {link["url"]: link.get("topic", "") for link in network_links} for link in links: if not link.get("topic") and link["url"] in topic_map: link["topic"] = topic_map[link["url"]] except Exception: pass # If we found links locally, return them sorted if links: links.sort(key=lambda x: x["create_time"]) return links # Otherwise pull from network return _fetch_ai_notes_links_from_network(client, target_day, tz, chat_id, storage) def _fetch_ai_notes_links_from_network( client: Any, target_day: date, tz: ZoneInfo, chat_id: str = AI_NOTES_CHAT_ID, storage: Any = None, ) -> list[dict[str, Any]]: """Fetch AI Notes links from network with topics extracted from content_data.""" start = datetime.combine(target_day - timedelta(days=1), time.min, tzinfo=tz) end = datetime.combine(target_day + timedelta(days=2), time.min, tzinfo=tz) start_ts = int(start.timestamp()) end_ts = int(end.timestamp()) links = [] seen_urls: set[str] = set() info = client.get_chat_info(chat_id) if not info or not info.get("lastMessagePosition"): return [] last_pos = int(info["lastMessagePosition"]) first_pos = max(0, int(info.get("firstChatMessagePosition") or 0)) upper = last_pos batch_size = 50 # Scan backwards until we pass the start of the window while upper >= first_pos: lower = max(first_pos, upper - batch_size + 1) messages = client.pull_history(chat_id, list(range(lower, upper + 1))) batch_min_time = None for msg in messages: ts = int(msg.get("create_time") or 0) if ts: batch_min_time = ts if batch_min_time is None else min(batch_min_time, ts) if start_ts <= ts < end_ts: content_data = msg.get("content_data") if content_data and storage is not None: # Extract URLs with topics from raw content_data extracted = storage._extract_links_with_topics(content_data) for item in extracted: url = item["url"] if url not in seen_urls: seen_urls.add(url) links.append({"url": url, "create_time": ts, "topic": item.get("topic", "")}) else: # Fallback to plain text search content = str(msg.get("content") or "") content_data_str = str(content_data or "") text_to_search = content + content_data_str for match in AI_NOTES_URL_RE.finditer(text_to_search): url = match.group(0) if url not in seen_urls: seen_urls.add(url) links.append({"url": url, "create_time": ts, "topic": ""}) if batch_min_time and batch_min_time < start_ts: break upper = lower - 1 links.sort(key=lambda x: x["create_time"]) return links def _match_ai_notes_url( event_end_ts: int, ai_notes_links: list[dict[str, Any]], used_urls: set[str], event_summary: str = "", ) -> str: """Pick the closest AI Notes link after the event ends, matching topic when available.""" best_url = "" best_delta = None for link in ai_notes_links: if link["url"] in used_urls: continue delta = link["create_time"] - event_end_ts # permission_change links may be sent long before/after the meeting # finish_recording links are sent right after the meeting if "permission_change" in link["url"]: window = 86400 # 24 hours else: window = 21600 # 6 hours if not (-window <= delta <= window): continue # If we have a specific topic, verify it matches the event summary topic = link.get("topic", "") if topic and event_summary: # Skip generic topics like "xxx的视频会议" - they don't help distinguish meetings is_generic = "视频会议" in topic or not topic.strip() if not is_generic: # Normalize: remove parentheses, spaces, and common suffixes for comparison def normalize(s): return re.sub(r"[\s()()\-—]", "", s).lower() if normalize(topic) != normalize(event_summary): continue if best_delta is None or abs(delta) < abs(best_delta): best_delta = delta best_url = link["url"] if best_url: used_urls.add(best_url) return best_url def fetch_calendar_events( client: Any, target_day: date, tz: ZoneInfo, meeting_links: dict[str, str] | None = None, ai_notes_chat_id: str | None = AI_NOTES_CHAT_ID, storage: Any = None, ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: """Return normalized primary-calendar instances and unmatched AI Notes links.""" 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 # Fetch AI Notes links as the primary source for meeting minutes URLs ai_notes_links = [] if ai_notes_chat_id: try: ai_notes_links = fetch_ai_notes_links(client, target_day, tz, ai_notes_chat_id, storage=storage) except Exception: pass # Fall back to native/manual URLs if AI Notes fetch fails event_map = response.get("events") or {} events = [] used_urls: set[str] = set() 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}", "" ) event_end_ts = int(instance["endTime"]) ai_notes_url = _match_ai_notes_url(event_end_ts, ai_notes_links, used_urls, event_summary=summary) events.append( { "summary": summary, "begin": datetime.fromtimestamp( int(instance["beginTime"]), tz ).isoformat(timespec="seconds"), "end": datetime.fromtimestamp( event_end_ts, tz ).isoformat(timespec="seconds"), "location": ";".join(location_names), "cancelled": bool(event.get("isDeleted")), "url": ai_notes_url or native_url or manual_url, } ) events.sort(key=lambda event: (event["begin"], event["summary"])) # Collect unmatched links for separate display unmatched_links = [ link for link in ai_notes_links if link["url"] not in used_urls ] return events, unmatched_links