raindrop.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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/config"
  13. "miniflux.app/v2/internal/http/client"
  14. "miniflux.app/v2/internal/version"
  15. )
  16. const defaultClientTimeout = 10 * time.Second
  17. type Client struct {
  18. token string
  19. collectionID string
  20. tags []string
  21. }
  22. func NewClient(token, collectionID, tags string) *Client {
  23. return &Client{token: token, collectionID: collectionID, tags: strings.Split(tags, ",")}
  24. }
  25. // https://developer.raindrop.io/v1/raindrops/single#create-raindrop
  26. func (c *Client) CreateRaindrop(entryURL, entryTitle string) error {
  27. if c.token == "" {
  28. return errors.New("raindrop: missing token")
  29. }
  30. var request *http.Request
  31. requestBodyJson, err := json.Marshal(&raindrop{
  32. Link: entryURL,
  33. Title: entryTitle,
  34. Collection: collection{Id: c.collectionID},
  35. Tags: c.tags,
  36. })
  37. if err != nil {
  38. return fmt.Errorf("raindrop: unable to encode request body: %v", err)
  39. }
  40. request, err = http.NewRequest(http.MethodPost, "https://api.raindrop.io/rest/v1/raindrop", bytes.NewReader(requestBodyJson))
  41. if err != nil {
  42. return fmt.Errorf("raindrop: unable to create request: %v", err)
  43. }
  44. request.Header.Set("Content-Type", "application/json")
  45. request.Header.Set("User-Agent", "Miniflux/"+version.Version)
  46. request.Header.Set("Authorization", "Bearer "+c.token)
  47. httpClient := client.NewClientWithOptions(client.Options{Timeout: defaultClientTimeout, BlockPrivateNetworks: !config.Opts.IntegrationAllowPrivateNetworks()})
  48. response, err := httpClient.Do(request)
  49. if err != nil {
  50. return fmt.Errorf("raindrop: unable to send request: %v", err)
  51. }
  52. defer response.Body.Close()
  53. if response.StatusCode >= 400 {
  54. return fmt.Errorf("raindrop: unable to create bookmark: status=%d", response.StatusCode)
  55. }
  56. return nil
  57. }
  58. type raindrop struct {
  59. Link string `json:"link"`
  60. Title string `json:"title"`
  61. Collection collection `json:"collection"`
  62. Tags []string `json:"tags"`
  63. }
  64. type collection struct {
  65. Id string `json:"$id"`
  66. }