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

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