blog/internal/service/diary_service.go

153 lines
3.7 KiB
Go
Raw Permalink 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 service
import (
"Blog/internal/client"
"Blog/internal/consts"
"Blog/internal/model"
"Blog/internal/repository"
"bytes"
"context"
"image/jpeg"
"mime/multipart"
"strings"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
)
var DiaryService *diaryService = newDiaryService()
type diaryService struct {
}
func newDiaryService() *diaryService {
// go initDiaryData()
return &diaryService{}
}
func (*diaryService) SaveDiary(content string, createBy string, fileHeaders []*multipart.FileHeader) *model.BlogDiary {
diaryId := uuid.NewString()
fileIds := []string{}
for i := range fileHeaders {
// defer file.Close()
header := fileHeaders[i]
data := compressImg(header)
fileName := header.Filename
extLastIndex := strings.LastIndex(fileName, ".")
ext := fileName[extLastIndex:]
// fileId := uuid.NewString()
uploadFile := FileService.SaveFile(fileName, data, createBy)
if uploadFile == nil {
logrus.Error("日记文件:", fileName, ",保存失败")
continue
}
fileId := uploadFile.Id
fileIds = append(fileIds, fileId+ext)
}
images := ""
if len(fileIds) > 0 {
images = strings.Join(fileIds, ",")
}
ctx := context.Background()
now := time.Now().UnixMilli()
cnt := model.BlogTextContent{
Id: uuid.NewString(),
RelId: diaryId,
Content: content,
State: consts.CONTENT_STATE_PUBLISH,
}
diary := model.BlogDiary{
Id: diaryId,
Images: images,
PublishTime: now,
Del: 0,
CreateTime: now,
CreateBy: createBy,
}
txErr := repository.DiaryRepository().WGorm(func(tx *gorm.DB) error {
err := tx.Table(consts.TABLE_BLOG_DIARY).Create(&diary).Error
if err != nil {
return err
}
err = tx.Table(consts.TABLE_BLOG_TEXT_CONTENT).Create(cnt).Error
if err != nil {
return err
}
// database.GormTemplate.Table(consts.TABLE_BLOG_DIARY).Where("id = ?", id).First(&diary)
return nil
})
if txErr != nil {
return nil
}
err := client.RedisClient().ZAdd(ctx, consts.REDIS_BLOG_DIARY_LATEST, redis.Z{Score: float64(diary.PublishTime), Member: &diary}).Err()
if err != nil {
logrus.Error("日记写入Redis失败,", err)
}
err = client.RedisClient().Set(ctx, consts.REDIS_BLOG_CONTENT+diaryId, content, time.Duration(0)).Err()
if err != nil {
logrus.Error("日记文本写入Redis失败", err)
}
return &diary
}
var compress int64 = 1 * 1024 * 1024
// 判断是否JPEG格式按大小进行压缩
func compressImg(fileHeader *multipart.FileHeader) []byte {
fileName := fileHeader.Filename
fileSize := fileHeader.Size
file, _ := fileHeader.Open()
if strings.HasSuffix(fileName, "jpg") || strings.HasSuffix(fileName, "jpeg") {
quality := 100
if fileSize > compress {
mul := fileSize / compress
if mul > 1 {
quality = 70
}
logrus.Info("JPG格式图片,判断是否压缩")
i, err := jpeg.Decode(file)
if err != nil {
return nil
}
var buf []byte
b := bytes.NewBuffer(buf)
jpeg.Encode(b, i, &jpeg.Options{Quality: quality})
return b.Bytes()
}
}
var bytes []byte = make([]byte, fileSize)
file.Read(bytes)
return bytes
}
func (*diaryService) RefreshLatest() {
var slices []model.BlogDiary = repository.DiaryRepository().FindList(nil)
logrus.Info("日记初始化数据加载量:", len(slices))
ctx := context.Background()
delErr := client.RedisClient().Del(ctx, consts.REDIS_BLOG_DIARY_LATEST).Err()
if delErr != nil {
logrus.Error("刷新最新日记失败,Err=>", delErr.Error())
return
}
for _, diary := range slices {
// logrus.Info(article)
publishTime := diary.PublishTime
err := client.RedisClient().ZAdd(ctx, consts.REDIS_BLOG_DIARY_LATEST, redis.Z{Score: float64(publishTime), Member: &diary}).Err()
if err != nil {
logrus.Info(err)
}
}
}