2020-11-26 06:36:33 +13:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/gorilla/websocket"
|
2021-08-30 04:23:58 +12:00
|
|
|
"github.com/rs/zerolog"
|
2020-11-26 06:36:33 +13:00
|
|
|
|
|
|
|
"demodesk/neko/internal/types"
|
2021-03-26 02:08:26 +13:00
|
|
|
"demodesk/neko/internal/types/event"
|
|
|
|
"demodesk/neko/internal/types/message"
|
2020-11-26 06:36:33 +13:00
|
|
|
)
|
|
|
|
|
|
|
|
type WebSocketPeerCtx struct {
|
2021-02-15 05:11:21 +13:00
|
|
|
mu sync.Mutex
|
2021-08-30 04:23:58 +12:00
|
|
|
logger zerolog.Logger
|
2020-11-26 06:36:33 +13:00
|
|
|
session types.Session
|
|
|
|
connection *websocket.Conn
|
|
|
|
}
|
|
|
|
|
2021-02-15 05:11:21 +13:00
|
|
|
func (peer *WebSocketPeerCtx) Send(v interface{}) error {
|
|
|
|
peer.mu.Lock()
|
|
|
|
defer peer.mu.Unlock()
|
2020-11-26 06:36:33 +13:00
|
|
|
|
2021-02-15 05:11:21 +13:00
|
|
|
if peer.connection == nil {
|
2020-11-26 06:36:33 +13:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
raw, err := json.Marshal(v)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-08-30 04:23:58 +12:00
|
|
|
peer.logger.Debug().
|
2021-02-15 05:11:21 +13:00
|
|
|
Str("address", peer.connection.RemoteAddr().String()).
|
2020-11-26 06:36:33 +13:00
|
|
|
Str("raw", string(raw)).
|
|
|
|
Msg("sending message to client")
|
|
|
|
|
2021-02-15 05:11:21 +13:00
|
|
|
return peer.connection.WriteMessage(websocket.TextMessage, raw)
|
2020-11-26 06:36:33 +13:00
|
|
|
}
|
|
|
|
|
2021-08-30 05:17:10 +12:00
|
|
|
func (peer *WebSocketPeerCtx) Destroy() {
|
|
|
|
peer.mu.Lock()
|
|
|
|
defer peer.mu.Unlock()
|
|
|
|
|
2021-02-15 05:11:21 +13:00
|
|
|
if peer.connection == nil {
|
2021-08-30 05:17:10 +12:00
|
|
|
return
|
2020-11-26 06:36:33 +13:00
|
|
|
}
|
|
|
|
|
2021-08-30 05:17:10 +12:00
|
|
|
if err := peer.Send(
|
2021-03-26 02:08:26 +13:00
|
|
|
message.SystemDisconnect{
|
|
|
|
Event: event.SYSTEM_DISCONNECT,
|
|
|
|
Message: "connection destroyed",
|
2021-08-30 05:17:10 +12:00
|
|
|
}); err != nil {
|
|
|
|
peer.logger.Warn().Err(err).Msg("failed to send disconnect event")
|
|
|
|
}
|
2021-03-26 02:08:26 +13:00
|
|
|
|
2021-08-30 05:17:10 +12:00
|
|
|
if err := peer.connection.Close(); err != nil {
|
|
|
|
peer.logger.Warn().Err(err).Msg("peer connection destroyed with an error")
|
|
|
|
} else {
|
|
|
|
peer.logger.Info().Msg("peer connection destroyed")
|
|
|
|
}
|
2021-03-26 02:08:26 +13:00
|
|
|
|
2021-08-30 05:17:10 +12:00
|
|
|
peer.connection = nil
|
2020-11-26 06:36:33 +13:00
|
|
|
}
|