add cache for groups and clients, http sending message remains to be add

This commit is contained in:
2026-03-15 14:15:24 +01:00
parent 76fbb8b970
commit c97b21a39e
7 changed files with 166 additions and 89 deletions
+17 -38
View File
@@ -2,6 +2,7 @@ package main
import (
"context"
"errors"
"log"
"net/http"
"sync"
@@ -18,8 +19,7 @@ type wsServer struct {
}
var (
clients []*Client
mu sync.Mutex
mu sync.Mutex
)
func (s *wsServer) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
@@ -33,9 +33,6 @@ func (s *wsServer) ServeHTTP(responseWriter http.ResponseWriter, request *http.R
defer conn.CloseNow()
client := &Client{conn: conn}
mu.Lock()
clients = append(clients, client)
mu.Unlock()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -61,37 +58,27 @@ func (s *wsServer) ServeHTTP(responseWriter http.ResponseWriter, request *http.R
s.OnClose(client, readErr)
}
mu.Lock()
for i, c := range clients {
if c == client {
clients[i] = clients[len(clients)-1]
clients = clients[:len(clients)-1]
break
}
}
mu.Unlock()
conn.Close(websocket.StatusNormalClosure, "done")
}
func sendAndCloseIfFails(conn *websocket.Conn, message map[string]any) {
func sendAndCloseIfFails(conn *websocket.Conn, message *map[string]any) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := wsjson.Write(ctx, conn, message); err != nil {
conn.Close(websocket.StatusGoingAway, "Write error")
}
}
func sendToGroup(id uint32, excludedUserId uint32, message *map[string]any) error {
if _, ok := Groups[id]; !ok {
return errors.New("Group Not Found")
}
func sendToAllExceptAndCloseIfFails(client *Client, message map[string]any) {
for _, other := range clients {
if other != client {
sendAndCloseIfFails(other.conn, message)
for client := range ConnectedClients[id] {
if client.User.Id != excludedUserId {
sendAndCloseIfFails(client.conn, message)
}
}
}
func sendToGroup() {
return nil
}
func handleUnauthenticatedMessage(client *Client, msg map[string]any) {
@@ -102,23 +89,15 @@ func handleUnauthenticatedMessage(client *Client, msg map[string]any) {
return
}
client.User = &user
sendAndCloseIfFails(client.conn, map[string]any{
m := map[string]any{
"authAs": user.Name,
})
}
sendAndCloseIfFails(client.conn, &m)
AddOrUpdateConnectedClientToCache(&mu, client)
log.Println("New User authenticated as: " + user.Name)
}
func handleAuthenticatedMessage(client *Client, msg map[string]any) {
message := msg["message"].(string)
if message == "" {
sendAndCloseIfFails(client.conn, map[string]any{
"error": "no message",
})
return
}
sendToAllExceptAndCloseIfFails(client, map[string]any{
"username": client.User.Name,
"message": message,
})
m := map[string]any{"temporary": "unauthorized"}
sendAndCloseIfFails(client.conn, &m)
}