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

This commit is contained in:
eson 2023-08-24 11:47:39 +08:00
commit bcd79f828c
14 changed files with 153 additions and 75 deletions

View File

@ -91,6 +91,9 @@ func (l *UploadFileBackendLogic) UploadFileBackend(req *types.UploadFileBackendR
UserId: userId,
GuestId: guestId,
Source: req.Source,
Metadata: req.Metadata,
Refresh: req.Refresh,
ResourceId: req.ResourceId,
})
if err != nil {

View File

@ -40,6 +40,8 @@ type UploadFileBackendReq struct {
FileSize int64 `form:"file_size,optional"` // 上传唯一标识信息
Metadata string `form:"meta_data,optional"` // 上传文件额外信息
Source string `form:"source"` // 上传来源
Refresh int64 `form:"refresh,optional"` // 强制更新 10
ResourceId string `form:"resource_id,optional"` // 资源ID
}
type UploadFilesReq struct {
@ -47,6 +49,8 @@ type UploadFilesReq struct {
UploadBucket int64 `form:"upload_bucket,options=[1,2],default=1"` // 上传桶名:1=缓存,2=持久
UploadInfo string `form:"upload_info"` // 上传信息 json
Source string `form:"source"` // 上传来源
Refresh int64 `form:"refresh,optional"` // 强制更新 10
ResourceId string `form:"resource_id,optional"` // 资源ID
}
type UploadCallbackReq struct {

View File

@ -84,16 +84,18 @@ type wsConnectItem struct {
func (l *DataTransferLogic) DataTransfer(w http.ResponseWriter, r *http.Request) {
//把子协议携带的token设置到标准token头信息中
token := r.Header.Get("Sec-Websocket-Protocol")
r.Header.Set("Authorization", "Bearer "+token)
//设置Sec-Websocket-Protocol
upgrader.Subprotocols = []string{token}
//有token是正常用户无则是白板用户也可以连接
if token != "" {
r.Header.Set("Authorization", "Bearer "+token)
//设置Sec-Websocket-Protocol
upgrader.Subprotocols = []string{token}
}
//升级websocket
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logx.Error("http upgrade websocket err:", err)
return
}
defer conn.Close()
//鉴权不成功后断开
var (
userInfo *auth.UserInfo
@ -103,11 +105,13 @@ func (l *DataTransferLogic) DataTransfer(w http.ResponseWriter, r *http.Request)
if !isAuth {
//未授权响应消息
l.unAuthResponse(conn)
conn.Close()
return
}
//设置连接
ws, err := l.setConnPool(conn, *userInfo)
if err != nil {
conn.Close()
return
}
defer ws.close()
@ -201,13 +205,10 @@ func (l *DataTransferLogic) checkAuth(r *http.Request) (isAuth bool, userInfo *a
logx.Error(err)
return false, nil
}
//不是登录用户也不是游客
if !userInfo.IsUser() && !userInfo.IsGuest() {
return false, nil
}
return true, userInfo
}
return false, nil
//白板用户
return true, &auth.UserInfo{}
}
// 鉴权失败通知
@ -249,7 +250,6 @@ func (w *wsConnectItem) heartbeat() {
//发送心跳信息
if err := w.conn.WriteMessage(websocket.PongMessage, nil); err != nil {
logx.Error("发送心跳信息异常,关闭连接:", w.uniqueId, err)
w.close()
return
}
}

View File

@ -2,9 +2,13 @@ package logic
//登录回调
import (
"encoding/json"
"fusenapi/constants"
"fusenapi/server/websocket/internal/websocket_data"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"fusenapi/utils/encryption_decryption"
"time"
"context"
@ -33,20 +37,43 @@ func NewLoginNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Login
// }
func (l *LoginNotifyLogic) LoginNotify(req *types.LoginNotifyReq, userinfo *auth.UserInfo) (resp *basic.Response) {
if req.Data.WebsocketConnId == "" {
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "参数错误,连接标识不能为空")
if req.Data == "" {
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "data is empty")
}
value, ok := mapConnPool.Load(req.Data.WebsocketConnId)
//解密数据
data, err := encryption_decryption.CBCDecrypt(req.Data)
if err != nil {
logx.Error("解密失败:", err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "invalid data ")
}
//真正的数据结构
var parseInfo websocket_data.NotifyData
if err = json.Unmarshal([]byte(data), &parseInfo); err != nil {
logx.Error("failed to parse json data:", err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "invalid format of parse data")
}
//websocket连接id不能为空
if parseInfo.WebsocketConnectId == "" {
return resp.SetStatusWithMessage(basic.CodeServiceErr, "websocket connect id is empty")
}
now := time.Now().UTC().Unix()
//请求时间前后20秒都会失效
if parseInfo.RequestTime < now-20 || parseInfo.RequestTime > now+20 {
return resp.SetStatusWithMessage(basic.CodeServiceErr, "invalid data ,time is not in allowed range")
}
//查询websocket连接
value, ok := mapConnPool.Load(parseInfo.WebsocketConnectId)
if !ok {
return resp.SetStatusWithMessage(basic.CodeOK, "success,but connection is not found")
}
//断言连接
ws, ok := value.(wsConnectItem)
if !ok {
logx.Error("渲染回调断言websocket连接失败")
return resp.SetStatusWithMessage(basic.CodeServiceErr, "断言连接错误")
}
//发送消息到出口缓冲池
ws.sendToOutChan(ws.respondDataFormat(constants.WEBSOCKET_LOGIN_NOTIFY, req.Data.Info))
ws.sendToOutChan(ws.respondDataFormat(constants.WEBSOCKET_LOGIN_NOTIFY, parseInfo.Data))
return resp.SetStatusWithMessage(basic.CodeOK, "success")
}

View File

@ -2,9 +2,13 @@ package logic
//注册帐号回调
import (
"encoding/json"
"fusenapi/constants"
"fusenapi/server/websocket/internal/websocket_data"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"fusenapi/utils/encryption_decryption"
"time"
"context"
@ -33,20 +37,43 @@ func NewRegisterAccountNotifyLogic(ctx context.Context, svcCtx *svc.ServiceConte
// }
func (l *RegisterAccountNotifyLogic) RegisterAccountNotify(req *types.RegisterAccountNotifyReq, userinfo *auth.UserInfo) (resp *basic.Response) {
if req.Data.WebsocketConnId == "" {
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "参数错误,连接标识不能为空")
if req.Data == "" {
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "data is empty")
}
value, ok := mapConnPool.Load(req.Data.WebsocketConnId)
//解密数据
data, err := encryption_decryption.CBCDecrypt(req.Data)
if err != nil {
logx.Error("解密失败:", err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "invalid data ")
}
//真正的数据结构
var parseInfo websocket_data.NotifyData
if err = json.Unmarshal([]byte(data), &parseInfo); err != nil {
logx.Error("failed to parse json data:", err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "invalid format of parse data")
}
//websocket连接id不能为空
if parseInfo.WebsocketConnectId == "" {
return resp.SetStatusWithMessage(basic.CodeServiceErr, "websocket connect id is empty")
}
now := time.Now().UTC().Unix()
//请求时间前后20秒都会失效
if parseInfo.RequestTime < now-20 || parseInfo.RequestTime > now+20 {
return resp.SetStatusWithMessage(basic.CodeServiceErr, "invalid data ,time is not in allowed range")
}
//查询websocket连接
value, ok := mapConnPool.Load(parseInfo.WebsocketConnectId)
if !ok {
return resp.SetStatusWithMessage(basic.CodeOK, "success,but connection is not found")
}
//断言连接
ws, ok := value.(wsConnectItem)
if !ok {
logx.Error("渲染回调断言websocket连接失败")
return resp.SetStatusWithMessage(basic.CodeServiceErr, "断言连接错误")
}
//发送消息到出口缓冲池
ws.sendToOutChan(ws.respondDataFormat(constants.WEBSOCKET_REGISTER_NOTIFY, req.Data.Info))
ws.sendToOutChan(ws.respondDataFormat(constants.WEBSOCKET_REGISTER_NOTIFY, parseInfo.Data))
return resp.SetStatusWithMessage(basic.CodeOK, "success")
}

View File

@ -88,7 +88,7 @@ func (l *RenderNotifyLogic) RenderNotify(req *types.RenderNotifyReq, userinfo *a
})
//发送处理并删除任务
ws.deleteRenderTask(renderImageControlChanItem{
Option: 0, //0删除 1添加
Option: 0, //0删除 1添加 2修改耗时属性
TaskId: req.TaskId,
RenderNotifyImageUrl: uploadRes.ResourceUrl,
})

View File

@ -154,7 +154,7 @@ func (w *wsConnectItem) consumeRenderCache(data []byte) {
//###########################################
//把需要渲染的图片任务加进去
w.createRenderTask(renderImageControlChanItem{
Option: 1, //0删除 1添加
Option: 1, //0删除 1添加 2修改耗时属性
TaskId: taskId,
RenderId: renderImageData.RenderId,
})

View File

@ -67,5 +67,5 @@ func (w *wsConnectItem) reuseLastConnect(data []byte) {
// 获取用户拼接部分(复用标识用到)
func getUserJoinPart(userId, guestId int64) string {
return fmt.Sprintf("|%d_%d", userId, guestId)
return fmt.Sprintf("|_%d_%d_|", userId, guestId)
}

View File

@ -13,25 +13,11 @@ type RenderNotifyReq struct {
}
type RegisterAccountNotifyReq struct {
Data RegisterAccountData `json:"data"`
Time int64 `json:"time,optional"` //utc时间戳(用于验证签名)
Sign string `json:"sign,optional"` //签名
}
type RegisterAccountData struct {
WebsocketConnId string `json:"websocket_conn_id"` //连接标识
Info map[string]interface{} `json:"info"`
Data string `json:"data"` //aes_cbc加密密文
}
type LoginNotifyReq struct {
Data LoginNotifyData `json:"data"`
Time int64 `json:"time,optional"` //utc时间戳(用于验证签名)
Sign string `json:"sign,optional"` //签名
}
type LoginNotifyData struct {
WebsocketConnId string `json:"websocket_conn_id"` //连接标识
Info map[string]interface{} `json:"info"`
Data string `json:"data"` //aes_cbc加密密文
}
type Request struct {

View File

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

View File

@ -89,6 +89,8 @@ type (
FileSize int64 `form:"file_size,optional"` // 上传唯一标识信息
Metadata string `form:"meta_data,optional"` // 上传文件额外信息
Source string `form:"source"` // 上传来源
Refresh int64 `form:"refresh,optional"` // 强制更新 10
ResourceId string `form:"resource_id,optional"` // 资源ID
}
UploadFilesReq {
@ -96,6 +98,8 @@ type (
UploadBucket int64 `form:"upload_bucket,options=[1,2],default=1"` // 上传桶名:1=缓存,2=持久
UploadInfo string `form:"upload_info"` // 上传信息 json
Source string `form:"source"` // 上传来源
Refresh int64 `form:"refresh,optional"` // 强制更新 10
ResourceId string `form:"resource_id,optional"` // 资源ID
}
UploadCallbackReq {
UploadBucket int64 `form:"upload_bucket,options=[1,2],default=1"` // 上传桶名:1=缓存,2=持久

View File

@ -32,21 +32,9 @@ type RenderNotifyReq {
}
//注册回调
type RegisterAccountNotifyReq {
Data RegisterAccountData `json:"data"`
Time int64 `json:"time,optional"` //utc时间戳(用于验证签名)
Sign string `json:"sign,optional"` //签名
}
type RegisterAccountData {
WebsocketConnId string `json:"websocket_conn_id"` //连接标识
Info map[string]interface{} `json:"info"`
Data string `json:"data"` //aes_cbc加密密文
}
//登录回调
type LoginNotifyReq {
Data LoginNotifyData `json:"data"`
Time int64 `json:"time,optional"` //utc时间戳(用于验证签名)
Sign string `json:"sign,optional"` //签名
}
type LoginNotifyData {
WebsocketConnId string `json:"websocket_conn_id"` //连接标识
Info map[string]interface{} `json:"info"`
Data string `json:"data"` //aes_cbc加密密文
}

View File

@ -65,7 +65,7 @@ type (
// PostJson请求
func (c *defaultClient) PostJson(jsonData interface{}, res interface{}) error {
logc.Infof(c.ctx, "客户端名称 Client PostJson jsonData:%+v", jsonData)
//logc.Infof(c.ctx, "客户端名称 Client PostJson jsonData:%+v", jsonData)
logc.Infof(c.ctx, "客户端名称 请求开始时间:%+v", time.Now().UTC())
resp, err := c.client.

View File

@ -70,12 +70,14 @@ func (upload *Upload) UploadFileByBase64(req *UploadBaseReq) (*UploadBaseRes, er
var uploadBaseRes = UploadBaseRes{}
// 是否强制刷新
var refresh bool
if req.ResourceId != "" {
refresh = true
resourceId = req.ResourceId
}
if req.Refresh == 1 {
refresh = true
}
err := upload.MysqlConn.Transaction(func(tx *gorm.DB) (err error) {
var resourceInfo *gmodel.FsResource
@ -198,15 +200,28 @@ func (upload *Upload) UploadFileByByte(req *UploadBaseReq) (*UploadBaseRes, erro
var uploadBaseRes = UploadBaseRes{}
err := upload.MysqlConn.Transaction(func(tx *gorm.DB) error {
// 是否强制刷新
var refresh bool
if req.ResourceId != "" {
resourceId = req.ResourceId
}
if req.Refresh == 1 {
refresh = true
}
err := upload.MysqlConn.Transaction(func(tx *gorm.DB) (err error) {
var resourceInfo *gmodel.FsResource
err := tx.Where("resource_id =?", resourceId).Take(&resourceInfo).Error
// resourceInfo, err := resourceModelTS.FindOneById(ctx, resourceId)
if err == nil && resourceInfo.ResourceId != "" {
uploadBaseRes.Status = 1
uploadBaseRes.ResourceId = resourceId
uploadBaseRes.ResourceUrl = *resourceInfo.ResourceUrl
} else {
if !refresh {
err = tx.Where("resource_id =?", resourceId).Take(&resourceInfo).Error
if err == nil && resourceInfo.ResourceId != "" {
uploadBaseRes.Status = 1
uploadBaseRes.ResourceId = resourceId
uploadBaseRes.ResourceUrl = *resourceInfo.ResourceUrl
} else {
refresh = true
}
}
if refresh {
contentType := http.DetectContentType(req.FileByte)
// 创建S3对象存储请求
s3req, _ = svc.PutObjectRequest(
@ -235,19 +250,35 @@ func (upload *Upload) UploadFileByByte(req *UploadBaseReq) (*UploadBaseRes, erro
uploadBaseRes.ResourceUrl = url
var version string = "0.0.1"
var nowTime = time.Now().UTC()
err = tx.Create(&gmodel.FsResource{
ResourceId: resourceId,
UserId: &req.UserId,
GuestId: &req.GuestId,
ResourceType: &contentType,
ResourceUrl: &url,
Version: &version,
UploadedAt: &nowTime,
Metadata: &req.Metadata,
ApiType: &apiType,
BucketName: bucketName,
Source: &req.Source,
}).Error
if refresh {
err = tx.Save(&gmodel.FsResource{
ResourceId: resourceId,
UserId: &req.UserId,
GuestId: &req.GuestId,
ResourceType: &contentType,
ResourceUrl: &url,
Version: &version,
UploadedAt: &nowTime,
Metadata: &req.Metadata,
ApiType: &apiType,
BucketName: bucketName,
Source: &req.Source,
}).Error
} else {
err = tx.Create(&gmodel.FsResource{
ResourceId: resourceId,
UserId: &req.UserId,
GuestId: &req.GuestId,
ResourceType: &contentType,
ResourceUrl: &url,
Version: &version,
UploadedAt: &nowTime,
Metadata: &req.Metadata,
ApiType: &apiType,
BucketName: bucketName,
Source: &req.Source,
}).Error
}
if err != nil {
logx.Errorf("err:%+vdesc:%+v", err, "fail.upload.resourceInfoAdd.mysql")
return err