go_dreamfactory/comm/usersession.go
2022-06-07 09:59:48 +08:00

94 lines
2.9 KiB
Go

package comm
import (
"context"
"fmt"
"go_dreamfactory/pb"
"github.com/liwei1dao/lego/base"
"github.com/liwei1dao/lego/sys/log"
"google.golang.org/protobuf/proto"
)
func NewUserSession(service base.IRPCXService, ip, sessionId, gatewayServiceId string, uid string) IUserSession {
return &UserSession{
IP: ip,
SessionId: sessionId,
GatewayServiceId: gatewayServiceId,
UserId: uid,
service: service,
}
}
type UserSession struct {
IP string
SessionId string
GatewayServiceId string //用户所在网关服务
UserId string
service base.IRPCXService
}
func (this *UserSession) GetSessionId() string {
return this.SessionId
}
func (this *UserSession) GetUserId() string {
return this.UserId
}
func (this *UserSession) GetIP() string {
return this.IP
}
func (this *UserSession) GetGatewayServiceId() string {
return this.GatewayServiceId
}
func (this *UserSession) Build(uid string) (err error) {
reply := &pb.RPCMessageReply{}
if err := this.service.RpcCallById(this.GatewayServiceId, string(Rpc_GatewayAgentBuild), context.Background(), &pb.AgentBuildReq{
UserSessionId: this.SessionId,
UserId: uid,
}, reply); err != nil {
log.Errorf("UserSession:%s UserId:%d Build:%s err:%v", this.SessionId, this.UserId, err)
}
return
}
func (this *UserSession) UnBuild(ServiceMethod string, msg proto.Message) (err error) {
reply := &pb.RPCMessageReply{}
if err := this.service.RpcCallById(this.GatewayServiceId, string(Rpc_GatewayAgentUnBuild), context.Background(), &pb.AgentUnBuildReq{
UserSessionId: this.SessionId,
}, reply); err != nil {
log.Errorf("UserSession:%s UserId:%d UnBuild err:%v", this.SessionId, this.UserId, err)
}
return
}
func (this *UserSession) SendMsg(mainType, subType string, code pb.ErrorCode, msg proto.Message) (err error) {
reply := &pb.RPCMessageReply{}
data, _ := proto.Marshal(msg)
log.Debugf("SendMsg Data: %v", msg)
if err := this.service.RpcCallById(this.GatewayServiceId, string(Rpc_GatewayAgentSendMsg), context.Background(), &pb.AgentSendMessageReq{
UserSessionId: this.SessionId,
MainType: mainType,
SubType: subType,
Code: code,
Data: data,
}, reply); err != nil {
log.Errorf("UserSession:%s UserId:%d SendMsg:%s err:%v", this.SessionId, this.UserId, mainType, err)
}
return
}
func (this *UserSession) Close() (err error) {
reply := &pb.RPCMessageReply{}
if err := this.service.RpcCallById(this.GatewayServiceId, string(Rpc_GatewayAgentSendMsg), context.Background(), &pb.AgentCloseeReq{
UserSessionId: this.SessionId,
}, reply); err != nil {
log.Errorf("UserSession:%s UserId:%d Close:%s err:%v", this.SessionId, this.UserId, err)
}
return
}
func (this *UserSession) ToString() string {
return fmt.Sprintf("SessionId:%s UserId:%d GatewayServiceId:%s", this.SessionId, this.UserId, this.GatewayServiceId)
}