nunuxkeeper.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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/urllib"
  12. "miniflux.app/v2/internal/version"
  13. )
  14. const defaultClientTimeout = 10 * time.Second
  15. type Client struct {
  16. baseURL string
  17. apiKey string
  18. }
  19. func NewClient(baseURL, apiKey string) *Client {
  20. return &Client{baseURL: baseURL, apiKey: apiKey}
  21. }
  22. func (c *Client) AddEntry(entryURL, entryTitle, entryContent string) error {
  23. if c.baseURL == "" || c.apiKey == "" {
  24. return errors.New("nunux-keeper: missing base URL or API key")
  25. }
  26. apiEndpoint, err := urllib.JoinBaseURLAndPath(c.baseURL, "/v2/documents")
  27. if err != nil {
  28. return fmt.Errorf(`nunux-keeper: invalid API endpoint: %v`, err)
  29. }
  30. requestBody, err := json.Marshal(&nunuxKeeperDocument{
  31. Title: entryTitle,
  32. Origin: entryURL,
  33. Content: entryContent,
  34. ContentType: "text/html",
  35. })
  36. if err != nil {
  37. return fmt.Errorf("notion: unable to encode request body: %v", err)
  38. }
  39. request, err := http.NewRequest(http.MethodPost, apiEndpoint, bytes.NewReader(requestBody))
  40. if err != nil {
  41. return fmt.Errorf("nunux-keeper: unable to create request: %v", err)
  42. }
  43. request.SetBasicAuth("api", c.apiKey)
  44. request.Header.Set("Content-Type", "application/json")
  45. request.Header.Set("User-Agent", "Miniflux/"+version.Version)
  46. httpClient := &http.Client{Timeout: defaultClientTimeout}
  47. response, err := httpClient.Do(request)
  48. if err != nil {
  49. return fmt.Errorf("nunux-keeper: unable to send request: %v", err)
  50. }
  51. defer response.Body.Close()
  52. if response.StatusCode != http.StatusOK {
  53. return fmt.Errorf("nunux-keeper: unable to create document: url=%s status=%d", apiEndpoint, response.StatusCode)
  54. }
  55. return nil
  56. }
  57. type nunuxKeeperDocument struct {
  58. Title string `json:"title,omitempty"`
  59. Origin string `json:"origin,omitempty"`
  60. Content string `json:"content,omitempty"`
  61. ContentType string `json:"contentType,omitempty"`
  62. }