28b95a6468
后端 - 每日任务惰性生成:某天为空则从最近一天顺延复制(done 重置),首天用模板 - 任务增删改 API(POST /pets/:id/tasks、PUT/DELETE /tasks/:id),改动自动顺延 - 30 天计划到期自动归档并按当前阶段生成新一轮 - 内置养护模板重写为兽医常识向:狗每阶段含遛狗/牵引/狂犬,猫含猫砂/梳毛/饮水 - 文件 URL 改为按 object_name + 当前配置动态拼接,换 IP/域名不再有旧地址 小程序 - 首页今日任务加「管理」入口:增删改任务弹层 - 记录时间轴显示照片缩略图(可全屏预览)+ 拍照成功提示 - 社区发布条精简为单个「发布图文」按钮,去掉头像/输入框误触 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
90 lines
2.4 KiB
Go
90 lines
2.4 KiB
Go
package service
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/md5"
|
|
"encoding/hex"
|
|
"errors"
|
|
"io"
|
|
"path"
|
|
"strings"
|
|
|
|
"github.com/sundynix/pets-be/internal/model"
|
|
)
|
|
|
|
// 允许的图片扩展名(服务端兜底校验,前端已限制仅图片)
|
|
var imageExts = map[string]bool{
|
|
".jpg": true, ".jpeg": true, ".png": true, ".gif": true,
|
|
".webp": true, ".bmp": true, ".heic": true, ".heif": true,
|
|
}
|
|
|
|
// UploadFile 上传文件并按 MD5 去重:内容相同直接返回已存记录,不重复占用 MinIO 空间。
|
|
func (s *Service) UploadFile(reader io.Reader, filename, contentType string) (*model.File, error) {
|
|
data, err := io.ReadAll(reader)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
sum := md5.Sum(data)
|
|
md5hex := hex.EncodeToString(sum[:])
|
|
|
|
// 已有相同内容 → 直接复用(URL 按当前配置重建,避免旧地址)
|
|
var existing model.File
|
|
if err := s.db.Where("md5 = ?", md5hex).First(&existing).Error; err == nil {
|
|
existing.URL = s.storage.PublicURL(existing.ObjectName)
|
|
return &existing, nil
|
|
}
|
|
|
|
ext := strings.ToLower(path.Ext(filename))
|
|
if !imageExts[ext] && !strings.HasPrefix(contentType, "image/") {
|
|
return nil, errors.New("只允许上传图片文件")
|
|
}
|
|
if contentType == "" {
|
|
contentType = "application/octet-stream"
|
|
}
|
|
objectName := "files/" + md5hex + ext
|
|
url, err := s.storage.Upload(objectName, bytes.NewReader(data), int64(len(data)), contentType)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
f := model.File{
|
|
MD5: md5hex, ObjectName: objectName, URL: url,
|
|
Size: int64(len(data)), ContentType: contentType, Ext: ext,
|
|
}
|
|
if err := s.db.Create(&f).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &f, nil
|
|
}
|
|
|
|
// fileURL 按 file_id 取 URL(由 object_name + 当前配置拼出,空 id 或不存在返回空串)
|
|
func (s *Service) fileURL(id string) string {
|
|
if id == "" {
|
|
return ""
|
|
}
|
|
var f model.File
|
|
if err := s.db.Select("object_name").First(&f, "id = ?", id).Error; err != nil {
|
|
return ""
|
|
}
|
|
return s.storage.PublicURL(f.ObjectName)
|
|
}
|
|
|
|
// fileURLs 批量按 file_id 取 URL
|
|
func (s *Service) fileURLs(ids []string) map[string]string {
|
|
out := map[string]string{}
|
|
clean := make([]string, 0, len(ids))
|
|
for _, id := range ids {
|
|
if id != "" {
|
|
clean = append(clean, id)
|
|
}
|
|
}
|
|
if len(clean) == 0 {
|
|
return out
|
|
}
|
|
var files []model.File
|
|
s.db.Select("id, object_name").Where("id IN ?", clean).Find(&files)
|
|
for _, f := range files {
|
|
out[f.ID] = s.storage.PublicURL(f.ObjectName)
|
|
}
|
|
return out
|
|
}
|