client.go 9.3 KB

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