signal-bot/fake_signal/routes_groups.py
2026-08-29 15:30:08 +02:00

50 lines
1.8 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The group endpoints, including the join the bot self-heals with."""
from __future__ import annotations
from typing import TYPE_CHECKING
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
if TYPE_CHECKING:
from fake_signal.state import State
def _state(request: Request) -> State:
"""Return the State attached to the running app."""
state: State = request.app.state.fake
return state
def build_group_router() -> APIRouter:
"""Build the router covering group listing and joining."""
router = APIRouter()
@router.get("/v1/groups/{number}")
async def groups(request: Request, number: str) -> JSONResponse:
state = _state(request)
if number not in state.accounts:
return JSONResponse({"error": f"{number} is not registered"}, status_code=400)
return JSONResponse(state.groups, status_code=200)
@router.post("/v1/groups/{number}/{group_id}/join")
async def join(request: Request, number: str, group_id: str) -> JSONResponse:
"""Accept a pending invitation, the way signal-cli sometimes can.
The real endpoint answers 201 whether or not the account ended up a
member, which is why the bot re-reads the listing instead of
trusting this. Modelling that faithfully is the point: a fake that
only ever succeeds would hide the re-check.
"""
state = _state(request)
if number not in state.accounts:
return JSONResponse({"error": f"{number} is not registered"}, status_code=400)
for group in state.groups:
if group_id in {group.get("id"), group.get("internal_id")} and group.get("joinable"):
group["member"] = True
return JSONResponse({}, status_code=201)
return router