4
0

cubox.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. // Cubox API documentation: https://help.cubox.cc/save/api/
  4. package cubox // import "miniflux.app/v2/internal/integration/cubox"
  5. import (
  6. "bytes"
  7. "context"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "net/http"
  12. "time"
  13. "miniflux.app/v2/internal/config"
  14. "miniflux.app/v2/internal/http/client"
  15. "miniflux.app/v2/internal/version"
  16. )
  17. const defaultClientTimeout = 10 * time.Second
  18. type Client struct {
  19. apiLink string
  20. }
  21. func NewClient(apiLink string) *Client {
  22. return &Client{apiLink: apiLink}
  23. }
  24. func (c *Client) SaveLink(entryURL string) error {
  25. if c.apiLink == "" {
  26. return errors.New("cubox: missing API link")
  27. }
  28. requestBody, err := json.Marshal(&card{
  29. Type: "url",
  30. Content: entryURL,
  31. })
  32. if err != nil {
  33. return fmt.Errorf("cubox: unable to encode request body: %w", err)
  34. }
  35. ctx, cancel := context.WithTimeout(context.Background(), defaultClientTimeout)
  36. defer cancel()
  37. request, err := http.NewRequestWithContext(ctx, http.MethodPost, c.apiLink, bytes.NewReader(requestBody))
  38. if err != nil {
  39. return fmt.Errorf("cubox: unable to create request: %w", err)
  40. }
  41. request.Header.Set("Content-Type", "application/json")
  42. request.Header.Set("User-Agent", "Miniflux/"+version.Version)
  43. response, err := client.NewClientWithOptions(client.Options{Timeout: defaultClientTimeout, BlockPrivateNetworks: !config.Opts.IntegrationAllowPrivateNetworks()}).Do(request)
  44. if err != nil {
  45. return fmt.Errorf("cubox: unable to send request: %w", err)
  46. }
  47. defer response.Body.Close()
  48. if response.StatusCode != 200 {
  49. return fmt.Errorf("cubox: unable to save link: status=%d", response.StatusCode)
  50. }
  51. return nil
  52. }
  53. type card struct {
  54. Type string `json:"type"`
  55. Content string `json:"content"`
  56. }