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

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