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

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