widget.go 6.3 KB

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