code.gitea.io/gitea@v1.22.3/modules/templates/util_avatar.go (about) 1 // Copyright 2023 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package templates 5 6 import ( 7 "context" 8 "fmt" 9 "html" 10 "html/template" 11 12 activities_model "code.gitea.io/gitea/models/activities" 13 "code.gitea.io/gitea/models/avatars" 14 "code.gitea.io/gitea/models/organization" 15 repo_model "code.gitea.io/gitea/models/repo" 16 user_model "code.gitea.io/gitea/models/user" 17 gitea_html "code.gitea.io/gitea/modules/html" 18 "code.gitea.io/gitea/modules/setting" 19 ) 20 21 type AvatarUtils struct { 22 ctx context.Context 23 } 24 25 func NewAvatarUtils(ctx context.Context) *AvatarUtils { 26 return &AvatarUtils{ctx: ctx} 27 } 28 29 // AvatarHTML creates the HTML for an avatar 30 func AvatarHTML(src string, size int, class, name string) template.HTML { 31 sizeStr := fmt.Sprintf(`%d`, size) 32 33 if name == "" { 34 name = "avatar" 35 } 36 37 return template.HTML(`<img loading="lazy" class="` + class + `" src="` + src + `" title="` + html.EscapeString(name) + `" width="` + sizeStr + `" height="` + sizeStr + `"/>`) 38 } 39 40 // Avatar renders user avatars. args: user, size (int), class (string) 41 func (au *AvatarUtils) Avatar(item any, others ...any) template.HTML { 42 size, class := gitea_html.ParseSizeAndClass(avatars.DefaultAvatarPixelSize, avatars.DefaultAvatarClass, others...) 43 44 switch t := item.(type) { 45 case *user_model.User: 46 src := t.AvatarLinkWithSize(au.ctx, size*setting.Avatar.RenderedSizeFactor) 47 if src != "" { 48 return AvatarHTML(src, size, class, t.DisplayName()) 49 } 50 case *repo_model.Collaborator: 51 src := t.AvatarLinkWithSize(au.ctx, size*setting.Avatar.RenderedSizeFactor) 52 if src != "" { 53 return AvatarHTML(src, size, class, t.DisplayName()) 54 } 55 case *organization.Organization: 56 src := t.AsUser().AvatarLinkWithSize(au.ctx, size*setting.Avatar.RenderedSizeFactor) 57 if src != "" { 58 return AvatarHTML(src, size, class, t.AsUser().DisplayName()) 59 } 60 } 61 62 return AvatarHTML(avatars.DefaultAvatarLink(), size, class, "") 63 } 64 65 // AvatarByAction renders user avatars from action. args: action, size (int), class (string) 66 func (au *AvatarUtils) AvatarByAction(action *activities_model.Action, others ...any) template.HTML { 67 action.LoadActUser(au.ctx) 68 return au.Avatar(action.ActUser, others...) 69 } 70 71 // AvatarByEmail renders avatars by email address. args: email, name, size (int), class (string) 72 func (au *AvatarUtils) AvatarByEmail(email, name string, others ...any) template.HTML { 73 size, class := gitea_html.ParseSizeAndClass(avatars.DefaultAvatarPixelSize, avatars.DefaultAvatarClass, others...) 74 src := avatars.GenerateEmailAvatarFastLink(au.ctx, email, size*setting.Avatar.RenderedSizeFactor) 75 76 if src != "" { 77 return AvatarHTML(src, size, class, name) 78 } 79 80 return "" 81 }