readwise.go 1.7 KB

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