espial.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package espial // import "miniflux.app/v2/internal/integration/espial"
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "net/http"
  10. "time"
  11. "miniflux.app/v2/internal/urllib"
  12. "miniflux.app/v2/internal/version"
  13. )
  14. const defaultClientTimeout = 10 * time.Second
  15. type Client struct {
  16. baseURL string
  17. apiKey string
  18. }
  19. func NewClient(baseURL, apiKey string) *Client {
  20. return &Client{baseURL: baseURL, apiKey: apiKey}
  21. }
  22. func (c *Client) CreateLink(entryURL, entryTitle, espialTags string) error {
  23. if c.baseURL == "" || c.apiKey == "" {
  24. return errors.New("espial: missing base URL or API key")
  25. }
  26. apiEndpoint, err := urllib.JoinBaseURLAndPath(c.baseURL, "/api/add")
  27. if err != nil {
  28. return fmt.Errorf("espial: invalid API endpoint: %v", err)
  29. }
  30. requestBody, err := json.Marshal(&espialDocument{
  31. Title: entryTitle,
  32. Url: entryURL,
  33. ToRead: true,
  34. Tags: espialTags,
  35. })
  36. if err != nil {
  37. return fmt.Errorf("espial: unable to encode request body: %v", err)
  38. }
  39. request, err := http.NewRequest(http.MethodPost, apiEndpoint, bytes.NewReader(requestBody))
  40. if err != nil {
  41. return fmt.Errorf("espial: unable to create request: %v", err)
  42. }
  43. request.Header.Set("Content-Type", "application/json")
  44. request.Header.Set("User-Agent", "Miniflux/"+version.Version)
  45. request.Header.Set("Authorization", "ApiKey "+c.apiKey)
  46. httpClient := &http.Client{Timeout: defaultClientTimeout}
  47. response, err := httpClient.Do(request)
  48. if err != nil {
  49. return fmt.Errorf("espial: unable to send request: %v", err)
  50. }
  51. defer response.Body.Close()
  52. if response.StatusCode != http.StatusCreated {
  53. responseBody := new(bytes.Buffer)
  54. responseBody.ReadFrom(response.Body)
  55. return fmt.Errorf("espial: unable to create link: url=%s status=%d body=%s", apiEndpoint, response.StatusCode, responseBody.String())
  56. }
  57. return nil
  58. }
  59. type espialDocument struct {
  60. Title string `json:"title,omitempty"`
  61. Url string `json:"url,omitempty"`
  62. ToRead bool `json:"toread,omitempty"`
  63. Tags string `json:"tags,omitempty"`
  64. }