You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

follow.go 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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, userID, followID int64) (err error) {
  26. if userID == followID || IsFollowing(ctx, userID, followID) {
  27. return nil
  28. }
  29. ctx, committer, err := db.TxContext(ctx)
  30. if err != nil {
  31. return err
  32. }
  33. defer committer.Close()
  34. if err = db.Insert(ctx, &Follow{UserID: userID, FollowID: followID}); err != nil {
  35. return err
  36. }
  37. if _, err = db.Exec(ctx, "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  38. return err
  39. }
  40. if _, err = db.Exec(ctx, "UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  41. return err
  42. }
  43. return committer.Commit()
  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. ctx, committer, err := db.TxContext(ctx)
  51. if err != nil {
  52. return err
  53. }
  54. defer committer.Close()
  55. if _, err = db.DeleteByBean(ctx, &Follow{UserID: userID, FollowID: followID}); err != nil {
  56. return err
  57. }
  58. if _, err = db.Exec(ctx, "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  59. return err
  60. }
  61. if _, err = db.Exec(ctx, "UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  62. return err
  63. }
  64. return committer.Commit()
  65. }