miniflux/internal/integration/readwise/readwise.go

70 lines
1.7 KiB
Go
Raw Normal View History

2023-07-28 05:51:44 +02:00
// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
// Readwise Reader API documentation: https://readwise.io/reader_api
package readwise // import "miniflux.app/v2/internal/integration/readwise"
2023-07-28 05:51:44 +02:00
import (
"bytes"
"encoding/json"
2023-07-28 05:51:44 +02:00
"fmt"
"net/http"
"time"
2023-07-28 05:51:44 +02:00
"miniflux.app/v2/internal/version"
2023-07-28 05:51:44 +02:00
)
const (
readwiseApiEndpoint = "https://readwise.io/api/v3/save/"
defaultClientTimeout = 10 * time.Second
)
2023-07-28 05:51:44 +02:00
type Client struct {
apiKey string
}
func NewClient(apiKey string) *Client {
return &Client{apiKey: apiKey}
}
func (c *Client) CreateDocument(entryURL string) error {
2023-07-28 05:51:44 +02:00
if c.apiKey == "" {
return fmt.Errorf("readwise: missing API key")
2023-07-28 05:51:44 +02:00
}
requestBody, err := json.Marshal(&readwiseDocument{
URL: entryURL,
})
if err != nil {
return fmt.Errorf("readwise: unable to encode request body: %v", err)
2023-07-28 05:51:44 +02:00
}
request, err := http.NewRequest(http.MethodPost, readwiseApiEndpoint, bytes.NewReader(requestBody))
2023-07-28 05:51:44 +02:00
if err != nil {
return fmt.Errorf("readwise: unable to create request: %v", err)
2023-07-28 05:51:44 +02:00
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("User-Agent", "Miniflux/"+version.Version)
request.Header.Set("Authorization", "Token "+c.apiKey)
httpClient := &http.Client{Timeout: defaultClientTimeout}
response, err := httpClient.Do(request)
2023-07-28 05:51:44 +02:00
if err != nil {
return fmt.Errorf("readwise: unable to send request: %v", err)
2023-07-28 05:51:44 +02:00
}
defer response.Body.Close()
2023-07-28 05:51:44 +02:00
if response.StatusCode >= 400 {
return fmt.Errorf("readwise: unable to create document: url=%s status=%d", readwiseApiEndpoint, response.StatusCode)
2023-07-28 05:51:44 +02:00
}
return nil
}
type readwiseDocument struct {
URL string `json:"url"`
2023-07-28 05:51:44 +02:00
}