diff --git a/docs/reference.md b/docs/reference.md index 2fb67e8..22e94db 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -11,7 +11,7 @@ Verified end-to-end against a live locked-down EDU tenant. | Calendar | `events(start, end)`, `event(id)`, `today()`, `calendars()` | `/me/events`, `/me/calendarView` | | Scheduling | `free_busy(users, start, end)`, `find_meeting_times(attendees)` | `getSchedule`, `findMeetingTimes` | | Calendar writes | `create_event`, `update_event`, `delete_event`, `respond_event` | `/me/events` | -| Teams chats | `chats(chat_type=)`, `chat(id)`, `chat_members(id)`, `unread_chats()`, `find_chat(user)`, `chat_messages(id, since=)` | `/me/chats` (members + last message expanded); `unread_chats`, `find_chat` and `chat_messages` use Teams' chat service, falling back to Graph | +| Teams chats | `chats(chat_type=)`, `chat(id)`, `chat_members(id)`, `unread_chats()`, `find_chat(user)`, `chat_messages(id, since=)`, `chat_message(id, message_id)` | `/me/chats` (members + last message expanded); `unread_chats`, `find_chat` and `chat_messages` use Teams' chat service, falling back to Graph | | Teams sending | `send_chat_message(id, text, mentions=)`, `create_chat(users)`, `send_to(user, text)` | `/chats`, `/chats/{id}/messages` | | Message lifecycle | `edit_chat_message`, `delete_chat_message`, `undelete_chat_message`, `react`, `unreact`, `mark_chat_read`, `mark_chat_unread` | `PATCH`, `softDelete`, `setReaction`, `markChatReadForUser` | | Chat management | `rename_chat`, `add_chat_member`, `remove_chat_member`, `pinned_messages`, `pin_message`, `unpin_message`, `hide_chat`, `unhide_chat` | `/chats/{id}/...` | @@ -27,6 +27,8 @@ Verified end-to-end against a live locked-down EDU tenant. | Planner | `planner_tasks()`, `plans(group_id=)`, `plan_tasks(plan)`, `buckets(plan)`, `planner_task_details(task)` | `/me/planner`, `/planner/plans` | | Assignments | `classes()`, `assignments(class_id=)`, `assignment_resources`, `submissions`, `due_assignments(days)` | Teams Assignments API (see [clients.md](clients.md)) | | Teams activity | `activity()`, `mentions()`, `call_history()`, `teams_presence(ids)` | Teams' own APIs, undocumented, no Graph equivalent or fallback | +| Autocomplete | `suggest_recipients(text)` | `/me/people?$search`, your frequent contacts first, then `/users` | +| Search one chat | `search_chat(chat_id, query, scan=)` | `/search/query`, filtered to that chat | | Extras | `people()`, `reminders(start, end)`, `categories()`, `mail_tips(addresses)`, `recent_files()`, `shared_with_me()` | `/me/people`, `reminderView`, `masterCategories`, `getMailTips`, `/me/drive/recent`, `/me/drive/sharedWithMe` | | Mailbox settings | `mailbox_settings()`, `auto_replies()`, `working_hours()`, `mail_rules()` | `/me/mailboxSettings`, `messageRules`, read-only, through the Teams client | | Behind an API | `outnote.api`: `ApiCache`, `ClientPool`, `respond`, `error_response` | optional, see [frontend-and-api.md](frontend-and-api.md) | diff --git a/src/outnote/_native.py b/src/outnote/_native.py index 2b908d4..b796b9c 100644 --- a/src/outnote/_native.py +++ b/src/outnote/_native.py @@ -191,6 +191,20 @@ def _native_messages(self, chat_id, top, since=None): log.warning("native messages failed, using Graph: %s", e) return None + def _native_message(self, chat_id, message_id): + """One message through chatsvc, or None if Graph should answer instead.""" + if not self.native: + return None + try: + raw = self._chatsvc_get( + f"conversations/{chat_id}/messages/{message_id}", + {"view": f"{_VIEW}|supportsMessageProperties"}, + ) + return message_from_native(raw, chat_id) + except _FALLBACK as e: + log.warning("native message failed, using Graph: %s", e) + return None + def _read_messages(self, chat_id, top, since=None): out = [] page = self._chatsvc_get( diff --git a/src/outnote/_people.py b/src/outnote/_people.py index ed4a589..114d262 100644 --- a/src/outnote/_people.py +++ b/src/outnote/_people.py @@ -63,6 +63,30 @@ def resolve_user(self, user): class ProfileMixin(Transport): + def suggest_recipients(self, text="", top=5): + """Email address suggestions as someone types, people you contact most first. Returns + `{"name", "address", "id"}` dicts. With no `text`, your top contacts. Fills up from the + directory if your own contacts give too few, which adds about 100 ms.""" + params = {"$top": top, "$select": "id,displayName,scoredEmailAddresses"} + text = text.strip() + if text: + params["$search"] = '"' + text.replace('"', "") + '"' + out, seen = [], set() + + def add(name, address, person_id): + key = (address or "").lower() + if key and key not in seen and len(out) < top: + seen.add(key) + out.append({"name": name, "address": address, "id": person_id}) + + for p in self.get("me/people", params).get("value", []): + scored = p.get("scoredEmailAddresses") or [] + add(p.get("displayName"), scored[0].get("address") if scored else None, p.get("id")) + if text and len(out) < top: + for u in self.find_users(text, top): + add(u.get("displayName"), u.get("mail") or u.get("userPrincipalName"), u.get("id")) + return out + def people(self, top=25): """People you work with most, ranked by Microsoft (`me/people`).""" params = {"$top": top, "$select": "id,displayName,jobTitle,department,scoredEmailAddresses"} diff --git a/src/outnote/_teams.py b/src/outnote/_teams.py index 251ad14..1b74df9 100644 --- a/src/outnote/_teams.py +++ b/src/outnote/_teams.py @@ -78,6 +78,14 @@ def chat_messages(self, chat_id, top=30, since=None): params["$orderby"] = "lastModifiedDateTime desc" return self.list(f"me/chats/{chat_id}/messages", params, limit=top) + def chat_message(self, chat_id, message_id): + """One message of a chat, with its attachments (see `message_files`). Uses Teams' own API, + because Graph can throttle single-message reads heavily, and falls back to Graph.""" + fast = self._native_message(chat_id, message_id) + if fast is not None: + return fast + return self.get(f"chats/{chat_id}/messages/{message_id}") + # --- sending (posts as the signed-in user) ------------------------------ def _mention_body(self, text, html, mentions): content = text if html else text_to_html(text) diff --git a/src/outnote/_work.py b/src/outnote/_work.py index d811356..01efcef 100644 --- a/src/outnote/_work.py +++ b/src/outnote/_work.py @@ -123,21 +123,39 @@ def search(self, query, entity="message", top=25): 'message' (email), 'driveItem' (files), 'chatMessage' (Teams chat/channel messages), 'event' (calendar), 'person', 'site', 'listItem'. (Graph only allows one of these per request.)""" + return self._search_page(query, entity, top)[0] + + def _search_page(self, query, entity, size, start=0): + """One page of results, and whether Graph has more.""" + request = {"entityTypes": [entity], "query": {"queryString": query}, "size": size} + if start: + request["from"] = start client = _SEARCH_CLIENT.get(entity, C_OFFICE) - body = { - "requests": [{"entityTypes": [entity], "query": {"queryString": query}, "size": top}] - } - data = self.post("search/query", body, client=client) or {} + data = self.post("search/query", {"requests": [request]}, client=client) or {} containers = (data.get("value") or [{}])[0].get("hitsContainers") or [] - hits = containers[0].get("hits", []) if containers else [] + container = containers[0] if containers else {} out = [] - for h in hits: + for h in container.get("hits", []): r = dict(h.get("resource") or {}) r["id"] = r.get("id") or h.get("hitId") if h.get("summary"): r["_summary"] = h["summary"] out.append(r) - return out + return out, bool(container.get("moreResultsAvailable")) + + def search_chat(self, chat_id, query, top=25, scan=200): + """Messages in one chat matching `query`, as Microsoft Search ranks them, with a highlighted + `_summary` when it gives one. Graph can't limit a search to one chat, so this looks through up to `scan` results + across all your chats and keeps this chat's. A word that's common elsewhere can use up `scan` + before reaching them; raise it, or use `chat_messages` and filter for an exact scan.""" + out, start, page = [], 0, 25 + while start < scan and len(out) < top: + hits, more = self._search_page(query, "chatMessage", page, start) + out.extend(h for h in hits if h.get("chatId") == chat_id) + if not more or not hits: + break + start += len(hits) + return out[:top] def search_emails(self, query, top=25): return self.search(query, "message", top) diff --git a/tests/test_native.py b/tests/test_native.py index 1ed6375..fac3c53 100644 --- a/tests/test_native.py +++ b/tests/test_native.py @@ -208,6 +208,30 @@ def test_chat_messages_filter_by_since(monkeypatch): assert [m["id"] for m in got] == ["new"] +def test_chat_message_uses_the_chat_service(monkeypatch): + files = json.dumps([{"itemid": "f", "fileName": "a.pdf", "objectUrl": "https://f/a.pdf"}]) + raw = {"id": "7", "messagetype": "Text", "content": "x", "properties": {"files": files}} + c = client(monkeypatch, [("authz", AUTHZ), ("messages/7", raw)]) + got = c.chat_message("19:a@thread.v2", "7") + assert got["id"] == "7" and got["chatId"] == "19:a@thread.v2" + assert c.message_files(got)[0]["name"] == "a.pdf" + assert not any(x["path"].startswith(_base.GRAPH) for x in c.fake.calls) + + +@pytest.mark.parametrize("failure", [outnote.GraphError(404, "no"), KeyError("x")]) +def test_chat_message_falls_back_to_graph(monkeypatch, failure): + c = client( + monkeypatch, [("authz", failure), ("chats/c/messages/7", {"id": "7", "graph": True})] + ) + assert c.chat_message("c", "7") == {"id": "7", "graph": True} + + +def test_chat_message_without_native_uses_graph(monkeypatch): + c = client(monkeypatch, [("chats/c/messages/7", {"id": "7"})], native=False) + assert c.chat_message("c", "7") == {"id": "7"} + assert not any("authz" in x["path"] for x in c.fake.calls) + + def test_mail_startup_sends_what_outlook_sends(monkeypatch): c = client(monkeypatch, [("startupdata", {"findConversation": {}})]) assert "findConversation" in c.mail_startup(top=10) diff --git a/tests/test_transport.py b/tests/test_transport.py index b16fcff..81953da 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -264,3 +264,114 @@ def test_items_and_ids_both_work(monkeypatch): "drives/d2/items/x", "me/drive/items/x", ] + + +# --- suggest_recipients -------------------------------------------------------- +def person(name, address): + return {"id": name, "displayName": name, "scoredEmailAddresses": [{"address": address}]} + + +def people_client(monkeypatch, people=(), directory=()): + c = outnote.OutNote("tok") + calls = {"people": [], "users": []} + monkeypatch.setattr( + c, + "get", + lambda path, params=None, **k: calls["people"].append(params) or {"value": list(people)}, + ) + monkeypatch.setattr( + c, "find_users", lambda text, top: calls["users"].append(text) or list(directory) + ) + c.calls = calls + return c + + +def test_suggestions_put_your_contacts_first_and_skip_the_directory_when_full(monkeypatch): + c = people_client(monkeypatch, [person("Ann", "ann@x.ch"), person("Abe", "abe@x.ch")]) + got = c.suggest_recipients("a", top=2) + assert got == [ + {"name": "Ann", "address": "ann@x.ch", "id": "Ann"}, + {"name": "Abe", "address": "abe@x.ch", "id": "Abe"}, + ] + assert c.calls["people"][0]["$search"] == '"a"' and c.calls["users"] == [] + + +def test_suggestions_fill_up_from_the_directory_without_duplicates(monkeypatch): + directory = [ + {"id": "1", "displayName": "Ann again", "mail": "ANN@x.ch"}, + {"id": "2", "displayName": "Ada", "mail": None, "userPrincipalName": "ada@x.ch"}, + {"id": "3", "displayName": "No address"}, + ] + c = people_client(monkeypatch, [person("Ann", "ann@x.ch")], directory) + got = c.suggest_recipients("a", top=5) + assert [g["address"] for g in got] == ["ann@x.ch", "ada@x.ch"] + + +def test_suggestions_with_no_text_are_your_top_contacts(monkeypatch): + c = people_client(monkeypatch, [person("Ann", "ann@x.ch")]) + assert c.suggest_recipients()[0]["name"] == "Ann" + assert "$search" not in c.calls["people"][0] and c.calls["users"] == [] + + +def test_suggestions_skip_people_without_an_address_and_clean_the_query(monkeypatch): + nobody = {"id": "x", "displayName": "No mail", "scoredEmailAddresses": []} + c = people_client(monkeypatch, [nobody]) + assert c.suggest_recipients(' a"b ') == [] + assert c.calls["people"][0]["$search"] == '"ab"' + + +# --- search_chat --------------------------------------------------------------- +def search_client(monkeypatch, *pages): + c = outnote.OutNote("tok") + bodies = [] + answers = list(pages) + + def post(path, body, client=None): + bodies.append(body["requests"][0]) + hits, more = answers.pop(0) + return { + "value": [ + { + "hitsContainers": [ + { + "hits": [ + {"hitId": h[0], "summary": "s", "resource": {"chatId": h[1]}} + for h in hits + ], + "moreResultsAvailable": more, + } + ] + } + ] + } + + monkeypatch.setattr(c, "post", post) + c.bodies = bodies + return c + + +def test_search_chat_keeps_that_chat_across_pages(monkeypatch): + c = search_client( + monkeypatch, + ([("1", "other"), ("2", "mine")], True), + ([("3", "mine"), ("4", "other")], False), + ) + got = c.search_chat("mine", "word") + assert [g["id"] for g in got] == ["2", "3"] and got[0]["_summary"] == "s" + assert "from" not in c.bodies[0] and c.bodies[1]["from"] == 2 + assert c.bodies[0]["entityTypes"] == ["chatMessage"] + + +def test_search_chat_stops_at_top_and_at_scan(monkeypatch): + many = [(str(i), "mine") for i in range(25)] + c = search_client(monkeypatch, (many, True)) + assert len(c.search_chat("mine", "w", top=5)) == 5 and len(c.bodies) == 1 + others = [(str(i), "other") for i in range(25)] + c = search_client(monkeypatch, (others, True), (others, True), (others, True)) + assert c.search_chat("mine", "w", scan=50) == [] and len(c.bodies) == 2 + + +def test_search_is_unchanged(monkeypatch): + c = search_client(monkeypatch, ([("1", "x")], True)) + assert [r["id"] for r in c.search("w", "chatMessage", 3)] == ["1"] + assert c.bodies[0]["size"] == 3