linkace.go 2.4 KB

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