2023-05-21 18:13:47 +03:00
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package user
import (
2023-10-11 07:24:07 +03:00
"context"
2024-05-19 07:58:39 +03:00
"errors"
2023-05-21 18:13:47 +03:00
"fmt"
"io"
2024-05-19 07:58:39 +03:00
"os"
2023-05-21 18:13:47 +03:00
"code.gitea.io/gitea/models/db"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/avatar"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/storage"
)
// UploadAvatar saves custom avatar for user.
2023-10-11 07:24:07 +03:00
func UploadAvatar ( ctx context . Context , u * user_model . User , data [ ] byte ) error {
2023-05-21 18:13:47 +03:00
avatarData , err := avatar . ProcessAvatarImage ( data )
if err != nil {
return err
}
2023-10-11 07:24:07 +03:00
ctx , committer , err := db . TxContext ( ctx )
2023-05-21 18:13:47 +03:00
if err != nil {
return err
}
defer committer . Close ( )
u . UseCustomAvatar = true
u . Avatar = avatar . HashAvatar ( u . ID , data )
if err = user_model . UpdateUserCols ( ctx , u , "use_custom_avatar" , "avatar" ) ; err != nil {
return fmt . Errorf ( "updateUser: %w" , err )
}
if err := storage . SaveFrom ( storage . Avatars , u . CustomAvatarRelativePath ( ) , func ( w io . Writer ) error {
_ , err := w . Write ( avatarData )
return err
} ) ; err != nil {
return fmt . Errorf ( "Failed to create dir %s: %w" , u . CustomAvatarRelativePath ( ) , err )
}
return committer . Commit ( )
}
// DeleteAvatar deletes the user's custom avatar.
2023-10-11 07:24:07 +03:00
func DeleteAvatar ( ctx context . Context , u * user_model . User ) error {
2023-05-21 18:13:47 +03:00
aPath := u . CustomAvatarRelativePath ( )
log . Trace ( "DeleteAvatar[%d]: %s" , u . ID , aPath )
2024-05-19 07:58:39 +03:00
return db . WithTx ( ctx , func ( ctx context . Context ) error {
hasAvatar := len ( u . Avatar ) > 0
u . UseCustomAvatar = false
u . Avatar = ""
if _ , err := db . GetEngine ( ctx ) . ID ( u . ID ) . Cols ( "avatar, use_custom_avatar" ) . Update ( u ) ; err != nil {
return fmt . Errorf ( "DeleteAvatar: %w" , err )
2023-05-21 18:13:47 +03:00
}
2024-05-19 07:58:39 +03:00
if hasAvatar {
if err := storage . Avatars . Delete ( aPath ) ; err != nil {
if ! errors . Is ( err , os . ErrNotExist ) {
return fmt . Errorf ( "failed to remove %s: %w" , aPath , err )
}
log . Warn ( "Deleting avatar %s but it doesn't exist" , aPath )
}
}
return nil
} )
2023-05-21 18:13:47 +03:00
}