64 lines
1.7 KiB
Python
64 lines
1.7 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import logging
|
||
|
|
|
||
|
|
from .graph import MSTeamsGraphClient
|
||
|
|
|
||
|
|
logger = logging.getLogger(__name__)
|
||
|
|
|
||
|
|
|
||
|
|
async def search_users(
|
||
|
|
graph_client: MSTeamsGraphClient,
|
||
|
|
query: str,
|
||
|
|
*,
|
||
|
|
limit: int = 10,
|
||
|
|
) -> list[dict]:
|
||
|
|
path = f'/users?$search="displayName:{query}"&$top={limit}&$select=id,displayName,mail,userPrincipalName'
|
||
|
|
try:
|
||
|
|
data = await graph_client.fetch_json(path)
|
||
|
|
return _parse_users(data)
|
||
|
|
except Exception as e:
|
||
|
|
logger.warning("User search failed for query '%s': %s", query, e)
|
||
|
|
return []
|
||
|
|
|
||
|
|
|
||
|
|
async def get_user(
|
||
|
|
graph_client: MSTeamsGraphClient,
|
||
|
|
user_id: str,
|
||
|
|
) -> dict | None:
|
||
|
|
path = f"/users/{user_id}?$select=id,displayName,mail,userPrincipalName"
|
||
|
|
try:
|
||
|
|
data = await graph_client.fetch_json(path)
|
||
|
|
return _parse_single_user(data)
|
||
|
|
except Exception as e:
|
||
|
|
logger.warning("Failed to get user %s: %s", user_id, e)
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
async def get_aad_object_id(
|
||
|
|
graph_client: MSTeamsGraphClient,
|
||
|
|
identifier: str,
|
||
|
|
) -> str | None:
|
||
|
|
users = await search_users(graph_client, identifier)
|
||
|
|
for user in users:
|
||
|
|
if (
|
||
|
|
user.get("displayName", "").lower() == identifier.lower()
|
||
|
|
or user.get("mail", "").lower() == identifier.lower()
|
||
|
|
):
|
||
|
|
return user.get("id")
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def _parse_single_user(data: dict) -> dict:
|
||
|
|
return {
|
||
|
|
"id": data.get("id", ""),
|
||
|
|
"display_name": data.get("displayName", ""),
|
||
|
|
"mail": data.get("mail", ""),
|
||
|
|
"user_principal_name": data.get("userPrincipalName", ""),
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
def _parse_users(data: dict) -> list[dict]:
|
||
|
|
users = data.get("value", [])
|
||
|
|
return [_parse_single_user(u) for u in users]
|