From f792215c2f850e26fa137a79a95dbf54dda4fed4 Mon Sep 17 00:00:00 2001 From: Hiven Date: Mon, 24 Jul 2023 12:19:34 +0800 Subject: [PATCH 01/68] =?UTF-8?q?=E8=AE=A2=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/logic/userorderlistlogic.go | 26 ++++--- utils/configs/order.go | 67 +++++++++++++++++++ utils/order/order_status.go | 4 +- 3 files changed, 86 insertions(+), 11 deletions(-) diff --git a/server/home-user-auth/internal/logic/userorderlistlogic.go b/server/home-user-auth/internal/logic/userorderlistlogic.go index b6d2b9a4..b43de13b 100644 --- a/server/home-user-auth/internal/logic/userorderlistlogic.go +++ b/server/home-user-auth/internal/logic/userorderlistlogic.go @@ -6,6 +6,7 @@ import ( "fusenapi/model/gmodel" "fusenapi/utils/auth" "fusenapi/utils/basic" + "fusenapi/utils/configs" "fusenapi/utils/format" "fusenapi/utils/order" @@ -39,6 +40,9 @@ func (l *UserOrderListLogic) UserOrderList(req *types.UserOrderListReq, userinfo // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) // userinfo 传入值时, 一定不为null + // 测试 + userinfo.UserId = 39 + orderDetailModel := gmodel.NewFsOrderDetailModel(l.svcCtx.MysqlConn) orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn) rowBuilder := orderModel.RowSelectBuilder(nil) @@ -86,10 +90,10 @@ func (l *UserOrderListLogic) UserOrderList(req *types.UserOrderListReq, userinfo var respList []types.Items if listResLen > 0 { // 获取订单时间配置 - // orderTimeConfig, err := configs.GetOrderTimeConfig(l.ctx, l.svcCtx.MysqlConn) - // if err != nil { - // return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get config time info") - // } + orderTimeConfig, err := configs.GetOrderTimeConfig(l.ctx, l.svcCtx.MysqlConn) + if err != nil { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get config time info") + } // 数据处理 for _, item := range listRes { @@ -121,9 +125,9 @@ func (l *UserOrderListLogic) UserOrderList(req *types.UserOrderListReq, userinfo fsOrderAffiliateInfo := item.FsOrderAffiliateInfo - statusAndLogisticsRes := order.GetOrderStatusAndLogistics(order.GetOrderStatusAndLogisticsReq{ - OrderStatus: constants.Order(*item.Status), - DeliveryMethod: constants.DeliveryMethod(*item.DeliveryMethod), + var getOrderStatusAndLogisticsReq = order.GetOrderStatusAndLogisticsReq{ + OrderStatus: 1, + DeliveryMethod: 1, IsPayCompleted: *item.IsAllProductCompleted, SureTime: *fsOrderAffiliateInfo.SureTime, ProductTime: *fsOrderAffiliateInfo.SureTime, @@ -134,9 +138,11 @@ func (l *UserOrderListLogic) UserOrderList(req *types.UserOrderListReq, userinfo ArrivalTime: *fsOrderAffiliateInfo.SureTime, RecevieTime: *fsOrderAffiliateInfo.SureTime, - OrderCtime: *item.Ctime, - //WebSetTimeInfo: orderTimeConfig, - }) + OrderCtime: *item.Ctime, + WebSetTimeInfo: orderTimeConfig, + } + + statusAndLogisticsRes := order.GetOrderStatusAndLogistics(getOrderStatusAndLogisticsReq) // 流程控制 statusTime := make([]*types.StatusTime, 5) diff --git a/utils/configs/order.go b/utils/configs/order.go index 291ac401..eb1f8d6b 100644 --- a/utils/configs/order.go +++ b/utils/configs/order.go @@ -1,8 +1,75 @@ package configs +import ( + "context" + "encoding/json" + "errors" + "fusenapi/constants" + "fusenapi/model/gmodel" + "strconv" + + "github.com/zeromicro/go-zero/core/logx" + "gorm.io/gorm" +) + type WebSetTimeInfo struct { ProductDay int64 FactoryDeliverDay int64 DeliverUpsDay int64 UpsTransDay int64 } + +type WebSetTimeInfoData struct { + ProductDay string `json:"product_day"` + FactoryDeliverDay string `json:"factory_deliver_day"` + DeliverUpsDay string `json:"deliver_ups_day"` + UpsTransDay string `json:"ups_trans_day"` +} + +func GetOrderTimeConfig(ctx context.Context, db *gorm.DB) (res WebSetTimeInfo, err error) { + resData, err := gmodel.NewFsWebSetModel(db).FindValueByKey(ctx, string(constants.WEBSET_TIME_INFO)) + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + res.ProductDay = int64(constants.ORDER_PRODUCT_DAY) + res.FactoryDeliverDay = int64(constants.ORDER_FACTORY_DELIVER_DAY) + res.DeliverUpsDay = int64(constants.ORDER_DELIVER_UPS_DAY) + res.UpsTransDay = int64(constants.ORDER_UPS_TRANS_DAY) + return res, nil + } + logx.Error(err) + return res, err + } else { + var timeInfo WebSetTimeInfoData + err = json.Unmarshal([]byte(*resData.Value), &timeInfo) + if err != nil { + logx.Error(err) + return res, err + } + productDay, err := strconv.Atoi(timeInfo.ProductDay) + if err != nil { + logx.Error(err) + return res, err + } + factoryDeliverDay, err := strconv.Atoi(timeInfo.FactoryDeliverDay) + if err != nil { + logx.Error(err) + return res, err + } + deliverUpsDay, err := strconv.Atoi(timeInfo.DeliverUpsDay) + if err != nil { + logx.Error(err) + return res, err + } + upsTransDay, err := strconv.Atoi(timeInfo.UpsTransDay) + if err != nil { + logx.Error(err) + return res, err + } + res.ProductDay = int64(productDay) + res.FactoryDeliverDay = int64(factoryDeliverDay) + res.DeliverUpsDay = int64(deliverUpsDay) + res.UpsTransDay = int64(upsTransDay) + } + + return res, nil +} diff --git a/utils/order/order_status.go b/utils/order/order_status.go index e12af5a8..51bc8351 100644 --- a/utils/order/order_status.go +++ b/utils/order/order_status.go @@ -37,6 +37,8 @@ type GetOrderStatusAndLogisticsReq struct { OrderStatus constants.Order DeliveryMethod constants.DeliveryMethod IsPayCompleted int64 + OrderCtime int64 + SureTime int64 ProductTime int64 ProductEndtime int64 @@ -46,7 +48,7 @@ type GetOrderStatusAndLogisticsReq struct { ArrivalTime int64 RecevieTime int64 - OrderCtime int64 + WebSetTimeInfo configs.WebSetTimeInfo } From f5cfed20d3e1fc776dddc4fd51fe3856257b69ae Mon Sep 17 00:00:00 2001 From: Hiven Date: Mon, 24 Jul 2023 13:03:43 +0800 Subject: [PATCH 02/68] =?UTF-8?q?=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/logic/userorderlistlogic.go | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/server/home-user-auth/internal/logic/userorderlistlogic.go b/server/home-user-auth/internal/logic/userorderlistlogic.go index b43de13b..cfe0df2c 100644 --- a/server/home-user-auth/internal/logic/userorderlistlogic.go +++ b/server/home-user-auth/internal/logic/userorderlistlogic.go @@ -2,6 +2,7 @@ package logic import ( "errors" + "fmt" "fusenapi/constants" "fusenapi/model/gmodel" "fusenapi/utils/auth" @@ -123,23 +124,23 @@ func (l *UserOrderListLogic) UserOrderList(req *types.UserOrderListReq, userinfo } } - fsOrderAffiliateInfo := item.FsOrderAffiliateInfo - + //fsOrderAffiliateInfo := item.FsOrderAffiliateInfo + fmt.Println(orderTimeConfig) var getOrderStatusAndLogisticsReq = order.GetOrderStatusAndLogisticsReq{ OrderStatus: 1, DeliveryMethod: 1, - IsPayCompleted: *item.IsAllProductCompleted, - SureTime: *fsOrderAffiliateInfo.SureTime, - ProductTime: *fsOrderAffiliateInfo.SureTime, - ProductEndtime: *fsOrderAffiliateInfo.SureTime, - DeliverTime: *fsOrderAffiliateInfo.SureTime, - UpsDeliverTime: *fsOrderAffiliateInfo.SureTime, - UpsTime: *fsOrderAffiliateInfo.SureTime, - ArrivalTime: *fsOrderAffiliateInfo.SureTime, - RecevieTime: *fsOrderAffiliateInfo.SureTime, + // IsPayCompleted: *item.IsAllProductCompleted, + // SureTime: *fsOrderAffiliateInfo.SureTime, + // ProductTime: *fsOrderAffiliateInfo.SureTime, + // ProductEndtime: *fsOrderAffiliateInfo.SureTime, + // DeliverTime: *fsOrderAffiliateInfo.SureTime, + // UpsDeliverTime: *fsOrderAffiliateInfo.SureTime, + // UpsTime: *fsOrderAffiliateInfo.SureTime, + // ArrivalTime: *fsOrderAffiliateInfo.SureTime, + // RecevieTime: *fsOrderAffiliateInfo.SureTime, - OrderCtime: *item.Ctime, - WebSetTimeInfo: orderTimeConfig, + // // OrderCtime: *item.Ctime, + // WebSetTimeInfo: orderTimeConfig, } statusAndLogisticsRes := order.GetOrderStatusAndLogistics(getOrderStatusAndLogisticsReq) From 7e22f47a0d0927df68ca4e02ee6f9ad981a45cd5 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 24 Jul 2023 16:07:05 +0800 Subject: [PATCH 03/68] fix --- go.mod | 1 + go.sum | 2 + server/websocket/etc/websocket.yaml | 8 ++ server/websocket/internal/config/config.go | 9 ++ .../internal/handler/datatransferhandler.go | 58 +++++++++++++ server/websocket/internal/handler/routes.go | 22 +++++ .../internal/logic/datatransferlogic.go | 43 ++++++++++ .../websocket/internal/svc/servicecontext.go | 61 +++++++++++++ server/websocket/internal/types/types.go | 85 +++++++++++++++++++ server/websocket/websocket.go | 36 ++++++++ server_api/websocket.api | 25 ++++++ 11 files changed, 350 insertions(+) create mode 100644 server/websocket/etc/websocket.yaml create mode 100644 server/websocket/internal/config/config.go create mode 100644 server/websocket/internal/handler/datatransferhandler.go create mode 100644 server/websocket/internal/handler/routes.go create mode 100644 server/websocket/internal/logic/datatransferlogic.go create mode 100644 server/websocket/internal/svc/servicecontext.go create mode 100644 server/websocket/internal/types/types.go create mode 100644 server/websocket/websocket.go create mode 100644 server_api/websocket.api diff --git a/go.mod b/go.mod index f586919c..6d45a2e4 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/bwmarrin/snowflake v0.3.0 github.com/golang-jwt/jwt v3.2.2+incompatible github.com/google/uuid v1.3.0 + github.com/gorilla/websocket v1.5.0 github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e github.com/stripe/stripe-go/v74 v74.26.0 diff --git a/go.sum b/go.sum index 1fef35de..959acd49 100644 --- a/go.sum +++ b/go.sum @@ -165,6 +165,8 @@ github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= +github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.0/go.mod h1:hgWBS7lorOAVIJEQMi4ZsPv9hVvWI6+ch50m39Pf2Ks= github.com/grpc-ecosystem/grpc-gateway/v2 v2.15.0 h1:1JYBfzqrWPcCclBwxFCPAou9n+q86mfnu7NAeHfte7A= diff --git a/server/websocket/etc/websocket.yaml b/server/websocket/etc/websocket.yaml new file mode 100644 index 00000000..d22f03a7 --- /dev/null +++ b/server/websocket/etc/websocket.yaml @@ -0,0 +1,8 @@ +Name: websocket +Host: 0.0.0.0 +Port: 8888 +SourceMysql: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest +Auth: + AccessSecret: fusen2023 + AccessExpire: 2592000 + RefreshAfter: 1592000 \ No newline at end of file diff --git a/server/websocket/internal/config/config.go b/server/websocket/internal/config/config.go new file mode 100644 index 00000000..b24bb7d7 --- /dev/null +++ b/server/websocket/internal/config/config.go @@ -0,0 +1,9 @@ +package config + +import "github.com/zeromicro/go-zero/rest" + +type Config struct { + rest.RestConf + SourceMysql string + Auth types.Auth +} diff --git a/server/websocket/internal/handler/datatransferhandler.go b/server/websocket/internal/handler/datatransferhandler.go new file mode 100644 index 00000000..4534d041 --- /dev/null +++ b/server/websocket/internal/handler/datatransferhandler.go @@ -0,0 +1,58 @@ +package handler + +import ( + "fusenapi/server/websocket/internal/svc" + "github.com/gorilla/websocket" + "net/http" + "sync" +) + +var ( + //升级 + upgrade = websocket.Upgrader{ + //允许跨域 + CheckOrigin: func(r *http.Request) bool { + return true + }, + } + //连接map池 + mapConn = sync.Map{} +) + +type wsConnectItem struct { + conn *websocket.Conn //websocket的连接 + renImage sync.Map //需要渲染的图片 +} + +func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + /*// 解析JWT token,并对空用户进行判断 + claims, err := svcCtx.ParseJwtToken(r) + // 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息 + if err != nil { + logx.Info("unauthorized:", err.Error()) // 记录错误日志 + w.Write([]byte("connect failed:unauthorized")) + return + } + var userInfo *auth.UserInfo + if claims != nil { + // 从token中获取对应的用户信息 + userInfo, err = auth.GetUserInfoFormMapClaims(claims) + // 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息 + if err != nil { + return + } + } else { + // 如果claims为nil,则认为用户身份为白板用户 + w.Write([]byte("connect failed:unauthorized!!")) + return + } + //升级websocket + conn, err := upgrade.Upgrade(w, r, r.Header) + if err != nil { + logx.Error("http upgrade websocket err:", err) + w.Write([]byte("http upgrade websocket err")) + return + }*/ + } +} diff --git a/server/websocket/internal/handler/routes.go b/server/websocket/internal/handler/routes.go new file mode 100644 index 00000000..fd3200e4 --- /dev/null +++ b/server/websocket/internal/handler/routes.go @@ -0,0 +1,22 @@ +// Code generated by goctl. DO NOT EDIT. +package handler + +import ( + "net/http" + + "fusenapi/server/websocket/internal/svc" + + "github.com/zeromicro/go-zero/rest" +) + +func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { + server.AddRoutes( + []rest.Route{ + { + Method: http.MethodGet, + Path: "/api/websocket/data_transfer", + Handler: DataTransferHandler(serverCtx), + }, + }, + ) +} diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go new file mode 100644 index 00000000..7b5db86b --- /dev/null +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -0,0 +1,43 @@ +package logic + +import ( + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "context" + + "fusenapi/server/websocket/internal/svc" + "fusenapi/server/websocket/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type DataTransferLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewDataTransferLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DataTransferLogic { + return &DataTransferLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +// 处理进入前逻辑w,r +// func (l *DataTransferLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) { +// } + +// 处理逻辑后 w,r 如:重定向, resp 必须重新处理 +// func (l *DataTransferLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { +// // httpx.OkJsonCtx(r.Context(), w, resp) +// } + +func (l *DataTransferLogic) DataTransfer(req *types.DataTransferReq, userinfo *auth.UserInfo) (resp *basic.Response) { + // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) + // userinfo 传入值时, 一定不为null + + return resp.SetStatus(basic.CodeOK) +} diff --git a/server/websocket/internal/svc/servicecontext.go b/server/websocket/internal/svc/servicecontext.go new file mode 100644 index 00000000..9a22471e --- /dev/null +++ b/server/websocket/internal/svc/servicecontext.go @@ -0,0 +1,61 @@ +package svc + +import ( + "errors" + "fmt" + "fusenapi/server/websocket/internal/config" + "net/http" + + "fusenapi/initalize" + "fusenapi/model/gmodel" + + "github.com/golang-jwt/jwt" + "gorm.io/gorm" +) + +type ServiceContext struct { + Config config.Config + + MysqlConn *gorm.DB + AllModels *gmodel.AllModelsGen +} + +func NewServiceContext(c config.Config) *ServiceContext { + + return &ServiceContext{ + Config: c, + MysqlConn: initalize.InitMysql(c.SourceMysql), + AllModels: gmodel.NewAllModels(initalize.InitMysql(c.SourceMysql)), + } +} + +func (svcCtx *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) { + AuthKey := r.Header.Get("Authorization") + if AuthKey == "" { + return nil, nil + } + AuthKey = AuthKey[7:] + + if len(AuthKey) <= 50 { + return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey))) + } + + token, err := jwt.Parse(AuthKey, func(token *jwt.Token) (interface{}, error) { + // 检查签名方法是否为 HS256 + if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) + } + // 返回用于验证签名的密钥 + return []byte(svcCtx.Config.Auth.AccessSecret), nil + }) + if err != nil { + return nil, errors.New(fmt.Sprint("Error parsing token:", err)) + } + + // 验证成功返回 + if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { + return claims, nil + } + + return nil, errors.New(fmt.Sprint("Invalid token", err)) +} diff --git a/server/websocket/internal/types/types.go b/server/websocket/internal/types/types.go new file mode 100644 index 00000000..06201d39 --- /dev/null +++ b/server/websocket/internal/types/types.go @@ -0,0 +1,85 @@ +// Code generated by goctl. DO NOT EDIT. +package types + +import ( + "fusenapi/utils/basic" +) + +type DataTransferReq struct { + MsgType string `json:"msg_type"` //消息类型 + Message interface{} `json:"message"` //传递的消息 +} + +type DataTransferRsp struct { + MsgType string `json:"msg_type"` //消息类型 + Message interface{} `json:"message"` //传递的消息 +} + +type Request struct { +} + +type Response struct { + Code int `json:"code"` + Message string `json:"msg"` + Data interface{} `json:"data"` +} + +type Auth struct { + AccessSecret string `json:"accessSecret"` + AccessExpire int64 `json:"accessExpire"` + RefreshAfter int64 `json:"refreshAfter"` +} + +type File struct { + Filename string `fsfile:"filename"` + Header map[string][]string `fsfile:"header"` + Size int64 `fsfile:"size"` + Data []byte `fsfile:"data"` +} + +type Meta struct { + TotalCount int64 `json:"totalCount"` + PageCount int64 `json:"pageCount"` + CurrentPage int `json:"currentPage"` + PerPage int `json:"perPage"` +} + +// Set 设置Response的Code和Message值 +func (resp *Response) Set(Code int, Message string) *Response { + return &Response{ + Code: Code, + Message: Message, + } +} + +// Set 设置整个Response +func (resp *Response) SetWithData(Code int, Message string, Data interface{}) *Response { + return &Response{ + Code: Code, + Message: Message, + Data: Data, + } +} + +// SetStatus 设置默认StatusResponse(内部自定义) 默认msg, 可以带data, data只使用一个参数 +func (resp *Response) SetStatus(sr *basic.StatusResponse, data ...interface{}) *Response { + newResp := &Response{ + Code: sr.Code, + } + if len(data) == 1 { + newResp.Data = data[0] + } + return newResp +} + +// SetStatusWithMessage 设置默认StatusResponse(内部自定义) 非默认msg, 可以带data, data只使用一个参数 +func (resp *Response) SetStatusWithMessage(sr *basic.StatusResponse, msg string, data ...interface{}) *Response { + newResp := &Response{ + Code: sr.Code, + Message: msg, + } + if len(data) == 1 { + newResp.Data = data[0] + } + return newResp +} diff --git a/server/websocket/websocket.go b/server/websocket/websocket.go new file mode 100644 index 00000000..c5e7bdd0 --- /dev/null +++ b/server/websocket/websocket.go @@ -0,0 +1,36 @@ +package main + +import ( + "flag" + "fmt" + "net/http" + "time" + + "fusenapi/utils/auth" + + "fusenapi/server/websocket/internal/config" + "fusenapi/server/websocket/internal/handler" + "fusenapi/server/websocket/internal/svc" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/rest" +) + +var configFile = flag.String("f", "etc/websocket.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + c.Timeout = int64(time.Second * 15) + server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { + })) + defer server.Stop() + + ctx := svc.NewServiceContext(c) + handler.RegisterHandlers(server, ctx) + + fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port) + server.Start() +} diff --git a/server_api/websocket.api b/server_api/websocket.api new file mode 100644 index 00000000..786e67e7 --- /dev/null +++ b/server_api/websocket.api @@ -0,0 +1,25 @@ +syntax = "v1" + +info ( + title: "websocket"// TODO: add title + desc: // TODO: add description + author: "" + email: "" +) + +import "basic.api" +service websocket { + //websocket数据交互 + @handler DataTransferHandler + get /api/websocket/data_transfer(DataTransferReq) returns (response); +} + +//websocket数据交互 +type DataTransferReq { + MsgType string `json:"msg_type"` //消息类型 + Message interface{} `json:"message"` //传递的消息 +} +type DataTransferRsp { + MsgType string `json:"msg_type"` //消息类型 + Message interface{} `json:"message"` //传递的消息 +} \ No newline at end of file From 9d4bbbf80b8fd4493eb84e294dfdbddd7291cb2e Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 24 Jul 2023 18:02:30 +0800 Subject: [PATCH 04/68] fix --- .../internal/logic/gettagproductlistlogic.go | 28 +++++++++++++------ server/product/internal/types/types.go | 21 ++++++-------- server_api/product.api | 21 ++++++-------- 3 files changed, 35 insertions(+), 35 deletions(-) diff --git a/server/product/internal/logic/gettagproductlistlogic.go b/server/product/internal/logic/gettagproductlistlogic.go index 8a185eea..2ecc63b3 100644 --- a/server/product/internal/logic/gettagproductlistlogic.go +++ b/server/product/internal/logic/gettagproductlistlogic.go @@ -223,11 +223,9 @@ func (l *GetTagProductListLogic) dealWithTagMenuData(req dealWithTagMenuDataReq) TagProductList: nil, TypeName: *tagInfo.Title, TypeId: tagInfo.Id, - Level: int64(lenLevel), - LevelPrefix: *tagInfo.LevelPrefix, Icon: *tagInfo.Icon, Sort: *tagInfo.Sort, - Description: *tagInfo.Description, + LevelPrefix: *tagInfo.LevelPrefix, ChildTagList: make([]*types.TagItem, 0, 50), } //携带产品 @@ -243,8 +241,10 @@ func (l *GetTagProductListLogic) dealWithTagMenuData(req dealWithTagMenuDataReq) Size: req.Size, User: req.User, }) - //赋值 - tagTem.TagProductList = productListRsp + //tag中产品 + for _, tmpProduct := range productListRsp { + tagTem.TagProductList = append(tagTem.TagProductList, tmpProduct) + } } //加入分类 req.MapTagLevel[*tagInfo.LevelPrefix] = &tagTem @@ -255,6 +255,7 @@ func (l *GetTagProductListLogic) dealWithTagMenuData(req dealWithTagMenuDataReq) // 组织等级从属关系 func (l *GetTagProductListLogic) organizationLevelRelation(minLevel int, mapTagLevel map[string]*types.TagItem) []types.TagItem { mapTop := make(map[string]struct{}) + //设置归属关系 for prefix, tagItem := range mapTagLevel { prefixSlice := strings.Split(prefix, "/") //存储最高等级 @@ -275,6 +276,18 @@ func (l *GetTagProductListLogic) organizationLevelRelation(minLevel int, mapTagL }) mapTagLevel[parentPrefix] = parent } + //把子类的产品列表变成产品id列表并且把产品列表都放到最顶级父级中 + for _, v := range mapTagLevel { + if _, ok := mapTop[v.LevelPrefix]; ok { + continue + } + topPrefixSlic := strings.Split(v.LevelPrefix, "/")[:minLevel] + topPrefix := strings.Join(topPrefixSlic, "/") + for k, tmpProduct := range v.TagProductList { + v.TagProductList[k] = tmpProduct.(types.TagProduct).ProductId + mapTagLevel[topPrefix].TagProductList = append(mapTagLevel[topPrefix].TagProductList, tmpProduct) + } + } //最终值提取最高级别那一层出来 rspList := make([]types.TagItem, 0, len(mapTagLevel)) for prefix, _ := range mapTop { @@ -326,12 +339,10 @@ func (l *GetTagProductListLogic) getTagProducts(req getTagProductsReq) (productL ProductId: productInfo.Id, Sn: *productInfo.Sn, Title: *productInfo.Title, - Intro: *productInfo.Intro, - IsEnv: *productInfo.IsProtection, - IsMicro: *productInfo.IsMicrowave, SizeNum: uint32(sizeNum), MinPrice: minPrice, HaveOptionalFitting: haveOptionalFitting, + Recommended: *productInfo.IsRecommend > 0, } //千人千面处理 r := image.ThousandFaceImageFormatReq{ @@ -348,7 +359,6 @@ func (l *GetTagProductListLogic) getTagProducts(req getTagProductsReq) (productL } image.ThousandFaceImageFormat(&r) item.Cover = r.Cover - item.CoverImg = r.CoverImg item.CoverDefault = r.CoverDefault //加入分类产品切片 productListRsp = append(productListRsp, item) diff --git a/server/product/internal/types/types.go b/server/product/internal/types/types.go index 8109fec5..d995f714 100644 --- a/server/product/internal/types/types.go +++ b/server/product/internal/types/types.go @@ -258,15 +258,13 @@ type GetTagProductListRsp struct { } type TagItem struct { - TypeName string `json:"type_name"` - TypeId int64 `json:"type_id"` - Description string `json:"description"` - Level int64 `json:"level"` - LevelPrefix string `json:"level_prefix"` - Icon string `json:"icon"` - Sort int64 `json:"sort"` - TagProductList []TagProduct `json:"tag_product_list"` //分类下的产品 - ChildTagList []*TagItem `json:"child_tag_list"` + TypeName string `json:"type_name"` + TypeId int64 `json:"type_id"` + Icon string `json:"icon"` + Sort int64 `json:"sort"` + LevelPrefix string `json:"level_prefix"` + TagProductList []interface{} `json:"tag_product_list"` //分类下的产品 + ChildTagList []*TagItem `json:"child_tag_list"` } type TagProduct struct { @@ -274,14 +272,11 @@ type TagProduct struct { Sn string `json:"sn"` Title string `json:"title"` Cover string `json:"cover"` - Intro string `json:"intro"` - CoverImg string `json:"cover_img"` - IsEnv int64 `json:"is_env"` - IsMicro int64 `json:"is_micro"` SizeNum uint32 `json:"size_num"` MinPrice int64 `json:"min_price"` CoverDefault string `json:"cover_default"` HaveOptionalFitting bool `json:"have_optional_fitting"` + Recommended bool `json:"recommended"` } type GetRenderDesignReq struct { diff --git a/server_api/product.api b/server_api/product.api index a7160506..cef01f26 100644 --- a/server_api/product.api +++ b/server_api/product.api @@ -308,29 +308,24 @@ type GetTagProductListRsp { TagList []TagItem `json:"tag_list"` } type TagItem { - TypeName string `json:"type_name"` - TypeId int64 `json:"type_id"` - Description string `json:"description"` - Level int64 `json:"level"` - LevelPrefix string `json:"level_prefix"` - Icon string `json:"icon"` - Sort int64 `json:"sort"` - TagProductList []TagProduct `json:"tag_product_list"` //分类下的产品 - ChildTagList []*TagItem `json:"child_tag_list"` + TypeName string `json:"type_name"` + TypeId int64 `json:"type_id"` + Icon string `json:"icon"` + Sort int64 `json:"sort"` + LevelPrefix string `json:"level_prefix"` + TagProductList []interface{} `json:"tag_product_list"` //分类下的产品 + ChildTagList []*TagItem `json:"child_tag_list"` } type TagProduct { ProductId int64 `json:"product_id"` Sn string `json:"sn"` Title string `json:"title"` Cover string `json:"cover"` - Intro string `json:"intro"` - CoverImg string `json:"cover_img"` - IsEnv int64 `json:"is_env"` - IsMicro int64 `json:"is_micro"` SizeNum uint32 `json:"size_num"` MinPrice int64 `json:"min_price"` CoverDefault string `json:"cover_default"` HaveOptionalFitting bool `json:"have_optional_fitting"` + Recommended bool `json:"recommended"` } //获取云渲染设计方案信息 type GetRenderDesignReq { From fd9e30ea74ec56c13a1072626ef7d2b68a2476c2 Mon Sep 17 00:00:00 2001 From: Hiven Date: Mon, 24 Jul 2023 18:04:24 +0800 Subject: [PATCH 05/68] =?UTF-8?q?=E8=AE=A2=E5=8D=95=E5=88=97=E8=A1=A8--?= =?UTF-8?q?=E5=AE=8C=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../gmodel/fs_order_detail_template_logic.go | 4 + model/gmodel/fs_order_logic.go | 18 +- model/gmodel/fs_product_design_logic.go | 4 + .../internal/logic/userorderlistlogic.go | 169 ++++++++++++++---- server/home-user-auth/internal/types/types.go | 38 ++-- server_api/home-user-auth.api | 74 ++++---- utils/order/order_status.go | 8 +- 7 files changed, 217 insertions(+), 98 deletions(-) diff --git a/model/gmodel/fs_order_detail_template_logic.go b/model/gmodel/fs_order_detail_template_logic.go index a4a1cac0..cbdcd360 100755 --- a/model/gmodel/fs_order_detail_template_logic.go +++ b/model/gmodel/fs_order_detail_template_logic.go @@ -25,3 +25,7 @@ func (dt *FsOrderDetailTemplateModel) FindOne(ctx context.Context, id int64) (re err = dt.db.WithContext(ctx).Model(&FsOrderDetailTemplate{}).Where("`id` = ?", id).Take(&resp).Error return resp, err } + +func (m *FsOrderDetailTemplateModel) TableName() string { + return m.name +} diff --git a/model/gmodel/fs_order_logic.go b/model/gmodel/fs_order_logic.go index d63c2e80..93f37a94 100755 --- a/model/gmodel/fs_order_logic.go +++ b/model/gmodel/fs_order_logic.go @@ -77,7 +77,7 @@ func (o *FsOrderModel) FindPageListByPage(ctx context.Context, rowBuilder *gorm. rowBuilder = rowBuilder.Scopes(handler.Paginate(page, pageSize)) // 结果 - result := rowBuilder.WithContext(ctx).Find(&resp) + result := rowBuilder.Debug().WithContext(ctx).Find(&resp) if result.Error != nil { return nil, result.Error } else { @@ -93,8 +93,20 @@ type FsOrderRel struct { type FsOrderDetails struct { FsOrderDetail - FsOrderDetailTemplateInfo FsOrderDetailTemplate `gorm:"foreignKey:id;references:order_detail_template_id"` - FsProductInfo FsProduct `gorm:"foreignKey:id;references:product_id"` + FsOrderDetailTemplateInfo FsOrderDetailTemplateInfo `gorm:"foreignKey:id;references:order_detail_template_id"` + FsProductInfo FsProduct `gorm:"foreignKey:id;references:product_id"` +} + +type FsOrderDetailTemplateInfo struct { + FsOrderDetailTemplate + FsProductDesignInfo FsProductDesignInfo `gorm:"foreignKey:id;references:design_id"` //获取设计数据 + FsProductSizeInfo FsProductSize `gorm:"foreignKey:id;references:size_id"` +} + +type FsProductDesignInfo struct { + FsProductDesign + OptionData FsProduct `gorm:"foreignKey:id;references:optional_id"` //获取配件信息 + TemplateData FsProductTemplateV2 `gorm:"foreignKey:id;references:template_id"` //获取模板信息 } func (m *FsOrderModel) RowSelectBuilder(selectData []string) *gorm.DB { diff --git a/model/gmodel/fs_product_design_logic.go b/model/gmodel/fs_product_design_logic.go index 29022eb8..a1b4fe62 100755 --- a/model/gmodel/fs_product_design_logic.go +++ b/model/gmodel/fs_product_design_logic.go @@ -34,3 +34,7 @@ func (d *FsProductDesignModel) Create(ctx context.Context, data *FsProductDesign func (d *FsProductDesignModel) UpdateBySn(ctx context.Context, sn string, data *FsProductDesign) error { return d.db.WithContext(ctx).Model(&FsProductDesign{}).Where("`sn` = ?", sn).Updates(&data).Error } + +func (m *FsProductDesignModel) TableName() string { + return m.name +} diff --git a/server/home-user-auth/internal/logic/userorderlistlogic.go b/server/home-user-auth/internal/logic/userorderlistlogic.go index cfe0df2c..c3a8b066 100644 --- a/server/home-user-auth/internal/logic/userorderlistlogic.go +++ b/server/home-user-auth/internal/logic/userorderlistlogic.go @@ -8,6 +8,8 @@ import ( "fusenapi/utils/auth" "fusenapi/utils/basic" "fusenapi/utils/configs" + "fusenapi/utils/image" + "strings" "fusenapi/utils/format" "fusenapi/utils/order" @@ -41,10 +43,15 @@ func (l *UserOrderListLogic) UserOrderList(req *types.UserOrderListReq, userinfo // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) // userinfo 传入值时, 一定不为null - // 测试 - userinfo.UserId = 39 + size := req.Size + + if size > 0 { + size = int64(image.GetCurrentSize(uint32(size))) + } orderDetailModel := gmodel.NewFsOrderDetailModel(l.svcCtx.MysqlConn) + orderDetailTemplateModel := gmodel.NewFsOrderDetailTemplateModel(l.svcCtx.MysqlConn) + fsProductDesignModel := gmodel.NewFsProductDesignModel(l.svcCtx.MysqlConn) orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn) rowBuilder := orderModel.RowSelectBuilder(nil) if userinfo == nil || userinfo.UserId == 0 { @@ -55,10 +62,39 @@ func (l *UserOrderListLogic) UserOrderList(req *types.UserOrderListReq, userinfo var page = req.Page var pageSize = req.PageSize var listRes []*gmodel.FsOrderRel - rowBuilder = rowBuilder.Where("user_id =?", userinfo.UserId) + rowBuilder = rowBuilder.Where("user_id =?", userinfo.UserId).Where("status <> ?", constants.STATUS_NEW_NOT_PAY).Where("status <>?", constants.STATUS_NEW_DELETE) + // 根据时间来查询不同范围的订单 + switch req.Time { + case 1: + rowBuilder = rowBuilder.Where("ctime >?", time.Now().AddDate(0, -1, 0).Unix()) + case 2: + rowBuilder = rowBuilder.Where("ctime >?", time.Now().AddDate(0, -3, 0).Unix()) + case 3: + rowBuilder = rowBuilder.Where("ctime >?", time.Now().AddDate(0, -6, 0).Unix()) + case 4: + rowBuilder = rowBuilder.Where("ctime >?", time.Now().AddDate(-1, 0, 0).Unix()) + default: + } + + //按照订单状态查询不同的订单 if req.Status != -1 { - rowBuilder = rowBuilder.Where("status = ?", req.Status) + switch req.Status { + case 1: + rowBuilder = rowBuilder.Where("status in ?", [3]constants.Order{constants.STATUS_NEW_PART_PAY, constants.STATUS_NEW_PAY_COMPLETED, constants.STATUS_NEW_SURE}) + case 2: + rowBuilder = rowBuilder.Where("status in ?", [2]constants.Order{constants.STATUS_NEW_PRODUTING, constants.STATUS_NEW_PRODUT_COMPLETED}) + case 3: + rowBuilder = rowBuilder.Where("status in ?", [2]constants.Order{constants.STATUS_NEW_DELIVER, constants.STATUS_NEW_UPS}) + case 4: + rowBuilder = rowBuilder.Where("status =?", constants.STATUS_NEW_ARRIVAL) + case 5: + rowBuilder = rowBuilder.Where("status =?", constants.STATUS_NEW_COMPLETED).Where("delivery_method =?", constants.DELIVERY_METHOD_ADDRESS) + case 7: + rowBuilder = rowBuilder.Where("status in ?", [3]constants.Order{constants.STATUS_NEW_CANCEL, constants.STATUS_NEW_REFUNDED, constants.STATUS_NEW_REFUNDING}) + case 8: + rowBuilder = rowBuilder.Where("status =?", constants.STATUS_NEW_COMPLETED).Where("delivery_method =?", constants.DELIVERY_METHOD_CLOUD) + } } // 查询总数 @@ -74,7 +110,11 @@ func (l *UserOrderListLogic) UserOrderList(req *types.UserOrderListReq, userinfo // 查询数据 if total > 0 { rowBuilder = rowBuilder.Preload("FsOrderAffiliateInfo").Preload("FsOrderDetails", func(dbPreload *gorm.DB) *gorm.DB { - return dbPreload.Table(orderDetailModel.TableName()).Preload("FsOrderDetailTemplateInfo").Preload("FsProductInfo") + return dbPreload.Table(orderDetailModel.TableName()).Preload("FsOrderDetailTemplateInfo", func(dbPreload *gorm.DB) *gorm.DB { + return dbPreload.Table(orderDetailTemplateModel.TableName()).Preload("FsProductDesignInfo", func(dbPreload *gorm.DB) *gorm.DB { + return dbPreload.Table(fsProductDesignModel.TableName()).Preload("OptionData").Preload("TemplateData") + }).Preload("FsProductSizeInfo") + }).Preload("FsProductInfo") }) listRes, err = orderModel.FindPageListByPage(l.ctx, rowBuilder, &page, &pageSize, nil, "") } @@ -112,7 +152,7 @@ func (l *UserOrderListLogic) UserOrderList(req *types.UserOrderListReq, userinfo var pcsBox int64 var pcs int64 - var productList []*types.Product + var productList []types.Product var surplusAt int64 @@ -124,31 +164,51 @@ func (l *UserOrderListLogic) UserOrderList(req *types.UserOrderListReq, userinfo } } - //fsOrderAffiliateInfo := item.FsOrderAffiliateInfo - fmt.Println(orderTimeConfig) - var getOrderStatusAndLogisticsReq = order.GetOrderStatusAndLogisticsReq{ - OrderStatus: 1, - DeliveryMethod: 1, - // IsPayCompleted: *item.IsAllProductCompleted, - // SureTime: *fsOrderAffiliateInfo.SureTime, - // ProductTime: *fsOrderAffiliateInfo.SureTime, - // ProductEndtime: *fsOrderAffiliateInfo.SureTime, - // DeliverTime: *fsOrderAffiliateInfo.SureTime, - // UpsDeliverTime: *fsOrderAffiliateInfo.SureTime, - // UpsTime: *fsOrderAffiliateInfo.SureTime, - // ArrivalTime: *fsOrderAffiliateInfo.SureTime, - // RecevieTime: *fsOrderAffiliateInfo.SureTime, + fsOrderAffiliateInfo := item.FsOrderAffiliateInfo - // // OrderCtime: *item.Ctime, - // WebSetTimeInfo: orderTimeConfig, + var sureTime int64 + var productTime int64 + var ProductEndtime int64 + var deliverTime int64 + var upsDeliverTime int64 + var upsTime int64 + var arrivalTime int64 + var recevieTime int64 + if fsOrderAffiliateInfo.Id > 0 { + sureTime = *fsOrderAffiliateInfo.SureTime + productTime = *fsOrderAffiliateInfo.ProductTime + ProductEndtime = *fsOrderAffiliateInfo.ProductEndtime + deliverTime = *fsOrderAffiliateInfo.DeliverTime + upsDeliverTime = *fsOrderAffiliateInfo.UpsDeliverTime + upsTime = *fsOrderAffiliateInfo.UpsTime + arrivalTime = *fsOrderAffiliateInfo.ArrivalTime + recevieTime = *fsOrderAffiliateInfo.RecevieTime + } + + var getOrderStatusAndLogisticsReq = order.GetOrderStatusAndLogisticsReq{ + OrderStatus: constants.Order(*item.Status), + DeliveryMethod: constants.DeliveryMethod(*item.DeliveryMethod), + IsPayCompleted: *item.IsAllProductCompleted, + OrderCtime: *item.Ctime, + + SureTime: sureTime, + ProductTime: productTime, + ProductEndtime: ProductEndtime, + DeliverTime: deliverTime, + UpsDeliverTime: upsDeliverTime, + UpsTime: upsTime, + ArrivalTime: arrivalTime, + RecevieTime: recevieTime, + + WebSetTimeInfo: orderTimeConfig, } statusAndLogisticsRes := order.GetOrderStatusAndLogistics(getOrderStatusAndLogisticsReq) // 流程控制 - statusTime := make([]*types.StatusTime, 5) + var statusTime []types.StatusTime for _, itemTimes := range statusAndLogisticsRes.Times { - statusTime = append(statusTime, &types.StatusTime{ + statusTime = append(statusTime, types.StatusTime{ Key: itemTimes.Key, Time: itemTimes.Time, }) @@ -157,8 +217,10 @@ func (l *UserOrderListLogic) UserOrderList(req *types.UserOrderListReq, userinfo pbData.LogisticsStatus = int64(statusAndLogisticsRes.LogisticsStatus) pbData.Status = int64(statusAndLogisticsRes.OrderStatus) + var isStopMax int64 if len(item.FsOrderDetails) > 0 { for _, fsOrderDetailItem := range item.FsOrderDetails { + fsOrderDetailBuyNum := *fsOrderDetailItem.FsOrderDetail.BuyNum fsOrderDetailEachBoxNum := *fsOrderDetailItem.FsOrderDetailTemplateInfo.EachBoxNum pcs = pcs + fsOrderDetailBuyNum @@ -169,23 +231,58 @@ func (l *UserOrderListLogic) UserOrderList(req *types.UserOrderListReq, userinfo } pcsBox = pcsBox + pcsBoxNum + csBoxNumF - var product types.Product - product.Cover = *fsOrderDetailItem.Cover - product.Fitting = *fsOrderDetailItem.OptionalTitle - product.OptionPrice = *fsOrderDetailItem.OptionPrice - product.OrderDetailTemplateId = *fsOrderDetailItem.OrderDetailTemplateId - product.OrderId = *fsOrderDetailItem.OrderId - product.Pcs = fsOrderDetailBuyNum - product.PcsBox = pcsBox - product.Price = *fsOrderDetailItem.FsOrderDetail.Amount - product.ProductId = *fsOrderDetailItem.OptionPrice - product.Title = *fsOrderDetailItem.FsProductInfo.Title + productCover := *fsOrderDetailItem.Cover + // 尺寸 + if size >= 200 { + coverArr := strings.Split(*fsOrderDetailItem.Cover, ".") + if len(coverArr) < 2 { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "cover split slice item count is less than 2") + } + productCover = fmt.Sprintf("%s_%d.%s", coverArr[0], req.Size, coverArr[1]) + } - productList = append(productList, &product) + // 判断stop + var isStop int64 + if fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductDesignInfo.OptionData.Id != 0 { + // 尺寸或者模板下架 + if fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id != 0 { + isStop = 1 + } else { + isStop = 3 + } + } else { + if fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id != 0 { + isStop = 1 + } + } + + // 判断产品是否下架 + if *fsOrderDetailItem.FsProductInfo.IsShelf == 0 || *fsOrderDetailItem.FsProductInfo.IsDel == 1 { + isStop = 2 + } + if isStop > isStopMax { + isStopMax = isStop + } + + productList = append(productList, types.Product{ + Cover: productCover, + Fitting: *fsOrderDetailItem.OptionalTitle, + OptionPrice: *fsOrderDetailItem.OptionPrice, + OrderDetailTemplateId: *fsOrderDetailItem.OrderDetailTemplateId, + OrderId: *fsOrderDetailItem.OrderId, + Pcs: fsOrderDetailBuyNum, + PcsBox: pcsBox, + Price: *fsOrderDetailItem.FsOrderDetail.Amount, + ProductId: *fsOrderDetailItem.OptionPrice, + Title: *fsOrderDetailItem.FsProductInfo.Title, + Size: *fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductSizeInfo.Capacity, + IsStop: isStop, + }) } pbData.ProductList = productList } + pbData.IsStop = isStopMax pbData.PcsBox = pcsBox pbData.Pcs = pcs pbData.SurplusAt = surplusAt diff --git a/server/home-user-auth/internal/types/types.go b/server/home-user-auth/internal/types/types.go index cdb5446a..ef269467 100644 --- a/server/home-user-auth/internal/types/types.go +++ b/server/home-user-auth/internal/types/types.go @@ -29,25 +29,25 @@ type UserOrderListRsp struct { } type Items struct { - ID int64 `json:"id"` - Sn string `json:"sn"` - UserID int64 `json:"user_id"` - TotalAmount int64 `json:"total_amount"` - Ctime string `json:"ctime"` - Status int64 `json:"status"` - DeliveryMethod int64 `json:"delivery_method"` - TsTime string `json:"ts_time"` - IsPayCompleted int64 `json:"is_pay_completed"` - DeliverSn string `json:"deliver_sn"` - PcsBox int64 `json:"pcs_box"` - Pcs int64 `json:"pcs"` - SurplusAt int64 `json:"surplus_at"` - LogisticsStatus int64 `json:"logistics_status"` - StatusTimes []*StatusTime `json:"status_times"` - Deposit int64 `json:"deposit"` - Remaining int64 `json:"remaining"` - ProductList []*Product `json:"productList"` - IsStop int64 `json:"is_stop"` + ID int64 `json:"id"` + Sn string `json:"sn"` + UserID int64 `json:"user_id"` + TotalAmount int64 `json:"total_amount"` + Ctime string `json:"ctime"` + Status int64 `json:"status"` + DeliveryMethod int64 `json:"delivery_method"` + TsTime string `json:"ts_time"` + IsPayCompleted int64 `json:"is_pay_completed"` + DeliverSn string `json:"deliver_sn"` + PcsBox int64 `json:"pcs_box"` + Pcs int64 `json:"pcs"` + SurplusAt int64 `json:"surplus_at"` + LogisticsStatus int64 `json:"logistics_status"` + StatusTimes []StatusTime `json:"status_times"` + Deposit int64 `json:"deposit"` + Remaining int64 `json:"remaining"` + ProductList []Product `json:"productList"` + IsStop int64 `json:"is_stop"` } type StatusTime struct { diff --git a/server_api/home-user-auth.api b/server_api/home-user-auth.api index fdc7594e..f3a19304 100644 --- a/server_api/home-user-auth.api +++ b/server_api/home-user-auth.api @@ -10,60 +10,60 @@ info ( import "basic.api" service home-user-auth { - + // @handler UserRegisterHandler // post /api/user/register(RequestUserRegister) returns (response); - + @handler UserLoginHandler post /api/user/login(RequestUserLogin) returns (response); - + @handler AcceptCookieHandler post /api/user/accept-cookie(request) returns (response); - + @handler UserFontsHandler get /api/user/fonts(request) returns (response); - + @handler UserGetTypeHandler get /api/user/get-type(request) returns (response); - + @handler UserSaveBasicInfoHandler post /api/user/basic-info(RequestBasicInfoForm) returns (response); - + @handler UserStatusConfigHandler get /api/user/status-config(request) returns (response); - + @handler UserBasicInfoHandler get /api/user/basic-info(request) returns (response); - + @handler UserAddressListHandler get /api/user/address-list(request) returns (response); - + @handler UserAddAddressHandler post /api/user/add-address(RequestAddAddress) returns (response); - + @handler UserContactServiceHandler post /api/user/contact-service (RequestContactService) returns (response); - + // @handler UserOderListHandler // get /api/user/order-list(RequestOrderId) returns (response); - + @handler UserOderDeleteHandler post /api/user/order-delete(RequestOrderId) returns (response); - + @handler UserGoogleLoginHandler get /api/user/oauth2/login/google(RequestGoogleLogin) returns (response); - + @handler UserEmailRegisterHandler get /api/user/oauth2/login/register(RequestEmailRegister) returns (response); - + //订单列表 @handler UserOrderListHandler get /api/user/order-list (UserOrderListReq) returns (response); - + //取消订单 @handler UserOrderCancelHandler get /api/user/order-cancel (UserOrderCancelReq) returns (response); - + } //取消订单 @@ -95,25 +95,25 @@ type ( ) type Items { - ID int64 `json:"id"` - Sn string `json:"sn"` - UserID int64 `json:"user_id"` - TotalAmount int64 `json:"total_amount"` - Ctime string `json:"ctime"` - Status int64 `json:"status"` - DeliveryMethod int64 `json:"delivery_method"` - TsTime string `json:"ts_time"` - IsPayCompleted int64 `json:"is_pay_completed"` - DeliverSn string `json:"deliver_sn"` - PcsBox int64 `json:"pcs_box"` - Pcs int64 `json:"pcs"` - SurplusAt int64 `json:"surplus_at"` - LogisticsStatus int64 `json:"logistics_status"` - StatusTimes []*StatusTime `json:"status_times"` - Deposit int64 `json:"deposit"` - Remaining int64 `json:"remaining"` - ProductList []*Product `json:"productList"` - IsStop int64 `json:"is_stop"` + ID int64 `json:"id"` + Sn string `json:"sn"` + UserID int64 `json:"user_id"` + TotalAmount int64 `json:"total_amount"` + Ctime string `json:"ctime"` + Status int64 `json:"status"` + DeliveryMethod int64 `json:"delivery_method"` + TsTime string `json:"ts_time"` + IsPayCompleted int64 `json:"is_pay_completed"` + DeliverSn string `json:"deliver_sn"` + PcsBox int64 `json:"pcs_box"` + Pcs int64 `json:"pcs"` + SurplusAt int64 `json:"surplus_at"` + LogisticsStatus int64 `json:"logistics_status"` + StatusTimes []StatusTime `json:"status_times"` + Deposit int64 `json:"deposit"` + Remaining int64 `json:"remaining"` + ProductList []Product `json:"productList"` + IsStop int64 `json:"is_stop"` } type StatusTime { diff --git a/utils/order/order_status.go b/utils/order/order_status.go index 51bc8351..8198e6d4 100644 --- a/utils/order/order_status.go +++ b/utils/order/order_status.go @@ -38,7 +38,7 @@ type GetOrderStatusAndLogisticsReq struct { DeliveryMethod constants.DeliveryMethod IsPayCompleted int64 OrderCtime int64 - + SureTime int64 ProductTime int64 ProductEndtime int64 @@ -48,7 +48,6 @@ type GetOrderStatusAndLogisticsReq struct { ArrivalTime int64 RecevieTime int64 - WebSetTimeInfo configs.WebSetTimeInfo } @@ -72,11 +71,11 @@ func GetOrderStatusAndLogistics(req GetOrderStatusAndLogisticsReq) (res GetOrder times := make([]GetOrderStatusAndLogisticsResTimes, 5) m := 1 for i := 0; i < 5; i++ { - m++ times[i] = GetOrderStatusAndLogisticsResTimes{ Key: m, Time: "", } + m++ } switch req.OrderStatus { @@ -162,6 +161,9 @@ func GetOrderStatusAndLogistics(req GetOrderStatusAndLogisticsReq) (res GetOrder res.Times = times } else { timesData := times[0:3] + if logisticsStatus == constants.LOGISTICS_STATUS_DRAW { + timesData[1].Time = format.TimeIntToFormat(req.OrderCtime + req.WebSetTimeInfo.ProductDay*daySecond) + } res.Times = timesData } return res From fc598402358f08b192c4c17c2852d4db67adcdd1 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 24 Jul 2023 18:08:19 +0800 Subject: [PATCH 06/68] fix --- .../internal/logic/homepagerecommendproductlistlogic.go | 6 +----- server/product/internal/types/types.go | 6 +----- server_api/product.api | 6 +----- 3 files changed, 3 insertions(+), 15 deletions(-) diff --git a/server/product/internal/logic/homepagerecommendproductlistlogic.go b/server/product/internal/logic/homepagerecommendproductlistlogic.go index 60c4cdb0..899de460 100644 --- a/server/product/internal/logic/homepagerecommendproductlistlogic.go +++ b/server/product/internal/logic/homepagerecommendproductlistlogic.go @@ -146,12 +146,9 @@ func (l *HomePageRecommendProductListLogic) HomePageRecommendProductList(req *ty haveOptionalFitting = true } item := types.HomePageRecommendProductListRsp{ - ProductId: productInfo.Id, + Id: productInfo.Id, Sn: *productInfo.Sn, Title: *productInfo.Title, - Intro: *productInfo.Intro, - IsEnv: *productInfo.IsProtection, - IsMicro: *productInfo.IsMicrowave, SizeNum: uint32(sizeNum), MinPrice: minPrice, HaveOptionalFitting: haveOptionalFitting, @@ -171,7 +168,6 @@ func (l *HomePageRecommendProductListLogic) HomePageRecommendProductList(req *ty } image.ThousandFaceImageFormat(&r) item.Cover = r.Cover - item.CoverImg = r.CoverImg item.CoverDefault = r.CoverDefault //加入分类产品切片 listRsp = append(listRsp, item) diff --git a/server/product/internal/types/types.go b/server/product/internal/types/types.go index d995f714..f2d27f0a 100644 --- a/server/product/internal/types/types.go +++ b/server/product/internal/types/types.go @@ -387,14 +387,10 @@ type HomePageRecommendProductListReq struct { } type HomePageRecommendProductListRsp struct { - ProductId int64 `json:"product_id"` + Id int64 `json:"id"` Sn string `json:"sn"` Title string `json:"title"` Cover string `json:"cover"` - Intro string `json:"intro"` - CoverImg string `json:"cover_img"` - IsEnv int64 `json:"is_env"` - IsMicro int64 `json:"is_micro"` SizeNum uint32 `json:"size_num"` MinPrice int64 `json:"min_price"` CoverDefault string `json:"cover_default"` diff --git a/server_api/product.api b/server_api/product.api index cef01f26..48ac5a50 100644 --- a/server_api/product.api +++ b/server_api/product.api @@ -429,14 +429,10 @@ type HomePageRecommendProductListReq { Size uint32 `form:"size"` } type HomePageRecommendProductListRsp { - ProductId int64 `json:"product_id"` + Id int64 `json:"id"` Sn string `json:"sn"` Title string `json:"title"` Cover string `json:"cover"` - Intro string `json:"intro"` - CoverImg string `json:"cover_img"` - IsEnv int64 `json:"is_env"` - IsMicro int64 `json:"is_micro"` SizeNum uint32 `json:"size_num"` MinPrice int64 `json:"min_price"` CoverDefault string `json:"cover_default"` From 148e0681ecc8f56ec25cab2a2219e8bda42bb248 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 24 Jul 2023 18:28:58 +0800 Subject: [PATCH 07/68] fix --- server/product/internal/logic/gettagproductlistlogic.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/product/internal/logic/gettagproductlistlogic.go b/server/product/internal/logic/gettagproductlistlogic.go index 2ecc63b3..27ce7ba5 100644 --- a/server/product/internal/logic/gettagproductlistlogic.go +++ b/server/product/internal/logic/gettagproductlistlogic.go @@ -100,7 +100,7 @@ func (l *GetTagProductListLogic) GetTagProductList(req *types.GetTagProductListR IsDel: &pIsDel, IsShelf: &pIsShelf, Status: &pStatus, - OrderBy: "`sort` DESC", + OrderBy: "`is_recommend` DESC,`sort` ASC", }) if err != nil { logx.Error(err) From b28fefdb0ee62e4de56e099db0134e90323a7af8 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 24 Jul 2023 18:39:27 +0800 Subject: [PATCH 08/68] fix --- .../internal/logic/getorderdetaillogic.go | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/server/orders/internal/logic/getorderdetaillogic.go b/server/orders/internal/logic/getorderdetaillogic.go index 966decc3..fc6e72f7 100644 --- a/server/orders/internal/logic/getorderdetaillogic.go +++ b/server/orders/internal/logic/getorderdetaillogic.go @@ -204,16 +204,22 @@ func (l *GetOrderDetailLogic) GetOrderDetail(req *types.GetOrderDetailReq, useri } //首款 if payIndex, ok := mapPay[1]; ok { - data.PayInfo.Deposit = types.Deposit{ - Method: *payList[payIndex].Brand, - TransNo: *payList[payIndex].TradeNo, + data.PayInfo = &types.PayInfo{ + Deposit: types.Deposit{ + Method: *payList[payIndex].Brand, + TransNo: *payList[payIndex].TradeNo, + }, + Final: types.Deposit{}, } } //尾款 if payIndex, ok := mapPay[2]; ok { - data.PayInfo.Final = types.Deposit{ - Method: *payList[payIndex].Brand, - TransNo: *payList[payIndex].TradeNo, + data.PayInfo = &types.PayInfo{ + Deposit: types.Deposit{}, + Final: types.Deposit{ + Method: *payList[payIndex].Brand, + TransNo: *payList[payIndex].TradeNo, + }, } } return resp.SetStatusWithMessage(basic.CodeOK, "success", data) From 25c3de6b990ea57814e6ca1a91de7956502bf4bf Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 24 Jul 2023 19:16:38 +0800 Subject: [PATCH 09/68] fix --- .../internal/logic/getorderdetaillogic.go | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/server/orders/internal/logic/getorderdetaillogic.go b/server/orders/internal/logic/getorderdetaillogic.go index fc6e72f7..72153f67 100644 --- a/server/orders/internal/logic/getorderdetaillogic.go +++ b/server/orders/internal/logic/getorderdetaillogic.go @@ -202,24 +202,19 @@ func (l *GetOrderDetailLogic) GetOrderDetail(req *types.GetOrderDetailReq, useri IsDefault: *addressInfo.IsDefault, } } + data.PayInfo = &types.PayInfo{} //首款 if payIndex, ok := mapPay[1]; ok { - data.PayInfo = &types.PayInfo{ - Deposit: types.Deposit{ - Method: *payList[payIndex].Brand, - TransNo: *payList[payIndex].TradeNo, - }, - Final: types.Deposit{}, + data.PayInfo.Deposit = types.Deposit{ + Method: *payList[payIndex].Brand, + TransNo: *payList[payIndex].TradeNo, } } //尾款 if payIndex, ok := mapPay[2]; ok { - data.PayInfo = &types.PayInfo{ - Deposit: types.Deposit{}, - Final: types.Deposit{ - Method: *payList[payIndex].Brand, - TransNo: *payList[payIndex].TradeNo, - }, + data.PayInfo.Final = types.Deposit{ + Method: *payList[payIndex].Brand, + TransNo: *payList[payIndex].TradeNo, } } return resp.SetStatusWithMessage(basic.CodeOK, "success", data) From 5fadf0697d8ff1f353eab3339d35cb6692d5409e Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 24 Jul 2023 19:44:28 +0800 Subject: [PATCH 10/68] fix --- constants/websocket.go | 11 ++++++ .../internal/handler/datatransferhandler.go | 35 ++++++++++++++++--- 2 files changed, 41 insertions(+), 5 deletions(-) create mode 100644 constants/websocket.go diff --git a/constants/websocket.go b/constants/websocket.go new file mode 100644 index 00000000..95bea53d --- /dev/null +++ b/constants/websocket.go @@ -0,0 +1,11 @@ +package constants + +type websocket string + +// websocket消息类型 +const ( + //ws连接成功 + WEBSOCKET_CONNECT_SUCCESS = "connect-success" + //图片渲染 + WEBSOCKET_RENDER_IMAGE = "render-image" +) diff --git a/server/websocket/internal/handler/datatransferhandler.go b/server/websocket/internal/handler/datatransferhandler.go index 4534d041..e1458960 100644 --- a/server/websocket/internal/handler/datatransferhandler.go +++ b/server/websocket/internal/handler/datatransferhandler.go @@ -1,10 +1,17 @@ package handler import ( + "encoding/json" + "fusenapi/constants" "fusenapi/server/websocket/internal/svc" + "fusenapi/server/websocket/internal/types" + "fusenapi/utils/auth" + "github.com/google/uuid" "github.com/gorilla/websocket" + "github.com/zeromicro/go-zero/core/logx" "net/http" "sync" + "time" ) var ( @@ -19,14 +26,15 @@ var ( mapConn = sync.Map{} ) +// 每个连接的连接属性 type wsConnectItem struct { conn *websocket.Conn //websocket的连接 - renImage sync.Map //需要渲染的图片 + property interface{} //属性 } func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - /*// 解析JWT token,并对空用户进行判断 + // 解析JWT token,并对空用户进行判断 claims, err := svcCtx.ParseJwtToken(r) // 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息 if err != nil { @@ -34,10 +42,9 @@ func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { w.Write([]byte("connect failed:unauthorized")) return } - var userInfo *auth.UserInfo if claims != nil { // 从token中获取对应的用户信息 - userInfo, err = auth.GetUserInfoFormMapClaims(claims) + _, err = auth.GetUserInfoFormMapClaims(claims) // 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息 if err != nil { return @@ -53,6 +60,24 @@ func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { logx.Error("http upgrade websocket err:", err) w.Write([]byte("http upgrade websocket err")) return - }*/ + } + //生成连接唯一标识 + uniqueId := uuid.New().String() + time.Now().Format("20060102150405") + c := wsConnectItem{ + conn: conn, + } + //保存连接 + mapConn.Store(uniqueId, c) + //把uniqueId传回去 + rsp := types.DataTransferRsp{ + MsgType: constants.WEBSOCKET_CONNECT_SUCCESS, + Message: uniqueId, + } + b, _ := json.Marshal(rsp) + conn.WriteMessage(websocket.TextMessage, b) } } + +func (w *wsConnectItem) Readloop() { + +} From a4164dbdf6da0c2b52ead4ba3396fb475df338a6 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 25 Jul 2023 12:06:19 +0800 Subject: [PATCH 11/68] fix --- constants/websocket.go | 4 + server/websocket/etc/websocket.yaml | 2 +- server/websocket/internal/config/config.go | 5 +- .../internal/handler/datatransferhandler.go | 128 ++++++++++++++---- 4 files changed, 114 insertions(+), 25 deletions(-) diff --git a/constants/websocket.go b/constants/websocket.go index 95bea53d..7fca9751 100644 --- a/constants/websocket.go +++ b/constants/websocket.go @@ -4,8 +4,12 @@ type websocket string // websocket消息类型 const ( + //鉴权失败 + WEBSOCKET_UNAUTH = "unAuth" //ws连接成功 WEBSOCKET_CONNECT_SUCCESS = "connect-success" + //心跳信息 + WEBSOCKET_HEARTBEAT = "heartbeat" //图片渲染 WEBSOCKET_RENDER_IMAGE = "render-image" ) diff --git a/server/websocket/etc/websocket.yaml b/server/websocket/etc/websocket.yaml index d22f03a7..7d2b68d7 100644 --- a/server/websocket/etc/websocket.yaml +++ b/server/websocket/etc/websocket.yaml @@ -1,6 +1,6 @@ Name: websocket Host: 0.0.0.0 -Port: 8888 +Port: 9914 SourceMysql: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest Auth: AccessSecret: fusen2023 diff --git a/server/websocket/internal/config/config.go b/server/websocket/internal/config/config.go index b24bb7d7..85ee62f1 100644 --- a/server/websocket/internal/config/config.go +++ b/server/websocket/internal/config/config.go @@ -1,6 +1,9 @@ package config -import "github.com/zeromicro/go-zero/rest" +import ( + "fusenapi/server/websocket/internal/types" + "github.com/zeromicro/go-zero/rest" +) type Config struct { rest.RestConf diff --git a/server/websocket/internal/handler/datatransferhandler.go b/server/websocket/internal/handler/datatransferhandler.go index e1458960..96a65455 100644 --- a/server/websocket/internal/handler/datatransferhandler.go +++ b/server/websocket/internal/handler/datatransferhandler.go @@ -2,6 +2,7 @@ package handler import ( "encoding/json" + "fmt" "fusenapi/constants" "fusenapi/server/websocket/internal/svc" "fusenapi/server/websocket/internal/types" @@ -28,18 +29,32 @@ var ( // 每个连接的连接属性 type wsConnectItem struct { - conn *websocket.Conn //websocket的连接 - property interface{} //属性 + conn *websocket.Conn //websocket的连接 + closeChan chan struct{} //关闭chan + isClose bool //是否已经关闭 + flag string + inChan chan interface{} //接受消息缓冲通道 + property interface{} //属性 } func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + //升级websocket + conn, err := upgrade.Upgrade(w, r, nil) + if err != nil { + logx.Error("http upgrade websocket err:", err) + return + } + defer conn.Close() + rsp := types.DataTransferRsp{} // 解析JWT token,并对空用户进行判断 claims, err := svcCtx.ParseJwtToken(r) // 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息 if err != nil { - logx.Info("unauthorized:", err.Error()) // 记录错误日志 - w.Write([]byte("connect failed:unauthorized")) + rsp.MsgType = constants.WEBSOCKET_UNAUTH + rsp.Message = "unAuth" + b, _ := json.Marshal(rsp) + _ = conn.WriteMessage(websocket.TextMessage, b) return } if claims != nil { @@ -47,37 +62,104 @@ func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { _, err = auth.GetUserInfoFormMapClaims(claims) // 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息 if err != nil { + rsp.MsgType = constants.WEBSOCKET_UNAUTH + rsp.Message = "unAuth!!" + b, _ := json.Marshal(rsp) + _ = conn.WriteMessage(websocket.TextMessage, b) return } } else { // 如果claims为nil,则认为用户身份为白板用户 - w.Write([]byte("connect failed:unauthorized!!")) - return - } - //升级websocket - conn, err := upgrade.Upgrade(w, r, r.Header) - if err != nil { - logx.Error("http upgrade websocket err:", err) - w.Write([]byte("http upgrade websocket err")) + rsp.MsgType = constants.WEBSOCKET_UNAUTH + rsp.Message = "unAuth!!!" + b, _ := json.Marshal(rsp) + _ = conn.WriteMessage(websocket.TextMessage, b) return } //生成连接唯一标识 - uniqueId := uuid.New().String() + time.Now().Format("20060102150405") - c := wsConnectItem{ - conn: conn, + flag := uuid.New().String() + time.Now().Format("20060102150405") + ws := wsConnectItem{ + conn: conn, + flag: flag, + closeChan: make(chan struct{}, 1), + inChan: make(chan interface{}, 1000), + isClose: false, } //保存连接 - mapConn.Store(uniqueId, c) - //把uniqueId传回去 - rsp := types.DataTransferRsp{ - MsgType: constants.WEBSOCKET_CONNECT_SUCCESS, - Message: uniqueId, - } + mapConn.Store(flag, ws) + defer ws.close() + //把连接成功消息发回去 + rsp.MsgType = constants.WEBSOCKET_CONNECT_SUCCESS + rsp.Message = flag b, _ := json.Marshal(rsp) conn.WriteMessage(websocket.TextMessage, b) + //循环读客户端信息 + go ws.readLoop() + //推消息到云渲染 + go ws.sendLoop() + //心跳 + for { + time.Sleep(time.Second * 3) + select { + case <-ws.closeChan: + return + default: + //发送心跳信息 + rsp.MsgType = constants.WEBSOCKET_HEARTBEAT + rsp.Message = "heartbeat" + b, _ = json.Marshal(rsp) + if err = conn.WriteMessage(websocket.TextMessage, b); err != nil { + logx.Error("发送心跳信息异常,关闭连接:", flag, err) + ws.close() + return + } + } + } + } } -func (w *wsConnectItem) Readloop() { - +// 关闭连接 +func (w *wsConnectItem) close() { + logx.Info("websocket:", w.flag, " is closing...") + w.conn.Close() + mapConn.Delete(w.flag) + if !w.isClose { + w.isClose = true + close(w.closeChan) + close(w.inChan) + } + logx.Info("websocket:", w.flag, " is closed") +} + +// 接受客户端发来的消息 +func (w *wsConnectItem) readLoop() { + for { + select { + case <-w.closeChan: //如果关闭了 + return + default: + _, data, err := w.conn.ReadMessage() + if err != nil { + logx.Error("接受信息错误:", err) + //关闭连接 + w.close() + return + } + //消息传入缓冲通道 + w.inChan <- data + } + } +} + +// 把收到的消息发往不同的地方处理 +func (w *wsConnectItem) sendLoop() { + for { + select { + case <-w.closeChan: + return + case data := <-w.inChan: + fmt.Println(data) + } + } } From 9c72a8a4c9f3e99f0b7cd054eead36f594b4afbc Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 25 Jul 2023 17:10:50 +0800 Subject: [PATCH 12/68] fix --- .../internal/handler/datatransferhandler.go | 129 +++++++++++++----- .../internal/handler/rendernotifyhandler.go | 62 +++++++++ server/websocket/internal/handler/routes.go | 5 + .../internal/logic/rendernotifylogic.go | 43 ++++++ server/websocket/internal/types/types.go | 32 ++++- server_api/websocket.api | 32 ++++- 6 files changed, 262 insertions(+), 41 deletions(-) create mode 100644 server/websocket/internal/handler/rendernotifyhandler.go create mode 100644 server/websocket/internal/logic/rendernotifylogic.go diff --git a/server/websocket/internal/handler/datatransferhandler.go b/server/websocket/internal/handler/datatransferhandler.go index 96a65455..e07d3abe 100644 --- a/server/websocket/internal/handler/datatransferhandler.go +++ b/server/websocket/internal/handler/datatransferhandler.go @@ -4,9 +4,9 @@ import ( "encoding/json" "fmt" "fusenapi/constants" + "fusenapi/server/websocket/internal/logic" "fusenapi/server/websocket/internal/svc" "fusenapi/server/websocket/internal/types" - "fusenapi/utils/auth" "github.com/google/uuid" "github.com/gorilla/websocket" "github.com/zeromicro/go-zero/core/logx" @@ -24,21 +24,27 @@ var ( }, } //连接map池 - mapConn = sync.Map{} + mapConnPool = sync.Map{} ) // 每个连接的连接属性 type wsConnectItem struct { - conn *websocket.Conn //websocket的连接 - closeChan chan struct{} //关闭chan - isClose bool //是否已经关闭 - flag string - inChan chan interface{} //接受消息缓冲通道 - property interface{} //属性 + conn *websocket.Conn //websocket的连接 + closeChan chan struct{} //关闭chan + isClose bool //是否已经关闭 + flag string + inChan chan []byte //接受消息缓冲通道 + outChan chan []byte //发送回客户端的消息 + mutex sync.Mutex + renderImage map[string]struct{} //需要渲染的图片 } func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + // 创建一个业务逻辑层实例 + var req types.DataTransferReq + l := logic.NewDataTransferLogic(r.Context(), svcCtx) + l.DataTransfer(&req, nil) //升级websocket conn, err := upgrade.Upgrade(w, r, nil) if err != nil { @@ -48,7 +54,7 @@ func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { defer conn.Close() rsp := types.DataTransferRsp{} // 解析JWT token,并对空用户进行判断 - claims, err := svcCtx.ParseJwtToken(r) + /*claims, err := svcCtx.ParseJwtToken(r) // 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息 if err != nil { rsp.MsgType = constants.WEBSOCKET_UNAUTH @@ -75,18 +81,20 @@ func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { b, _ := json.Marshal(rsp) _ = conn.WriteMessage(websocket.TextMessage, b) return - } + }*/ //生成连接唯一标识 flag := uuid.New().String() + time.Now().Format("20060102150405") ws := wsConnectItem{ - conn: conn, - flag: flag, - closeChan: make(chan struct{}, 1), - inChan: make(chan interface{}, 1000), - isClose: false, + conn: conn, + flag: flag, + closeChan: make(chan struct{}, 1), + inChan: make(chan []byte, 100), + outChan: make(chan []byte, 100), + renderImage: make(map[string]struct{}), + isClose: false, } //保存连接 - mapConn.Store(flag, ws) + mapConnPool.Store(flag, ws) defer ws.close() //把连接成功消息发回去 rsp.MsgType = constants.WEBSOCKET_CONNECT_SUCCESS @@ -95,43 +103,66 @@ func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { conn.WriteMessage(websocket.TextMessage, b) //循环读客户端信息 go ws.readLoop() + //循环把数据发送给客户端 + go ws.writeLoop() //推消息到云渲染 go ws.sendLoop() //心跳 - for { - time.Sleep(time.Second * 3) - select { - case <-ws.closeChan: + ws.heartbeat() + + } +} + +// 心跳 +func (w *wsConnectItem) heartbeat() { + rsp := types.DataTransferRsp{ + MsgType: constants.WEBSOCKET_HEARTBEAT, + Message: "", + } + for { + time.Sleep(time.Second * 10) + select { + case <-w.closeChan: + return + default: + //发送心跳信息 + b, _ := json.Marshal(rsp) + if err := w.conn.WriteMessage(websocket.TextMessage, b); err != nil { + logx.Error("发送心跳信息异常,关闭连接:", w.flag, err) + w.close() return - default: - //发送心跳信息 - rsp.MsgType = constants.WEBSOCKET_HEARTBEAT - rsp.Message = "heartbeat" - b, _ = json.Marshal(rsp) - if err = conn.WriteMessage(websocket.TextMessage, b); err != nil { - logx.Error("发送心跳信息异常,关闭连接:", flag, err) - ws.close() - return - } } } - } } // 关闭连接 func (w *wsConnectItem) close() { + w.mutex.Lock() + defer w.mutex.Unlock() logx.Info("websocket:", w.flag, " is closing...") w.conn.Close() - mapConn.Delete(w.flag) + mapConnPool.Delete(w.flag) if !w.isClose { w.isClose = true close(w.closeChan) + close(w.outChan) close(w.inChan) } logx.Info("websocket:", w.flag, " is closed") } +func (w *wsConnectItem) writeLoop() { + for { + select { + case <-w.closeChan: //如果关闭了 + return + case data := <-w.outChan: + w.conn.WriteMessage(websocket.TextMessage, data) + } + } +} + // 接受客户端发来的消息 func (w *wsConnectItem) readLoop() { for { @@ -159,7 +190,39 @@ func (w *wsConnectItem) sendLoop() { case <-w.closeChan: return case data := <-w.inChan: - fmt.Println(data) + w.dealwithReciveData(data) } } } + +// 处理接受到的数据 +func (w *wsConnectItem) dealwithReciveData(data []byte) { + var parseInfo types.DataTransferReq + if err := json.Unmarshal(data, &parseInfo); err != nil { + logx.Error("invalid format of websocket message") + return + } + switch parseInfo.MsgType { + case constants.WEBSOCKET_RENDER_IMAGE: //图片渲染 + var renderImageData []types.RenderImageReqMsg + if err := json.Unmarshal([]byte(parseInfo.Message), &renderImageData); err != nil { + logx.Error("invalid format of websocket render image message", err) + return + } + logx.Info("收到请求云渲染图片数据:", renderImageData) + w.mutex.Lock() + defer w.mutex.Unlock() + //把需要渲染的图片加进去 + for _, v := range renderImageData { + key := getRenderImageMapKey(v.ProductId, v.SizeId, v.TemplateId) + w.renderImage[key] = struct{}{} + } + default: + + } +} + +// 获取需要渲染图片的map key +func getRenderImageMapKey(productId, sizeId, templateId int64) string { + return fmt.Sprintf("%d-%d-%d", productId, sizeId, templateId) +} diff --git a/server/websocket/internal/handler/rendernotifyhandler.go b/server/websocket/internal/handler/rendernotifyhandler.go new file mode 100644 index 00000000..9c2eb28d --- /dev/null +++ b/server/websocket/internal/handler/rendernotifyhandler.go @@ -0,0 +1,62 @@ +package handler + +import ( + "encoding/json" + "fusenapi/utils/basic" + "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/rest/httpx" + "net/http" + + "fusenapi/server/websocket/internal/svc" + "fusenapi/server/websocket/internal/types" +) + +func RenderNotifyHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.RenderNotifyReq + _, err := basic.RequestParse(w, r, svcCtx, &req) + if err != nil { + return + } + mapConnPool.Range(func(key, value any) bool { + ws, ok := value.(wsConnectItem) + if !ok { + return false + } + setOutRenderImage(req, ws) + return true + }) + httpx.OkJsonCtx(r.Context(), w, basic.Response{ + Code: 200, + Message: "success", + Data: nil, + }) + } +} + +// 把渲染好的数据放入outchan +func setOutRenderImage(req types.RenderNotifyReq, ws wsConnectItem) { + ws.mutex.Lock() + defer ws.mutex.Unlock() + for _, notifyItem := range req.NotifyList { + renderKey := getRenderImageMapKey(notifyItem.ProductId, notifyItem.SizeId, notifyItem.TemplateId) + //加载并删除 + _, ok := ws.renderImage[renderKey] + if !ok { + continue + } + responseData := types.RenderImageRspMsg{ + ProductId: notifyItem.ProductId, + SizeId: notifyItem.SizeId, + TemplateId: notifyItem.TemplateId, + Source: "我是渲染资源", + } + b, _ := json.Marshal(responseData) + select { + case <-ws.closeChan: + return + case ws.outChan <- b: + logx.Info("notify send render result to out chan") + } + } +} diff --git a/server/websocket/internal/handler/routes.go b/server/websocket/internal/handler/routes.go index fd3200e4..859ecc5b 100644 --- a/server/websocket/internal/handler/routes.go +++ b/server/websocket/internal/handler/routes.go @@ -17,6 +17,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { Path: "/api/websocket/data_transfer", Handler: DataTransferHandler(serverCtx), }, + { + Method: http.MethodPost, + Path: "/api/websocket/render_notify", + Handler: RenderNotifyHandler(serverCtx), + }, }, ) } diff --git a/server/websocket/internal/logic/rendernotifylogic.go b/server/websocket/internal/logic/rendernotifylogic.go new file mode 100644 index 00000000..49803d29 --- /dev/null +++ b/server/websocket/internal/logic/rendernotifylogic.go @@ -0,0 +1,43 @@ +package logic + +import ( + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "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, userinfo *auth.UserInfo) (resp *basic.Response) { + // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) + // userinfo 传入值时, 一定不为null + + return resp.SetStatus(basic.CodeOK) +} diff --git a/server/websocket/internal/types/types.go b/server/websocket/internal/types/types.go index 06201d39..35df171d 100644 --- a/server/websocket/internal/types/types.go +++ b/server/websocket/internal/types/types.go @@ -6,13 +6,37 @@ import ( ) type DataTransferReq struct { - MsgType string `json:"msg_type"` //消息类型 - Message interface{} `json:"message"` //传递的消息 + MsgType string `json:"msg_type"` //消息类型 + Message string `json:"message"` //传递的消息 } type DataTransferRsp struct { - MsgType string `json:"msg_type"` //消息类型 - Message interface{} `json:"message"` //传递的消息 + MsgType string `json:"msg_type"` //消息类型 + Message string `json:"message"` //传递的消息 +} + +type RenderImageReqMsg struct { + ProductId int64 `json:"product_id"` + SizeId int64 `json:"size_id"` + TemplateId int64 `json:"template_id"` +} + +type RenderImageRspMsg struct { + ProductId int64 `json:"product_id"` + SizeId int64 `json:"size_id"` + TemplateId int64 `json:"template_id"` + Source string `json:"source"` +} + +type RenderNotifyReq struct { + NotifyList []NotifyItem `json:"notify_list"` +} + +type NotifyItem struct { + ProductId int64 `json:"product_id"` + SizeId int64 `json:"size_id"` + TemplateId int64 `json:"template_id"` + Source string `json:"source"` } type Request struct { diff --git a/server_api/websocket.api b/server_api/websocket.api index 786e67e7..ee90cdcc 100644 --- a/server_api/websocket.api +++ b/server_api/websocket.api @@ -12,14 +12,38 @@ service websocket { //websocket数据交互 @handler DataTransferHandler get /api/websocket/data_transfer(DataTransferReq) returns (response); + //渲染完了通知接口 + @handler RenderNotifyHandler + post /api/websocket/render_notify(RenderNotifyReq) returns (response); } //websocket数据交互 type DataTransferReq { - MsgType string `json:"msg_type"` //消息类型 - Message interface{} `json:"message"` //传递的消息 + MsgType string `json:"msg_type"` //消息类型 + Message string `json:"message"` //传递的消息 } type DataTransferRsp { - MsgType string `json:"msg_type"` //消息类型 - Message interface{} `json:"message"` //传递的消息 + MsgType string `json:"msg_type"` //消息类型 + Message string `json:"message"` //传递的消息 +} +type RenderImageReqMsg { //websocket接受需要云渲染的图片 + ProductId int64 `json:"product_id"` + SizeId int64 `json:"size_id"` + TemplateId int64 `json:"template_id"` +} +type RenderImageRspMsg { //websocket发送渲染完的数据 + ProductId int64 `json:"product_id"` + SizeId int64 `json:"size_id"` + TemplateId int64 `json:"template_id"` + Source string `json:"source"` +} +//渲染完了通知接口 +type RenderNotifyReq { + NotifyList []NotifyItem `json:"notify_list"` +} +type NotifyItem { + ProductId int64 `json:"product_id"` + SizeId int64 `json:"size_id"` + TemplateId int64 `json:"template_id"` + Source string `json:"source"` } \ No newline at end of file From 17aac7ad664864f15a639d7700c1412831837fd3 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 25 Jul 2023 17:12:37 +0800 Subject: [PATCH 13/68] fix --- server/websocket/internal/handler/datatransferhandler.go | 4 ++-- server/websocket/internal/handler/rendernotifyhandler.go | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/server/websocket/internal/handler/datatransferhandler.go b/server/websocket/internal/handler/datatransferhandler.go index e07d3abe..9e0363eb 100644 --- a/server/websocket/internal/handler/datatransferhandler.go +++ b/server/websocket/internal/handler/datatransferhandler.go @@ -214,7 +214,7 @@ func (w *wsConnectItem) dealwithReciveData(data []byte) { defer w.mutex.Unlock() //把需要渲染的图片加进去 for _, v := range renderImageData { - key := getRenderImageMapKey(v.ProductId, v.SizeId, v.TemplateId) + key := w.getRenderImageMapKey(v.ProductId, v.SizeId, v.TemplateId) w.renderImage[key] = struct{}{} } default: @@ -223,6 +223,6 @@ func (w *wsConnectItem) dealwithReciveData(data []byte) { } // 获取需要渲染图片的map key -func getRenderImageMapKey(productId, sizeId, templateId int64) string { +func (w *wsConnectItem) getRenderImageMapKey(productId, sizeId, templateId int64) string { return fmt.Sprintf("%d-%d-%d", productId, sizeId, templateId) } diff --git a/server/websocket/internal/handler/rendernotifyhandler.go b/server/websocket/internal/handler/rendernotifyhandler.go index 9c2eb28d..6dde0c3f 100644 --- a/server/websocket/internal/handler/rendernotifyhandler.go +++ b/server/websocket/internal/handler/rendernotifyhandler.go @@ -39,7 +39,7 @@ func setOutRenderImage(req types.RenderNotifyReq, ws wsConnectItem) { ws.mutex.Lock() defer ws.mutex.Unlock() for _, notifyItem := range req.NotifyList { - renderKey := getRenderImageMapKey(notifyItem.ProductId, notifyItem.SizeId, notifyItem.TemplateId) + renderKey := ws.getRenderImageMapKey(notifyItem.ProductId, notifyItem.SizeId, notifyItem.TemplateId) //加载并删除 _, ok := ws.renderImage[renderKey] if !ok { From d0fc91b61b25db36a881162e6edb2b450bd59064 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 25 Jul 2023 17:41:38 +0800 Subject: [PATCH 14/68] fix --- constants/websocket.go | 3 ++ .../internal/handler/datatransferhandler.go | 3 +- .../internal/handler/rendernotifyhandler.go | 46 ++++++++++++++++++- server/websocket/internal/types/types.go | 2 + server_api/websocket.api | 2 + 5 files changed, 54 insertions(+), 2 deletions(-) diff --git a/constants/websocket.go b/constants/websocket.go index 7fca9751..a9a6aa5d 100644 --- a/constants/websocket.go +++ b/constants/websocket.go @@ -13,3 +13,6 @@ const ( //图片渲染 WEBSOCKET_RENDER_IMAGE = "render-image" ) + +// 云渲染通知需要的签名字符串 +const RENDER_NOTIFY_SIGN_KEY = "fusen-render-notify-%s-%d" diff --git a/server/websocket/internal/handler/datatransferhandler.go b/server/websocket/internal/handler/datatransferhandler.go index 9e0363eb..afcaf88d 100644 --- a/server/websocket/internal/handler/datatransferhandler.go +++ b/server/websocket/internal/handler/datatransferhandler.go @@ -203,7 +203,8 @@ func (w *wsConnectItem) dealwithReciveData(data []byte) { return } switch parseInfo.MsgType { - case constants.WEBSOCKET_RENDER_IMAGE: //图片渲染 + //图片渲染 + case constants.WEBSOCKET_RENDER_IMAGE: var renderImageData []types.RenderImageReqMsg if err := json.Unmarshal([]byte(parseInfo.Message), &renderImageData); err != nil { logx.Error("invalid format of websocket render image message", err) diff --git a/server/websocket/internal/handler/rendernotifyhandler.go b/server/websocket/internal/handler/rendernotifyhandler.go index 6dde0c3f..5fa2371a 100644 --- a/server/websocket/internal/handler/rendernotifyhandler.go +++ b/server/websocket/internal/handler/rendernotifyhandler.go @@ -1,11 +1,16 @@ package handler import ( + "crypto/sha256" + "encoding/hex" "encoding/json" + "fmt" + "fusenapi/constants" "fusenapi/utils/basic" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/rest/httpx" "net/http" + "time" "fusenapi/server/websocket/internal/svc" "fusenapi/server/websocket/internal/types" @@ -16,8 +21,45 @@ func RenderNotifyHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { var req types.RenderNotifyReq _, err := basic.RequestParse(w, r, svcCtx, &req) if err != nil { + httpx.OkJsonCtx(r.Context(), w, basic.Response{ + Code: basic.CodeRequestParamsErr.Code, + Message: "err param", + Data: nil, + }) return } + if len(req.NotifyList) == 0 { + httpx.OkJsonCtx(r.Context(), w, basic.Response{ + Code: basic.CodeRequestParamsErr.Code, + Message: "invalid param,notify list is empty", + Data: nil, + }) + return + } + if time.Now().Unix()-120 > req.Time { + httpx.OkJsonCtx(r.Context(), w, basic.Response{ + Code: basic.CodeRequestParamsErr.Code, + Message: "invalid param,time is expired", + Data: nil, + }) + return + } + //验证签名 sha256 + notifyByte, _ := json.Marshal(req.NotifyList) + 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 { + httpx.OkJsonCtx(r.Context(), w, basic.Response{ + Code: basic.CodeRequestParamsErr.Code, + Message: "invalid sign", + Data: nil, + }) + return + } + //遍历链接 mapConnPool.Range(func(key, value any) bool { ws, ok := value.(wsConnectItem) if !ok { @@ -40,7 +82,7 @@ func setOutRenderImage(req types.RenderNotifyReq, ws wsConnectItem) { defer ws.mutex.Unlock() for _, notifyItem := range req.NotifyList { renderKey := ws.getRenderImageMapKey(notifyItem.ProductId, notifyItem.SizeId, notifyItem.TemplateId) - //加载并删除 + //查询 _, ok := ws.renderImage[renderKey] if !ok { continue @@ -58,5 +100,7 @@ func setOutRenderImage(req types.RenderNotifyReq, ws wsConnectItem) { case ws.outChan <- b: logx.Info("notify send render result to out chan") } + //删掉已经处理的渲染任务 + delete(ws.renderImage, renderKey) } } diff --git a/server/websocket/internal/types/types.go b/server/websocket/internal/types/types.go index 35df171d..6082881a 100644 --- a/server/websocket/internal/types/types.go +++ b/server/websocket/internal/types/types.go @@ -29,6 +29,8 @@ type RenderImageRspMsg struct { } type RenderNotifyReq struct { + Sign string `json:"sign"` + Time int64 `json:"time"` NotifyList []NotifyItem `json:"notify_list"` } diff --git a/server_api/websocket.api b/server_api/websocket.api index ee90cdcc..4b5c1fed 100644 --- a/server_api/websocket.api +++ b/server_api/websocket.api @@ -39,6 +39,8 @@ type RenderImageRspMsg { //websocket发送渲染完的数据 } //渲染完了通知接口 type RenderNotifyReq { + Sign string `json:"sign"` + Time int64 `json:"time"` NotifyList []NotifyItem `json:"notify_list"` } type NotifyItem { From b0f598af6816880ac72124e6ad08d0448d80aba5 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 25 Jul 2023 18:04:01 +0800 Subject: [PATCH 15/68] fix --- .../internal/handler/datatransferhandler.go | 12 ++++++------ .../internal/handler/rendernotifyhandler.go | 1 - server/websocket/internal/types/types.go | 8 ++++---- server_api/websocket.api | 8 ++++---- 4 files changed, 14 insertions(+), 15 deletions(-) diff --git a/server/websocket/internal/handler/datatransferhandler.go b/server/websocket/internal/handler/datatransferhandler.go index afcaf88d..827ac058 100644 --- a/server/websocket/internal/handler/datatransferhandler.go +++ b/server/websocket/internal/handler/datatransferhandler.go @@ -97,8 +97,8 @@ func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { mapConnPool.Store(flag, ws) defer ws.close() //把连接成功消息发回去 - rsp.MsgType = constants.WEBSOCKET_CONNECT_SUCCESS - rsp.Message = flag + rsp.T = constants.WEBSOCKET_CONNECT_SUCCESS + rsp.D = flag b, _ := json.Marshal(rsp) conn.WriteMessage(websocket.TextMessage, b) //循环读客户端信息 @@ -116,8 +116,8 @@ func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { // 心跳 func (w *wsConnectItem) heartbeat() { rsp := types.DataTransferRsp{ - MsgType: constants.WEBSOCKET_HEARTBEAT, - Message: "", + T: constants.WEBSOCKET_HEARTBEAT, + D: "", } for { time.Sleep(time.Second * 10) @@ -202,11 +202,11 @@ func (w *wsConnectItem) dealwithReciveData(data []byte) { logx.Error("invalid format of websocket message") return } - switch parseInfo.MsgType { + switch parseInfo.T { //图片渲染 case constants.WEBSOCKET_RENDER_IMAGE: var renderImageData []types.RenderImageReqMsg - if err := json.Unmarshal([]byte(parseInfo.Message), &renderImageData); err != nil { + if err := json.Unmarshal([]byte(parseInfo.D), &renderImageData); err != nil { logx.Error("invalid format of websocket render image message", err) return } diff --git a/server/websocket/internal/handler/rendernotifyhandler.go b/server/websocket/internal/handler/rendernotifyhandler.go index 5fa2371a..de6e3e21 100644 --- a/server/websocket/internal/handler/rendernotifyhandler.go +++ b/server/websocket/internal/handler/rendernotifyhandler.go @@ -50,7 +50,6 @@ func RenderNotifyHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { 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 { httpx.OkJsonCtx(r.Context(), w, basic.Response{ Code: basic.CodeRequestParamsErr.Code, diff --git a/server/websocket/internal/types/types.go b/server/websocket/internal/types/types.go index 6082881a..6a1cf750 100644 --- a/server/websocket/internal/types/types.go +++ b/server/websocket/internal/types/types.go @@ -6,13 +6,13 @@ import ( ) type DataTransferReq struct { - MsgType string `json:"msg_type"` //消息类型 - Message string `json:"message"` //传递的消息 + T string `json:"t"` //消息类型 + D string `json:"d"` //传递的消息 } type DataTransferRsp struct { - MsgType string `json:"msg_type"` //消息类型 - Message string `json:"message"` //传递的消息 + T string `json:"t"` //消息类型 + D string `json:"d"` //传递的消息 } type RenderImageReqMsg struct { diff --git a/server_api/websocket.api b/server_api/websocket.api index 4b5c1fed..d0daf98b 100644 --- a/server_api/websocket.api +++ b/server_api/websocket.api @@ -19,12 +19,12 @@ service websocket { //websocket数据交互 type DataTransferReq { - MsgType string `json:"msg_type"` //消息类型 - Message string `json:"message"` //传递的消息 + T string `json:"t"` //消息类型 + D string `json:"d"` //传递的消息 } type DataTransferRsp { - MsgType string `json:"msg_type"` //消息类型 - Message string `json:"message"` //传递的消息 + T string `json:"t"` //消息类型 + D string `json:"d"` //传递的消息 } type RenderImageReqMsg { //websocket接受需要云渲染的图片 ProductId int64 `json:"product_id"` From 932ee1a578484ab46078caf4ef8af7c7558759d7 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 25 Jul 2023 18:21:30 +0800 Subject: [PATCH 16/68] fix --- server/websocket/internal/handler/rendernotifyhandler.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/websocket/internal/handler/rendernotifyhandler.go b/server/websocket/internal/handler/rendernotifyhandler.go index de6e3e21..f7dfa3ec 100644 --- a/server/websocket/internal/handler/rendernotifyhandler.go +++ b/server/websocket/internal/handler/rendernotifyhandler.go @@ -36,7 +36,7 @@ func RenderNotifyHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { }) return } - if time.Now().Unix()-120 > req.Time { + if time.Now().Unix()-120 > req.Time || req.Time > time.Now().Unix() { httpx.OkJsonCtx(r.Context(), w, basic.Response{ Code: basic.CodeRequestParamsErr.Code, Message: "invalid param,time is expired", From 222b9ec155537e9542f76c3137bc5c74820ff094 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 25 Jul 2023 18:34:56 +0800 Subject: [PATCH 17/68] fix --- .../internal/handler/datatransferhandler.go | 34 ++++++++++--------- .../internal/handler/rendernotifyhandler.go | 2 +- 2 files changed, 19 insertions(+), 17 deletions(-) diff --git a/server/websocket/internal/handler/datatransferhandler.go b/server/websocket/internal/handler/datatransferhandler.go index 827ac058..d981d377 100644 --- a/server/websocket/internal/handler/datatransferhandler.go +++ b/server/websocket/internal/handler/datatransferhandler.go @@ -125,13 +125,14 @@ func (w *wsConnectItem) heartbeat() { case <-w.closeChan: return default: - //发送心跳信息 - b, _ := json.Marshal(rsp) - if err := w.conn.WriteMessage(websocket.TextMessage, b); err != nil { - logx.Error("发送心跳信息异常,关闭连接:", w.flag, err) - w.close() - return - } + + } + //发送心跳信息 + b, _ := json.Marshal(rsp) + if err := w.conn.WriteMessage(websocket.TextMessage, b); err != nil { + logx.Error("发送心跳信息异常,关闭连接:", w.flag, err) + w.close() + return } } } @@ -170,16 +171,17 @@ func (w *wsConnectItem) readLoop() { case <-w.closeChan: //如果关闭了 return default: - _, data, err := w.conn.ReadMessage() - if err != nil { - logx.Error("接受信息错误:", err) - //关闭连接 - w.close() - return - } - //消息传入缓冲通道 - w.inChan <- data + } + _, data, err := w.conn.ReadMessage() + if err != nil { + logx.Error("接受信息错误:", err) + //关闭连接 + w.close() + return + } + //消息传入缓冲通道 + w.inChan <- data } } diff --git a/server/websocket/internal/handler/rendernotifyhandler.go b/server/websocket/internal/handler/rendernotifyhandler.go index f7dfa3ec..3767bd9c 100644 --- a/server/websocket/internal/handler/rendernotifyhandler.go +++ b/server/websocket/internal/handler/rendernotifyhandler.go @@ -36,7 +36,7 @@ func RenderNotifyHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { }) return } - if time.Now().Unix()-120 > req.Time || req.Time > time.Now().Unix() { + if time.Now().Unix()-120 > req.Time /*|| req.Time > time.Now().Unix() */ { httpx.OkJsonCtx(r.Context(), w, basic.Response{ Code: basic.CodeRequestParamsErr.Code, Message: "invalid param,time is expired", From 743ea961574d446a3f6376642893b3de8d67bd85 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 25 Jul 2023 19:33:59 +0800 Subject: [PATCH 18/68] fix --- .../internal/handler/datatransferhandler.go | 29 +++++++++++++++++ .../internal/handler/rendernotifyhandler.go | 32 +------------------ 2 files changed, 30 insertions(+), 31 deletions(-) diff --git a/server/websocket/internal/handler/datatransferhandler.go b/server/websocket/internal/handler/datatransferhandler.go index d981d377..04f0a7ae 100644 --- a/server/websocket/internal/handler/datatransferhandler.go +++ b/server/websocket/internal/handler/datatransferhandler.go @@ -225,6 +225,35 @@ func (w *wsConnectItem) dealwithReciveData(data []byte) { } } +// 把渲染好的数据放入outchan +func (w *wsConnectItem) setOutRenderImage(req types.RenderNotifyReq, ws wsConnectItem) { + ws.mutex.Lock() + defer ws.mutex.Unlock() + for _, notifyItem := range req.NotifyList { + renderKey := ws.getRenderImageMapKey(notifyItem.ProductId, notifyItem.SizeId, notifyItem.TemplateId) + //查询 + _, ok := ws.renderImage[renderKey] + if !ok { + continue + } + responseData := types.RenderImageRspMsg{ + ProductId: notifyItem.ProductId, + SizeId: notifyItem.SizeId, + TemplateId: notifyItem.TemplateId, + Source: "我是渲染资源", + } + b, _ := json.Marshal(responseData) + select { + case <-ws.closeChan: + return + case ws.outChan <- b: + logx.Info("notify send render result to out chan") + } + //删掉已经处理的渲染任务 + delete(ws.renderImage, renderKey) + } +} + // 获取需要渲染图片的map key func (w *wsConnectItem) getRenderImageMapKey(productId, sizeId, templateId int64) string { return fmt.Sprintf("%d-%d-%d", productId, sizeId, templateId) diff --git a/server/websocket/internal/handler/rendernotifyhandler.go b/server/websocket/internal/handler/rendernotifyhandler.go index 3767bd9c..b51fee32 100644 --- a/server/websocket/internal/handler/rendernotifyhandler.go +++ b/server/websocket/internal/handler/rendernotifyhandler.go @@ -7,7 +7,6 @@ import ( "fmt" "fusenapi/constants" "fusenapi/utils/basic" - "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/rest/httpx" "net/http" "time" @@ -64,7 +63,7 @@ func RenderNotifyHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { if !ok { return false } - setOutRenderImage(req, ws) + ws.setOutRenderImage(req, ws) return true }) httpx.OkJsonCtx(r.Context(), w, basic.Response{ @@ -74,32 +73,3 @@ func RenderNotifyHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { }) } } - -// 把渲染好的数据放入outchan -func setOutRenderImage(req types.RenderNotifyReq, ws wsConnectItem) { - ws.mutex.Lock() - defer ws.mutex.Unlock() - for _, notifyItem := range req.NotifyList { - renderKey := ws.getRenderImageMapKey(notifyItem.ProductId, notifyItem.SizeId, notifyItem.TemplateId) - //查询 - _, ok := ws.renderImage[renderKey] - if !ok { - continue - } - responseData := types.RenderImageRspMsg{ - ProductId: notifyItem.ProductId, - SizeId: notifyItem.SizeId, - TemplateId: notifyItem.TemplateId, - Source: "我是渲染资源", - } - b, _ := json.Marshal(responseData) - select { - case <-ws.closeChan: - return - case ws.outChan <- b: - logx.Info("notify send render result to out chan") - } - //删掉已经处理的渲染任务 - delete(ws.renderImage, renderKey) - } -} From 3be83ed42401d2bda4ea75dcedaa163430b9e13f Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 25 Jul 2023 19:35:52 +0800 Subject: [PATCH 19/68] fix --- .../internal/handler/datatransferhandler.go | 16 ++++++++-------- .../internal/handler/rendernotifyhandler.go | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/server/websocket/internal/handler/datatransferhandler.go b/server/websocket/internal/handler/datatransferhandler.go index 04f0a7ae..7c8a6c5b 100644 --- a/server/websocket/internal/handler/datatransferhandler.go +++ b/server/websocket/internal/handler/datatransferhandler.go @@ -226,13 +226,13 @@ func (w *wsConnectItem) dealwithReciveData(data []byte) { } // 把渲染好的数据放入outchan -func (w *wsConnectItem) setOutRenderImage(req types.RenderNotifyReq, ws wsConnectItem) { - ws.mutex.Lock() - defer ws.mutex.Unlock() +func (w *wsConnectItem) setOutRenderImage(req types.RenderNotifyReq) { + w.mutex.Lock() + defer w.mutex.Unlock() for _, notifyItem := range req.NotifyList { - renderKey := ws.getRenderImageMapKey(notifyItem.ProductId, notifyItem.SizeId, notifyItem.TemplateId) + renderKey := w.getRenderImageMapKey(notifyItem.ProductId, notifyItem.SizeId, notifyItem.TemplateId) //查询 - _, ok := ws.renderImage[renderKey] + _, ok := w.renderImage[renderKey] if !ok { continue } @@ -244,13 +244,13 @@ func (w *wsConnectItem) setOutRenderImage(req types.RenderNotifyReq, ws wsConnec } b, _ := json.Marshal(responseData) select { - case <-ws.closeChan: + case <-w.closeChan: return - case ws.outChan <- b: + case w.outChan <- b: logx.Info("notify send render result to out chan") } //删掉已经处理的渲染任务 - delete(ws.renderImage, renderKey) + delete(w.renderImage, renderKey) } } diff --git a/server/websocket/internal/handler/rendernotifyhandler.go b/server/websocket/internal/handler/rendernotifyhandler.go index b51fee32..005ee044 100644 --- a/server/websocket/internal/handler/rendernotifyhandler.go +++ b/server/websocket/internal/handler/rendernotifyhandler.go @@ -63,7 +63,7 @@ func RenderNotifyHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { if !ok { return false } - ws.setOutRenderImage(req, ws) + ws.setOutRenderImage(req) return true }) httpx.OkJsonCtx(r.Context(), w, basic.Response{ From 59edb394fa6437e8502cfb48a1905a0d0098fc8a Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 25 Jul 2023 19:37:56 +0800 Subject: [PATCH 20/68] fix --- server/websocket/internal/handler/datatransferhandler.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/websocket/internal/handler/datatransferhandler.go b/server/websocket/internal/handler/datatransferhandler.go index 7c8a6c5b..050f84ad 100644 --- a/server/websocket/internal/handler/datatransferhandler.go +++ b/server/websocket/internal/handler/datatransferhandler.go @@ -119,6 +119,7 @@ func (w *wsConnectItem) heartbeat() { T: constants.WEBSOCKET_HEARTBEAT, D: "", } + b, _ := json.Marshal(rsp) for { time.Sleep(time.Second * 10) select { @@ -128,7 +129,6 @@ func (w *wsConnectItem) heartbeat() { } //发送心跳信息 - b, _ := json.Marshal(rsp) if err := w.conn.WriteMessage(websocket.TextMessage, b); err != nil { logx.Error("发送心跳信息异常,关闭连接:", w.flag, err) w.close() From 0657307265b8b688293772e2dfe5f0f0df9a40a0 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 25 Jul 2023 19:43:28 +0800 Subject: [PATCH 21/68] fix --- .../internal/handler/datatransferhandler.go | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/server/websocket/internal/handler/datatransferhandler.go b/server/websocket/internal/handler/datatransferhandler.go index 050f84ad..66cde398 100644 --- a/server/websocket/internal/handler/datatransferhandler.go +++ b/server/websocket/internal/handler/datatransferhandler.go @@ -7,6 +7,7 @@ import ( "fusenapi/server/websocket/internal/logic" "fusenapi/server/websocket/internal/svc" "fusenapi/server/websocket/internal/types" + "fusenapi/utils/auth" "github.com/google/uuid" "github.com/gorilla/websocket" "github.com/zeromicro/go-zero/core/logx" @@ -54,11 +55,11 @@ func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { defer conn.Close() rsp := types.DataTransferRsp{} // 解析JWT token,并对空用户进行判断 - /*claims, err := svcCtx.ParseJwtToken(r) + claims, err := svcCtx.ParseJwtToken(r) // 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息 if err != nil { - rsp.MsgType = constants.WEBSOCKET_UNAUTH - rsp.Message = "unAuth" + rsp.T = constants.WEBSOCKET_UNAUTH + rsp.D = "unAuth" b, _ := json.Marshal(rsp) _ = conn.WriteMessage(websocket.TextMessage, b) return @@ -68,20 +69,20 @@ func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { _, err = auth.GetUserInfoFormMapClaims(claims) // 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息 if err != nil { - rsp.MsgType = constants.WEBSOCKET_UNAUTH - rsp.Message = "unAuth!!" + rsp.T = constants.WEBSOCKET_UNAUTH + rsp.D = "unAuth!!" b, _ := json.Marshal(rsp) _ = conn.WriteMessage(websocket.TextMessage, b) return } } else { // 如果claims为nil,则认为用户身份为白板用户 - rsp.MsgType = constants.WEBSOCKET_UNAUTH - rsp.Message = "unAuth!!!" + rsp.T = constants.WEBSOCKET_UNAUTH + rsp.D = "unAuth!!!" b, _ := json.Marshal(rsp) _ = conn.WriteMessage(websocket.TextMessage, b) return - }*/ + } //生成连接唯一标识 flag := uuid.New().String() + time.Now().Format("20060102150405") ws := wsConnectItem{ From c378c6d8daab76bbbc40b55798f08864fc218f56 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 10:03:15 +0800 Subject: [PATCH 22/68] fix --- .../internal/handler/datatransferhandler.go | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/server/websocket/internal/handler/datatransferhandler.go b/server/websocket/internal/handler/datatransferhandler.go index 66cde398..3e5177d7 100644 --- a/server/websocket/internal/handler/datatransferhandler.go +++ b/server/websocket/internal/handler/datatransferhandler.go @@ -54,6 +54,7 @@ func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { } defer conn.Close() rsp := types.DataTransferRsp{} + isAuth := true // 解析JWT token,并对空用户进行判断 claims, err := svcCtx.ParseJwtToken(r) // 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息 @@ -62,7 +63,7 @@ func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { rsp.D = "unAuth" b, _ := json.Marshal(rsp) _ = conn.WriteMessage(websocket.TextMessage, b) - return + isAuth = false } if claims != nil { // 从token中获取对应的用户信息 @@ -73,7 +74,7 @@ func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { rsp.D = "unAuth!!" b, _ := json.Marshal(rsp) _ = conn.WriteMessage(websocket.TextMessage, b) - return + isAuth = false } } else { // 如果claims为nil,则认为用户身份为白板用户 @@ -81,7 +82,15 @@ func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { rsp.D = "unAuth!!!" b, _ := json.Marshal(rsp) _ = conn.WriteMessage(websocket.TextMessage, b) - return + isAuth = false + } + //不是授权的连接(10秒后关闭) + if !isAuth { + select { + case <-time.After(time.Second * 10): + conn.Close() + return + } } //生成连接唯一标识 flag := uuid.New().String() + time.Now().Format("20060102150405") From c7536d0fdb13ed22d4ed0e26a9b01b9fdf970242 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 11:02:30 +0800 Subject: [PATCH 23/68] fix --- fs_gen_api_backend.sh | 2 +- model/gmodel/fs_product_template_tags_gen.go | 1 + .../gmodel/fs_product_template_tags_logic.go | 9 ++ .../etc/product-template-tag.yaml | 8 ++ .../internal/config/config.go | 12 +++ .../handler/getproducttemplatetagshandler.go | 35 ++++++++ .../internal/handler/routes.go | 22 +++++ .../logic/getproducttemplatetagslogic.go | 55 ++++++++++++ .../internal/svc/servicecontext.go | 61 ++++++++++++++ .../internal/types/types.go | 84 +++++++++++++++++++ .../product-template-tag.go | 36 ++++++++ server_api/product-template-tag.api | 25 ++++++ 12 files changed, 349 insertions(+), 1 deletion(-) create mode 100644 server/product-template-tag/etc/product-template-tag.yaml create mode 100644 server/product-template-tag/internal/config/config.go create mode 100644 server/product-template-tag/internal/handler/getproducttemplatetagshandler.go create mode 100644 server/product-template-tag/internal/handler/routes.go create mode 100644 server/product-template-tag/internal/logic/getproducttemplatetagslogic.go create mode 100644 server/product-template-tag/internal/svc/servicecontext.go create mode 100644 server/product-template-tag/internal/types/types.go create mode 100644 server/product-template-tag/product-template-tag.go create mode 100644 server_api/product-template-tag.api diff --git a/fs_gen_api_backend.sh b/fs_gen_api_backend.sh index 1acbf5fa..d870c95d 100755 --- a/fs_gen_api_backend.sh +++ b/fs_gen_api_backend.sh @@ -1,6 +1,6 @@ #! /bin/bash name=${1%%\\*} -options=("backend" "product-template" "product-model") +options=("backend" "product-template" "product-template-tag" "product-model") for option in "${options[@]}"; do if [ "$name" = "$option" ]; then echo $name diff --git a/model/gmodel/fs_product_template_tags_gen.go b/model/gmodel/fs_product_template_tags_gen.go index db246f6e..227af16d 100644 --- a/model/gmodel/fs_product_template_tags_gen.go +++ b/model/gmodel/fs_product_template_tags_gen.go @@ -8,6 +8,7 @@ import ( type FsProductTemplateTags struct { Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // ID Title *string `gorm:"default:'';" json:"title"` // 标题 + CoverImg *string `gorm:"default:'';" json:"cover_img"` // 封面图 Status *int64 `gorm:"default:0;" json:"status"` // 状态 1:可用 CreateAt *int64 `gorm:"default:0;" json:"create_at"` // 创建时间 } diff --git a/model/gmodel/fs_product_template_tags_logic.go b/model/gmodel/fs_product_template_tags_logic.go index f5c87b39..4c26d2fb 100755 --- a/model/gmodel/fs_product_template_tags_logic.go +++ b/model/gmodel/fs_product_template_tags_logic.go @@ -23,3 +23,12 @@ func (pt *FsProductTemplateTagsModel) FindOne(ctx context.Context, id int64, fie err = db.Take(&resp).Error return resp, err } +func (pt *FsProductTemplateTagsModel) GetList(ctx context.Context, page, limit int, orderBy string) (resp []FsProductTemplateTags, err error) { + db := pt.db.WithContext(ctx).Model(&FsProductTemplateTags{}).Where("`status` = ?", 1) + if orderBy != "" { + db = db.Order(orderBy) + } + offset := (page - 1) * limit + err = db.Offset(offset).Limit(limit).Find(&resp).Error + return resp, err +} diff --git a/server/product-template-tag/etc/product-template-tag.yaml b/server/product-template-tag/etc/product-template-tag.yaml new file mode 100644 index 00000000..253828fb --- /dev/null +++ b/server/product-template-tag/etc/product-template-tag.yaml @@ -0,0 +1,8 @@ +Name: product-template-tag +Host: 0.0.0.0 +Port: 9916 +SourceMysql: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest +Auth: + AccessSecret: fusen2023 + AccessExpire: 2592000 + RefreshAfter: 1592000 \ No newline at end of file diff --git a/server/product-template-tag/internal/config/config.go b/server/product-template-tag/internal/config/config.go new file mode 100644 index 00000000..b5a0124e --- /dev/null +++ b/server/product-template-tag/internal/config/config.go @@ -0,0 +1,12 @@ +package config + +import ( + "fusenapi/server/product-template-tag/internal/types" + "github.com/zeromicro/go-zero/rest" +) + +type Config struct { + rest.RestConf + SourceMysql string + Auth types.Auth +} diff --git a/server/product-template-tag/internal/handler/getproducttemplatetagshandler.go b/server/product-template-tag/internal/handler/getproducttemplatetagshandler.go new file mode 100644 index 00000000..cf7cf96e --- /dev/null +++ b/server/product-template-tag/internal/handler/getproducttemplatetagshandler.go @@ -0,0 +1,35 @@ +package handler + +import ( + "net/http" + "reflect" + + "fusenapi/utils/basic" + + "fusenapi/server/product-template-tag/internal/logic" + "fusenapi/server/product-template-tag/internal/svc" + "fusenapi/server/product-template-tag/internal/types" +) + +func GetProductTemplateTagsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + var req types.GetProductTemplateTagsReq + userinfo, err := basic.RequestParse(w, r, svcCtx, &req) + if err != nil { + return + } + + // 创建一个业务逻辑层实例 + l := logic.NewGetProductTemplateTagsLogic(r.Context(), svcCtx) + + rl := reflect.ValueOf(l) + basic.BeforeLogic(w, r, rl) + + resp := l.GetProductTemplateTags(&req, userinfo) + + if !basic.AfterLogic(w, r, rl, resp) { + basic.NormalAfterLogic(w, r, resp) + } + } +} diff --git a/server/product-template-tag/internal/handler/routes.go b/server/product-template-tag/internal/handler/routes.go new file mode 100644 index 00000000..b2c8f181 --- /dev/null +++ b/server/product-template-tag/internal/handler/routes.go @@ -0,0 +1,22 @@ +// Code generated by goctl. DO NOT EDIT. +package handler + +import ( + "net/http" + + "fusenapi/server/product-template-tag/internal/svc" + + "github.com/zeromicro/go-zero/rest" +) + +func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { + server.AddRoutes( + []rest.Route{ + { + Method: http.MethodGet, + Path: "/api/product-template/get_product_template_tags", + Handler: GetProductTemplateTagsHandler(serverCtx), + }, + }, + ) +} diff --git a/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go b/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go new file mode 100644 index 00000000..68c62363 --- /dev/null +++ b/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go @@ -0,0 +1,55 @@ +package logic + +import ( + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "context" + + "fusenapi/server/product-template-tag/internal/svc" + "fusenapi/server/product-template-tag/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetProductTemplateTagsLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewGetProductTemplateTagsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetProductTemplateTagsLogic { + return &GetProductTemplateTagsLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +// 处理进入前逻辑w,r +// func (l *GetProductTemplateTagsLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) { +// } + +// 处理逻辑后 w,r 如:重定向, resp 必须重新处理 +// func (l *GetProductTemplateTagsLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { +// // httpx.OkJsonCtx(r.Context(), w, resp) +// } + +func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProductTemplateTagsReq, userinfo *auth.UserInfo) (resp *basic.Response) { + if req.Limit <= 0 || req.Limit > 100 { + req.Limit = 4 + } + productTemplateTags, err := l.svcCtx.AllModels.FsProductTemplateTags.GetList(l.ctx, 1, req.Limit, "`id` DESC") + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get template tags") + } + list := make([]types.GetProductTemplateTagsRsp, 0, len(productTemplateTags)) + for _, v := range productTemplateTags { + list = append(list, types.GetProductTemplateTagsRsp{ + Tag: *v.Title, + Cover: *v.CoverImg, + }) + } + return resp.SetStatusWithMessage(basic.CodeOK, "success", list) +} diff --git a/server/product-template-tag/internal/svc/servicecontext.go b/server/product-template-tag/internal/svc/servicecontext.go new file mode 100644 index 00000000..4ebf8b31 --- /dev/null +++ b/server/product-template-tag/internal/svc/servicecontext.go @@ -0,0 +1,61 @@ +package svc + +import ( + "errors" + "fmt" + "fusenapi/server/product-template-tag/internal/config" + "net/http" + + "fusenapi/initalize" + "fusenapi/model/gmodel" + + "github.com/golang-jwt/jwt" + "gorm.io/gorm" +) + +type ServiceContext struct { + Config config.Config + + MysqlConn *gorm.DB + AllModels *gmodel.AllModelsGen +} + +func NewServiceContext(c config.Config) *ServiceContext { + + return &ServiceContext{ + Config: c, + MysqlConn: initalize.InitMysql(c.SourceMysql), + AllModels: gmodel.NewAllModels(initalize.InitMysql(c.SourceMysql)), + } +} + +func (svcCtx *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) { + AuthKey := r.Header.Get("Authorization") + if AuthKey == "" { + return nil, nil + } + AuthKey = AuthKey[7:] + + if len(AuthKey) <= 50 { + return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey))) + } + + token, err := jwt.Parse(AuthKey, func(token *jwt.Token) (interface{}, error) { + // 检查签名方法是否为 HS256 + if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) + } + // 返回用于验证签名的密钥 + return []byte(svcCtx.Config.Auth.AccessSecret), nil + }) + if err != nil { + return nil, errors.New(fmt.Sprint("Error parsing token:", err)) + } + + // 验证成功返回 + if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { + return claims, nil + } + + return nil, errors.New(fmt.Sprint("Invalid token", err)) +} diff --git a/server/product-template-tag/internal/types/types.go b/server/product-template-tag/internal/types/types.go new file mode 100644 index 00000000..39866da6 --- /dev/null +++ b/server/product-template-tag/internal/types/types.go @@ -0,0 +1,84 @@ +// Code generated by goctl. DO NOT EDIT. +package types + +import ( + "fusenapi/utils/basic" +) + +type GetProductTemplateTagsReq struct { + Limit int `form:"limit"` +} + +type GetProductTemplateTagsRsp struct { + Tag string `json:"tag"` + Cover string `json:"cover"` +} + +type Request struct { +} + +type Response struct { + Code int `json:"code"` + Message string `json:"msg"` + Data interface{} `json:"data"` +} + +type Auth struct { + AccessSecret string `json:"accessSecret"` + AccessExpire int64 `json:"accessExpire"` + RefreshAfter int64 `json:"refreshAfter"` +} + +type File struct { + Filename string `fsfile:"filename"` + Header map[string][]string `fsfile:"header"` + Size int64 `fsfile:"size"` + Data []byte `fsfile:"data"` +} + +type Meta struct { + TotalCount int64 `json:"totalCount"` + PageCount int64 `json:"pageCount"` + CurrentPage int `json:"currentPage"` + PerPage int `json:"perPage"` +} + +// Set 设置Response的Code和Message值 +func (resp *Response) Set(Code int, Message string) *Response { + return &Response{ + Code: Code, + Message: Message, + } +} + +// Set 设置整个Response +func (resp *Response) SetWithData(Code int, Message string, Data interface{}) *Response { + return &Response{ + Code: Code, + Message: Message, + Data: Data, + } +} + +// SetStatus 设置默认StatusResponse(内部自定义) 默认msg, 可以带data, data只使用一个参数 +func (resp *Response) SetStatus(sr *basic.StatusResponse, data ...interface{}) *Response { + newResp := &Response{ + Code: sr.Code, + } + if len(data) == 1 { + newResp.Data = data[0] + } + return newResp +} + +// SetStatusWithMessage 设置默认StatusResponse(内部自定义) 非默认msg, 可以带data, data只使用一个参数 +func (resp *Response) SetStatusWithMessage(sr *basic.StatusResponse, msg string, data ...interface{}) *Response { + newResp := &Response{ + Code: sr.Code, + Message: msg, + } + if len(data) == 1 { + newResp.Data = data[0] + } + return newResp +} diff --git a/server/product-template-tag/product-template-tag.go b/server/product-template-tag/product-template-tag.go new file mode 100644 index 00000000..18898784 --- /dev/null +++ b/server/product-template-tag/product-template-tag.go @@ -0,0 +1,36 @@ +package main + +import ( + "flag" + "fmt" + "net/http" + "time" + + "fusenapi/utils/auth" + + "fusenapi/server/product-template-tag/internal/config" + "fusenapi/server/product-template-tag/internal/handler" + "fusenapi/server/product-template-tag/internal/svc" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/rest" +) + +var configFile = flag.String("f", "etc/product-template-tag.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + c.Timeout = int64(time.Second * 15) + server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { + })) + defer server.Stop() + + ctx := svc.NewServiceContext(c) + handler.RegisterHandlers(server, ctx) + + fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port) + server.Start() +} diff --git a/server_api/product-template-tag.api b/server_api/product-template-tag.api new file mode 100644 index 00000000..ae62099a --- /dev/null +++ b/server_api/product-template-tag.api @@ -0,0 +1,25 @@ +syntax = "v1" + +info ( + title: "产品模板标签服务"// TODO: add title + desc: // TODO: add description + author: "" + email: "" +) + +import "basic.api" + +service product-template-tag { + //获取产品模板标签列表 + @handler GetProductTemplateTagsHandler + get /api/product-template/get_product_template_tags(GetProductTemplateTagsReq) returns (response); +} + +//获取产品模板标签列表 +type GetProductTemplateTagsReq { + Limit int `form:"limit"` +} +type GetProductTemplateTagsRsp { + Tag string `json:"tag"` + Cover string `json:"cover"` +} \ No newline at end of file From 95baad761a8586452293443842cc33df05b2f137 Mon Sep 17 00:00:00 2001 From: Hiven Date: Wed, 26 Jul 2023 11:06:05 +0800 Subject: [PATCH 24/68] =?UTF-8?q?=E6=94=AF=E4=BB=98=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- constants/pay.go | 8 + model/gmodel/fs_order_logic.go | 21 ++ model/gmodel/fs_pay_logic.go | 22 +++ .../home-user-auth/internal/handler/routes.go | 5 + .../handler/userorderdeletehandler.go | 35 ++++ .../internal/logic/userorderdeletelogic.go | 78 ++++++++ server/home-user-auth/internal/types/types.go | 7 + server/pay/etc/pay.yaml | 13 ++ server/pay/internal/config/config.go | 21 ++ .../handler/orderpaymentintenthandler.go | 35 ++++ server/pay/internal/handler/routes.go | 22 +++ .../internal/logic/orderpaymentintentlogic.go | 183 ++++++++++++++++++ server/pay/internal/svc/servicecontext.go | 61 ++++++ server/pay/internal/types/types.go | 86 ++++++++ server/pay/pay.go | 36 ++++ server/pay/pay_test.go | 12 ++ server/websocket/internal/config/config.go | 6 +- server_api/home-user-auth.api | 12 ++ server_api/pay.api | 29 +++ utils/pay/pay.go | 40 ++++ utils/pay/stripe.go | 58 ++++++ 21 files changed, 789 insertions(+), 1 deletion(-) create mode 100644 constants/pay.go create mode 100644 server/home-user-auth/internal/handler/userorderdeletehandler.go create mode 100644 server/home-user-auth/internal/logic/userorderdeletelogic.go create mode 100644 server/pay/etc/pay.yaml create mode 100644 server/pay/internal/config/config.go create mode 100644 server/pay/internal/handler/orderpaymentintenthandler.go create mode 100644 server/pay/internal/handler/routes.go create mode 100644 server/pay/internal/logic/orderpaymentintentlogic.go create mode 100644 server/pay/internal/svc/servicecontext.go create mode 100644 server/pay/internal/types/types.go create mode 100644 server/pay/pay.go create mode 100644 server/pay/pay_test.go create mode 100644 server_api/pay.api create mode 100644 utils/pay/pay.go create mode 100644 utils/pay/stripe.go diff --git a/constants/pay.go b/constants/pay.go new file mode 100644 index 00000000..cd39d457 --- /dev/null +++ b/constants/pay.go @@ -0,0 +1,8 @@ +package constants + +type PayMethod int64 + +const ( + PAYMETHOD_STRIPE PayMethod = 1 + PAYMETHOD_PAYPAL PayMethod = 2 +) diff --git a/model/gmodel/fs_order_logic.go b/model/gmodel/fs_order_logic.go index 93f37a94..16c9a527 100755 --- a/model/gmodel/fs_order_logic.go +++ b/model/gmodel/fs_order_logic.go @@ -136,6 +136,27 @@ func (m *FsOrderModel) FindCount(ctx context.Context, countBuilder *gorm.DB, fil } } +// 事务 +func (m *FsOrderModel) Trans(ctx context.Context, fn func(ctx context.Context, connGorm *gorm.DB) error) error { + tx := m.db.Table(m.name).WithContext(ctx).Begin() + defer func() { + if r := recover(); r != nil { + tx.Rollback() + } + }() + + if err := tx.Error; err != nil { + return err + } + + if err := fn(ctx, tx); err != nil { + tx.Rollback() + return err + } + + return tx.Commit().Error +} + func (m *FsOrderModel) TableName() string { return m.name } diff --git a/model/gmodel/fs_pay_logic.go b/model/gmodel/fs_pay_logic.go index b8de697d..885c7dbc 100644 --- a/model/gmodel/fs_pay_logic.go +++ b/model/gmodel/fs_pay_logic.go @@ -14,3 +14,25 @@ func (p *FsPayModel) GetOrderPayList(ctx context.Context, sn string, payStatus i err = p.db.WithContext(ctx).Model(&FsPay{}).Where("`order_number` = ? and `pay_status` = ? and `is_refund` = ?", sn, payStatus, isRefund).Find(&resp).Error return resp, err } + +func (p *FsPayModel) GetListByOrderNumberStage(ctx context.Context, sn string, stage int64) (resp *FsPay, err error) { + err = p.db.Table(p.name).WithContext(ctx).Model(&FsPay{}).Where("`order_number` = ? ", sn).Where("`pay_stage` = ? ", stage).Take(&resp).Error + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *FsPayModel) CreateOrUpdate(ctx context.Context, req *FsPay) (resp *FsPay, err error) { + rowBuilder := p.db.Table(p.name).WithContext(ctx) + if req.Id > 0 { + err = rowBuilder.Save(req).Error + } else { + err = rowBuilder.Create(req).Error + } + return req, err +} + +func (m *FsPayModel) TableName() string { + return m.name +} diff --git a/server/home-user-auth/internal/handler/routes.go b/server/home-user-auth/internal/handler/routes.go index 75ac9d8f..91852e0d 100644 --- a/server/home-user-auth/internal/handler/routes.go +++ b/server/home-user-auth/internal/handler/routes.go @@ -82,6 +82,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { Path: "/api/user/order-list", Handler: UserOrderListHandler(serverCtx), }, + { + Method: http.MethodGet, + Path: "/api/user/order-delete", + Handler: UserOrderDeleteHandler(serverCtx), + }, { Method: http.MethodGet, Path: "/api/user/order-cancel", diff --git a/server/home-user-auth/internal/handler/userorderdeletehandler.go b/server/home-user-auth/internal/handler/userorderdeletehandler.go new file mode 100644 index 00000000..4b4ca392 --- /dev/null +++ b/server/home-user-auth/internal/handler/userorderdeletehandler.go @@ -0,0 +1,35 @@ +package handler + +import ( + "net/http" + "reflect" + + "fusenapi/utils/basic" + + "fusenapi/server/home-user-auth/internal/logic" + "fusenapi/server/home-user-auth/internal/svc" + "fusenapi/server/home-user-auth/internal/types" +) + +func UserOrderDeleteHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + var req types.UserOrderDeleteReq + userinfo, err := basic.RequestParse(w, r, svcCtx, &req) + if err != nil { + return + } + + // 创建一个业务逻辑层实例 + l := logic.NewUserOrderDeleteLogic(r.Context(), svcCtx) + + rl := reflect.ValueOf(l) + basic.BeforeLogic(w, r, rl) + + resp := l.UserOrderDelete(&req, userinfo) + + if !basic.AfterLogic(w, r, rl, resp) { + basic.NormalAfterLogic(w, r, resp) + } + } +} diff --git a/server/home-user-auth/internal/logic/userorderdeletelogic.go b/server/home-user-auth/internal/logic/userorderdeletelogic.go new file mode 100644 index 00000000..0842b983 --- /dev/null +++ b/server/home-user-auth/internal/logic/userorderdeletelogic.go @@ -0,0 +1,78 @@ +package logic + +import ( + "errors" + "fusenapi/constants" + "fusenapi/model/gmodel" + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "context" + + "fusenapi/server/home-user-auth/internal/svc" + "fusenapi/server/home-user-auth/internal/types" + + "github.com/zeromicro/go-zero/core/logx" + "gorm.io/gorm" +) + +type UserOrderDeleteLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewUserOrderDeleteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserOrderDeleteLogic { + return &UserOrderDeleteLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +// 处理进入前逻辑w,r +// func (l *UserOrderDeleteLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) { +// } + +// 处理逻辑后 w,r 如:重定向, resp 必须重新处理 +// func (l *UserOrderDeleteLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { +// // httpx.OkJsonCtx(r.Context(), w, resp) +// } + +func (l *UserOrderDeleteLogic) UserOrderDelete(req *types.UserOrderDeleteReq, userinfo *auth.UserInfo) (resp *basic.Response) { + // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) + // userinfo 传入值时, 一定不为null + + if userinfo == nil || userinfo.UserId == 0 { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + } + + orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn) + orderInfo, err := orderModel.FindOne(l.ctx, userinfo.UserId, req.ID) + + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + } + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info") + } + + updateStatusMap := make(map[constants.Order]struct{}, 4) + updateStatusMap[constants.STATUS_NEW_COMPLETED] = struct{}{} + updateStatusMap[constants.STATUS_NEW_CANCEL] = struct{}{} + updateStatusMap[constants.STATUS_NEW_REFUNDED] = struct{}{} + updateStatusMap[constants.STATUS_NEW_CLOSE] = struct{}{} + if _, ok := updateStatusMap[constants.Order(*orderInfo.Status)]; !ok { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + } + *orderInfo.Status = int64(constants.STATUS_NEW_DELETE) + *orderInfo.IsDeleted = 1 + err = orderModel.Update(l.ctx, orderInfo) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "fail to delete") + } + + return resp.SetStatus(basic.CodeOK) +} diff --git a/server/home-user-auth/internal/types/types.go b/server/home-user-auth/internal/types/types.go index ef269467..81011e49 100644 --- a/server/home-user-auth/internal/types/types.go +++ b/server/home-user-auth/internal/types/types.go @@ -5,6 +5,13 @@ import ( "fusenapi/utils/basic" ) +type UserOrderDeleteReq struct { + ID int64 `form:"id"` //订单id +} + +type UserOrderDeleteRes struct { +} + type UserOrderCancelReq struct { ID int64 `form:"id"` //订单id RefundReasonId int64 `form:"refund_reason_id"` //退款配置id diff --git a/server/pay/etc/pay.yaml b/server/pay/etc/pay.yaml new file mode 100644 index 00000000..dcc6a6fe --- /dev/null +++ b/server/pay/etc/pay.yaml @@ -0,0 +1,13 @@ +Name: pay +Host: 0.0.0.0 +Port: 9915 +SourceMysql: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest +Auth: + AccessSecret: fusen2023 + AccessExpire: 2592000 + RefreshAfter: 1592000 +PayConfig: + Stripe: + Key: "sk_test_51IisojHygnIJZeghPVSBhkwySfcyDV4SoAduIxu3J7bvSJ9cZMD96LY1LO6SpdbYquLJX5oKvgEBB67KT9pecfCy00iEC4pp9y" + SuccessURL: "http://www.baidu.com" + CancelURL: "http://www.baidu.com" \ No newline at end of file diff --git a/server/pay/internal/config/config.go b/server/pay/internal/config/config.go new file mode 100644 index 00000000..d032023a --- /dev/null +++ b/server/pay/internal/config/config.go @@ -0,0 +1,21 @@ +package config + +import ( + "fusenapi/server/pay/internal/types" + + "github.com/zeromicro/go-zero/rest" +) + +type Config struct { + rest.RestConf + SourceMysql string + Auth types.Auth + + PayConfig struct { + Stripe struct { + Key string + SuccessURL string + CancelURL string + } + } +} diff --git a/server/pay/internal/handler/orderpaymentintenthandler.go b/server/pay/internal/handler/orderpaymentintenthandler.go new file mode 100644 index 00000000..d252d73c --- /dev/null +++ b/server/pay/internal/handler/orderpaymentintenthandler.go @@ -0,0 +1,35 @@ +package handler + +import ( + "net/http" + "reflect" + + "fusenapi/utils/basic" + + "fusenapi/server/pay/internal/logic" + "fusenapi/server/pay/internal/svc" + "fusenapi/server/pay/internal/types" +) + +func OrderPaymentIntentHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + var req types.OrderPaymentIntentReq + userinfo, err := basic.RequestParse(w, r, svcCtx, &req) + if err != nil { + return + } + + // 创建一个业务逻辑层实例 + l := logic.NewOrderPaymentIntentLogic(r.Context(), svcCtx) + + rl := reflect.ValueOf(l) + basic.BeforeLogic(w, r, rl) + + resp := l.OrderPaymentIntent(&req, userinfo) + + if !basic.AfterLogic(w, r, rl, resp) { + basic.NormalAfterLogic(w, r, resp) + } + } +} diff --git a/server/pay/internal/handler/routes.go b/server/pay/internal/handler/routes.go new file mode 100644 index 00000000..13f9ba4c --- /dev/null +++ b/server/pay/internal/handler/routes.go @@ -0,0 +1,22 @@ +// Code generated by goctl. DO NOT EDIT. +package handler + +import ( + "net/http" + + "fusenapi/server/pay/internal/svc" + + "github.com/zeromicro/go-zero/rest" +) + +func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { + server.AddRoutes( + []rest.Route{ + { + Method: http.MethodPost, + Path: "/api/pay/payment-intent", + Handler: OrderPaymentIntentHandler(serverCtx), + }, + }, + ) +} diff --git a/server/pay/internal/logic/orderpaymentintentlogic.go b/server/pay/internal/logic/orderpaymentintentlogic.go new file mode 100644 index 00000000..98c5f0d0 --- /dev/null +++ b/server/pay/internal/logic/orderpaymentintentlogic.go @@ -0,0 +1,183 @@ +package logic + +import ( + "errors" + "fusenapi/constants" + "fusenapi/model/gmodel" + "fusenapi/utils/auth" + "fusenapi/utils/basic" + "fusenapi/utils/pay" + "time" + + "context" + + "fusenapi/server/pay/internal/svc" + "fusenapi/server/pay/internal/types" + + "github.com/zeromicro/go-zero/core/logx" + "gorm.io/gorm" +) + +type OrderPaymentIntentLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewOrderPaymentIntentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderPaymentIntentLogic { + return &OrderPaymentIntentLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +// 处理进入前逻辑w,r +// func (l *OrderPaymentIntentLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) { +// } + +// 处理逻辑后 w,r 如:重定向, resp 必须重新处理 +// func (l *OrderPaymentIntentLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { +// // httpx.OkJsonCtx(r.Context(), w, resp) +// } + +func (l *OrderPaymentIntentLogic) OrderPaymentIntent(req *types.OrderPaymentIntentReq, userinfo *auth.UserInfo) (resp *basic.Response) { + // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) + // userinfo 传入值时, 一定不为null + + if userinfo == nil || userinfo.UserId == 0 { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + } + + // 查询订单数据 + orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn) + orderInfo, err := orderModel.FindOneBySn(l.ctx, userinfo.UserId, req.Sn) + + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + } + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info") + } + + // 校验订单状态 + if *orderInfo.IsCancel == 1 { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "order cancelled") + } + + // 校验地址信息 + addressModel := gmodel.NewFsAddressModel(l.svcCtx.MysqlConn) + _, err = addressModel.GetOne(l.ctx, req.AddressId, userinfo.UserId) + + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "address not found") + } + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get address info") + } + + // 校验订单支付信息 + if *orderInfo.IsPayCompleted == 1 { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "order is pay completed") + } + + // 判断订单状态以及该支付金额 + // 未支付 + var payAmount int64 + if *orderInfo.Status == int64(constants.STATUS_NEW_NOT_PAY) { + payAmount = *orderInfo.TotalAmount / 2 + *orderInfo.DeliveryMethod = req.DeliveryMethod + *orderInfo.AddressId = req.AddressId + *orderInfo.PayMethod = req.PayMethod + } else { + payAmount = *orderInfo.TotalAmount - *orderInfo.TotalAmount/2 + } + + payConfig := &pay.Config{} + var generatePrepaymentReq = &pay.GeneratePrepaymentReq{ + ProductName: "aa", + Amount: payAmount, + Currency: "eur", + Quantity: 1, + ProductDescription: "ddddddddddddddddddddddd", + } + if constants.PayMethod(req.PayMethod) == constants.PAYMETHOD_STRIPE { + payConfig.Stripe.Key = l.svcCtx.Config.PayConfig.Stripe.Key + generatePrepaymentReq.SuccessURL = l.svcCtx.Config.PayConfig.Stripe.SuccessURL + generatePrepaymentReq.CancelURL = l.svcCtx.Config.PayConfig.Stripe.CancelURL + } + payDriver := pay.NewPayDriver(req.PayMethod, payConfig) + + var resData types.OrderPaymentIntentRes + // 事务处理 + err = orderModel.Trans(l.ctx, func(ctx context.Context, connGorm *gorm.DB) error { + // 支付预付--生成 + prepaymentRes, err := payDriver.GeneratePrepayment(generatePrepaymentReq) + if err != nil { + return err + } + resData.RedirectUrl = prepaymentRes.URL + + // 订单信息--修改 + err = gmodel.NewFsOrderModel(connGorm).Update(ctx, orderInfo) + if err != nil { + return err + } + + // 支付记录--处理 //支付记录改为一条订单多条,分首款尾款 + var createdAt int64 = time.Now().Unix() + var payStatus int64 = 0 + var orderSource int64 = 1 + var payStage int64 + var fspay *gmodel.FsPay + newFsPayModel := gmodel.NewFsPayModel(connGorm) + if *orderInfo.Status == int64(constants.STATUS_NEW_NOT_PAY) { + fspay, err = newFsPayModel.GetListByOrderNumberStage(ctx, *orderInfo.Sn, 1) + if err != nil { + if !errors.Is(err, gorm.ErrRecordNotFound) { + return err + } + } + payStage = 1 + } else { + fspay, err = newFsPayModel.GetListByOrderNumberStage(ctx, *orderInfo.Sn, 2) + if err != nil { + if !errors.Is(err, gorm.ErrRecordNotFound) { + return err + } + } + payStage = 2 + } + if fspay == nil { + fspay = &gmodel.FsPay{ + UserId: orderInfo.UserId, + OrderNumber: orderInfo.Sn, + CreatedAt: &createdAt, + } + } else { + fspay.UpdatedAt = &createdAt + } + fspay.PayAmount = &payAmount + fspay.PayStage = &payStage + fspay.TradeNo = &prepaymentRes.TradeNo + fspay.PaymentMethod = &req.PayMethod + fspay.OrderSource = &orderSource + fspay.PayStatus = &payStatus + + _, err = newFsPayModel.CreateOrUpdate(ctx, fspay) + if err != nil { + return err + } + + return nil + }) + + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to make payment") + } + + return resp.SetStatusWithMessage(basic.CodeOK, "success", resData) +} diff --git a/server/pay/internal/svc/servicecontext.go b/server/pay/internal/svc/servicecontext.go new file mode 100644 index 00000000..e94ec174 --- /dev/null +++ b/server/pay/internal/svc/servicecontext.go @@ -0,0 +1,61 @@ +package svc + +import ( + "errors" + "fmt" + "fusenapi/server/pay/internal/config" + "net/http" + + "fusenapi/initalize" + "fusenapi/model/gmodel" + + "github.com/golang-jwt/jwt" + "gorm.io/gorm" +) + +type ServiceContext struct { + Config config.Config + + MysqlConn *gorm.DB + AllModels *gmodel.AllModelsGen +} + +func NewServiceContext(c config.Config) *ServiceContext { + + return &ServiceContext{ + Config: c, + MysqlConn: initalize.InitMysql(c.SourceMysql), + AllModels: gmodel.NewAllModels(initalize.InitMysql(c.SourceMysql)), + } +} + +func (svcCtx *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) { + AuthKey := r.Header.Get("Authorization") + if AuthKey == "" { + return nil, nil + } + AuthKey = AuthKey[7:] + + if len(AuthKey) <= 50 { + return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey))) + } + + token, err := jwt.Parse(AuthKey, func(token *jwt.Token) (interface{}, error) { + // 检查签名方法是否为 HS256 + if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) + } + // 返回用于验证签名的密钥 + return []byte(svcCtx.Config.Auth.AccessSecret), nil + }) + if err != nil { + return nil, errors.New(fmt.Sprint("Error parsing token:", err)) + } + + // 验证成功返回 + if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { + return claims, nil + } + + return nil, errors.New(fmt.Sprint("Invalid token", err)) +} diff --git a/server/pay/internal/types/types.go b/server/pay/internal/types/types.go new file mode 100644 index 00000000..13a18778 --- /dev/null +++ b/server/pay/internal/types/types.go @@ -0,0 +1,86 @@ +// Code generated by goctl. DO NOT EDIT. +package types + +import ( + "fusenapi/utils/basic" +) + +type OrderPaymentIntentReq struct { + Sn string `form:"sn"` //订单编号 + DeliveryMethod int64 `form:"delivery_method"` //发货方式 + AddressId int64 `form:"address_id"` //地址id + PayMethod int64 `form:"pay_method"` //支付方式 +} + +type OrderPaymentIntentRes struct { + RedirectUrl string `json:"redirect_url"` +} + +type Request struct { +} + +type Response struct { + Code int `json:"code"` + Message string `json:"msg"` + Data interface{} `json:"data"` +} + +type Auth struct { + AccessSecret string `json:"accessSecret"` + AccessExpire int64 `json:"accessExpire"` + RefreshAfter int64 `json:"refreshAfter"` +} + +type File struct { + Filename string `fsfile:"filename"` + Header map[string][]string `fsfile:"header"` + Size int64 `fsfile:"size"` + Data []byte `fsfile:"data"` +} + +type Meta struct { + TotalCount int64 `json:"totalCount"` + PageCount int64 `json:"pageCount"` + CurrentPage int `json:"currentPage"` + PerPage int `json:"perPage"` +} + +// Set 设置Response的Code和Message值 +func (resp *Response) Set(Code int, Message string) *Response { + return &Response{ + Code: Code, + Message: Message, + } +} + +// Set 设置整个Response +func (resp *Response) SetWithData(Code int, Message string, Data interface{}) *Response { + return &Response{ + Code: Code, + Message: Message, + Data: Data, + } +} + +// SetStatus 设置默认StatusResponse(内部自定义) 默认msg, 可以带data, data只使用一个参数 +func (resp *Response) SetStatus(sr *basic.StatusResponse, data ...interface{}) *Response { + newResp := &Response{ + Code: sr.Code, + } + if len(data) == 1 { + newResp.Data = data[0] + } + return newResp +} + +// SetStatusWithMessage 设置默认StatusResponse(内部自定义) 非默认msg, 可以带data, data只使用一个参数 +func (resp *Response) SetStatusWithMessage(sr *basic.StatusResponse, msg string, data ...interface{}) *Response { + newResp := &Response{ + Code: sr.Code, + Message: msg, + } + if len(data) == 1 { + newResp.Data = data[0] + } + return newResp +} diff --git a/server/pay/pay.go b/server/pay/pay.go new file mode 100644 index 00000000..08c53e12 --- /dev/null +++ b/server/pay/pay.go @@ -0,0 +1,36 @@ +package main + +import ( + "flag" + "fmt" + "net/http" + "time" + + "fusenapi/utils/auth" + + "fusenapi/server/pay/internal/config" + "fusenapi/server/pay/internal/handler" + "fusenapi/server/pay/internal/svc" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/rest" +) + +var configFile = flag.String("f", "etc/pay.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + c.Timeout = int64(time.Second * 15) + server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { + })) + defer server.Stop() + + ctx := svc.NewServiceContext(c) + handler.RegisterHandlers(server, ctx) + + fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port) + server.Start() +} diff --git a/server/pay/pay_test.go b/server/pay/pay_test.go new file mode 100644 index 00000000..d035c13a --- /dev/null +++ b/server/pay/pay_test.go @@ -0,0 +1,12 @@ +package main + +import ( + "testing" +) + +// var configFile = flag.String("f", "etc/home-user-auth.yaml", "the config file") + +func TestMain(t *testing.T) { + // log.Println(model.RawFieldNames[FsCanteenType]()) + main() +} diff --git a/server/websocket/internal/config/config.go b/server/websocket/internal/config/config.go index b24bb7d7..3ed0e8c4 100644 --- a/server/websocket/internal/config/config.go +++ b/server/websocket/internal/config/config.go @@ -1,6 +1,10 @@ package config -import "github.com/zeromicro/go-zero/rest" +import ( + "fusenapi/server/websocket/internal/types" + + "github.com/zeromicro/go-zero/rest" +) type Config struct { rest.RestConf diff --git a/server_api/home-user-auth.api b/server_api/home-user-auth.api index f3a19304..bc07a158 100644 --- a/server_api/home-user-auth.api +++ b/server_api/home-user-auth.api @@ -60,12 +60,24 @@ service home-user-auth { @handler UserOrderListHandler get /api/user/order-list (UserOrderListReq) returns (response); + //删除订单 + @handler UserOrderDeleteHandler + get /api/user/order-delete (UserOrderDeleteReq) returns (response); + //取消订单 @handler UserOrderCancelHandler get /api/user/order-cancel (UserOrderCancelReq) returns (response); } +type ( + UserOrderDeleteReq { + ID int64 `form:"id"` //订单id + } + UserOrderDeleteRes { + } +) + //取消订单 type ( UserOrderCancelReq { diff --git a/server_api/pay.api b/server_api/pay.api new file mode 100644 index 00000000..f94d77a9 --- /dev/null +++ b/server_api/pay.api @@ -0,0 +1,29 @@ +syntax = "v1" + +info ( + title: 支付模块 + desc: 支付相关 + author: "" + email: "" +) + +import "basic.api" + +service pay { + + @handler OrderPaymentIntentHandler + post /api/pay/payment-intent(OrderPaymentIntentReq) returns (response); +} + +// 生成预付款 +type ( + OrderPaymentIntentReq { + Sn string `form:"sn"` //订单编号 + DeliveryMethod int64 `form:"delivery_method"` //发货方式 + AddressId int64 `form:"address_id"` //地址id + PayMethod int64 `form:"pay_method"` //支付方式 + } + OrderPaymentIntentRes { + RedirectUrl string `json:"redirect_url"` + } +) \ No newline at end of file diff --git a/utils/pay/pay.go b/utils/pay/pay.go new file mode 100644 index 00000000..005d700d --- /dev/null +++ b/utils/pay/pay.go @@ -0,0 +1,40 @@ +package pay + +import "fusenapi/constants" + +type Config struct { + // stripe支付 + Stripe Stripe +} + +// NewPayDriver 实例化方法 +func NewPayDriver(PayMethod int64, config *Config) Pay { + switch PayMethod { + case int64(constants.PAYMETHOD_STRIPE): + return &Stripe{Key: config.Stripe.Key} + default: + return &Stripe{Key: config.Stripe.Key} + } + +} + +// Pay 支付集成接口 +type Pay interface { + GeneratePrepayment(req *GeneratePrepaymentReq) (res *GeneratePrepaymentRes, err error) +} + +type GeneratePrepaymentReq struct { + Amount int64 `json:"amount"` // 支付金额 + Currency string `json:"currency"` // 支付货币 + ProductName string `json:"product_name"` // 商品名称 + ProductDescription string `json:"product_description"` // 商品描述 + ProductImages []*string `json:"product_imageso"` // 商品照片 + Quantity int64 `json:"quantity"` //数量 + SuccessURL string `json:"success_url"` // 支付成功回调 + CancelURL string `json:"cancel_url"` // 支付取消回调 +} + +type GeneratePrepaymentRes struct { + URL string `json:"url"` // 支付重定向地址 + TradeNo string `json:"trade_no"` //交易ID +} diff --git a/utils/pay/stripe.go b/utils/pay/stripe.go new file mode 100644 index 00000000..9dc5a2cf --- /dev/null +++ b/utils/pay/stripe.go @@ -0,0 +1,58 @@ +package pay + +import ( + "github.com/stripe/stripe-go/v74" + "github.com/stripe/stripe-go/v74/checkout/session" +) + +type Stripe struct { + Key string `json:"key"` +} + +// 生成预付款 +func (stripePay *Stripe) GeneratePrepayment(req *GeneratePrepaymentReq) (res *GeneratePrepaymentRes, err error) { + var productData stripe.CheckoutSessionLineItemPriceDataProductDataParams + + if req.ProductName != "" { + productData.Name = stripe.String(req.ProductName) + } + + if req.ProductDescription != "" { + productData.Description = stripe.String(req.ProductDescription) + } + + if len(req.ProductImages) > 0 { + productData.Images = req.ProductImages + } + // var images = make([]*string, 1) + // var image string = "https://img2.woyaogexing.com/2023/07/25/133132a32b9f79cfad84965a4bea57e0.jpg" + // images[0] = stripe.String(image) + // productData.Images = images + stripe.Key = stripePay.Key + + params := &stripe.CheckoutSessionParams{ + LineItems: []*stripe.CheckoutSessionLineItemParams{ + { + PriceData: &stripe.CheckoutSessionLineItemPriceDataParams{ + Currency: stripe.String(req.Currency), + ProductData: &productData, + UnitAmount: stripe.Int64(req.Amount), + }, + Quantity: stripe.Int64(req.Quantity), + }, + }, + Mode: stripe.String(string(stripe.CheckoutSessionModePayment)), + SuccessURL: stripe.String(req.SuccessURL), + CancelURL: stripe.String(req.CancelURL), + } + result, err := session.New(params) + + if err != nil { + return nil, err + } + + return &GeneratePrepaymentRes{ + URL: result.URL, + TradeNo: result.ID, + }, err +} From 999dc36e764e5927526418f29508378127dd8b56 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 11:53:06 +0800 Subject: [PATCH 25/68] fix --- .../internal/handler/datatransferhandler.go | 257 +---------------- .../internal/handler/rendernotifyhandler.go | 72 +---- .../internal/logic/datatransferlogic.go | 264 +++++++++++++++++- .../internal/logic/rendernotifylogic.go | 36 ++- server/websocket/internal/types/types.go | 7 +- server_api/websocket.api | 8 +- 6 files changed, 300 insertions(+), 344 deletions(-) diff --git a/server/websocket/internal/handler/datatransferhandler.go b/server/websocket/internal/handler/datatransferhandler.go index 3e5177d7..8ef09842 100644 --- a/server/websocket/internal/handler/datatransferhandler.go +++ b/server/websocket/internal/handler/datatransferhandler.go @@ -1,270 +1,15 @@ package handler import ( - "encoding/json" - "fmt" - "fusenapi/constants" "fusenapi/server/websocket/internal/logic" "fusenapi/server/websocket/internal/svc" - "fusenapi/server/websocket/internal/types" - "fusenapi/utils/auth" - "github.com/google/uuid" - "github.com/gorilla/websocket" - "github.com/zeromicro/go-zero/core/logx" "net/http" - "sync" - "time" ) -var ( - //升级 - upgrade = websocket.Upgrader{ - //允许跨域 - CheckOrigin: func(r *http.Request) bool { - return true - }, - } - //连接map池 - mapConnPool = sync.Map{} -) - -// 每个连接的连接属性 -type wsConnectItem struct { - conn *websocket.Conn //websocket的连接 - closeChan chan struct{} //关闭chan - isClose bool //是否已经关闭 - flag string - inChan chan []byte //接受消息缓冲通道 - outChan chan []byte //发送回客户端的消息 - mutex sync.Mutex - renderImage map[string]struct{} //需要渲染的图片 -} - func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // 创建一个业务逻辑层实例 - var req types.DataTransferReq l := logic.NewDataTransferLogic(r.Context(), svcCtx) - l.DataTransfer(&req, nil) - //升级websocket - conn, err := upgrade.Upgrade(w, r, nil) - if err != nil { - logx.Error("http upgrade websocket err:", err) - return - } - defer conn.Close() - rsp := types.DataTransferRsp{} - isAuth := true - // 解析JWT token,并对空用户进行判断 - claims, err := svcCtx.ParseJwtToken(r) - // 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息 - if err != nil { - rsp.T = constants.WEBSOCKET_UNAUTH - rsp.D = "unAuth" - b, _ := json.Marshal(rsp) - _ = conn.WriteMessage(websocket.TextMessage, b) - isAuth = false - } - if claims != nil { - // 从token中获取对应的用户信息 - _, err = auth.GetUserInfoFormMapClaims(claims) - // 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息 - if err != nil { - rsp.T = constants.WEBSOCKET_UNAUTH - rsp.D = "unAuth!!" - b, _ := json.Marshal(rsp) - _ = conn.WriteMessage(websocket.TextMessage, b) - isAuth = false - } - } else { - // 如果claims为nil,则认为用户身份为白板用户 - rsp.T = constants.WEBSOCKET_UNAUTH - rsp.D = "unAuth!!!" - b, _ := json.Marshal(rsp) - _ = conn.WriteMessage(websocket.TextMessage, b) - isAuth = false - } - //不是授权的连接(10秒后关闭) - if !isAuth { - select { - case <-time.After(time.Second * 10): - conn.Close() - return - } - } - //生成连接唯一标识 - flag := uuid.New().String() + time.Now().Format("20060102150405") - ws := wsConnectItem{ - conn: conn, - flag: flag, - closeChan: make(chan struct{}, 1), - inChan: make(chan []byte, 100), - outChan: make(chan []byte, 100), - renderImage: make(map[string]struct{}), - isClose: false, - } - //保存连接 - mapConnPool.Store(flag, ws) - defer ws.close() - //把连接成功消息发回去 - rsp.T = constants.WEBSOCKET_CONNECT_SUCCESS - rsp.D = flag - b, _ := json.Marshal(rsp) - conn.WriteMessage(websocket.TextMessage, b) - //循环读客户端信息 - go ws.readLoop() - //循环把数据发送给客户端 - go ws.writeLoop() - //推消息到云渲染 - go ws.sendLoop() - //心跳 - ws.heartbeat() - + l.DataTransfer(svcCtx, w, r) } } - -// 心跳 -func (w *wsConnectItem) heartbeat() { - rsp := types.DataTransferRsp{ - T: constants.WEBSOCKET_HEARTBEAT, - D: "", - } - b, _ := json.Marshal(rsp) - for { - time.Sleep(time.Second * 10) - select { - case <-w.closeChan: - return - default: - - } - //发送心跳信息 - if err := w.conn.WriteMessage(websocket.TextMessage, b); err != nil { - logx.Error("发送心跳信息异常,关闭连接:", w.flag, err) - w.close() - return - } - } -} - -// 关闭连接 -func (w *wsConnectItem) close() { - w.mutex.Lock() - defer w.mutex.Unlock() - logx.Info("websocket:", w.flag, " is closing...") - w.conn.Close() - mapConnPool.Delete(w.flag) - if !w.isClose { - w.isClose = true - close(w.closeChan) - close(w.outChan) - close(w.inChan) - } - logx.Info("websocket:", w.flag, " is closed") -} - -func (w *wsConnectItem) writeLoop() { - for { - select { - case <-w.closeChan: //如果关闭了 - return - case data := <-w.outChan: - w.conn.WriteMessage(websocket.TextMessage, data) - } - } -} - -// 接受客户端发来的消息 -func (w *wsConnectItem) readLoop() { - for { - select { - case <-w.closeChan: //如果关闭了 - return - default: - - } - _, data, err := w.conn.ReadMessage() - if err != nil { - logx.Error("接受信息错误:", err) - //关闭连接 - w.close() - return - } - //消息传入缓冲通道 - w.inChan <- data - } -} - -// 把收到的消息发往不同的地方处理 -func (w *wsConnectItem) sendLoop() { - for { - select { - case <-w.closeChan: - return - case data := <-w.inChan: - w.dealwithReciveData(data) - } - } -} - -// 处理接受到的数据 -func (w *wsConnectItem) dealwithReciveData(data []byte) { - var parseInfo types.DataTransferReq - if err := json.Unmarshal(data, &parseInfo); err != nil { - logx.Error("invalid format of websocket message") - return - } - switch parseInfo.T { - //图片渲染 - case constants.WEBSOCKET_RENDER_IMAGE: - var renderImageData []types.RenderImageReqMsg - if err := json.Unmarshal([]byte(parseInfo.D), &renderImageData); err != nil { - logx.Error("invalid format of websocket render image message", err) - return - } - logx.Info("收到请求云渲染图片数据:", renderImageData) - w.mutex.Lock() - defer w.mutex.Unlock() - //把需要渲染的图片加进去 - for _, v := range renderImageData { - key := w.getRenderImageMapKey(v.ProductId, v.SizeId, v.TemplateId) - w.renderImage[key] = struct{}{} - } - default: - - } -} - -// 把渲染好的数据放入outchan -func (w *wsConnectItem) setOutRenderImage(req types.RenderNotifyReq) { - w.mutex.Lock() - defer w.mutex.Unlock() - for _, notifyItem := range req.NotifyList { - renderKey := w.getRenderImageMapKey(notifyItem.ProductId, notifyItem.SizeId, notifyItem.TemplateId) - //查询 - _, ok := w.renderImage[renderKey] - if !ok { - continue - } - responseData := types.RenderImageRspMsg{ - ProductId: notifyItem.ProductId, - SizeId: notifyItem.SizeId, - TemplateId: notifyItem.TemplateId, - Source: "我是渲染资源", - } - b, _ := json.Marshal(responseData) - select { - case <-w.closeChan: - return - case w.outChan <- b: - logx.Info("notify send render result to out chan") - } - //删掉已经处理的渲染任务 - delete(w.renderImage, renderKey) - } -} - -// 获取需要渲染图片的map key -func (w *wsConnectItem) getRenderImageMapKey(productId, sizeId, templateId int64) string { - return fmt.Sprintf("%d-%d-%d", productId, sizeId, templateId) -} diff --git a/server/websocket/internal/handler/rendernotifyhandler.go b/server/websocket/internal/handler/rendernotifyhandler.go index 005ee044..ab16cdad 100644 --- a/server/websocket/internal/handler/rendernotifyhandler.go +++ b/server/websocket/internal/handler/rendernotifyhandler.go @@ -1,18 +1,12 @@ package handler import ( - "crypto/sha256" - "encoding/hex" - "encoding/json" - "fmt" - "fusenapi/constants" - "fusenapi/utils/basic" - "github.com/zeromicro/go-zero/rest/httpx" - "net/http" - "time" - + "fusenapi/server/websocket/internal/logic" "fusenapi/server/websocket/internal/svc" "fusenapi/server/websocket/internal/types" + "fusenapi/utils/basic" + "net/http" + "reflect" ) func RenderNotifyHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { @@ -20,56 +14,18 @@ func RenderNotifyHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { var req types.RenderNotifyReq _, err := basic.RequestParse(w, r, svcCtx, &req) if err != nil { - httpx.OkJsonCtx(r.Context(), w, basic.Response{ - Code: basic.CodeRequestParamsErr.Code, - Message: "err param", - Data: nil, - }) return } - if len(req.NotifyList) == 0 { - httpx.OkJsonCtx(r.Context(), w, basic.Response{ - Code: basic.CodeRequestParamsErr.Code, - Message: "invalid param,notify list is empty", - Data: nil, - }) - return + // 创建一个业务逻辑层实例 + l := logic.NewRenderNotifyLogic(r.Context(), svcCtx) + + rl := reflect.ValueOf(l) + basic.BeforeLogic(w, r, rl) + + resp := l.RenderNotify(&req) + + if !basic.AfterLogic(w, r, rl, resp) { + basic.NormalAfterLogic(w, r, resp) } - if time.Now().Unix()-120 > req.Time /*|| req.Time > time.Now().Unix() */ { - httpx.OkJsonCtx(r.Context(), w, basic.Response{ - Code: basic.CodeRequestParamsErr.Code, - Message: "invalid param,time is expired", - Data: nil, - }) - return - } - //验证签名 sha256 - notifyByte, _ := json.Marshal(req.NotifyList) - 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) - if req.Sign != sign { - httpx.OkJsonCtx(r.Context(), w, basic.Response{ - Code: basic.CodeRequestParamsErr.Code, - Message: "invalid sign", - Data: nil, - }) - return - } - //遍历链接 - mapConnPool.Range(func(key, value any) bool { - ws, ok := value.(wsConnectItem) - if !ok { - return false - } - ws.setOutRenderImage(req) - return true - }) - httpx.OkJsonCtx(r.Context(), w, basic.Response{ - Code: 200, - Message: "success", - Data: nil, - }) } } diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 7b5db86b..17792d10 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -1,14 +1,20 @@ package logic import ( - "fusenapi/utils/auth" + "encoding/json" + "fmt" + "fusenapi/constants" + "fusenapi/server/websocket/internal/types" "fusenapi/utils/basic" + "github.com/google/uuid" + "github.com/gorilla/websocket" + "net/http" + "sync" + "time" "context" "fusenapi/server/websocket/internal/svc" - "fusenapi/server/websocket/internal/types" - "github.com/zeromicro/go-zero/core/logx" ) @@ -26,18 +32,250 @@ func NewDataTransferLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Data } } -// 处理进入前逻辑w,r -// func (l *DataTransferLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) { -// } +var ( + //升级 + upgrade = websocket.Upgrader{ + //允许跨域 + CheckOrigin: func(r *http.Request) bool { + return true + }, + } + //连接map池 + mapConnPool = sync.Map{} +) -// 处理逻辑后 w,r 如:重定向, resp 必须重新处理 -// func (l *DataTransferLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { -// // httpx.OkJsonCtx(r.Context(), w, resp) -// } +// 每个连接的连接属性 +type wsConnectItem struct { + conn *websocket.Conn //websocket的连接 + closeChan chan struct{} //关闭chan + isClose bool //是否已经关闭 + flag string + inChan chan []byte //接受消息缓冲通道 + outChan chan []byte //发送回客户端的消息 + mutex sync.Mutex + renderImage map[string]struct{} //需要渲染的图片 +} -func (l *DataTransferLogic) DataTransfer(req *types.DataTransferReq, userinfo *auth.UserInfo) (resp *basic.Response) { - // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) - // userinfo 传入值时, 一定不为null +func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.ResponseWriter, r *http.Request) (resp *basic.Response) { + //升级websocket + conn, err := upgrade.Upgrade(w, r, nil) + if err != nil { + logx.Error("http upgrade websocket err:", err) + return + } + defer conn.Close() + rsp := types.DataTransferData{} + /*isAuth := true + // 解析JWT token,并对空用户进行判断 + claims, err := svcCtx.ParseJwtToken(r) + // 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息 + if err != nil { + rsp.T = constants.WEBSOCKET_UNAUTH + rsp.D = "unAuth" + b, _ := json.Marshal(rsp) + _ = conn.WriteMessage(websocket.TextMessage, b) + isAuth = false + } + if claims != nil { + // 从token中获取对应的用户信息 + _, err = auth.GetUserInfoFormMapClaims(claims) + // 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息 + if err != nil { + rsp.T = constants.WEBSOCKET_UNAUTH + rsp.D = "unAuth!!" + b, _ := json.Marshal(rsp) + _ = conn.WriteMessage(websocket.TextMessage, b) + isAuth = false + } + } else { + // 如果claims为nil,则认为用户身份为白板用户 + rsp.T = constants.WEBSOCKET_UNAUTH + rsp.D = "unAuth!!!" + b, _ := json.Marshal(rsp) + _ = conn.WriteMessage(websocket.TextMessage, b) + isAuth = false + } + //不是授权的连接(10秒后关闭) + if !isAuth { + select { + case <-time.After(time.Second * 10): + conn.Close() + return + } + }*/ + //生成连接唯一标识 + flag := uuid.New().String() + time.Now().Format("20060102150405") + ws := wsConnectItem{ + conn: conn, + flag: flag, + closeChan: make(chan struct{}, 1), + inChan: make(chan []byte, 100), + outChan: make(chan []byte, 100), + renderImage: make(map[string]struct{}), + isClose: false, + } + //保存连接 + mapConnPool.Store(flag, ws) + defer ws.close() + //把连接成功消息发回去 + rsp.T = constants.WEBSOCKET_CONNECT_SUCCESS + rsp.D = flag + b, _ := json.Marshal(rsp) + conn.WriteMessage(websocket.TextMessage, b) + //循环读客户端信息 + go ws.readLoop() + //循环把数据发送给客户端 + go ws.writeLoop() + //推消息到云渲染 + go ws.sendLoop() + //心跳 + ws.heartbeat() return resp.SetStatus(basic.CodeOK) } + +// 心跳 +func (w *wsConnectItem) heartbeat() { + rsp := types.DataTransferData{ + T: constants.WEBSOCKET_HEARTBEAT, + D: "", + } + b, _ := json.Marshal(rsp) + for { + time.Sleep(time.Second * 10) + select { + case <-w.closeChan: + return + default: + + } + //发送心跳信息 + if err := w.conn.WriteMessage(websocket.TextMessage, b); err != nil { + logx.Error("发送心跳信息异常,关闭连接:", w.flag, err) + w.close() + return + } + } +} + +// 关闭连接 +func (w *wsConnectItem) close() { + w.mutex.Lock() + defer w.mutex.Unlock() + logx.Info("websocket:", w.flag, " is closing...") + w.conn.Close() + mapConnPool.Delete(w.flag) + if !w.isClose { + w.isClose = true + close(w.closeChan) + close(w.outChan) + close(w.inChan) + } + logx.Info("websocket:", w.flag, " is closed") +} + +func (w *wsConnectItem) writeLoop() { + for { + select { + case <-w.closeChan: //如果关闭了 + return + case data := <-w.outChan: + w.conn.WriteMessage(websocket.TextMessage, data) + } + } +} + +// 接受客户端发来的消息 +func (w *wsConnectItem) readLoop() { + for { + select { + case <-w.closeChan: //如果关闭了 + return + default: + + } + _, data, err := w.conn.ReadMessage() + if err != nil { + logx.Error("接受信息错误:", err) + //关闭连接 + w.close() + return + } + //消息传入缓冲通道 + w.inChan <- data + } +} + +// 把收到的消息发往不同的地方处理 +func (w *wsConnectItem) sendLoop() { + for { + select { + case <-w.closeChan: + return + case data := <-w.inChan: + w.dealwithReciveData(data) + } + } +} + +// 处理接受到的数据 +func (w *wsConnectItem) dealwithReciveData(data []byte) { + var parseInfo types.DataTransferData + if err := json.Unmarshal(data, &parseInfo); err != nil { + logx.Error("invalid format of websocket message") + return + } + switch parseInfo.T { + //图片渲染 + case constants.WEBSOCKET_RENDER_IMAGE: + var renderImageData []types.RenderImageReqMsg + if err := json.Unmarshal([]byte(parseInfo.D), &renderImageData); err != nil { + logx.Error("invalid format of websocket render image message", err) + return + } + logx.Info("收到请求云渲染图片数据:", renderImageData) + w.mutex.Lock() + defer w.mutex.Unlock() + //把需要渲染的图片加进去 + for _, v := range renderImageData { + key := w.getRenderImageMapKey(v.ProductId, v.SizeId, v.TemplateId) + w.renderImage[key] = struct{}{} + } + default: + + } +} + +// 把渲染好的数据放入outchan +func (w *wsConnectItem) setOutRenderImage(req *types.RenderNotifyReq) { + w.mutex.Lock() + defer w.mutex.Unlock() + for _, notifyItem := range req.NotifyList { + renderKey := w.getRenderImageMapKey(notifyItem.ProductId, notifyItem.SizeId, notifyItem.TemplateId) + //查询 + _, ok := w.renderImage[renderKey] + if !ok { + continue + } + responseData := types.RenderImageRspMsg{ + ProductId: notifyItem.ProductId, + SizeId: notifyItem.SizeId, + TemplateId: notifyItem.TemplateId, + Source: "我是渲染资源", + } + b, _ := json.Marshal(responseData) + select { + case <-w.closeChan: + return + case w.outChan <- b: + logx.Info("notify send render result to out chan") + } + //删掉已经处理的渲染任务 + delete(w.renderImage, renderKey) + } +} + +// 获取需要渲染图片的map key +func (w *wsConnectItem) getRenderImageMapKey(productId, sizeId, templateId int64) string { + return fmt.Sprintf("%d-%d-%d", productId, sizeId, templateId) +} diff --git a/server/websocket/internal/logic/rendernotifylogic.go b/server/websocket/internal/logic/rendernotifylogic.go index 49803d29..f354b736 100644 --- a/server/websocket/internal/logic/rendernotifylogic.go +++ b/server/websocket/internal/logic/rendernotifylogic.go @@ -1,8 +1,13 @@ package logic import ( - "fusenapi/utils/auth" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "fusenapi/constants" "fusenapi/utils/basic" + "time" "context" @@ -35,9 +40,30 @@ func NewRenderNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Rend // // httpx.OkJsonCtx(r.Context(), w, resp) // } -func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq, userinfo *auth.UserInfo) (resp *basic.Response) { - // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) - // userinfo 传入值时, 一定不为null - +func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basic.Response) { + if len(req.NotifyList) == 0 { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "notify list is empty") + } + if time.Now().Unix()-120 > req.Time /*|| req.Time > time.Now().Unix() */ { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "time is expire") + } + //验证签名 sha256 + notifyByte, _ := json.Marshal(req.NotifyList) + 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) + if req.Sign != sign { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "invalid") + } + //遍历websocket链接 + mapConnPool.Range(func(key, value any) bool { + ws, ok := value.(wsConnectItem) + if !ok { + return false + } + ws.setOutRenderImage(req) + return true + }) return resp.SetStatus(basic.CodeOK) } diff --git a/server/websocket/internal/types/types.go b/server/websocket/internal/types/types.go index 6a1cf750..8178bcc6 100644 --- a/server/websocket/internal/types/types.go +++ b/server/websocket/internal/types/types.go @@ -5,12 +5,7 @@ import ( "fusenapi/utils/basic" ) -type DataTransferReq struct { - T string `json:"t"` //消息类型 - D string `json:"d"` //传递的消息 -} - -type DataTransferRsp struct { +type DataTransferData struct { T string `json:"t"` //消息类型 D string `json:"d"` //传递的消息 } diff --git a/server_api/websocket.api b/server_api/websocket.api index d0daf98b..dadbd2ab 100644 --- a/server_api/websocket.api +++ b/server_api/websocket.api @@ -11,18 +11,14 @@ import "basic.api" service websocket { //websocket数据交互 @handler DataTransferHandler - get /api/websocket/data_transfer(DataTransferReq) returns (response); + get /api/websocket/data_transfer(request) returns (response); //渲染完了通知接口 @handler RenderNotifyHandler post /api/websocket/render_notify(RenderNotifyReq) returns (response); } //websocket数据交互 -type DataTransferReq { - T string `json:"t"` //消息类型 - D string `json:"d"` //传递的消息 -} -type DataTransferRsp { +type DataTransferData { T string `json:"t"` //消息类型 D string `json:"d"` //传递的消息 } From b9afdf1dda4c01934915e73dcf96b42a48a1029c Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 11:53:57 +0800 Subject: [PATCH 26/68] fix --- server/websocket/internal/logic/rendernotifylogic.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/websocket/internal/logic/rendernotifylogic.go b/server/websocket/internal/logic/rendernotifylogic.go index f354b736..c8495ed2 100644 --- a/server/websocket/internal/logic/rendernotifylogic.go +++ b/server/websocket/internal/logic/rendernotifylogic.go @@ -56,7 +56,7 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi if req.Sign != sign { return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "invalid") } - //遍历websocket链接 + //遍历websocket链接把数据传进去 mapConnPool.Range(func(key, value any) bool { ws, ok := value.(wsConnectItem) if !ok { From 16feddfe3ea34f443be0b859485c875d23c7cd00 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 12:27:34 +0800 Subject: [PATCH 27/68] fix --- .../internal/logic/datatransferlogic.go | 35 ++++++++----------- .../internal/logic/rendernotifylogic.go | 26 +++++++++++++- 2 files changed, 39 insertions(+), 22 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 17792d10..73227ee6 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -241,37 +241,30 @@ func (w *wsConnectItem) dealwithReciveData(data []byte) { key := w.getRenderImageMapKey(v.ProductId, v.SizeId, v.TemplateId) w.renderImage[key] = struct{}{} } + //TODO 发送数据到云渲染服务器 default: } } -// 把渲染好的数据放入outchan -func (w *wsConnectItem) setOutRenderImage(req *types.RenderNotifyReq) { - w.mutex.Lock() - defer w.mutex.Unlock() - for _, notifyItem := range req.NotifyList { - renderKey := w.getRenderImageMapKey(notifyItem.ProductId, notifyItem.SizeId, notifyItem.TemplateId) - //查询 - _, ok := w.renderImage[renderKey] - if !ok { - continue - } - responseData := types.RenderImageRspMsg{ - ProductId: notifyItem.ProductId, - SizeId: notifyItem.SizeId, - TemplateId: notifyItem.TemplateId, - Source: "我是渲染资源", - } - b, _ := json.Marshal(responseData) +// 把要传递给客户端的数据放入outchan +func (w *wsConnectItem) sendToOutChan(data [][]byte) { + for _, v := range data { select { case <-w.closeChan: return - case w.outChan <- b: + case w.outChan <- v: logx.Info("notify send render result to out chan") } - //删掉已经处理的渲染任务 - delete(w.renderImage, renderKey) + } +} + +// 删除对应需要渲染的map值 +func (w *wsConnectItem) deleteRenderMapVal(keys []string) { + w.mutex.Lock() + defer w.mutex.Unlock() + for _, v := range keys { + delete(w.renderImage, v) } } diff --git a/server/websocket/internal/logic/rendernotifylogic.go b/server/websocket/internal/logic/rendernotifylogic.go index c8495ed2..22fff393 100644 --- a/server/websocket/internal/logic/rendernotifylogic.go +++ b/server/websocket/internal/logic/rendernotifylogic.go @@ -58,11 +58,35 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi } //遍历websocket链接把数据传进去 mapConnPool.Range(func(key, value any) bool { + //断言连接 ws, ok := value.(wsConnectItem) if !ok { return false } - ws.setOutRenderImage(req) + dataList := make([][]byte, 0, len(req.NotifyList)) + deleteRenderKey := make([]string, 0, len(req.NotifyList)) + //遍历数据 + for _, notifyItem := range req.NotifyList { + renderKey := ws.getRenderImageMapKey(notifyItem.ProductId, notifyItem.SizeId, notifyItem.TemplateId) + //查询 + _, ok = ws.renderImage[renderKey] + if !ok { + continue + } + responseData := types.RenderImageRspMsg{ + ProductId: notifyItem.ProductId, + SizeId: notifyItem.SizeId, + TemplateId: notifyItem.TemplateId, + Source: "我是渲染资源", + } + b, _ := json.Marshal(responseData) + dataList = append(dataList, b) + deleteRenderKey = append(deleteRenderKey, renderKey) + } + //删除对应的需要渲染的图片map + ws.deleteRenderMapVal(deleteRenderKey) + //发送数据 + ws.sendToOutChan(dataList) return true }) return resp.SetStatus(basic.CodeOK) From 736f57c0c25e30a5531bd66be41caa530dd58120 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 14:17:30 +0800 Subject: [PATCH 28/68] fix --- model/gmodel/fs_user_gen.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/model/gmodel/fs_user_gen.go b/model/gmodel/fs_user_gen.go index 05b8cdd1..81d0f008 100644 --- a/model/gmodel/fs_user_gen.go +++ b/model/gmodel/fs_user_gen.go @@ -30,7 +30,7 @@ type FsUser struct { IsPhoneAdvertisement *int64 `gorm:"default:0;" json:"is_phone_advertisement"` // 是否接收短信广告 IsOpenRender *int64 `gorm:"default:0;" json:"is_open_render"` // 是否打开个性化渲染(1:开启,0:关闭) IsThousandFace *int64 `gorm:"default:0;" json:"is_thousand_face"` // 是否已经存在千人千面(1:存在,0:不存在) - IsLowRendering *int64 `gorm:"default:0;" json:"is_low_rendering"` // + IsLowRendering *int64 `gorm:"default:0;" json:"is_low_rendering"` // 是否开启低渲染模型渲染 IsRemoveBg *int64 `gorm:"default:1;" json:"is_remove_bg"` // 用户上传logo是否去除背景 } type FsUserModel struct { From e40a4d43f4df8349308cd5096e0a87f5aa8680c5 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 14:35:29 +0800 Subject: [PATCH 29/68] fix --- .../internal/logic/datatransferlogic.go | 21 +++------------- .../internal/logic/ws_render_image_logic.go | 24 +++++++++++++++++++ 2 files changed, 27 insertions(+), 18 deletions(-) create mode 100644 server/websocket/internal/logic/ws_render_image_logic.go diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 73227ee6..81cecdd9 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -5,7 +5,6 @@ import ( "fmt" "fusenapi/constants" "fusenapi/server/websocket/internal/types" - "fusenapi/utils/basic" "github.com/google/uuid" "github.com/gorilla/websocket" "net/http" @@ -56,7 +55,7 @@ type wsConnectItem struct { renderImage map[string]struct{} //需要渲染的图片 } -func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.ResponseWriter, r *http.Request) (resp *basic.Response) { +func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.ResponseWriter, r *http.Request) { //升级websocket conn, err := upgrade.Upgrade(w, r, nil) if err != nil { @@ -130,8 +129,6 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp go ws.sendLoop() //心跳 ws.heartbeat() - - return resp.SetStatus(basic.CodeOK) } // 心跳 @@ -225,23 +222,11 @@ func (w *wsConnectItem) dealwithReciveData(data []byte) { logx.Error("invalid format of websocket message") return } + //分消息类型给到不同逻辑处理,可扩展 switch parseInfo.T { //图片渲染 case constants.WEBSOCKET_RENDER_IMAGE: - var renderImageData []types.RenderImageReqMsg - if err := json.Unmarshal([]byte(parseInfo.D), &renderImageData); err != nil { - logx.Error("invalid format of websocket render image message", err) - return - } - logx.Info("收到请求云渲染图片数据:", renderImageData) - w.mutex.Lock() - defer w.mutex.Unlock() - //把需要渲染的图片加进去 - for _, v := range renderImageData { - key := w.getRenderImageMapKey(v.ProductId, v.SizeId, v.TemplateId) - w.renderImage[key] = struct{}{} - } - //TODO 发送数据到云渲染服务器 + w.SendToCloudRender([]byte(parseInfo.D)) default: } diff --git a/server/websocket/internal/logic/ws_render_image_logic.go b/server/websocket/internal/logic/ws_render_image_logic.go new file mode 100644 index 00000000..2428cd17 --- /dev/null +++ b/server/websocket/internal/logic/ws_render_image_logic.go @@ -0,0 +1,24 @@ +package logic + +import ( + "encoding/json" + "fusenapi/server/websocket/internal/types" + "github.com/zeromicro/go-zero/core/logx" +) + +// 渲染请求数据处理发送云渲染服务处理 +func (w *wsConnectItem) SendToCloudRender(data []byte) { + var renderImageData []types.RenderImageReqMsg + if err := json.Unmarshal(data, &renderImageData); err != nil { + logx.Error("invalid format of websocket render image message", err) + return + } + logx.Info("收到请求云渲染图片数据:", renderImageData) + w.mutex.Lock() + defer w.mutex.Unlock() + //把需要渲染的图片加进去 + for _, v := range renderImageData { + key := w.getRenderImageMapKey(v.ProductId, v.SizeId, v.TemplateId) + w.renderImage[key] = struct{}{} + } +} From 918b5903d7368faf2a5c35b89d66edf199ed90c3 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 15:01:59 +0800 Subject: [PATCH 30/68] fix --- .../internal/logic/datatransferlogic.go | 67 ++++++++++++------- .../internal/logic/rendernotifylogic.go | 9 +-- .../internal/logic/ws_render_image_logic.go | 7 +- 3 files changed, 50 insertions(+), 33 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 81cecdd9..6a3b206f 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -45,14 +45,19 @@ var ( // 每个连接的连接属性 type wsConnectItem struct { - conn *websocket.Conn //websocket的连接 - closeChan chan struct{} //关闭chan - isClose bool //是否已经关闭 - flag string - inChan chan []byte //接受消息缓冲通道 - outChan chan []byte //发送回客户端的消息 - mutex sync.Mutex - renderImage map[string]struct{} //需要渲染的图片 + conn *websocket.Conn //websocket的连接 + closeChan chan struct{} //关闭chan + isClose bool //是否已经关闭 + flag string + inChan chan []byte //接受消息缓冲通道 + outChan chan []byte //发送回客户端的消息 + mutex sync.Mutex + renderImage map[string]struct{} //需要渲染的图片 + renderImageControlChan chan renderImageControlChanItem +} +type renderImageControlChanItem struct { + Option int // 0删除 1添加 + Key string //map的key } func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.ResponseWriter, r *http.Request) { @@ -105,13 +110,14 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp //生成连接唯一标识 flag := uuid.New().String() + time.Now().Format("20060102150405") ws := wsConnectItem{ - conn: conn, - flag: flag, - closeChan: make(chan struct{}, 1), - inChan: make(chan []byte, 100), - outChan: make(chan []byte, 100), - renderImage: make(map[string]struct{}), - isClose: false, + conn: conn, + flag: flag, + closeChan: make(chan struct{}, 1), + inChan: make(chan []byte, 100), + outChan: make(chan []byte, 100), + renderImage: make(map[string]struct{}), + renderImageControlChan: make(chan renderImageControlChanItem, 100), + isClose: false, } //保存连接 mapConnPool.Store(flag, ws) @@ -127,6 +133,8 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp go ws.writeLoop() //推消息到云渲染 go ws.sendLoop() + //操作连接中渲染任务的增加/删除 + go ws.operationRenderTask() //心跳 ws.heartbeat() } @@ -165,12 +173,28 @@ func (w *wsConnectItem) close() { if !w.isClose { w.isClose = true close(w.closeChan) - close(w.outChan) - close(w.inChan) } logx.Info("websocket:", w.flag, " is closed") } +// 操作连接中渲染任务的增加/删除 +func (w *wsConnectItem) operationRenderTask() { + for { + select { + case <-w.closeChan: + return + case data := <-w.renderImageControlChan: + switch data.Option { + case 0: //删除 + delete(w.renderImage, data.Key) + case 1: //新增 + w.renderImage[data.Key] = struct{}{} + default: + + } + } + } +} func (w *wsConnectItem) writeLoop() { for { select { @@ -244,15 +268,6 @@ func (w *wsConnectItem) sendToOutChan(data [][]byte) { } } -// 删除对应需要渲染的map值 -func (w *wsConnectItem) deleteRenderMapVal(keys []string) { - w.mutex.Lock() - defer w.mutex.Unlock() - for _, v := range keys { - delete(w.renderImage, v) - } -} - // 获取需要渲染图片的map key func (w *wsConnectItem) getRenderImageMapKey(productId, sizeId, templateId int64) string { return fmt.Sprintf("%d-%d-%d", productId, sizeId, templateId) diff --git a/server/websocket/internal/logic/rendernotifylogic.go b/server/websocket/internal/logic/rendernotifylogic.go index 22fff393..aa504999 100644 --- a/server/websocket/internal/logic/rendernotifylogic.go +++ b/server/websocket/internal/logic/rendernotifylogic.go @@ -64,7 +64,6 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi return false } dataList := make([][]byte, 0, len(req.NotifyList)) - deleteRenderKey := make([]string, 0, len(req.NotifyList)) //遍历数据 for _, notifyItem := range req.NotifyList { renderKey := ws.getRenderImageMapKey(notifyItem.ProductId, notifyItem.SizeId, notifyItem.TemplateId) @@ -81,10 +80,12 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi } b, _ := json.Marshal(responseData) dataList = append(dataList, b) - deleteRenderKey = append(deleteRenderKey, renderKey) + //删除对应的需要渲染的图片map + ws.renderImageControlChan <- renderImageControlChanItem{ + Option: 0, + Key: renderKey, + } } - //删除对应的需要渲染的图片map - ws.deleteRenderMapVal(deleteRenderKey) //发送数据 ws.sendToOutChan(dataList) return true diff --git a/server/websocket/internal/logic/ws_render_image_logic.go b/server/websocket/internal/logic/ws_render_image_logic.go index 2428cd17..46c742ba 100644 --- a/server/websocket/internal/logic/ws_render_image_logic.go +++ b/server/websocket/internal/logic/ws_render_image_logic.go @@ -14,11 +14,12 @@ func (w *wsConnectItem) SendToCloudRender(data []byte) { return } logx.Info("收到请求云渲染图片数据:", renderImageData) - w.mutex.Lock() - defer w.mutex.Unlock() //把需要渲染的图片加进去 for _, v := range renderImageData { key := w.getRenderImageMapKey(v.ProductId, v.SizeId, v.TemplateId) - w.renderImage[key] = struct{}{} + w.renderImageControlChan <- renderImageControlChanItem{ + Option: 1, + Key: key, + } } } From ae58ebe35a382183c83882ae0a0edcfb08b9a476 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 15:05:53 +0800 Subject: [PATCH 31/68] fix --- .../websocket/internal/logic/datatransferlogic.go | 14 +++++++------- .../websocket/internal/logic/rendernotifylogic.go | 6 +++--- .../internal/logic/ws_render_image_logic.go | 4 ++-- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 6a3b206f..6566d2d7 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -52,8 +52,8 @@ type wsConnectItem struct { inChan chan []byte //接受消息缓冲通道 outChan chan []byte //发送回客户端的消息 mutex sync.Mutex - renderImage map[string]struct{} //需要渲染的图片 - renderImageControlChan chan renderImageControlChanItem + renderImageTask map[string]struct{} //需要渲染的图片 + renderImageTaskCtlChan chan renderImageControlChanItem } type renderImageControlChanItem struct { Option int // 0删除 1添加 @@ -115,8 +115,8 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp closeChan: make(chan struct{}, 1), inChan: make(chan []byte, 100), outChan: make(chan []byte, 100), - renderImage: make(map[string]struct{}), - renderImageControlChan: make(chan renderImageControlChanItem, 100), + renderImageTask: make(map[string]struct{}), + renderImageTaskCtlChan: make(chan renderImageControlChanItem, 100), isClose: false, } //保存连接 @@ -183,12 +183,12 @@ func (w *wsConnectItem) operationRenderTask() { select { case <-w.closeChan: return - case data := <-w.renderImageControlChan: + case data := <-w.renderImageTaskCtlChan: switch data.Option { case 0: //删除 - delete(w.renderImage, data.Key) + delete(w.renderImageTask, data.Key) case 1: //新增 - w.renderImage[data.Key] = struct{}{} + w.renderImageTask[data.Key] = struct{}{} default: } diff --git a/server/websocket/internal/logic/rendernotifylogic.go b/server/websocket/internal/logic/rendernotifylogic.go index aa504999..01f630de 100644 --- a/server/websocket/internal/logic/rendernotifylogic.go +++ b/server/websocket/internal/logic/rendernotifylogic.go @@ -67,8 +67,8 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi //遍历数据 for _, notifyItem := range req.NotifyList { renderKey := ws.getRenderImageMapKey(notifyItem.ProductId, notifyItem.SizeId, notifyItem.TemplateId) - //查询 - _, ok = ws.renderImage[renderKey] + //查询有无该渲染任务 + _, ok = ws.renderImageTask[renderKey] if !ok { continue } @@ -81,7 +81,7 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi b, _ := json.Marshal(responseData) dataList = append(dataList, b) //删除对应的需要渲染的图片map - ws.renderImageControlChan <- renderImageControlChanItem{ + ws.renderImageTaskCtlChan <- renderImageControlChanItem{ Option: 0, Key: renderKey, } diff --git a/server/websocket/internal/logic/ws_render_image_logic.go b/server/websocket/internal/logic/ws_render_image_logic.go index 46c742ba..40c07f1e 100644 --- a/server/websocket/internal/logic/ws_render_image_logic.go +++ b/server/websocket/internal/logic/ws_render_image_logic.go @@ -14,10 +14,10 @@ func (w *wsConnectItem) SendToCloudRender(data []byte) { return } logx.Info("收到请求云渲染图片数据:", renderImageData) - //把需要渲染的图片加进去 + //把需要渲染的图片任务加进去 for _, v := range renderImageData { key := w.getRenderImageMapKey(v.ProductId, v.SizeId, v.TemplateId) - w.renderImageControlChan <- renderImageControlChanItem{ + w.renderImageTaskCtlChan <- renderImageControlChanItem{ Option: 1, Key: key, } From 34d5e62824e6a9c34147386db96fb9ac4241eece Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 15:06:29 +0800 Subject: [PATCH 32/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 6566d2d7..fe187443 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -52,8 +52,8 @@ type wsConnectItem struct { inChan chan []byte //接受消息缓冲通道 outChan chan []byte //发送回客户端的消息 mutex sync.Mutex - renderImageTask map[string]struct{} //需要渲染的图片 - renderImageTaskCtlChan chan renderImageControlChanItem + renderImageTask map[string]struct{} //需要渲染的图片 + renderImageTaskCtlChan chan renderImageControlChanItem //渲染任务新增移除的控制通道 } type renderImageControlChanItem struct { Option int // 0删除 1添加 From e07d55efca9089cfa7fd6136602cbbc372a30180 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 15:08:43 +0800 Subject: [PATCH 33/68] fix --- .../internal/logic/datatransferlogic.go | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index fe187443..44810927 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -239,23 +239,6 @@ func (w *wsConnectItem) sendLoop() { } } -// 处理接受到的数据 -func (w *wsConnectItem) dealwithReciveData(data []byte) { - var parseInfo types.DataTransferData - if err := json.Unmarshal(data, &parseInfo); err != nil { - logx.Error("invalid format of websocket message") - return - } - //分消息类型给到不同逻辑处理,可扩展 - switch parseInfo.T { - //图片渲染 - case constants.WEBSOCKET_RENDER_IMAGE: - w.SendToCloudRender([]byte(parseInfo.D)) - default: - - } -} - // 把要传递给客户端的数据放入outchan func (w *wsConnectItem) sendToOutChan(data [][]byte) { for _, v := range data { @@ -272,3 +255,20 @@ func (w *wsConnectItem) sendToOutChan(data [][]byte) { func (w *wsConnectItem) getRenderImageMapKey(productId, sizeId, templateId int64) string { return fmt.Sprintf("%d-%d-%d", productId, sizeId, templateId) } + +// 处理接受到的数据 +func (w *wsConnectItem) dealwithReciveData(data []byte) { + var parseInfo types.DataTransferData + if err := json.Unmarshal(data, &parseInfo); err != nil { + logx.Error("invalid format of websocket message") + return + } + //分消息类型给到不同逻辑处理,可扩展 + switch parseInfo.T { + //图片渲染 + case constants.WEBSOCKET_RENDER_IMAGE: + w.SendToCloudRender([]byte(parseInfo.D)) + default: + + } +} From a896d42bc1f3762c30471d3dd2d448e3776ae2ac Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 15:12:24 +0800 Subject: [PATCH 34/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 44810927..ec9969dd 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -195,6 +195,8 @@ func (w *wsConnectItem) operationRenderTask() { } } } + +// 读取输出返回给客户端 func (w *wsConnectItem) writeLoop() { for { select { From 36aad6a0887b812998f6eb74d9092a6aae456c00 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 15:15:37 +0800 Subject: [PATCH 35/68] fix --- .../internal/logic/datatransferlogic.go | 19 ------------------- .../internal/logic/ws_render_image_logic.go | 19 +++++++++++++++++++ 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index ec9969dd..3df09209 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -177,25 +177,6 @@ func (w *wsConnectItem) close() { logx.Info("websocket:", w.flag, " is closed") } -// 操作连接中渲染任务的增加/删除 -func (w *wsConnectItem) operationRenderTask() { - for { - select { - case <-w.closeChan: - return - case data := <-w.renderImageTaskCtlChan: - switch data.Option { - case 0: //删除 - delete(w.renderImageTask, data.Key) - case 1: //新增 - w.renderImageTask[data.Key] = struct{}{} - default: - - } - } - } -} - // 读取输出返回给客户端 func (w *wsConnectItem) writeLoop() { for { diff --git a/server/websocket/internal/logic/ws_render_image_logic.go b/server/websocket/internal/logic/ws_render_image_logic.go index 40c07f1e..6a075acb 100644 --- a/server/websocket/internal/logic/ws_render_image_logic.go +++ b/server/websocket/internal/logic/ws_render_image_logic.go @@ -23,3 +23,22 @@ func (w *wsConnectItem) SendToCloudRender(data []byte) { } } } + +// 操作连接中渲染任务的增加/删除 +func (w *wsConnectItem) operationRenderTask() { + for { + select { + case <-w.closeChan: + return + case data := <-w.renderImageTaskCtlChan: + switch data.Option { + case 0: //删除任务 + delete(w.renderImageTask, data.Key) + case 1: //新增任务 + w.renderImageTask[data.Key] = struct{}{} + default: + + } + } + } +} From 88a59bbdea0ddb16eb2e02a5650d9a9bb5509494 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 16:00:19 +0800 Subject: [PATCH 36/68] fix --- model/gmodel/fs_pay_gen.go | 1 + model/gmodel/fs_resources_gen.go | 26 +++++++++++++++++++ model/gmodel/fs_resources_logic.go | 2 ++ model/gmodel/var_gen.go | 2 ++ .../internal/logic/datatransferlogic.go | 16 +++++++++++- 5 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 model/gmodel/fs_resources_gen.go create mode 100644 model/gmodel/fs_resources_logic.go diff --git a/model/gmodel/fs_pay_gen.go b/model/gmodel/fs_pay_gen.go index 0ee65802..e30685b6 100644 --- a/model/gmodel/fs_pay_gen.go +++ b/model/gmodel/fs_pay_gen.go @@ -7,6 +7,7 @@ import ( // fs_pay 支付记录 type FsPay struct { Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // + PayNo *string `gorm:"default:'';" json:"pay_no"` // 支付编号 UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户id OrderNumber *string `gorm:"default:'';" json:"order_number"` // 订单编号 TradeNo *string `gorm:"index;default:'';" json:"trade_no"` // 第三方支付编号 diff --git a/model/gmodel/fs_resources_gen.go b/model/gmodel/fs_resources_gen.go new file mode 100644 index 00000000..432a8113 --- /dev/null +++ b/model/gmodel/fs_resources_gen.go @@ -0,0 +1,26 @@ +package gmodel + +import ( + "gorm.io/gorm" + "time" +) + +// fs_resources 资源表 +type FsResources struct { + ResourceId string `gorm:"primary_key;default:'';" json:"resource_id"` // 资源 ID + UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户 ID + GuestId *int64 `gorm:"index;default:0;" json:"guest_id"` // 访客 ID + ResourceType *string `gorm:"index;default:'';" json:"resource_type"` // 资源类型 + ResourceUrl *string `gorm:"default:'';" json:"resource_url"` // 资源 URL + UploadedAt *time.Time `gorm:"index;default:'0000-00-00 00:00:00';" json:"uploaded_at"` // 上传时间 + Metadata *string `gorm:"default:'';" json:"metadata"` // 元数据,json格式,存储图像分率 + MetaKey1 *string `gorm:"index;default:'';" json:"meta_key1"` // 需要关键信息查询的自定义属性1,可以动态增加 +} +type FsResourcesModel struct { + db *gorm.DB + name string +} + +func NewFsResourcesModel(db *gorm.DB) *FsResourcesModel { + return &FsResourcesModel{db: db, name: "fs_resources"} +} diff --git a/model/gmodel/fs_resources_logic.go b/model/gmodel/fs_resources_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_resources_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/var_gen.go b/model/gmodel/var_gen.go index a5916431..2fac48a5 100644 --- a/model/gmodel/var_gen.go +++ b/model/gmodel/var_gen.go @@ -79,6 +79,7 @@ type AllModelsGen struct { FsQuotationRemarkTemplate *FsQuotationRemarkTemplateModel // fs_quotation_remark_template 报价单备注模板 FsQuotationSaler *FsQuotationSalerModel // fs_quotation_saler 报价单业务员表 FsRefundReason *FsRefundReasonModel // fs_refund_reason + FsResources *FsResourcesModel // fs_resources 资源表 FsStandardLogo *FsStandardLogoModel // fs_standard_logo 标准logo FsTags *FsTagsModel // fs_tags 产品分类表 FsToolLogs *FsToolLogsModel // fs_tool_logs 3d设计工具日志表 @@ -169,6 +170,7 @@ func NewAllModels(gdb *gorm.DB) *AllModelsGen { FsQuotationRemarkTemplate: NewFsQuotationRemarkTemplateModel(gdb), FsQuotationSaler: NewFsQuotationSalerModel(gdb), FsRefundReason: NewFsRefundReasonModel(gdb), + FsResources: NewFsResourcesModel(gdb), FsStandardLogo: NewFsStandardLogoModel(gdb), FsTags: NewFsTagsModel(gdb), FsToolLogs: NewFsToolLogsModel(gdb), diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 3df09209..29ad842a 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -1,12 +1,14 @@ package logic import ( + "bytes" "encoding/json" "fmt" "fusenapi/constants" "fusenapi/server/websocket/internal/types" "github.com/google/uuid" "github.com/gorilla/websocket" + "github.com/zeromicro/go-zero/rest/httpx" "net/http" "sync" "time" @@ -32,12 +34,24 @@ func NewDataTransferLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Data } var ( - //升级 + buffPool = sync.Pool{ + New: func() interface{} { + return bytes.Buffer{} + }, + } + //升级websocket upgrade = websocket.Upgrader{ + //握手超时时间15s + HandshakeTimeout: time.Second * 15, //允许跨域 CheckOrigin: func(r *http.Request) bool { return true }, + Error: func(w http.ResponseWriter, r *http.Request, status int, reason error) { + httpx.ErrorCtx(r.Context(), w, reason) + return + }, + WriteBufferPool: &buffPool, } //连接map池 mapConnPool = sync.Map{} From e25cc97ea0c629d78c8e49e5a77098e156f4b667 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 16:23:38 +0800 Subject: [PATCH 37/68] fix --- .../internal/logic/datatransferlogic.go | 34 +++++++++---------- .../internal/logic/ws_render_image_logic.go | 19 ++++++++--- 2 files changed, 31 insertions(+), 22 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 29ad842a..f2b31ab9 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -166,13 +166,12 @@ func (w *wsConnectItem) heartbeat() { case <-w.closeChan: return default: - - } - //发送心跳信息 - if err := w.conn.WriteMessage(websocket.TextMessage, b); err != nil { - logx.Error("发送心跳信息异常,关闭连接:", w.flag, err) - w.close() - return + //发送心跳信息 + if err := w.conn.WriteMessage(websocket.TextMessage, b); err != nil { + logx.Error("发送心跳信息异常,关闭连接:", w.flag, err) + w.close() + return + } } } } @@ -210,17 +209,16 @@ func (w *wsConnectItem) readLoop() { case <-w.closeChan: //如果关闭了 return default: - + _, data, err := w.conn.ReadMessage() + if err != nil { + logx.Error("接受信息错误:", err) + //关闭连接 + w.close() + return + } + //消息传入缓冲通道 + w.inChan <- data } - _, data, err := w.conn.ReadMessage() - if err != nil { - logx.Error("接受信息错误:", err) - //关闭连接 - w.close() - return - } - //消息传入缓冲通道 - w.inChan <- data } } @@ -264,7 +262,7 @@ func (w *wsConnectItem) dealwithReciveData(data []byte) { switch parseInfo.T { //图片渲染 case constants.WEBSOCKET_RENDER_IMAGE: - w.SendToCloudRender([]byte(parseInfo.D)) + go w.SendToCloudRender([]byte(parseInfo.D)) default: } diff --git a/server/websocket/internal/logic/ws_render_image_logic.go b/server/websocket/internal/logic/ws_render_image_logic.go index 6a075acb..cfa118a8 100644 --- a/server/websocket/internal/logic/ws_render_image_logic.go +++ b/server/websocket/internal/logic/ws_render_image_logic.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fusenapi/server/websocket/internal/types" "github.com/zeromicro/go-zero/core/logx" + "time" ) // 渲染请求数据处理发送云渲染服务处理 @@ -14,12 +15,22 @@ func (w *wsConnectItem) SendToCloudRender(data []byte) { return } logx.Info("收到请求云渲染图片数据:", renderImageData) + timer := time.NewTimer(time.Second * 10) //把需要渲染的图片任务加进去 for _, v := range renderImageData { - key := w.getRenderImageMapKey(v.ProductId, v.SizeId, v.TemplateId) - w.renderImageTaskCtlChan <- renderImageControlChanItem{ - Option: 1, - Key: key, + select { + case <-w.closeChan: //连接关闭了 + return + case <-timer.C: //10秒超时了 + return + default: + //加入渲染任务 + key := w.getRenderImageMapKey(v.ProductId, v.SizeId, v.TemplateId) + w.renderImageTaskCtlChan <- renderImageControlChanItem{ + Option: 1, + Key: key, + } + // TODO 数据发送给云渲染服务器 } } } From 7dc9760d94f3df93684e43fa37d437a815eb58ab Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 16:27:24 +0800 Subject: [PATCH 38/68] fix --- server/websocket/internal/logic/ws_render_image_logic.go | 4 ---- 1 file changed, 4 deletions(-) diff --git a/server/websocket/internal/logic/ws_render_image_logic.go b/server/websocket/internal/logic/ws_render_image_logic.go index cfa118a8..8521ee91 100644 --- a/server/websocket/internal/logic/ws_render_image_logic.go +++ b/server/websocket/internal/logic/ws_render_image_logic.go @@ -4,7 +4,6 @@ import ( "encoding/json" "fusenapi/server/websocket/internal/types" "github.com/zeromicro/go-zero/core/logx" - "time" ) // 渲染请求数据处理发送云渲染服务处理 @@ -15,14 +14,11 @@ func (w *wsConnectItem) SendToCloudRender(data []byte) { return } logx.Info("收到请求云渲染图片数据:", renderImageData) - timer := time.NewTimer(time.Second * 10) //把需要渲染的图片任务加进去 for _, v := range renderImageData { select { case <-w.closeChan: //连接关闭了 return - case <-timer.C: //10秒超时了 - return default: //加入渲染任务 key := w.getRenderImageMapKey(v.ProductId, v.SizeId, v.TemplateId) From 3deda93e7e715ab9b7c5757fdb20b1aea09cf58d Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 16:47:53 +0800 Subject: [PATCH 39/68] fix --- constants/websocket.go | 10 ++++++---- .../websocket/internal/logic/datatransferlogic.go | 3 ++- .../websocket/internal/logic/rendernotifylogic.go | 15 +++++++++------ .../internal/logic/ws_render_image_logic.go | 2 ++ server/websocket/internal/types/types.go | 4 ++-- server_api/websocket.api | 4 ++-- 6 files changed, 23 insertions(+), 15 deletions(-) diff --git a/constants/websocket.go b/constants/websocket.go index a9a6aa5d..71f1fc36 100644 --- a/constants/websocket.go +++ b/constants/websocket.go @@ -5,13 +5,15 @@ type websocket string // websocket消息类型 const ( //鉴权失败 - WEBSOCKET_UNAUTH = "unAuth" + WEBSOCKET_UNAUTH = "WEBSOCKET_UNAUTH" //ws连接成功 - WEBSOCKET_CONNECT_SUCCESS = "connect-success" + WEBSOCKET_CONNECT_SUCCESS = "WEBSOCKET_CONNECT_SUCCESS" //心跳信息 - WEBSOCKET_HEARTBEAT = "heartbeat" + WEBSOCKET_HEARTBEAT = "WEBSOCKET_HEARTBEAT" //图片渲染 - WEBSOCKET_RENDER_IMAGE = "render-image" + WEBSOCKET_RENDER_IMAGE = "WEBSOCKET_RENDER_IMAGE" + //数据格式错误 + WEBSOCKET_ERR_DATA_FORMAT = "WEBSOCKET_ERR_DATA_FORMAT" ) // 云渲染通知需要的签名字符串 diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index f2b31ab9..ec39e0d9 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -258,11 +258,12 @@ func (w *wsConnectItem) dealwithReciveData(data []byte) { logx.Error("invalid format of websocket message") return } + d, _ := json.Marshal(parseInfo.D) //分消息类型给到不同逻辑处理,可扩展 switch parseInfo.T { //图片渲染 case constants.WEBSOCKET_RENDER_IMAGE: - go w.SendToCloudRender([]byte(parseInfo.D)) + go w.SendToCloudRender(d) default: } diff --git a/server/websocket/internal/logic/rendernotifylogic.go b/server/websocket/internal/logic/rendernotifylogic.go index 01f630de..064b459d 100644 --- a/server/websocket/internal/logic/rendernotifylogic.go +++ b/server/websocket/internal/logic/rendernotifylogic.go @@ -72,13 +72,16 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi if !ok { continue } - responseData := types.RenderImageRspMsg{ - ProductId: notifyItem.ProductId, - SizeId: notifyItem.SizeId, - TemplateId: notifyItem.TemplateId, - Source: "我是渲染资源", + rspData := types.DataTransferData{ + T: constants.WEBSOCKET_RENDER_IMAGE, + D: types.RenderImageRspMsg{ + ProductId: notifyItem.ProductId, + SizeId: notifyItem.SizeId, + TemplateId: notifyItem.TemplateId, + Source: "我是渲染资源", + }, } - b, _ := json.Marshal(responseData) + b, _ := json.Marshal(rspData) dataList = append(dataList, b) //删除对应的需要渲染的图片map ws.renderImageTaskCtlChan <- renderImageControlChanItem{ diff --git a/server/websocket/internal/logic/ws_render_image_logic.go b/server/websocket/internal/logic/ws_render_image_logic.go index 8521ee91..c8b7f816 100644 --- a/server/websocket/internal/logic/ws_render_image_logic.go +++ b/server/websocket/internal/logic/ws_render_image_logic.go @@ -2,12 +2,14 @@ package logic import ( "encoding/json" + "fmt" "fusenapi/server/websocket/internal/types" "github.com/zeromicro/go-zero/core/logx" ) // 渲染请求数据处理发送云渲染服务处理 func (w *wsConnectItem) SendToCloudRender(data []byte) { + fmt.Println(string(data)) var renderImageData []types.RenderImageReqMsg if err := json.Unmarshal(data, &renderImageData); err != nil { logx.Error("invalid format of websocket render image message", err) diff --git a/server/websocket/internal/types/types.go b/server/websocket/internal/types/types.go index 8178bcc6..d3336021 100644 --- a/server/websocket/internal/types/types.go +++ b/server/websocket/internal/types/types.go @@ -6,8 +6,8 @@ import ( ) type DataTransferData struct { - T string `json:"t"` //消息类型 - D string `json:"d"` //传递的消息 + T string `json:"t"` //消息类型 + D interface{} `json:"d"` //传递的消息 } type RenderImageReqMsg struct { diff --git a/server_api/websocket.api b/server_api/websocket.api index dadbd2ab..0d445c71 100644 --- a/server_api/websocket.api +++ b/server_api/websocket.api @@ -19,8 +19,8 @@ service websocket { //websocket数据交互 type DataTransferData { - T string `json:"t"` //消息类型 - D string `json:"d"` //传递的消息 + T string `json:"t"` //消息类型 + D interface{} `json:"d"` //传递的消息 } type RenderImageReqMsg { //websocket接受需要云渲染的图片 ProductId int64 `json:"product_id"` From 5a92db70ebc86e9cff0bbd6852d8a7444d2ce44d Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 16:50:06 +0800 Subject: [PATCH 40/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 1 - 1 file changed, 1 deletion(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index ec39e0d9..66b2e626 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -131,7 +131,6 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp outChan: make(chan []byte, 100), renderImageTask: make(map[string]struct{}), renderImageTaskCtlChan: make(chan renderImageControlChanItem, 100), - isClose: false, } //保存连接 mapConnPool.Store(flag, ws) From 436ed9ae4f76d0a7c12730bbaf753a0ca1414f36 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 16:58:14 +0800 Subject: [PATCH 41/68] fix --- .../websocket/internal/logic/datatransferlogic.go | 14 ++++++-------- .../websocket/internal/logic/rendernotifylogic.go | 10 ++++------ .../internal/logic/ws_render_image_logic.go | 4 +--- 3 files changed, 11 insertions(+), 17 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 66b2e626..c7f05b3a 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -234,14 +234,12 @@ func (w *wsConnectItem) sendLoop() { } // 把要传递给客户端的数据放入outchan -func (w *wsConnectItem) sendToOutChan(data [][]byte) { - for _, v := range data { - select { - case <-w.closeChan: - return - case w.outChan <- v: - logx.Info("notify send render result to out chan") - } +func (w *wsConnectItem) sendToOutChan(data []byte) { + select { + case <-w.closeChan: + return + case w.outChan <- data: + logx.Info("notify send render result to out chan") } } diff --git a/server/websocket/internal/logic/rendernotifylogic.go b/server/websocket/internal/logic/rendernotifylogic.go index 064b459d..97570811 100644 --- a/server/websocket/internal/logic/rendernotifylogic.go +++ b/server/websocket/internal/logic/rendernotifylogic.go @@ -63,7 +63,6 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi if !ok { return false } - dataList := make([][]byte, 0, len(req.NotifyList)) //遍历数据 for _, notifyItem := range req.NotifyList { renderKey := ws.getRenderImageMapKey(notifyItem.ProductId, notifyItem.SizeId, notifyItem.TemplateId) @@ -78,19 +77,18 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi ProductId: notifyItem.ProductId, SizeId: notifyItem.SizeId, TemplateId: notifyItem.TemplateId, - Source: "我是渲染资源", + Source: notifyItem.Source, }, } b, _ := json.Marshal(rspData) - dataList = append(dataList, b) //删除对应的需要渲染的图片map ws.renderImageTaskCtlChan <- renderImageControlChanItem{ - Option: 0, + Option: 0, //0删除 1添加 Key: renderKey, } + //发送数据到out chan + ws.sendToOutChan(b) } - //发送数据 - ws.sendToOutChan(dataList) return true }) return resp.SetStatus(basic.CodeOK) diff --git a/server/websocket/internal/logic/ws_render_image_logic.go b/server/websocket/internal/logic/ws_render_image_logic.go index c8b7f816..3fca11ca 100644 --- a/server/websocket/internal/logic/ws_render_image_logic.go +++ b/server/websocket/internal/logic/ws_render_image_logic.go @@ -2,14 +2,12 @@ package logic import ( "encoding/json" - "fmt" "fusenapi/server/websocket/internal/types" "github.com/zeromicro/go-zero/core/logx" ) // 渲染请求数据处理发送云渲染服务处理 func (w *wsConnectItem) SendToCloudRender(data []byte) { - fmt.Println(string(data)) var renderImageData []types.RenderImageReqMsg if err := json.Unmarshal(data, &renderImageData); err != nil { logx.Error("invalid format of websocket render image message", err) @@ -25,7 +23,7 @@ func (w *wsConnectItem) SendToCloudRender(data []byte) { //加入渲染任务 key := w.getRenderImageMapKey(v.ProductId, v.SizeId, v.TemplateId) w.renderImageTaskCtlChan <- renderImageControlChanItem{ - Option: 1, + Option: 1, //0删除 1添加 Key: key, } // TODO 数据发送给云渲染服务器 From d5ff15849d8467c0f4915488f8126713030e4b3f Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 17:06:53 +0800 Subject: [PATCH 42/68] fix --- .../internal/logic/datatransferlogic.go | 39 +++++++++---------- .../internal/logic/rendernotifylogic.go | 4 +- .../internal/logic/ws_render_image_logic.go | 20 ++++++++-- 3 files changed, 36 insertions(+), 27 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index c7f05b3a..78ff3004 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -57,21 +57,16 @@ var ( mapConnPool = sync.Map{} ) -// 每个连接的连接属性 +// 每个连接的连接基本属性 type wsConnectItem struct { - conn *websocket.Conn //websocket的连接 - closeChan chan struct{} //关闭chan - isClose bool //是否已经关闭 - flag string - inChan chan []byte //接受消息缓冲通道 - outChan chan []byte //发送回客户端的消息 - mutex sync.Mutex - renderImageTask map[string]struct{} //需要渲染的图片 - renderImageTaskCtlChan chan renderImageControlChanItem //渲染任务新增移除的控制通道 -} -type renderImageControlChanItem struct { - Option int // 0删除 1添加 - Key string //map的key + conn *websocket.Conn //websocket的连接 + closeChan chan struct{} //关闭chan + isClose bool //是否已经关闭 + flag string //ws连接唯一标识 + inChan chan []byte //接受消息缓冲通道 + outChan chan []byte //发送回客户端的消息 + mutex sync.Mutex //互斥锁 + renderProperty renderProperty //扩展云渲染属性 } func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.ResponseWriter, r *http.Request) { @@ -124,13 +119,15 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp //生成连接唯一标识 flag := uuid.New().String() + time.Now().Format("20060102150405") ws := wsConnectItem{ - conn: conn, - flag: flag, - closeChan: make(chan struct{}, 1), - inChan: make(chan []byte, 100), - outChan: make(chan []byte, 100), - renderImageTask: make(map[string]struct{}), - renderImageTaskCtlChan: make(chan renderImageControlChanItem, 100), + conn: conn, + flag: flag, + closeChan: make(chan struct{}, 1), + inChan: make(chan []byte, 100), + outChan: make(chan []byte, 100), + renderProperty: renderProperty{ + renderImageTask: make(map[string]struct{}), + renderImageTaskCtlChan: make(chan renderImageControlChanItem, 100), + }, } //保存连接 mapConnPool.Store(flag, ws) diff --git a/server/websocket/internal/logic/rendernotifylogic.go b/server/websocket/internal/logic/rendernotifylogic.go index 97570811..c203443e 100644 --- a/server/websocket/internal/logic/rendernotifylogic.go +++ b/server/websocket/internal/logic/rendernotifylogic.go @@ -67,7 +67,7 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi for _, notifyItem := range req.NotifyList { renderKey := ws.getRenderImageMapKey(notifyItem.ProductId, notifyItem.SizeId, notifyItem.TemplateId) //查询有无该渲染任务 - _, ok = ws.renderImageTask[renderKey] + _, ok = ws.renderProperty.renderImageTask[renderKey] if !ok { continue } @@ -82,7 +82,7 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi } b, _ := json.Marshal(rspData) //删除对应的需要渲染的图片map - ws.renderImageTaskCtlChan <- renderImageControlChanItem{ + ws.renderProperty.renderImageTaskCtlChan <- renderImageControlChanItem{ Option: 0, //0删除 1添加 Key: renderKey, } diff --git a/server/websocket/internal/logic/ws_render_image_logic.go b/server/websocket/internal/logic/ws_render_image_logic.go index 3fca11ca..b93e4b67 100644 --- a/server/websocket/internal/logic/ws_render_image_logic.go +++ b/server/websocket/internal/logic/ws_render_image_logic.go @@ -6,6 +6,18 @@ import ( "github.com/zeromicro/go-zero/core/logx" ) +// 云渲染属性 +type renderProperty struct { + renderImageTask map[string]struct{} //需要渲染的图片任务 + renderImageTaskCtlChan chan renderImageControlChanItem //渲染任务新增移除的控制通道 +} + +// 渲染任务新增移除的控制通道的数据 +type renderImageControlChanItem struct { + Option int // 0删除 1添加 + Key string //map的key +} + // 渲染请求数据处理发送云渲染服务处理 func (w *wsConnectItem) SendToCloudRender(data []byte) { var renderImageData []types.RenderImageReqMsg @@ -22,7 +34,7 @@ func (w *wsConnectItem) SendToCloudRender(data []byte) { default: //加入渲染任务 key := w.getRenderImageMapKey(v.ProductId, v.SizeId, v.TemplateId) - w.renderImageTaskCtlChan <- renderImageControlChanItem{ + w.renderProperty.renderImageTaskCtlChan <- renderImageControlChanItem{ Option: 1, //0删除 1添加 Key: key, } @@ -37,12 +49,12 @@ func (w *wsConnectItem) operationRenderTask() { select { case <-w.closeChan: return - case data := <-w.renderImageTaskCtlChan: + case data := <-w.renderProperty.renderImageTaskCtlChan: switch data.Option { case 0: //删除任务 - delete(w.renderImageTask, data.Key) + delete(w.renderProperty.renderImageTask, data.Key) case 1: //新增任务 - w.renderImageTask[data.Key] = struct{}{} + w.renderProperty.renderImageTask[data.Key] = struct{}{} default: } From 3c5b0d7e421acb09825052fac689b886411b0e69 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 17:09:04 +0800 Subject: [PATCH 43/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 1 + 1 file changed, 1 insertion(+) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 78ff3004..1d5fc074 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -34,6 +34,7 @@ func NewDataTransferLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Data } var ( + //临时缓存对象池 buffPool = sync.Pool{ New: func() interface{} { return bytes.Buffer{} From be045b26151057a523e0a206fd26630c13b9279e Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 17:13:14 +0800 Subject: [PATCH 44/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 1d5fc074..ae4663cb 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -61,7 +61,7 @@ var ( // 每个连接的连接基本属性 type wsConnectItem struct { conn *websocket.Conn //websocket的连接 - closeChan chan struct{} //关闭chan + closeChan chan struct{} //ws连接关闭chan isClose bool //是否已经关闭 flag string //ws连接唯一标识 inChan chan []byte //接受消息缓冲通道 From 0142e04ef55fa2d8754c68efd2a25b5df17d1470 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 17:30:35 +0800 Subject: [PATCH 45/68] fix --- .../internal/logic/datatransferlogic.go | 57 +++++++++---------- 1 file changed, 26 insertions(+), 31 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index ae4663cb..0d8571f6 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -6,6 +6,7 @@ import ( "fmt" "fusenapi/constants" "fusenapi/server/websocket/internal/types" + "fusenapi/utils/auth" "github.com/google/uuid" "github.com/gorilla/websocket" "github.com/zeromicro/go-zero/rest/httpx" @@ -79,44 +80,17 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp } defer conn.Close() rsp := types.DataTransferData{} - /*isAuth := true - // 解析JWT token,并对空用户进行判断 - claims, err := svcCtx.ParseJwtToken(r) - // 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息 - if err != nil { + //鉴权不成功10秒后断开 + if !l.checkAuth(svcCtx, r) { rsp.T = constants.WEBSOCKET_UNAUTH rsp.D = "unAuth" b, _ := json.Marshal(rsp) _ = conn.WriteMessage(websocket.TextMessage, b) - isAuth = false - } - if claims != nil { - // 从token中获取对应的用户信息 - _, err = auth.GetUserInfoFormMapClaims(claims) - // 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息 - if err != nil { - rsp.T = constants.WEBSOCKET_UNAUTH - rsp.D = "unAuth!!" - b, _ := json.Marshal(rsp) - _ = conn.WriteMessage(websocket.TextMessage, b) - isAuth = false - } - } else { - // 如果claims为nil,则认为用户身份为白板用户 - rsp.T = constants.WEBSOCKET_UNAUTH - rsp.D = "unAuth!!!" - b, _ := json.Marshal(rsp) - _ = conn.WriteMessage(websocket.TextMessage, b) - isAuth = false - } - //不是授权的连接(10秒后关闭) - if !isAuth { select { - case <-time.After(time.Second * 10): - conn.Close() + case <-time.After(time.Second * 10): //10秒后断开 return } - }*/ + } //生成连接唯一标识 flag := uuid.New().String() + time.Now().Format("20060102150405") ws := wsConnectItem{ @@ -150,6 +124,27 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp ws.heartbeat() } +// 鉴权 +func (l *DataTransferLogic) checkAuth(svcCtx *svc.ServiceContext, r *http.Request) bool { + // 解析JWT token,并对空用户进行判断 + claims, err := svcCtx.ParseJwtToken(r) + // 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息 + if err != nil { + return false + } + if claims != nil { + // 从token中获取对应的用户信息 + _, err = auth.GetUserInfoFormMapClaims(claims) + // 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息 + if err != nil { + return false + } + } else { + return false + } + return true +} + // 心跳 func (w *wsConnectItem) heartbeat() { rsp := types.DataTransferData{ From 7280c38b16149f6bc6612200b71c29f87ba4a921 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 17:39:56 +0800 Subject: [PATCH 46/68] fix --- .../internal/logic/datatransferlogic.go | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 0d8571f6..e0ac8a3f 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -81,16 +81,16 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp defer conn.Close() rsp := types.DataTransferData{} //鉴权不成功10秒后断开 - if !l.checkAuth(svcCtx, r) { + /*if !l.checkAuth(svcCtx, r) { rsp.T = constants.WEBSOCKET_UNAUTH rsp.D = "unAuth" b, _ := json.Marshal(rsp) + //先发一条正常信息 _ = conn.WriteMessage(websocket.TextMessage, b) - select { - case <-time.After(time.Second * 10): //10秒后断开 - return - } - } + //发送关闭信息 + _ = conn.WriteMessage(websocket.CloseMessage, nil) + return + }*/ //生成连接唯一标识 flag := uuid.New().String() + time.Now().Format("20060102150405") ws := wsConnectItem{ @@ -147,11 +147,6 @@ func (l *DataTransferLogic) checkAuth(svcCtx *svc.ServiceContext, r *http.Reques // 心跳 func (w *wsConnectItem) heartbeat() { - rsp := types.DataTransferData{ - T: constants.WEBSOCKET_HEARTBEAT, - D: "", - } - b, _ := json.Marshal(rsp) for { time.Sleep(time.Second * 10) select { @@ -159,7 +154,7 @@ func (w *wsConnectItem) heartbeat() { return default: //发送心跳信息 - if err := w.conn.WriteMessage(websocket.TextMessage, b); err != nil { + if err := w.conn.WriteMessage(websocket.PongMessage, nil); err != nil { logx.Error("发送心跳信息异常,关闭连接:", w.flag, err) w.close() return @@ -173,6 +168,8 @@ func (w *wsConnectItem) close() { w.mutex.Lock() defer w.mutex.Unlock() logx.Info("websocket:", w.flag, " is closing...") + //发送关闭信息 + _ = w.conn.WriteMessage(websocket.CloseMessage, nil) w.conn.Close() mapConnPool.Delete(w.flag) if !w.isClose { From 06e4f1f96e51077be65d2d2e2e22ca14f409af6d Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 17:47:02 +0800 Subject: [PATCH 47/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 5 ----- 1 file changed, 5 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index e0ac8a3f..a606852a 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -9,7 +9,6 @@ import ( "fusenapi/utils/auth" "github.com/google/uuid" "github.com/gorilla/websocket" - "github.com/zeromicro/go-zero/rest/httpx" "net/http" "sync" "time" @@ -49,10 +48,6 @@ var ( CheckOrigin: func(r *http.Request) bool { return true }, - Error: func(w http.ResponseWriter, r *http.Request, status int, reason error) { - httpx.ErrorCtx(r.Context(), w, reason) - return - }, WriteBufferPool: &buffPool, } //连接map池 From fcd20e7fc235b9192243e9d16cc0ce96e80f90c9 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 17:48:51 +0800 Subject: [PATCH 48/68] fix --- server/websocket/internal/logic/rendernotifylogic.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/websocket/internal/logic/rendernotifylogic.go b/server/websocket/internal/logic/rendernotifylogic.go index c203443e..5b3e3d2d 100644 --- a/server/websocket/internal/logic/rendernotifylogic.go +++ b/server/websocket/internal/logic/rendernotifylogic.go @@ -54,7 +54,7 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi signHex := h.Sum(nil) sign := hex.EncodeToString(signHex) if req.Sign != sign { - return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "invalid") + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "invalid sign") } //遍历websocket链接把数据传进去 mapConnPool.Range(func(key, value any) bool { From 9a8bdcb5baec8707748bf42041cb07fcea694329 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 17:55:14 +0800 Subject: [PATCH 49/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index a606852a..88097476 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -193,15 +193,18 @@ func (w *wsConnectItem) readLoop() { case <-w.closeChan: //如果关闭了 return default: - _, data, err := w.conn.ReadMessage() + msgType, data, err := w.conn.ReadMessage() if err != nil { logx.Error("接受信息错误:", err) //关闭连接 w.close() return } - //消息传入缓冲通道 - w.inChan <- data + //ping的消息不处理 + if msgType != websocket.PingMessage { + //消息传入缓冲通道 + w.inChan <- data + } } } } From fdaddf9184a71a9e18f093b1ee3ad960af7fe3b4 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 18:00:46 +0800 Subject: [PATCH 50/68] fix --- constants/websocket.go | 2 -- server/websocket/internal/logic/datatransferlogic.go | 4 ++-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/constants/websocket.go b/constants/websocket.go index 71f1fc36..93648380 100644 --- a/constants/websocket.go +++ b/constants/websocket.go @@ -8,8 +8,6 @@ const ( WEBSOCKET_UNAUTH = "WEBSOCKET_UNAUTH" //ws连接成功 WEBSOCKET_CONNECT_SUCCESS = "WEBSOCKET_CONNECT_SUCCESS" - //心跳信息 - WEBSOCKET_HEARTBEAT = "WEBSOCKET_HEARTBEAT" //图片渲染 WEBSOCKET_RENDER_IMAGE = "WEBSOCKET_RENDER_IMAGE" //数据格式错误 diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 88097476..6c317518 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -142,12 +142,12 @@ func (l *DataTransferLogic) checkAuth(svcCtx *svc.ServiceContext, r *http.Reques // 心跳 func (w *wsConnectItem) heartbeat() { + tick := time.Tick(time.Second * 10) for { - time.Sleep(time.Second * 10) select { case <-w.closeChan: return - default: + case <-tick: //发送心跳信息 if err := w.conn.WriteMessage(websocket.PongMessage, nil); err != nil { logx.Error("发送心跳信息异常,关闭连接:", w.flag, err) From 265fd81b279be63f326c7b5e1d4e7785718f0c99 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 18:03:27 +0800 Subject: [PATCH 51/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 6c317518..b0961617 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -106,7 +106,7 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp rsp.T = constants.WEBSOCKET_CONNECT_SUCCESS rsp.D = flag b, _ := json.Marshal(rsp) - conn.WriteMessage(websocket.TextMessage, b) + _ = conn.WriteMessage(websocket.TextMessage, b) //循环读客户端信息 go ws.readLoop() //循环把数据发送给客户端 @@ -181,7 +181,11 @@ func (w *wsConnectItem) writeLoop() { case <-w.closeChan: //如果关闭了 return case data := <-w.outChan: - w.conn.WriteMessage(websocket.TextMessage, data) + if err := w.conn.WriteMessage(websocket.TextMessage, data); err != nil { + logx.Error("websocket write loop err:", err) + w.close() + return + } } } } From 32e954ccc870ffc549e75e236c6f4b67d69345c2 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 18:09:09 +0800 Subject: [PATCH 52/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 1 + 1 file changed, 1 insertion(+) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index b0961617..b67eaa80 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -42,6 +42,7 @@ var ( } //升级websocket upgrade = websocket.Upgrader{ + ReadBufferSize: 1024 * 10, //最大可读取大小 10M //握手超时时间15s HandshakeTimeout: time.Second * 15, //允许跨域 From 9255a0073f195faa04202517752531186def7ba5 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 18:14:04 +0800 Subject: [PATCH 53/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index b67eaa80..cac946a2 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -88,7 +88,7 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp return }*/ //生成连接唯一标识 - flag := uuid.New().String() + time.Now().Format("20060102150405") + flag := uuid.New().String() + "" ws := wsConnectItem{ conn: conn, flag: flag, From 857a632ceac53c1d103d2f67035aa12b2f5468d9 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 18:20:15 +0800 Subject: [PATCH 54/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 1 - 1 file changed, 1 deletion(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index cac946a2..49e81fe0 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -79,7 +79,6 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp //鉴权不成功10秒后断开 /*if !l.checkAuth(svcCtx, r) { rsp.T = constants.WEBSOCKET_UNAUTH - rsp.D = "unAuth" b, _ := json.Marshal(rsp) //先发一条正常信息 _ = conn.WriteMessage(websocket.TextMessage, b) From 636bc0aee715f8d2f6cd072a90495e059007bac0 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 18:32:39 +0800 Subject: [PATCH 55/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 49e81fe0..c8270928 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -148,6 +148,8 @@ func (w *wsConnectItem) heartbeat() { case <-w.closeChan: return case <-tick: + //设置写超时时间10s + _ = w.conn.SetWriteDeadline(time.Now().Add(time.Second * 10)) //发送心跳信息 if err := w.conn.WriteMessage(websocket.PongMessage, nil); err != nil { logx.Error("发送心跳信息异常,关闭连接:", w.flag, err) From f609fa364dc5b95477c681af9a2b8ebea85ebb65 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 19:19:20 +0800 Subject: [PATCH 56/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index c8270928..2250611e 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -142,7 +142,7 @@ func (l *DataTransferLogic) checkAuth(svcCtx *svc.ServiceContext, r *http.Reques // 心跳 func (w *wsConnectItem) heartbeat() { - tick := time.Tick(time.Second * 10) + tick := time.Tick(time.Second * 2) for { select { case <-w.closeChan: @@ -166,6 +166,7 @@ func (w *wsConnectItem) close() { defer w.mutex.Unlock() logx.Info("websocket:", w.flag, " is closing...") //发送关闭信息 + _ = w.conn.SetWriteDeadline(time.Now().Add(time.Second)) _ = w.conn.WriteMessage(websocket.CloseMessage, nil) w.conn.Close() mapConnPool.Delete(w.flag) From 72543d519f6fdba25099c38fcdf939a402d903f1 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 26 Jul 2023 19:29:23 +0800 Subject: [PATCH 57/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 2250611e..49e81fe0 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -142,14 +142,12 @@ func (l *DataTransferLogic) checkAuth(svcCtx *svc.ServiceContext, r *http.Reques // 心跳 func (w *wsConnectItem) heartbeat() { - tick := time.Tick(time.Second * 2) + tick := time.Tick(time.Second * 10) for { select { case <-w.closeChan: return case <-tick: - //设置写超时时间10s - _ = w.conn.SetWriteDeadline(time.Now().Add(time.Second * 10)) //发送心跳信息 if err := w.conn.WriteMessage(websocket.PongMessage, nil); err != nil { logx.Error("发送心跳信息异常,关闭连接:", w.flag, err) @@ -166,7 +164,6 @@ func (w *wsConnectItem) close() { defer w.mutex.Unlock() logx.Info("websocket:", w.flag, " is closing...") //发送关闭信息 - _ = w.conn.SetWriteDeadline(time.Now().Add(time.Second)) _ = w.conn.WriteMessage(websocket.CloseMessage, nil) w.conn.Close() mapConnPool.Delete(w.flag) From 2b30911ec64750541d54d324f05fcfd491a366a2 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Thu, 27 Jul 2023 10:06:27 +0800 Subject: [PATCH 58/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 49e81fe0..0a043c6e 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -49,7 +49,8 @@ var ( CheckOrigin: func(r *http.Request) bool { return true }, - WriteBufferPool: &buffPool, + WriteBufferPool: &buffPool, + EnableCompression: true, } //连接map池 mapConnPool = sync.Map{} From 2cb4549f008a4fb6721c44fd8ac30ce473e826f3 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Thu, 27 Jul 2023 10:08:30 +0800 Subject: [PATCH 59/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 0a043c6e..01df20fe 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -143,7 +143,7 @@ func (l *DataTransferLogic) checkAuth(svcCtx *svc.ServiceContext, r *http.Reques // 心跳 func (w *wsConnectItem) heartbeat() { - tick := time.Tick(time.Second * 10) + tick := time.Tick(time.Second * 5) for { select { case <-w.closeChan: From 2a06a28ad68701b168faf9eae4e40aef392dc7a8 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Thu, 27 Jul 2023 10:46:08 +0800 Subject: [PATCH 60/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 01df20fe..7ba85da9 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -76,9 +76,11 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp return } defer conn.Close() + w.Header().Set("Connection", "Upgrade") rsp := types.DataTransferData{} //鉴权不成功10秒后断开 - /*if !l.checkAuth(svcCtx, r) { + if !l.checkAuth(svcCtx, r) { + time.Sleep(time.Second) //兼容下火狐 rsp.T = constants.WEBSOCKET_UNAUTH b, _ := json.Marshal(rsp) //先发一条正常信息 @@ -86,7 +88,7 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp //发送关闭信息 _ = conn.WriteMessage(websocket.CloseMessage, nil) return - }*/ + } //生成连接唯一标识 flag := uuid.New().String() + "" ws := wsConnectItem{ @@ -104,6 +106,7 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp mapConnPool.Store(flag, ws) defer ws.close() //把连接成功消息发回去 + time.Sleep(time.Second) //兼容下火狐 rsp.T = constants.WEBSOCKET_CONNECT_SUCCESS rsp.D = flag b, _ := json.Marshal(rsp) From 84692531313be7f9959517cf77fa39037fea32f4 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Thu, 27 Jul 2023 12:32:03 +0800 Subject: [PATCH 61/68] fix --- .../internal/logic/datatransferlogic.go | 41 +++++++------ .../internal/logic/rendernotifylogic.go | 57 +++++++++---------- .../internal/logic/ws_render_image_logic.go | 23 ++++---- server/websocket/internal/types/types.go | 34 ++++++----- server_api/websocket.api | 36 ++++++------ 5 files changed, 101 insertions(+), 90 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 7ba85da9..f6935f10 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -65,6 +65,7 @@ type wsConnectItem struct { inChan chan []byte //接受消息缓冲通道 outChan chan []byte //发送回客户端的消息 mutex sync.Mutex //互斥锁 + userId int64 //用户id renderProperty renderProperty //扩展云渲染属性 } @@ -79,16 +80,17 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp w.Header().Set("Connection", "Upgrade") rsp := types.DataTransferData{} //鉴权不成功10秒后断开 - if !l.checkAuth(svcCtx, r) { - time.Sleep(time.Second) //兼容下火狐 - rsp.T = constants.WEBSOCKET_UNAUTH - b, _ := json.Marshal(rsp) - //先发一条正常信息 - _ = conn.WriteMessage(websocket.TextMessage, b) - //发送关闭信息 - _ = conn.WriteMessage(websocket.CloseMessage, nil) - return - } + /* isAuth, userInfo := l.checkAuth(svcCtx, r) + if !isAuth { + time.Sleep(time.Second) //兼容下火狐 + rsp.T = constants.WEBSOCKET_UNAUTH + b, _ := json.Marshal(rsp) + //先发一条正常信息 + _ = conn.WriteMessage(websocket.TextMessage, b) + //发送关闭信息 + _ = conn.WriteMessage(websocket.CloseMessage, nil) + return + }*/ //生成连接唯一标识 flag := uuid.New().String() + "" ws := wsConnectItem{ @@ -102,6 +104,9 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp renderImageTaskCtlChan: make(chan renderImageControlChanItem, 100), }, } + /*if userInfo != nil { + ws.userId = userInfo.UserId + }*/ //保存连接 mapConnPool.Store(flag, ws) defer ws.close() @@ -124,24 +129,24 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp } // 鉴权 -func (l *DataTransferLogic) checkAuth(svcCtx *svc.ServiceContext, r *http.Request) bool { +func (l *DataTransferLogic) checkAuth(svcCtx *svc.ServiceContext, r *http.Request) (isAuth bool, userInfo *auth.UserInfo) { // 解析JWT token,并对空用户进行判断 claims, err := svcCtx.ParseJwtToken(r) // 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息 if err != nil { - return false + return false, nil } if claims != nil { // 从token中获取对应的用户信息 - _, err = auth.GetUserInfoFormMapClaims(claims) + userInfo, err = auth.GetUserInfoFormMapClaims(claims) // 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息 if err != nil { - return false + return false, nil } } else { - return false + return false, nil } - return true + return true, userInfo } // 心跳 @@ -240,8 +245,8 @@ func (w *wsConnectItem) sendToOutChan(data []byte) { } // 获取需要渲染图片的map key -func (w *wsConnectItem) getRenderImageMapKey(productId, sizeId, templateId int64) string { - return fmt.Sprintf("%d-%d-%d", productId, sizeId, templateId) +func (w *wsConnectItem) getRenderImageMapKey(productId, mapsSourceId, templateId, renderDesignId int64) string { + return fmt.Sprintf("%d-%d-%d-%d", productId, mapsSourceId, templateId, renderDesignId) } // 处理接受到的数据 diff --git a/server/websocket/internal/logic/rendernotifylogic.go b/server/websocket/internal/logic/rendernotifylogic.go index 5b3e3d2d..68a49e0d 100644 --- a/server/websocket/internal/logic/rendernotifylogic.go +++ b/server/websocket/internal/logic/rendernotifylogic.go @@ -41,18 +41,16 @@ func NewRenderNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Rend // } func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basic.Response) { - if len(req.NotifyList) == 0 { - return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "notify list is empty") - } if time.Now().Unix()-120 > req.Time /*|| req.Time > time.Now().Unix() */ { - return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "time is expire") + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "invalid param time") } //验证签名 sha256 - notifyByte, _ := json.Marshal(req.NotifyList) + 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") } @@ -61,34 +59,31 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi //断言连接 ws, ok := value.(wsConnectItem) if !ok { - return false + return true } - //遍历数据 - for _, notifyItem := range req.NotifyList { - renderKey := ws.getRenderImageMapKey(notifyItem.ProductId, notifyItem.SizeId, notifyItem.TemplateId) - //查询有无该渲染任务 - _, ok = ws.renderProperty.renderImageTask[renderKey] - if !ok { - continue - } - rspData := types.DataTransferData{ - T: constants.WEBSOCKET_RENDER_IMAGE, - D: types.RenderImageRspMsg{ - ProductId: notifyItem.ProductId, - SizeId: notifyItem.SizeId, - TemplateId: notifyItem.TemplateId, - Source: notifyItem.Source, - }, - } - b, _ := json.Marshal(rspData) - //删除对应的需要渲染的图片map - ws.renderProperty.renderImageTaskCtlChan <- renderImageControlChanItem{ - Option: 0, //0删除 1添加 - Key: renderKey, - } - //发送数据到out chan - ws.sendToOutChan(b) + renderKey := ws.getRenderImageMapKey(req.Info.ProductId, req.Info.MapsSourceId, req.Info.TemplateId, req.Info.RenderDesignId) + //查询有无该渲染任务 + _, ok = ws.renderProperty.renderImageTask[renderKey] + if !ok { + return true } + rspData := types.DataTransferData{ + T: constants.WEBSOCKET_RENDER_IMAGE, + D: types.RenderImageRspMsg{ + ProductId: req.Info.ProductId, + MapsSourceId: req.Info.MapsSourceId, + TemplateId: req.Info.TemplateId, + RenderSource: req.Info.RenderSource, + }, + } + 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) diff --git a/server/websocket/internal/logic/ws_render_image_logic.go b/server/websocket/internal/logic/ws_render_image_logic.go index b93e4b67..5dc17dd4 100644 --- a/server/websocket/internal/logic/ws_render_image_logic.go +++ b/server/websocket/internal/logic/ws_render_image_logic.go @@ -28,17 +28,20 @@ func (w *wsConnectItem) SendToCloudRender(data []byte) { logx.Info("收到请求云渲染图片数据:", renderImageData) //把需要渲染的图片任务加进去 for _, v := range renderImageData { - select { - case <-w.closeChan: //连接关闭了 - return - default: - //加入渲染任务 - key := w.getRenderImageMapKey(v.ProductId, v.SizeId, v.TemplateId) - w.renderProperty.renderImageTaskCtlChan <- renderImageControlChanItem{ - Option: 1, //0删除 1添加 - Key: key, + for _, productId := range v.ProductIds { + select { + case <-w.closeChan: //连接关闭了 + return + default: + //加入渲染任务 + key := w.getRenderImageMapKey(productId, v.MapsSourceId, v.TemplateId, v.RenderDesignId) + w.renderProperty.renderImageTaskCtlChan <- renderImageControlChanItem{ + Option: 1, //0删除 1添加 + Key: key, + } + // TODO 数据发送给云渲染服务器 + v.UserId = w.userId //赋值 } - // TODO 数据发送给云渲染服务器 } } } diff --git a/server/websocket/internal/types/types.go b/server/websocket/internal/types/types.go index d3336021..27260328 100644 --- a/server/websocket/internal/types/types.go +++ b/server/websocket/internal/types/types.go @@ -11,29 +11,33 @@ type DataTransferData struct { } type RenderImageReqMsg struct { - ProductId int64 `json:"product_id"` - SizeId int64 `json:"size_id"` - TemplateId int64 `json:"template_id"` + ProductIds []int64 `json:"product_ids"` //产品 id + MapsSourceId int64 `json:"maps_source_id"` //贴图数据id + TemplateId int64 `json:"template_id"` //模板id + UserId int64 `json:"user_id"` //用户id(这个前端不用传,后台获取) + RenderDesignId int64 `json:"render_design_id"` //渲染设计id } type RenderImageRspMsg struct { - ProductId int64 `json:"product_id"` - SizeId int64 `json:"size_id"` - TemplateId int64 `json:"template_id"` - Source string `json:"source"` + ProductId int64 `json:"product_id"` //产品 id + MapsSourceId int64 `json:"maps_source_id"` //贴图数据id + TemplateId int64 `json:"template_id"` //模板id + RenderDesignId int64 `json:"render_design_id"` //渲染设计id + RenderSource interface{} `json:"render_source"` //渲染结果数据 } type RenderNotifyReq struct { - Sign string `json:"sign"` - Time int64 `json:"time"` - NotifyList []NotifyItem `json:"notify_list"` + Sign string `json:"sign"` + Time int64 `json:"time"` + Info NotifyInfo `json:"info"` } -type NotifyItem struct { - ProductId int64 `json:"product_id"` - SizeId int64 `json:"size_id"` - TemplateId int64 `json:"template_id"` - Source string `json:"source"` +type NotifyInfo struct { + ProductId int64 `json:"product_id"` + MapsSourceId int64 `json:"maps_source_id"` + TemplateId int64 `json:"template_id"` + RenderDesignId int64 `json:"render_design_id"` //渲染设计id + RenderSource interface{} `json:"render_source"` //渲染完返回的数据 } type Request struct { diff --git a/server_api/websocket.api b/server_api/websocket.api index 0d445c71..15366697 100644 --- a/server_api/websocket.api +++ b/server_api/websocket.api @@ -22,26 +22,30 @@ type DataTransferData { T string `json:"t"` //消息类型 D interface{} `json:"d"` //传递的消息 } -type RenderImageReqMsg { //websocket接受需要云渲染的图片 - ProductId int64 `json:"product_id"` - SizeId int64 `json:"size_id"` - TemplateId int64 `json:"template_id"` +type RenderImageReqMsg { //websocket接受要云渲染处理的数据 + ProductIds []int64 `json:"product_ids"` //产品 id + MapsSourceId int64 `json:"maps_source_id"` //贴图数据id + TemplateId int64 `json:"template_id"` //模板id + UserId int64 `json:"user_id"` //用户id(这个前端不用传,后台获取) + RenderDesignId int64 `json:"render_design_id"` //渲染设计id } type RenderImageRspMsg { //websocket发送渲染完的数据 - ProductId int64 `json:"product_id"` - SizeId int64 `json:"size_id"` - TemplateId int64 `json:"template_id"` - Source string `json:"source"` + ProductId int64 `json:"product_id"` //产品 id + MapsSourceId int64 `json:"maps_source_id"` //贴图数据id + TemplateId int64 `json:"template_id"` //模板id + RenderDesignId int64 `json:"render_design_id"` //渲染设计id + RenderSource interface{} `json:"render_source"` //渲染结果数据 } //渲染完了通知接口 type RenderNotifyReq { - Sign string `json:"sign"` - Time int64 `json:"time"` - NotifyList []NotifyItem `json:"notify_list"` + Sign string `json:"sign"` + Time int64 `json:"time"` + Info NotifyInfo `json:"info"` } -type NotifyItem { - ProductId int64 `json:"product_id"` - SizeId int64 `json:"size_id"` - TemplateId int64 `json:"template_id"` - Source string `json:"source"` +type NotifyInfo { + ProductId int64 `json:"product_id"` + MapsSourceId int64 `json:"maps_source_id"` + TemplateId int64 `json:"template_id"` + RenderDesignId int64 `json:"render_design_id"` //渲染设计id + RenderSource interface{} `json:"render_source"` //渲染完返回的数据 } \ No newline at end of file From c375d17c07fd12124a1c415faea17927469c8ff5 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Thu, 27 Jul 2023 14:10:41 +0800 Subject: [PATCH 62/68] fix --- .../internal/logic/rendernotifylogic.go | 4 ++-- server/websocket/internal/types/types.go | 20 +++++++++---------- server_api/websocket.api | 20 +++++++++---------- 3 files changed, 22 insertions(+), 22 deletions(-) diff --git a/server/websocket/internal/logic/rendernotifylogic.go b/server/websocket/internal/logic/rendernotifylogic.go index 68a49e0d..f2b2ebdb 100644 --- a/server/websocket/internal/logic/rendernotifylogic.go +++ b/server/websocket/internal/logic/rendernotifylogic.go @@ -50,7 +50,7 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi 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) + //fmt.Println(sign) if req.Sign != sign { return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "invalid sign") } @@ -73,7 +73,7 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi ProductId: req.Info.ProductId, MapsSourceId: req.Info.MapsSourceId, TemplateId: req.Info.TemplateId, - RenderSource: req.Info.RenderSource, + RenderResult: req.Info.RenderResult, }, } b, _ := json.Marshal(rspData) diff --git a/server/websocket/internal/types/types.go b/server/websocket/internal/types/types.go index 27260328..29427449 100644 --- a/server/websocket/internal/types/types.go +++ b/server/websocket/internal/types/types.go @@ -19,11 +19,11 @@ type RenderImageReqMsg struct { } type RenderImageRspMsg struct { - ProductId int64 `json:"product_id"` //产品 id - MapsSourceId int64 `json:"maps_source_id"` //贴图数据id - TemplateId int64 `json:"template_id"` //模板id - RenderDesignId int64 `json:"render_design_id"` //渲染设计id - RenderSource interface{} `json:"render_source"` //渲染结果数据 + ProductId int64 `json:"product_id"` //产品 id + MapsSourceId int64 `json:"maps_source_id"` //贴图数据id + TemplateId int64 `json:"template_id"` //模板id + RenderDesignId int64 `json:"render_design_id"` //渲染设计id + RenderResult string `json:"render_result"` //渲染结果数据 } type RenderNotifyReq struct { @@ -33,11 +33,11 @@ type RenderNotifyReq struct { } type NotifyInfo struct { - ProductId int64 `json:"product_id"` - MapsSourceId int64 `json:"maps_source_id"` - TemplateId int64 `json:"template_id"` - RenderDesignId int64 `json:"render_design_id"` //渲染设计id - RenderSource interface{} `json:"render_source"` //渲染完返回的数据 + ProductId int64 `json:"product_id"` + MapsSourceId int64 `json:"maps_source_id"` + TemplateId int64 `json:"template_id"` + RenderDesignId int64 `json:"render_design_id"` //渲染设计id + RenderResult string `json:"render_result"` //渲染结果数据 } type Request struct { diff --git a/server_api/websocket.api b/server_api/websocket.api index 15366697..90ff6e31 100644 --- a/server_api/websocket.api +++ b/server_api/websocket.api @@ -30,11 +30,11 @@ type RenderImageReqMsg { //websocket接受要云渲染处理的数据 RenderDesignId int64 `json:"render_design_id"` //渲染设计id } type RenderImageRspMsg { //websocket发送渲染完的数据 - ProductId int64 `json:"product_id"` //产品 id - MapsSourceId int64 `json:"maps_source_id"` //贴图数据id - TemplateId int64 `json:"template_id"` //模板id - RenderDesignId int64 `json:"render_design_id"` //渲染设计id - RenderSource interface{} `json:"render_source"` //渲染结果数据 + ProductId int64 `json:"product_id"` //产品 id + MapsSourceId int64 `json:"maps_source_id"` //贴图数据id + TemplateId int64 `json:"template_id"` //模板id + RenderDesignId int64 `json:"render_design_id"` //渲染设计id + RenderResult string `json:"render_result"` //渲染结果数据 } //渲染完了通知接口 type RenderNotifyReq { @@ -43,9 +43,9 @@ type RenderNotifyReq { Info NotifyInfo `json:"info"` } type NotifyInfo { - ProductId int64 `json:"product_id"` - MapsSourceId int64 `json:"maps_source_id"` - TemplateId int64 `json:"template_id"` - RenderDesignId int64 `json:"render_design_id"` //渲染设计id - RenderSource interface{} `json:"render_source"` //渲染完返回的数据 + ProductId int64 `json:"product_id"` + MapsSourceId int64 `json:"maps_source_id"` + TemplateId int64 `json:"template_id"` + RenderDesignId int64 `json:"render_design_id"` //渲染设计id + RenderResult string `json:"render_result"` //渲染结果数据 } \ No newline at end of file From 55a879ada836f5a73f37bc0f92080fa4808aae1e Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Thu, 27 Jul 2023 14:31:53 +0800 Subject: [PATCH 63/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index f6935f10..56f47c85 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -92,7 +92,7 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp return }*/ //生成连接唯一标识 - flag := uuid.New().String() + "" + flag := uuid.New().String() + "time=" + time.Now().Format("15-04-05") ws := wsConnectItem{ conn: conn, flag: flag, From 7297a1ef020873f8bb5dfc3e10624ab42faaa5cb Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Thu, 27 Jul 2023 15:46:07 +0800 Subject: [PATCH 64/68] fix --- .../internal/logic/datatransferlogic.go | 30 ++++++++----------- .../internal/logic/rendernotifylogic.go | 11 ++++--- .../internal/logic/ws_render_image_logic.go | 27 ++++++++--------- server/websocket/internal/types/types.go | 23 +++++--------- server_api/websocket.api | 23 +++++--------- 5 files changed, 46 insertions(+), 68 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 56f47c85..34d14adb 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -65,7 +65,6 @@ type wsConnectItem struct { inChan chan []byte //接受消息缓冲通道 outChan chan []byte //发送回客户端的消息 mutex sync.Mutex //互斥锁 - userId int64 //用户id renderProperty renderProperty //扩展云渲染属性 } @@ -80,17 +79,17 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp w.Header().Set("Connection", "Upgrade") rsp := types.DataTransferData{} //鉴权不成功10秒后断开 - /* isAuth, userInfo := l.checkAuth(svcCtx, r) - if !isAuth { - time.Sleep(time.Second) //兼容下火狐 - rsp.T = constants.WEBSOCKET_UNAUTH - b, _ := json.Marshal(rsp) - //先发一条正常信息 - _ = conn.WriteMessage(websocket.TextMessage, b) - //发送关闭信息 - _ = conn.WriteMessage(websocket.CloseMessage, nil) - return - }*/ + /*isAuth, _ := l.checkAuth(svcCtx, r) + if !isAuth { + time.Sleep(time.Second) //兼容下火狐 + rsp.T = constants.WEBSOCKET_UNAUTH + b, _ := json.Marshal(rsp) + //先发一条正常信息 + _ = conn.WriteMessage(websocket.TextMessage, b) + //发送关闭信息 + _ = conn.WriteMessage(websocket.CloseMessage, nil) + return + }*/ //生成连接唯一标识 flag := uuid.New().String() + "time=" + time.Now().Format("15-04-05") ws := wsConnectItem{ @@ -104,9 +103,6 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp renderImageTaskCtlChan: make(chan renderImageControlChanItem, 100), }, } - /*if userInfo != nil { - ws.userId = userInfo.UserId - }*/ //保存连接 mapConnPool.Store(flag, ws) defer ws.close() @@ -245,8 +241,8 @@ func (w *wsConnectItem) sendToOutChan(data []byte) { } // 获取需要渲染图片的map key -func (w *wsConnectItem) getRenderImageMapKey(productId, mapsSourceId, templateId, renderDesignId int64) string { - return fmt.Sprintf("%d-%d-%d-%d", productId, mapsSourceId, templateId, renderDesignId) +func (w *wsConnectItem) getRenderImageMapKey(productId, templateTagId int64) string { + return fmt.Sprintf("%d-%d", productId, templateTagId) } // 处理接受到的数据 diff --git a/server/websocket/internal/logic/rendernotifylogic.go b/server/websocket/internal/logic/rendernotifylogic.go index f2b2ebdb..20ab5c9a 100644 --- a/server/websocket/internal/logic/rendernotifylogic.go +++ b/server/websocket/internal/logic/rendernotifylogic.go @@ -50,7 +50,7 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi 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) + fmt.Println(sign) if req.Sign != sign { return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "invalid sign") } @@ -61,7 +61,7 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi if !ok { return true } - renderKey := ws.getRenderImageMapKey(req.Info.ProductId, req.Info.MapsSourceId, req.Info.TemplateId, req.Info.RenderDesignId) + renderKey := ws.getRenderImageMapKey(req.Info.ProductId, req.Info.TemplateTagId) //查询有无该渲染任务 _, ok = ws.renderProperty.renderImageTask[renderKey] if !ok { @@ -70,10 +70,9 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi rspData := types.DataTransferData{ T: constants.WEBSOCKET_RENDER_IMAGE, D: types.RenderImageRspMsg{ - ProductId: req.Info.ProductId, - MapsSourceId: req.Info.MapsSourceId, - TemplateId: req.Info.TemplateId, - RenderResult: req.Info.RenderResult, + ProductId: req.Info.ProductId, + TemplateTagId: req.Info.TemplateTagId, + Image: req.Info.Image, }, } b, _ := json.Marshal(rspData) diff --git a/server/websocket/internal/logic/ws_render_image_logic.go b/server/websocket/internal/logic/ws_render_image_logic.go index 5dc17dd4..012d7d6b 100644 --- a/server/websocket/internal/logic/ws_render_image_logic.go +++ b/server/websocket/internal/logic/ws_render_image_logic.go @@ -20,28 +20,25 @@ type renderImageControlChanItem struct { // 渲染请求数据处理发送云渲染服务处理 func (w *wsConnectItem) SendToCloudRender(data []byte) { - var renderImageData []types.RenderImageReqMsg + var renderImageData types.RenderImageReqMsg if err := json.Unmarshal(data, &renderImageData); err != nil { logx.Error("invalid format of websocket render image message", err) return } logx.Info("收到请求云渲染图片数据:", renderImageData) //把需要渲染的图片任务加进去 - for _, v := range renderImageData { - for _, productId := range v.ProductIds { - select { - case <-w.closeChan: //连接关闭了 - return - default: - //加入渲染任务 - key := w.getRenderImageMapKey(productId, v.MapsSourceId, v.TemplateId, v.RenderDesignId) - w.renderProperty.renderImageTaskCtlChan <- renderImageControlChanItem{ - Option: 1, //0删除 1添加 - Key: key, - } - // TODO 数据发送给云渲染服务器 - v.UserId = w.userId //赋值 + for _, productId := range renderImageData.ProductIds { + select { + case <-w.closeChan: //连接关闭了 + return + default: + //加入渲染任务 + key := w.getRenderImageMapKey(productId, renderImageData.TemplateTagId) + w.renderProperty.renderImageTaskCtlChan <- renderImageControlChanItem{ + Option: 1, //0删除 1添加 + Key: key, } + // TODO 数据发送给云渲染服务器 } } } diff --git a/server/websocket/internal/types/types.go b/server/websocket/internal/types/types.go index 29427449..01801c85 100644 --- a/server/websocket/internal/types/types.go +++ b/server/websocket/internal/types/types.go @@ -11,19 +11,14 @@ type DataTransferData struct { } type RenderImageReqMsg struct { - ProductIds []int64 `json:"product_ids"` //产品 id - MapsSourceId int64 `json:"maps_source_id"` //贴图数据id - TemplateId int64 `json:"template_id"` //模板id - UserId int64 `json:"user_id"` //用户id(这个前端不用传,后台获取) - RenderDesignId int64 `json:"render_design_id"` //渲染设计id + ProductIds []int64 `json:"product_ids"` //产品 id + TemplateTagId int64 `json:"template_tag_id"` //模板标签id } type RenderImageRspMsg struct { - ProductId int64 `json:"product_id"` //产品 id - MapsSourceId int64 `json:"maps_source_id"` //贴图数据id - TemplateId int64 `json:"template_id"` //模板id - RenderDesignId int64 `json:"render_design_id"` //渲染设计id - RenderResult string `json:"render_result"` //渲染结果数据 + ProductId int64 `json:"product_id"` //产品 id + TemplateTagId int64 `json:"template_tag_id"` //模板标签id + Image string `json:"image"` //渲染后的图片 } type RenderNotifyReq struct { @@ -33,11 +28,9 @@ type RenderNotifyReq struct { } type NotifyInfo struct { - ProductId int64 `json:"product_id"` - MapsSourceId int64 `json:"maps_source_id"` - TemplateId int64 `json:"template_id"` - RenderDesignId int64 `json:"render_design_id"` //渲染设计id - RenderResult string `json:"render_result"` //渲染结果数据 + ProductId int64 `json:"product_id"` + TemplateTagId int64 `json:"template_tag_id"` //模板标签id + Image string `json:"image"` } type Request struct { diff --git a/server_api/websocket.api b/server_api/websocket.api index 90ff6e31..2b46d61f 100644 --- a/server_api/websocket.api +++ b/server_api/websocket.api @@ -23,18 +23,13 @@ type DataTransferData { D interface{} `json:"d"` //传递的消息 } type RenderImageReqMsg { //websocket接受要云渲染处理的数据 - ProductIds []int64 `json:"product_ids"` //产品 id - MapsSourceId int64 `json:"maps_source_id"` //贴图数据id - TemplateId int64 `json:"template_id"` //模板id - UserId int64 `json:"user_id"` //用户id(这个前端不用传,后台获取) - RenderDesignId int64 `json:"render_design_id"` //渲染设计id + ProductIds []int64 `json:"product_ids"` //产品 id + TemplateTagId int64 `json:"template_tag_id"` //模板标签id } type RenderImageRspMsg { //websocket发送渲染完的数据 - ProductId int64 `json:"product_id"` //产品 id - MapsSourceId int64 `json:"maps_source_id"` //贴图数据id - TemplateId int64 `json:"template_id"` //模板id - RenderDesignId int64 `json:"render_design_id"` //渲染设计id - RenderResult string `json:"render_result"` //渲染结果数据 + ProductId int64 `json:"product_id"` //产品 id + TemplateTagId int64 `json:"template_tag_id"` //模板标签id + Image string `json:"image"` //渲染后的图片 } //渲染完了通知接口 type RenderNotifyReq { @@ -43,9 +38,7 @@ type RenderNotifyReq { Info NotifyInfo `json:"info"` } type NotifyInfo { - ProductId int64 `json:"product_id"` - MapsSourceId int64 `json:"maps_source_id"` - TemplateId int64 `json:"template_id"` - RenderDesignId int64 `json:"render_design_id"` //渲染设计id - RenderResult string `json:"render_result"` //渲染结果数据 + ProductId int64 `json:"product_id"` + TemplateTagId int64 `json:"template_tag_id"` //模板标签id + Image string `json:"image"` } \ No newline at end of file From 5532cd1a11aeebbd1f5a91daabcfc1023551ee23 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Thu, 27 Jul 2023 16:13:06 +0800 Subject: [PATCH 65/68] fix --- .../internal/logic/datatransferlogic.go | 4 ++-- .../internal/logic/rendernotifylogic.go | 4 ++-- .../internal/logic/ws_render_image_logic.go | 2 +- server/websocket/internal/types/types.go | 19 +++++++++++-------- server_api/websocket.api | 19 +++++++++++-------- 5 files changed, 27 insertions(+), 21 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 34d14adb..582624d1 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -241,8 +241,8 @@ func (w *wsConnectItem) sendToOutChan(data []byte) { } // 获取需要渲染图片的map key -func (w *wsConnectItem) getRenderImageMapKey(productId, templateTagId int64) string { - return fmt.Sprintf("%d-%d", productId, templateTagId) +func (w *wsConnectItem) getRenderImageMapKey(productId, templateTagId int64, algorithmVersion string) string { + return fmt.Sprintf("%d-%d-%s", productId, templateTagId, algorithmVersion) } // 处理接受到的数据 diff --git a/server/websocket/internal/logic/rendernotifylogic.go b/server/websocket/internal/logic/rendernotifylogic.go index 20ab5c9a..06ab1172 100644 --- a/server/websocket/internal/logic/rendernotifylogic.go +++ b/server/websocket/internal/logic/rendernotifylogic.go @@ -50,7 +50,7 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi 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) + //fmt.Println(sign) if req.Sign != sign { return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "invalid sign") } @@ -61,7 +61,7 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq) (resp *basi if !ok { return true } - renderKey := ws.getRenderImageMapKey(req.Info.ProductId, req.Info.TemplateTagId) + renderKey := ws.getRenderImageMapKey(req.Info.ProductId, req.Info.TemplateTagId, req.Info.AlgorithmVersion) //查询有无该渲染任务 _, ok = ws.renderProperty.renderImageTask[renderKey] if !ok { diff --git a/server/websocket/internal/logic/ws_render_image_logic.go b/server/websocket/internal/logic/ws_render_image_logic.go index 012d7d6b..634b6267 100644 --- a/server/websocket/internal/logic/ws_render_image_logic.go +++ b/server/websocket/internal/logic/ws_render_image_logic.go @@ -33,7 +33,7 @@ func (w *wsConnectItem) SendToCloudRender(data []byte) { return default: //加入渲染任务 - key := w.getRenderImageMapKey(productId, renderImageData.TemplateTagId) + key := w.getRenderImageMapKey(productId, renderImageData.TemplateTagId, renderImageData.AlgorithmVersion) w.renderProperty.renderImageTaskCtlChan <- renderImageControlChanItem{ Option: 1, //0删除 1添加 Key: key, diff --git a/server/websocket/internal/types/types.go b/server/websocket/internal/types/types.go index 01801c85..c8aa0da8 100644 --- a/server/websocket/internal/types/types.go +++ b/server/websocket/internal/types/types.go @@ -11,14 +11,16 @@ type DataTransferData struct { } type RenderImageReqMsg struct { - ProductIds []int64 `json:"product_ids"` //产品 id - TemplateTagId int64 `json:"template_tag_id"` //模板标签id + ProductIds []int64 `json:"product_ids"` //产品 id + TemplateTagId int64 `json:"template_tag_id"` //模板标签id + AlgorithmVersion string `json:"algorithm_version,optional"` //算法版本 } type RenderImageRspMsg struct { - ProductId int64 `json:"product_id"` //产品 id - TemplateTagId int64 `json:"template_tag_id"` //模板标签id - Image string `json:"image"` //渲染后的图片 + ProductId int64 `json:"product_id"` //产品 id + TemplateTagId int64 `json:"template_tag_id"` //模板标签id + AlgorithmVersion string `json:"algorithm_version,optional"` //算法版本 + Image string `json:"image"` //渲染后的图片 } type RenderNotifyReq struct { @@ -28,9 +30,10 @@ type RenderNotifyReq struct { } type NotifyInfo struct { - ProductId int64 `json:"product_id"` - TemplateTagId int64 `json:"template_tag_id"` //模板标签id - Image string `json:"image"` + ProductId int64 `json:"product_id"` //产品id + TemplateTagId int64 `json:"template_tag_id"` //模板标签id + AlgorithmVersion string `json:"algorithm_version,optional"` //算法版本 + Image string `json:"image"` } type Request struct { diff --git a/server_api/websocket.api b/server_api/websocket.api index 2b46d61f..c2dc6430 100644 --- a/server_api/websocket.api +++ b/server_api/websocket.api @@ -23,13 +23,15 @@ type DataTransferData { D interface{} `json:"d"` //传递的消息 } type RenderImageReqMsg { //websocket接受要云渲染处理的数据 - ProductIds []int64 `json:"product_ids"` //产品 id - TemplateTagId int64 `json:"template_tag_id"` //模板标签id + ProductIds []int64 `json:"product_ids"` //产品 id + TemplateTagId int64 `json:"template_tag_id"` //模板标签id + AlgorithmVersion string `json:"algorithm_version,optional"` //算法版本 } type RenderImageRspMsg { //websocket发送渲染完的数据 - ProductId int64 `json:"product_id"` //产品 id - TemplateTagId int64 `json:"template_tag_id"` //模板标签id - Image string `json:"image"` //渲染后的图片 + ProductId int64 `json:"product_id"` //产品 id + TemplateTagId int64 `json:"template_tag_id"` //模板标签id + AlgorithmVersion string `json:"algorithm_version,optional"` //算法版本 + Image string `json:"image"` //渲染后的图片 } //渲染完了通知接口 type RenderNotifyReq { @@ -38,7 +40,8 @@ type RenderNotifyReq { Info NotifyInfo `json:"info"` } type NotifyInfo { - ProductId int64 `json:"product_id"` - TemplateTagId int64 `json:"template_tag_id"` //模板标签id - Image string `json:"image"` + ProductId int64 `json:"product_id"` //产品id + TemplateTagId int64 `json:"template_tag_id"` //模板标签id + AlgorithmVersion string `json:"algorithm_version,optional"` //算法版本 + Image string `json:"image"` } \ No newline at end of file From 4eb37c3820a8f5255f7a008f6960382607d2287e Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Thu, 27 Jul 2023 16:14:27 +0800 Subject: [PATCH 66/68] fix --- constants/websocket.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/constants/websocket.go b/constants/websocket.go index 93648380..fcc6e372 100644 --- a/constants/websocket.go +++ b/constants/websocket.go @@ -14,5 +14,5 @@ const ( WEBSOCKET_ERR_DATA_FORMAT = "WEBSOCKET_ERR_DATA_FORMAT" ) -// 云渲染通知需要的签名字符串 +// 云渲染完成通知api需要的签名字符串 const RENDER_NOTIFY_SIGN_KEY = "fusen-render-notify-%s-%d" From 58c0580cad22fdfc2f9e3270f8e2d848ff788d4f Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Thu, 27 Jul 2023 16:27:42 +0800 Subject: [PATCH 67/68] fix --- constants/websocket.go | 1 + .../internal/logic/datatransferlogic.go | 22 ++++++++++-------- utils/id_generator/wesocket.go | 23 +++++++++++++++++++ 3 files changed, 36 insertions(+), 10 deletions(-) create mode 100644 utils/id_generator/wesocket.go diff --git a/constants/websocket.go b/constants/websocket.go index fcc6e372..7b4c9ca3 100644 --- a/constants/websocket.go +++ b/constants/websocket.go @@ -12,6 +12,7 @@ const ( WEBSOCKET_RENDER_IMAGE = "WEBSOCKET_RENDER_IMAGE" //数据格式错误 WEBSOCKET_ERR_DATA_FORMAT = "WEBSOCKET_ERR_DATA_FORMAT" + // ) // 云渲染完成通知api需要的签名字符串 diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 582624d1..1b25d9f8 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -7,7 +7,7 @@ import ( "fusenapi/constants" "fusenapi/server/websocket/internal/types" "fusenapi/utils/auth" - "github.com/google/uuid" + "fusenapi/utils/id_generator" "github.com/gorilla/websocket" "net/http" "sync" @@ -34,6 +34,8 @@ func NewDataTransferLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Data } var ( + //全局websocketid生成器 + websocketIdGenerator = id_generator.NewWebsocketId(1) //临时缓存对象池 buffPool = sync.Pool{ New: func() interface{} { @@ -61,7 +63,7 @@ type wsConnectItem struct { conn *websocket.Conn //websocket的连接 closeChan chan struct{} //ws连接关闭chan isClose bool //是否已经关闭 - flag string //ws连接唯一标识 + uniqueId uint64 //ws连接唯一标识 inChan chan []byte //接受消息缓冲通道 outChan chan []byte //发送回客户端的消息 mutex sync.Mutex //互斥锁 @@ -91,10 +93,10 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp return }*/ //生成连接唯一标识 - flag := uuid.New().String() + "time=" + time.Now().Format("15-04-05") + uniqueId := websocketIdGenerator.Get() ws := wsConnectItem{ conn: conn, - flag: flag, + uniqueId: uniqueId, closeChan: make(chan struct{}, 1), inChan: make(chan []byte, 100), outChan: make(chan []byte, 100), @@ -104,12 +106,12 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp }, } //保存连接 - mapConnPool.Store(flag, ws) + mapConnPool.Store(uniqueId, ws) defer ws.close() //把连接成功消息发回去 time.Sleep(time.Second) //兼容下火狐 rsp.T = constants.WEBSOCKET_CONNECT_SUCCESS - rsp.D = flag + rsp.D = uniqueId b, _ := json.Marshal(rsp) _ = conn.WriteMessage(websocket.TextMessage, b) //循环读客户端信息 @@ -155,7 +157,7 @@ func (w *wsConnectItem) heartbeat() { case <-tick: //发送心跳信息 if err := w.conn.WriteMessage(websocket.PongMessage, nil); err != nil { - logx.Error("发送心跳信息异常,关闭连接:", w.flag, err) + logx.Error("发送心跳信息异常,关闭连接:", w.uniqueId, err) w.close() return } @@ -167,16 +169,16 @@ func (w *wsConnectItem) heartbeat() { func (w *wsConnectItem) close() { w.mutex.Lock() defer w.mutex.Unlock() - logx.Info("websocket:", w.flag, " is closing...") + logx.Info("websocket:", w.uniqueId, " is closing...") //发送关闭信息 _ = w.conn.WriteMessage(websocket.CloseMessage, nil) w.conn.Close() - mapConnPool.Delete(w.flag) + mapConnPool.Delete(w.uniqueId) if !w.isClose { w.isClose = true close(w.closeChan) } - logx.Info("websocket:", w.flag, " is closed") + logx.Info("websocket:", w.uniqueId, " is closed") } // 读取输出返回给客户端 diff --git a/utils/id_generator/wesocket.go b/utils/id_generator/wesocket.go new file mode 100644 index 00000000..62f21adf --- /dev/null +++ b/utils/id_generator/wesocket.go @@ -0,0 +1,23 @@ +package id_generator + +import "sync" + +type WebsocketId struct { + nodeId uint64 + count uint64 + mu sync.Mutex +} + +func (wid *WebsocketId) Get() uint64 { + wid.mu.Lock() + defer wid.mu.Unlock() + wid.count++ + return (wid.count << 8) | wid.nodeId +} + +func NewWebsocketId(NodeId uint8) *WebsocketId { + return &WebsocketId{ + nodeId: uint64(NodeId), + count: 0, + } +} From d843fff73d7ba5d4e14a5d86281d5166f04cb303 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Thu, 27 Jul 2023 16:29:09 +0800 Subject: [PATCH 68/68] fix --- server/websocket/internal/logic/datatransferlogic.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 1b25d9f8..999bd381 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -54,7 +54,7 @@ var ( WriteBufferPool: &buffPool, EnableCompression: true, } - //连接map池 + //websocket连接存储 mapConnPool = sync.Map{} )