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

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