Merge branch 'develop' of gitee.com:fusenpack/fusenapi into develop

This commit is contained in:
momo 2023-08-25 10:08:53 +08:00
commit 4fb4def7d8
14 changed files with 222 additions and 341 deletions

View File

@ -20,8 +20,6 @@ const (
WEBSOCKET_RENDER_IMAGE_ERR Websocket = "WEBSOCKET_RENDER_IMAGE_ERR"
//传入数据格式错误
WEBSOCKET_ERR_DATA_FORMAT Websocket = "WEBSOCKET_ERR_DATA_FORMAT"
//登录回调通知
WEBSOCKET_LOGIN_NOTIFY Websocket = "WEBSOCKET_LOGIN_NOTIFY"
//注册帐号回调通知
WEBSOCKET_REGISTER_NOTIFY Websocket = "WEBSOCKET_REGISTER_NOTIFY"
//通用回调通知
WEBSOCKET_COMMON_NOTIFY Websocket = "WEBSOCKET_COMMON_NOTIFY"
)

View File

@ -11,22 +11,22 @@ import (
"fusenapi/server/websocket/internal/types"
)
func LoginNotifyHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
func CommonNotifyHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.LoginNotifyReq
var req types.CommonNotifyReq
userinfo, err := basic.RequestParse(w, r, svcCtx, &req)
if err != nil {
return
}
// 创建一个业务逻辑层实例
l := logic.NewLoginNotifyLogic(r.Context(), svcCtx)
l := logic.NewCommonNotifyLogic(r.Context(), svcCtx)
rl := reflect.ValueOf(l)
basic.BeforeLogic(w, r, rl)
resp := l.LoginNotify(&req, userinfo)
resp := l.CommonNotify(&req, userinfo)
if !basic.AfterLogic(w, r, rl, resp) {
basic.NormalAfterLogic(w, r, resp)

View File

@ -1,35 +0,0 @@
package handler
import (
"net/http"
"reflect"
"fusenapi/utils/basic"
"fusenapi/server/websocket/internal/logic"
"fusenapi/server/websocket/internal/svc"
"fusenapi/server/websocket/internal/types"
)
func RegisterAccountNotifyHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.RegisterAccountNotifyReq
userinfo, err := basic.RequestParse(w, r, svcCtx, &req)
if err != nil {
return
}
// 创建一个业务逻辑层实例
l := logic.NewRegisterAccountNotifyLogic(r.Context(), svcCtx)
rl := reflect.ValueOf(l)
basic.BeforeLogic(w, r, rl)
resp := l.RegisterAccountNotify(&req, userinfo)
if !basic.AfterLogic(w, r, rl, resp) {
basic.NormalAfterLogic(w, r, resp)
}
}
}

View File

@ -24,13 +24,8 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
},
{
Method: http.MethodPost,
Path: "/api/websocket/register_account_notify",
Handler: RegisterAccountNotifyHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/api/websocket/login_notify",
Handler: LoginNotifyHandler(serverCtx),
Path: "/api/websocket/common_notify",
Handler: CommonNotifyHandler(serverCtx),
},
},
)

View File

@ -0,0 +1,56 @@
package logic
import (
"context"
"fusenapi/constants"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"fusenapi/server/websocket/internal/svc"
"fusenapi/server/websocket/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type CommonNotifyLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewCommonNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CommonNotifyLogic {
return &CommonNotifyLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
// 处理进入前逻辑w,r
// func (l *CommonNotifyLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }
func (l *CommonNotifyLogic) CommonNotify(req *types.CommonNotifyReq, userinfo *auth.UserInfo) (resp *basic.Response) {
//websocket连接id不能为空
if req.Wid == "" {
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "websocket connect id is empty")
}
//查询websocket连接
value, ok := mapConnPool.Load(req.Wid)
if !ok {
return resp.SetStatusWithMessage(basic.CodeOK, "success,but connection is not found")
}
//断言连接
ws, ok := value.(wsConnectItem)
if !ok {
logx.Error("渲染回调断言websocket连接失败")
return resp.SetStatusWithMessage(basic.CodeServiceErr, "断言连接错误")
}
ws.sendToOutChan(ws.respondDataFormat(constants.WEBSOCKET_COMMON_NOTIFY, req.Data))
return resp.SetStatusWithMessage(basic.CodeOK, "success")
}
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *CommonNotifyLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)
// }

View File

@ -204,6 +204,8 @@ func (l *DataTransferLogic) checkAuth(r *http.Request) (isAuth bool, userInfo *a
logx.Error(err)
return false, nil
}
userInfo.UserId = 39
userInfo.GuestId = 0
return true, userInfo
}
//白板用户
@ -366,8 +368,8 @@ func (w *wsConnectItem) respondDataFormat(msgType constants.Websocket, data inte
func (w *wsConnectItem) dealwithReciveData(data []byte) {
var parseInfo websocket_data.DataTransferData
if err := json.Unmarshal(data, &parseInfo); err != nil {
w.incomeDataFormatErrResponse("invalid format of income message:" + string(data))
logx.Error("invalid format of websocket message:", err)
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_ERR_DATA_FORMAT, "invalid format of websocket message:"+string(data)))
return
}
d, _ := json.Marshal(parseInfo.D)

View File

@ -1,83 +0,0 @@
package logic
//登录回调
import (
"encoding/json"
"fusenapi/constants"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"fusenapi/utils/encryption_decryption"
"fusenapi/utils/websocket_data"
"time"
"context"
"fusenapi/server/websocket/internal/svc"
"fusenapi/server/websocket/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type LoginNotifyLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewLoginNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginNotifyLogic {
return &LoginNotifyLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
// 处理进入前逻辑w,r
// func (l *LoginNotifyLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }
func (l *LoginNotifyLogic) LoginNotify(req *types.LoginNotifyReq, userinfo *auth.UserInfo) (resp *basic.Response) {
if req.Data == "" {
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "data is empty")
}
//解密数据
data, err := encryption_decryption.CBCDecrypt(req.Data)
if err != nil {
logx.Error("解密失败:", err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "invalid data ")
}
//真正的数据结构
var parseInfo websocket_data.NotifyData
if err = json.Unmarshal([]byte(data), &parseInfo); err != nil {
logx.Error("failed to parse json data:", err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "invalid format of parse data")
}
//websocket连接id不能为空
if parseInfo.WebsocketConnectId == "" {
return resp.SetStatusWithMessage(basic.CodeServiceErr, "websocket connect id is empty")
}
now := time.Now().UTC().Unix()
//请求时间前后20秒都会失效
if parseInfo.RequestTime < now-20 || parseInfo.RequestTime > now+20 {
return resp.SetStatusWithMessage(basic.CodeServiceErr, "invalid data ,time is not in allowed range")
}
//查询websocket连接
value, ok := mapConnPool.Load(parseInfo.WebsocketConnectId)
if !ok {
return resp.SetStatusWithMessage(basic.CodeOK, "success,but connection is not found")
}
//断言连接
ws, ok := value.(wsConnectItem)
if !ok {
logx.Error("渲染回调断言websocket连接失败")
return resp.SetStatusWithMessage(basic.CodeServiceErr, "断言连接错误")
}
//发送消息到出口缓冲池
ws.sendToOutChan(ws.respondDataFormat(constants.WEBSOCKET_LOGIN_NOTIFY, parseInfo.Data))
return resp.SetStatusWithMessage(basic.CodeOK, "success")
}
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *LoginNotifyLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)
// }

View File

@ -1,83 +0,0 @@
package logic
//注册帐号回调
import (
"encoding/json"
"fusenapi/constants"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"fusenapi/utils/encryption_decryption"
"fusenapi/utils/websocket_data"
"time"
"context"
"fusenapi/server/websocket/internal/svc"
"fusenapi/server/websocket/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type RegisterAccountNotifyLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewRegisterAccountNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterAccountNotifyLogic {
return &RegisterAccountNotifyLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
// 处理进入前逻辑w,r
// func (l *RegisterAccountNotifyLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }
func (l *RegisterAccountNotifyLogic) RegisterAccountNotify(req *types.RegisterAccountNotifyReq, userinfo *auth.UserInfo) (resp *basic.Response) {
if req.Data == "" {
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "data is empty")
}
//解密数据
data, err := encryption_decryption.CBCDecrypt(req.Data)
if err != nil {
logx.Error("解密失败:", err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "invalid data ")
}
//真正的数据结构
var parseInfo websocket_data.NotifyData
if err = json.Unmarshal([]byte(data), &parseInfo); err != nil {
logx.Error("failed to parse json data:", err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "invalid format of parse data")
}
//websocket连接id不能为空
if parseInfo.WebsocketConnectId == "" {
return resp.SetStatusWithMessage(basic.CodeServiceErr, "websocket connect id is empty")
}
now := time.Now().UTC().Unix()
//请求时间前后20秒都会失效
if parseInfo.RequestTime < now-20 || parseInfo.RequestTime > now+20 {
return resp.SetStatusWithMessage(basic.CodeServiceErr, "invalid data ,time is not in allowed range")
}
//查询websocket连接
value, ok := mapConnPool.Load(parseInfo.WebsocketConnectId)
if !ok {
return resp.SetStatusWithMessage(basic.CodeOK, "success,but connection is not found")
}
//断言连接
ws, ok := value.(wsConnectItem)
if !ok {
logx.Error("渲染回调断言websocket连接失败")
return resp.SetStatusWithMessage(basic.CodeServiceErr, "断言连接错误")
}
//发送消息到出口缓冲池
ws.sendToOutChan(ws.respondDataFormat(constants.WEBSOCKET_REGISTER_NOTIFY, parseInfo.Data))
return resp.SetStatusWithMessage(basic.CodeOK, "success")
}
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *RegisterAccountNotifyLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)
// }

View File

@ -0,0 +1,40 @@
package logic
import "fusenapi/constants"
// 入口数据格式错误
func (w *wsConnectItem) incomeDataFormatErrResponse(data interface{}) {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_ERR_DATA_FORMAT, data))
}
// 渲染错误通知
func (w *wsConnectItem) renderErrResponse(renderId, templateTag, taskId, description string, userId, guestId, templateId, modelId, sizeId int64) {
data := make(map[string]interface{})
data["render_id"] = renderId
data["description"] = description
data["template_tag"] = templateTag
if taskId != "" {
data["task_id"] = taskId
}
if userId >= 0 {
data["user_id"] = userId
}
if guestId >= 0 {
data["guest_id"] = guestId
}
if templateId > 0 {
data["template_id"] = templateId
}
if modelId > 0 {
data["model_id"] = modelId
}
if sizeId > 0 {
data["size_id"] = sizeId
}
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_RENDER_IMAGE_ERR, data))
}
// 复用连接错误通知
func (w *wsConnectItem) reuseLastConnErrResponse(data interface{}) {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_REQUEST_RESUME_LAST_CONNECT_ERR, data))
}

View File

@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"fusenapi/constants"
"fusenapi/model/gmodel"
"fusenapi/service/repositories"
"fusenapi/utils/curl"
"fusenapi/utils/hash"
@ -72,30 +73,15 @@ func (w *wsConnectItem) consumeRenderCache(data []byte) {
logx.Info("消费渲染数据:", string(data))
var renderImageData websocket_data.RenderImageReqMsg
if err := json.Unmarshal(data, &renderImageData); err != nil {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_ERR_DATA_FORMAT, "invalid format of websocket render image message:"+string(data)))
w.incomeDataFormatErrResponse("invalid format of render data:" + string(data))
logx.Error("invalid format of websocket render image message", err)
return
}
if renderImageData.RenderId == "" {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_ERR_DATA_FORMAT, "invalid format of websocket render image message:render_id is empty"))
logx.Error("invalid format of websocket render image message:render_id is empty")
return
}
if renderImageData.RenderData.ProductId <= 0 {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_ERR_DATA_FORMAT, "invalid format of websocket render image message:product_id "))
logx.Error("invalid format of websocket render image message:product_id")
return
}
if renderImageData.RenderData.TemplateTag == "" {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_ERR_DATA_FORMAT, "invalid format of websocket render image message:template_tag "))
logx.Error("invalid format of websocket render image message:template_tag")
return
}
//获取上传最近的logo
userMaterial, err := w.logic.svcCtx.AllModels.FsUserMaterial.FindLatestOne(w.logic.ctx, w.userId, w.guestId)
if err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_ERR_DATA_FORMAT, "failed to get user logo"))
w.renderErrResponse(renderImageData.RenderId, renderImageData.RenderData.TemplateTag, "", "failed to get user logo", w.userId, w.guestId, 0, 0, 0)
logx.Error("failed to get user logo")
return
}
@ -103,10 +89,10 @@ func (w *wsConnectItem) consumeRenderCache(data []byte) {
userMaterialDefault, err := w.logic.svcCtx.AllModels.FsUserMaterial.FindOneById(w.logic.ctx, 0)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_ERR_DATA_FORMAT, "default logo is not exists"))
w.renderErrResponse(renderImageData.RenderId, renderImageData.RenderData.TemplateTag, "", "default logo is not exists", w.userId, w.guestId, 0, 0, 0)
return
}
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_ERR_DATA_FORMAT, "failed to get default logo"))
w.renderErrResponse(renderImageData.RenderId, renderImageData.RenderData.TemplateTag, "", "failed to get default logo", w.userId, w.guestId, 0, 0, 0)
logx.Error("default logo is not exists")
return
}
@ -117,20 +103,61 @@ func (w *wsConnectItem) consumeRenderCache(data []byte) {
//用户id赋值
renderImageData.RenderData.UserId = w.userId
renderImageData.RenderData.GuestId = w.guestId
//生成任务id(需要把user_id,guest_id设为0)
hashVal := renderImageData.RenderData
hashVal.UserId = 0
hashVal.GuestId = 0
hashByte, _ := json.Marshal(hashVal)
var hashData map[string]interface{}
_ = json.Unmarshal(hashByte, &hashData)
taskId := hash.JsonHashKey(hashData)
//获取产品第一个尺寸
productFirstSize, err := w.logic.svcCtx.AllModels.FsProductSize.GetProductFirstSize(w.logic.ctx, renderImageData.RenderData.ProductId)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
w.renderErrResponse(renderImageData.RenderId, renderImageData.RenderData.TemplateTag, "", "product first size is not exists", w.userId, w.guestId, 0, 0, 0)
logx.Error("product first size is not found")
return
}
w.renderErrResponse(renderImageData.RenderId, renderImageData.RenderData.TemplateTag, "", "failed to get product first size", w.userId, w.guestId, 0, 0, 0)
logx.Error("failed to get product first size:", err)
return
}
//获取模型(只是获取id)
model3dInfo, err := w.logic.svcCtx.AllModels.FsProductModel3d.GetOneBySizeIdTag(w.logic.ctx, productFirstSize.Id, constants.TAG_MODEL, "id")
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
w.renderErrResponse(renderImageData.RenderId, renderImageData.RenderData.TemplateTag, "", "product model is not exists", w.userId, w.guestId, 0, 0, productFirstSize.Id)
logx.Error("product model is not found")
return
}
w.renderErrResponse(renderImageData.RenderId, renderImageData.RenderData.TemplateTag, "", "failed to get product model", w.userId, w.guestId, 0, 0, productFirstSize.Id)
logx.Error("failed to get product model:", err)
return
}
//获取模板
productTemplate, err := w.logic.svcCtx.AllModels.FsProductTemplateV2.FindFirstOneByProductIdModelIdTemplateTag(w.logic.ctx, renderImageData.RenderData.ProductId, model3dInfo.Id, renderImageData.RenderData.TemplateTag)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
w.renderErrResponse(renderImageData.RenderId, renderImageData.RenderData.TemplateTag, "", "product template is not exists", w.userId, w.guestId, 0, model3dInfo.Id, productFirstSize.Id)
logx.Error("template info is not found")
return
}
w.renderErrResponse(renderImageData.RenderId, renderImageData.RenderData.TemplateTag, "", "failed to get product template", w.userId, w.guestId, 0, model3dInfo.Id, productFirstSize.Id)
logx.Error("failed to get template info:", err)
return
}
//获取渲染设置信息
element, err := w.logic.svcCtx.AllModels.FsProductTemplateElement.FindOneByModelId(w.logic.ctx, *productTemplate.ModelId)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
w.renderErrResponse(renderImageData.RenderId, renderImageData.RenderData.TemplateTag, "", "render element is not exists", w.userId, w.guestId, productTemplate.Id, model3dInfo.Id, productFirstSize.Id)
logx.Error("element info is not found,model_id = ", *productTemplate.ModelId)
return
}
w.renderErrResponse(renderImageData.RenderId, renderImageData.RenderData.TemplateTag, "", "failed to get render element", w.userId, w.guestId, productTemplate.Id, model3dInfo.Id, productFirstSize.Id)
logx.Error("failed to get element list,", err)
return
}
//获取唯一id
taskId := w.genRenderTaskId(renderImageData, model3dInfo, productTemplate, element)
//查询有没有缓存的资源,有就返回######################
resource, err := w.logic.svcCtx.AllModels.FsResource.FindOneById(w.logic.ctx, taskId)
if err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_RENDER_IMAGE_ERR, fmt.Sprintf("获取云渲染缓存资源错误 task_id:%s ", taskId)))
w.renderErrResponse(renderImageData.RenderId, renderImageData.RenderData.TemplateTag, taskId, "failed to get render cache", w.userId, w.guestId, 0, 0, 0)
logx.Error("failed to find render resource:", err)
return
}
@ -154,50 +181,40 @@ func (w *wsConnectItem) consumeRenderCache(data []byte) {
RenderId: renderImageData.RenderId,
})
//组装数据
if err = w.assembleRenderData(taskId, renderImageData); err != nil {
if err = w.assembleRenderData(taskId, renderImageData, productTemplate, model3dInfo, element, productFirstSize); err != nil {
logx.Error("组装数据失败:", err)
return
}
}
// 组装渲染任务id
func (w *wsConnectItem) genRenderTaskId(renderImageData websocket_data.RenderImageReqMsg, model3dInfo *gmodel.FsProductModel3d, productTemplate *gmodel.FsProductTemplateV2, element *gmodel.FsProductTemplateElement) string {
//生成任务id(需要把user_id,guest_id设为0)
incomeHashParam := renderImageData.RenderData
incomeHashParam.UserId = 0 //设为0(渲染跟用户id无关)
incomeHashParam.GuestId = 0 //设为0(渲染跟用户id无关)
incomeHashBytes, _ := json.Marshal(incomeHashParam)
modelHashStr := ""
templateHashStr := ""
if model3dInfo.ModelInfo != nil {
modelHashStr = *model3dInfo.ModelInfo
}
if productTemplate.TemplateInfo != nil {
templateHashStr = *productTemplate.TemplateInfo
}
elementHashBytes, _ := json.Marshal(element)
hashMap := map[string]interface{}{
"income_param": incomeHashBytes,
"model_info": modelHashStr,
"template_info": templateHashStr,
"render_element": elementHashBytes,
}
return hash.JsonHashKey(hashMap)
}
// 组装数据发送给unity
func (w *wsConnectItem) assembleRenderData(taskId string, info websocket_data.RenderImageReqMsg) error {
//获取产品第一个尺寸
productFirstSize, err := w.logic.svcCtx.AllModels.FsProductSize.GetProductFirstSize(w.logic.ctx, info.RenderData.ProductId)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_RENDER_IMAGE_ERR, fmt.Sprintf("没有尺寸 product_id:%d ", info.RenderData.ProductId)))
logx.Error("product first size is not found")
return err
}
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_RENDER_IMAGE_ERR, fmt.Sprintf("获取尺寸错误 product_id:%d ", info.RenderData.ProductId)))
logx.Error("failed to get product first size:", err)
return err
}
//获取模型(只是获取id)
model3dInfo, err := w.logic.svcCtx.AllModels.FsProductModel3d.GetOneBySizeIdTag(w.logic.ctx, productFirstSize.Id, constants.TAG_MODEL, "id")
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_RENDER_IMAGE_ERR, fmt.Sprintf("没有模型 product_id:%d , size_id:%d ", info.RenderData.ProductId, productFirstSize.Id)))
logx.Error("product model is not found")
return err
}
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_RENDER_IMAGE_ERR, fmt.Sprintf("获取模型错误 product_id:%d , size_id:%d ", info.RenderData.ProductId, productFirstSize.Id)))
logx.Error("failed to get product model:", err)
return err
}
//获取模板
productTemplate, err := w.logic.svcCtx.AllModels.FsProductTemplateV2.FindFirstOneByProductIdModelIdTemplateTag(w.logic.ctx, info.RenderData.ProductId, model3dInfo.Id, info.RenderData.TemplateTag)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_RENDER_IMAGE_ERR, fmt.Sprintf("模板未找到 product_id:%d , model_id:%d ,template_tag:%s", info.RenderData.ProductId, model3dInfo.Id, info.RenderData.TemplateTag)))
logx.Error("template info is not found")
return err
}
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_RENDER_IMAGE_ERR, fmt.Sprintf("获取模板错误 product_id:%d , model_id:%d ,template_tag:%s", info.RenderData.ProductId, model3dInfo.Id, info.RenderData.TemplateTag)))
logx.Error("failed to get template info:", err)
return err
}
func (w *wsConnectItem) assembleRenderData(taskId string, info websocket_data.RenderImageReqMsg, productTemplate *gmodel.FsProductTemplateV2, model3dInfo *gmodel.FsProductModel3d, element *gmodel.FsProductTemplateElement, productFirstSize *gmodel.FsProductSize) error {
//记录刀版图合成开始时间
w.modifyRenderTaskTimeConsuming(renderImageControlChanItem{
Option: 2,
@ -219,7 +236,7 @@ func (w *wsConnectItem) assembleRenderData(taskId string, info websocket_data.Re
}
res, err := w.logic.svcCtx.Repositories.ImageHandle.LogoCombine(w.logic.ctx, &combineReq)
if err != nil {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_RENDER_IMAGE_ERR, fmt.Sprintf("接口合图错误,产品id:%d,模板id%d", info.RenderData.ProductId, productTemplate.Id)))
w.renderErrResponse(info.RenderId, info.RenderData.TemplateTag, taskId, "failed to combine image", w.userId, w.guestId, productTemplate.Id, model3dInfo.Id, productFirstSize.Id)
logx.Error("合成刀版图失败,合成请求数据:", combineReq, "错误信息:", err)
return err
}
@ -227,7 +244,7 @@ func (w *wsConnectItem) assembleRenderData(taskId string, info websocket_data.Re
if res != nil && res.ResourceUrl != nil {
combineImage = *res.ResourceUrl
} else {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_RENDER_IMAGE_ERR, fmt.Sprintf("接口合图错误,刀版图是空的,产品id:%d", info.RenderData.ProductId)))
w.renderErrResponse(info.RenderId, info.RenderData.TemplateTag, taskId, "combine image is empty", w.userId, w.guestId, productTemplate.Id, model3dInfo.Id, productFirstSize.Id)
logx.Error("合成刀版图失败,合成的刀版图是空指针:", err)
return err
}
@ -240,23 +257,14 @@ func (w *wsConnectItem) assembleRenderData(taskId string, info websocket_data.Re
},
})
logx.Info("合成刀版图成功,合成刀版图数据:", combineReq, ",logo图片:", info.RenderData.Logo, " 刀版图:", *res.ResourceUrl)
//获取渲染设置信息
element, err := w.logic.svcCtx.AllModels.FsProductTemplateElement.FindOneByModelId(w.logic.ctx, *productTemplate.ModelId)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_RENDER_IMAGE_ERR, fmt.Sprintf("无渲染设置信息,产品id:%d ,模板id%d,模型id:%d", info.RenderData.ProductId, productTemplate.Id, *productTemplate.ModelId)))
logx.Error("element info is not found,model_id = ", *productTemplate.ModelId)
return err
}
logx.Error("failed to get element list,", err)
return err
}
//组装数据
refletion := -1
if element.Refletion != nil && *element.Refletion != "" {
refletion, err = strconv.Atoi(*element.Refletion)
if err != nil {
logx.Error("err refletion:set default -1")
w.renderErrResponse(info.RenderId, info.RenderData.TemplateTag, taskId, "parse element.Refletion from string to number err", w.userId, w.guestId, productTemplate.Id, model3dInfo.Id, productFirstSize.Id)
return err
}
}
//组装data数据
@ -264,6 +272,7 @@ func (w *wsConnectItem) assembleRenderData(taskId string, info websocket_data.Re
if element.Mode != nil && *element.Mode != "" {
if err = json.Unmarshal([]byte(*element.Mode), &mode); err != nil {
logx.Error("faile to parse element mode json:", err)
w.renderErrResponse(info.RenderId, info.RenderData.TemplateTag, taskId, "parse element.Mode err", w.userId, w.guestId, productTemplate.Id, model3dInfo.Id, productFirstSize.Id)
return err
}
}
@ -336,7 +345,7 @@ func (w *wsConnectItem) assembleRenderData(taskId string, info websocket_data.Re
postDataBytes, _ := json.Marshal(postData)
_, err = curl.ApiCall(url, "POST", header, bytes.NewReader(postDataBytes), time.Second*10)
if err != nil {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_RENDER_IMAGE_ERR, fmt.Sprintf("请求unity接口错误,产品id:%d", info.RenderData.ProductId)))
w.renderErrResponse(info.RenderId, info.RenderData.TemplateTag, taskId, "request unity api err", w.userId, w.guestId, productTemplate.Id, model3dInfo.Id, productFirstSize.Id)
logx.Error("failed to send data to unity")
return err
}

View File

@ -12,33 +12,33 @@ import (
// 刷新重连请求恢复上次连接的标识
func (w *wsConnectItem) reuseLastConnect(data []byte) {
logx.Info("收到请求恢复上次连接标识数据:", string(data))
var clientId string
if err := json.Unmarshal(data, &clientId); err != nil {
logx.Error(" invalid format of client id :", clientId)
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_REQUEST_RESUME_LAST_CONNECT_ERR, "invalid format of client id"))
var wid string
if err := json.Unmarshal(data, &wid); err != nil {
logx.Error(" invalid format of wid :", wid)
w.incomeDataFormatErrResponse("invalid format of wid")
return
}
//解密
decryptionClientId, err := encryption_decryption.CBCDecrypt(clientId)
decryptionWid, err := encryption_decryption.CBCDecrypt(wid)
if err != nil {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_REQUEST_RESUME_LAST_CONNECT_ERR, "invalid client id"))
w.reuseLastConnErrResponse("invalid wid")
return
}
lendecryptionClientId := len(decryptionClientId)
lendecryptionWid := len(decryptionWid)
//合成client后缀,不是同个后缀的不能复用
userPart := getUserJoinPart(w.userId, w.guestId)
lenUserPart := len(userPart)
if lendecryptionClientId <= lenUserPart {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_REQUEST_RESUME_LAST_CONNECT_ERR, "length of client id is to short"))
if lendecryptionWid <= lenUserPart {
w.reuseLastConnErrResponse("length of client id is to short")
return
}
//尾部不同不能复用
if decryptionClientId[lendecryptionClientId-lenUserPart:] != userPart {
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_REQUEST_RESUME_LAST_CONNECT_ERR, "the client id is not belong you before"))
if decryptionWid[lendecryptionWid-lenUserPart:] != userPart {
w.reuseLastConnErrResponse("the client id is not belong you before")
return
}
//存在是不能给他申请重新绑定
if v, ok := mapConnPool.Load(clientId); ok {
if v, ok := mapConnPool.Load(wid); ok {
obj, ok := v.(wsConnectItem)
if !ok {
logx.Error("连接断言失败")
@ -47,14 +47,13 @@ func (w *wsConnectItem) reuseLastConnect(data []byte) {
if obj.uniqueId == w.uniqueId {
return
} else {
rsp := w.respondDataFormat(constants.WEBSOCKET_REQUEST_RESUME_LAST_CONNECT_ERR, "id has bound by other connect ")
w.sendToOutChan(rsp)
w.reuseLastConnErrResponse("the wid is used by other people")
return
}
}
//重新绑定
w.uniqueId = clientId
rsp := w.respondDataFormat(constants.WEBSOCKET_CONNECT_SUCCESS, clientId)
w.uniqueId = wid
rsp := w.respondDataFormat(constants.WEBSOCKET_CONNECT_SUCCESS, wid)
w.sendToOutChan(rsp)
return
}

View File

@ -12,12 +12,9 @@ type RenderNotifyReq struct {
Image string `json:"image"`
}
type RegisterAccountNotifyReq struct {
Data string `json:"data"` //aes_cbc加密密文
}
type LoginNotifyReq struct {
Data string `json:"data"` //aes_cbc加密密文
type CommonNotifyReq struct {
Wid string `json:"wid"` //websocket连接标识
Data map[string]interface{} `json:"data"` //后端与前端约定好的数据
}
type Request struct {

View File

@ -15,12 +15,9 @@ service websocket {
//云渲染完了通知接口
@handler RenderNotifyHandler
post /api/websocket/render_notify(RenderNotifyReq) returns (response);
//注册回调
@handler RegisterAccountNotifyHandler
post /api/websocket/register_account_notify(RegisterAccountNotifyReq) returns (response);
//登录回调
@handler LoginNotifyHandler
post /api/websocket/login_notify(LoginNotifyReq) returns (response);
//通用回调接口
@handler CommonNotifyHandler
post /api/websocket/common_notify(CommonNotifyReq) returns (response);
}
//渲染完了通知接口
@ -30,11 +27,8 @@ type RenderNotifyReq {
GuestId int64 `json:"guest_id"`
Image string `json:"image"`
}
//注册回调
type RegisterAccountNotifyReq {
Data string `json:"data"` //aes_cbc加密密文
}
//登录回调
type LoginNotifyReq {
Data string `json:"data"` //aes_cbc加密密文
//通用回调接口
type CommonNotifyReq {
Wid string `json:"wid"` //websocket连接标识
Data map[string]interface{} `json:"data"` //后端与前端约定好的数据
}

View File

@ -1,8 +0,0 @@
package websocket_data
// 请求回调接口数据(登录|注册)
type NotifyData struct {
WebsocketConnectId string `json:"websocket_connect_id"` //websocket连接唯一标识
RequestTime int64 `json:"request_time"` //请求回调时的utc时间
Data interface{} `json:"data"` //其他数据
}