widget.go 6.6 KB

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