readwise.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. // Readwise Reader API documentation: https://readwise.io/reader_api
  4. package readwise // import "miniflux.app/v2/internal/integration/readwise"
  5. import (
  6. "bytes"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "net/http"
  11. "time"
  12. "miniflux.app/v2/internal/config"
  13. "miniflux.app/v2/internal/http/client"
  14. "miniflux.app/v2/internal/version"
  15. )
  16. const (
  17. readwiseApiEndpoint = "https://readwise.io/api/v3/save/"
  18. defaultClientTimeout = 10 * time.Second
  19. )
  20. type Client struct {
  21. apiKey string
  22. }
  23. func NewClient(apiKey string) *Client {
  24. return &Client{apiKey: apiKey}
  25. }
  26. func (c *Client) CreateDocument(entryURL string) error {
  27. if c.apiKey == "" {
  28. return errors.New("readwise: missing API key")
  29. }
  30. requestBody, err := json.Marshal(&readwiseDocument{
  31. URL: entryURL,
  32. })
  33. if err != nil {
  34. return fmt.Errorf("readwise: unable to encode request body: %v", err)
  35. }
  36. request, err := http.NewRequest(http.MethodPost, readwiseApiEndpoint, bytes.NewReader(requestBody))
  37. if err != nil {
  38. return fmt.Errorf("readwise: unable to create request: %v", err)
  39. }
  40. request.Header.Set("Content-Type", "application/json")
  41. request.Header.Set("User-Agent", "Miniflux/"+version.Version)
  42. request.Header.Set("Authorization", "Token "+c.apiKey)
  43. httpClient := client.NewClientWithOptions(client.Options{Timeout: defaultClientTimeout, BlockPrivateNetworks: !config.Opts.IntegrationAllowPrivateNetworks()})
  44. response, err := httpClient.Do(request)
  45. if err != nil {
  46. return fmt.Errorf("readwise: unable to send request: %v", err)
  47. }
  48. defer response.Body.Close()
  49. if response.StatusCode >= 400 {
  50. return fmt.Errorf("readwise: unable to create document: url=%s status=%d", readwiseApiEndpoint, response.StatusCode)
  51. }
  52. return nil
  53. }
  54. type readwiseDocument struct {
  55. URL string `json:"url"`
  56. }