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

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