2021-10-23 03:26:01 +02:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
_ "embed" // required for go:embed
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
2021-10-23 19:21:33 +02:00
|
|
|
"fmt"
|
2021-10-24 03:29:45 +02:00
|
|
|
"heckel.io/ntfy/config"
|
2021-10-23 03:26:01 +02:00
|
|
|
"io"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"regexp"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Server struct {
|
2021-10-24 03:29:45 +02:00
|
|
|
config *config.Config
|
2021-10-23 03:26:01 +02:00
|
|
|
topics map[string]*topic
|
2021-10-23 21:22:17 +02:00
|
|
|
mu sync.Mutex
|
2021-10-23 03:26:01 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type message struct {
|
2021-10-23 21:22:17 +02:00
|
|
|
Time int64 `json:"time"`
|
2021-10-23 03:26:01 +02:00
|
|
|
Message string `json:"message"`
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
messageLimit = 1024
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2021-10-23 21:22:17 +02:00
|
|
|
topicRegex = regexp.MustCompile(`^/[^/]+$`)
|
|
|
|
jsonRegex = regexp.MustCompile(`^/[^/]+/json$`)
|
|
|
|
sseRegex = regexp.MustCompile(`^/[^/]+/sse$`)
|
2021-10-24 03:29:45 +02:00
|
|
|
rawRegex = regexp.MustCompile(`^/[^/]+/raw$`)
|
2021-10-23 03:26:01 +02:00
|
|
|
|
|
|
|
//go:embed "index.html"
|
|
|
|
indexSource string
|
2021-10-24 03:29:45 +02:00
|
|
|
|
|
|
|
errTopicNotFound = errors.New("topic not found")
|
2021-10-23 03:26:01 +02:00
|
|
|
)
|
|
|
|
|
2021-10-24 03:29:45 +02:00
|
|
|
func New(conf *config.Config) *Server {
|
2021-10-23 03:26:01 +02:00
|
|
|
return &Server{
|
2021-10-24 03:29:45 +02:00
|
|
|
config: conf,
|
2021-10-23 03:26:01 +02:00
|
|
|
topics: make(map[string]*topic),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) Run() error {
|
2021-10-23 21:22:17 +02:00
|
|
|
go s.runMonitor()
|
|
|
|
return s.listenAndServe()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) listenAndServe() error {
|
2021-10-24 03:29:45 +02:00
|
|
|
log.Printf("Listening on %s", s.config.ListenHTTP)
|
2021-10-23 03:26:01 +02:00
|
|
|
http.HandleFunc("/", s.handle)
|
2021-10-24 03:29:45 +02:00
|
|
|
return http.ListenAndServe(s.config.ListenHTTP, nil)
|
2021-10-23 03:26:01 +02:00
|
|
|
}
|
|
|
|
|
2021-10-23 21:22:17 +02:00
|
|
|
func (s *Server) runMonitor() {
|
|
|
|
for {
|
2021-10-24 03:29:45 +02:00
|
|
|
time.Sleep(30 * time.Second)
|
2021-10-23 21:22:17 +02:00
|
|
|
s.mu.Lock()
|
2021-10-24 03:29:45 +02:00
|
|
|
var subscribers, messages int
|
2021-10-23 21:22:17 +02:00
|
|
|
for _, t := range s.topics {
|
2021-10-24 03:29:45 +02:00
|
|
|
subs, msgs := t.Stats()
|
|
|
|
subscribers += subs
|
|
|
|
messages += msgs
|
2021-10-23 21:22:17 +02:00
|
|
|
}
|
2021-10-24 03:29:45 +02:00
|
|
|
log.Printf("Stats: %d topic(s), %d subscriber(s), %d message(s) sent", len(s.topics), subscribers, messages)
|
2021-10-23 21:22:17 +02:00
|
|
|
s.mu.Unlock()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-23 03:26:01 +02:00
|
|
|
func (s *Server) handle(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if err := s.handleInternal(w, r); err != nil {
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
2021-10-24 03:29:45 +02:00
|
|
|
_, _ = io.WriteString(w, err.Error()+"\n")
|
2021-10-23 03:26:01 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) handleInternal(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
if r.Method == http.MethodGet && r.URL.Path == "/" {
|
|
|
|
return s.handleHome(w, r)
|
|
|
|
} else if r.Method == http.MethodGet && jsonRegex.MatchString(r.URL.Path) {
|
2021-10-23 19:21:33 +02:00
|
|
|
return s.handleSubscribeJSON(w, r)
|
|
|
|
} else if r.Method == http.MethodGet && sseRegex.MatchString(r.URL.Path) {
|
|
|
|
return s.handleSubscribeSSE(w, r)
|
2021-10-24 03:29:45 +02:00
|
|
|
} else if r.Method == http.MethodGet && rawRegex.MatchString(r.URL.Path) {
|
|
|
|
return s.handleSubscribeRaw(w, r)
|
2021-10-23 03:26:01 +02:00
|
|
|
} else if (r.Method == http.MethodPut || r.Method == http.MethodPost) && topicRegex.MatchString(r.URL.Path) {
|
|
|
|
return s.handlePublishHTTP(w, r)
|
|
|
|
}
|
|
|
|
http.NotFound(w, r)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) handleHome(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
_, err := io.WriteString(w, indexSource)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) handlePublishHTTP(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
t, err := s.topic(r.URL.Path[1:])
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
reader := io.LimitReader(r.Body, messageLimit)
|
|
|
|
b, err := io.ReadAll(reader)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
msg := &message{
|
|
|
|
Time: time.Now().UnixMilli(),
|
|
|
|
Message: string(b),
|
|
|
|
}
|
|
|
|
return t.Publish(msg)
|
|
|
|
}
|
|
|
|
|
2021-10-23 19:21:33 +02:00
|
|
|
func (s *Server) handleSubscribeJSON(w http.ResponseWriter, r *http.Request) error {
|
2021-10-23 03:26:01 +02:00
|
|
|
t := s.createTopic(strings.TrimSuffix(r.URL.Path[1:], "/json")) // Hack
|
2021-10-23 21:22:17 +02:00
|
|
|
subscriberID := t.Subscribe(func(msg *message) error {
|
2021-10-23 03:26:01 +02:00
|
|
|
if err := json.NewEncoder(w).Encode(&msg); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if fl, ok := w.(http.Flusher); ok {
|
|
|
|
fl.Flush()
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
2021-10-24 03:29:45 +02:00
|
|
|
defer s.unsubscribe(t, subscriberID)
|
2021-10-23 03:26:01 +02:00
|
|
|
select {
|
|
|
|
case <-t.ctx.Done():
|
|
|
|
case <-r.Context().Done():
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-10-23 19:21:33 +02:00
|
|
|
func (s *Server) handleSubscribeSSE(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
t := s.createTopic(strings.TrimSuffix(r.URL.Path[1:], "/sse")) // Hack
|
2021-10-23 21:22:17 +02:00
|
|
|
subscriberID := t.Subscribe(func(msg *message) error {
|
2021-10-23 19:21:33 +02:00
|
|
|
var buf bytes.Buffer
|
|
|
|
if err := json.NewEncoder(&buf).Encode(&msg); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-10-23 21:22:17 +02:00
|
|
|
m := fmt.Sprintf("data: %s\n", buf.String())
|
2021-10-23 19:21:33 +02:00
|
|
|
if _, err := io.WriteString(w, m); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if fl, ok := w.(http.Flusher); ok {
|
|
|
|
fl.Flush()
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
2021-10-24 03:29:45 +02:00
|
|
|
defer s.unsubscribe(t, subscriberID)
|
2021-10-23 19:21:33 +02:00
|
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
|
|
w.WriteHeader(http.StatusOK)
|
2021-10-23 21:22:17 +02:00
|
|
|
if _, err := io.WriteString(w, "event: open\n\n"); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if fl, ok := w.(http.Flusher); ok {
|
|
|
|
fl.Flush()
|
|
|
|
}
|
2021-10-23 19:21:33 +02:00
|
|
|
select {
|
|
|
|
case <-t.ctx.Done():
|
|
|
|
case <-r.Context().Done():
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-10-24 03:29:45 +02:00
|
|
|
func (s *Server) handleSubscribeRaw(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
t := s.createTopic(strings.TrimSuffix(r.URL.Path[1:], "/raw")) // Hack
|
|
|
|
subscriberID := t.Subscribe(func(msg *message) error {
|
|
|
|
m := strings.ReplaceAll(msg.Message, "\n", " ") + "\n"
|
|
|
|
if _, err := io.WriteString(w, m); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if fl, ok := w.(http.Flusher); ok {
|
|
|
|
fl.Flush()
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
defer s.unsubscribe(t, subscriberID)
|
|
|
|
select {
|
|
|
|
case <-t.ctx.Done():
|
|
|
|
case <-r.Context().Done():
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-10-23 03:26:01 +02:00
|
|
|
func (s *Server) createTopic(id string) *topic {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
if _, ok := s.topics[id]; !ok {
|
|
|
|
s.topics[id] = newTopic(id)
|
|
|
|
}
|
|
|
|
return s.topics[id]
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) topic(topicID string) (*topic, error) {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
c, ok := s.topics[topicID]
|
|
|
|
if !ok {
|
2021-10-24 03:29:45 +02:00
|
|
|
return nil, errTopicNotFound
|
2021-10-23 03:26:01 +02:00
|
|
|
}
|
|
|
|
return c, nil
|
|
|
|
}
|
2021-10-24 03:29:45 +02:00
|
|
|
|
|
|
|
func (s *Server) unsubscribe(t *topic, subscriberID int) {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
if subscribers := t.Unsubscribe(subscriberID); subscribers == 0 {
|
|
|
|
delete(s.topics, t.id)
|
|
|
|
}
|
|
|
|
}
|