feat(voice): модерация через RoomService, саундборд и звуковая палитра
AGENT.md 7.13, 7.14:
- `internal/voice/admin.go` — клиент RoomService (Twirp/JSON, без SDK):
GetParticipant, ListParticipants, MutePublishedTrack, RemoveParticipant с
административным токеном; внутренний адрес SFU задаётся LIVEKIT_API_URL;
- серверный мьют теперь применяется и на стороне SFU (клиент не обойдёт),
кик из голосовой (DELETE /guilds/{id}/voice-states/{user_id}) удаляет
участника из комнаты через RemoveParticipant, перемещение — тоже;
- саундборд и звуковая палитра: таблица `guild_sounds` (миграция 00010),
загрузка MP3/OGG/WAV/WebM/M4A до 512 КБ с MANAGE_SOUNDS, отдельные лимиты
30 + 30, переименование, удаление, список с фильтром по виду;
- проигрывание POST /guilds/{id}/sounds/{sound_id}/play: нужно право
USE_SOUNDBOARD и присутствие в голосовой комнате, событие SOUNDBOARD_PLAY
уходит только участникам этой комнаты (звук играют клиенты), лимит 3 звука
за 10 секунд; набор звуков приходит в READY и обновляется событием
GUILD_SOUNDS_UPDATE;
- тесты: права на загрузку, требование события для звука интерфейса, запрет
проигрывания вне комнаты, лимит частоты, переименование и удаление.
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
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()
|
||||
}
|
||||
@@ -119,6 +119,42 @@ func encodeSegment(payload []byte) string {
|
||||
return base64.RawURLEncoding.EncodeToString(payload)
|
||||
}
|
||||
|
||||
// IssueAdmin подписывает административный токен RoomService: полные права на
|
||||
// комнаты (модерация, удаление участников), но не на запись медиа.
|
||||
func (i *TokenIssuer) IssueAdmin() (string, error) {
|
||||
if !i.Enabled() {
|
||||
return "", ErrDisabled
|
||||
}
|
||||
now := i.now().UTC()
|
||||
claims := map[string]any{
|
||||
"iss": i.apiKey,
|
||||
"sub": i.apiKey,
|
||||
"nbf": now.Add(-10 * time.Second).Unix(),
|
||||
"exp": now.Add(10 * time.Minute).Unix(),
|
||||
"video": map[string]any{
|
||||
"roomCreate": true,
|
||||
"roomList": true,
|
||||
"roomAdmin": true,
|
||||
"roomRecord": false,
|
||||
"ingressAdmin": false,
|
||||
},
|
||||
}
|
||||
header, err := json.Marshal(map[string]string{"alg": "HS256", "typ": "JWT"})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
payload, err := json.Marshal(claims)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
signingInput := encodeSegment(header) + "." + encodeSegment(payload)
|
||||
mac := hmac.New(sha256.New, []byte(i.apiSecret))
|
||||
if _, err := mac.Write([]byte(signingInput)); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return signingInput + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// VerifyWebhook проверяет подпись вебхука LiveKit: это JWT, подписанный тем же
|
||||
// API-секретом, а в payload лежит base64(sha256(тело запроса)) (AGENT.md 7.14).
|
||||
func (i *TokenIssuer) VerifyWebhook(authorization string, body []byte) error {
|
||||
|
||||
Reference in New Issue
Block a user