You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

110 lines
2.7 KiB

// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package file
import (
"context"
"fmt"
"strings"
"github.com/youruser/base/internal/svc"
"github.com/youruser/base/internal/types"
"github.com/youruser/base/model"
"github.com/zeromicro/go-zero/core/logx"
)
type UpdateFileLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// 更新文件信息
func NewUpdateFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateFileLogic {
return &UpdateFileLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *UpdateFileLogic) UpdateFile(req *types.UpdateFileRequest) (resp *types.FileInfo, err error) {
// Get userId and role from context
userId, _ := l.ctx.Value("userId").(int64)
if userId == 0 {
if num, ok := l.ctx.Value("userId").(interface{ Int64() (int64, error) }); ok {
userId, _ = num.Int64()
}
}
userRole, _ := l.ctx.Value("role").(string)
// Find file by ID
fileRecord, err := model.FileFindOne(l.ctx, l.svcCtx.DB, req.Id)
if err != nil {
if err == model.ErrNotFound {
return nil, fmt.Errorf("file not found")
}
return nil, fmt.Errorf("failed to query file: %v", err)
}
// Permission check: user can only edit own files, admin can edit all
if userRole != model.RoleAdmin && userRole != model.RoleSuperAdmin {
if fileRecord.UserId != userId {
return nil, fmt.Errorf("permission denied")
}
}
// Apply optional updates
if req.Name != "" {
fileRecord.Name = req.Name
}
if req.Category != "" {
fileRecord.Category = req.Category
}
if req.IsPublic != nil {
fileRecord.IsPublic = *req.IsPublic
}
// Save updates
if err := model.FileUpdate(l.ctx, l.svcCtx.DB, fileRecord); err != nil {
return nil, fmt.Errorf("failed to update file: %v", err)
}
// Build URL
url := l.buildFileURL(fileRecord.Id, fileRecord.Key)
resp = &types.FileInfo{
Id: fileRecord.Id,
Name: fileRecord.Name,
Key: fileRecord.Key,
Size: fileRecord.Size,
MimeType: fileRecord.MimeType,
Category: fileRecord.Category,
IsPublic: fileRecord.IsPublic,
UserId: fileRecord.UserId,
StorageType: fileRecord.StorageType,
Url: url,
CreatedAt: fileRecord.CreatedAt.Format("2006-01-02 15:04:05"),
UpdatedAt: fileRecord.UpdatedAt.Format("2006-01-02 15:04:05"),
}
return resp, nil
}
// buildFileURL generates the appropriate URL for the file
func (l *UpdateFileLogic) buildFileURL(fileId int64, key string) string {
rawURL, err := l.svcCtx.Storage.GetURL(l.ctx, key)
if err != nil {
l.Errorf("failed to get URL for file %d: %v", fileId, err)
return ""
}
// For local storage, return API endpoint URL
if strings.HasPrefix(rawURL, "local://") {
return fmt.Sprintf("/api/v1/file/%d/url", fileId)
}
return rawURL
}