miniflux/internal/integration/espial/espial.go

81 lines
2.1 KiB
Go
Raw Permalink Normal View History

// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package espial // import "miniflux.app/v2/internal/integration/espial"
2022-04-21 04:44:47 +02:00
import (
"bytes"
"encoding/json"
2022-04-21 04:44:47 +02:00
"fmt"
"net/http"
"time"
2022-04-21 04:44:47 +02:00
"miniflux.app/v2/internal/urllib"
"miniflux.app/v2/internal/version"
2022-04-21 04:44:47 +02:00
)
const defaultClientTimeout = 10 * time.Second
2022-04-21 04:44:47 +02:00
type Client struct {
baseURL string
apiKey string
}
func NewClient(baseURL, apiKey string) *Client {
return &Client{baseURL: baseURL, apiKey: apiKey}
}
func (c *Client) CreateLink(entryURL, entryTitle, espialTags string) error {
2022-04-21 04:44:47 +02:00
if c.baseURL == "" || c.apiKey == "" {
return fmt.Errorf("espial: missing base URL or API key")
2022-04-21 04:44:47 +02:00
}
apiEndpoint, err := urllib.JoinBaseURLAndPath(c.baseURL, "/api/add")
if err != nil {
return fmt.Errorf("espial: invalid API endpoint: %v", err)
}
requestBody, err := json.Marshal(&espialDocument{
Title: entryTitle,
Url: entryURL,
2022-04-21 04:44:47 +02:00
ToRead: true,
Tags: espialTags,
})
if err != nil {
return fmt.Errorf("espial: unable to encode request body: %v", err)
2022-04-21 04:44:47 +02:00
}
request, err := http.NewRequest(http.MethodPost, apiEndpoint, bytes.NewReader(requestBody))
2022-04-21 04:44:47 +02:00
if err != nil {
return fmt.Errorf("espial: unable to create request: %v", err)
2022-04-21 04:44:47 +02:00
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("User-Agent", "Miniflux/"+version.Version)
request.Header.Set("Authorization", "ApiKey "+c.apiKey)
httpClient := &http.Client{Timeout: defaultClientTimeout}
response, err := httpClient.Do(request)
2022-04-21 04:44:47 +02:00
if err != nil {
return fmt.Errorf("espial: unable to send request: %v", err)
2022-04-21 04:44:47 +02:00
}
defer response.Body.Close()
2022-04-21 04:44:47 +02:00
if response.StatusCode != http.StatusCreated {
responseBody := new(bytes.Buffer)
responseBody.ReadFrom(response.Body)
return fmt.Errorf("espial: unable to create link: url=%s status=%d body=%s", apiEndpoint, response.StatusCode, responseBody.String())
2022-04-21 04:44:47 +02:00
}
return nil
}
type espialDocument struct {
Title string `json:"title,omitempty"`
Url string `json:"url,omitempty"`
ToRead bool `json:"toread,omitempty"`
Tags string `json:"tags,omitempty"`
}