raindrop.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package raindrop // import "miniflux.app/v2/internal/integration/raindrop"
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "net/http"
  10. "strings"
  11. "time"
  12. "miniflux.app/v2/internal/version"
  13. )
  14. const defaultClientTimeout = 10 * time.Second
  15. type Client struct {
  16. token string
  17. collectionID string
  18. tags []string
  19. }
  20. func NewClient(token, collectionID, tags string) *Client {
  21. return &Client{token: token, collectionID: collectionID, tags: strings.Split(tags, ",")}
  22. }
  23. // https://developer.raindrop.io/v1/raindrops/single#create-raindrop
  24. func (c *Client) CreateRaindrop(entryURL, entryTitle string) error {
  25. if c.token == "" {
  26. return errors.New("raindrop: missing token")
  27. }
  28. var request *http.Request
  29. requestBodyJson, err := json.Marshal(&raindrop{
  30. Link: entryURL,
  31. Title: entryTitle,
  32. Collection: collection{Id: c.collectionID},
  33. Tags: c.tags,
  34. })
  35. if err != nil {
  36. return fmt.Errorf("raindrop: unable to encode request body: %v", err)
  37. }
  38. request, err = http.NewRequest(http.MethodPost, "https://api.raindrop.io/rest/v1/raindrop", bytes.NewReader(requestBodyJson))
  39. if err != nil {
  40. return fmt.Errorf("raindrop: unable to create request: %v", err)
  41. }
  42. request.Header.Set("Content-Type", "application/json")
  43. request.Header.Set("User-Agent", "Miniflux/"+version.Version)
  44. request.Header.Set("Authorization", "Bearer "+c.token)
  45. httpClient := &http.Client{Timeout: defaultClientTimeout}
  46. response, err := httpClient.Do(request)
  47. if err != nil {
  48. return fmt.Errorf("raindrop: unable to send request: %v", err)
  49. }
  50. defer response.Body.Close()
  51. if response.StatusCode >= 400 {
  52. return fmt.Errorf("raindrop: unable to create bookmark: status=%d", response.StatusCode)
  53. }
  54. return nil
  55. }
  56. type raindrop struct {
  57. Link string `json:"link"`
  58. Title string `json:"title"`
  59. Collection collection `json:"collection,omitempty"`
  60. Tags []string `json:"tags"`
  61. }
  62. type collection struct {
  63. Id string `json:"$id"`
  64. }