service/library/mediafiller/mediafiller.go

114 lines
2.8 KiB
Go
Raw Normal View History

2023-12-21 22:17:40 +08:00
package mediafiller
import (
"service/dbstruct"
"service/library/logger"
"github.com/gin-gonic/gin"
)
var defaultMediaFiller *MediaFiller
type GetImageByIdsFunc func(ctx *gin.Context, ids []int64) ([]*dbstruct.Image, error)
type GetVideoByIdsFunc func(ctx *gin.Context, ids []int64) ([]*dbstruct.Video, error)
type MediaFiller struct {
fileServerDomainName string //文件服务器域名
getImageByIds GetImageByIdsFunc //获取图片数据源
getVideoByIds GetVideoByIdsFunc //获取视频数据源
}
func InitDefaultMediaFiller() {
defaultMediaFiller = &MediaFiller{}
}
func SetGetImageByIdsFunc(getImageByIdsFunc GetImageByIdsFunc) {
defaultMediaFiller.getImageByIds = getImageByIdsFunc
}
func SetGetVideoByIdsFunc(getVideoByIdsFunc GetVideoByIdsFunc) {
defaultMediaFiller.getVideoByIds = getVideoByIdsFunc
}
func SetFileServerDomainName(fileServerDomainName string) {
defaultMediaFiller.fileServerDomainName = fileServerDomainName
}
func FillEntity(ctx *gin.Context, entity MediaFillable) error {
imageIds := entity.GetImageIds()
videoIds := entity.GetVideoIds()
imageMap, err := getImageMapByIds(ctx, imageIds)
if err != nil {
logger.Error("mediafiller component getImageMapByIds failed : %v", err)
return err
}
videoMap, err := getVideoMapByIds(ctx, videoIds)
if err != nil {
logger.Error("mediafiller component getVideoMapByIds failed : %v", err)
return err
}
images := make([]*dbstruct.ToCImage, 0)
videos := make([]*dbstruct.ToCVideo, 0)
for _, imageId := range imageIds {
if image, ok := imageMap[imageId]; ok {
images = append(images, transToCImage(image))
}
}
for _, videoId := range videoIds {
if video, ok := videoMap[videoId]; ok {
videos = append(videos, transToCVideo(video))
}
}
entity.SetImages(images)
entity.SetVideos(videos)
return nil
}
func FillList(ctx *gin.Context, list []MediaFillable) error {
imageIds := make([]int64, 0)
videoIds := make([]int64, 0)
for _, v := range list {
imageIds = append(imageIds, v.GetImageIds()...)
videoIds = append(videoIds, v.GetVideoIds()...)
}
imageMap, err := getImageMapByIds(ctx, imageIds)
if err != nil {
logger.Error("mediafiller component getImageMapByIds failed : %v", err)
return err
}
videoMap, err := getVideoMapByIds(ctx, videoIds)
if err != nil {
logger.Error("mediafiller component getVideoMapByIds failed : %v", err)
return err
}
for _, v := range list {
images := make([]*dbstruct.ToCImage, 0)
videos := make([]*dbstruct.ToCVideo, 0)
for _, imageId := range v.GetImageIds() {
if image, ok := imageMap[imageId]; ok {
images = append(images, transToCImage(image))
}
}
for _, videoId := range v.GetVideoIds() {
if video, ok := videoMap[videoId]; ok {
videos = append(videos, transToCVideo(video))
}
}
v.SetImages(images)
v.SetVideos(videos)
}
return nil
}