155 lines
4.3 KiB
Go
155 lines
4.3 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"xhchat/server/internal/account"
|
|
|
|
"github.com/coder/websocket"
|
|
"github.com/coder/websocket/wsjson"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
func errorType(err error) string { return fmt.Sprintf("%T", err) }
|
|
|
|
func (a *API) ticket(w http.ResponseWriter, r *http.Request, token string, identity account.Identity) {
|
|
if !a.limit(w, r, "ticket:"+identity.Device.ID, 30) {
|
|
return
|
|
}
|
|
ticket := account.Secret()
|
|
digest, _ := account.SessionDigest(token)
|
|
if err := a.redis.Set(r.Context(), "xhchat:ticket:"+ticket, digest[:], 30*time.Second).Err(); err != nil {
|
|
unavailable(w, err)
|
|
return
|
|
}
|
|
respond(w, 200, map[string]string{"ticket": ticket})
|
|
}
|
|
|
|
func (a *API) realtime(w http.ResponseWriter, r *http.Request) {
|
|
if !a.origins[r.Header.Get("Origin")] {
|
|
problem(w, 403, "origin_denied", "此来源未获授权")
|
|
return
|
|
}
|
|
protocols := strings.Split(r.Header.Get("Sec-WebSocket-Protocol"), ",")
|
|
var ticket string
|
|
if len(protocols) == 2 && strings.TrimSpace(protocols[0]) == "xhchat.v1" {
|
|
ticket, _ = strings.CutPrefix(strings.TrimSpace(protocols[1]), "ticket.")
|
|
}
|
|
raw, err := account.Encoding.DecodeString(ticket)
|
|
if err != nil || len(raw) != 32 {
|
|
problem(w, 401, "invalid_ticket", "连接凭据无效")
|
|
return
|
|
}
|
|
digest, err := a.redis.GetDel(r.Context(), "xhchat:ticket:"+ticket).Bytes()
|
|
if errors.Is(err, redis.Nil) {
|
|
problem(w, 401, "invalid_ticket", "连接凭据已失效")
|
|
return
|
|
}
|
|
if err != nil {
|
|
unavailable(w, err)
|
|
return
|
|
}
|
|
identity, err := a.accounts.SessionByDigest(r.Context(), digest)
|
|
if errors.Is(err, account.ErrCredentials) {
|
|
problem(w, 401, "unauthorized", "登录会话已失效")
|
|
return
|
|
}
|
|
if err != nil {
|
|
unavailable(w, err)
|
|
return
|
|
}
|
|
inboxChannel := "xhchat:inbox:" + identity.Device.ID
|
|
groupsChannel := "xhchat:groups:" + identity.User.ID
|
|
subscription := a.redis.Subscribe(r.Context(), "xhchat:contacts:"+identity.User.ID, inboxChannel, groupsChannel)
|
|
defer subscription.Close()
|
|
for range 3 {
|
|
if _, err = subscription.Receive(r.Context()); err != nil {
|
|
unavailable(w, err)
|
|
return
|
|
}
|
|
}
|
|
changes := subscription.Channel()
|
|
// The exact Origin was checked before consuming the ticket.
|
|
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{
|
|
Subprotocols: []string{"xhchat.v1"}, InsecureSkipVerify: true,
|
|
})
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer conn.CloseNow()
|
|
conn.SetReadLimit(1024)
|
|
ctx := conn.CloseRead(r.Context())
|
|
writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
err = wsjson.Write(writeCtx, conn, map[string]string{"type": "ready", "deviceId": identity.Device.ID})
|
|
cancel()
|
|
if err != nil {
|
|
return
|
|
}
|
|
ticker := time.NewTicker(5 * time.Second)
|
|
defer ticker.Stop()
|
|
heartbeat := time.NewTicker(30 * time.Second)
|
|
defer heartbeat.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case change, ok := <-changes:
|
|
if !ok {
|
|
return
|
|
}
|
|
writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
event := map[string]any{"type": "contacts_changed"}
|
|
switch change.Channel {
|
|
case groupsChannel:
|
|
event["type"] = "group_list_changed"
|
|
case inboxChannel:
|
|
event["type"] = "inbox_changed"
|
|
kind, group, _ := strings.Cut(change.Payload, ":")
|
|
if (kind == "group" || kind == "group-notify") && uuidPattern.MatchString(group) {
|
|
event["type"] = "group_changed"
|
|
event["groupId"] = group
|
|
if kind == "group-notify" {
|
|
event["notify"] = true
|
|
}
|
|
}
|
|
}
|
|
err := wsjson.Write(writeCtx, conn, event)
|
|
cancel()
|
|
if err != nil {
|
|
return
|
|
}
|
|
case <-heartbeat.C:
|
|
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
err := conn.Ping(pingCtx)
|
|
cancel()
|
|
if err != nil {
|
|
return
|
|
}
|
|
updateCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
|
err = a.accounts.TouchDevice(updateCtx, identity.Device.ID)
|
|
cancel()
|
|
if err != nil {
|
|
_ = conn.Close(websocket.StatusInternalError, "dependency unavailable")
|
|
return
|
|
}
|
|
case <-ticker.C:
|
|
checkCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
|
_, err := a.accounts.SessionByDigest(checkCtx, digest)
|
|
cancel()
|
|
if errors.Is(err, account.ErrCredentials) {
|
|
_ = conn.Close(websocket.StatusPolicyViolation, "session ended")
|
|
return
|
|
}
|
|
if err != nil {
|
|
_ = conn.Close(websocket.StatusInternalError, "dependency unavailable")
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}
|