linkace.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. "errors"
  6. "fmt"
  7. "net/http"
  8. "strings"
  9. "miniflux.app/v2/internal/http/client"
  10. "miniflux.app/v2/internal/urllib"
  11. )
  12. type Client struct {
  13. baseURL string
  14. apiKey string
  15. tags string
  16. private bool
  17. checkDisabled bool
  18. }
  19. func NewClient(baseURL, apiKey, tags string, private bool, checkDisabled bool) *Client {
  20. return &Client{baseURL: baseURL, apiKey: apiKey, tags: tags, private: private, checkDisabled: checkDisabled}
  21. }
  22. func (c *Client) AddURL(entryURL, entryTitle string) error {
  23. if c.baseURL == "" || c.apiKey == "" {
  24. return errors.New("linkace: missing base URL or API key")
  25. }
  26. tagsSplitFn := func(c rune) bool {
  27. return c == ',' || c == ' '
  28. }
  29. apiEndpoint, err := urllib.JoinBaseURLAndPath(c.baseURL, "/api/v2/links")
  30. if err != nil {
  31. return fmt.Errorf("linkace: invalid API endpoint: %v", err)
  32. }
  33. response, err := client.NewRequestBuilder(apiEndpoint).
  34. WithMethod(http.MethodPost).
  35. WithJSON(&createItemRequest{
  36. URL: entryURL,
  37. Title: entryTitle,
  38. Tags: strings.FieldsFunc(c.tags, tagsSplitFn),
  39. Private: c.private,
  40. CheckDisabled: c.checkDisabled,
  41. }).
  42. WithHeader("Accept", "application/json").
  43. WithHeader("Authorization", "Bearer "+c.apiKey).
  44. Do()
  45. if err != nil {
  46. return fmt.Errorf("linkace: %w", err)
  47. }
  48. defer response.Body.Close()
  49. if response.StatusCode >= 400 {
  50. return fmt.Errorf("linkace: unable to create item: url=%s status=%d", apiEndpoint, response.StatusCode)
  51. }
  52. return nil
  53. }
  54. type createItemRequest struct {
  55. Title string `json:"title,omitempty"`
  56. URL string `json:"url"`
  57. Tags []string `json:"tags,omitempty"`
  58. Private bool `json:"is_private,omitempty"`
  59. CheckDisabled bool `json:"check_disabled,omitempty"`
  60. }