Files
XHChat/server/internal/httpapi/groups.go
T

116 lines
3.0 KiB
Go

package httpapi
import (
"errors"
"net/http"
"strings"
"unicode"
"unicode/utf8"
"xhchat/server/internal/account"
"xhchat/server/internal/groups"
)
func groupName(name string) bool {
return name != "" && utf8.RuneCountInString(name) <= 64 && !strings.ContainsFunc(name, unicode.IsControl)
}
func groupError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, groups.ErrUnavailable):
problem(w, 404, "group_not_found", "群聊不可用")
case errors.Is(err, groups.ErrAction):
problem(w, 409, "group_action_unavailable", "当前无法执行此群操作")
case errors.Is(err, groups.ErrLimit):
problem(w, 409, "group_member_limit", "群成员与待处理邀请已达上限")
case errors.Is(err, groups.ErrVersion):
problem(w, 409, "group_epoch_changed", "群成员或设备版本已变更")
default:
unavailable(w, err)
}
}
func (a *API) createGroup(w http.ResponseWriter, r *http.Request, _ string, id account.Identity) {
var body struct {
Name string `json:"name"`
}
if !parse(w, r, &body) {
return
}
name := strings.TrimSpace(body.Name)
if !groupName(name) {
problem(w, 400, "invalid_group_name", "群名称须为 1 至 64 个字符")
return
}
if !a.limit(w, r, "group-create:"+id.User.ID, 10) {
return
}
group, err := a.groups.Create(r.Context(), id.User.ID, name)
if err != nil {
groupError(w, err)
return
}
respond(w, 201, group)
}
func (a *API) listGroups(w http.ResponseWriter, r *http.Request, _ string, id account.Identity) {
result, err := a.groups.List(r.Context(), id.User.ID)
if err != nil {
groupError(w, err)
return
}
respond(w, 200, result)
}
func (a *API) groupDetail(w http.ResponseWriter, r *http.Request, _ string, id account.Identity) {
group := r.PathValue("id")
if !uuidPattern.MatchString(group) {
groupError(w, groups.ErrUnavailable)
return
}
result, err := a.groups.Detail(r.Context(), id.User.ID, group)
if err != nil {
groupError(w, err)
return
}
respond(w, 200, result)
}
func (a *API) changeGroup(w http.ResponseWriter, r *http.Request, _ string, id account.Identity) {
group := r.PathValue("id")
if !uuidPattern.MatchString(group) {
groupError(w, groups.ErrUnavailable)
return
}
var change groups.Change
if !parse(w, r, &change) {
return
}
switch change.Action {
case "invite", "remove", "promote", "demote":
if !uuidPattern.MatchString(change.Target) {
problem(w, 400, "invalid_member", "群成员 ID 无效")
return
}
change.Target = strings.ToLower(change.Target)
case "rename":
change.Name = strings.TrimSpace(change.Name)
if !groupName(change.Name) {
problem(w, 400, "invalid_group_name", "群名称须为 1 至 64 个字符")
return
}
case "accept", "decline", "leave", "disband":
default:
problem(w, 400, "invalid_group_action", "群操作无效")
return
}
if !a.limit(w, r, "group-change:"+id.User.ID, 60) {
return
}
if err := a.groups.Change(r.Context(), id.User.ID, group, change); err != nil {
groupError(w, err)
return
}
w.WriteHeader(204)
}