readwise.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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/version"
  13. )
  14. const (
  15. readwiseApiEndpoint = "https://readwise.io/api/v3/save/"
  16. defaultClientTimeout = 10 * time.Second
  17. )
  18. type Client struct {
  19. apiKey string
  20. }
  21. func NewClient(apiKey string) *Client {
  22. return &Client{apiKey: apiKey}
  23. }
  24. func (c *Client) CreateDocument(entryURL string) error {
  25. if c.apiKey == "" {
  26. return errors.New("readwise: missing API key")
  27. }
  28. requestBody, err := json.Marshal(&readwiseDocument{
  29. URL: entryURL,
  30. })
  31. if err != nil {
  32. return fmt.Errorf("readwise: unable to encode request body: %v", err)
  33. }
  34. request, err := http.NewRequest(http.MethodPost, readwiseApiEndpoint, bytes.NewReader(requestBody))
  35. if err != nil {
  36. return fmt.Errorf("readwise: unable to create request: %v", err)
  37. }
  38. request.Header.Set("Content-Type", "application/json")
  39. request.Header.Set("User-Agent", "Miniflux/"+version.Version)
  40. request.Header.Set("Authorization", "Token "+c.apiKey)
  41. httpClient := &http.Client{Timeout: defaultClientTimeout}
  42. response, err := httpClient.Do(request)
  43. if err != nil {
  44. return fmt.Errorf("readwise: unable to send request: %v", err)
  45. }
  46. defer response.Body.Close()
  47. if response.StatusCode >= 400 {
  48. return fmt.Errorf("readwise: unable to create document: url=%s status=%d", readwiseApiEndpoint, response.StatusCode)
  49. }
  50. return nil
  51. }
  52. type readwiseDocument struct {
  53. URL string `json:"url"`
  54. }