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

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