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

user_follow.go 2.0 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. import "code.gitea.io/gitea/modules/timeutil"
  6. // Follow represents relations of user and his/her followers.
  7. type Follow struct {
  8. ID int64 `xorm:"pk autoincr"`
  9. UserID int64 `xorm:"UNIQUE(follow)"`
  10. FollowID int64 `xorm:"UNIQUE(follow)"`
  11. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  12. }
  13. // IsFollowing returns true if user is following followID.
  14. func IsFollowing(userID, followID int64) bool {
  15. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  16. return has
  17. }
  18. // FollowUser marks someone be another's follower.
  19. func FollowUser(userID, followID int64) (err error) {
  20. if userID == followID || IsFollowing(userID, followID) {
  21. return nil
  22. }
  23. sess := x.NewSession()
  24. defer sess.Close()
  25. if err = sess.Begin(); err != nil {
  26. return err
  27. }
  28. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  29. return err
  30. }
  31. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  32. return err
  33. }
  34. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  35. return err
  36. }
  37. return sess.Commit()
  38. }
  39. // UnfollowUser unmarks someone as another's follower.
  40. func UnfollowUser(userID, followID int64) (err error) {
  41. if userID == followID || !IsFollowing(userID, followID) {
  42. return nil
  43. }
  44. sess := x.NewSession()
  45. defer sess.Close()
  46. if err = sess.Begin(); err != nil {
  47. return err
  48. }
  49. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  50. return err
  51. }
  52. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  53. return err
  54. }
  55. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  56. return err
  57. }
  58. return sess.Commit()
  59. }