refactor(avatar): remove all avatar global variables config

This commit is contained in:
LinkinStars 2023-05-29 14:58:58 +08:00
parent 7e9becd8f5
commit fb412cb417
12 changed files with 165 additions and 139 deletions

View File

@ -122,7 +122,7 @@ func initApplication(debug bool, serverConf *conf.Server, dbConf *data.Database,
roleRepo := role.NewRoleRepo(dataData) roleRepo := role.NewRoleRepo(dataData)
roleService := role2.NewRoleService(roleRepo) roleService := role2.NewRoleService(roleRepo)
userRoleRelService := role2.NewUserRoleRelService(userRoleRelRepo, roleService) userRoleRelService := role2.NewUserRoleRelService(userRoleRelRepo, roleService)
userCommon := usercommon.NewUserCommon(userRepo, userRoleRelService, authService) userCommon := usercommon.NewUserCommon(userRepo, userRoleRelService, authService, siteInfoCommonService)
userExternalLoginRepo := user_external_login.NewUserExternalLoginRepo(dataData) userExternalLoginRepo := user_external_login.NewUserExternalLoginRepo(dataData)
userExternalLoginService := user_external_login2.NewUserExternalLoginService(userRepo, userCommon, userExternalLoginRepo, emailService, siteInfoCommonService, userActiveActivityRepo) userExternalLoginService := user_external_login2.NewUserExternalLoginService(userRepo, userCommon, userExternalLoginRepo, emailService, siteInfoCommonService, userActiveActivityRepo)
userService := service.NewUserService(userRepo, userActiveActivityRepo, activityRepo, emailService, authService, serviceConf, siteInfoCommonService, userRoleRelService, userCommon, userExternalLoginService) userService := service.NewUserService(userRepo, userActiveActivityRepo, activityRepo, emailService, authService, serviceConf, siteInfoCommonService, userRoleRelService, userCommon, userExternalLoginService)
@ -187,7 +187,7 @@ func initApplication(debug bool, serverConf *conf.Server, dbConf *data.Database,
reportAdminService := report_admin.NewReportAdminService(reportRepo, userCommon, answerRepo, questionRepo, commentCommonRepo, reportHandle, configService, objService) reportAdminService := report_admin.NewReportAdminService(reportRepo, userCommon, answerRepo, questionRepo, commentCommonRepo, reportHandle, configService, objService)
controller_adminReportController := controller_admin.NewReportController(reportAdminService) controller_adminReportController := controller_admin.NewReportController(reportAdminService)
userAdminRepo := user.NewUserAdminRepo(dataData, authRepo) userAdminRepo := user.NewUserAdminRepo(dataData, authRepo)
userAdminService := user_admin.NewUserAdminService(userAdminRepo, userRoleRelService, authService, userCommon, userActiveActivityRepo) userAdminService := user_admin.NewUserAdminService(userAdminRepo, userRoleRelService, authService, userCommon, userActiveActivityRepo, siteInfoCommonService)
userAdminController := controller_admin.NewUserAdminController(userAdminService) userAdminController := controller_admin.NewUserAdminController(userAdminService)
reasonRepo := reason.NewReasonRepo(configService) reasonRepo := reason.NewReasonRepo(configService)
reasonService := reason2.NewReasonService(reasonRepo) reasonService := reason2.NewReasonService(reasonRepo)

View File

@ -1,7 +1,13 @@
package constant package constant
var ( const (
DefaultAvatar = "system"
DefaultGravatarBaseURL = "https://www.gravatar.com/avatar/" DefaultGravatarBaseURL = "https://www.gravatar.com/avatar/"
DefaultSiteURL = "" DefaultAvatar = "system"
AvatarTypeDefault = "default"
AvatarTypeGravatar = "gravatar"
AvatarTypeCustom = "custom"
)
var (
DefaultSiteURL = ""
) )

View File

@ -55,7 +55,7 @@ func NewUserController(
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Security ApiKeyAuth // @Security ApiKeyAuth
// @Success 200 {object} handler.RespBody{data=schema.GetUserToSetShowResp} // @Success 200 {object} handler.RespBody{data=schema.GetCurrentLoginUserInfoResp}
// @Router /answer/api/v1/user/info [get] // @Router /answer/api/v1/user/info [get]
func (uc *UserController) GetUserInfoByUserID(ctx *gin.Context) { func (uc *UserController) GetUserInfoByUserID(ctx *gin.Context) {
token := middleware.ExtractToken(ctx) token := middleware.ExtractToken(ctx)
@ -102,7 +102,7 @@ func (uc *UserController) GetOtherUserInfoByUsername(ctx *gin.Context) {
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param data body schema.UserEmailLogin true "UserEmailLogin" // @Param data body schema.UserEmailLogin true "UserEmailLogin"
// @Success 200 {object} handler.RespBody{data=schema.GetUserResp} // @Success 200 {object} handler.RespBody{data=schema.UserLoginResp}
// @Router /answer/api/v1/user/login/email [post] // @Router /answer/api/v1/user/login/email [post]
func (uc *UserController) UserEmailLogin(ctx *gin.Context) { func (uc *UserController) UserEmailLogin(ctx *gin.Context) {
req := &schema.UserEmailLogin{} req := &schema.UserEmailLogin{}
@ -215,7 +215,7 @@ func (uc *UserController) UserLogout(ctx *gin.Context) {
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param data body schema.UserRegisterReq true "UserRegisterReq" // @Param data body schema.UserRegisterReq true "UserRegisterReq"
// @Success 200 {object} handler.RespBody{data=schema.GetUserResp} // @Success 200 {object} handler.RespBody{data=schema.UserLoginResp}
// @Router /answer/api/v1/user/register/email [post] // @Router /answer/api/v1/user/register/email [post]
func (uc *UserController) UserRegisterByEmail(ctx *gin.Context) { func (uc *UserController) UserRegisterByEmail(ctx *gin.Context) {
// check whether site allow register or not // check whether site allow register or not
@ -267,7 +267,7 @@ func (uc *UserController) UserRegisterByEmail(ctx *gin.Context) {
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param code query string true "code" default() // @Param code query string true "code" default()
// @Success 200 {object} handler.RespBody{data=schema.GetUserResp} // @Success 200 {object} handler.RespBody{data=schema.UserLoginResp}
// @Router /answer/api/v1/user/email/verification [post] // @Router /answer/api/v1/user/email/verification [post]
func (uc *UserController) UserVerifyEmail(ctx *gin.Context) { func (uc *UserController) UserVerifyEmail(ctx *gin.Context) {
req := &schema.UserVerifyEmailReq{} req := &schema.UserVerifyEmailReq{}
@ -464,7 +464,7 @@ func (uc *UserController) ActionRecord(ctx *gin.Context) {
// @Tags User // @Tags User
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Success 200 {object} handler.RespBody{data=schema.GetUserResp} // @Success 200 {object} handler.RespBody{data=schema.UserLoginResp}
// @Router /answer/api/v1/user/register/captcha [get] // @Router /answer/api/v1/user/register/captcha [get]
func (uc *UserController) UserRegisterCaptcha(ctx *gin.Context) { func (uc *UserController) UserRegisterCaptcha(ctx *gin.Context) {
resp, err := uc.actionService.UserRegisterCaptcha(ctx) resp, err := uc.actionService.UserRegisterCaptcha(ctx)

View File

@ -8,7 +8,6 @@ import (
"github.com/answerdev/answer/internal/entity" "github.com/answerdev/answer/internal/entity"
"github.com/answerdev/answer/pkg/checker" "github.com/answerdev/answer/pkg/checker"
"github.com/answerdev/answer/pkg/converter" "github.com/answerdev/answer/pkg/converter"
"github.com/answerdev/answer/pkg/gravatar"
"github.com/jinzhu/copier" "github.com/jinzhu/copier"
) )
@ -20,8 +19,8 @@ type UserVerifyEmailReq struct {
Content string `json:"-"` Content string `json:"-"`
} }
// GetUserResp get user response // UserLoginResp get user response
type GetUserResp struct { type UserLoginResp struct {
// user id // user id
ID string `json:"id"` ID string `json:"id"`
// create time // create time
@ -74,80 +73,25 @@ type GetUserResp struct {
HavePassword bool `json:"have_password"` HavePassword bool `json:"have_password"`
} }
func (r *GetUserResp) GetFromUserEntity(userInfo *entity.User) { func (r *UserLoginResp) ConvertFromUserEntity(userInfo *entity.User) {
_ = copier.Copy(r, userInfo) _ = copier.Copy(r, userInfo)
r.Avatar = FormatAvatarInfo(userInfo.Avatar, userInfo.EMail)
r.CreatedAt = userInfo.CreatedAt.Unix() r.CreatedAt = userInfo.CreatedAt.Unix()
r.LastLoginDate = userInfo.LastLoginDate.Unix() r.LastLoginDate = userInfo.LastLoginDate.Unix()
statusShow, ok := UserStatusShow[userInfo.Status] r.Status = UserStatusShow[userInfo.Status]
if ok {
r.Status = statusShow
}
r.HavePassword = len(userInfo.Pass) > 0 r.HavePassword = len(userInfo.Pass) > 0
} }
type GetUserToSetShowResp struct { type GetCurrentLoginUserInfoResp struct {
*GetUserResp *UserLoginResp
Avatar *AvatarInfo `json:"avatar"` Avatar *AvatarInfo `json:"avatar"`
HavePassword bool `json:"have_password"` HavePassword bool `json:"have_password"`
} }
func (r *GetUserToSetShowResp) GetFromUserEntity(userInfo *entity.User) { func (r *GetCurrentLoginUserInfoResp) ConvertFromUserEntity(userInfo *entity.User) {
_ = copier.Copy(r, userInfo) _ = copier.Copy(r, userInfo)
r.CreatedAt = userInfo.CreatedAt.Unix() r.CreatedAt = userInfo.CreatedAt.Unix()
r.LastLoginDate = userInfo.LastLoginDate.Unix() r.LastLoginDate = userInfo.LastLoginDate.Unix()
statusShow, ok := UserStatusShow[userInfo.Status] r.Status = UserStatusShow[userInfo.Status]
if ok {
r.Status = statusShow
}
avatarInfo := &AvatarInfo{}
_ = json.Unmarshal([]byte(userInfo.Avatar), avatarInfo)
if len(avatarInfo.Type) == 0 && constant.DefaultAvatar == AvatarTypeGravatar {
avatarInfo.Type = AvatarTypeGravatar
avatarInfo.Gravatar = gravatar.GetAvatarURL(userInfo.EMail)
} else if avatarInfo.Type == AvatarTypeGravatar {
avatarInfo.Gravatar = gravatar.GetAvatarURL(userInfo.EMail)
}
r.Avatar = avatarInfo
}
const (
AvatarTypeDefault = "default"
AvatarTypeGravatar = "gravatar"
AvatarTypeCustom = "custom"
)
func FormatAvatarInfo(avatarJson, email string) (res string) {
defer func() {
if constant.DefaultAvatar == AvatarTypeGravatar && len(res) == 0 {
res = gravatar.GetAvatarURL(email)
}
}()
if avatarJson == "" {
return ""
}
avatarInfo := &AvatarInfo{}
err := json.Unmarshal([]byte(avatarJson), avatarInfo)
if err != nil {
return ""
}
switch avatarInfo.Type {
case AvatarTypeGravatar:
return gravatar.GetAvatarURL(email)
case AvatarTypeCustom:
return avatarInfo.Custom
default:
return ""
}
}
func CustomAvatar(url string) *AvatarInfo {
return &AvatarInfo{
Type: AvatarTypeCustom,
Custom: url,
}
} }
// GetUserStatusResp get user status info // GetUserStatusResp get user status info
@ -193,11 +137,8 @@ type GetOtherUserInfoByUsernameResp struct {
StatusMsg string `json:"status_msg,omitempty"` StatusMsg string `json:"status_msg,omitempty"`
} }
func (r *GetOtherUserInfoByUsernameResp) GetFromUserEntity(userInfo *entity.User) { func (r *GetOtherUserInfoByUsernameResp) ConvertFromUserEntity(userInfo *entity.User) {
_ = copier.Copy(r, userInfo) _ = copier.Copy(r, userInfo)
Avatar := FormatAvatarInfo(userInfo.Avatar, userInfo.EMail)
r.Avatar = Avatar
r.CreatedAt = userInfo.CreatedAt.Unix() r.CreatedAt = userInfo.CreatedAt.Unix()
r.LastLoginDate = userInfo.LastLoginDate.Unix() r.LastLoginDate = userInfo.LastLoginDate.Unix()
statusShow, ok := UserStatusShow[userInfo.Status] statusShow, ok := UserStatusShow[userInfo.Status]
@ -325,6 +266,24 @@ func (a *AvatarInfo) ToJsonString() string {
return string(data) return string(data)
} }
func (a *AvatarInfo) GetURL() string {
switch a.Type {
case constant.AvatarTypeGravatar:
return a.Gravatar
case constant.AvatarTypeCustom:
return a.Custom
default:
return ""
}
}
func CustomAvatar(url string) *AvatarInfo {
return &AvatarInfo{
Type: constant.AvatarTypeCustom,
Custom: url,
}
}
func (req *UpdateInfoRequest) Check() (errFields []*validator.FormErrorField, err error) { func (req *UpdateInfoRequest) Check() (errFields []*validator.FormErrorField, err error) {
req.BioHTML = converter.Markdown2BasicHTML(req.Bio) req.BioHTML = converter.Markdown2BasicHTML(req.Bio)
return nil, nil return nil, nil

View File

@ -36,11 +36,11 @@ func NewSiteInfoService(
tagCommonService *tagcommon.TagCommonService, tagCommonService *tagcommon.TagCommonService,
configService *config.ConfigService, configService *config.ConfigService,
) *SiteInfoService { ) *SiteInfoService {
usersSiteInfo, _ := siteInfoCommonService.GetSiteUsers(context.Background()) //usersSiteInfo, _ := siteInfoCommonService.GetSiteUsers(context.Background())
if usersSiteInfo != nil { //if usersSiteInfo != nil {
constant.DefaultAvatar = usersSiteInfo.DefaultAvatar // constant.DefaultAvatar = usersSiteInfo.DefaultAvatar
constant.DefaultGravatarBaseURL = usersSiteInfo.GravatarBaseURL // constant.DefaultGravatarBaseURL = usersSiteInfo.GravatarBaseURL
} //}
generalSiteInfo, _ := siteInfoCommonService.GetSiteGeneral(context.Background()) generalSiteInfo, _ := siteInfoCommonService.GetSiteGeneral(context.Background())
if generalSiteInfo != nil { if generalSiteInfo != nil {
constant.DefaultSiteURL = generalSiteInfo.SiteUrl constant.DefaultSiteURL = generalSiteInfo.SiteUrl
@ -227,12 +227,7 @@ func (s *SiteInfoService) SaveSiteUsers(ctx context.Context, req *schema.SiteUse
Content: string(content), Content: string(content),
Status: 1, Status: 1,
} }
err = s.siteInfoRepo.SaveByType(ctx, constant.SiteTypeUsers, data) return s.siteInfoRepo.SaveByType(ctx, constant.SiteTypeUsers, data)
if err == nil {
constant.DefaultAvatar = req.DefaultAvatar
constant.DefaultGravatarBaseURL = req.GravatarBaseURL
}
return err
} }
// GetSMTPConfig get smtp config // GetSMTPConfig get smtp config

View File

@ -7,6 +7,7 @@ import (
"github.com/answerdev/answer/internal/base/constant" "github.com/answerdev/answer/internal/base/constant"
"github.com/answerdev/answer/internal/entity" "github.com/answerdev/answer/internal/entity"
"github.com/answerdev/answer/internal/schema" "github.com/answerdev/answer/internal/schema"
"github.com/answerdev/answer/pkg/gravatar"
"github.com/answerdev/answer/pkg/uid" "github.com/answerdev/answer/pkg/uid"
"github.com/segmentfault/pacman/log" "github.com/segmentfault/pacman/log"
) )
@ -76,6 +77,49 @@ func (s *SiteInfoCommonService) GetSiteUsers(ctx context.Context) (resp *schema.
return resp, nil return resp, nil
} }
// FormatAvatar format avatar
func (s *SiteInfoCommonService) FormatAvatar(ctx context.Context, originalAvatarData, email string) *schema.AvatarInfo {
gravatarBaseURL, defaultAvatar := s.getAvatarDefaultConfig(ctx)
return s.selectedAvatar(originalAvatarData, defaultAvatar, gravatarBaseURL, email)
}
// FormatListAvatar format avatar
func (s *SiteInfoCommonService) FormatListAvatar(ctx context.Context, userList []*entity.User) (
avatarMapping map[string]*schema.AvatarInfo) {
gravatarBaseURL, defaultAvatar := s.getAvatarDefaultConfig(ctx)
avatarMapping = make(map[string]*schema.AvatarInfo)
for _, user := range userList {
avatarMapping[user.ID] = s.selectedAvatar(user.Avatar, defaultAvatar, gravatarBaseURL, user.EMail)
}
return avatarMapping
}
func (s *SiteInfoCommonService) getAvatarDefaultConfig(ctx context.Context) (string, string) {
gravatarBaseURL, defaultAvatar := constant.DefaultGravatarBaseURL, constant.DefaultAvatar
usersConfig, err := s.GetSiteUsers(ctx)
if err != nil {
log.Error(err)
} else {
gravatarBaseURL = usersConfig.GravatarBaseURL
defaultAvatar = usersConfig.DefaultAvatar
}
return gravatarBaseURL, defaultAvatar
}
func (s *SiteInfoCommonService) selectedAvatar(
originalAvatarData string, defaultAvatar string, gravatarBaseURL string, email string) *schema.AvatarInfo {
avatarInfo := &schema.AvatarInfo{}
_ = json.Unmarshal([]byte(originalAvatarData), avatarInfo)
if len(avatarInfo.Type) == 0 && defaultAvatar == constant.AvatarTypeGravatar {
avatarInfo.Type = constant.AvatarTypeGravatar
avatarInfo.Gravatar = gravatar.GetAvatarURL(gravatarBaseURL, email)
} else if avatarInfo.Type == constant.AvatarTypeGravatar {
avatarInfo.Gravatar = gravatar.GetAvatarURL(gravatarBaseURL, email)
}
return avatarInfo
}
// GetSiteWrite get site info write // GetSiteWrite get site info write
func (s *SiteInfoCommonService) GetSiteWrite(ctx context.Context) (resp *schema.SiteWriteResp, err error) { func (s *SiteInfoCommonService) GetSiteWrite(ctx context.Context) (resp *schema.SiteWriteResp, err error) {
resp = &schema.SiteWriteResp{} resp = &schema.SiteWriteResp{}

View File

@ -15,6 +15,7 @@ import (
"github.com/answerdev/answer/internal/service/activity" "github.com/answerdev/answer/internal/service/activity"
"github.com/answerdev/answer/internal/service/auth" "github.com/answerdev/answer/internal/service/auth"
"github.com/answerdev/answer/internal/service/role" "github.com/answerdev/answer/internal/service/role"
"github.com/answerdev/answer/internal/service/siteinfo_common"
usercommon "github.com/answerdev/answer/internal/service/user_common" usercommon "github.com/answerdev/answer/internal/service/user_common"
"github.com/jinzhu/copier" "github.com/jinzhu/copier"
"github.com/segmentfault/pacman/errors" "github.com/segmentfault/pacman/errors"
@ -35,11 +36,12 @@ type UserAdminRepo interface {
// UserAdminService user service // UserAdminService user service
type UserAdminService struct { type UserAdminService struct {
userRepo UserAdminRepo userRepo UserAdminRepo
userRoleRelService *role.UserRoleRelService userRoleRelService *role.UserRoleRelService
authService *auth.AuthService authService *auth.AuthService
userCommonService *usercommon.UserCommon userCommonService *usercommon.UserCommon
userActivity activity.UserActiveActivityRepo userActivity activity.UserActiveActivityRepo
siteInfoCommonService *siteinfo_common.SiteInfoCommonService
} }
// NewUserAdminService new user admin service // NewUserAdminService new user admin service
@ -49,13 +51,15 @@ func NewUserAdminService(
authService *auth.AuthService, authService *auth.AuthService,
userCommonService *usercommon.UserCommon, userCommonService *usercommon.UserCommon,
userActivity activity.UserActiveActivityRepo, userActivity activity.UserActiveActivityRepo,
siteInfoCommonService *siteinfo_common.SiteInfoCommonService,
) *UserAdminService { ) *UserAdminService {
return &UserAdminService{ return &UserAdminService{
userRepo: userRepo, userRepo: userRepo,
userRoleRelService: userRoleRelService, userRoleRelService: userRoleRelService,
authService: authService, authService: authService,
userCommonService: userCommonService, userCommonService: userCommonService,
userActivity: userActivity, userActivity: userActivity,
siteInfoCommonService: siteInfoCommonService,
} }
} }
@ -238,10 +242,10 @@ func (us *UserAdminService) GetUserPage(ctx context.Context, req *schema.GetUser
if err != nil { if err != nil {
return return
} }
avatarMapping := us.siteInfoCommonService.FormatListAvatar(ctx, users)
resp := make([]*schema.GetUserPageResp, 0) resp := make([]*schema.GetUserPageResp, 0)
for _, u := range users { for _, u := range users {
avatar := schema.FormatAvatarInfo(u.Avatar, u.EMail)
t := &schema.GetUserPageResp{ t := &schema.GetUserPageResp{
UserID: u.ID, UserID: u.ID,
CreatedAt: u.CreatedAt.Unix(), CreatedAt: u.CreatedAt.Unix(),
@ -249,7 +253,7 @@ func (us *UserAdminService) GetUserPage(ctx context.Context, req *schema.GetUser
EMail: u.EMail, EMail: u.EMail,
Rank: u.Rank, Rank: u.Rank,
DisplayName: u.DisplayName, DisplayName: u.DisplayName,
Avatar: avatar, Avatar: avatarMapping[u.ID].GetURL(),
} }
if u.Status == entity.UserStatusDeleted { if u.Status == entity.UserStatusDeleted {
t.Status = schema.UserDeleted t.Status = schema.UserDeleted

View File

@ -10,6 +10,7 @@ import (
"github.com/answerdev/answer/internal/schema" "github.com/answerdev/answer/internal/schema"
"github.com/answerdev/answer/internal/service/auth" "github.com/answerdev/answer/internal/service/auth"
"github.com/answerdev/answer/internal/service/role" "github.com/answerdev/answer/internal/service/role"
"github.com/answerdev/answer/internal/service/siteinfo_common"
"github.com/answerdev/answer/pkg/checker" "github.com/answerdev/answer/pkg/checker"
"github.com/answerdev/answer/pkg/random" "github.com/answerdev/answer/pkg/random"
"github.com/segmentfault/pacman/errors" "github.com/segmentfault/pacman/errors"
@ -40,20 +41,23 @@ type UserRepo interface {
// UserCommon user service // UserCommon user service
type UserCommon struct { type UserCommon struct {
userRepo UserRepo userRepo UserRepo
userRoleService *role.UserRoleRelService userRoleService *role.UserRoleRelService
authService *auth.AuthService authService *auth.AuthService
siteInfoCommonService *siteinfo_common.SiteInfoCommonService
} }
func NewUserCommon( func NewUserCommon(
userRepo UserRepo, userRepo UserRepo,
userRoleService *role.UserRoleRelService, userRoleService *role.UserRoleRelService,
authService *auth.AuthService, authService *auth.AuthService,
siteInfoCommonService *siteinfo_common.SiteInfoCommonService,
) *UserCommon { ) *UserCommon {
return &UserCommon{ return &UserCommon{
userRepo: userRepo, userRepo: userRepo,
userRoleService: userRoleService, userRoleService: userRoleService,
authService: authService, authService: authService,
siteInfoCommonService: siteInfoCommonService,
} }
} }
@ -64,6 +68,7 @@ func (us *UserCommon) GetUserBasicInfoByID(ctx context.Context, ID string) (
return nil, exist, err return nil, exist, err
} }
info := us.FormatUserBasicInfo(ctx, userInfo) info := us.FormatUserBasicInfo(ctx, userInfo)
info.Avatar = us.siteInfoCommonService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL()
return info, exist, nil return info, exist, nil
} }
@ -73,6 +78,7 @@ func (us *UserCommon) GetUserBasicInfoByUserName(ctx context.Context, username s
return nil, exist, err return nil, exist, err
} }
info := us.FormatUserBasicInfo(ctx, userInfo) info := us.FormatUserBasicInfo(ctx, userInfo)
info.Avatar = us.siteInfoCommonService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL()
return info, exist, nil return info, exist, nil
} }
@ -82,8 +88,10 @@ func (us *UserCommon) BatchGetUserBasicInfoByUserNames(ctx context.Context, user
if err != nil { if err != nil {
return infomap, err return infomap, err
} }
avatarMapping := us.siteInfoCommonService.FormatListAvatar(ctx, list)
for _, user := range list { for _, user := range list {
info := us.FormatUserBasicInfo(ctx, user) info := us.FormatUserBasicInfo(ctx, user)
info.Avatar = avatarMapping[user.ID].GetURL()
infomap[user.Username] = info infomap[user.Username] = info
} }
return infomap, nil return infomap, nil
@ -99,13 +107,15 @@ func (us *UserCommon) UpdateQuestionCount(ctx context.Context, userID string, nu
func (us *UserCommon) BatchUserBasicInfoByID(ctx context.Context, IDs []string) (map[string]*schema.UserBasicInfo, error) { func (us *UserCommon) BatchUserBasicInfoByID(ctx context.Context, IDs []string) (map[string]*schema.UserBasicInfo, error) {
userMap := make(map[string]*schema.UserBasicInfo) userMap := make(map[string]*schema.UserBasicInfo)
dbInfo, err := us.userRepo.BatchGetByID(ctx, IDs) userList, err := us.userRepo.BatchGetByID(ctx, IDs)
if err != nil { if err != nil {
return userMap, err return userMap, err
} }
for _, item := range dbInfo { avatarMapping := us.siteInfoCommonService.FormatListAvatar(ctx, userList)
info := us.FormatUserBasicInfo(ctx, item) for _, user := range userList {
userMap[item.ID] = info info := us.FormatUserBasicInfo(ctx, user)
info.Avatar = avatarMapping[user.ID].GetURL()
userMap[user.ID] = info
} }
return userMap, nil return userMap, nil
} }
@ -117,7 +127,6 @@ func (us *UserCommon) FormatUserBasicInfo(ctx context.Context, userInfo *entity.
userBasicInfo.Username = userInfo.Username userBasicInfo.Username = userInfo.Username
userBasicInfo.Rank = userInfo.Rank userBasicInfo.Rank = userInfo.Rank
userBasicInfo.DisplayName = userInfo.DisplayName userBasicInfo.DisplayName = userInfo.DisplayName
userBasicInfo.Avatar = schema.FormatAvatarInfo(userInfo.Avatar, userInfo.EMail)
userBasicInfo.Website = userInfo.Website userBasicInfo.Website = userInfo.Website
userBasicInfo.Location = userInfo.Location userBasicInfo.Location = userInfo.Location
userBasicInfo.IPInfo = userInfo.IPInfo userBasicInfo.IPInfo = userInfo.IPInfo

View File

@ -5,6 +5,7 @@ import (
"encoding/json" "encoding/json"
"time" "time"
"github.com/answerdev/answer/internal/base/constant"
"github.com/answerdev/answer/internal/base/handler" "github.com/answerdev/answer/internal/base/handler"
"github.com/answerdev/answer/internal/base/reason" "github.com/answerdev/answer/internal/base/reason"
"github.com/answerdev/answer/internal/base/translator" "github.com/answerdev/answer/internal/base/translator"
@ -130,7 +131,7 @@ func (us *UserCenterLoginService) registerNewUser(ctx context.Context, provider
if len(basicUserInfo.Avatar) > 0 { if len(basicUserInfo.Avatar) > 0 {
avatarInfo := &schema.AvatarInfo{ avatarInfo := &schema.AvatarInfo{
Type: schema.AvatarTypeCustom, Type: constant.AvatarTypeCustom,
Custom: basicUserInfo.Avatar, Custom: basicUserInfo.Avatar,
} }
avatar, _ := json.Marshal(avatarInfo) avatar, _ := json.Marshal(avatarInfo)

View File

@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"time" "time"
"github.com/answerdev/answer/internal/base/constant"
"github.com/answerdev/answer/internal/base/handler" "github.com/answerdev/answer/internal/base/handler"
"github.com/answerdev/answer/internal/base/reason" "github.com/answerdev/answer/internal/base/reason"
"github.com/answerdev/answer/internal/base/translator" "github.com/answerdev/answer/internal/base/translator"
@ -164,7 +165,7 @@ func (us *UserExternalLoginService) registerNewUser(ctx context.Context,
if len(externalUserInfo.Avatar) > 0 { if len(externalUserInfo.Avatar) > 0 {
avatarInfo := &schema.AvatarInfo{ avatarInfo := &schema.AvatarInfo{
Type: schema.AvatarTypeCustom, Type: constant.AvatarTypeCustom,
Custom: externalUserInfo.Avatar, Custom: externalUserInfo.Avatar,
} }
avatar, _ := json.Marshal(avatarInfo) avatar, _ := json.Marshal(avatarInfo)
@ -222,9 +223,9 @@ func (us *UserExternalLoginService) activeUser(ctx context.Context, oldUserInfo
} }
// try to update user avatar // try to update user avatar
if len(externalUserInfo.Avatar) > 0 && len(schema.FormatAvatarInfo(oldUserInfo.Avatar, oldUserInfo.EMail)) == 0 { if len(externalUserInfo.Avatar) > 0 {
avatarInfo := &schema.AvatarInfo{ avatarInfo := &schema.AvatarInfo{
Type: schema.AvatarTypeCustom, Type: constant.AvatarTypeCustom,
Custom: externalUserInfo.Avatar, Custom: externalUserInfo.Avatar,
} }
avatar, _ := json.Marshal(avatarInfo) avatar, _ := json.Marshal(avatarInfo)

View File

@ -72,7 +72,7 @@ func NewUserService(userRepo usercommon.UserRepo,
// GetUserInfoByUserID get user info by user id // GetUserInfoByUserID get user info by user id
func (us *UserService) GetUserInfoByUserID(ctx context.Context, token, userID string) ( func (us *UserService) GetUserInfoByUserID(ctx context.Context, token, userID string) (
resp *schema.GetUserToSetShowResp, err error) { resp *schema.GetCurrentLoginUserInfoResp, err error) {
userInfo, exist, err := us.userRepo.GetByUserID(ctx, userID) userInfo, exist, err := us.userRepo.GetByUserID(ctx, userID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -83,14 +83,15 @@ func (us *UserService) GetUserInfoByUserID(ctx context.Context, token, userID st
if userInfo.Status == entity.UserStatusDeleted { if userInfo.Status == entity.UserStatusDeleted {
return nil, errors.Unauthorized(reason.UnauthorizedError) return nil, errors.Unauthorized(reason.UnauthorizedError)
} }
roleID, err := us.userRoleService.GetUserRole(ctx, userInfo.ID)
resp = &schema.GetCurrentLoginUserInfoResp{}
resp.ConvertFromUserEntity(userInfo)
resp.RoleID, err = us.userRoleService.GetUserRole(ctx, userInfo.ID)
if err != nil { if err != nil {
log.Error(err) log.Error(err)
} }
resp = &schema.GetUserToSetShowResp{} resp.Avatar = us.siteInfoService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail)
resp.GetFromUserEntity(userInfo)
resp.AccessToken = token resp.AccessToken = token
resp.RoleID = roleID
resp.HavePassword = len(userInfo.Pass) > 0 resp.HavePassword = len(userInfo.Pass) > 0
return resp, nil return resp, nil
} }
@ -106,12 +107,13 @@ func (us *UserService) GetOtherUserInfoByUsername(ctx context.Context, username
return nil, errors.NotFound(reason.UserNotFound) return nil, errors.NotFound(reason.UserNotFound)
} }
resp = &schema.GetOtherUserInfoByUsernameResp{} resp = &schema.GetOtherUserInfoByUsernameResp{}
resp.GetFromUserEntity(userInfo) resp.ConvertFromUserEntity(userInfo)
resp.Avatar = us.siteInfoService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL()
return resp, nil return resp, nil
} }
// EmailLogin email login // EmailLogin email login
func (us *UserService) EmailLogin(ctx context.Context, req *schema.UserEmailLogin) (resp *schema.GetUserResp, err error) { func (us *UserService) EmailLogin(ctx context.Context, req *schema.UserEmailLogin) (resp *schema.UserLoginResp, err error) {
userInfo, exist, err := us.userRepo.GetByEmail(ctx, req.Email) userInfo, exist, err := us.userRepo.GetByEmail(ctx, req.Email)
if err != nil { if err != nil {
return nil, err return nil, err
@ -140,8 +142,9 @@ func (us *UserService) EmailLogin(ctx context.Context, req *schema.UserEmailLogi
log.Error(err) log.Error(err)
} }
resp = &schema.GetUserResp{} resp = &schema.UserLoginResp{}
resp.GetFromUserEntity(userInfo) resp.ConvertFromUserEntity(userInfo)
resp.Avatar = us.siteInfoService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL()
userCacheInfo := &entity.UserCacheInfo{ userCacheInfo := &entity.UserCacheInfo{
UserID: userInfo.ID, UserID: userInfo.ID,
EmailStatus: userInfo.MailStatus, EmailStatus: userInfo.MailStatus,
@ -368,7 +371,7 @@ func (us *UserService) UserUpdateInterface(ctx context.Context, req *schema.Upda
// UserRegisterByEmail user register // UserRegisterByEmail user register
func (us *UserService) UserRegisterByEmail(ctx context.Context, registerUserInfo *schema.UserRegisterReq) ( func (us *UserService) UserRegisterByEmail(ctx context.Context, registerUserInfo *schema.UserRegisterReq) (
resp *schema.GetUserResp, errFields []*validator.FormErrorField, err error, resp *schema.UserLoginResp, errFields []*validator.FormErrorField, err error,
) { ) {
_, has, err := us.userRepo.GetByEmail(ctx, registerUserInfo.Email) _, has, err := us.userRepo.GetByEmail(ctx, registerUserInfo.Email)
if err != nil { if err != nil {
@ -425,8 +428,9 @@ func (us *UserService) UserRegisterByEmail(ctx context.Context, registerUserInfo
} }
// return user info and token // return user info and token
resp = &schema.GetUserResp{} resp = &schema.UserLoginResp{}
resp.GetFromUserEntity(userInfo) resp.ConvertFromUserEntity(userInfo)
resp.Avatar = us.siteInfoService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL()
userCacheInfo := &entity.UserCacheInfo{ userCacheInfo := &entity.UserCacheInfo{
UserID: userInfo.ID, UserID: userInfo.ID,
EmailStatus: userInfo.MailStatus, EmailStatus: userInfo.MailStatus,
@ -489,7 +493,7 @@ func (us *UserService) UserNoticeSet(ctx context.Context, userID string, noticeS
return &schema.UserNoticeSetResp{NoticeSwitch: noticeSwitch}, err return &schema.UserNoticeSetResp{NoticeSwitch: noticeSwitch}, err
} }
func (us *UserService) UserVerifyEmail(ctx context.Context, req *schema.UserVerifyEmailReq) (resp *schema.GetUserResp, err error) { func (us *UserService) UserVerifyEmail(ctx context.Context, req *schema.UserVerifyEmailReq) (resp *schema.UserLoginResp, err error) {
data := &schema.EmailCodeContent{} data := &schema.EmailCodeContent{}
err = data.FromJSONString(req.Content) err = data.FromJSONString(req.Content)
if err != nil { if err != nil {
@ -528,8 +532,9 @@ func (us *UserService) UserVerifyEmail(ctx context.Context, req *schema.UserVeri
return nil, err return nil, err
} }
resp = &schema.GetUserResp{} resp = &schema.UserLoginResp{}
resp.GetFromUserEntity(userInfo) resp.ConvertFromUserEntity(userInfo)
resp.Avatar = us.siteInfoService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL()
resp.AccessToken = accessToken resp.AccessToken = accessToken
// User verified email will update user email status. So user status cache should be updated. // User verified email will update user email status. So user status cache should be updated.
if err = us.authService.SetUserStatus(ctx, userCacheInfo); err != nil { if err = us.authService.SetUserStatus(ctx, userCacheInfo); err != nil {
@ -610,7 +615,7 @@ func (us *UserService) UserChangeEmailSendCode(ctx context.Context, req *schema.
} }
// UserChangeEmailVerify user change email verify code // UserChangeEmailVerify user change email verify code
func (us *UserService) UserChangeEmailVerify(ctx context.Context, content string) (resp *schema.GetUserResp, err error) { func (us *UserService) UserChangeEmailVerify(ctx context.Context, content string) (resp *schema.UserLoginResp, err error) {
data := &schema.EmailCodeContent{} data := &schema.EmailCodeContent{}
err = data.FromJSONString(content) err = data.FromJSONString(content)
if err != nil { if err != nil {
@ -646,8 +651,9 @@ func (us *UserService) UserChangeEmailVerify(ctx context.Context, content string
log.Error(err) log.Error(err)
} }
resp = &schema.GetUserResp{} resp = &schema.UserLoginResp{}
resp.GetFromUserEntity(userInfo) resp.ConvertFromUserEntity(userInfo)
resp.Avatar = us.siteInfoService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL()
userCacheInfo := &entity.UserCacheInfo{ userCacheInfo := &entity.UserCacheInfo{
UserID: userInfo.ID, UserID: userInfo.ID,
EmailStatus: entity.EmailStatusAvailable, EmailStatus: entity.EmailStatusAvailable,
@ -807,8 +813,9 @@ func (us *UserService) getUserInfoMapping(ctx context.Context, userIDs []string)
if err != nil { if err != nil {
return nil, err return nil, err
} }
avatarMapping := us.siteInfoService.FormatListAvatar(ctx, userInfoList)
for _, user := range userInfoList { for _, user := range userInfoList {
user.Avatar = schema.FormatAvatarInfo(user.Avatar, user.EMail) user.Avatar = avatarMapping[user.ID].GetURL()
userInfoMapping[user.ID] = user userInfoMapping[user.ID] = user
} }
return userInfoMapping, nil return userInfoMapping, nil
@ -820,8 +827,10 @@ func (us *UserService) SearchUserListByName(ctx context.Context, name string) ([
if err != nil { if err != nil {
return userinfolist, err return userinfolist, err
} }
avatarMapping := us.siteInfoService.FormatListAvatar(ctx, list)
for _, user := range list { for _, user := range list {
userinfo := us.userCommonService.FormatUserBasicInfo(ctx, user) userinfo := us.userCommonService.FormatUserBasicInfo(ctx, user)
userinfo.Avatar = avatarMapping[user.ID].GetURL()
userinfolist = append(userinfolist, userinfo) userinfolist = append(userinfolist, userinfo)
} }
return userinfolist, nil return userinfolist, nil

View File

@ -5,15 +5,13 @@ import (
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"net/url" "net/url"
"github.com/answerdev/answer/internal/base/constant"
) )
// GetAvatarURL get avatar url from gravatar by email // GetAvatarURL get avatar url from gravatar by email
func GetAvatarURL(email string) string { func GetAvatarURL(baseURL, email string) string {
h := md5.New() h := md5.New()
h.Write([]byte(email)) h.Write([]byte(email))
return constant.DefaultGravatarBaseURL + hex.EncodeToString(h.Sum(nil)) return baseURL + hex.EncodeToString(h.Sum(nil))
} }
// Resize resize avatar by pixel // Resize resize avatar by pixel