Files

89 lines
2.6 KiB
Go

package httpapi
import (
"errors"
"net/http"
"strings"
"unicode"
"unicode/utf8"
"xhchat/server/internal/account"
"xhchat/server/internal/contacts"
"github.com/jackc/pgx/v5"
)
func (a *API) listContacts(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
result, err := a.contacts.List(r.Context(), identity.User.ID)
if err != nil {
unavailable(w, err)
return
}
respond(w, 200, result)
}
func (a *API) searchContact(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
username := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("username")))
if !usernamePattern.MatchString(username) {
problem(w, 400, "invalid_username", "请输入完整用户名")
return
}
if !a.limit(w, r, "contact-search:"+identity.User.ID, 60) {
return
}
result, err := a.contacts.Search(r.Context(), identity.User.ID, username)
if errors.Is(err, pgx.ErrNoRows) {
problem(w, 404, "contact_not_found", "找不到该用户")
return
}
if err != nil {
unavailable(w, err)
return
}
respond(w, 200, result)
}
func (a *API) changeContact(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
target := r.PathValue("id")
if !uuidPattern.MatchString(target) {
problem(w, 404, "contact_not_found", "找不到该用户")
return
}
var input struct {
Action string `json:"action"`
Alias string `json:"alias"`
Category string `json:"category"`
}
if !parse(w, r, &input) {
return
}
input.Alias = strings.TrimSpace(input.Alias)
input.Category = strings.TrimSpace(input.Category)
if utf8.RuneCountInString(input.Alias) > 64 || utf8.RuneCountInString(input.Category) > 32 ||
strings.ContainsFunc(input.Alias, unicode.IsControl) || strings.ContainsFunc(input.Category, unicode.IsControl) {
problem(w, 400, "invalid_contact_preferences", "请检查备注和分组")
return
}
if !a.limit(w, r, "contact-change:"+identity.User.ID, 60) {
return
}
err := a.contacts.Change(r.Context(), identity.User.ID, target, input.Action, input.Alias, input.Category)
if errors.Is(err, contacts.ErrUnavailable) {
problem(w, 409, "contact_action_unavailable", "当前无法执行此联系人操作,请刷新后重试")
return
}
if err != nil {
unavailable(w, err)
return
}
pipe := a.redis.Pipeline()
pipe.Publish(r.Context(), "xhchat:contacts:"+identity.User.ID, "changed")
switch input.Action {
case "preferences", "mute", "unmute", "pin", "unpin":
default:
pipe.Publish(r.Context(), "xhchat:contacts:"+strings.ToLower(target), "changed")
}
_, _ = pipe.Exec(r.Context())
w.WriteHeader(204)
}