package voice import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "strings" "time" ) // AdminClient обращается к RoomService LiveKit (Twirp/JSON) для модерации: // серверный мьют дорожки и удаление участника из комнаты (AGENT.md 7.14). // Собственный HTTP-клиент вместо SDK: нужны три метода из всего API. type AdminClient struct { issuer *TokenIssuer baseURL string http *http.Client } // NewAdminClient создаёт клиента RoomService. Пустой baseURL означает, что // модерация на стороне SFU недоступна (например, в тестах). func NewAdminClient(issuer *TokenIssuer, baseURL string) *AdminClient { return &AdminClient{ issuer: issuer, baseURL: strings.TrimSuffix(strings.TrimSpace(baseURL), "/"), http: &http.Client{Timeout: 5 * time.Second}, } } // Enabled сообщает, настроен ли доступ к RoomService. func (c *AdminClient) Enabled() bool { return c != nil && c.baseURL != "" && c.issuer.Enabled() } // Participant — участник комнаты на стороне SFU. type Participant struct { Identity string `json:"identity"` SID string `json:"sid"` Tracks []struct { SID string `json:"sid"` Type string `json:"type"` Source string `json:"source"` Muted bool `json:"muted"` Name string `json:"name"` } `json:"tracks"` } // ParticipantInfo отдаёт данные участника комнаты. func (c *AdminClient) ParticipantInfo(ctx context.Context, room, identity string) (*Participant, error) { var response struct { Participant Participant `json:"participant"` } err := c.call(ctx, "GetParticipant", map[string]any{"room": room, "identity": identity}, &response) if err != nil { return nil, err } return &response.Participant, nil } // SetMicrophoneMuted включает или выключает микрофон участника на стороне SFU: // клиент физически не может обойти серверный мьют (AGENT.md 7.14). func (c *AdminClient) SetMicrophoneMuted(ctx context.Context, room, identity string, muted bool) error { participant, err := c.ParticipantInfo(ctx, room, identity) if err != nil { return err } trackSID := "" for _, track := range participant.Tracks { if strings.EqualFold(track.Source, "MICROPHONE") || strings.EqualFold(track.Type, "AUDIO") { trackSID = track.SID break } } if trackSID == "" { // Участник без микрофона: мьютить нечего, это не ошибка. return nil } return c.call(ctx, "MutePublishedTrack", map[string]any{ "room": room, "identity": identity, "track_sid": trackSID, "muted": muted, }, nil) } // RemoveParticipant удаляет участника из комнаты (кик из голосовой). func (c *AdminClient) RemoveParticipant(ctx context.Context, room, identity string) error { return c.call(ctx, "RemoveParticipant", map[string]any{"room": room, "identity": identity}, nil) } // ListParticipants перечисляет участников комнаты: используется для проверки // расхождений между БД и SFU. func (c *AdminClient) ListParticipants(ctx context.Context, room string) ([]Participant, error) { var response struct { Participants []Participant `json:"participants"` } if err := c.call(ctx, "ListParticipants", map[string]any{"room": room}, &response); err != nil { return nil, err } return response.Participants, nil } // call выполняет запрос к Twirp-методу RoomService с административным токеном. func (c *AdminClient) call(ctx context.Context, method string, body any, out any) error { if !c.Enabled() { return ErrDisabled } payload, err := json.Marshal(body) if err != nil { return err } token, err := c.adminToken() if err != nil { return err } endpoint := fmt.Sprintf("%s/twirp/livekit.RoomService/%s", c.baseURL, method) request, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload)) if err != nil { return err } request.Header.Set("Content-Type", "application/json") request.Header.Set("Authorization", "Bearer "+token) response, err := c.http.Do(request) if err != nil { return fmt.Errorf("voice.api_unavailable: %w", err) } defer func() { _ = response.Body.Close() }() raw, err := io.ReadAll(io.LimitReader(response.Body, 1<<20)) if err != nil { return err } if response.StatusCode != http.StatusOK { return fmt.Errorf("voice.api_error: %s: %s", response.Status, strings.TrimSpace(string(raw))) } if out == nil || len(raw) == 0 { return nil } if err := json.Unmarshal(raw, out); err != nil { return fmt.Errorf("voice.api_decode: %w", err) } return nil } // adminToken подписывает административный токен RoomService. func (c *AdminClient) adminToken() (string, error) { return c.issuer.IssueAdmin() }