fusenapi/service/repositories/image_handle.go
2023-08-18 18:41:51 +08:00

347 lines
9.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 repositories
import (
"context"
"encoding/json"
"errors"
"fmt"
"fusenapi/constants"
"fusenapi/model/gmodel"
"fusenapi/utils/curl"
"fusenapi/utils/file"
"fusenapi/utils/hash"
"io"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/zeromicro/go-zero/core/logx"
"gorm.io/gorm"
)
func NewImageHandle(gormDB *gorm.DB, bLMServiceUrl *string, awsSession *session.Session) ImageHandle {
return &defaultImageHandle{
MysqlConn: gormDB,
BLMServiceUrl: bLMServiceUrl,
AwsSession: awsSession,
}
}
type (
defaultImageHandle struct {
MysqlConn *gorm.DB
BLMServiceUrl *string
AwsSession *session.Session
}
ImageHandle = interface {
// logo合图
LogoCombine(ctx context.Context, in *LogoCombineReq) (*LogoCombineRes, error)
// logo裁剪
LogoStandard(ctx context.Context, in *LogoStandardReq) (*LogoStandardRes, error)
}
)
/* logo合图 */
type (
LogoCombineReq struct {
UserId int64 `json:"user_id"`
GuestId int64 `json:"guest_id"`
TemplateId int64 `json:"template_id"`
TemplateTag string `json:"template_tag"`
Website string `json:"website"` // 合图参数
Slogan string `json:"slogan"` // 合图参数
Address string `json:"address"` // 合图参数
Phone string `json:"phone"` // 合图参数
Qrcode string `json:"qrcode"` // 合图参数
LogoUrl string `json:"logo_url"` // 合图参数
}
LogoCombineRes struct {
ResourceId string
ResourceUrl *string
Metadata *string
}
)
func (l *defaultImageHandle) LogoCombine(ctx context.Context, in *LogoCombineReq) (*LogoCombineRes, error) {
// 查询logo最新基础信息
var metadata *string
userMaterialModel := gmodel.NewFsUserMaterialModel(l.MysqlConn)
userMaterialInfo, err := userMaterialModel.FindLatestOne(ctx, in.UserId, in.GuestId)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
userMaterialInfoDefault, err := userMaterialModel.FindOneById(ctx, 0)
if err != nil {
logx.Error(err)
return nil, err
}
metadata = userMaterialInfoDefault.Metadata
} else {
logx.Error(err)
return nil, err
}
} else {
metadata = userMaterialInfo.Metadata
}
// 根据hash 查询数据资源
var hashKeyData = *in
hashKeyData.GuestId = 0
hashKeyData.UserId = 0
hashKeyData.LogoUrl = *userMaterialInfo.ResourceUrl
var resourceId string = hash.JsonHashKey(hashKeyData)
resourceModel := gmodel.NewFsResourceModel(l.MysqlConn)
resourceInfo, err := resourceModel.FindOneById(ctx, resourceId)
if err == nil && resourceInfo.ResourceId != "" {
return &LogoCombineRes{
ResourceId: resourceId,
ResourceUrl: resourceInfo.ResourceUrl,
}, nil
} else {
if err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
logx.Error(err)
return nil, err
}
}
}
// 没有查到先根据模版id 查询模版数据 请求算法数据
productTemplateV2Model := gmodel.NewFsProductTemplateV2Model(l.MysqlConn)
productTemplateV2Info, err := productTemplateV2Model.FindOne(ctx, in.TemplateId)
if err != nil {
logx.Error(err)
return nil, err
}
var groupOptions map[string]interface{}
var materialList []interface{}
if productTemplateV2Info.TemplateInfo != nil {
var templateInfo map[string]interface{}
err = json.Unmarshal([]byte(*productTemplateV2Info.TemplateInfo), &templateInfo)
if err != nil {
logx.Error(err)
return nil, err
}
materialList = templateInfo["materialList"].([]interface{})
groupOptions = templateInfo["groupOptions"].(map[string]interface{})
}
fmt.Println("合图开始时间:", time.Now())
var moduleDataMap = make(map[string]interface{}, 4)
moduleDataMap["id"] = productTemplateV2Info.Id
moduleDataMap["material"] = productTemplateV2Info.MaterialImg
moduleDataMap["groupOptions"] = groupOptions
moduleDataMap["materialList"] = materialList
var combineParam map[string]interface{}
json.Unmarshal([]byte(*metadata), &combineParam)
combineParam["template_tagid"] = in.TemplateTag
combineParam["website"] = in.Website
combineParam["slogan"] = in.Slogan
combineParam["phone"] = in.Phone
combineParam["address"] = in.Address
combineParam["qrcode"] = in.Qrcode
var postMap = make(map[string]interface{}, 2)
fmt.Println(combineParam)
postMap["module_data"] = moduleDataMap
postMap["param_data"] = combineParam
postMapB, _ := json.Marshal(postMap)
var headerData = make(map[string]string, 1)
headerData["Content-Type"] = "application/json"
result, err := curl.ApiCall(*l.BLMServiceUrl+constants.BLMServiceUrlLogoCombine, "POST", headerData, strings.NewReader(string(postMapB)), time.Minute*5)
if err != nil {
logx.Error(err)
return nil, err
}
defer result.Body.Close()
b, err := io.ReadAll(result.Body)
if err != nil {
logx.Error(err)
return nil, err
}
var resultStr string
if string(b) == "Internal Server Error" {
err = errors.New("BLMService fail Internal Server Error")
logx.Error(err)
return nil, err
} else {
var resData map[string]interface{}
err = json.Unmarshal(b, &resData)
if err != nil || resData == nil {
logx.Error(err)
return nil, err
}
if resData != nil {
if resData["code"].(string) == "200" {
resultStr = resData["data"].(string)
} else {
logx.Error(err)
return nil, err
}
} else {
logx.Error(err)
return nil, err
}
}
var resultData map[string]interface{}
err = json.Unmarshal([]byte(resultStr), &resultData)
if err != nil || resultData == nil {
logx.Error(err)
return nil, err
}
fmt.Println("合图结束时间:", time.Now())
// {
// id: "",
// logo_url:"https://s3.amazon.com/xxxx"
// result: "$saa541afaldjaldjasldjsadjsapsaasda"
// }
var fileBase = resultData["result"].(string)
// 上传文件
var upload = file.Upload{
Ctx: ctx,
MysqlConn: l.MysqlConn,
AwsSession: l.AwsSession,
}
uploadRes, err := upload.UploadFileByBase64(&file.UploadBaseReq{
Source: "combine-image",
FileHash: resourceId,
FileData: fileBase,
UploadBucket: 1,
ApiType: 2,
UserId: in.UserId,
GuestId: in.GuestId,
})
if err != nil {
logx.Error(err)
return nil, err
}
return &LogoCombineRes{
ResourceId: uploadRes.ResourceId,
ResourceUrl: &uploadRes.ResourceUrl,
}, nil
}
/* logo合图 */
type (
LogoStandardReq struct {
IsRemoveBg string `json:"is_remove_bg"`
LogoFile string `json:"logo_file"`
Width string `json:"width"`
Height string `json:"height"`
Proportion int64 `json:"proportion"`
}
LogoStandardRes struct {
ResourceId string
ResourceUrl string
IsmaxProportion bool
ImgColor []string
}
)
/* 图片裁剪 */
func (l *defaultImageHandle) LogoStandard(ctx context.Context, in *LogoStandardReq) (*LogoStandardRes, error) {
var resourceId string = hash.JsonHashKey(in)
var postMap = make(map[string]interface{}, 5)
postMap["is_remove_bg"] = in.IsRemoveBg
postMap["logo_file"] = in.LogoFile
postMap["width"] = in.Width
postMap["height"] = in.Height
postMap["proportion"] = in.Proportion
postMapB, _ := json.Marshal(postMap)
var headerData = make(map[string]string, 1)
headerData["Content-Type"] = "application/json"
result, err := curl.ApiCall(*l.BLMServiceUrl+constants.BLMServiceUrlLogoRemovebg, "POST", headerData, strings.NewReader(string(postMapB)), time.Minute*5)
if err != nil {
logx.Error(err)
return nil, err
}
defer result.Body.Close()
b, err := io.ReadAll(result.Body)
if err != nil {
logx.Error(err)
return nil, err
}
var resultStr string
if string(b) == "Internal Server Error" {
err = errors.New("BLMService fail Internal Server Error")
logx.Error(err)
return nil, err
} else {
var resData map[string]interface{}
err = json.Unmarshal(b, &resData)
if err != nil || resData == nil {
logx.Error(err)
return nil, err
}
if resData != nil {
if resData["code"].(string) == "200" {
resultStr = resData["data"].(string)
} else {
logx.Error(err)
return nil, err
}
} else {
logx.Error(err)
return nil, err
}
}
var resultData map[string]interface{}
err = json.Unmarshal([]byte(resultStr), &resultData)
if err != nil || resultData == nil {
logx.Error(err)
return nil, err
}
//$removeBg ='{"nobg_url": "/test/dIE10gGfXM_scale.png", "thumbnail_url": "/test/dIE10gGfXM_thumbnail.png", "ismax_proportion": true, "img_color": ["#000000", "#EEF5FB", "#6AAFE6", "#9ECDF1", "#298EDC", "#0C7BD1"]}'
var fileBase = resultData["nobg_url"].(string)
var ismaxProportion = resultData["ismax_proportion"].(bool)
var imgColor []string
for _, v := range resultData["img_color"].([]interface{}) {
imgColor = append(imgColor, v.(string))
}
// 上传文件
var upload = file.Upload{
Ctx: ctx,
MysqlConn: l.MysqlConn,
AwsSession: l.AwsSession,
}
uploadRes, err := upload.UploadFileByBase64(&file.UploadBaseReq{
Source: "combine-removebg",
FileHash: resourceId,
FileData: fileBase,
UploadBucket: 1,
ApiType: 2,
})
if err != nil {
logx.Error(err)
return nil, err
}
return &LogoStandardRes{
ResourceId: uploadRes.ResourceId,
ResourceUrl: uploadRes.ResourceUrl,
IsmaxProportion: ismaxProportion,
ImgColor: imgColor,
}, nil
}
/* 图片裁剪 */