Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

user_follow.go 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. // Follow represents relations of user and his/her followers.
  6. type Follow struct {
  7. ID int64 `xorm:"pk autoincr"`
  8. UserID int64 `xorm:"UNIQUE(follow)"`
  9. FollowID int64 `xorm:"UNIQUE(follow)"`
  10. }
  11. // IsFollowing returns true if user is following followID.
  12. func IsFollowing(userID, followID int64) bool {
  13. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  14. return has
  15. }
  16. // FollowUser marks someone be another's follower.
  17. func FollowUser(userID, followID int64) (err error) {
  18. if userID == followID || IsFollowing(userID, followID) {
  19. return nil
  20. }
  21. sess := x.NewSession()
  22. defer sess.Close()
  23. if err = sess.Begin(); err != nil {
  24. return err
  25. }
  26. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  27. return err
  28. }
  29. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  30. return err
  31. }
  32. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  33. return err
  34. }
  35. return sess.Commit()
  36. }
  37. // UnfollowUser unmarks someone as another's follower.
  38. func UnfollowUser(userID, followID int64) (err error) {
  39. if userID == followID || !IsFollowing(userID, followID) {
  40. return nil
  41. }
  42. sess := x.NewSession()
  43. defer sess.Close()
  44. if err = sess.Begin(); err != nil {
  45. return err
  46. }
  47. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  48. return err
  49. }
  50. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  51. return err
  52. }
  53. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  54. return err
  55. }
  56. return sess.Commit()
  57. }