espial.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package espial // import "miniflux.app/integration/espial"
  2. import (
  3. "fmt"
  4. "net/url"
  5. "path"
  6. "miniflux.app/http/client"
  7. )
  8. // Document structure of an Espial document
  9. type Document struct {
  10. Title string `json:"title,omitempty"`
  11. Url string `json:"url,omitempty"`
  12. ToRead bool `json:"toread,omitempty"`
  13. Tags string `json:"tags,omitempty"`
  14. }
  15. // Client represents an Espial client.
  16. type Client struct {
  17. baseURL string
  18. apiKey string
  19. }
  20. // NewClient returns a new Espial client.
  21. func NewClient(baseURL, apiKey string) *Client {
  22. return &Client{baseURL: baseURL, apiKey: apiKey}
  23. }
  24. // AddEntry sends an entry to Espial.
  25. func (c *Client) AddEntry(link, title, content, tags string) error {
  26. if c.baseURL == "" || c.apiKey == "" {
  27. return fmt.Errorf("espial: missing credentials")
  28. }
  29. doc := &Document{
  30. Title: title,
  31. Url: link,
  32. ToRead: true,
  33. Tags: tags,
  34. }
  35. apiURL, err := getAPIEndpoint(c.baseURL, "/api/add")
  36. if err != nil {
  37. return err
  38. }
  39. clt := client.New(apiURL)
  40. clt.WithAuthorization("ApiKey " + c.apiKey)
  41. response, err := clt.PostJSON(doc)
  42. if err != nil {
  43. return fmt.Errorf("espial: unable to send entry: %v", err)
  44. }
  45. if response.HasServerFailure() {
  46. return fmt.Errorf("espial: unable to send entry, status=%d", response.StatusCode)
  47. }
  48. return nil
  49. }
  50. func getAPIEndpoint(baseURL, pathURL string) (string, error) {
  51. u, err := url.Parse(baseURL)
  52. if err != nil {
  53. return "", fmt.Errorf("espial: invalid API endpoint: %v", err)
  54. }
  55. u.Path = path.Join(u.Path, pathURL)
  56. return u.String(), nil
  57. }