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

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