espial.go 2.1 KB

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