Files

78 lines
2.2 KiB
Go
Raw Permalink Normal View History

2017-03-11 03:46:53 -05:00
// Copyright 2017 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
2017-03-11 03:46:53 -05:00
package user
2017-03-11 03:46:53 -05:00
import (
"context"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/timeutil"
)
// Follow represents relations of user and their followers.
2017-03-11 03:46:53 -05:00
type Follow struct {
ID int64 `xorm:"pk autoincr"`
UserID int64 `xorm:"UNIQUE(follow)"`
FollowID int64 `xorm:"UNIQUE(follow)"`
CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
2017-03-11 03:46:53 -05:00
}
func init() {
db.RegisterModel(new(Follow))
}
2017-03-11 03:46:53 -05:00
// IsFollowing returns true if user is following followID.
func IsFollowing(ctx context.Context, userID, followID int64) bool {
has, _ := db.GetEngine(ctx).Get(&Follow{UserID: userID, FollowID: followID})
2017-03-11 03:46:53 -05:00
return has
}
// FollowUser marks someone be another's follower.
2024-03-04 09:16:03 +01:00
func FollowUser(ctx context.Context, user, follow *User) (err error) {
if user.ID == follow.ID || IsFollowing(ctx, user.ID, follow.ID) {
2017-03-11 03:46:53 -05:00
return nil
}
2024-03-04 09:16:03 +01:00
if IsUserBlockedBy(ctx, user, follow.ID) || IsUserBlockedBy(ctx, follow, user.ID) {
return ErrBlockedUser
}
return db.WithTx(ctx, func(ctx context.Context) error {
if err = db.Insert(ctx, &Follow{UserID: user.ID, FollowID: follow.ID}); err != nil {
return err
}
if _, err = db.Exec(ctx, "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", follow.ID); err != nil {
return err
}
if _, err = db.Exec(ctx, "UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", user.ID); err != nil {
return err
}
return nil
})
2017-03-11 03:46:53 -05:00
}
// UnfollowUser unmarks someone as another's follower.
func UnfollowUser(ctx context.Context, userID, followID int64) (err error) {
if userID == followID || !IsFollowing(ctx, userID, followID) {
2017-03-11 03:46:53 -05:00
return nil
}
return db.WithTx(ctx, func(ctx context.Context) error {
if _, err = db.DeleteByBean(ctx, &Follow{UserID: userID, FollowID: followID}); err != nil {
return err
}
2017-03-11 03:46:53 -05:00
if _, err = db.Exec(ctx, "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
return err
}
2017-03-11 03:46:53 -05:00
if _, err = db.Exec(ctx, "UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
return err
}
return nil
})
2017-03-11 03:46:53 -05:00
}