client.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. // c := client.New(client.NewConfig())
  155. // subscriptionID := c.Subscribe("mytopic")
  156. // for m := range c.Messages {
  157. // fmt.Printf("New message: %s", m.Message)
  158. // }
  159. func (c *Client) Subscribe(topic string, options ...SubscribeOption) string {
  160. c.mu.Lock()
  161. defer c.mu.Unlock()
  162. subscriptionID := util.RandomString(10)
  163. topicURL := c.expandTopicURL(topic)
  164. log.Debug("%s Subscribing to topic", util.ShortTopicURL(topicURL))
  165. ctx, cancel := context.WithCancel(context.Background())
  166. c.subscriptions[subscriptionID] = &subscription{
  167. ID: subscriptionID,
  168. topicURL: topicURL,
  169. cancel: cancel,
  170. }
  171. go handleSubscribeConnLoop(ctx, c.Messages, topicURL, subscriptionID, options...)
  172. return subscriptionID
  173. }
  174. // Unsubscribe unsubscribes from a topic that has been previously subscribed to using the unique
  175. // subscriptionID returned in Subscribe.
  176. func (c *Client) Unsubscribe(subscriptionID string) {
  177. c.mu.Lock()
  178. defer c.mu.Unlock()
  179. sub, ok := c.subscriptions[subscriptionID]
  180. if !ok {
  181. return
  182. }
  183. delete(c.subscriptions, subscriptionID)
  184. sub.cancel()
  185. }
  186. // UnsubscribeAll unsubscribes from a topic that has been previously subscribed with Subscribe.
  187. // If there are multiple subscriptions matching the topic, all of them are unsubscribed from.
  188. //
  189. // A topic can be either a full URL (e.g. https://myhost.lan/mytopic), a short URL which is then prepended https://
  190. // (e.g. myhost.lan -> https://myhost.lan), or a short name which is expanded using the default host in the
  191. // config (e.g. mytopic -> https://ntfy.sh/mytopic).
  192. func (c *Client) UnsubscribeAll(topic string) {
  193. c.mu.Lock()
  194. defer c.mu.Unlock()
  195. topicURL := c.expandTopicURL(topic)
  196. for _, sub := range c.subscriptions {
  197. if sub.topicURL == topicURL {
  198. delete(c.subscriptions, sub.ID)
  199. sub.cancel()
  200. }
  201. }
  202. }
  203. func (c *Client) expandTopicURL(topic string) string {
  204. if strings.HasPrefix(topic, "http://") || strings.HasPrefix(topic, "https://") {
  205. return topic
  206. } else if strings.Contains(topic, "/") {
  207. return fmt.Sprintf("https://%s", topic)
  208. }
  209. return fmt.Sprintf("%s/%s", c.config.DefaultHost, topic)
  210. }
  211. func handleSubscribeConnLoop(ctx context.Context, msgChan chan *Message, topicURL, subcriptionID string, options ...SubscribeOption) {
  212. for {
  213. // TODO The retry logic is crude and may lose messages. It should record the last message like the
  214. // Android client, use since=, and do incremental backoff too
  215. if err := performSubscribeRequest(ctx, msgChan, topicURL, subcriptionID, options...); err != nil {
  216. log.Warn("%s Connection failed: %s", util.ShortTopicURL(topicURL), err.Error())
  217. }
  218. select {
  219. case <-ctx.Done():
  220. log.Info("%s Connection exited", util.ShortTopicURL(topicURL))
  221. return
  222. case <-time.After(10 * time.Second): // TODO Add incremental backoff
  223. }
  224. }
  225. }
  226. func performSubscribeRequest(ctx context.Context, msgChan chan *Message, topicURL string, subscriptionID string, options ...SubscribeOption) error {
  227. streamURL := fmt.Sprintf("%s/json", topicURL)
  228. log.Debug("%s Listening to %s", util.ShortTopicURL(topicURL), streamURL)
  229. req, err := http.NewRequestWithContext(ctx, http.MethodGet, streamURL, nil)
  230. if err != nil {
  231. return err
  232. }
  233. for _, option := range options {
  234. if err := option(req); err != nil {
  235. return err
  236. }
  237. }
  238. resp, err := http.DefaultClient.Do(req)
  239. if err != nil {
  240. return err
  241. }
  242. defer resp.Body.Close()
  243. if resp.StatusCode != http.StatusOK {
  244. b, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes))
  245. if err != nil {
  246. return err
  247. }
  248. return errors.New(strings.TrimSpace(string(b)))
  249. }
  250. scanner := bufio.NewScanner(resp.Body)
  251. for scanner.Scan() {
  252. messageJSON := scanner.Text()
  253. m, err := toMessage(messageJSON, topicURL, subscriptionID)
  254. if err != nil {
  255. return err
  256. }
  257. log.Trace("%s Message received: %s", util.ShortTopicURL(topicURL), messageJSON)
  258. if m.Event == MessageEvent {
  259. msgChan <- m
  260. }
  261. }
  262. return nil
  263. }
  264. func toMessage(s, topicURL, subscriptionID string) (*Message, error) {
  265. var m *Message
  266. if err := json.NewDecoder(strings.NewReader(s)).Decode(&m); err != nil {
  267. return nil, err
  268. }
  269. m.TopicURL = topicURL
  270. m.SubscriptionID = subscriptionID
  271. m.Raw = s
  272. return m, nil
  273. }