webhook.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package webhook // import "miniflux.app/v2/internal/integration/webhook"
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "fmt"
  8. "net/http"
  9. "time"
  10. "miniflux.app/v2/internal/crypto"
  11. "miniflux.app/v2/internal/model"
  12. "miniflux.app/v2/internal/version"
  13. )
  14. const defaultClientTimeout = 10 * time.Second
  15. type Client struct {
  16. webhookURL string
  17. webhookSecret string
  18. }
  19. func NewClient(webhookURL, webhookSecret string) *Client {
  20. return &Client{webhookURL, webhookSecret}
  21. }
  22. func (c *Client) SendWebhook(feed *model.Feed, entries model.Entries) error {
  23. if c.webhookURL == "" {
  24. return fmt.Errorf(`webhook: missing webhook URL`)
  25. }
  26. if len(entries) == 0 {
  27. return nil
  28. }
  29. webhookEvent := &WebhookEvent{
  30. // Send only a subset of the fields to avoid leaking sensitive data.
  31. Feed: &WebhookFeed{
  32. ID: feed.ID,
  33. UserID: feed.UserID,
  34. FeedURL: feed.FeedURL,
  35. SiteURL: feed.SiteURL,
  36. Title: feed.Title,
  37. CheckedAt: feed.CheckedAt,
  38. },
  39. Entries: entries,
  40. }
  41. requestBody, err := json.Marshal(webhookEvent)
  42. if err != nil {
  43. return fmt.Errorf("webhook: unable to encode request body: %v", err)
  44. }
  45. request, err := http.NewRequest(http.MethodPost, c.webhookURL, bytes.NewReader(requestBody))
  46. if err != nil {
  47. return fmt.Errorf("webhook: unable to create request: %v", err)
  48. }
  49. request.Header.Set("Content-Type", "application/json")
  50. request.Header.Set("User-Agent", "Miniflux/"+version.Version)
  51. request.Header.Set("X-Miniflux-Signature", crypto.GenerateSHA256Hmac(c.webhookSecret, requestBody))
  52. httpClient := &http.Client{Timeout: defaultClientTimeout}
  53. response, err := httpClient.Do(request)
  54. if err != nil {
  55. return fmt.Errorf("webhook: unable to send request: %v", err)
  56. }
  57. defer response.Body.Close()
  58. if response.StatusCode >= 400 {
  59. return fmt.Errorf("webhook: incorrect response status code: url=%s status=%d", c.webhookURL, response.StatusCode)
  60. }
  61. return nil
  62. }
  63. type WebhookFeed struct {
  64. ID int64 `json:"id"`
  65. UserID int64 `json:"user_id"`
  66. FeedURL string `json:"feed_url"`
  67. SiteURL string `json:"site_url"`
  68. Title string `json:"title"`
  69. CheckedAt time.Time `json:"checked_at"`
  70. }
  71. type WebhookEvent struct {
  72. Feed *WebhookFeed `json:"feed"`
  73. Entries model.Entries `json:"entries"`
  74. }