monitor.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package widget
  2. import (
  3. "context"
  4. "html/template"
  5. "strconv"
  6. "time"
  7. "github.com/glanceapp/glance/internal/assets"
  8. "github.com/glanceapp/glance/internal/feed"
  9. )
  10. func statusCodeToText(status int) string {
  11. if status == 200 {
  12. return "OK"
  13. }
  14. if status == 404 {
  15. return "Not Found"
  16. }
  17. if status == 403 {
  18. return "Forbidden"
  19. }
  20. if status == 401 {
  21. return "Unauthorized"
  22. }
  23. if status >= 400 {
  24. return "Client Error"
  25. }
  26. if status >= 500 {
  27. return "Server Error"
  28. }
  29. return strconv.Itoa(status)
  30. }
  31. func statusCodeToStyle(status int) string {
  32. if status == 200 {
  33. return "ok"
  34. }
  35. return "error"
  36. }
  37. type Monitor struct {
  38. widgetBase `yaml:",inline"`
  39. Sites []struct {
  40. *feed.SiteStatusRequest `yaml:",inline"`
  41. Status *feed.SiteStatus `yaml:"-"`
  42. Title string `yaml:"title"`
  43. IconUrl string `yaml:"icon"`
  44. IsSimpleIcon bool `yaml:"-"`
  45. IconSource IconSource `yaml:"-"`
  46. SameTab bool `yaml:"same-tab"`
  47. StatusText string `yaml:"-"`
  48. StatusStyle string `yaml:"-"`
  49. } `yaml:"sites"`
  50. ShowFailingOnly bool `yaml:"show-failing-only"`
  51. HasFailing bool `yaml:"-"`
  52. }
  53. func (widget *Monitor) Initialize() error {
  54. widget.withTitle("Monitor").withCacheDuration(5 * time.Minute)
  55. for i := range widget.Sites {
  56. widget.Sites[i].IconUrl, widget.Sites[i].IconSource = toRemoteResourceIconIfPrefixed(widget.Sites[i].IconUrl)
  57. widget.Sites[i].IsSimpleIcon = widget.Sites[i].IconSource == SimpleIcon
  58. }
  59. return nil
  60. }
  61. func (widget *Monitor) Update(ctx context.Context) {
  62. requests := make([]*feed.SiteStatusRequest, len(widget.Sites))
  63. for i := range widget.Sites {
  64. requests[i] = widget.Sites[i].SiteStatusRequest
  65. }
  66. statuses, err := feed.FetchStatusForSites(requests)
  67. if !widget.canContinueUpdateAfterHandlingErr(err) {
  68. return
  69. }
  70. widget.HasFailing = false
  71. for i := range widget.Sites {
  72. site := &widget.Sites[i]
  73. status := &statuses[i]
  74. site.Status = status
  75. if status.Code >= 400 || status.TimedOut || status.Error != nil {
  76. widget.HasFailing = true
  77. }
  78. if !status.TimedOut {
  79. site.StatusText = statusCodeToText(status.Code)
  80. site.StatusStyle = statusCodeToStyle(status.Code)
  81. }
  82. }
  83. }
  84. func (widget *Monitor) Render() template.HTML {
  85. return widget.render(widget, assets.MonitorTemplate)
  86. }