Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

8.4 KB
Raw Blame
from __future__ import annotations

from collections import Counter
from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, Response
from sqlalchemy.ext.asyncio import AsyncSession

from switch_core.authz import Principal, require
from switch_core.db.models import RoomGroup, User
from switch_core.db.stores.room_group_store import (
    RoomGroupNameTaken,
    RoomGroupStore,
)
from switch_core.db.stores.room_store import RoomStore
from switch_core.gateway.auth import (
    get_current_user,
    get_tenant_is_admin,
    require_group_filing_or_403,
)
from switch_core.gateway.dependencies import (
    current_telemetry,
    get_room_group_store,
    get_room_store,
    get_session,
)
from switch_core.gateway.schemas import (
    RoomGroupAssignRequest,
    RoomGroupAssignResponse,
    RoomGroupCreateRequest,
    RoomGroupDetail,
    RoomGroupUpdateRequest,
)
from switch_core.telemetry import emit_safely
from switch_core.telemetry.ages import UNKNOWN_AGE, age_days

router = APIRouter()


def _require_group_admin(is_admin: bool) -> None:
    """Groups are shared by the whole workspace and have no owner, so only a
    workspace admin may create, change or delete one. Filing a room one can
    write into an existing group stays open to everyone."""
    if not is_admin:
        raise HTTPException(
            status_code=403, detail="Only a workspace admin can manage room groups."
        )


async def _readable_room_counts(
    session: AsyncSession, room_store: RoomStore, user: User, is_admin: bool
) -> Counter[str]:
    """Rooms directly in each group, counting only rooms `user` may read."""
    rooms = await room_store.list_readable(
        session, user.id, is_admin=is_admin, include_archived=True
    )
    return Counter(r.group_id for r in rooms if r.group_id is not None)


def _to_detail(group: RoomGroup, room_count: int) -> RoomGroupDetail:
    return RoomGroupDetail(
        id=group.id,
        name=group.name,
        description=group.description,
        color=group.color,
        parent_group_id=group.parent_group_id,
        room_count=room_count,
        created_at=str(group.created_at),
    )


@router.get("")
async def list_room_groups(
    session: Annotated[AsyncSession, Depends(get_session)],
    room_group_store: Annotated[RoomGroupStore, Depends(get_room_group_store)],
    room_store: Annotated[RoomStore, Depends(get_room_store)],
    user: Annotated[User, Depends(get_current_user)],
    is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> list[RoomGroupDetail]:
    groups = await room_group_store.get_all(session)
    counts = await _readable_room_counts(session, room_store, user, is_admin)
    return [_to_detail(g, counts.get(g.id, 0)) for g in groups]


@router.post("", status_code=201)
async def create_room_group(
    req: RoomGroupCreateRequest,
    session: Annotated[AsyncSession, Depends(get_session)],
    room_group_store: Annotated[RoomGroupStore, Depends(get_room_group_store)],
    _user: Annotated[User, Depends(get_current_user)],
    is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> RoomGroupDetail:
    _require_group_admin(is_admin)
    try:
        group = await room_group_store.create(
            session,
            name=req.name,
            description=req.description,
            color=req.color,
            parent_group_id=req.parent_group_id,
        )
    except RoomGroupNameTaken as e:
        raise HTTPException(status_code=409, detail=str(e)) from e
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e)) from e
    await session.commit()
    emit_safely(
        current_telemetry(),
        "room_group_created",
        {"has_parent": req.parent_group_id is not None},
    )
    return _to_detail(group, 0)


@router.patch("/{group_id}")
async def patch_room_group(
    group_id: str,
    req: RoomGroupUpdateRequest,
    session: Annotated[AsyncSession, Depends(get_session)],
    room_group_store: Annotated[RoomGroupStore, Depends(get_room_group_store)],
    room_store: Annotated[RoomStore, Depends(get_room_store)],
    user: Annotated[User, Depends(get_current_user)],
    is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> RoomGroupDetail:
    _require_group_admin(is_admin)
    # Only reparent when the client actually sent `parent_group_id` (so we can
    # tell "make top-level" (null) apart from "leave the parent alone" (absent)).
    reparent = "parent_group_id" in req.model_fields_set
    try:
        group = await room_group_store.update_fields(
            session,
            group_id,
            name=req.name,
            description=req.description,
            color=req.color,
            parent_group_id=req.parent_group_id,
            reparent=reparent,
        )
    except RoomGroupNameTaken as e:
        raise HTTPException(status_code=409, detail=str(e)) from e
    except ValueError as e:
        # "not found" → 404; cycle/validation → 400.
        if "not found" in str(e).lower():
            raise HTTPException(status_code=404, detail=str(e)) from e
        raise HTTPException(status_code=400, detail=str(e)) from e
    await session.commit()
    counts = await _readable_room_counts(session, room_store, user, is_admin)
    return _to_detail(group, counts.get(group.id, 0))


@router.put("/{group_id}/rooms")
async def assign_rooms_to_group(
    group_id: str,
    req: RoomGroupAssignRequest,
    session: Annotated[AsyncSession, Depends(get_session)],
    room_group_store: Annotated[RoomGroupStore, Depends(get_room_group_store)],
    room_store: Annotated[RoomStore, Depends(get_room_store)],
    user: Annotated[User, Depends(get_current_user)],
    is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> RoomGroupAssignResponse:
    """Bulk-assign rooms into a group. Requires a workspace admin (see
    `require_group_filing`) and write access to each room; unknown room ids
    are skipped."""
    # Before the lookup: whether a group exists is not for someone who may
    # not file into it.
    require_group_filing_or_403(is_admin)
    if await room_group_store.get(session, group_id) is None:
        raise HTTPException(status_code=404, detail="Room group not found")

    principal = Principal(user.id, is_admin)
    forbidden: list[str] = []
    allowed: list[str] = []
    for room_id in req.room_ids:
        room = await room_store.get(session, room_id)
        if room is None:
            continue  # skip unknown ids rather than failing the whole batch
        try:
            require(principal, "write", room)
        except PermissionError:
            forbidden.append(room_id)
            continue
        allowed.append(room_id)

    if forbidden:
        raise HTTPException(
            status_code=403,
            detail=f"No write access to rooms: {', '.join(forbidden)}",
        )

    assigned = await room_store.set_group_bulk(
        session, allowed, group_id, acting_is_admin=is_admin
    )
    await session.commit()
    return RoomGroupAssignResponse(assigned=assigned)


@router.delete("/{group_id}", status_code=204)
async def delete_room_group(
    group_id: str,
    session: Annotated[AsyncSession, Depends(get_session)],
    room_group_store: Annotated[RoomGroupStore, Depends(get_room_group_store)],
    _user: Annotated[User, Depends(get_current_user)],
    is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> Response:
    _require_group_admin(is_admin)
    # Read before the delete: afterwards there is nothing left to say how much
    # was filed under it, which is the difference between tidying up an empty
    # group and dismantling a working one.
    group = await room_group_store.get(session, group_id)
    room_count = (await room_group_store.get_room_counts(session)).get(group_id, 0)
    # `UNKNOWN_AGE`, not `0.0`: a group that could not be read has no age, and
    # zero is one a real group can have. Unreachable today — the delete below
    # 404s on a missing group before the event is built — but the sentinel is
    # what makes that stay true if the order ever changes.
    age = age_days(group.created_at) if group else UNKNOWN_AGE

    try:
        removed = await room_group_store.delete(session, group_id)
    except RoomGroupNameTaken as e:
        raise HTTPException(status_code=409, detail=str(e)) from e
    if not removed:
        raise HTTPException(status_code=404, detail="Room group not found")
    await session.commit()
    emit_safely(
        current_telemetry(),
        "room_group_deleted",
        {"room_count": room_count, "age_days": age},
    )
    return Response(status_code=204)