client.go 9.3 KB

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