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.

311 lines
8.1 KiB

  1. // Copyright 2016 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 (
  6. "fmt"
  7. "code.gitea.io/gitea/modules/util"
  8. )
  9. type (
  10. // NotificationStatus is the status of the notification (read or unread)
  11. NotificationStatus uint8
  12. // NotificationSource is the source of the notification (issue, PR, commit, etc)
  13. NotificationSource uint8
  14. )
  15. const (
  16. // NotificationStatusUnread represents an unread notification
  17. NotificationStatusUnread NotificationStatus = iota + 1
  18. // NotificationStatusRead represents a read notification
  19. NotificationStatusRead
  20. // NotificationStatusPinned represents a pinned notification
  21. NotificationStatusPinned
  22. )
  23. const (
  24. // NotificationSourceIssue is a notification of an issue
  25. NotificationSourceIssue NotificationSource = iota + 1
  26. // NotificationSourcePullRequest is a notification of a pull request
  27. NotificationSourcePullRequest
  28. // NotificationSourceCommit is a notification of a commit
  29. NotificationSourceCommit
  30. )
  31. // Notification represents a notification
  32. type Notification struct {
  33. ID int64 `xorm:"pk autoincr"`
  34. UserID int64 `xorm:"INDEX NOT NULL"`
  35. RepoID int64 `xorm:"INDEX NOT NULL"`
  36. Status NotificationStatus `xorm:"SMALLINT INDEX NOT NULL"`
  37. Source NotificationSource `xorm:"SMALLINT INDEX NOT NULL"`
  38. IssueID int64 `xorm:"INDEX NOT NULL"`
  39. CommitID string `xorm:"INDEX"`
  40. UpdatedBy int64 `xorm:"INDEX NOT NULL"`
  41. Issue *Issue `xorm:"-"`
  42. Repository *Repository `xorm:"-"`
  43. CreatedUnix util.TimeStamp `xorm:"created INDEX NOT NULL"`
  44. UpdatedUnix util.TimeStamp `xorm:"updated INDEX NOT NULL"`
  45. }
  46. // CreateOrUpdateIssueNotifications creates an issue notification
  47. // for each watcher, or updates it if already exists
  48. func CreateOrUpdateIssueNotifications(issue *Issue, notificationAuthorID int64) error {
  49. sess := x.NewSession()
  50. defer sess.Close()
  51. if err := sess.Begin(); err != nil {
  52. return err
  53. }
  54. if err := createOrUpdateIssueNotifications(sess, issue, notificationAuthorID); err != nil {
  55. return err
  56. }
  57. return sess.Commit()
  58. }
  59. func createOrUpdateIssueNotifications(e Engine, issue *Issue, notificationAuthorID int64) error {
  60. issueWatches, err := getIssueWatchers(e, issue.ID)
  61. if err != nil {
  62. return err
  63. }
  64. watches, err := getWatchers(e, issue.RepoID)
  65. if err != nil {
  66. return err
  67. }
  68. notifications, err := getNotificationsByIssueID(e, issue.ID)
  69. if err != nil {
  70. return err
  71. }
  72. alreadyNotified := make(map[int64]struct{}, len(issueWatches)+len(watches))
  73. notifyUser := func(userID int64) error {
  74. // do not send notification for the own issuer/commenter
  75. if userID == notificationAuthorID {
  76. return nil
  77. }
  78. if _, ok := alreadyNotified[userID]; ok {
  79. return nil
  80. }
  81. alreadyNotified[userID] = struct{}{}
  82. if notificationExists(notifications, issue.ID, userID) {
  83. return updateIssueNotification(e, userID, issue.ID, notificationAuthorID)
  84. }
  85. return createIssueNotification(e, userID, issue, notificationAuthorID)
  86. }
  87. for _, issueWatch := range issueWatches {
  88. // ignore if user unwatched the issue
  89. if !issueWatch.IsWatching {
  90. alreadyNotified[issueWatch.UserID] = struct{}{}
  91. continue
  92. }
  93. if err := notifyUser(issueWatch.UserID); err != nil {
  94. return err
  95. }
  96. }
  97. issue.loadRepo(e)
  98. for _, watch := range watches {
  99. issue.Repo.Units = nil
  100. if issue.IsPull && !issue.Repo.checkUnitUser(e, watch.UserID, false, UnitTypePullRequests) {
  101. continue
  102. }
  103. if !issue.IsPull && !issue.Repo.checkUnitUser(e, watch.UserID, false, UnitTypeIssues) {
  104. continue
  105. }
  106. if err := notifyUser(watch.UserID); err != nil {
  107. return err
  108. }
  109. }
  110. return nil
  111. }
  112. func getNotificationsByIssueID(e Engine, issueID int64) (notifications []*Notification, err error) {
  113. err = e.
  114. Where("issue_id = ?", issueID).
  115. Find(&notifications)
  116. return
  117. }
  118. func notificationExists(notifications []*Notification, issueID, userID int64) bool {
  119. for _, notification := range notifications {
  120. if notification.IssueID == issueID && notification.UserID == userID {
  121. return true
  122. }
  123. }
  124. return false
  125. }
  126. func createIssueNotification(e Engine, userID int64, issue *Issue, updatedByID int64) error {
  127. notification := &Notification{
  128. UserID: userID,
  129. RepoID: issue.RepoID,
  130. Status: NotificationStatusUnread,
  131. IssueID: issue.ID,
  132. UpdatedBy: updatedByID,
  133. }
  134. if issue.IsPull {
  135. notification.Source = NotificationSourcePullRequest
  136. } else {
  137. notification.Source = NotificationSourceIssue
  138. }
  139. _, err := e.Insert(notification)
  140. return err
  141. }
  142. func updateIssueNotification(e Engine, userID, issueID, updatedByID int64) error {
  143. notification, err := getIssueNotification(e, userID, issueID)
  144. if err != nil {
  145. return err
  146. }
  147. notification.Status = NotificationStatusUnread
  148. notification.UpdatedBy = updatedByID
  149. _, err = e.ID(notification.ID).Update(notification)
  150. return err
  151. }
  152. func getIssueNotification(e Engine, userID, issueID int64) (*Notification, error) {
  153. notification := new(Notification)
  154. _, err := e.
  155. Where("user_id = ?", userID).
  156. And("issue_id = ?", issueID).
  157. Get(notification)
  158. return notification, err
  159. }
  160. // NotificationsForUser returns notifications for a given user and status
  161. func NotificationsForUser(user *User, statuses []NotificationStatus, page, perPage int) ([]*Notification, error) {
  162. return notificationsForUser(x, user, statuses, page, perPage)
  163. }
  164. func notificationsForUser(e Engine, user *User, statuses []NotificationStatus, page, perPage int) (notifications []*Notification, err error) {
  165. if len(statuses) == 0 {
  166. return
  167. }
  168. sess := e.
  169. Where("user_id = ?", user.ID).
  170. In("status", statuses).
  171. OrderBy("updated_unix DESC")
  172. if page > 0 && perPage > 0 {
  173. sess.Limit(perPage, (page-1)*perPage)
  174. }
  175. err = sess.Find(&notifications)
  176. return
  177. }
  178. // GetRepo returns the repo of the notification
  179. func (n *Notification) GetRepo() (*Repository, error) {
  180. n.Repository = new(Repository)
  181. _, err := x.
  182. Where("id = ?", n.RepoID).
  183. Get(n.Repository)
  184. return n.Repository, err
  185. }
  186. // GetIssue returns the issue of the notification
  187. func (n *Notification) GetIssue() (*Issue, error) {
  188. n.Issue = new(Issue)
  189. _, err := x.
  190. Where("id = ?", n.IssueID).
  191. Get(n.Issue)
  192. return n.Issue, err
  193. }
  194. // GetNotificationCount returns the notification count for user
  195. func GetNotificationCount(user *User, status NotificationStatus) (int64, error) {
  196. return getNotificationCount(x, user, status)
  197. }
  198. func getNotificationCount(e Engine, user *User, status NotificationStatus) (count int64, err error) {
  199. count, err = e.
  200. Where("user_id = ?", user.ID).
  201. And("status = ?", status).
  202. Count(&Notification{})
  203. return
  204. }
  205. func setNotificationStatusReadIfUnread(e Engine, userID, issueID int64) error {
  206. notification, err := getIssueNotification(e, userID, issueID)
  207. // ignore if not exists
  208. if err != nil {
  209. return nil
  210. }
  211. if notification.Status != NotificationStatusUnread {
  212. return nil
  213. }
  214. notification.Status = NotificationStatusRead
  215. _, err = e.ID(notification.ID).Update(notification)
  216. return err
  217. }
  218. // SetNotificationStatus change the notification status
  219. func SetNotificationStatus(notificationID int64, user *User, status NotificationStatus) error {
  220. notification, err := getNotificationByID(notificationID)
  221. if err != nil {
  222. return err
  223. }
  224. if notification.UserID != user.ID {
  225. return fmt.Errorf("Can't change notification of another user: %d, %d", notification.UserID, user.ID)
  226. }
  227. notification.Status = status
  228. _, err = x.ID(notificationID).Update(notification)
  229. return err
  230. }
  231. func getNotificationByID(notificationID int64) (*Notification, error) {
  232. notification := new(Notification)
  233. ok, err := x.
  234. Where("id = ?", notificationID).
  235. Get(notification)
  236. if err != nil {
  237. return nil, err
  238. }
  239. if !ok {
  240. return nil, fmt.Errorf("Notification %d does not exists", notificationID)
  241. }
  242. return notification, nil
  243. }
  244. // UpdateNotificationStatuses updates the statuses of all of a user's notifications that are of the currentStatus type to the desiredStatus
  245. func UpdateNotificationStatuses(user *User, currentStatus NotificationStatus, desiredStatus NotificationStatus) error {
  246. n := &Notification{Status: desiredStatus, UpdatedBy: user.ID}
  247. _, err := x.
  248. Where("user_id = ? AND status = ?", user.ID, currentStatus).
  249. Cols("status", "updated_by", "updated_unix").
  250. Update(n)
  251. return err
  252. }