本站源代码
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.

71 lines
1.9KB

  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. }
上海开阖软件有限公司 沪ICP备12045867号-1