client.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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 { // TODO combine with server.message
  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, 50), // Allow reading a few messages
  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. options = append(options, WithPoll())
  110. go func() {
  111. err := performSubscribeRequest(ctx, msgChan, topicURL, "", options...)
  112. close(msgChan)
  113. errChan <- err
  114. }()
  115. for m := range msgChan {
  116. messages = append(messages, m)
  117. }
  118. return messages, <-errChan
  119. }
  120. // Subscribe subscribes to a topic to listen for newly incoming messages. The method starts a connection in the
  121. // background and returns new messages via the Messages channel.
  122. //
  123. // A topic can be either a full URL (e.g. https://myhost.lan/mytopic), a short URL which is then prepended https://
  124. // (e.g. myhost.lan -> https://myhost.lan), or a short name which is expanded using the default host in the
  125. // config (e.g. mytopic -> https://ntfy.sh/mytopic).
  126. //
  127. // By default, only new messages will be returned, but you can change this behavior using a SubscribeOption.
  128. // See WithSince, WithSinceAll, WithSinceUnixTime, WithScheduled, and the generic WithQueryParam.
  129. //
  130. // The method returns a unique subscriptionID that can be used in Unsubscribe.
  131. //
  132. // Example:
  133. // c := client.New(client.NewConfig())
  134. // subscriptionID := c.Subscribe("mytopic")
  135. // for m := range c.Messages {
  136. // fmt.Printf("New message: %s", m.Message)
  137. // }
  138. func (c *Client) Subscribe(topic string, options ...SubscribeOption) string {
  139. c.mu.Lock()
  140. defer c.mu.Unlock()
  141. subscriptionID := util.RandomString(10)
  142. topicURL := c.expandTopicURL(topic)
  143. ctx, cancel := context.WithCancel(context.Background())
  144. c.subscriptions[subscriptionID] = &subscription{
  145. ID: subscriptionID,
  146. topicURL: topicURL,
  147. cancel: cancel,
  148. }
  149. go handleSubscribeConnLoop(ctx, c.Messages, topicURL, subscriptionID, options...)
  150. return subscriptionID
  151. }
  152. // Unsubscribe unsubscribes from a topic that has been previously subscribed to using the unique
  153. // subscriptionID returned in Subscribe.
  154. func (c *Client) Unsubscribe(subscriptionID string) {
  155. c.mu.Lock()
  156. defer c.mu.Unlock()
  157. sub, ok := c.subscriptions[subscriptionID]
  158. if !ok {
  159. return
  160. }
  161. delete(c.subscriptions, subscriptionID)
  162. sub.cancel()
  163. }
  164. // UnsubscribeAll unsubscribes from a topic that has been previously subscribed with Subscribe.
  165. // If there are multiple subscriptions matching the topic, all of them are unsubscribed from.
  166. //
  167. // A topic can be either a full URL (e.g. https://myhost.lan/mytopic), a short URL which is then prepended https://
  168. // (e.g. myhost.lan -> https://myhost.lan), or a short name which is expanded using the default host in the
  169. // config (e.g. mytopic -> https://ntfy.sh/mytopic).
  170. func (c *Client) UnsubscribeAll(topic string) {
  171. c.mu.Lock()
  172. defer c.mu.Unlock()
  173. topicURL := c.expandTopicURL(topic)
  174. for _, sub := range c.subscriptions {
  175. if sub.topicURL == topicURL {
  176. delete(c.subscriptions, sub.ID)
  177. sub.cancel()
  178. }
  179. }
  180. }
  181. func (c *Client) expandTopicURL(topic string) string {
  182. if strings.HasPrefix(topic, "http://") || strings.HasPrefix(topic, "https://") {
  183. return topic
  184. } else if strings.Contains(topic, "/") {
  185. return fmt.Sprintf("https://%s", topic)
  186. }
  187. return fmt.Sprintf("%s/%s", c.config.DefaultHost, topic)
  188. }
  189. func handleSubscribeConnLoop(ctx context.Context, msgChan chan *Message, topicURL, subcriptionID string, options ...SubscribeOption) {
  190. for {
  191. // TODO The retry logic is crude and may lose messages. It should record the last message like the
  192. // Android client, use since=, and do incremental backoff too
  193. if err := performSubscribeRequest(ctx, msgChan, topicURL, subcriptionID, options...); err != nil {
  194. log.Printf("Connection to %s failed: %s", topicURL, err.Error())
  195. }
  196. select {
  197. case <-ctx.Done():
  198. log.Printf("Connection to %s exited", topicURL)
  199. return
  200. case <-time.After(10 * time.Second): // TODO Add incremental backoff
  201. }
  202. }
  203. }
  204. func performSubscribeRequest(ctx context.Context, msgChan chan *Message, topicURL string, subscriptionID string, options ...SubscribeOption) error {
  205. req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s/json", topicURL), nil)
  206. if err != nil {
  207. return err
  208. }
  209. for _, option := range options {
  210. if err := option(req); err != nil {
  211. return err
  212. }
  213. }
  214. resp, err := http.DefaultClient.Do(req)
  215. if err != nil {
  216. return err
  217. }
  218. defer resp.Body.Close()
  219. scanner := bufio.NewScanner(resp.Body)
  220. for scanner.Scan() {
  221. m, err := toMessage(scanner.Text(), topicURL, subscriptionID)
  222. if err != nil {
  223. return err
  224. }
  225. if m.Event == MessageEvent {
  226. msgChan <- m
  227. }
  228. }
  229. return nil
  230. }
  231. func toMessage(s, topicURL, subscriptionID string) (*Message, error) {
  232. var m *Message
  233. if err := json.NewDecoder(strings.NewReader(s)).Decode(&m); err != nil {
  234. return nil, err
  235. }
  236. m.TopicURL = topicURL
  237. m.SubscriptionID = subscriptionID
  238. m.Raw = s
  239. return m, nil
  240. }