mirror of
https://github.com/hanzoai/forge.git
synced 2026-10-30 15:00:39 +00:00
Source files keep their SPDX-License-Identifier and Hanzo copyright line; the Gitea, Gogs and LFS Test Server copyrights they used to repeat now live once in NOTICE, alongside LICENSE. The header lint accepts any copyright line above the SPDX line, so it no longer demands an upstream one. Co-authored-by: Hanzo Dev <[email protected]>
70 lines
2.0 KiB
Go
70 lines
2.0 KiB
Go
// Copyright 2026 Hanzo AI, Inc. All rights reserved.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package user
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
|
|
"github.com/hanzoai/git/models/db"
|
|
user_model "github.com/hanzoai/git/models/user"
|
|
"github.com/hanzoai/git/modules/avatar"
|
|
"github.com/hanzoai/git/modules/log"
|
|
"github.com/hanzoai/git/modules/storage"
|
|
)
|
|
|
|
// UploadAvatar saves custom avatar for user.
|
|
func UploadAvatar(ctx context.Context, u *user_model.User, data []byte) error {
|
|
avatarData, err := avatar.ProcessAvatarImage(data)
|
|
if err != nil {
|
|
return fmt.Errorf("UploadAvatar: failed to process user avatar image: %w", err)
|
|
}
|
|
|
|
return db.WithTx(ctx, func(ctx context.Context) error {
|
|
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("UploadAvatar: failed to update user avatar: %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("UploadAvatar: failed to save user avatar %s: %w", u.CustomAvatarRelativePath(), err)
|
|
}
|
|
|
|
return nil
|
|
})
|
|
}
|
|
|
|
// DeleteAvatar deletes the user's custom avatar.
|
|
func DeleteAvatar(ctx context.Context, u *user_model.User) error {
|
|
aPath := u.CustomAvatarRelativePath()
|
|
log.Trace("DeleteAvatar[%d]: %s", u.ID, aPath)
|
|
|
|
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)
|
|
}
|
|
|
|
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
|
|
})
|
|
}
|