69 lines
2.0 KiB
Go
69 lines
2.0 KiB
Go
// Code scaffolded by goctl. Safe to edit.
|
|
// goctl 1.10.1
|
|
|
|
package member
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
app "haixun-backend/internal/library/errors"
|
|
"haixun-backend/internal/library/errors/code"
|
|
memberusecase "haixun-backend/internal/model/member/domain/usecase"
|
|
"haixun-backend/internal/svc"
|
|
"haixun-backend/internal/types"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
type UploadMemberAvatarLogic struct {
|
|
logx.Logger
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
}
|
|
|
|
func NewUploadMemberAvatarLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadMemberAvatarLogic {
|
|
return &UploadMemberAvatarLogic{
|
|
Logger: logx.WithContext(ctx),
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
}
|
|
}
|
|
|
|
func (l *UploadMemberAvatarLogic) UploadMemberAvatar(filename, contentType string, body io.Reader) (resp *types.UploadAvatarData, err error) {
|
|
if l.svcCtx.AvatarStorage == nil {
|
|
return nil, app.For(code.Member).SysNotImplemented("avatar storage is not configured")
|
|
}
|
|
tenantID, uid, err := actorFrom(l.ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
ext := strings.ToLower(filepath.Ext(filename))
|
|
if !allowedAvatarExt(ext) {
|
|
return nil, app.For(code.Member).InputInvalidFormat("avatar file must be jpg, png, webp, or gif")
|
|
}
|
|
if contentType != "" && !strings.HasPrefix(strings.ToLower(contentType), "image/") {
|
|
return nil, app.For(code.Member).InputInvalidFormat("avatar file must be an image")
|
|
}
|
|
key := "avatars/" + tenantID + "/" + uid + ext
|
|
storedKey, err := l.svcCtx.AvatarStorage.Upload(l.ctx, key, contentType, body)
|
|
if err != nil {
|
|
return nil, app.For(code.Member).SysInternal("upload avatar failed").WithCause(err)
|
|
}
|
|
if _, err := l.svcCtx.Member.UpdateProfile(l.ctx, memberusecase.UpdateProfileRequest{TenantID: tenantID, UID: uid, Avatar: &storedKey}); err != nil {
|
|
return nil, err
|
|
}
|
|
return &types.UploadAvatarData{Avatar: storedKey}, nil
|
|
}
|
|
|
|
func allowedAvatarExt(ext string) bool {
|
|
switch ext {
|
|
case ".jpg", ".jpeg", ".png", ".webp", ".gif":
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|