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:
2026-09-20 19:01:14 +03:00
parent 3ae03ec515
commit 1552146aa1
13 changed files with 1056 additions and 10 deletions
+156
View File
@@ -1155,3 +1155,159 @@ func TestLiveKitWebhook(t *testing.T) {
t.Fatalf("после participant_left = %+v", empty.States)
}
}
// TestSoundboard проверяет загрузку звуков, права, лимит и событие проигрывания.
func TestSoundboard(t *testing.T) {
f := newMessagingFixture(t)
httpServer := httptest.NewServer(f.srv.Handler())
t.Cleanup(httpServer.Close)
f.srv.cfg.LiveKitAPIKey = "testkey"
f.srv.cfg.LiveKitAPISecret = "testsecret"
f.srv.cfg.LiveKitURL = "wss://gl.test/rtc"
f.srv.voice = voice.NewIssuer("testkey", "testsecret", time.Hour)
voiceRec := doJSON(t, f.srv, http.MethodPost, "/api/v1/guilds/"+f.guildID+"/channels",
`{"name":"Голос","type":"voice"}`, f.ownerCookie)
voiceChannel := decodeResponse[struct {
Channel struct {
ID string `json:"id"`
} `json:"channel"`
}](t, voiceRec)
// Участник без MANAGE_SOUNDS не может загрузить звук.
denied := uploadSound(t, httpServer, f.memberCookie, f.guildID, "soundboard", "boo", "", []byte("OggS\x00звук"))
if denied.status != http.StatusForbidden {
t.Fatalf("member upload sound = %d, want 403", denied.status)
}
// Владелец загружает звук саундборда.
created := uploadSound(t, httpServer, f.ownerCookie, f.guildID, "soundboard", "boo", "", []byte("OggS\x00звук"))
if created.status != http.StatusOK {
t.Fatalf("owner upload sound = %d, body = %s", created.status, created.body)
}
sound := decodeResponse[struct {
Sound struct {
ID string `json:"id"`
Name string `json:"name"`
Kind string `json:"kind"`
FileID string `json:"file_id"`
} `json:"sound"`
}](t, created.recorder)
if sound.Sound.Name != "boo" || sound.Sound.Kind != "soundboard" {
t.Fatalf("unexpected sound: %+v", sound.Sound)
}
// Звук интерфейса требует событие.
uiMissing := uploadSound(t, httpServer, f.ownerCookie, f.guildID, "ui", "join_sound", "", []byte("OggS\x00звук"))
if uiMissing.status != http.StatusUnprocessableEntity {
t.Fatalf("ui sound без события = %d, want 422", uiMissing.status)
}
ui := uploadSound(t, httpServer, f.ownerCookie, f.guildID, "ui", "join_sound", "member_join", []byte("OggS\x00звук"))
if ui.status != http.StatusOK {
t.Fatalf("ui sound = %d, body = %s", ui.status, ui.body)
}
// Список и фильтр по виду.
list := doJSON(t, f.srv, http.MethodGet, "/api/v1/guilds/"+f.guildID+"/sounds?kind=soundboard", "", f.memberCookie)
sounds := decodeResponse[struct {
Sounds []struct {
Name string `json:"name"`
Kind string `json:"kind"`
} `json:"sounds"`
}](t, list)
if len(sounds.Sounds) != 1 || sounds.Sounds[0].Name != "boo" {
t.Fatalf("soundboard list = %+v", sounds.Sounds)
}
// Проигрывание вне голосовой комнаты запрещено.
notConnected := doJSON(t, f.srv, http.MethodPost,
"/api/v1/guilds/"+f.guildID+"/sounds/"+sound.Sound.ID+"/play", "", f.memberCookie)
if notConnected.Code != http.StatusForbidden {
t.Fatalf("play вне комнаты = %d, want 403", notConnected.Code)
}
// Владелец входит в голосовую комнату и играет звук.
join := doJSON(t, f.srv, http.MethodPost, "/api/v1/channels/"+voiceChannel.Channel.ID+"/voice/join", "", f.ownerCookie)
if join.Code != http.StatusOK {
t.Fatalf("join voice = %d, body = %s", join.Code, join.Body.String())
}
play := doJSON(t, f.srv, http.MethodPost,
"/api/v1/guilds/"+f.guildID+"/sounds/"+sound.Sound.ID+"/play", "", f.ownerCookie)
if play.Code != http.StatusOK {
t.Fatalf("play = %d, body = %s", play.Code, play.Body.String())
}
// Лимит частоты: 3 звука за 10 секунд.
blocked := (*httptest.ResponseRecorder)(nil)
for range 4 {
blocked = doJSON(t, f.srv, http.MethodPost,
"/api/v1/guilds/"+f.guildID+"/sounds/"+sound.Sound.ID+"/play", "", f.ownerCookie)
}
if blocked.Code != http.StatusTooManyRequests {
t.Fatalf("четвёртый звук подряд = %d, want 429", blocked.Code)
}
// Переименование и удаление.
renamed := doJSON(t, f.srv, http.MethodPatch,
"/api/v1/guilds/"+f.guildID+"/sounds/"+sound.Sound.ID, `{"name":"boo2","emoji":"👻"}`, f.ownerCookie)
if renamed.Code != http.StatusOK {
t.Fatalf("rename sound = %d, body = %s", renamed.Code, renamed.Body.String())
}
deleted := doJSON(t, f.srv, http.MethodDelete,
"/api/v1/guilds/"+f.guildID+"/sounds/"+sound.Sound.ID, "", f.ownerCookie)
if deleted.Code != http.StatusOK {
t.Fatalf("delete sound = %d", deleted.Code)
}
}
// uploadSound загружает звук через multipart.
func uploadSound(t *testing.T, server *httptest.Server, cookie *http.Cookie, guildID, kind, name, event string, content []byte) struct {
status int
body string
recorder *httptest.ResponseRecorder
} {
t.Helper()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
if err := writer.WriteField("name", name); err != nil {
t.Fatalf("write name: %v", err)
}
if event != "" {
if err := writer.WriteField("event", event); err != nil {
t.Fatalf("write event: %v", err)
}
}
header := textproto.MIMEHeader{}
header.Set("Content-Disposition", `form-data; name="file"; filename="`+name+`.ogg"`)
header.Set("Content-Type", "audio/ogg")
part, err := writer.CreatePart(header)
if err != nil {
t.Fatalf("CreatePart: %v", err)
}
if _, err := part.Write(content); err != nil {
t.Fatalf("write sound: %v", err)
}
if err := writer.Close(); err != nil {
t.Fatalf("close writer: %v", err)
}
url := server.URL + "/api/v1/guilds/" + guildID + "/sounds?kind=" + kind
req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, url, bytes.NewReader(body.Bytes()))
if err != nil {
t.Fatalf("new request: %v", err)
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.AddCookie(cookie)
resp, err := server.Client().Do(req)
if err != nil {
t.Fatalf("upload sound: %v", err)
}
payload, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
recorder := httptest.NewRecorder()
recorder.WriteHeader(resp.StatusCode)
if _, err := recorder.Body.Write(payload); err != nil {
t.Fatalf("copy body: %v", err)
}
return struct {
status int
body string
recorder *httptest.ResponseRecorder
}{status: resp.StatusCode, body: string(payload), recorder: recorder}
}