Debian Codegraph @

client/client.go

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