gitea/services/websocket/websocket.go

82 lines
1.5 KiB
Go
Raw Normal View History

2024-02-11 14:26:53 +01:00
// Copyright 2024 The Gitea Authors. All rights reserved.
2024-02-03 11:34:26 +01:00
// SPDX-License-Identifier: MIT
package websocket
import (
"code.gitea.io/gitea/modules/context"
2024-02-11 14:26:53 +01:00
"code.gitea.io/gitea/modules/json"
2024-02-16 17:19:50 +01:00
notify_service "code.gitea.io/gitea/services/notify"
2024-02-16 18:09:00 +01:00
"github.com/mitchellh/mapstructure"
"github.com/olahol/melody"
2024-02-03 11:34:26 +01:00
)
2024-02-16 17:19:50 +01:00
var m *melody.Melody
2024-02-11 14:26:53 +01:00
type websocketMessage struct {
Action string `json:"action"`
2024-02-16 17:50:49 +01:00
Data any `json:"data"`
2024-02-11 14:26:53 +01:00
}
type subscribeMessageData struct {
URL string `json:"url"`
}
2024-02-16 17:19:50 +01:00
func Init() *melody.Melody {
m = melody.New()
m.HandleConnect(handleConnect)
m.HandleMessage(handleMessage)
m.HandleDisconnect(handleDisconnect)
notify_service.RegisterNotifier(newNotifier(m))
return m
}
func handleConnect(s *melody.Session) {
2024-02-03 11:34:26 +01:00
ctx := context.GetWebContext(s.Request)
2024-02-11 14:11:51 +01:00
data := &sessionData{}
if ctx.IsSigned {
2024-02-16 17:19:50 +01:00
data.user = ctx.Doer
2024-02-03 11:34:26 +01:00
}
2024-02-11 14:11:51 +01:00
s.Set("data", data)
2024-02-03 20:30:04 +01:00
// TODO: handle logouts
2024-02-03 11:34:26 +01:00
}
2024-02-16 17:19:50 +01:00
func handleMessage(s *melody.Session, _msg []byte) {
2024-02-11 14:11:51 +01:00
data, err := getSessionData(s)
if err != nil {
return
}
2024-02-11 14:26:53 +01: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 {
2024-02-16 17:50:49 +01:00
msgData := &subscribeMessageData{}
err := mapstructure.Decode(_data, &msgData)
if err != nil {
return err
2024-02-11 14:26:53 +01:00
}
data.onURL = msgData.URL
return nil
2024-02-03 11:34:26 +01:00
}
2024-02-16 17:19:50 +01:00
func handleDisconnect(s *melody.Session) {
2024-02-03 11:34:26 +01:00
}