Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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. "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. UpdatedAfterUnix int64
  64. UpdatedBeforeUnix int64
  65. }
  66. // ToCond will convert each condition into a xorm-Cond
  67. func (opts *FindNotificationOptions) ToCond() builder.Cond {
  68. cond := builder.NewCond()
  69. if opts.UserID != 0 {
  70. cond = cond.And(builder.Eq{"notification.user_id": opts.UserID})
  71. }
  72. if opts.RepoID != 0 {
  73. cond = cond.And(builder.Eq{"notification.repo_id": opts.RepoID})
  74. }
  75. if opts.IssueID != 0 {
  76. cond = cond.And(builder.Eq{"notification.issue_id": opts.IssueID})
  77. }
  78. if len(opts.Status) > 0 {
  79. cond = cond.And(builder.In("notification.status", opts.Status))
  80. }
  81. if opts.UpdatedAfterUnix != 0 {
  82. cond = cond.And(builder.Gte{"notification.updated_unix": opts.UpdatedAfterUnix})
  83. }
  84. if opts.UpdatedBeforeUnix != 0 {
  85. cond = cond.And(builder.Lte{"notification.updated_unix": opts.UpdatedBeforeUnix})
  86. }
  87. return cond
  88. }
  89. // ToSession will convert the given options to a xorm Session by using the conditions from ToCond and joining with issue table if required
  90. func (opts *FindNotificationOptions) ToSession(e Engine) *xorm.Session {
  91. sess := e.Where(opts.ToCond())
  92. if opts.Page != 0 {
  93. sess = opts.setSessionPagination(sess)
  94. }
  95. return sess
  96. }
  97. func getNotifications(e Engine, options FindNotificationOptions) (nl NotificationList, err error) {
  98. err = options.ToSession(e).OrderBy("notification.updated_unix DESC").Find(&nl)
  99. return
  100. }
  101. // GetNotifications returns all notifications that fit to the given options.
  102. func GetNotifications(opts FindNotificationOptions) (NotificationList, error) {
  103. return getNotifications(x, opts)
  104. }
  105. // CreateRepoTransferNotification creates notification for the user a repository was transferred to
  106. func CreateRepoTransferNotification(doer, newOwner *User, repo *Repository) error {
  107. sess := x.NewSession()
  108. defer sess.Close()
  109. if err := sess.Begin(); err != nil {
  110. return err
  111. }
  112. var notify []*Notification
  113. if newOwner.IsOrganization() {
  114. users, err := getUsersWhoCanCreateOrgRepo(sess, newOwner.ID)
  115. if err != nil || len(users) == 0 {
  116. return err
  117. }
  118. for i := range users {
  119. notify = append(notify, &Notification{
  120. UserID: users[i].ID,
  121. RepoID: repo.ID,
  122. Status: NotificationStatusUnread,
  123. UpdatedBy: doer.ID,
  124. Source: NotificationSourceRepository,
  125. })
  126. }
  127. } else {
  128. notify = []*Notification{{
  129. UserID: newOwner.ID,
  130. RepoID: repo.ID,
  131. Status: NotificationStatusUnread,
  132. UpdatedBy: doer.ID,
  133. Source: NotificationSourceRepository,
  134. }}
  135. }
  136. if _, err := sess.InsertMulti(notify); err != nil {
  137. return err
  138. }
  139. return sess.Commit()
  140. }
  141. // CreateOrUpdateIssueNotifications creates an issue notification
  142. // for each watcher, or updates it if already exists
  143. // receiverID > 0 just send to reciver, else send to all watcher
  144. func CreateOrUpdateIssueNotifications(issueID, commentID, notificationAuthorID, receiverID int64) error {
  145. sess := x.NewSession()
  146. defer sess.Close()
  147. if err := sess.Begin(); err != nil {
  148. return err
  149. }
  150. if err := createOrUpdateIssueNotifications(sess, issueID, commentID, notificationAuthorID, receiverID); err != nil {
  151. return err
  152. }
  153. return sess.Commit()
  154. }
  155. func createOrUpdateIssueNotifications(e Engine, issueID, commentID, notificationAuthorID, receiverID int64) error {
  156. // init
  157. var toNotify map[int64]struct{}
  158. notifications, err := getNotificationsByIssueID(e, issueID)
  159. if err != nil {
  160. return err
  161. }
  162. issue, err := getIssueByID(e, issueID)
  163. if err != nil {
  164. return err
  165. }
  166. if receiverID > 0 {
  167. toNotify = make(map[int64]struct{}, 1)
  168. toNotify[receiverID] = struct{}{}
  169. } else {
  170. toNotify = make(map[int64]struct{}, 32)
  171. issueWatches, err := getIssueWatchersIDs(e, issueID, true)
  172. if err != nil {
  173. return err
  174. }
  175. for _, id := range issueWatches {
  176. toNotify[id] = struct{}{}
  177. }
  178. repoWatches, err := getRepoWatchersIDs(e, issue.RepoID)
  179. if err != nil {
  180. return err
  181. }
  182. for _, id := range repoWatches {
  183. toNotify[id] = struct{}{}
  184. }
  185. issueParticipants, err := issue.getParticipantIDsByIssue(e)
  186. if err != nil {
  187. return err
  188. }
  189. for _, id := range issueParticipants {
  190. toNotify[id] = struct{}{}
  191. }
  192. // dont notify user who cause notification
  193. delete(toNotify, notificationAuthorID)
  194. // explicit unwatch on issue
  195. issueUnWatches, err := getIssueWatchersIDs(e, issueID, false)
  196. if err != nil {
  197. return err
  198. }
  199. for _, id := range issueUnWatches {
  200. delete(toNotify, id)
  201. }
  202. }
  203. err = issue.loadRepo(e)
  204. if err != nil {
  205. return err
  206. }
  207. // notify
  208. for userID := range toNotify {
  209. issue.Repo.Units = nil
  210. user, err := getUserByID(e, userID)
  211. if err != nil {
  212. if IsErrUserNotExist(err) {
  213. continue
  214. }
  215. return err
  216. }
  217. if issue.IsPull && !issue.Repo.checkUnitUser(e, user, UnitTypePullRequests) {
  218. continue
  219. }
  220. if !issue.IsPull && !issue.Repo.checkUnitUser(e, user, UnitTypeIssues) {
  221. continue
  222. }
  223. if notificationExists(notifications, issue.ID, userID) {
  224. if err = updateIssueNotification(e, userID, issue.ID, commentID, notificationAuthorID); err != nil {
  225. return err
  226. }
  227. continue
  228. }
  229. if err = createIssueNotification(e, userID, issue, commentID, notificationAuthorID); err != nil {
  230. return err
  231. }
  232. }
  233. return nil
  234. }
  235. func getNotificationsByIssueID(e Engine, issueID int64) (notifications []*Notification, err error) {
  236. err = e.
  237. Where("issue_id = ?", issueID).
  238. Find(&notifications)
  239. return
  240. }
  241. func notificationExists(notifications []*Notification, issueID, userID int64) bool {
  242. for _, notification := range notifications {
  243. if notification.IssueID == issueID && notification.UserID == userID {
  244. return true
  245. }
  246. }
  247. return false
  248. }
  249. func createIssueNotification(e Engine, userID int64, issue *Issue, commentID, updatedByID int64) error {
  250. notification := &Notification{
  251. UserID: userID,
  252. RepoID: issue.RepoID,
  253. Status: NotificationStatusUnread,
  254. IssueID: issue.ID,
  255. CommentID: commentID,
  256. UpdatedBy: updatedByID,
  257. }
  258. if issue.IsPull {
  259. notification.Source = NotificationSourcePullRequest
  260. } else {
  261. notification.Source = NotificationSourceIssue
  262. }
  263. _, err := e.Insert(notification)
  264. return err
  265. }
  266. func updateIssueNotification(e Engine, userID, issueID, commentID, updatedByID int64) error {
  267. notification, err := getIssueNotification(e, userID, issueID)
  268. if err != nil {
  269. return err
  270. }
  271. // NOTICE: Only update comment id when the before notification on this issue is read, otherwise you may miss some old comments.
  272. // But we need update update_by so that the notification will be reorder
  273. var cols []string
  274. if notification.Status == NotificationStatusRead {
  275. notification.Status = NotificationStatusUnread
  276. notification.CommentID = commentID
  277. cols = []string{"status", "update_by", "comment_id"}
  278. } else {
  279. notification.UpdatedBy = updatedByID
  280. cols = []string{"update_by"}
  281. }
  282. _, err = e.ID(notification.ID).Cols(cols...).Update(notification)
  283. return err
  284. }
  285. func getIssueNotification(e Engine, userID, issueID int64) (*Notification, error) {
  286. notification := new(Notification)
  287. _, err := e.
  288. Where("user_id = ?", userID).
  289. And("issue_id = ?", issueID).
  290. Get(notification)
  291. return notification, err
  292. }
  293. // NotificationsForUser returns notifications for a given user and status
  294. func NotificationsForUser(user *User, statuses []NotificationStatus, page, perPage int) (NotificationList, error) {
  295. return notificationsForUser(x, user, statuses, page, perPage)
  296. }
  297. func notificationsForUser(e Engine, user *User, statuses []NotificationStatus, page, perPage int) (notifications []*Notification, err error) {
  298. if len(statuses) == 0 {
  299. return
  300. }
  301. sess := e.
  302. Where("user_id = ?", user.ID).
  303. In("status", statuses).
  304. OrderBy("updated_unix DESC")
  305. if page > 0 && perPage > 0 {
  306. sess.Limit(perPage, (page-1)*perPage)
  307. }
  308. err = sess.Find(&notifications)
  309. return
  310. }
  311. // CountUnread count unread notifications for a user
  312. func CountUnread(user *User) int64 {
  313. return countUnread(x, user.ID)
  314. }
  315. func countUnread(e Engine, userID int64) int64 {
  316. exist, err := e.Where("user_id = ?", userID).And("status = ?", NotificationStatusUnread).Count(new(Notification))
  317. if err != nil {
  318. log.Error("countUnread", err)
  319. return 0
  320. }
  321. return exist
  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 && n.IssueID != 0 {
  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. switch n.Source {
  390. case NotificationSourceIssue, NotificationSourcePullRequest:
  391. if n.Comment != nil {
  392. return n.Comment.HTMLURL()
  393. }
  394. return n.Issue.HTMLURL()
  395. case NotificationSourceCommit:
  396. return n.Repository.HTMLURL() + "/commit/" + n.CommitID
  397. case NotificationSourceRepository:
  398. return n.Repository.HTMLURL()
  399. }
  400. return ""
  401. }
  402. // APIURL formats a URL-string to the notification
  403. func (n *Notification) APIURL() string {
  404. return setting.AppURL + "api/v1/notifications/threads/" + strconv.FormatInt(n.ID, 10)
  405. }
  406. // NotificationList contains a list of notifications
  407. type NotificationList []*Notification
  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. 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. repoIDs := nl.getPendingRepoIDs()
  436. repos := make(map[int64]*Repository, len(repoIDs))
  437. left := len(repoIDs)
  438. for left > 0 {
  439. 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. 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. 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. issueIDs := nl.getPendingIssueIDs()
  504. issues := make(map[int64]*Issue, len(issueIDs))
  505. left := len(issueIDs)
  506. for left > 0 {
  507. 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. if notification.IssueID != 0 {
  536. log.Error("Notification[%d]: IssueID: %d Not Found", notification.ID, notification.IssueID)
  537. failures = append(failures, i)
  538. }
  539. continue
  540. }
  541. notification.Issue.Repo = notification.Repository
  542. }
  543. }
  544. return failures, nil
  545. }
  546. // Without returns the notification list without the failures
  547. func (nl NotificationList) Without(failures []int) NotificationList {
  548. if len(failures) == 0 {
  549. return nl
  550. }
  551. remaining := make([]*Notification, 0, len(nl))
  552. last := -1
  553. var i int
  554. for _, i = range failures {
  555. remaining = append(remaining, nl[last+1:i]...)
  556. last = i
  557. }
  558. if len(nl) > i {
  559. remaining = append(remaining, nl[i+1:]...)
  560. }
  561. return remaining
  562. }
  563. func (nl NotificationList) getPendingCommentIDs() []int64 {
  564. ids := make(map[int64]struct{}, len(nl))
  565. for _, notification := range nl {
  566. if notification.CommentID == 0 || notification.Comment != nil {
  567. continue
  568. }
  569. if _, ok := ids[notification.CommentID]; !ok {
  570. ids[notification.CommentID] = struct{}{}
  571. }
  572. }
  573. return keysInt64(ids)
  574. }
  575. // LoadComments loads comments from database
  576. func (nl NotificationList) LoadComments() ([]int, error) {
  577. if len(nl) == 0 {
  578. return []int{}, nil
  579. }
  580. commentIDs := nl.getPendingCommentIDs()
  581. comments := make(map[int64]*Comment, len(commentIDs))
  582. left := len(commentIDs)
  583. for left > 0 {
  584. limit := defaultMaxInSize
  585. if left < limit {
  586. limit = left
  587. }
  588. rows, err := x.
  589. In("id", commentIDs[:limit]).
  590. Rows(new(Comment))
  591. if err != nil {
  592. return nil, err
  593. }
  594. for rows.Next() {
  595. var comment Comment
  596. err = rows.Scan(&comment)
  597. if err != nil {
  598. rows.Close()
  599. return nil, err
  600. }
  601. comments[comment.ID] = &comment
  602. }
  603. _ = rows.Close()
  604. left -= limit
  605. commentIDs = commentIDs[limit:]
  606. }
  607. failures := []int{}
  608. for i, notification := range nl {
  609. if notification.CommentID > 0 && notification.Comment == nil && comments[notification.CommentID] != nil {
  610. notification.Comment = comments[notification.CommentID]
  611. if notification.Comment == nil {
  612. log.Error("Notification[%d]: CommentID[%d] failed to load", notification.ID, notification.CommentID)
  613. failures = append(failures, i)
  614. continue
  615. }
  616. notification.Comment.Issue = notification.Issue
  617. }
  618. }
  619. return failures, nil
  620. }
  621. // GetNotificationCount returns the notification count for user
  622. func GetNotificationCount(user *User, status NotificationStatus) (int64, error) {
  623. return getNotificationCount(x, user, status)
  624. }
  625. func getNotificationCount(e Engine, user *User, status NotificationStatus) (count int64, err error) {
  626. count, err = e.
  627. Where("user_id = ?", user.ID).
  628. And("status = ?", status).
  629. Count(&Notification{})
  630. return
  631. }
  632. // UserIDCount is a simple coalition of UserID and Count
  633. type UserIDCount struct {
  634. UserID int64
  635. Count int64
  636. }
  637. // GetUIDsAndNotificationCounts between the two provided times
  638. func GetUIDsAndNotificationCounts(since, until timeutil.TimeStamp) ([]UserIDCount, error) {
  639. sql := `SELECT user_id, count(*) AS count FROM notification ` +
  640. `WHERE user_id IN (SELECT user_id FROM notification WHERE updated_unix >= ? AND ` +
  641. `updated_unix < ?) AND status = ? GROUP BY user_id`
  642. var res []UserIDCount
  643. return res, x.SQL(sql, since, until, NotificationStatusUnread).Find(&res)
  644. }
  645. func setIssueNotificationStatusReadIfUnread(e Engine, userID, issueID int64) error {
  646. notification, err := getIssueNotification(e, userID, issueID)
  647. // ignore if not exists
  648. if err != nil {
  649. return nil
  650. }
  651. if notification.Status != NotificationStatusUnread {
  652. return nil
  653. }
  654. notification.Status = NotificationStatusRead
  655. _, err = e.ID(notification.ID).Update(notification)
  656. return err
  657. }
  658. func setRepoNotificationStatusReadIfUnread(e Engine, userID, repoID int64) error {
  659. _, err := e.Where(builder.Eq{
  660. "user_id": userID,
  661. "status": NotificationStatusUnread,
  662. "source": NotificationSourceRepository,
  663. "repo_id": repoID,
  664. }).Cols("status").Update(&Notification{Status: NotificationStatusRead})
  665. return err
  666. }
  667. // SetNotificationStatus change the notification status
  668. func SetNotificationStatus(notificationID int64, user *User, status NotificationStatus) error {
  669. notification, err := getNotificationByID(x, notificationID)
  670. if err != nil {
  671. return err
  672. }
  673. if notification.UserID != user.ID {
  674. return fmt.Errorf("Can't change notification of another user: %d, %d", notification.UserID, user.ID)
  675. }
  676. notification.Status = status
  677. _, err = x.ID(notificationID).Update(notification)
  678. return err
  679. }
  680. // GetNotificationByID return notification by ID
  681. func GetNotificationByID(notificationID int64) (*Notification, error) {
  682. return getNotificationByID(x, notificationID)
  683. }
  684. func getNotificationByID(e Engine, notificationID int64) (*Notification, error) {
  685. notification := new(Notification)
  686. ok, err := e.
  687. Where("id = ?", notificationID).
  688. Get(notification)
  689. if err != nil {
  690. return nil, err
  691. }
  692. if !ok {
  693. return nil, ErrNotExist{ID: notificationID}
  694. }
  695. return notification, nil
  696. }
  697. // UpdateNotificationStatuses updates the statuses of all of a user's notifications that are of the currentStatus type to the desiredStatus
  698. func UpdateNotificationStatuses(user *User, currentStatus, desiredStatus NotificationStatus) error {
  699. n := &Notification{Status: desiredStatus, UpdatedBy: user.ID}
  700. _, err := x.
  701. Where("user_id = ? AND status = ?", user.ID, currentStatus).
  702. Cols("status", "updated_by", "updated_unix").
  703. Update(n)
  704. return err
  705. }