package controller import ( socketio "github.com/googollee/go-socket.io" "github.com/hyperzlib/isekai-remote-playback/context" "github.com/hyperzlib/isekai-remote-playback/store" "github.com/hyperzlib/isekai-remote-playback/utils" "log" "time" ) type ServerSocketContext struct { IsAuth bool } type ServerSocketController struct { SocketController appsConfig utils.ApplicationsConfig } func NewServerSocketController(basePath string, ctx *context.ServerContext) (*ServerSocketController, error) { appConfig, err := utils.GetApplicationsConfig() if err != nil { panic("Cannot load applications config: " + err.Error()) } instance := &ServerSocketController{ SocketController: SocketController{ basePath: basePath, sockets: ctx.Sockets, events: ctx.EventSource, context: ctx, storeModel: store.NewStoreModel(), }, appsConfig: appConfig, } err = instance.Initialize() if err != nil { return nil, err } return instance, nil } func (c *ServerSocketController) Initialize() error { server := c.sockets server.OnConnect(c.basePath, func(s socketio.Conn) error { s.SetContext(&ServerSocketContext{}) log.Println("Server connected: " + s.RemoteAddr().String()) time.AfterFunc(5*time.Second, func() { // 关闭5秒内为登录成功的链接 ctx := GetContext[ServerSocketContext](s) if !ctx.IsAuth { log.Println("Server auth timeout: " + s.RemoteAddr().String()) s.Emit("error", "ERR::AUTH_TIMEOUT") time.AfterFunc(1000, func() { s.Close() }) } }) return nil }) server.OnEvent(c.basePath, "auth:login", c.AppLogin) server.OnEvent(c.basePath, "user:player:bind", c.AppLogin) server.OnError(c.basePath, func(s socketio.Conn, e error) { log.Println("meet error:", e) }) return nil } func (c *ServerSocketController) AppLogin(s socketio.Conn, appId string, token string) { if appId == "" || token == "" { s.Emit("error", "ERR::AUTH_PARAM_INVALID") s.Close() return } appConfig, ok := c.appsConfig[appId] if !ok { s.Emit("error", "ERR::AUTH_APP_NOT_EXISTS") s.Close() return } if token != appConfig.Token { s.Emit("error", "ERR::AUTH_APP_TOKEN_INVALID") s.Close() return } // 设置登录状态 ctx := GetContext[ServerSocketContext](s) ctx.IsAuth = true s.Emit("auth:update", true) log.Println("Server auth success: " + s.RemoteAddr().String()) } func (c *ServerSocketController) UserBindPlayer(s socketio.Conn, user string, code string) { ctx := GetContext[ServerSocketContext](s) if !ctx.IsAuth { return } }