client.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. // Package client provides a ntfy client to publish and subscribe to topics
  2. package client
  3. import (
  4. "bufio"
  5. "context"
  6. "encoding/json"
  7. "fmt"
  8. "heckel.io/ntfy/util"
  9. "io"
  10. "log"
  11. "net/http"
  12. "strings"
  13. "sync"
  14. "time"
  15. )
  16. // Event type constants
  17. const (
  18. MessageEvent = "message"
  19. KeepaliveEvent = "keepalive"
  20. OpenEvent = "open"
  21. )
  22. const (
  23. maxResponseBytes = 4096
  24. )
  25. // Client is the ntfy client that can be used to publish and subscribe to ntfy topics
  26. type Client struct {
  27. Messages chan *Message
  28. config *Config
  29. subscriptions map[string]*subscription
  30. mu sync.Mutex
  31. }
  32. // Message is a struct that represents a ntfy message
  33. type Message struct {
  34. ID string
  35. Event string
  36. Time int64
  37. Topic string
  38. Message string
  39. Title string
  40. Priority int
  41. Tags []string
  42. // Additional fields
  43. TopicURL string
  44. SubscriptionID string
  45. Raw string
  46. }
  47. type subscription struct {
  48. ID string
  49. topicURL string
  50. cancel context.CancelFunc
  51. }
  52. // New creates a new Client using a given Config
  53. func New(config *Config) *Client {
  54. return &Client{
  55. Messages: make(chan *Message),
  56. config: config,
  57. subscriptions: make(map[string]*subscription),
  58. }
  59. }
  60. // Publish sends a message to a specific topic, optionally using options.
  61. //
  62. // A topic can be either a full URL (e.g. https://myhost.lan/mytopic), a short URL which is then prepended https://
  63. // (e.g. myhost.lan -> https://myhost.lan), or a short name which is expanded using the default host in the
  64. // config (e.g. mytopic -> https://ntfy.sh/mytopic).
  65. //
  66. // To pass title, priority and tags, check out WithTitle, WithPriority, WithTagsList, WithDelay, WithNoCache,
  67. // WithNoFirebase, and the generic WithHeader.
  68. func (c *Client) Publish(topic, message string, options ...PublishOption) (*Message, error) {
  69. topicURL := c.expandTopicURL(topic)
  70. req, _ := http.NewRequest("POST", topicURL, strings.NewReader(message))
  71. for _, option := range options {
  72. if err := option(req); err != nil {
  73. return nil, err
  74. }
  75. }
  76. resp, err := http.DefaultClient.Do(req)
  77. if err != nil {
  78. return nil, err
  79. }
  80. defer resp.Body.Close()
  81. if resp.StatusCode != http.StatusOK {
  82. return nil, fmt.Errorf("unexpected response %d from server", resp.StatusCode)
  83. }
  84. b, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes))
  85. if err != nil {
  86. return nil, err
  87. }
  88. m, err := toMessage(string(b), topicURL, "")
  89. if err != nil {
  90. return nil, err
  91. }
  92. return m, nil
  93. }
  94. // Poll queries a topic for all (or a limited set) of messages. Unlike Subscribe, this method only polls for
  95. // messages and does not subscribe to messages that arrive after this call.
  96. //
  97. // A topic can be either a full URL (e.g. https://myhost.lan/mytopic), a short URL which is then prepended https://
  98. // (e.g. myhost.lan -> https://myhost.lan), or a short name which is expanded using the default host in the
  99. // config (e.g. mytopic -> https://ntfy.sh/mytopic).
  100. //
  101. // By default, all messages will be returned, but you can change this behavior using a SubscribeOption.
  102. // See WithSince, WithSinceAll, WithSinceUnixTime, WithScheduled, and the generic WithQueryParam.
  103. func (c *Client) Poll(topic string, options ...SubscribeOption) ([]*Message, error) {
  104. ctx := context.Background()
  105. messages := make([]*Message, 0)
  106. msgChan := make(chan *Message)
  107. errChan := make(chan error)
  108. topicURL := c.expandTopicURL(topic)
  109. go func() {
  110. err := performSubscribeRequest(ctx, msgChan, topicURL, "", options...)
  111. close(msgChan)
  112. errChan <- err
  113. }()
  114. for m := range msgChan {
  115. messages = append(messages, m)
  116. }
  117. return messages, <-errChan
  118. }
  119. // Subscribe subscribes to a topic to listen for newly incoming messages. The method starts a connection in the
  120. // background and returns new messages via the Messages channel.
  121. //
  122. // A topic can be either a full URL (e.g. https://myhost.lan/mytopic), a short URL which is then prepended https://
  123. // (e.g. myhost.lan -> https://myhost.lan), or a short name which is expanded using the default host in the
  124. // config (e.g. mytopic -> https://ntfy.sh/mytopic).
  125. //
  126. // By default, only new messages will be returned, but you can change this behavior using a SubscribeOption.
  127. // See WithSince, WithSinceAll, WithSinceUnixTime, WithScheduled, and the generic WithQueryParam.
  128. //
  129. // The method returns a unique subscriptionID that can be used in Unsubscribe.
  130. //
  131. // Example:
  132. // c := client.New(client.NewConfig())
  133. // subscriptionID := c.Subscribe("mytopic")
  134. // for m := range c.Messages {
  135. // fmt.Printf("New message: %s", m.Message)
  136. // }
  137. func (c *Client) Subscribe(topic string, options ...SubscribeOption) string {
  138. c.mu.Lock()
  139. defer c.mu.Unlock()
  140. subscriptionID := util.RandomString(10)
  141. topicURL := c.expandTopicURL(topic)
  142. ctx, cancel := context.WithCancel(context.Background())
  143. c.subscriptions[subscriptionID] = &subscription{
  144. ID: subscriptionID,
  145. topicURL: topicURL,
  146. cancel: cancel,
  147. }
  148. go handleSubscribeConnLoop(ctx, c.Messages, topicURL, subscriptionID, options...)
  149. return subscriptionID
  150. }
  151. // Unsubscribe unsubscribes from a topic that has been previously subscribed to using the unique
  152. // subscriptionID returned in Subscribe.
  153. func (c *Client) Unsubscribe(subscriptionID string) {
  154. c.mu.Lock()
  155. defer c.mu.Unlock()
  156. sub, ok := c.subscriptions[subscriptionID]
  157. if !ok {
  158. return
  159. }
  160. delete(c.subscriptions, subscriptionID)
  161. sub.cancel()
  162. }
  163. // UnsubscribeAll unsubscribes from a topic that has been previously subscribed with Subscribe.
  164. // If there are multiple subscriptions matching the topic, all of them are unsubscribed from.
  165. //
  166. // A topic can be either a full URL (e.g. https://myhost.lan/mytopic), a short URL which is then prepended https://
  167. // (e.g. myhost.lan -> https://myhost.lan), or a short name which is expanded using the default host in the
  168. // config (e.g. mytopic -> https://ntfy.sh/mytopic).
  169. func (c *Client) UnsubscribeAll(topic string) {
  170. c.mu.Lock()
  171. defer c.mu.Unlock()
  172. topicURL := c.expandTopicURL(topic)
  173. for _, sub := range c.subscriptions {
  174. if sub.topicURL == topicURL {
  175. delete(c.subscriptions, sub.ID)
  176. sub.cancel()
  177. }
  178. }
  179. }
  180. func (c *Client) expandTopicURL(topic string) string {
  181. if strings.HasPrefix(topic, "http://") || strings.HasPrefix(topic, "https://") {
  182. return topic
  183. } else if strings.Contains(topic, "/") {
  184. return fmt.Sprintf("https://%s", topic)
  185. }
  186. return fmt.Sprintf("%s/%s", c.config.DefaultHost, topic)
  187. }
  188. func handleSubscribeConnLoop(ctx context.Context, msgChan chan *Message, topicURL, subcriptionID string, options ...SubscribeOption) {
  189. for {
  190. // TODO The retry logic is crude and may lose messages. It should record the last message like the
  191. // Android client, use since=, and do incremental backoff too
  192. if err := performSubscribeRequest(ctx, msgChan, topicURL, subcriptionID, options...); err != nil {
  193. log.Printf("Connection to %s failed: %s", topicURL, err.Error())
  194. }
  195. select {
  196. case <-ctx.Done():
  197. log.Printf("Connection to %s exited", topicURL)
  198. return
  199. case <-time.After(10 * time.Second): // TODO Add incremental backoff
  200. }
  201. }
  202. }
  203. func performSubscribeRequest(ctx context.Context, msgChan chan *Message, topicURL string, subscriptionID string, options ...SubscribeOption) error {
  204. req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s/json", topicURL), nil)
  205. if err != nil {
  206. return err
  207. }
  208. for _, option := range options {
  209. if err := option(req); err != nil {
  210. return err
  211. }
  212. }
  213. resp, err := http.DefaultClient.Do(req)
  214. if err != nil {
  215. return err
  216. }
  217. defer resp.Body.Close()
  218. scanner := bufio.NewScanner(resp.Body)
  219. for scanner.Scan() {
  220. m, err := toMessage(scanner.Text(), topicURL, subscriptionID)
  221. if err != nil {
  222. return err
  223. }
  224. msgChan <- m
  225. }
  226. return nil
  227. }
  228. func toMessage(s, topicURL, subscriptionID string) (*Message, error) {
  229. var m *Message
  230. if err := json.NewDecoder(strings.NewReader(s)).Decode(&m); err != nil {
  231. return nil, err
  232. }
  233. m.TopicURL = topicURL
  234. m.SubscriptionID = subscriptionID
  235. m.Raw = s
  236. return m, nil
  237. }