linkding.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. "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. unread bool
  17. }
  18. func NewClient(baseURL, apiKey, tags string, unread bool) *Client {
  19. return &Client{baseURL: baseURL, apiKey: apiKey, tags: tags, unread: unread}
  20. }
  21. func (c *Client) CreateBookmark(entryURL, entryTitle string) error {
  22. if c.baseURL == "" || c.apiKey == "" {
  23. return errors.New("linkding: missing base URL or API key")
  24. }
  25. tagsSplitFn := func(c rune) bool {
  26. return c == ',' || c == ' '
  27. }
  28. apiEndpoint, err := urllib.JoinBaseURLAndPath(c.baseURL, "/api/bookmarks/")
  29. if err != nil {
  30. return fmt.Errorf(`linkding: invalid API endpoint: %v`, err)
  31. }
  32. response, err := client.NewRequestBuilder(apiEndpoint).
  33. WithMethod(http.MethodPost).
  34. WithJSON(&linkdingBookmark{
  35. URL: entryURL,
  36. Title: entryTitle,
  37. TagNames: strings.FieldsFunc(c.tags, tagsSplitFn),
  38. Unread: c.unread,
  39. }).
  40. WithHeader("Authorization", "Token "+c.apiKey).
  41. Do()
  42. if err != nil {
  43. return fmt.Errorf("linkding: %w", err)
  44. }
  45. defer response.Body.Close()
  46. if response.StatusCode >= 400 {
  47. return fmt.Errorf("linkding: unable to create bookmark: url=%s status=%d", apiEndpoint, response.StatusCode)
  48. }
  49. return nil
  50. }
  51. type linkdingBookmark struct {
  52. URL string `json:"url,omitempty"`
  53. Title string `json:"title,omitempty"`
  54. TagNames []string `json:"tag_names,omitempty"`
  55. Unread bool `json:"unread,omitempty"`
  56. }