widget-custom-api.go 4.4 KB

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