gitea源码

follow.go 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package user
  4. import (
  5. "context"
  6. "code.gitea.io/gitea/models/db"
  7. "code.gitea.io/gitea/modules/timeutil"
  8. )
  9. // Follow represents relations of user and their followers.
  10. type Follow struct {
  11. ID int64 `xorm:"pk autoincr"`
  12. UserID int64 `xorm:"UNIQUE(follow)"`
  13. FollowID int64 `xorm:"UNIQUE(follow)"`
  14. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  15. }
  16. func init() {
  17. db.RegisterModel(new(Follow))
  18. }
  19. // IsFollowing returns true if user is following followID.
  20. func IsFollowing(ctx context.Context, userID, followID int64) bool {
  21. has, _ := db.GetEngine(ctx).Get(&Follow{UserID: userID, FollowID: followID})
  22. return has
  23. }
  24. // FollowUser marks someone be another's follower.
  25. func FollowUser(ctx context.Context, user, follow *User) (err error) {
  26. if user.ID == follow.ID || IsFollowing(ctx, user.ID, follow.ID) {
  27. return nil
  28. }
  29. if IsUserBlockedBy(ctx, user, follow.ID) || IsUserBlockedBy(ctx, follow, user.ID) {
  30. return ErrBlockedUser
  31. }
  32. return db.WithTx(ctx, func(ctx context.Context) error {
  33. if err = db.Insert(ctx, &Follow{UserID: user.ID, FollowID: follow.ID}); err != nil {
  34. return err
  35. }
  36. if _, err = db.Exec(ctx, "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", follow.ID); err != nil {
  37. return err
  38. }
  39. if _, err = db.Exec(ctx, "UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", user.ID); err != nil {
  40. return err
  41. }
  42. return nil
  43. })
  44. }
  45. // UnfollowUser unmarks someone as another's follower.
  46. func UnfollowUser(ctx context.Context, userID, followID int64) (err error) {
  47. if userID == followID || !IsFollowing(ctx, userID, followID) {
  48. return nil
  49. }
  50. return db.WithTx(ctx, func(ctx context.Context) error {
  51. if _, err = db.DeleteByBean(ctx, &Follow{UserID: userID, FollowID: followID}); err != nil {
  52. return err
  53. }
  54. if _, err = db.Exec(ctx, "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  55. return err
  56. }
  57. if _, err = db.Exec(ctx, "UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  58. return err
  59. }
  60. return nil
  61. })
  62. }