raindrop.go 2.0 KB

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