custom-api.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package widget
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "html/template"
  7. "net/http"
  8. "time"
  9. "github.com/glanceapp/glance/internal/assets"
  10. "github.com/glanceapp/glance/internal/feed"
  11. )
  12. type CustomApi struct {
  13. widgetBase `yaml:",inline"`
  14. URL OptionalEnvString `yaml:"url"`
  15. Template string `yaml:"template"`
  16. Frameless bool `yaml:"frameless"`
  17. Headers map[string]OptionalEnvString `yaml:"headers"`
  18. APIRequest *http.Request `yaml:"-"`
  19. compiledTemplate *template.Template `yaml:"-"`
  20. CompiledHTML template.HTML `yaml:"-"`
  21. }
  22. func (widget *CustomApi) Initialize() error {
  23. widget.withTitle("Custom API").withCacheDuration(1 * time.Hour)
  24. if widget.URL == "" {
  25. return errors.New("URL is required for the custom API widget")
  26. }
  27. if widget.Template == "" {
  28. return errors.New("template is required for the custom API widget")
  29. }
  30. compiledTemplate, err := template.New("").Funcs(feed.CustomAPITemplateFuncs).Parse(widget.Template)
  31. if err != nil {
  32. return fmt.Errorf("failed parsing custom API widget template: %w", err)
  33. }
  34. widget.compiledTemplate = compiledTemplate
  35. req, err := http.NewRequest(http.MethodGet, widget.URL.String(), nil)
  36. if err != nil {
  37. return err
  38. }
  39. for key, value := range widget.Headers {
  40. req.Header.Add(key, value.String())
  41. }
  42. widget.APIRequest = req
  43. return nil
  44. }
  45. func (widget *CustomApi) Update(ctx context.Context) {
  46. compiledHTML, err := feed.FetchAndParseCustomAPI(widget.APIRequest, widget.compiledTemplate)
  47. if !widget.canContinueUpdateAfterHandlingErr(err) {
  48. return
  49. }
  50. widget.CompiledHTML = compiledHTML
  51. }
  52. func (widget *CustomApi) Render() template.HTML {
  53. return widget.render(widget, assets.CustomAPITemplate)
  54. }