widget.go 6.1 KB

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