espial.go 1.6 KB

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