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

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