code.gitea.io/gitea@v1.21.7/services/user/avatar.go (about) 1 // Copyright 2023 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package user 5 6 import ( 7 "fmt" 8 "io" 9 10 "code.gitea.io/gitea/models/db" 11 user_model "code.gitea.io/gitea/models/user" 12 "code.gitea.io/gitea/modules/avatar" 13 "code.gitea.io/gitea/modules/log" 14 "code.gitea.io/gitea/modules/storage" 15 ) 16 17 // UploadAvatar saves custom avatar for user. 18 func UploadAvatar(u *user_model.User, data []byte) error { 19 avatarData, err := avatar.ProcessAvatarImage(data) 20 if err != nil { 21 return err 22 } 23 24 ctx, committer, err := db.TxContext(db.DefaultContext) 25 if err != nil { 26 return err 27 } 28 defer committer.Close() 29 30 u.UseCustomAvatar = true 31 u.Avatar = avatar.HashAvatar(u.ID, data) 32 if err = user_model.UpdateUserCols(ctx, u, "use_custom_avatar", "avatar"); err != nil { 33 return fmt.Errorf("updateUser: %w", err) 34 } 35 36 if err := storage.SaveFrom(storage.Avatars, u.CustomAvatarRelativePath(), func(w io.Writer) error { 37 _, err := w.Write(avatarData) 38 return err 39 }); err != nil { 40 return fmt.Errorf("Failed to create dir %s: %w", u.CustomAvatarRelativePath(), err) 41 } 42 43 return committer.Commit() 44 } 45 46 // DeleteAvatar deletes the user's custom avatar. 47 func DeleteAvatar(u *user_model.User) error { 48 aPath := u.CustomAvatarRelativePath() 49 log.Trace("DeleteAvatar[%d]: %s", u.ID, aPath) 50 if len(u.Avatar) > 0 { 51 if err := storage.Avatars.Delete(aPath); err != nil { 52 return fmt.Errorf("Failed to remove %s: %w", aPath, err) 53 } 54 } 55 56 u.UseCustomAvatar = false 57 u.Avatar = "" 58 if _, err := db.GetEngine(db.DefaultContext).ID(u.ID).Cols("avatar, use_custom_avatar").Update(u); err != nil { 59 return fmt.Errorf("UpdateUser: %w", err) 60 } 61 return nil 62 }