選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

notification.go 22KB

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