widget.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. package widget
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "html/template"
  8. "log/slog"
  9. "math"
  10. "time"
  11. "github.com/glanceapp/glance/internal/feed"
  12. "gopkg.in/yaml.v3"
  13. )
  14. func New(widgetType string) (Widget, error) {
  15. switch widgetType {
  16. case "calendar":
  17. return &Calendar{}, nil
  18. case "weather":
  19. return &Weather{}, nil
  20. case "bookmarks":
  21. return &Bookmarks{}, nil
  22. case "iframe":
  23. return &IFrame{}, nil
  24. case "hacker-news":
  25. return &HackerNews{}, nil
  26. case "releases":
  27. return &Releases{}, nil
  28. case "videos":
  29. return &Videos{}, nil
  30. case "stocks":
  31. return &Stocks{}, nil
  32. case "reddit":
  33. return &Reddit{}, nil
  34. case "rss":
  35. return &RSS{}, nil
  36. case "monitor":
  37. return &Monitor{}, nil
  38. case "twitch-top-games":
  39. return &TwitchGames{}, nil
  40. case "twitch-channels":
  41. return &TwitchChannels{}, nil
  42. case "change-detection":
  43. return &ChangeDetection{}, nil
  44. case "repository":
  45. return &Repository{}, nil
  46. default:
  47. return nil, fmt.Errorf("unknown widget type: %s", widgetType)
  48. }
  49. }
  50. type Widgets []Widget
  51. func (w *Widgets) UnmarshalYAML(node *yaml.Node) error {
  52. var nodes []yaml.Node
  53. if err := node.Decode(&nodes); err != nil {
  54. return err
  55. }
  56. for _, node := range nodes {
  57. meta := struct {
  58. Type string `yaml:"type"`
  59. }{}
  60. if err := node.Decode(&meta); err != nil {
  61. return err
  62. }
  63. widget, err := New(meta.Type)
  64. if err != nil {
  65. return err
  66. }
  67. if err = node.Decode(widget); err != nil {
  68. return err
  69. }
  70. if err = widget.Initialize(); err != nil {
  71. return err
  72. }
  73. *w = append(*w, widget)
  74. }
  75. return nil
  76. }
  77. type Widget interface {
  78. Initialize() error
  79. RequiresUpdate(*time.Time) bool
  80. Update(context.Context)
  81. Render() template.HTML
  82. GetType() string
  83. }
  84. type cacheType int
  85. const (
  86. cacheTypeInfinite cacheType = iota
  87. cacheTypeDuration
  88. cacheTypeOnTheHour
  89. )
  90. type widgetBase struct {
  91. Type string `yaml:"type"`
  92. Title string `yaml:"title"`
  93. CustomCacheDuration DurationField `yaml:"cache"`
  94. ContentAvailable bool `yaml:"-"`
  95. Error error `yaml:"-"`
  96. Notice error `yaml:"-"`
  97. templateBuffer bytes.Buffer `yaml:"-"`
  98. cacheDuration time.Duration `yaml:"-"`
  99. cacheType cacheType `yaml:"-"`
  100. nextUpdate time.Time `yaml:"-"`
  101. updateRetriedTimes int `yaml:"-"`
  102. }
  103. func (w *widgetBase) RequiresUpdate(now *time.Time) bool {
  104. if w.cacheType == cacheTypeInfinite {
  105. return false
  106. }
  107. if w.nextUpdate.IsZero() {
  108. return true
  109. }
  110. return now.After(w.nextUpdate)
  111. }
  112. func (w *widgetBase) Update(ctx context.Context) {
  113. }
  114. func (w *widgetBase) GetType() string {
  115. return w.Type
  116. }
  117. func (w *widgetBase) render(data any, t *template.Template) template.HTML {
  118. w.templateBuffer.Reset()
  119. err := t.Execute(&w.templateBuffer, data)
  120. if err != nil {
  121. w.ContentAvailable = false
  122. w.Error = err
  123. slog.Error("failed to render template", "error", err)
  124. // need to immediately re-render with the error,
  125. // otherwise risk breaking the page since the widget
  126. // will likely be partially rendered with tags not closed.
  127. w.templateBuffer.Reset()
  128. err2 := t.Execute(&w.templateBuffer, data)
  129. if err2 != nil {
  130. slog.Error("failed to render error within widget", "error", err2, "initial_error", err)
  131. w.templateBuffer.Reset()
  132. // TODO: add some kind of a generic widget error template when the widget
  133. // failed to render, and we also failed to re-render the widget with the error
  134. }
  135. }
  136. return template.HTML(w.templateBuffer.String())
  137. }
  138. func (w *widgetBase) withTitle(title string) *widgetBase {
  139. if w.Title == "" {
  140. w.Title = title
  141. }
  142. return w
  143. }
  144. func (w *widgetBase) withCacheDuration(duration time.Duration) *widgetBase {
  145. w.cacheType = cacheTypeDuration
  146. if duration == -1 || w.CustomCacheDuration == 0 {
  147. w.cacheDuration = duration
  148. } else {
  149. w.cacheDuration = time.Duration(w.CustomCacheDuration)
  150. }
  151. return w
  152. }
  153. func (w *widgetBase) withCacheOnTheHour() *widgetBase {
  154. w.cacheType = cacheTypeOnTheHour
  155. return w
  156. }
  157. func (w *widgetBase) withNotice(err error) *widgetBase {
  158. w.Notice = err
  159. return w
  160. }
  161. func (w *widgetBase) withError(err error) *widgetBase {
  162. if err == nil && !w.ContentAvailable {
  163. w.ContentAvailable = true
  164. }
  165. w.Error = err
  166. return w
  167. }
  168. func (w *widgetBase) canContinueUpdateAfterHandlingErr(err error) bool {
  169. // TODO: needs covering more edge cases.
  170. // if there's partial content and we update early there's a chance
  171. // the early update returns even less content than the initial update.
  172. // need some kind of mechanism that tells us whether we should update early
  173. // or not depending on the number of things that failed during the initial
  174. // and subsequent update and how they failed - ie whether it was server
  175. // error (like gateway timeout, do retry early) or client error (like
  176. // hitting a rate limit, don't retry early). will require reworking a
  177. // good amount of code in the feed package and probably having a custom
  178. // error type that holds more information because screw wrapping errors.
  179. // alternatively have a resource cache and only refetch the failed resources,
  180. // then rebuild the widget.
  181. if err != nil {
  182. w.scheduleEarlyUpdate()
  183. if !errors.Is(err, feed.ErrPartialContent) {
  184. w.withError(err)
  185. w.withNotice(nil)
  186. return false
  187. }
  188. w.withError(nil)
  189. w.withNotice(err)
  190. return true
  191. }
  192. w.withNotice(nil)
  193. w.withError(nil)
  194. w.scheduleNextUpdate()
  195. return true
  196. }
  197. func (w *widgetBase) getNextUpdateTime() time.Time {
  198. now := time.Now()
  199. if w.cacheType == cacheTypeDuration {
  200. return now.Add(w.cacheDuration)
  201. }
  202. if w.cacheType == cacheTypeOnTheHour {
  203. return now.Add(time.Duration(
  204. ((60-now.Minute())*60)-now.Second(),
  205. ) * time.Second)
  206. }
  207. return time.Time{}
  208. }
  209. func (w *widgetBase) scheduleNextUpdate() *widgetBase {
  210. w.nextUpdate = w.getNextUpdateTime()
  211. w.updateRetriedTimes = 0
  212. return w
  213. }
  214. func (w *widgetBase) scheduleEarlyUpdate() *widgetBase {
  215. w.updateRetriedTimes++
  216. if w.updateRetriedTimes > 5 {
  217. w.updateRetriedTimes = 5
  218. }
  219. nextEarlyUpdate := time.Now().Add(time.Duration(math.Pow(float64(w.updateRetriedTimes), 2)) * time.Minute)
  220. nextUsualUpdate := w.getNextUpdateTime()
  221. if nextEarlyUpdate.After(nextUsualUpdate) {
  222. w.nextUpdate = nextUsualUpdate
  223. } else {
  224. w.nextUpdate = nextEarlyUpdate
  225. }
  226. return w
  227. }