package socketclients import ( "janex/admin-dashboard-backend/modules/cache" "janex/admin-dashboard-backend/modules/database" "janex/admin-dashboard-backend/modules/structs" "janex/admin-dashboard-backend/modules/utils" ) func BroadcastMessage(sendSocketMessage structs.SendSocketMessage) { for _, client := range cache.GetSocketClients() { client.SendMessage(sendSocketMessage) } } func UpdateConnectedUsers() { BroadcastMessage(structs.SendSocketMessage{ Cmd: utils.SentCmdUpdateConnectedUsers, Body: len(cache.GetSocketClients()), }) } func SendMessageToUser(userId string, ignoreUserSessionId string, sendSocketMessage structs.SendSocketMessage) { for _, client := range cache.GetSocketClients() { if client.UserId == userId && client.SessionId != ignoreUserSessionId { client.SendMessage(sendSocketMessage) } } } // This close all connections that are connected with one session id. // For example when a user has two browser tabs opened func CloseAllUserSessionConnections(sessionId string) { for _, client := range cache.GetSocketClients() { if client.SessionId == sessionId { client.SendSessionClosedMessage() } } } func GetUserSessions(userId string) []structs.UserSessionSocket { var userSessions []structs.UserSession database.DB.Where("user_id = ?", userId).Find(&userSessions) var userSessionsSocket []structs.UserSessionSocket socketClients := cache.GetSocketClients() for _, userSession := range userSessions { userSessionsSocket = append(userSessionsSocket, structs.UserSessionSocket{ IdForDeletion: userSession.IdForDeletion, UserAgent: userSession.UserAgent, ConnectionStatus: isUserSessionConnected(userSession.Id, socketClients), LastUsed: userSession.LastUsed, ExpiresAt: userSession.ExpiresAt, }) } return userSessionsSocket } func UpdateUserSessionsForUser(userId string, ignoreUserSessionId string) { GetUserSessions(userId) SendMessageToUser(userId, ignoreUserSessionId, structs.SendSocketMessage{ Cmd: utils.SendCmdUpdateUserSessions, Body: GetUserSessions(userId), }) } func isUserSessionConnected(userSessionId string, socketClients []*structs.SocketClient) uint8 { for _, socketClient := range socketClients { if socketClient.SessionId == userSessionId { return 1 } } return 0 }