gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2025 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package common
  4. import (
  5. goctx "context"
  6. "errors"
  7. "sync"
  8. activities_model "code.gitea.io/gitea/models/activities"
  9. "code.gitea.io/gitea/models/db"
  10. issues_model "code.gitea.io/gitea/models/issues"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/services/context"
  13. )
  14. // StopwatchTmplInfo is a view on a stopwatch specifically for template rendering
  15. type StopwatchTmplInfo struct {
  16. IssueLink string
  17. RepoSlug string
  18. IssueIndex int64
  19. Seconds int64
  20. }
  21. func getActiveStopwatch(ctx *context.Context) *StopwatchTmplInfo {
  22. if ctx.Doer == nil {
  23. return nil
  24. }
  25. _, sw, issue, err := issues_model.HasUserStopwatch(ctx, ctx.Doer.ID)
  26. if err != nil {
  27. if !errors.Is(err, goctx.Canceled) {
  28. log.Error("Unable to HasUserStopwatch for user:%-v: %v", ctx.Doer, err)
  29. }
  30. return nil
  31. }
  32. if sw == nil || sw.ID == 0 {
  33. return nil
  34. }
  35. return &StopwatchTmplInfo{
  36. issue.Link(),
  37. issue.Repo.FullName(),
  38. issue.Index,
  39. sw.Seconds() + 1, // ensure time is never zero in ui
  40. }
  41. }
  42. func notificationUnreadCount(ctx *context.Context) int64 {
  43. if ctx.Doer == nil {
  44. return 0
  45. }
  46. count, err := db.Count[activities_model.Notification](ctx, activities_model.FindNotificationOptions{
  47. UserID: ctx.Doer.ID,
  48. Status: []activities_model.NotificationStatus{activities_model.NotificationStatusUnread},
  49. })
  50. if err != nil {
  51. if !errors.Is(err, goctx.Canceled) {
  52. log.Error("Unable to find notification for user:%-v: %v", ctx.Doer, err)
  53. }
  54. return 0
  55. }
  56. return count
  57. }
  58. type pageGlobalDataType struct {
  59. IsSigned bool
  60. IsSiteAdmin bool
  61. GetNotificationUnreadCount func() int64
  62. GetActiveStopwatch func() *StopwatchTmplInfo
  63. }
  64. func PageGlobalData(ctx *context.Context) {
  65. var data pageGlobalDataType
  66. data.IsSigned = ctx.Doer != nil
  67. data.IsSiteAdmin = ctx.Doer != nil && ctx.Doer.IsAdmin
  68. data.GetNotificationUnreadCount = sync.OnceValue(func() int64 { return notificationUnreadCount(ctx) })
  69. data.GetActiveStopwatch = sync.OnceValue(func() *StopwatchTmplInfo { return getActiveStopwatch(ctx) })
  70. ctx.Data["PageGlobalData"] = data
  71. }