From fb412cb4170bb25184c2ab63f1115624a97560d1 Mon Sep 17 00:00:00 2001 From: LinkinStars Date: Mon, 29 May 2023 14:58:58 +0800 Subject: [PATCH] refactor(avatar): remove all avatar global variables config --- cmd/wire_gen.go | 4 +- internal/base/constant/site_info.go | 12 ++- internal/controller/user_controller.go | 10 +- internal/schema/user_schema.go | 95 ++++++------------- internal/service/siteinfo/siteinfo_service.go | 17 ++-- .../siteinfo_common/siteinfo_service.go | 44 +++++++++ internal/service/user_admin/user_backyard.go | 28 +++--- internal/service/user_common/user.go | 31 +++--- .../user_center_login_service.go | 3 +- .../user_external_login_service.go | 7 +- internal/service/user_service.go | 47 +++++---- pkg/gravatar/gravatar.go | 6 +- 12 files changed, 165 insertions(+), 139 deletions(-) diff --git a/cmd/wire_gen.go b/cmd/wire_gen.go index 61f3e6f4..49055ded 100644 --- a/cmd/wire_gen.go +++ b/cmd/wire_gen.go @@ -122,7 +122,7 @@ func initApplication(debug bool, serverConf *conf.Server, dbConf *data.Database, roleRepo := role.NewRoleRepo(dataData) roleService := role2.NewRoleService(roleRepo) userRoleRelService := role2.NewUserRoleRelService(userRoleRelRepo, roleService) - userCommon := usercommon.NewUserCommon(userRepo, userRoleRelService, authService) + userCommon := usercommon.NewUserCommon(userRepo, userRoleRelService, authService, siteInfoCommonService) userExternalLoginRepo := user_external_login.NewUserExternalLoginRepo(dataData) userExternalLoginService := user_external_login2.NewUserExternalLoginService(userRepo, userCommon, userExternalLoginRepo, emailService, siteInfoCommonService, userActiveActivityRepo) 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) controller_adminReportController := controller_admin.NewReportController(reportAdminService) 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) reasonRepo := reason.NewReasonRepo(configService) reasonService := reason2.NewReasonService(reasonRepo) diff --git a/internal/base/constant/site_info.go b/internal/base/constant/site_info.go index 88f3a4d8..7d7c0439 100644 --- a/internal/base/constant/site_info.go +++ b/internal/base/constant/site_info.go @@ -1,7 +1,13 @@ package constant -var ( - DefaultAvatar = "system" +const ( DefaultGravatarBaseURL = "https://www.gravatar.com/avatar/" - DefaultSiteURL = "" + DefaultAvatar = "system" + AvatarTypeDefault = "default" + AvatarTypeGravatar = "gravatar" + AvatarTypeCustom = "custom" +) + +var ( + DefaultSiteURL = "" ) diff --git a/internal/controller/user_controller.go b/internal/controller/user_controller.go index 4fbf0482..88e57ca3 100644 --- a/internal/controller/user_controller.go +++ b/internal/controller/user_controller.go @@ -55,7 +55,7 @@ func NewUserController( // @Accept json // @Produce json // @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] func (uc *UserController) GetUserInfoByUserID(ctx *gin.Context) { token := middleware.ExtractToken(ctx) @@ -102,7 +102,7 @@ func (uc *UserController) GetOtherUserInfoByUsername(ctx *gin.Context) { // @Accept json // @Produce json // @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] func (uc *UserController) UserEmailLogin(ctx *gin.Context) { req := &schema.UserEmailLogin{} @@ -215,7 +215,7 @@ func (uc *UserController) UserLogout(ctx *gin.Context) { // @Accept json // @Produce json // @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] func (uc *UserController) UserRegisterByEmail(ctx *gin.Context) { // check whether site allow register or not @@ -267,7 +267,7 @@ func (uc *UserController) UserRegisterByEmail(ctx *gin.Context) { // @Accept json // @Produce json // @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] func (uc *UserController) UserVerifyEmail(ctx *gin.Context) { req := &schema.UserVerifyEmailReq{} @@ -464,7 +464,7 @@ func (uc *UserController) ActionRecord(ctx *gin.Context) { // @Tags User // @Accept 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] func (uc *UserController) UserRegisterCaptcha(ctx *gin.Context) { resp, err := uc.actionService.UserRegisterCaptcha(ctx) diff --git a/internal/schema/user_schema.go b/internal/schema/user_schema.go index 79442cb2..b1155bf4 100644 --- a/internal/schema/user_schema.go +++ b/internal/schema/user_schema.go @@ -8,7 +8,6 @@ import ( "github.com/answerdev/answer/internal/entity" "github.com/answerdev/answer/pkg/checker" "github.com/answerdev/answer/pkg/converter" - "github.com/answerdev/answer/pkg/gravatar" "github.com/jinzhu/copier" ) @@ -20,8 +19,8 @@ type UserVerifyEmailReq struct { Content string `json:"-"` } -// GetUserResp get user response -type GetUserResp struct { +// UserLoginResp get user response +type UserLoginResp struct { // user id ID string `json:"id"` // create time @@ -74,80 +73,25 @@ type GetUserResp struct { HavePassword bool `json:"have_password"` } -func (r *GetUserResp) GetFromUserEntity(userInfo *entity.User) { +func (r *UserLoginResp) ConvertFromUserEntity(userInfo *entity.User) { _ = copier.Copy(r, userInfo) - r.Avatar = FormatAvatarInfo(userInfo.Avatar, userInfo.EMail) r.CreatedAt = userInfo.CreatedAt.Unix() r.LastLoginDate = userInfo.LastLoginDate.Unix() - statusShow, ok := UserStatusShow[userInfo.Status] - if ok { - r.Status = statusShow - } + r.Status = UserStatusShow[userInfo.Status] r.HavePassword = len(userInfo.Pass) > 0 } -type GetUserToSetShowResp struct { - *GetUserResp +type GetCurrentLoginUserInfoResp struct { + *UserLoginResp Avatar *AvatarInfo `json:"avatar"` HavePassword bool `json:"have_password"` } -func (r *GetUserToSetShowResp) GetFromUserEntity(userInfo *entity.User) { +func (r *GetCurrentLoginUserInfoResp) ConvertFromUserEntity(userInfo *entity.User) { _ = copier.Copy(r, userInfo) r.CreatedAt = userInfo.CreatedAt.Unix() r.LastLoginDate = userInfo.LastLoginDate.Unix() - statusShow, ok := 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, - } + r.Status = UserStatusShow[userInfo.Status] } // GetUserStatusResp get user status info @@ -193,11 +137,8 @@ type GetOtherUserInfoByUsernameResp struct { StatusMsg string `json:"status_msg,omitempty"` } -func (r *GetOtherUserInfoByUsernameResp) GetFromUserEntity(userInfo *entity.User) { +func (r *GetOtherUserInfoByUsernameResp) ConvertFromUserEntity(userInfo *entity.User) { _ = copier.Copy(r, userInfo) - Avatar := FormatAvatarInfo(userInfo.Avatar, userInfo.EMail) - r.Avatar = Avatar - r.CreatedAt = userInfo.CreatedAt.Unix() r.LastLoginDate = userInfo.LastLoginDate.Unix() statusShow, ok := UserStatusShow[userInfo.Status] @@ -325,6 +266,24 @@ func (a *AvatarInfo) ToJsonString() string { 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) { req.BioHTML = converter.Markdown2BasicHTML(req.Bio) return nil, nil diff --git a/internal/service/siteinfo/siteinfo_service.go b/internal/service/siteinfo/siteinfo_service.go index a1c4c08e..620906d3 100644 --- a/internal/service/siteinfo/siteinfo_service.go +++ b/internal/service/siteinfo/siteinfo_service.go @@ -36,11 +36,11 @@ func NewSiteInfoService( tagCommonService *tagcommon.TagCommonService, configService *config.ConfigService, ) *SiteInfoService { - usersSiteInfo, _ := siteInfoCommonService.GetSiteUsers(context.Background()) - if usersSiteInfo != nil { - constant.DefaultAvatar = usersSiteInfo.DefaultAvatar - constant.DefaultGravatarBaseURL = usersSiteInfo.GravatarBaseURL - } + //usersSiteInfo, _ := siteInfoCommonService.GetSiteUsers(context.Background()) + //if usersSiteInfo != nil { + // constant.DefaultAvatar = usersSiteInfo.DefaultAvatar + // constant.DefaultGravatarBaseURL = usersSiteInfo.GravatarBaseURL + //} generalSiteInfo, _ := siteInfoCommonService.GetSiteGeneral(context.Background()) if generalSiteInfo != nil { constant.DefaultSiteURL = generalSiteInfo.SiteUrl @@ -227,12 +227,7 @@ func (s *SiteInfoService) SaveSiteUsers(ctx context.Context, req *schema.SiteUse Content: string(content), Status: 1, } - err = s.siteInfoRepo.SaveByType(ctx, constant.SiteTypeUsers, data) - if err == nil { - constant.DefaultAvatar = req.DefaultAvatar - constant.DefaultGravatarBaseURL = req.GravatarBaseURL - } - return err + return s.siteInfoRepo.SaveByType(ctx, constant.SiteTypeUsers, data) } // GetSMTPConfig get smtp config diff --git a/internal/service/siteinfo_common/siteinfo_service.go b/internal/service/siteinfo_common/siteinfo_service.go index 7e2934a3..fff82a8d 100644 --- a/internal/service/siteinfo_common/siteinfo_service.go +++ b/internal/service/siteinfo_common/siteinfo_service.go @@ -7,6 +7,7 @@ import ( "github.com/answerdev/answer/internal/base/constant" "github.com/answerdev/answer/internal/entity" "github.com/answerdev/answer/internal/schema" + "github.com/answerdev/answer/pkg/gravatar" "github.com/answerdev/answer/pkg/uid" "github.com/segmentfault/pacman/log" ) @@ -76,6 +77,49 @@ func (s *SiteInfoCommonService) GetSiteUsers(ctx context.Context) (resp *schema. 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 func (s *SiteInfoCommonService) GetSiteWrite(ctx context.Context) (resp *schema.SiteWriteResp, err error) { resp = &schema.SiteWriteResp{} diff --git a/internal/service/user_admin/user_backyard.go b/internal/service/user_admin/user_backyard.go index a98086ae..86270e08 100644 --- a/internal/service/user_admin/user_backyard.go +++ b/internal/service/user_admin/user_backyard.go @@ -15,6 +15,7 @@ import ( "github.com/answerdev/answer/internal/service/activity" "github.com/answerdev/answer/internal/service/auth" "github.com/answerdev/answer/internal/service/role" + "github.com/answerdev/answer/internal/service/siteinfo_common" usercommon "github.com/answerdev/answer/internal/service/user_common" "github.com/jinzhu/copier" "github.com/segmentfault/pacman/errors" @@ -35,11 +36,12 @@ type UserAdminRepo interface { // UserAdminService user service type UserAdminService struct { - userRepo UserAdminRepo - userRoleRelService *role.UserRoleRelService - authService *auth.AuthService - userCommonService *usercommon.UserCommon - userActivity activity.UserActiveActivityRepo + userRepo UserAdminRepo + userRoleRelService *role.UserRoleRelService + authService *auth.AuthService + userCommonService *usercommon.UserCommon + userActivity activity.UserActiveActivityRepo + siteInfoCommonService *siteinfo_common.SiteInfoCommonService } // NewUserAdminService new user admin service @@ -49,13 +51,15 @@ func NewUserAdminService( authService *auth.AuthService, userCommonService *usercommon.UserCommon, userActivity activity.UserActiveActivityRepo, + siteInfoCommonService *siteinfo_common.SiteInfoCommonService, ) *UserAdminService { return &UserAdminService{ - userRepo: userRepo, - userRoleRelService: userRoleRelService, - authService: authService, - userCommonService: userCommonService, - userActivity: userActivity, + userRepo: userRepo, + userRoleRelService: userRoleRelService, + authService: authService, + userCommonService: userCommonService, + userActivity: userActivity, + siteInfoCommonService: siteInfoCommonService, } } @@ -238,10 +242,10 @@ func (us *UserAdminService) GetUserPage(ctx context.Context, req *schema.GetUser if err != nil { return } + avatarMapping := us.siteInfoCommonService.FormatListAvatar(ctx, users) resp := make([]*schema.GetUserPageResp, 0) for _, u := range users { - avatar := schema.FormatAvatarInfo(u.Avatar, u.EMail) t := &schema.GetUserPageResp{ UserID: u.ID, CreatedAt: u.CreatedAt.Unix(), @@ -249,7 +253,7 @@ func (us *UserAdminService) GetUserPage(ctx context.Context, req *schema.GetUser EMail: u.EMail, Rank: u.Rank, DisplayName: u.DisplayName, - Avatar: avatar, + Avatar: avatarMapping[u.ID].GetURL(), } if u.Status == entity.UserStatusDeleted { t.Status = schema.UserDeleted diff --git a/internal/service/user_common/user.go b/internal/service/user_common/user.go index b6331e70..9a451265 100644 --- a/internal/service/user_common/user.go +++ b/internal/service/user_common/user.go @@ -10,6 +10,7 @@ import ( "github.com/answerdev/answer/internal/schema" "github.com/answerdev/answer/internal/service/auth" "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/random" "github.com/segmentfault/pacman/errors" @@ -40,20 +41,23 @@ type UserRepo interface { // UserCommon user service type UserCommon struct { - userRepo UserRepo - userRoleService *role.UserRoleRelService - authService *auth.AuthService + userRepo UserRepo + userRoleService *role.UserRoleRelService + authService *auth.AuthService + siteInfoCommonService *siteinfo_common.SiteInfoCommonService } func NewUserCommon( userRepo UserRepo, userRoleService *role.UserRoleRelService, authService *auth.AuthService, + siteInfoCommonService *siteinfo_common.SiteInfoCommonService, ) *UserCommon { return &UserCommon{ - userRepo: userRepo, - userRoleService: userRoleService, - authService: authService, + userRepo: userRepo, + userRoleService: userRoleService, + authService: authService, + siteInfoCommonService: siteInfoCommonService, } } @@ -64,6 +68,7 @@ func (us *UserCommon) GetUserBasicInfoByID(ctx context.Context, ID string) ( return nil, exist, err } info := us.FormatUserBasicInfo(ctx, userInfo) + info.Avatar = us.siteInfoCommonService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL() return info, exist, nil } @@ -73,6 +78,7 @@ func (us *UserCommon) GetUserBasicInfoByUserName(ctx context.Context, username s return nil, exist, err } info := us.FormatUserBasicInfo(ctx, userInfo) + info.Avatar = us.siteInfoCommonService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL() return info, exist, nil } @@ -82,8 +88,10 @@ func (us *UserCommon) BatchGetUserBasicInfoByUserNames(ctx context.Context, user if err != nil { return infomap, err } + avatarMapping := us.siteInfoCommonService.FormatListAvatar(ctx, list) for _, user := range list { info := us.FormatUserBasicInfo(ctx, user) + info.Avatar = avatarMapping[user.ID].GetURL() infomap[user.Username] = info } 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) { userMap := make(map[string]*schema.UserBasicInfo) - dbInfo, err := us.userRepo.BatchGetByID(ctx, IDs) + userList, err := us.userRepo.BatchGetByID(ctx, IDs) if err != nil { return userMap, err } - for _, item := range dbInfo { - info := us.FormatUserBasicInfo(ctx, item) - userMap[item.ID] = info + avatarMapping := us.siteInfoCommonService.FormatListAvatar(ctx, userList) + for _, user := range userList { + info := us.FormatUserBasicInfo(ctx, user) + info.Avatar = avatarMapping[user.ID].GetURL() + userMap[user.ID] = info } return userMap, nil } @@ -117,7 +127,6 @@ func (us *UserCommon) FormatUserBasicInfo(ctx context.Context, userInfo *entity. userBasicInfo.Username = userInfo.Username userBasicInfo.Rank = userInfo.Rank userBasicInfo.DisplayName = userInfo.DisplayName - userBasicInfo.Avatar = schema.FormatAvatarInfo(userInfo.Avatar, userInfo.EMail) userBasicInfo.Website = userInfo.Website userBasicInfo.Location = userInfo.Location userBasicInfo.IPInfo = userInfo.IPInfo diff --git a/internal/service/user_external_login/user_center_login_service.go b/internal/service/user_external_login/user_center_login_service.go index 37a0614d..9e870381 100644 --- a/internal/service/user_external_login/user_center_login_service.go +++ b/internal/service/user_external_login/user_center_login_service.go @@ -5,6 +5,7 @@ import ( "encoding/json" "time" + "github.com/answerdev/answer/internal/base/constant" "github.com/answerdev/answer/internal/base/handler" "github.com/answerdev/answer/internal/base/reason" "github.com/answerdev/answer/internal/base/translator" @@ -130,7 +131,7 @@ func (us *UserCenterLoginService) registerNewUser(ctx context.Context, provider if len(basicUserInfo.Avatar) > 0 { avatarInfo := &schema.AvatarInfo{ - Type: schema.AvatarTypeCustom, + Type: constant.AvatarTypeCustom, Custom: basicUserInfo.Avatar, } avatar, _ := json.Marshal(avatarInfo) diff --git a/internal/service/user_external_login/user_external_login_service.go b/internal/service/user_external_login/user_external_login_service.go index baed23fc..4b10aef4 100644 --- a/internal/service/user_external_login/user_external_login_service.go +++ b/internal/service/user_external_login/user_external_login_service.go @@ -6,6 +6,7 @@ import ( "fmt" "time" + "github.com/answerdev/answer/internal/base/constant" "github.com/answerdev/answer/internal/base/handler" "github.com/answerdev/answer/internal/base/reason" "github.com/answerdev/answer/internal/base/translator" @@ -164,7 +165,7 @@ func (us *UserExternalLoginService) registerNewUser(ctx context.Context, if len(externalUserInfo.Avatar) > 0 { avatarInfo := &schema.AvatarInfo{ - Type: schema.AvatarTypeCustom, + Type: constant.AvatarTypeCustom, Custom: externalUserInfo.Avatar, } avatar, _ := json.Marshal(avatarInfo) @@ -222,9 +223,9 @@ func (us *UserExternalLoginService) activeUser(ctx context.Context, oldUserInfo } // 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{ - Type: schema.AvatarTypeCustom, + Type: constant.AvatarTypeCustom, Custom: externalUserInfo.Avatar, } avatar, _ := json.Marshal(avatarInfo) diff --git a/internal/service/user_service.go b/internal/service/user_service.go index c6ca63c2..0cdf1f9d 100644 --- a/internal/service/user_service.go +++ b/internal/service/user_service.go @@ -72,7 +72,7 @@ func NewUserService(userRepo usercommon.UserRepo, // GetUserInfoByUserID get user info by user id 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) if err != nil { return nil, err @@ -83,14 +83,15 @@ func (us *UserService) GetUserInfoByUserID(ctx context.Context, token, userID st if userInfo.Status == entity.UserStatusDeleted { 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 { log.Error(err) } - resp = &schema.GetUserToSetShowResp{} - resp.GetFromUserEntity(userInfo) + resp.Avatar = us.siteInfoService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail) resp.AccessToken = token - resp.RoleID = roleID resp.HavePassword = len(userInfo.Pass) > 0 return resp, nil } @@ -106,12 +107,13 @@ func (us *UserService) GetOtherUserInfoByUsername(ctx context.Context, username return nil, errors.NotFound(reason.UserNotFound) } resp = &schema.GetOtherUserInfoByUsernameResp{} - resp.GetFromUserEntity(userInfo) + resp.ConvertFromUserEntity(userInfo) + resp.Avatar = us.siteInfoService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL() return resp, nil } // 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) if err != nil { return nil, err @@ -140,8 +142,9 @@ func (us *UserService) EmailLogin(ctx context.Context, req *schema.UserEmailLogi log.Error(err) } - resp = &schema.GetUserResp{} - resp.GetFromUserEntity(userInfo) + resp = &schema.UserLoginResp{} + resp.ConvertFromUserEntity(userInfo) + resp.Avatar = us.siteInfoService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL() userCacheInfo := &entity.UserCacheInfo{ UserID: userInfo.ID, EmailStatus: userInfo.MailStatus, @@ -368,7 +371,7 @@ func (us *UserService) UserUpdateInterface(ctx context.Context, req *schema.Upda // UserRegisterByEmail user register 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) if err != nil { @@ -425,8 +428,9 @@ func (us *UserService) UserRegisterByEmail(ctx context.Context, registerUserInfo } // return user info and token - resp = &schema.GetUserResp{} - resp.GetFromUserEntity(userInfo) + resp = &schema.UserLoginResp{} + resp.ConvertFromUserEntity(userInfo) + resp.Avatar = us.siteInfoService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL() userCacheInfo := &entity.UserCacheInfo{ UserID: userInfo.ID, EmailStatus: userInfo.MailStatus, @@ -489,7 +493,7 @@ func (us *UserService) UserNoticeSet(ctx context.Context, userID string, noticeS 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{} err = data.FromJSONString(req.Content) if err != nil { @@ -528,8 +532,9 @@ func (us *UserService) UserVerifyEmail(ctx context.Context, req *schema.UserVeri return nil, err } - resp = &schema.GetUserResp{} - resp.GetFromUserEntity(userInfo) + resp = &schema.UserLoginResp{} + resp.ConvertFromUserEntity(userInfo) + resp.Avatar = us.siteInfoService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL() resp.AccessToken = accessToken // User verified email will update user email status. So user status cache should be updated. 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 -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{} err = data.FromJSONString(content) if err != nil { @@ -646,8 +651,9 @@ func (us *UserService) UserChangeEmailVerify(ctx context.Context, content string log.Error(err) } - resp = &schema.GetUserResp{} - resp.GetFromUserEntity(userInfo) + resp = &schema.UserLoginResp{} + resp.ConvertFromUserEntity(userInfo) + resp.Avatar = us.siteInfoService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL() userCacheInfo := &entity.UserCacheInfo{ UserID: userInfo.ID, EmailStatus: entity.EmailStatusAvailable, @@ -807,8 +813,9 @@ func (us *UserService) getUserInfoMapping(ctx context.Context, userIDs []string) if err != nil { return nil, err } + avatarMapping := us.siteInfoService.FormatListAvatar(ctx, userInfoList) for _, user := range userInfoList { - user.Avatar = schema.FormatAvatarInfo(user.Avatar, user.EMail) + user.Avatar = avatarMapping[user.ID].GetURL() userInfoMapping[user.ID] = user } return userInfoMapping, nil @@ -820,8 +827,10 @@ func (us *UserService) SearchUserListByName(ctx context.Context, name string) ([ if err != nil { return userinfolist, err } + avatarMapping := us.siteInfoService.FormatListAvatar(ctx, list) for _, user := range list { userinfo := us.userCommonService.FormatUserBasicInfo(ctx, user) + userinfo.Avatar = avatarMapping[user.ID].GetURL() userinfolist = append(userinfolist, userinfo) } return userinfolist, nil diff --git a/pkg/gravatar/gravatar.go b/pkg/gravatar/gravatar.go index 92afcdd9..baac92da 100644 --- a/pkg/gravatar/gravatar.go +++ b/pkg/gravatar/gravatar.go @@ -5,15 +5,13 @@ import ( "encoding/hex" "fmt" "net/url" - - "github.com/answerdev/answer/internal/base/constant" ) // GetAvatarURL get avatar url from gravatar by email -func GetAvatarURL(email string) string { +func GetAvatarURL(baseURL, email string) string { h := md5.New() h.Write([]byte(email)) - return constant.DefaultGravatarBaseURL + hex.EncodeToString(h.Sum(nil)) + return baseURL + hex.EncodeToString(h.Sum(nil)) } // Resize resize avatar by pixel