monitor.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. SameTab bool `yaml:"same-tab"`
  46. StatusText string `yaml:"-"`
  47. StatusStyle string `yaml:"-"`
  48. } `yaml:"sites"`
  49. Style string `yaml:"style"`
  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].IsSimpleIcon = toSimpleIconIfPrefixed(widget.Sites[i].IconUrl)
  57. }
  58. return nil
  59. }
  60. func (widget *Monitor) Update(ctx context.Context) {
  61. requests := make([]*feed.SiteStatusRequest, len(widget.Sites))
  62. for i := range widget.Sites {
  63. requests[i] = widget.Sites[i].SiteStatusRequest
  64. }
  65. statuses, err := feed.FetchStatusForSites(requests)
  66. if !widget.canContinueUpdateAfterHandlingErr(err) {
  67. return
  68. }
  69. widget.HasFailing = false
  70. for i := range widget.Sites {
  71. site := &widget.Sites[i]
  72. status := &statuses[i]
  73. site.Status = status
  74. if status.Code >= 400 || status.TimedOut || status.Error != nil {
  75. widget.HasFailing = true
  76. }
  77. if !status.TimedOut {
  78. site.StatusText = statusCodeToText(status.Code)
  79. site.StatusStyle = statusCodeToStyle(status.Code)
  80. }
  81. }
  82. }
  83. func (widget *Monitor) Render() template.HTML {
  84. return widget.render(widget, assets.MonitorTemplate)
  85. }