apprise.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package apprise
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "fmt"
  8. "net/http"
  9. "time"
  10. "miniflux.app/v2/internal/model"
  11. "miniflux.app/v2/internal/urllib"
  12. "miniflux.app/v2/internal/version"
  13. )
  14. const defaultClientTimeout = 10 * time.Second
  15. type Client struct {
  16. servicesURL string
  17. baseURL string
  18. }
  19. func NewClient(serviceURL, baseURL string) *Client {
  20. return &Client{serviceURL, baseURL}
  21. }
  22. func (c *Client) SendNotification(entry *model.Entry) error {
  23. if c.baseURL == "" || c.servicesURL == "" {
  24. return fmt.Errorf("apprise: missing base URL or services URL")
  25. }
  26. message := "[" + entry.Title + "]" + "(" + entry.URL + ")" + "\n\n"
  27. apiEndpoint, err := urllib.JoinBaseURLAndPath(c.baseURL, "/notify")
  28. if err != nil {
  29. return fmt.Errorf(`apprise: invalid API endpoint: %v`, err)
  30. }
  31. requestBody, err := json.Marshal(map[string]any{
  32. "urls": c.servicesURL,
  33. "body": message,
  34. })
  35. if err != nil {
  36. return fmt.Errorf("apprise: unable to encode request body: %v", err)
  37. }
  38. request, err := http.NewRequest(http.MethodPost, apiEndpoint, bytes.NewReader(requestBody))
  39. if err != nil {
  40. return fmt.Errorf("apprise: 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. httpClient := &http.Client{Timeout: defaultClientTimeout}
  45. response, err := httpClient.Do(request)
  46. if err != nil {
  47. return fmt.Errorf("apprise: unable to send request: %v", err)
  48. }
  49. defer response.Body.Close()
  50. if response.StatusCode >= 400 {
  51. return fmt.Errorf("apprise: unable to send a notification: url=%s status=%d", apiEndpoint, response.StatusCode)
  52. }
  53. return nil
  54. }