fusenapi/server/websocket/internal/logic/rendernotifylogic.go
laodaming 5532cd1a11 fix
2023-07-27 16:13:06 +08:00

90 lines
2.4 KiB
Go

package logic
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"fusenapi/constants"
"fusenapi/utils/basic"
"time"
"context"
"fusenapi/server/websocket/internal/svc"
"fusenapi/server/websocket/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type RenderNotifyLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewRenderNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RenderNotifyLogic {
return &RenderNotifyLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
// 处理进入前逻辑w,r
// func (l *RenderNotifyLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *RenderNotifyLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)
// }
func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basic.Response) {
if time.Now().Unix()-120 > req.Time /*|| req.Time > time.Now().Unix() */ {
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "invalid param time")
}
//验证签名 sha256
notifyByte, _ := json.Marshal(req.Info)
h := sha256.New()
h.Write([]byte(fmt.Sprintf(constants.RENDER_NOTIFY_SIGN_KEY, string(notifyByte), req.Time)))
signHex := h.Sum(nil)
sign := hex.EncodeToString(signHex)
//fmt.Println(sign)
if req.Sign != sign {
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "invalid sign")
}
//遍历websocket链接把数据传进去
mapConnPool.Range(func(key, value any) bool {
//断言连接
ws, ok := value.(wsConnectItem)
if !ok {
return true
}
renderKey := ws.getRenderImageMapKey(req.Info.ProductId, req.Info.TemplateTagId, req.Info.AlgorithmVersion)
//查询有无该渲染任务
_, ok = ws.renderProperty.renderImageTask[renderKey]
if !ok {
return true
}
rspData := types.DataTransferData{
T: constants.WEBSOCKET_RENDER_IMAGE,
D: types.RenderImageRspMsg{
ProductId: req.Info.ProductId,
TemplateTagId: req.Info.TemplateTagId,
Image: req.Info.Image,
},
}
b, _ := json.Marshal(rspData)
//删除对应的需要渲染的图片map
ws.renderProperty.renderImageTaskCtlChan <- renderImageControlChanItem{
Option: 0, //0删除 1添加
Key: renderKey,
}
//发送数据到out chan
ws.sendToOutChan(b)
return true
})
return resp.SetStatus(basic.CodeOK)
}