linkding.go 2.4 KB

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