78 lines
1.4 KiB
Go
78 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"sync"
|
|
)
|
|
|
|
var Groups map[uint64]ChatGroup
|
|
var ConnectedClients map[uint64]map[*Client]struct{}
|
|
|
|
func InitCache() {
|
|
groups, err := GetAllChatGroups(context.Background())
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
for _, group := range groups {
|
|
Groups[group.Id] = group
|
|
}
|
|
}
|
|
|
|
func GetGroupById(groupId uint64) (*ChatGroup, error) {
|
|
group, ok := Groups[groupId]
|
|
if !ok {
|
|
return nil, errors.New("group not found")
|
|
}
|
|
return &group, nil
|
|
}
|
|
|
|
func AddOrUpdateGroupToCache(mu *sync.Mutex, group ChatGroup) {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
|
|
Groups[group.Id] = group
|
|
}
|
|
|
|
func RemoveGroupFromCache(mu *sync.Mutex, groupId uint64) {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
|
|
delete(Groups, groupId)
|
|
}
|
|
|
|
func AddOrUpdateConnectedClientToCache(mu *sync.Mutex, client *Client) {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
|
|
for _, groupId := range client.User.MemberGroupsId {
|
|
ConnectedClients[groupId][client] = struct{}{}
|
|
}
|
|
}
|
|
|
|
func RemoveConnectedClientFromCache(mu *sync.Mutex, client *Client) {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
|
|
for _, groupId := range client.User.MemberGroupsId {
|
|
delete(ConnectedClients[groupId], client)
|
|
}
|
|
}
|
|
|
|
func IsUserInGivenGroup(mu *sync.Mutex, userId uint64, groupId uint64) bool {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
|
|
group, ok := ConnectedClients[groupId]
|
|
if !ok {
|
|
return false
|
|
}
|
|
for client := range group {
|
|
if client.User.Id == userId {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|