Files
backend/internal/service/serialize_service.go

114 lines
2.7 KiB
Go
Raw Normal View History

package service
import (
"carrotskin/internal/model"
"carrotskin/pkg/redis"
"encoding/base64"
"time"
"go.uber.org/zap"
"gorm.io/gorm"
)
type Property struct {
Name string `json:"name"`
Value string `json:"value"`
Signature string `json:"signature,omitempty"`
}
func SerializeProfile(db *gorm.DB, logger *zap.Logger, redisClient *redis.Client, p model.Profile) map[string]interface{} {
var err error
// 创建基本材质数据
texturesMap := make(map[string]interface{})
textures := map[string]interface{}{
"timestamp": time.Now().UnixMilli(),
"profileId": p.UUID,
"profileName": p.Name,
"textures": texturesMap,
}
// 处理皮肤
if p.SkinID != nil {
skin, err := GetTextureByID(db, *p.SkinID)
if err != nil {
logger.Error("[ERROR] 获取皮肤失败:", zap.Error(err), zap.Any("SkinID:", *p.SkinID))
} else {
texturesMap["SKIN"] = map[string]interface{}{
"url": skin.URL,
"metadata": skin.Size,
}
}
}
// 处理披风
if p.CapeID != nil {
cape, err := GetTextureByID(db, *p.CapeID)
if err != nil {
logger.Error("[ERROR] 获取披风失败:", zap.Error(err), zap.Any("capeID:", *p.CapeID))
} else {
texturesMap["CAPE"] = map[string]interface{}{
"url": cape.URL,
"metadata": cape.Size,
}
}
}
// 将textures编码为base64
bytes, err := json.Marshal(textures)
if err != nil {
logger.Error("[ERROR] 序列化textures失败: ", zap.Error(err))
return nil
}
textureData := base64.StdEncoding.EncodeToString(bytes)
signature, err := SignStringWithSHA1withRSA(logger, redisClient, textureData)
if err != nil {
logger.Error("[ERROR] 签名textures失败: ", zap.Error(err))
return nil
}
// 构建结果
data := map[string]interface{}{
"id": p.UUID,
"name": p.Name,
"properties": []Property{
{
Name: "textures",
Value: textureData,
Signature: signature,
},
},
}
return data
}
func SerializeUser(logger *zap.Logger, u *model.User, UUID string) map[string]interface{} {
if u == nil {
logger.Error("[ERROR] 尝试序列化空用户")
return nil
}
data := map[string]interface{}{
"id": UUID,
}
// 正确处理 *datatypes.JSON 指针类型
// 如果 Properties 为 nil则设置为 nil否则解引用并解析为 JSON 值
if u.Properties == nil {
data["properties"] = nil
} else {
// datatypes.JSON 是 []byte 类型,需要解析为实际的 JSON 值
var propertiesValue interface{}
if err := json.Unmarshal(*u.Properties, &propertiesValue); err != nil {
logger.Warn("[WARN] 解析用户Properties失败使用空值", zap.Error(err))
data["properties"] = nil
} else {
data["properties"] = propertiesValue
}
}
return data
}