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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  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.AutoTx(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: users[i].ID,
  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.GetUserByIDCtx(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
  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
  327. }
  328. if err = n.loadIssue(ctx); err != nil {
  329. return
  330. }
  331. if err = n.loadUser(ctx); err != nil {
  332. return
  333. }
  334. if err = n.loadComment(ctx); err != nil {
  335. return
  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.GetRepositoryByIDCtx(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.GetUserByIDCtx(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. // APIURL formats a URL-string to the notification
  406. func (n *Notification) APIURL() string {
  407. return setting.AppURL + "api/v1/notifications/threads/" + strconv.FormatInt(n.ID, 10)
  408. }
  409. // NotificationList contains a list of notifications
  410. type NotificationList []*Notification
  411. // LoadAttributes load Repo Issue User and Comment if not loaded
  412. func (nl NotificationList) LoadAttributes(ctx context.Context) error {
  413. var err error
  414. for i := 0; i < len(nl); i++ {
  415. err = nl[i].LoadAttributes(ctx)
  416. if err != nil && !issues_model.IsErrCommentNotExist(err) {
  417. return err
  418. }
  419. }
  420. return nil
  421. }
  422. func (nl NotificationList) getPendingRepoIDs() []int64 {
  423. ids := make(container.Set[int64], len(nl))
  424. for _, notification := range nl {
  425. if notification.Repository != nil {
  426. continue
  427. }
  428. ids.Add(notification.RepoID)
  429. }
  430. return ids.Values()
  431. }
  432. // LoadRepos loads repositories from database
  433. func (nl NotificationList) LoadRepos(ctx context.Context) (repo_model.RepositoryList, []int, error) {
  434. if len(nl) == 0 {
  435. return repo_model.RepositoryList{}, []int{}, nil
  436. }
  437. repoIDs := nl.getPendingRepoIDs()
  438. repos := make(map[int64]*repo_model.Repository, len(repoIDs))
  439. left := len(repoIDs)
  440. for left > 0 {
  441. limit := db.DefaultMaxInSize
  442. if left < limit {
  443. limit = left
  444. }
  445. rows, err := db.GetEngine(ctx).
  446. In("id", repoIDs[:limit]).
  447. Rows(new(repo_model.Repository))
  448. if err != nil {
  449. return nil, nil, err
  450. }
  451. for rows.Next() {
  452. var repo repo_model.Repository
  453. err = rows.Scan(&repo)
  454. if err != nil {
  455. rows.Close()
  456. return nil, nil, err
  457. }
  458. repos[repo.ID] = &repo
  459. }
  460. _ = rows.Close()
  461. left -= limit
  462. repoIDs = repoIDs[limit:]
  463. }
  464. failed := []int{}
  465. reposList := make(repo_model.RepositoryList, 0, len(repoIDs))
  466. for i, notification := range nl {
  467. if notification.Repository == nil {
  468. notification.Repository = repos[notification.RepoID]
  469. }
  470. if notification.Repository == nil {
  471. log.Error("Notification[%d]: RepoID: %d not found", notification.ID, notification.RepoID)
  472. failed = append(failed, i)
  473. continue
  474. }
  475. var found bool
  476. for _, r := range reposList {
  477. if r.ID == notification.RepoID {
  478. found = true
  479. break
  480. }
  481. }
  482. if !found {
  483. reposList = append(reposList, notification.Repository)
  484. }
  485. }
  486. return reposList, failed, nil
  487. }
  488. func (nl NotificationList) getPendingIssueIDs() []int64 {
  489. ids := make(container.Set[int64], len(nl))
  490. for _, notification := range nl {
  491. if notification.Issue != nil {
  492. continue
  493. }
  494. ids.Add(notification.IssueID)
  495. }
  496. return ids.Values()
  497. }
  498. // LoadIssues loads issues from database
  499. func (nl NotificationList) LoadIssues(ctx context.Context) ([]int, error) {
  500. if len(nl) == 0 {
  501. return []int{}, nil
  502. }
  503. issueIDs := nl.getPendingIssueIDs()
  504. issues := make(map[int64]*issues_model.Issue, len(issueIDs))
  505. left := len(issueIDs)
  506. for left > 0 {
  507. limit := db.DefaultMaxInSize
  508. if left < limit {
  509. limit = left
  510. }
  511. rows, err := db.GetEngine(ctx).
  512. In("id", issueIDs[:limit]).
  513. Rows(new(issues_model.Issue))
  514. if err != nil {
  515. return nil, err
  516. }
  517. for rows.Next() {
  518. var issue issues_model.Issue
  519. err = rows.Scan(&issue)
  520. if err != nil {
  521. rows.Close()
  522. return nil, err
  523. }
  524. issues[issue.ID] = &issue
  525. }
  526. _ = rows.Close()
  527. left -= limit
  528. issueIDs = issueIDs[limit:]
  529. }
  530. failures := []int{}
  531. for i, notification := range nl {
  532. if notification.Issue == nil {
  533. notification.Issue = issues[notification.IssueID]
  534. if notification.Issue == nil {
  535. if notification.IssueID != 0 {
  536. log.Error("Notification[%d]: IssueID: %d Not Found", notification.ID, notification.IssueID)
  537. failures = append(failures, i)
  538. }
  539. continue
  540. }
  541. notification.Issue.Repo = notification.Repository
  542. }
  543. }
  544. return failures, nil
  545. }
  546. // Without returns the notification list without the failures
  547. func (nl NotificationList) Without(failures []int) NotificationList {
  548. if len(failures) == 0 {
  549. return nl
  550. }
  551. remaining := make([]*Notification, 0, len(nl))
  552. last := -1
  553. var i int
  554. for _, i = range failures {
  555. remaining = append(remaining, nl[last+1:i]...)
  556. last = i
  557. }
  558. if len(nl) > i {
  559. remaining = append(remaining, nl[i+1:]...)
  560. }
  561. return remaining
  562. }
  563. func (nl NotificationList) getPendingCommentIDs() []int64 {
  564. ids := make(container.Set[int64], len(nl))
  565. for _, notification := range nl {
  566. if notification.CommentID == 0 || notification.Comment != nil {
  567. continue
  568. }
  569. ids.Add(notification.CommentID)
  570. }
  571. return ids.Values()
  572. }
  573. // LoadComments loads comments from database
  574. func (nl NotificationList) LoadComments(ctx context.Context) ([]int, error) {
  575. if len(nl) == 0 {
  576. return []int{}, nil
  577. }
  578. commentIDs := nl.getPendingCommentIDs()
  579. comments := make(map[int64]*issues_model.Comment, len(commentIDs))
  580. left := len(commentIDs)
  581. for left > 0 {
  582. limit := db.DefaultMaxInSize
  583. if left < limit {
  584. limit = left
  585. }
  586. rows, err := db.GetEngine(ctx).
  587. In("id", commentIDs[:limit]).
  588. Rows(new(issues_model.Comment))
  589. if err != nil {
  590. return nil, err
  591. }
  592. for rows.Next() {
  593. var comment issues_model.Comment
  594. err = rows.Scan(&comment)
  595. if err != nil {
  596. rows.Close()
  597. return nil, err
  598. }
  599. comments[comment.ID] = &comment
  600. }
  601. _ = rows.Close()
  602. left -= limit
  603. commentIDs = commentIDs[limit:]
  604. }
  605. failures := []int{}
  606. for i, notification := range nl {
  607. if notification.CommentID > 0 && notification.Comment == nil && comments[notification.CommentID] != nil {
  608. notification.Comment = comments[notification.CommentID]
  609. if notification.Comment == nil {
  610. log.Error("Notification[%d]: CommentID[%d] failed to load", notification.ID, notification.CommentID)
  611. failures = append(failures, i)
  612. continue
  613. }
  614. notification.Comment.Issue = notification.Issue
  615. }
  616. }
  617. return failures, nil
  618. }
  619. // GetNotificationCount returns the notification count for user
  620. func GetNotificationCount(ctx context.Context, user *user_model.User, status NotificationStatus) (count int64, err error) {
  621. count, err = db.GetEngine(ctx).
  622. Where("user_id = ?", user.ID).
  623. And("status = ?", status).
  624. Count(&Notification{})
  625. return count, err
  626. }
  627. // UserIDCount is a simple coalition of UserID and Count
  628. type UserIDCount struct {
  629. UserID int64
  630. Count int64
  631. }
  632. // GetUIDsAndNotificationCounts between the two provided times
  633. func GetUIDsAndNotificationCounts(since, until timeutil.TimeStamp) ([]UserIDCount, error) {
  634. sql := `SELECT user_id, count(*) AS count FROM notification ` +
  635. `WHERE user_id IN (SELECT user_id FROM notification WHERE updated_unix >= ? AND ` +
  636. `updated_unix < ?) AND status = ? GROUP BY user_id`
  637. var res []UserIDCount
  638. return res, db.GetEngine(db.DefaultContext).SQL(sql, since, until, NotificationStatusUnread).Find(&res)
  639. }
  640. // SetIssueReadBy sets issue to be read by given user.
  641. func SetIssueReadBy(ctx context.Context, issueID, userID int64) error {
  642. if err := issues_model.UpdateIssueUserByRead(userID, issueID); err != nil {
  643. return err
  644. }
  645. return setIssueNotificationStatusReadIfUnread(ctx, userID, issueID)
  646. }
  647. func setIssueNotificationStatusReadIfUnread(ctx context.Context, userID, issueID int64) error {
  648. notification, err := getIssueNotification(ctx, userID, issueID)
  649. // ignore if not exists
  650. if err != nil {
  651. return nil
  652. }
  653. if notification.Status != NotificationStatusUnread {
  654. return nil
  655. }
  656. notification.Status = NotificationStatusRead
  657. _, err = db.GetEngine(ctx).ID(notification.ID).Update(notification)
  658. return err
  659. }
  660. // SetRepoReadBy sets repo to be visited by given user.
  661. func SetRepoReadBy(ctx context.Context, userID, repoID int64) error {
  662. _, err := db.GetEngine(ctx).Where(builder.Eq{
  663. "user_id": userID,
  664. "status": NotificationStatusUnread,
  665. "source": NotificationSourceRepository,
  666. "repo_id": repoID,
  667. }).Cols("status").Update(&Notification{Status: NotificationStatusRead})
  668. return err
  669. }
  670. // SetNotificationStatus change the notification status
  671. func SetNotificationStatus(ctx context.Context, notificationID int64, user *user_model.User, status NotificationStatus) (*Notification, error) {
  672. notification, err := GetNotificationByID(ctx, notificationID)
  673. if err != nil {
  674. return notification, err
  675. }
  676. if notification.UserID != user.ID {
  677. return nil, fmt.Errorf("Can't change notification of another user: %d, %d", notification.UserID, user.ID)
  678. }
  679. notification.Status = status
  680. _, err = db.GetEngine(ctx).ID(notificationID).Update(notification)
  681. return notification, err
  682. }
  683. // GetNotificationByID return notification by ID
  684. func GetNotificationByID(ctx context.Context, notificationID int64) (*Notification, error) {
  685. notification := new(Notification)
  686. ok, err := db.GetEngine(ctx).
  687. Where("id = ?", notificationID).
  688. Get(notification)
  689. if err != nil {
  690. return nil, err
  691. }
  692. if !ok {
  693. return nil, db.ErrNotExist{Resource: "notification", ID: notificationID}
  694. }
  695. return notification, nil
  696. }
  697. // UpdateNotificationStatuses updates the statuses of all of a user's notifications that are of the currentStatus type to the desiredStatus
  698. func UpdateNotificationStatuses(ctx context.Context, user *user_model.User, currentStatus, desiredStatus NotificationStatus) error {
  699. n := &Notification{Status: desiredStatus, UpdatedBy: user.ID}
  700. _, err := db.GetEngine(ctx).
  701. Where("user_id = ? AND status = ?", user.ID, currentStatus).
  702. Cols("status", "updated_by", "updated_unix").
  703. Update(n)
  704. return err
  705. }