nunuxkeeper.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package nunuxkeeper // import "miniflux.app/v2/internal/integration/nunuxkeeper"
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "net/http"
  10. "time"
  11. "miniflux.app/v2/internal/config"
  12. "miniflux.app/v2/internal/http/client"
  13. "miniflux.app/v2/internal/urllib"
  14. "miniflux.app/v2/internal/version"
  15. )
  16. const defaultClientTimeout = 10 * time.Second
  17. type Client struct {
  18. baseURL string
  19. apiKey string
  20. }
  21. func NewClient(baseURL, apiKey string) *Client {
  22. return &Client{baseURL: baseURL, apiKey: apiKey}
  23. }
  24. func (c *Client) AddEntry(entryURL, entryTitle, entryContent string) error {
  25. if c.baseURL == "" || c.apiKey == "" {
  26. return errors.New("nunux-keeper: missing base URL or API key")
  27. }
  28. apiEndpoint, err := urllib.JoinBaseURLAndPath(c.baseURL, "/v2/documents")
  29. if err != nil {
  30. return fmt.Errorf(`nunux-keeper: invalid API endpoint: %v`, err)
  31. }
  32. requestBody, err := json.Marshal(&nunuxKeeperDocument{
  33. Title: entryTitle,
  34. Origin: entryURL,
  35. Content: entryContent,
  36. ContentType: "text/html",
  37. })
  38. if err != nil {
  39. return fmt.Errorf("nunux-keeper: unable to encode request body: %v", err)
  40. }
  41. request, err := http.NewRequest(http.MethodPost, apiEndpoint, bytes.NewReader(requestBody))
  42. if err != nil {
  43. return fmt.Errorf("nunux-keeper: unable to create request: %v", err)
  44. }
  45. request.SetBasicAuth("api", c.apiKey)
  46. request.Header.Set("Content-Type", "application/json")
  47. request.Header.Set("User-Agent", "Miniflux/"+version.Version)
  48. httpClient := client.NewClientWithOptions(client.Options{Timeout: defaultClientTimeout, BlockPrivateNetworks: !config.Opts.IntegrationAllowPrivateNetworks()})
  49. response, err := httpClient.Do(request)
  50. if err != nil {
  51. return fmt.Errorf("nunux-keeper: unable to send request: %v", err)
  52. }
  53. defer response.Body.Close()
  54. if response.StatusCode != http.StatusOK {
  55. return fmt.Errorf("nunux-keeper: unable to create document: url=%s status=%d", apiEndpoint, response.StatusCode)
  56. }
  57. return nil
  58. }
  59. type nunuxKeeperDocument struct {
  60. Title string `json:"title,omitempty"`
  61. Origin string `json:"origin,omitempty"`
  62. Content string `json:"content,omitempty"`
  63. ContentType string `json:"contentType,omitempty"`
  64. }