widget.go 6.2 KB

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