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

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