monitor.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. }
  51. func (widget *Monitor) Initialize() error {
  52. widget.withTitle("Monitor").withCacheDuration(5 * time.Minute)
  53. for i := range widget.Sites {
  54. widget.Sites[i].IconUrl, widget.Sites[i].IsSimpleIcon = toSimpleIconIfPrefixed(widget.Sites[i].IconUrl)
  55. }
  56. return nil
  57. }
  58. func (widget *Monitor) Update(ctx context.Context) {
  59. requests := make([]*feed.SiteStatusRequest, len(widget.Sites))
  60. for i := range widget.Sites {
  61. requests[i] = widget.Sites[i].SiteStatusRequest
  62. }
  63. statuses, err := feed.FetchStatusForSites(requests)
  64. if !widget.canContinueUpdateAfterHandlingErr(err) {
  65. return
  66. }
  67. for i := range widget.Sites {
  68. site := &widget.Sites[i]
  69. status := &statuses[i]
  70. site.Status = status
  71. if !status.TimedOut {
  72. site.StatusText = statusCodeToText(status.Code)
  73. site.StatusStyle = statusCodeToStyle(status.Code)
  74. }
  75. }
  76. }
  77. func (widget *Monitor) Render() template.HTML {
  78. return widget.render(widget, assets.MonitorTemplate)
  79. }