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.
 
 
 
 
 
 

94 lines
2.4 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 GetFileLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// 获取文件详情
func NewGetFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFileLogic {
return &GetFileLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetFileLogic) GetFile(req *types.GetFileRequest) (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: non-admin can only see own files + public files
if userRole != model.RoleAdmin && userRole != model.RoleSuperAdmin {
if fileRecord.UserId != userId && !fileRecord.IsPublic {
return nil, fmt.Errorf("permission denied")
}
}
// 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 *GetFileLogic) 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
}