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.

313 lines
7.8 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. "time"
  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. Created time.Time `xorm:"-"`
  44. CreatedUnix int64 `xorm:"INDEX NOT NULL"`
  45. Updated time.Time `xorm:"-"`
  46. UpdatedUnix int64 `xorm:"INDEX NOT NULL"`
  47. }
  48. // BeforeInsert runs while inserting a record
  49. func (n *Notification) BeforeInsert() {
  50. var (
  51. now = time.Now()
  52. nowUnix = now.Unix()
  53. )
  54. n.Created = now
  55. n.CreatedUnix = nowUnix
  56. n.Updated = now
  57. n.UpdatedUnix = nowUnix
  58. }
  59. // BeforeUpdate runs while updating a record
  60. func (n *Notification) BeforeUpdate() {
  61. var (
  62. now = time.Now()
  63. nowUnix = now.Unix()
  64. )
  65. n.Updated = now
  66. n.UpdatedUnix = nowUnix
  67. }
  68. // CreateOrUpdateIssueNotifications creates an issue notification
  69. // for each watcher, or updates it if already exists
  70. func CreateOrUpdateIssueNotifications(issue *Issue, notificationAuthorID int64) error {
  71. sess := x.NewSession()
  72. defer sess.Close()
  73. if err := sess.Begin(); err != nil {
  74. return err
  75. }
  76. if err := createOrUpdateIssueNotifications(sess, issue, notificationAuthorID); err != nil {
  77. return err
  78. }
  79. return sess.Commit()
  80. }
  81. func createOrUpdateIssueNotifications(e Engine, issue *Issue, notificationAuthorID int64) error {
  82. issueWatches, err := getIssueWatchers(e, issue.ID)
  83. if err != nil {
  84. return err
  85. }
  86. watches, err := getWatchers(e, issue.RepoID)
  87. if err != nil {
  88. return err
  89. }
  90. notifications, err := getNotificationsByIssueID(e, issue.ID)
  91. if err != nil {
  92. return err
  93. }
  94. alreadyNotified := make(map[int64]struct{}, len(issueWatches)+len(watches))
  95. notifyUser := func(userID int64) error {
  96. // do not send notification for the own issuer/commenter
  97. if userID == notificationAuthorID {
  98. return nil
  99. }
  100. if _, ok := alreadyNotified[userID]; ok {
  101. return nil
  102. }
  103. alreadyNotified[userID] = struct{}{}
  104. if notificationExists(notifications, issue.ID, userID) {
  105. return updateIssueNotification(e, userID, issue.ID, notificationAuthorID)
  106. }
  107. return createIssueNotification(e, userID, issue, notificationAuthorID)
  108. }
  109. for _, issueWatch := range issueWatches {
  110. // ignore if user unwatched the issue
  111. if !issueWatch.IsWatching {
  112. alreadyNotified[issueWatch.UserID] = struct{}{}
  113. continue
  114. }
  115. if err := notifyUser(issueWatch.UserID); err != nil {
  116. return err
  117. }
  118. }
  119. for _, watch := range watches {
  120. if err := notifyUser(watch.UserID); err != nil {
  121. return err
  122. }
  123. }
  124. return nil
  125. }
  126. func getNotificationsByIssueID(e Engine, issueID int64) (notifications []*Notification, err error) {
  127. err = e.
  128. Where("issue_id = ?", issueID).
  129. Find(&notifications)
  130. return
  131. }
  132. func notificationExists(notifications []*Notification, issueID, userID int64) bool {
  133. for _, notification := range notifications {
  134. if notification.IssueID == issueID && notification.UserID == userID {
  135. return true
  136. }
  137. }
  138. return false
  139. }
  140. func createIssueNotification(e Engine, userID int64, issue *Issue, updatedByID int64) error {
  141. notification := &Notification{
  142. UserID: userID,
  143. RepoID: issue.RepoID,
  144. Status: NotificationStatusUnread,
  145. IssueID: issue.ID,
  146. UpdatedBy: updatedByID,
  147. }
  148. if issue.IsPull {
  149. notification.Source = NotificationSourcePullRequest
  150. } else {
  151. notification.Source = NotificationSourceIssue
  152. }
  153. _, err := e.Insert(notification)
  154. return err
  155. }
  156. func updateIssueNotification(e Engine, userID, issueID, updatedByID int64) error {
  157. notification, err := getIssueNotification(e, userID, issueID)
  158. if err != nil {
  159. return err
  160. }
  161. notification.Status = NotificationStatusUnread
  162. notification.UpdatedBy = updatedByID
  163. _, err = e.ID(notification.ID).Update(notification)
  164. return err
  165. }
  166. func getIssueNotification(e Engine, userID, issueID int64) (*Notification, error) {
  167. notification := new(Notification)
  168. _, err := e.
  169. Where("user_id = ?", userID).
  170. And("issue_id = ?", issueID).
  171. Get(notification)
  172. return notification, err
  173. }
  174. // NotificationsForUser returns notifications for a given user and status
  175. func NotificationsForUser(user *User, statuses []NotificationStatus, page, perPage int) ([]*Notification, error) {
  176. return notificationsForUser(x, user, statuses, page, perPage)
  177. }
  178. func notificationsForUser(e Engine, user *User, statuses []NotificationStatus, page, perPage int) (notifications []*Notification, err error) {
  179. if len(statuses) == 0 {
  180. return
  181. }
  182. sess := e.
  183. Where("user_id = ?", user.ID).
  184. In("status", statuses).
  185. OrderBy("updated_unix DESC")
  186. if page > 0 && perPage > 0 {
  187. sess.Limit(perPage, (page-1)*perPage)
  188. }
  189. err = sess.Find(&notifications)
  190. return
  191. }
  192. // GetRepo returns the repo of the notification
  193. func (n *Notification) GetRepo() (*Repository, error) {
  194. n.Repository = new(Repository)
  195. _, err := x.
  196. Where("id = ?", n.RepoID).
  197. Get(n.Repository)
  198. return n.Repository, err
  199. }
  200. // GetIssue returns the issue of the notification
  201. func (n *Notification) GetIssue() (*Issue, error) {
  202. n.Issue = new(Issue)
  203. _, err := x.
  204. Where("id = ?", n.IssueID).
  205. Get(n.Issue)
  206. return n.Issue, err
  207. }
  208. // GetNotificationCount returns the notification count for user
  209. func GetNotificationCount(user *User, status NotificationStatus) (int64, error) {
  210. return getNotificationCount(x, user, status)
  211. }
  212. func getNotificationCount(e Engine, user *User, status NotificationStatus) (count int64, err error) {
  213. count, err = e.
  214. Where("user_id = ?", user.ID).
  215. And("status = ?", status).
  216. Count(&Notification{})
  217. return
  218. }
  219. func setNotificationStatusReadIfUnread(e Engine, userID, issueID int64) error {
  220. notification, err := getIssueNotification(e, userID, issueID)
  221. // ignore if not exists
  222. if err != nil {
  223. return nil
  224. }
  225. if notification.Status != NotificationStatusUnread {
  226. return nil
  227. }
  228. notification.Status = NotificationStatusRead
  229. _, err = e.ID(notification.ID).Update(notification)
  230. return err
  231. }
  232. // SetNotificationStatus change the notification status
  233. func SetNotificationStatus(notificationID int64, user *User, status NotificationStatus) error {
  234. notification, err := getNotificationByID(notificationID)
  235. if err != nil {
  236. return err
  237. }
  238. if notification.UserID != user.ID {
  239. return fmt.Errorf("Can't change notification of another user: %d, %d", notification.UserID, user.ID)
  240. }
  241. notification.Status = status
  242. _, err = x.ID(notificationID).Update(notification)
  243. return err
  244. }
  245. func getNotificationByID(notificationID int64) (*Notification, error) {
  246. notification := new(Notification)
  247. ok, err := x.
  248. Where("id = ?", notificationID).
  249. Get(notification)
  250. if err != nil {
  251. return nil, err
  252. }
  253. if !ok {
  254. return nil, fmt.Errorf("Notification %d does not exists", notificationID)
  255. }
  256. return notification, nil
  257. }