fusenapi/server/upload/internal/logic/uploadlogologic.go

224 lines
6.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package logic
import (
"fmt"
"fusenapi/model/gmodel"
"fusenapi/service/repositories"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"fusenapi/utils/file"
"fusenapi/utils/hash"
"io"
"net/http"
"time"
"context"
"fusenapi/server/upload/internal/svc"
"fusenapi/server/upload/internal/types"
"github.com/zeromicro/go-zero/core/logc"
"github.com/zeromicro/go-zero/core/logx"
"gorm.io/gorm"
)
type UploadLogoLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
r *http.Request
}
func NewUploadLogoLogic(r *http.Request, svcCtx *svc.ServiceContext) *UploadLogoLogic {
return &UploadLogoLogic{
Logger: logx.WithContext(r.Context()),
ctx: r.Context(),
svcCtx: svcCtx,
r: r,
}
}
// 处理进入前逻辑w,r
// func (l *UploadLogoLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *UploadLogoLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)
// }
func (l *UploadLogoLogic) UploadLogo(req *types.UploadLogoReq, userinfo *auth.UserInfo) (resp *basic.Response) {
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
// userinfo 传入值时, 一定不为null
if userinfo.IsOnlooker() {
// 如果是,返回未授权的错误码
return resp.SetStatus(basic.CodeUnAuth)
}
var userId int64
var guestId int64
// 检查用户是否是游客
if userinfo.IsGuest() {
// 如果是使用游客ID和游客键名格式
guestId = userinfo.GuestId
} else {
// 否则使用用户ID和用户键名格式
userId = userinfo.UserId
}
//设置内存大小
l.r.ParseMultipartForm(32 << 20)
fileObject, fileHeader, err := l.r.FormFile("file")
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeFileUploadErr, "file upload err,no files")
}
defer fileObject.Close()
// 获取文件的MIME类型
fileType := fileHeader.Header.Get("Content-Type")
var imageTypes = make(map[string]struct{}, 7)
imageTypes["image/jpg"] = struct{}{}
imageTypes["image/jpeg"] = struct{}{}
imageTypes["image/png"] = struct{}{}
imageTypes["image/gif"] = struct{}{}
imageTypes["image/bmp"] = struct{}{}
imageTypes["image/tiff"] = struct{}{}
imageTypes["image/webp"] = struct{}{}
imageTypes["image/svg+xml"] = struct{}{}
// 判断文件类型是否为图片
_, ok := imageTypes[fileType]
if !ok {
return resp.SetStatus(basic.CodeFileUploadErr, "file upload err,file is not image")
}
// 限制上传文件大小 50k
// maxSize := 100 * 1024
// if fileHeader.Size > int64(maxSize) {
// return resp.SetStatus(basic.CodeFileUploadErr, "file upload err,The file size exceeds the maximum limit of 100k")
// }
// 读取数据流
ioData, err := io.ReadAll(fileObject)
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeFileUploadErr, "file upload err,no files")
}
// 上传文件
var upload = file.Upload{
Ctx: l.ctx,
MysqlConn: l.svcCtx.MysqlConn,
AwsSession: l.svcCtx.AwsSession,
}
var resourceId string = hash.JsonHashKey(req.FileKey)
uploadRes, err := upload.UploadFileByByte(&file.UploadBaseReq{
FileHash: resourceId,
FileByte: ioData,
UploadBucket: 1,
ApiType: 2,
UserId: userId,
GuestId: guestId,
Source: "upload-logo",
})
var logoUrl string
// 是否去背景
if req.IsRemoveBg == 1 {
resLogoStandard, err := l.svcCtx.Repositories.ImageHandle.LogoStandard(l.ctx, &repositories.LogoStandardReq{
LogoFile: uploadRes.ResourceUrl,
IsRemoveBg: "true",
Width: "0",
Height: "0",
Proportion: "100",
})
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeServiceErr, fmt.Sprintf("算法请求--LOGO信息--错误:%+v", err))
}
logoUrl = resLogoStandard.ResourceUrl
} else {
logoUrl = uploadRes.ResourceUrl
}
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeFileUploadErr, "upload file failed")
}
var logoWidth int64
var logoHeight int64
// 查看sku是否存在
if req.SkuId > 0 {
// 查询出产品模板信息
productTemplateV2Model := gmodel.NewFsProductTemplateV2Model(l.svcCtx.MysqlConn)
productTemplateV2Info, err := productTemplateV2Model.FindOne(l.ctx, req.SkuId)
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeFileUploadLogoErr, "logo upload err,no product template")
}
logoWidth = *productTemplateV2Info.LogoWidth
logoHeight = *productTemplateV2Info.LogoHeight
}
// 设置默认宽高
if logoWidth == 0 || logoHeight == 0 {
logoWidth = 300
logoHeight = 200
}
var resultStr string
resLogoStandard, err := l.svcCtx.Repositories.ImageHandle.LogoInfoSet(l.ctx, &repositories.LogoInfoSetReq{
LogoUrl: logoUrl,
Version: l.svcCtx.Config.BLMService.Version,
})
if err != nil {
logx.Error(err)
basic.CodeServiceErr.Message = fmt.Sprintf("算法请求--LOGO信息--错误:%+v", err)
return resp.SetStatus(basic.CodeServiceErr, fmt.Sprintf("算法请求--LOGO信息--错误:%+v", err))
}
resultStr = resLogoStandard.Res
resultStrB := []byte(resultStr)
var module = "logo"
var nowTime = time.Now().UTC()
// 新增素材记录
materialInfo := gmodel.FsUserMaterial{
Module: &module,
UserId: &userId,
GuestId: &guestId,
ResourceId: &uploadRes.ResourceId,
ResourceUrl: &uploadRes.ResourceUrl,
Metadata: &resultStrB,
Ctime: &nowTime,
}
err = l.svcCtx.MysqlConn.WithContext(l.ctx).Transaction(func(tx *gorm.DB) error {
resCreate := tx.Create(&materialInfo)
err = resCreate.Error
if err != nil {
logc.Errorf(l.ctx, "FsUserInfo First err%+v", err)
return err
}
return nil
})
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeFileUploadLogoErr, "service fail")
}
// 返回成功的响应和上传URL
return resp.SetStatus(basic.CodeOK, map[string]interface{}{
"upload_data": UploadUrl{
Status: 1,
LogoId: materialInfo.Id,
ResourceId: uploadRes.ResourceId,
ResourceUrl: uploadRes.ResourceUrl,
},
})
}