linkace.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package linkace
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "strings"
  8. "time"
  9. "miniflux.app/v2/internal/urllib"
  10. "miniflux.app/v2/internal/version"
  11. )
  12. const defaultClientTimeout = 10 * time.Second
  13. type Client struct {
  14. baseURL string
  15. apiKey string
  16. tags string
  17. private bool
  18. checkDisabled bool
  19. }
  20. func NewClient(baseURL, apiKey, tags string, private bool, checkDisabled bool) *Client {
  21. return &Client{baseURL: baseURL, apiKey: apiKey, tags: tags, private: private, checkDisabled: checkDisabled}
  22. }
  23. func (c *Client) AddURL(entryURL, entryTitle string) error {
  24. if c.baseURL == "" || c.apiKey == "" {
  25. return fmt.Errorf("linkace: missing base URL or API key")
  26. }
  27. tagsSplitFn := func(c rune) bool {
  28. return c == ',' || c == ' '
  29. }
  30. apiEndpoint, err := urllib.JoinBaseURLAndPath(c.baseURL, "/api/v2/links")
  31. if err != nil {
  32. return fmt.Errorf("linkace: invalid API endpoint: %v", err)
  33. }
  34. requestBody, err := json.Marshal(&createItemRequest{
  35. Url: entryURL,
  36. Title: entryTitle,
  37. Tags: strings.FieldsFunc(c.tags, tagsSplitFn),
  38. Private: c.private,
  39. CheckDisabled: c.checkDisabled,
  40. })
  41. if err != nil {
  42. return fmt.Errorf("linkace: unable to encode request body: %v", err)
  43. }
  44. request, err := http.NewRequest(http.MethodPost, apiEndpoint, bytes.NewReader(requestBody))
  45. if err != nil {
  46. return fmt.Errorf("linkace: unable to create request: %v", err)
  47. }
  48. request.Header.Set("Content-Type", "application/json")
  49. request.Header.Set("Accept", "application/json")
  50. request.Header.Set("User-Agent", "Miniflux/"+version.Version)
  51. request.Header.Set("Authorization", "Bearer "+c.apiKey)
  52. httpClient := &http.Client{Timeout: defaultClientTimeout}
  53. response, err := httpClient.Do(request)
  54. if err != nil {
  55. return fmt.Errorf("linkace: unable to send request: %v", err)
  56. }
  57. defer response.Body.Close()
  58. if response.StatusCode >= 400 {
  59. return fmt.Errorf("linkace: unable to create item: url=%s status=%d", apiEndpoint, response.StatusCode)
  60. }
  61. return nil
  62. }
  63. type createItemRequest struct {
  64. Title string `json:"title,omitempty"`
  65. Url string `json:"url"`
  66. Tags []string `json:"tags,omitempty"`
  67. Private bool `json:"is_private,omitempty"`
  68. CheckDisabled bool `json:"check_disabled,omitempty"`
  69. }