widget.go 6.2 KB

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