gitea/services/websocket/websocket.go

73 lines
1.2 KiB
Go
Raw Normal View History

2024-02-11 13:26:53 +00:00
// Copyright 2024 The Gitea Authors. All rights reserved.
2024-02-03 10:34:26 +00:00
// SPDX-License-Identifier: MIT
package websocket
import (
2024-02-11 13:26:53 +00:00
"fmt"
2024-02-03 10:34:26 +00:00
"code.gitea.io/gitea/modules/context"
2024-02-11 13:26:53 +00:00
"code.gitea.io/gitea/modules/json"
2024-02-03 21:13:32 +00:00
2024-02-03 10:34:26 +00:00
"github.com/olahol/melody"
)
2024-02-11 13:26:53 +00:00
type websocketMessage struct {
Action string `json:"action"`
Data string `json:"data"`
}
type subscribeMessageData struct {
URL string `json:"url"`
}
2024-02-03 10:34:26 +00:00
func HandleConnect(s *melody.Session) {
ctx := context.GetWebContext(s.Request)
2024-02-11 13:11:51 +00:00
data := &sessionData{}
2024-02-03 10:34:26 +00:00
2024-02-11 13:11:51 +00:00
if ctx.IsSigned {
data.isSigned = true
data.userID = ctx.Doer.ID
2024-02-03 10:34:26 +00:00
}
2024-02-11 13:11:51 +00:00
s.Set("data", data)
2024-02-03 19:30:04 +00:00
// TODO: handle logouts
2024-02-03 10:34:26 +00:00
}
2024-02-11 13:26:53 +00:00
func HandleMessage(s *melody.Session, _msg []byte) {
2024-02-11 13:11:51 +00:00
data, err := getSessionData(s)
if err != nil {
return
}
2024-02-11 13:26:53 +00:00
msg := &websocketMessage{}
err = json.Unmarshal(_msg, msg)
if err != nil {
return
}
switch msg.Action {
case "subscribe":
err := handleSubscribeMessage(data, msg.Data)
if err != nil {
return
}
}
}
func handleSubscribeMessage(data *sessionData, _data any) error {
msgData, ok := _data.(*subscribeMessageData)
if !ok {
return fmt.Errorf("invalid message data")
}
data.onURL = msgData.URL
return nil
2024-02-03 10:34:26 +00:00
}
func HandleDisconnect(s *melody.Session) {
2024-02-03 15:41:20 +00:00
// TODO: Handle disconnect
2024-02-03 10:34:26 +00:00
}