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

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