widget-custom-api.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. package glance
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "html/template"
  8. "io"
  9. "log/slog"
  10. "math"
  11. "net/http"
  12. "time"
  13. "github.com/tidwall/gjson"
  14. )
  15. var customAPIWidgetTemplate = mustParseTemplate("custom-api.html", "widget-base.html")
  16. type customAPIWidget struct {
  17. widgetBase `yaml:",inline"`
  18. URL string `yaml:"url"`
  19. Template string `yaml:"template"`
  20. Frameless bool `yaml:"frameless"`
  21. Headers map[string]string `yaml:"headers"`
  22. APIRequest *http.Request `yaml:"-"`
  23. compiledTemplate *template.Template `yaml:"-"`
  24. CompiledHTML template.HTML `yaml:"-"`
  25. }
  26. func (widget *customAPIWidget) initialize() error {
  27. widget.withTitle("Custom API").withCacheDuration(1 * time.Hour)
  28. if widget.URL == "" {
  29. return errors.New("URL is required")
  30. }
  31. if widget.Template == "" {
  32. return errors.New("template is required")
  33. }
  34. compiledTemplate, err := template.New("").Funcs(customAPITemplateFuncs).Parse(widget.Template)
  35. if err != nil {
  36. return fmt.Errorf("parsing template: %w", err)
  37. }
  38. widget.compiledTemplate = compiledTemplate
  39. req, err := http.NewRequest(http.MethodGet, widget.URL, nil)
  40. if err != nil {
  41. return err
  42. }
  43. for key, value := range widget.Headers {
  44. req.Header.Add(key, value)
  45. }
  46. widget.APIRequest = req
  47. return nil
  48. }
  49. func (widget *customAPIWidget) update(ctx context.Context) {
  50. compiledHTML, err := fetchAndParseCustomAPI(widget.APIRequest, widget.compiledTemplate)
  51. if !widget.canContinueUpdateAfterHandlingErr(err) {
  52. return
  53. }
  54. widget.CompiledHTML = compiledHTML
  55. }
  56. func (widget *customAPIWidget) Render() template.HTML {
  57. return widget.renderTemplate(widget, customAPIWidgetTemplate)
  58. }
  59. func fetchAndParseCustomAPI(req *http.Request, tmpl *template.Template) (template.HTML, error) {
  60. emptyBody := template.HTML("")
  61. resp, err := defaultHTTPClient.Do(req)
  62. if err != nil {
  63. return emptyBody, err
  64. }
  65. defer resp.Body.Close()
  66. bodyBytes, err := io.ReadAll(resp.Body)
  67. if err != nil {
  68. return emptyBody, err
  69. }
  70. body := string(bodyBytes)
  71. if !gjson.Valid(body) {
  72. truncatedBody, isTruncated := limitStringLength(body, 100)
  73. if isTruncated {
  74. truncatedBody += "... <truncated>"
  75. }
  76. slog.Error("Invalid response JSON in custom API widget", "url", req.URL.String(), "body", truncatedBody)
  77. return emptyBody, errors.New("invalid response JSON")
  78. }
  79. var templateBuffer bytes.Buffer
  80. data := customAPITemplateData{
  81. JSON: decoratedGJSONResult{gjson.Parse(body)},
  82. Response: resp,
  83. }
  84. err = tmpl.Execute(&templateBuffer, &data)
  85. if err != nil {
  86. return emptyBody, err
  87. }
  88. return template.HTML(templateBuffer.String()), nil
  89. }
  90. type decoratedGJSONResult struct {
  91. gjson.Result
  92. }
  93. type customAPITemplateData struct {
  94. JSON decoratedGJSONResult
  95. Response *http.Response
  96. }
  97. func gJsonResultArrayToDecoratedResultArray(results []gjson.Result) []decoratedGJSONResult {
  98. decoratedResults := make([]decoratedGJSONResult, len(results))
  99. for i, result := range results {
  100. decoratedResults[i] = decoratedGJSONResult{result}
  101. }
  102. return decoratedResults
  103. }
  104. func (r *decoratedGJSONResult) Exists(key string) bool {
  105. return r.Get(key).Exists()
  106. }
  107. func (r *decoratedGJSONResult) Array(key string) []decoratedGJSONResult {
  108. if key == "" {
  109. return gJsonResultArrayToDecoratedResultArray(r.Result.Array())
  110. }
  111. return gJsonResultArrayToDecoratedResultArray(r.Get(key).Array())
  112. }
  113. func (r *decoratedGJSONResult) String(key string) string {
  114. if key == "" {
  115. return r.Result.String()
  116. }
  117. return r.Get(key).String()
  118. }
  119. func (r *decoratedGJSONResult) Int(key string) int64 {
  120. if key == "" {
  121. return r.Result.Int()
  122. }
  123. return r.Get(key).Int()
  124. }
  125. func (r *decoratedGJSONResult) Float(key string) float64 {
  126. if key == "" {
  127. return r.Result.Float()
  128. }
  129. return r.Get(key).Float()
  130. }
  131. func (r *decoratedGJSONResult) Bool(key string) bool {
  132. if key == "" {
  133. return r.Result.Bool()
  134. }
  135. return r.Get(key).Bool()
  136. }
  137. var customAPITemplateFuncs = func() template.FuncMap {
  138. funcs := template.FuncMap{
  139. "toFloat": func(a int64) float64 {
  140. return float64(a)
  141. },
  142. "toInt": func(a float64) int64 {
  143. return int64(a)
  144. },
  145. "add": func(a, b float64) float64 {
  146. return a + b
  147. },
  148. "sub": func(a, b float64) float64 {
  149. return a - b
  150. },
  151. "mul": func(a, b float64) float64 {
  152. return a * b
  153. },
  154. "div": func(a, b float64) float64 {
  155. if b == 0 {
  156. return math.NaN()
  157. }
  158. return a / b
  159. },
  160. }
  161. for key, value := range globalTemplateFunctions {
  162. if _, exists := funcs[key]; !exists {
  163. funcs[key] = value
  164. }
  165. }
  166. return funcs
  167. }()