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 1.9 kB

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