2020-02-12 16:39:57 +00:00
|
|
|
package core
|
2020-02-10 09:23:10 +00:00
|
|
|
|
|
|
|
import (
|
2021-03-30 19:40:02 +00:00
|
|
|
"github.com/cadmium-im/zirconium-go/core/models"
|
2021-04-06 13:55:41 +00:00
|
|
|
"github.com/cadmium-im/zirconium-go/core/utils"
|
|
|
|
"github.com/fatih/structs"
|
2020-02-10 09:23:10 +00:00
|
|
|
"github.com/google/logger"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Router struct {
|
2021-04-06 13:55:41 +00:00
|
|
|
appContext *AppContext
|
|
|
|
handlers map[string][]C2SMessageHandler
|
2020-02-10 09:23:10 +00:00
|
|
|
}
|
|
|
|
|
2021-03-30 19:40:02 +00:00
|
|
|
type C2SMessageHandler interface {
|
|
|
|
HandleMessage(s *Session, message models.BaseMessage)
|
|
|
|
IsAuthorizationRequired() bool
|
|
|
|
HandlingType() string
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewRouter(ctx *AppContext) (*Router, error) {
|
2020-02-10 09:23:10 +00:00
|
|
|
r := &Router{
|
2021-03-30 19:40:02 +00:00
|
|
|
appContext: ctx,
|
|
|
|
handlers: map[string][]C2SMessageHandler{},
|
2020-02-10 09:23:10 +00:00
|
|
|
}
|
|
|
|
return r, nil
|
|
|
|
}
|
|
|
|
|
2021-03-30 19:40:02 +00:00
|
|
|
func (r *Router) RouteMessage(origin *Session, message models.BaseMessage) {
|
|
|
|
handlers := r.handlers[message.MessageType]
|
2020-02-10 09:23:10 +00:00
|
|
|
if handlers != nil {
|
|
|
|
for _, v := range handlers {
|
2021-03-30 19:40:02 +00:00
|
|
|
if v.IsAuthorizationRequired() {
|
2021-04-06 13:55:41 +00:00
|
|
|
if origin.Claims == nil {
|
2020-02-10 09:23:10 +00:00
|
|
|
logger.Warningf("Connection %s isn't authorized", origin.connID)
|
|
|
|
|
2021-04-06 13:55:41 +00:00
|
|
|
msg := utils.PrepareMessageUnauthorized(message, r.appContext.cfg.ServerDomains[0]) // fixme: domain
|
2021-03-30 19:40:02 +00:00
|
|
|
_ = origin.Send(msg)
|
2020-02-10 09:23:10 +00:00
|
|
|
}
|
|
|
|
}
|
2021-03-30 19:40:02 +00:00
|
|
|
go v.HandleMessage(origin, message)
|
2020-02-10 09:23:10 +00:00
|
|
|
}
|
|
|
|
} else {
|
2020-02-10 10:56:13 +00:00
|
|
|
protocolError := models.ProtocolError{
|
|
|
|
ErrCode: "unhandled",
|
|
|
|
ErrText: "Server doesn't implement message type " + message.MessageType,
|
|
|
|
ErrPayload: make(map[string]interface{}),
|
|
|
|
}
|
2021-04-06 13:55:41 +00:00
|
|
|
errMsg := models.NewBaseMessage(message.ID, message.MessageType, r.appContext.cfg.ServerID, []string{message.From}, false, structs.Map(protocolError))
|
2020-02-10 09:23:10 +00:00
|
|
|
logger.Infof("Drop message with type %s because server hasn't proper handlers", message.MessageType)
|
2021-03-30 19:40:02 +00:00
|
|
|
_ = origin.Send(errMsg)
|
2020-02-10 09:23:10 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-30 19:40:02 +00:00
|
|
|
func (r *Router) RegisterC2SHandler(c C2SMessageHandler) {
|
|
|
|
r.handlers[c.HandlingType()] = append(r.handlers[c.HandlingType()], c)
|
2020-02-10 09:23:10 +00:00
|
|
|
}
|