widget.go 6.1 KB

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