linkding.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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/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. unread bool
  21. }
  22. func NewClient(baseURL, apiKey, tags string, unread bool) *Client {
  23. return &Client{baseURL: baseURL, apiKey: apiKey, tags: tags, unread: unread}
  24. }
  25. func (c *Client) CreateBookmark(entryURL, entryTitle string) error {
  26. if c.baseURL == "" || c.apiKey == "" {
  27. return errors.New("linkding: missing base URL or API key")
  28. }
  29. tagsSplitFn := func(c rune) bool {
  30. return c == ',' || c == ' '
  31. }
  32. apiEndpoint, err := urllib.JoinBaseURLAndPath(c.baseURL, "/api/bookmarks/")
  33. if err != nil {
  34. return fmt.Errorf(`linkding: invalid API endpoint: %v`, err)
  35. }
  36. requestBody, err := json.Marshal(&linkdingBookmark{
  37. Url: entryURL,
  38. Title: entryTitle,
  39. TagNames: strings.FieldsFunc(c.tags, tagsSplitFn),
  40. Unread: c.unread,
  41. })
  42. if err != nil {
  43. return fmt.Errorf("linkding: unable to encode request body: %v", err)
  44. }
  45. request, err := http.NewRequest(http.MethodPost, apiEndpoint, bytes.NewReader(requestBody))
  46. if err != nil {
  47. return fmt.Errorf("linkding: unable to create request: %v", err)
  48. }
  49. request.Header.Set("Content-Type", "application/json")
  50. request.Header.Set("User-Agent", "Miniflux/"+version.Version)
  51. request.Header.Set("Authorization", "Token "+c.apiKey)
  52. httpClient := &http.Client{Timeout: defaultClientTimeout}
  53. response, err := httpClient.Do(request)
  54. if err != nil {
  55. return fmt.Errorf("linkding: unable to send request: %v", err)
  56. }
  57. defer response.Body.Close()
  58. if response.StatusCode >= 400 {
  59. return fmt.Errorf("linkding: unable to create bookmark: url=%s status=%d", apiEndpoint, response.StatusCode)
  60. }
  61. return nil
  62. }
  63. type linkdingBookmark struct {
  64. Url string `json:"url,omitempty"`
  65. Title string `json:"title,omitempty"`
  66. TagNames []string `json:"tag_names,omitempty"`
  67. Unread bool `json:"unread,omitempty"`
  68. }