nunuxkeeper.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package nunuxkeeper // import "miniflux.app/integration/nunuxkeeper"
  4. import (
  5. "fmt"
  6. "net/url"
  7. "path"
  8. "miniflux.app/http/client"
  9. )
  10. // Document structure of a Nununx Keeper document
  11. type Document struct {
  12. Title string `json:"title,omitempty"`
  13. Origin string `json:"origin,omitempty"`
  14. Content string `json:"content,omitempty"`
  15. ContentType string `json:"contentType,omitempty"`
  16. }
  17. // Client represents an Nunux Keeper client.
  18. type Client struct {
  19. baseURL string
  20. apiKey string
  21. }
  22. // NewClient returns a new Nunux Keeepr client.
  23. func NewClient(baseURL, apiKey string) *Client {
  24. return &Client{baseURL: baseURL, apiKey: apiKey}
  25. }
  26. // AddEntry sends an entry to Nunux Keeper.
  27. func (c *Client) AddEntry(link, title, content string) error {
  28. if c.baseURL == "" || c.apiKey == "" {
  29. return fmt.Errorf("nunux-keeper: missing credentials")
  30. }
  31. doc := &Document{
  32. Title: title,
  33. Origin: link,
  34. Content: content,
  35. ContentType: "text/html",
  36. }
  37. apiURL, err := getAPIEndpoint(c.baseURL, "/v2/documents")
  38. if err != nil {
  39. return err
  40. }
  41. clt := client.New(apiURL)
  42. clt.WithCredentials("api", c.apiKey)
  43. response, err := clt.PostJSON(doc)
  44. if err != nil {
  45. return fmt.Errorf("nunux-keeper: unable to send entry: %v", err)
  46. }
  47. if response.HasServerFailure() {
  48. return fmt.Errorf("nunux-keeper: 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("nunux-keeper: invalid API endpoint: %v", err)
  56. }
  57. u.Path = path.Join(u.Path, pathURL)
  58. return u.String(), nil
  59. }