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.

808 lines
21 KiB

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