neko/internal/websocket/manager.go

283 lines
7.1 KiB
Go
Raw Normal View History

2020-11-02 04:09:48 +13:00
package websocket
import (
"net/http"
"time"
"github.com/gorilla/websocket"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"demodesk/neko/internal/websocket/handler"
2021-01-10 11:01:39 +13:00
"demodesk/neko/internal/types"
2020-11-02 04:09:48 +13:00
"demodesk/neko/internal/types/event"
"demodesk/neko/internal/types/message"
2021-01-10 11:01:39 +13:00
"demodesk/neko/internal/utils"
2020-11-02 04:09:48 +13:00
)
func New(
sessions types.SessionManager,
desktop types.DesktopManager,
capture types.CaptureManager,
webrtc types.WebRTCManager,
) *WebSocketManagerCtx {
logger := log.With().Str("module", "websocket").Logger()
return &WebSocketManagerCtx{
logger: logger,
sessions: sessions,
desktop: desktop,
upgrader: websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
},
2020-12-13 05:40:10 +13:00
handler: handler.New(sessions, desktop, capture, webrtc),
2020-12-13 06:37:19 +13:00
handlers: []types.HandlerFunction{},
2020-11-02 04:09:48 +13:00
}
}
// Send pings to peer with this period. Must be less than pongWait.
const pingPeriod = 60 * time.Second
type WebSocketManagerCtx struct {
logger zerolog.Logger
upgrader websocket.Upgrader
sessions types.SessionManager
desktop types.DesktopManager
handler *handler.MessageHandlerCtx
2020-12-13 06:37:19 +13:00
handlers []types.HandlerFunction
2020-11-02 04:09:48 +13:00
}
func (ws *WebSocketManagerCtx) Start() {
2020-12-03 06:59:54 +13:00
ws.sessions.OnCreated(func(session types.Session) {
if err := ws.handler.SessionCreated(session); err != nil {
ws.logger.Warn().Str("id", session.ID()).Err(err).Msg("session created with an error")
} else {
ws.logger.Debug().Str("id", session.ID()).Msg("session created")
}
})
ws.sessions.OnDeleted(func(session types.Session) {
if err := ws.handler.SessionDeleted(session); err != nil {
ws.logger.Warn().Str("id", session.ID()).Err(err).Msg("session deleted with an error")
} else {
ws.logger.Debug().Str("id", session.ID()).Msg("session deleted")
}
})
2020-11-02 04:09:48 +13:00
ws.sessions.OnConnected(func(session types.Session) {
if err := ws.handler.SessionConnected(session); err != nil {
2020-11-02 08:53:25 +13:00
ws.logger.Warn().Str("id", session.ID()).Err(err).Msg("session connected with an error")
2020-11-02 04:09:48 +13:00
} else {
ws.logger.Debug().Str("id", session.ID()).Msg("session connected")
}
})
2020-11-02 08:53:25 +13:00
ws.sessions.OnDisconnected(func(session types.Session) {
if err := ws.handler.SessionDisconnected(session); err != nil {
ws.logger.Warn().Str("id", session.ID()).Err(err).Msg("session disconnected with an error")
2020-11-02 04:09:48 +13:00
} else {
2020-11-02 08:53:25 +13:00
ws.logger.Debug().Str("id", session.ID()).Msg("session disconnected")
2020-11-02 04:09:48 +13:00
}
})
2020-12-04 04:10:52 +13:00
ws.sessions.OnProfileChanged(func(session types.Session) {
if err := ws.handler.SessionProfileChanged(session); err != nil {
ws.logger.Warn().Str("id", session.ID()).Err(err).Msg("session profile changed with an error")
2020-12-03 06:59:54 +13:00
} else {
2020-12-04 04:10:52 +13:00
ws.logger.Debug().Str("id", session.ID()).Msg("session profile changed")
2020-12-03 06:59:54 +13:00
}
})
2020-12-04 04:10:52 +13:00
ws.sessions.OnStateChanged(func(session types.Session) {
if err := ws.handler.SessionStateChanged(session); err != nil {
ws.logger.Warn().Str("id", session.ID()).Err(err).Msg("session state changed with an error")
2020-12-03 06:59:54 +13:00
} else {
2020-12-04 04:10:52 +13:00
ws.logger.Debug().Str("id", session.ID()).Msg("session state changed")
2020-12-03 06:59:54 +13:00
}
})
2021-01-11 03:58:17 +13:00
// TOOD: Throttle events.
ws.desktop.OnCursorChanged(func(serial uint64) {
cur := ws.desktop.GetCursorImage()
uri, err := utils.GetCursorImageURI(cur)
if err != nil {
ws.logger.Warn().Err(err).Msg("could create cursor image")
return
}
ws.sessions.Broadcast(message.CursorImage{
Event: event.CURSOR_IMAGE,
Uri: uri,
Width: cur.Width,
Height: cur.Height,
X: cur.Xhot,
Y: cur.Yhot,
}, nil)
})
2021-01-12 03:30:53 +13:00
ws.desktop.OnClipboardUpdated(func() {
session := ws.sessions.GetHost()
if session == nil || !session.CanAccessClipboard() {
return
}
text := ws.desktop.ReadClipboard()
err := session.Send(message.ClipboardData{
Event: event.CLIPBOARD_UPDATED,
Text: text,
})
if err != nil {
ws.logger.Warn().Err(err).Msg("could not sync clipboard")
2020-11-02 04:09:48 +13:00
}
2021-01-12 03:30:53 +13:00
})
2020-11-02 04:09:48 +13:00
}
func (ws *WebSocketManagerCtx) Shutdown() error {
return nil
}
2020-12-13 06:37:19 +13:00
func (ws *WebSocketManagerCtx) AddHandler(handler types.HandlerFunction) {
2020-12-13 05:40:10 +13:00
ws.handlers = append(ws.handlers, handler)
}
2020-11-02 04:09:48 +13:00
func (ws *WebSocketManagerCtx) Upgrade(w http.ResponseWriter, r *http.Request) error {
ws.logger.Debug().Msg("attempting to upgrade connection")
connection, err := ws.upgrader.Upgrade(w, r, nil)
if err != nil {
ws.logger.Error().Err(err).Msg("failed to upgrade connection")
return err
}
2020-11-02 08:23:09 +13:00
session, err := ws.sessions.Authenticate(r)
2020-11-02 04:09:48 +13:00
if err != nil {
ws.logger.Warn().Err(err).Msg("authentication failed")
2020-12-07 06:49:08 +13:00
// TODO: Refactor, return error code.
2020-12-02 07:44:23 +13:00
if err = connection.WriteJSON(
message.SystemDisconnect{
Event: event.SYSTEM_DISCONNECT,
2020-12-07 06:49:08 +13:00
Message: err.Error(),
}); err != nil {
ws.logger.Error().Err(err).Msg("failed to send disconnect")
}
return connection.Close()
}
if !session.CanConnect() {
// TODO: Refactor, return error code.
if err = connection.WriteJSON(
message.SystemDisconnect{
Event: event.SYSTEM_DISCONNECT,
Message: "connection disabled",
2020-12-02 07:44:23 +13:00
}); err != nil {
2020-11-02 04:09:48 +13:00
ws.logger.Error().Err(err).Msg("failed to send disconnect")
}
return connection.Close()
}
2020-12-03 04:49:51 +13:00
if session.IsConnected() {
2020-12-07 06:49:08 +13:00
// TODO: Refactor, return error code.
if err = connection.WriteJSON(
message.SystemDisconnect{
Event: event.SYSTEM_DISCONNECT,
Message: "already connected",
}); err != nil {
ws.logger.Error().Err(err).Msg("failed to send disconnect")
}
return connection.Close()
}
2020-11-26 10:16:56 +13:00
session.SetWebSocketPeer(&WebSocketPeerCtx{
2020-11-15 04:03:12 +13:00
session: session,
2020-11-02 04:09:48 +13:00
ws: ws,
connection: connection,
2020-11-26 10:16:56 +13:00
})
2020-11-02 04:09:48 +13:00
ws.logger.
Debug().
2020-11-02 08:23:09 +13:00
Str("session", session.ID()).
2020-11-02 04:09:48 +13:00
Str("address", connection.RemoteAddr().String()).
2020-11-15 04:03:39 +13:00
Msg("connection started")
2020-11-02 04:09:48 +13:00
2020-11-26 08:26:11 +13:00
session.SetWebSocketConnected(true)
2020-11-02 04:09:48 +13:00
defer func() {
ws.logger.
Debug().
2020-11-02 08:23:09 +13:00
Str("session", session.ID()).
2020-11-02 04:09:48 +13:00
Str("address", connection.RemoteAddr().String()).
2020-11-15 04:03:39 +13:00
Msg("connection ended")
2020-11-26 08:26:11 +13:00
session.SetWebSocketConnected(false)
2020-11-02 04:09:48 +13:00
}()
2020-11-02 08:53:25 +13:00
ws.handle(connection, session)
2020-11-02 04:09:48 +13:00
return nil
}
2020-11-02 08:53:25 +13:00
func (ws *WebSocketManagerCtx) handle(connection *websocket.Conn, session types.Session) {
2020-11-02 04:09:48 +13:00
bytes := make(chan []byte)
cancel := make(chan struct{})
ticker := time.NewTicker(pingPeriod)
2020-11-26 08:26:11 +13:00
defer func() {
ticker.Stop()
}()
2020-11-02 04:09:48 +13:00
2020-11-26 08:26:11 +13:00
go func() {
2020-11-02 04:09:48 +13:00
for {
_, raw, err := connection.ReadMessage()
2020-11-02 04:37:00 +13:00
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
ws.logger.Warn().Err(err).Msg("read message error")
} else {
ws.logger.Debug().Err(err).Msg("read message error")
}
close(cancel)
break
2020-11-02 04:09:48 +13:00
}
2020-11-02 04:37:00 +13:00
bytes <- raw
2020-11-02 04:09:48 +13:00
}
}()
for {
select {
case raw := <-bytes:
ws.logger.Debug().
2020-11-02 08:53:25 +13:00
Str("session", session.ID()).
2020-11-02 04:09:48 +13:00
Str("address", connection.RemoteAddr().String()).
Str("raw", string(raw)).
Msg("received message from client")
2020-12-13 05:40:10 +13:00
handled := ws.handler.Message(session, raw)
for _, handler := range ws.handlers {
if handled {
break
}
handled = handler(session, raw)
}
if !handled {
ws.logger.Warn().Msg("unhandled message")
2020-11-02 04:09:48 +13:00
}
case <-cancel:
return
case <-ticker.C:
if err := connection.WriteMessage(websocket.PingMessage, nil); err != nil {
ws.logger.Error().Err(err).Msg("ping message has failed")
return
}
}
}
}