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 19KB

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