nunuxkeeper.go 2.1 KB

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