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

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