espial.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. "errors"
  7. "fmt"
  8. "net/http"
  9. "miniflux.app/v2/internal/http/client"
  10. "miniflux.app/v2/internal/urllib"
  11. )
  12. type Client struct {
  13. baseURL string
  14. apiKey string
  15. }
  16. func NewClient(baseURL, apiKey string) *Client {
  17. return &Client{baseURL: baseURL, apiKey: apiKey}
  18. }
  19. func (c *Client) CreateLink(entryURL, entryTitle, espialTags string) error {
  20. if c.baseURL == "" || c.apiKey == "" {
  21. return errors.New("espial: missing base URL or API key")
  22. }
  23. apiEndpoint, err := urllib.JoinBaseURLAndPath(c.baseURL, "/api/add")
  24. if err != nil {
  25. return fmt.Errorf("espial: invalid API endpoint: %v", err)
  26. }
  27. response, err := client.NewRequestBuilder(apiEndpoint).
  28. WithMethod(http.MethodPost).
  29. WithJSON(&espialDocument{
  30. Title: entryTitle,
  31. URL: entryURL,
  32. ToRead: true,
  33. Tags: espialTags,
  34. }).
  35. WithHeader("Authorization", "ApiKey "+c.apiKey).
  36. Do()
  37. if err != nil {
  38. return fmt.Errorf("espial: %w", err)
  39. }
  40. defer response.Body.Close()
  41. if response.StatusCode != http.StatusCreated {
  42. responseBody := new(bytes.Buffer)
  43. responseBody.ReadFrom(response.Body)
  44. return fmt.Errorf("espial: unable to create link: url=%s status=%d body=%s", apiEndpoint, response.StatusCode, responseBody.String())
  45. }
  46. return nil
  47. }
  48. type espialDocument struct {
  49. Title string `json:"title,omitempty"`
  50. URL string `json:"url,omitempty"`
  51. ToRead bool `json:"toread,omitempty"`
  52. Tags string `json:"tags,omitempty"`
  53. }