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.

notification.go 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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. "path"
  8. "code.gitea.io/gitea/modules/log"
  9. "code.gitea.io/gitea/modules/setting"
  10. api "code.gitea.io/gitea/modules/structs"
  11. "code.gitea.io/gitea/modules/timeutil"
  12. "xorm.io/builder"
  13. "xorm.io/xorm"
  14. )
  15. type (
  16. // NotificationStatus is the status of the notification (read or unread)
  17. NotificationStatus uint8
  18. // NotificationSource is the source of the notification (issue, PR, commit, etc)
  19. NotificationSource uint8
  20. )
  21. const (
  22. // NotificationStatusUnread represents an unread notification
  23. NotificationStatusUnread NotificationStatus = iota + 1
  24. // NotificationStatusRead represents a read notification
  25. NotificationStatusRead
  26. // NotificationStatusPinned represents a pinned notification
  27. NotificationStatusPinned
  28. )
  29. const (
  30. // NotificationSourceIssue is a notification of an issue
  31. NotificationSourceIssue NotificationSource = iota + 1
  32. // NotificationSourcePullRequest is a notification of a pull request
  33. NotificationSourcePullRequest
  34. // NotificationSourceCommit is a notification of a commit
  35. NotificationSourceCommit
  36. )
  37. // Notification represents a notification
  38. type Notification struct {
  39. ID int64 `xorm:"pk autoincr"`
  40. UserID int64 `xorm:"INDEX NOT NULL"`
  41. RepoID int64 `xorm:"INDEX NOT NULL"`
  42. Status NotificationStatus `xorm:"SMALLINT INDEX NOT NULL"`
  43. Source NotificationSource `xorm:"SMALLINT INDEX NOT NULL"`
  44. IssueID int64 `xorm:"INDEX NOT NULL"`
  45. CommitID string `xorm:"INDEX"`
  46. CommentID int64
  47. UpdatedBy int64 `xorm:"INDEX NOT NULL"`
  48. Issue *Issue `xorm:"-"`
  49. Repository *Repository `xorm:"-"`
  50. Comment *Comment `xorm:"-"`
  51. User *User `xorm:"-"`
  52. CreatedUnix timeutil.TimeStamp `xorm:"created INDEX NOT NULL"`
  53. UpdatedUnix timeutil.TimeStamp `xorm:"updated INDEX NOT NULL"`
  54. }
  55. // FindNotificationOptions represent the filters for notifications. If an ID is 0 it will be ignored.
  56. type FindNotificationOptions struct {
  57. ListOptions
  58. UserID int64
  59. RepoID int64
  60. IssueID int64
  61. Status NotificationStatus
  62. UpdatedAfterUnix int64
  63. UpdatedBeforeUnix int64
  64. }
  65. // ToCond will convert each condition into a xorm-Cond
  66. func (opts *FindNotificationOptions) ToCond() builder.Cond {
  67. cond := builder.NewCond()
  68. if opts.UserID != 0 {
  69. cond = cond.And(builder.Eq{"notification.user_id": opts.UserID})
  70. }
  71. if opts.RepoID != 0 {
  72. cond = cond.And(builder.Eq{"notification.repo_id": opts.RepoID})
  73. }
  74. if opts.IssueID != 0 {
  75. cond = cond.And(builder.Eq{"notification.issue_id": opts.IssueID})
  76. }
  77. if opts.Status != 0 {
  78. cond = cond.And(builder.Eq{"notification.status": opts.Status})
  79. }
  80. if opts.UpdatedAfterUnix != 0 {
  81. cond = cond.And(builder.Gte{"notification.updated_unix": opts.UpdatedAfterUnix})
  82. }
  83. if opts.UpdatedBeforeUnix != 0 {
  84. cond = cond.And(builder.Lte{"notification.updated_unix": opts.UpdatedBeforeUnix})
  85. }
  86. return cond
  87. }
  88. // ToSession will convert the given options to a xorm Session by using the conditions from ToCond and joining with issue table if required
  89. func (opts *FindNotificationOptions) ToSession(e Engine) *xorm.Session {
  90. return opts.setSessionPagination(e.Where(opts.ToCond()))
  91. }
  92. func getNotifications(e Engine, options FindNotificationOptions) (nl NotificationList, err error) {
  93. err = options.ToSession(e).OrderBy("notification.updated_unix DESC").Find(&nl)
  94. return
  95. }
  96. // GetNotifications returns all notifications that fit to the given options.
  97. func GetNotifications(opts FindNotificationOptions) (NotificationList, error) {
  98. return getNotifications(x, opts)
  99. }
  100. // CreateOrUpdateIssueNotifications creates an issue notification
  101. // for each watcher, or updates it if already exists
  102. func CreateOrUpdateIssueNotifications(issueID, commentID int64, notificationAuthorID int64) error {
  103. sess := x.NewSession()
  104. defer sess.Close()
  105. if err := sess.Begin(); err != nil {
  106. return err
  107. }
  108. if err := createOrUpdateIssueNotifications(sess, issueID, commentID, notificationAuthorID); err != nil {
  109. return err
  110. }
  111. return sess.Commit()
  112. }
  113. func createOrUpdateIssueNotifications(e Engine, issueID, commentID int64, notificationAuthorID int64) error {
  114. // init
  115. toNotify := make(map[int64]struct{}, 32)
  116. notifications, err := getNotificationsByIssueID(e, issueID)
  117. if err != nil {
  118. return err
  119. }
  120. issue, err := getIssueByID(e, issueID)
  121. if err != nil {
  122. return err
  123. }
  124. issueWatches, err := getIssueWatchersIDs(e, issueID, true)
  125. if err != nil {
  126. return err
  127. }
  128. for _, id := range issueWatches {
  129. toNotify[id] = struct{}{}
  130. }
  131. repoWatches, err := getRepoWatchersIDs(e, issue.RepoID)
  132. if err != nil {
  133. return err
  134. }
  135. for _, id := range repoWatches {
  136. toNotify[id] = struct{}{}
  137. }
  138. issueParticipants, err := issue.getParticipantIDsByIssue(e)
  139. if err != nil {
  140. return err
  141. }
  142. for _, id := range issueParticipants {
  143. toNotify[id] = struct{}{}
  144. }
  145. // dont notify user who cause notification
  146. delete(toNotify, notificationAuthorID)
  147. // explicit unwatch on issue
  148. issueUnWatches, err := getIssueWatchersIDs(e, issueID, false)
  149. if err != nil {
  150. return err
  151. }
  152. for _, id := range issueUnWatches {
  153. delete(toNotify, id)
  154. }
  155. err = issue.loadRepo(e)
  156. if err != nil {
  157. return err
  158. }
  159. // notify
  160. for userID := range toNotify {
  161. issue.Repo.Units = nil
  162. if issue.IsPull && !issue.Repo.checkUnitUser(e, userID, false, UnitTypePullRequests) {
  163. continue
  164. }
  165. if !issue.IsPull && !issue.Repo.checkUnitUser(e, userID, false, UnitTypeIssues) {
  166. continue
  167. }
  168. if notificationExists(notifications, issue.ID, userID) {
  169. if err = updateIssueNotification(e, userID, issue.ID, commentID, notificationAuthorID); err != nil {
  170. return err
  171. }
  172. continue
  173. }
  174. if err = createIssueNotification(e, userID, issue, commentID, notificationAuthorID); err != nil {
  175. return err
  176. }
  177. }
  178. return nil
  179. }
  180. func getNotificationsByIssueID(e Engine, issueID int64) (notifications []*Notification, err error) {
  181. err = e.
  182. Where("issue_id = ?", issueID).
  183. Find(&notifications)
  184. return
  185. }
  186. func notificationExists(notifications []*Notification, issueID, userID int64) bool {
  187. for _, notification := range notifications {
  188. if notification.IssueID == issueID && notification.UserID == userID {
  189. return true
  190. }
  191. }
  192. return false
  193. }
  194. func createIssueNotification(e Engine, userID int64, issue *Issue, commentID, updatedByID int64) error {
  195. notification := &Notification{
  196. UserID: userID,
  197. RepoID: issue.RepoID,
  198. Status: NotificationStatusUnread,
  199. IssueID: issue.ID,
  200. CommentID: commentID,
  201. UpdatedBy: updatedByID,
  202. }
  203. if issue.IsPull {
  204. notification.Source = NotificationSourcePullRequest
  205. } else {
  206. notification.Source = NotificationSourceIssue
  207. }
  208. _, err := e.Insert(notification)
  209. return err
  210. }
  211. func updateIssueNotification(e Engine, userID, issueID, commentID, updatedByID int64) error {
  212. notification, err := getIssueNotification(e, userID, issueID)
  213. if err != nil {
  214. return err
  215. }
  216. // NOTICE: Only update comment id when the before notification on this issue is read, otherwise you may miss some old comments.
  217. // But we need update update_by so that the notification will be reorder
  218. var cols []string
  219. if notification.Status == NotificationStatusRead {
  220. notification.Status = NotificationStatusUnread
  221. notification.CommentID = commentID
  222. cols = []string{"status", "update_by", "comment_id"}
  223. } else {
  224. notification.UpdatedBy = updatedByID
  225. cols = []string{"update_by"}
  226. }
  227. _, err = e.ID(notification.ID).Cols(cols...).Update(notification)
  228. return err
  229. }
  230. func getIssueNotification(e Engine, userID, issueID int64) (*Notification, error) {
  231. notification := new(Notification)
  232. _, err := e.
  233. Where("user_id = ?", userID).
  234. And("issue_id = ?", issueID).
  235. Get(notification)
  236. return notification, err
  237. }
  238. // NotificationsForUser returns notifications for a given user and status
  239. func NotificationsForUser(user *User, statuses []NotificationStatus, page, perPage int) (NotificationList, error) {
  240. return notificationsForUser(x, user, statuses, page, perPage)
  241. }
  242. func notificationsForUser(e Engine, user *User, statuses []NotificationStatus, page, perPage int) (notifications []*Notification, err error) {
  243. if len(statuses) == 0 {
  244. return
  245. }
  246. sess := e.
  247. Where("user_id = ?", user.ID).
  248. In("status", statuses).
  249. OrderBy("updated_unix DESC")
  250. if page > 0 && perPage > 0 {
  251. sess.Limit(perPage, (page-1)*perPage)
  252. }
  253. err = sess.Find(&notifications)
  254. return
  255. }
  256. // CountUnread count unread notifications for a user
  257. func CountUnread(user *User) int64 {
  258. return countUnread(x, user.ID)
  259. }
  260. func countUnread(e Engine, userID int64) int64 {
  261. exist, err := e.Where("user_id = ?", userID).And("status = ?", NotificationStatusUnread).Count(new(Notification))
  262. if err != nil {
  263. log.Error("countUnread", err)
  264. return 0
  265. }
  266. return exist
  267. }
  268. // APIFormat converts a Notification to api.NotificationThread
  269. func (n *Notification) APIFormat() *api.NotificationThread {
  270. result := &api.NotificationThread{
  271. ID: n.ID,
  272. Unread: !(n.Status == NotificationStatusRead || n.Status == NotificationStatusPinned),
  273. Pinned: n.Status == NotificationStatusPinned,
  274. UpdatedAt: n.UpdatedUnix.AsTime(),
  275. URL: n.APIURL(),
  276. }
  277. //since user only get notifications when he has access to use minimal access mode
  278. if n.Repository != nil {
  279. result.Repository = n.Repository.APIFormat(AccessModeRead)
  280. }
  281. //handle Subject
  282. switch n.Source {
  283. case NotificationSourceIssue:
  284. result.Subject = &api.NotificationSubject{Type: "Issue"}
  285. if n.Issue != nil {
  286. result.Subject.Title = n.Issue.Title
  287. result.Subject.URL = n.Issue.APIURL()
  288. comment, err := n.Issue.GetLastComment()
  289. if err == nil && comment != nil {
  290. result.Subject.LatestCommentURL = comment.APIURL()
  291. }
  292. }
  293. case NotificationSourcePullRequest:
  294. result.Subject = &api.NotificationSubject{Type: "Pull"}
  295. if n.Issue != nil {
  296. result.Subject.Title = n.Issue.Title
  297. result.Subject.URL = n.Issue.APIURL()
  298. comment, err := n.Issue.GetLastComment()
  299. if err == nil && comment != nil {
  300. result.Subject.LatestCommentURL = comment.APIURL()
  301. }
  302. }
  303. case NotificationSourceCommit:
  304. result.Subject = &api.NotificationSubject{
  305. Type: "Commit",
  306. Title: n.CommitID,
  307. }
  308. //unused until now
  309. }
  310. return result
  311. }
  312. // LoadAttributes load Repo Issue User and Comment if not loaded
  313. func (n *Notification) LoadAttributes() (err error) {
  314. return n.loadAttributes(x)
  315. }
  316. func (n *Notification) loadAttributes(e Engine) (err error) {
  317. if err = n.loadRepo(e); err != nil {
  318. return
  319. }
  320. if err = n.loadIssue(e); err != nil {
  321. return
  322. }
  323. if err = n.loadUser(e); err != nil {
  324. return
  325. }
  326. if err = n.loadComment(e); err != nil {
  327. return
  328. }
  329. return
  330. }
  331. func (n *Notification) loadRepo(e Engine) (err error) {
  332. if n.Repository == nil {
  333. n.Repository, err = getRepositoryByID(e, n.RepoID)
  334. if err != nil {
  335. return fmt.Errorf("getRepositoryByID [%d]: %v", n.RepoID, err)
  336. }
  337. }
  338. return nil
  339. }
  340. func (n *Notification) loadIssue(e Engine) (err error) {
  341. if n.Issue == nil {
  342. n.Issue, err = getIssueByID(e, n.IssueID)
  343. if err != nil {
  344. return fmt.Errorf("getIssueByID [%d]: %v", n.IssueID, err)
  345. }
  346. return n.Issue.loadAttributes(e)
  347. }
  348. return nil
  349. }
  350. func (n *Notification) loadComment(e Engine) (err error) {
  351. if n.Comment == nil && n.CommentID > 0 {
  352. n.Comment, err = getCommentByID(e, n.CommentID)
  353. if err != nil {
  354. return fmt.Errorf("GetCommentByID [%d] for issue ID [%d]: %v", n.CommentID, n.IssueID, err)
  355. }
  356. }
  357. return nil
  358. }
  359. func (n *Notification) loadUser(e Engine) (err error) {
  360. if n.User == nil {
  361. n.User, err = getUserByID(e, n.UserID)
  362. if err != nil {
  363. return fmt.Errorf("getUserByID [%d]: %v", n.UserID, err)
  364. }
  365. }
  366. return nil
  367. }
  368. // GetRepo returns the repo of the notification
  369. func (n *Notification) GetRepo() (*Repository, error) {
  370. return n.Repository, n.loadRepo(x)
  371. }
  372. // GetIssue returns the issue of the notification
  373. func (n *Notification) GetIssue() (*Issue, error) {
  374. return n.Issue, n.loadIssue(x)
  375. }
  376. // HTMLURL formats a URL-string to the notification
  377. func (n *Notification) HTMLURL() string {
  378. if n.Comment != nil {
  379. return n.Comment.HTMLURL()
  380. }
  381. return n.Issue.HTMLURL()
  382. }
  383. // APIURL formats a URL-string to the notification
  384. func (n *Notification) APIURL() string {
  385. return setting.AppURL + path.Join("api/v1/notifications/threads", fmt.Sprintf("%d", n.ID))
  386. }
  387. // NotificationList contains a list of notifications
  388. type NotificationList []*Notification
  389. // APIFormat converts a NotificationList to api.NotificationThread list
  390. func (nl NotificationList) APIFormat() []*api.NotificationThread {
  391. var result = make([]*api.NotificationThread, 0, len(nl))
  392. for _, n := range nl {
  393. result = append(result, n.APIFormat())
  394. }
  395. return result
  396. }
  397. // LoadAttributes load Repo Issue User and Comment if not loaded
  398. func (nl NotificationList) LoadAttributes() (err error) {
  399. for i := 0; i < len(nl); i++ {
  400. err = nl[i].LoadAttributes()
  401. if err != nil {
  402. return
  403. }
  404. }
  405. return
  406. }
  407. func (nl NotificationList) getPendingRepoIDs() []int64 {
  408. var ids = make(map[int64]struct{}, len(nl))
  409. for _, notification := range nl {
  410. if notification.Repository != nil {
  411. continue
  412. }
  413. if _, ok := ids[notification.RepoID]; !ok {
  414. ids[notification.RepoID] = struct{}{}
  415. }
  416. }
  417. return keysInt64(ids)
  418. }
  419. // LoadRepos loads repositories from database
  420. func (nl NotificationList) LoadRepos() (RepositoryList, []int, error) {
  421. if len(nl) == 0 {
  422. return RepositoryList{}, []int{}, nil
  423. }
  424. var repoIDs = nl.getPendingRepoIDs()
  425. var repos = make(map[int64]*Repository, len(repoIDs))
  426. var left = len(repoIDs)
  427. for left > 0 {
  428. var limit = defaultMaxInSize
  429. if left < limit {
  430. limit = left
  431. }
  432. rows, err := x.
  433. In("id", repoIDs[:limit]).
  434. Rows(new(Repository))
  435. if err != nil {
  436. return nil, nil, err
  437. }
  438. for rows.Next() {
  439. var repo Repository
  440. err = rows.Scan(&repo)
  441. if err != nil {
  442. rows.Close()
  443. return nil, nil, err
  444. }
  445. repos[repo.ID] = &repo
  446. }
  447. _ = rows.Close()
  448. left -= limit
  449. repoIDs = repoIDs[limit:]
  450. }
  451. failed := []int{}
  452. var reposList = make(RepositoryList, 0, len(repoIDs))
  453. for i, notification := range nl {
  454. if notification.Repository == nil {
  455. notification.Repository = repos[notification.RepoID]
  456. }
  457. if notification.Repository == nil {
  458. log.Error("Notification[%d]: RepoID: %d not found", notification.ID, notification.RepoID)
  459. failed = append(failed, i)
  460. continue
  461. }
  462. var found bool
  463. for _, r := range reposList {
  464. if r.ID == notification.RepoID {
  465. found = true
  466. break
  467. }
  468. }
  469. if !found {
  470. reposList = append(reposList, notification.Repository)
  471. }
  472. }
  473. return reposList, failed, nil
  474. }
  475. func (nl NotificationList) getPendingIssueIDs() []int64 {
  476. var ids = make(map[int64]struct{}, len(nl))
  477. for _, notification := range nl {
  478. if notification.Issue != nil {
  479. continue
  480. }
  481. if _, ok := ids[notification.IssueID]; !ok {
  482. ids[notification.IssueID] = struct{}{}
  483. }
  484. }
  485. return keysInt64(ids)
  486. }
  487. // LoadIssues loads issues from database
  488. func (nl NotificationList) LoadIssues() ([]int, error) {
  489. if len(nl) == 0 {
  490. return []int{}, nil
  491. }
  492. var issueIDs = nl.getPendingIssueIDs()
  493. var issues = make(map[int64]*Issue, len(issueIDs))
  494. var left = len(issueIDs)
  495. for left > 0 {
  496. var limit = defaultMaxInSize
  497. if left < limit {
  498. limit = left
  499. }
  500. rows, err := x.
  501. In("id", issueIDs[:limit]).
  502. Rows(new(Issue))
  503. if err != nil {
  504. return nil, err
  505. }
  506. for rows.Next() {
  507. var issue Issue
  508. err = rows.Scan(&issue)
  509. if err != nil {
  510. rows.Close()
  511. return nil, err
  512. }
  513. issues[issue.ID] = &issue
  514. }
  515. _ = rows.Close()
  516. left -= limit
  517. issueIDs = issueIDs[limit:]
  518. }
  519. failures := []int{}
  520. for i, notification := range nl {
  521. if notification.Issue == nil {
  522. notification.Issue = issues[notification.IssueID]
  523. if notification.Issue == nil {
  524. log.Error("Notification[%d]: IssueID: %d Not Found", notification.ID, notification.IssueID)
  525. failures = append(failures, i)
  526. continue
  527. }
  528. notification.Issue.Repo = notification.Repository
  529. }
  530. }
  531. return failures, nil
  532. }
  533. // Without returns the notification list without the failures
  534. func (nl NotificationList) Without(failures []int) NotificationList {
  535. if len(failures) == 0 {
  536. return nl
  537. }
  538. remaining := make([]*Notification, 0, len(nl))
  539. last := -1
  540. var i int
  541. for _, i = range failures {
  542. remaining = append(remaining, nl[last+1:i]...)
  543. last = i
  544. }
  545. if len(nl) > i {
  546. remaining = append(remaining, nl[i+1:]...)
  547. }
  548. return remaining
  549. }
  550. func (nl NotificationList) getPendingCommentIDs() []int64 {
  551. var ids = make(map[int64]struct{}, len(nl))
  552. for _, notification := range nl {
  553. if notification.CommentID == 0 || notification.Comment != nil {
  554. continue
  555. }
  556. if _, ok := ids[notification.CommentID]; !ok {
  557. ids[notification.CommentID] = struct{}{}
  558. }
  559. }
  560. return keysInt64(ids)
  561. }
  562. // LoadComments loads comments from database
  563. func (nl NotificationList) LoadComments() ([]int, error) {
  564. if len(nl) == 0 {
  565. return []int{}, nil
  566. }
  567. var commentIDs = nl.getPendingCommentIDs()
  568. var comments = make(map[int64]*Comment, len(commentIDs))
  569. var left = len(commentIDs)
  570. for left > 0 {
  571. var limit = defaultMaxInSize
  572. if left < limit {
  573. limit = left
  574. }
  575. rows, err := x.
  576. In("id", commentIDs[:limit]).
  577. Rows(new(Comment))
  578. if err != nil {
  579. return nil, err
  580. }
  581. for rows.Next() {
  582. var comment Comment
  583. err = rows.Scan(&comment)
  584. if err != nil {
  585. rows.Close()
  586. return nil, err
  587. }
  588. comments[comment.ID] = &comment
  589. }
  590. _ = rows.Close()
  591. left -= limit
  592. commentIDs = commentIDs[limit:]
  593. }
  594. failures := []int{}
  595. for i, notification := range nl {
  596. if notification.CommentID > 0 && notification.Comment == nil && comments[notification.CommentID] != nil {
  597. notification.Comment = comments[notification.CommentID]
  598. if notification.Comment == nil {
  599. log.Error("Notification[%d]: CommentID[%d] failed to load", notification.ID, notification.CommentID)
  600. failures = append(failures, i)
  601. continue
  602. }
  603. notification.Comment.Issue = notification.Issue
  604. }
  605. }
  606. return failures, nil
  607. }
  608. // GetNotificationCount returns the notification count for user
  609. func GetNotificationCount(user *User, status NotificationStatus) (int64, error) {
  610. return getNotificationCount(x, user, status)
  611. }
  612. func getNotificationCount(e Engine, user *User, status NotificationStatus) (count int64, err error) {
  613. count, err = e.
  614. Where("user_id = ?", user.ID).
  615. And("status = ?", status).
  616. Count(&Notification{})
  617. return
  618. }
  619. func setNotificationStatusReadIfUnread(e Engine, userID, issueID int64) error {
  620. notification, err := getIssueNotification(e, userID, issueID)
  621. // ignore if not exists
  622. if err != nil {
  623. return nil
  624. }
  625. if notification.Status != NotificationStatusUnread {
  626. return nil
  627. }
  628. notification.Status = NotificationStatusRead
  629. _, err = e.ID(notification.ID).Update(notification)
  630. return err
  631. }
  632. // SetNotificationStatus change the notification status
  633. func SetNotificationStatus(notificationID int64, user *User, status NotificationStatus) error {
  634. notification, err := getNotificationByID(x, notificationID)
  635. if err != nil {
  636. return err
  637. }
  638. if notification.UserID != user.ID {
  639. return fmt.Errorf("Can't change notification of another user: %d, %d", notification.UserID, user.ID)
  640. }
  641. notification.Status = status
  642. _, err = x.ID(notificationID).Update(notification)
  643. return err
  644. }
  645. // GetNotificationByID return notification by ID
  646. func GetNotificationByID(notificationID int64) (*Notification, error) {
  647. return getNotificationByID(x, notificationID)
  648. }
  649. func getNotificationByID(e Engine, notificationID int64) (*Notification, error) {
  650. notification := new(Notification)
  651. ok, err := e.
  652. Where("id = ?", notificationID).
  653. Get(notification)
  654. if err != nil {
  655. return nil, err
  656. }
  657. if !ok {
  658. return nil, ErrNotExist{ID: notificationID}
  659. }
  660. return notification, nil
  661. }
  662. // UpdateNotificationStatuses updates the statuses of all of a user's notifications that are of the currentStatus type to the desiredStatus
  663. func UpdateNotificationStatuses(user *User, currentStatus NotificationStatus, desiredStatus NotificationStatus) error {
  664. n := &Notification{Status: desiredStatus, UpdatedBy: user.ID}
  665. _, err := x.
  666. Where("user_id = ? AND status = ?", user.ID, currentStatus).
  667. Cols("status", "updated_by", "updated_unix").
  668. Update(n)
  669. return err
  670. }