Skip to content

Commit

Permalink
WIP CLI
Browse files Browse the repository at this point in the history
  • Loading branch information
Philipp Heckel committed Dec 18, 2021
1 parent 5639cf7 commit f266afa
Show file tree
Hide file tree
Showing 12 changed files with 209 additions and 74 deletions.
34 changes: 20 additions & 14 deletions client/client.go
Expand Up @@ -12,19 +12,15 @@ import (
"time"
)

const (
DefaultBaseURL = "https://ntfy.sh"
)

const (
MessageEvent = "message"
KeepaliveEvent = "keepalive"
OpenEvent = "open"
)

type Client struct {
BaseURL string
Messages chan *Message
config *Config
subscriptions map[string]*subscription
mu sync.Mutex
}
Expand All @@ -34,7 +30,6 @@ type Message struct {
Event string
Time int64
Topic string
BaseURL string
TopicURL string
Message string
Title string
Expand All @@ -47,11 +42,10 @@ type subscription struct {
cancel context.CancelFunc
}

var DefaultClient = New()

func New() *Client {
func New(config *Config) *Client {
return &Client{
Messages: make(chan *Message),
config: config,
subscriptions: make(map[string]*subscription),
}
}
Expand All @@ -73,11 +67,12 @@ func (c *Client) Publish(topicURL, message string, options ...PublishOption) err
return err
}

func (c *Client) Poll(topicURL string, options ...SubscribeOption) ([]*Message, error) {
func (c *Client) Poll(topic string, options ...SubscribeOption) ([]*Message, error) {
ctx := context.Background()
messages := make([]*Message, 0)
msgChan := make(chan *Message)
errChan := make(chan error)
topicURL := c.expandTopicURL(topic)
go func() {
err := performSubscribeRequest(ctx, msgChan, topicURL, options...)
close(msgChan)
Expand All @@ -89,20 +84,23 @@ func (c *Client) Poll(topicURL string, options ...SubscribeOption) ([]*Message,
return messages, <-errChan
}

func (c *Client) Subscribe(topicURL string, options ...SubscribeOption) {
func (c *Client) Subscribe(topic string, options ...SubscribeOption) string {
c.mu.Lock()
defer c.mu.Unlock()
topicURL := c.expandTopicURL(topic)
if _, ok := c.subscriptions[topicURL]; ok {
return
return topicURL
}
ctx, cancel := context.WithCancel(context.Background())
c.subscriptions[topicURL] = &subscription{cancel}
go handleSubscribeConnLoop(ctx, c.Messages, topicURL, options...)
return topicURL
}

func (c *Client) Unsubscribe(topicURL string) {
func (c *Client) Unsubscribe(topic string) {
c.mu.Lock()
defer c.mu.Unlock()
topicURL := c.expandTopicURL(topic)
sub, ok := c.subscriptions[topicURL]
if !ok {
return
Expand All @@ -111,6 +109,15 @@ func (c *Client) Unsubscribe(topicURL string) {
return
}

func (c *Client) expandTopicURL(topic string) string {
if strings.HasPrefix(topic, "http://") || strings.HasPrefix(topic, "https://") {
return topic
} else if strings.Contains(topic, "/") {
return fmt.Sprintf("https://%s", topic)
}
return fmt.Sprintf("%s/%s", c.config.DefaultHost, topic)
}

func handleSubscribeConnLoop(ctx context.Context, msgChan chan *Message, topicURL string, options ...SubscribeOption) {
for {
if err := performSubscribeRequest(ctx, msgChan, topicURL, options...); err != nil {
Expand Down Expand Up @@ -147,7 +154,6 @@ func performSubscribeRequest(ctx context.Context, msgChan chan *Message, topicUR
if err := json.NewDecoder(strings.NewReader(line)).Decode(&m); err != nil {
return err
}
m.BaseURL = strings.TrimSuffix(topicURL, "/"+m.Topic) // FIXME hack!
m.TopicURL = topicURL
m.Raw = line
msgChan <- m
Expand Down
18 changes: 18 additions & 0 deletions client/client.yml
@@ -0,0 +1,18 @@
# ntfy client config file

# Base URL used to expand short topic names in the "ntfy publish" and "ntfy subscribe" commands.
# If you self-host a ntfy server, you'll likely want to change this.
#
# default-host: https://ntfy.sh

# Subscriptions to topics and their actions. This option is only used by the "ntfy subscribe --from-config"
# command.
#
# Here's a (hopefully self-explanatory) example:
# subscribe:
# - topic: mytopic
# exec: /usr/local/bin/mytopic-triggered.sh
# - topic: myserver.com/anothertopic
# exec: 'echo "$message"'
#
# subscribe:
20 changes: 20 additions & 0 deletions client/config.go
@@ -0,0 +1,20 @@
package client

const (
DefaultBaseURL = "https://ntfy.sh"
)

type Config struct {
DefaultHost string
Subscribe []struct {
Topic string
Exec string
}
}

func NewConfig() *Config {
return &Config{
DefaultHost: DefaultBaseURL,
Subscribe: nil,
}
}
20 changes: 7 additions & 13 deletions cmd/app.go
Expand Up @@ -5,13 +5,16 @@ import (
"fmt"
"github.com/urfave/cli/v2"
"github.com/urfave/cli/v2/altsrc"
"heckel.io/ntfy/client"
"heckel.io/ntfy/util"
"log"
"os"
"strings"
)

var (
defaultClientRootConfigFile = "/etc/ntfy/client.yml"
defaultClientUserConfigFile = "~/.config/ntfy/client.yml"
)

// New creates a new CLI application
func New() *cli.App {
return &cli.App{
Expand All @@ -35,8 +38,8 @@ func New() *cli.App {
}

func execMainApp(c *cli.Context) error {
log.Printf("\x1b[1;33mDeprecation notice: Please run the server using 'ntfy serve'; see 'ntfy -h' for help.\x1b[0m")
log.Printf("\x1b[1;33mThis way of running the server will be removed March 2022. See https://ntfy.sh/docs/deprecations/ for details.\x1b[0m")
fmt.Fprintln(c.App.ErrWriter, "\x1b[1;33mDeprecation notice: Please run the server using 'ntfy serve'; see 'ntfy -h' for help.\x1b[0m")
fmt.Fprintln(c.App.ErrWriter, "\x1b[1;33mThis way of running the server will be removed March 2022. See https://ntfy.sh/docs/deprecations/ for details.\x1b[0m")
return execServe(c)
}

Expand All @@ -58,15 +61,6 @@ func initConfigFileInputSource(configFlag string, flags []cli.Flag) cli.BeforeFu
}
}

func expandTopicURL(s string) string {
if strings.HasPrefix(s, "http://") || strings.HasPrefix(s, "https://") {
return s
} else if strings.Contains(s, "/") {
return fmt.Sprintf("https://%s", s)
}
return fmt.Sprintf("%s/%s", client.DefaultBaseURL, s)
}

func collapseTopicURL(s string) string {
return strings.TrimPrefix(strings.TrimPrefix(s, "https://"), "http://")
}
9 changes: 7 additions & 2 deletions cmd/publish.go
Expand Up @@ -46,7 +46,7 @@ func execPublish(c *cli.Context) error {
delay := c.String("delay")
noCache := c.Bool("no-cache")
noFirebase := c.Bool("no-firebase")
topicURL := expandTopicURL(c.Args().Get(0))
topic := c.Args().Get(0)
message := ""
if c.NArg() > 1 {
message = strings.Join(c.Args().Slice()[1:], " ")
Expand All @@ -70,5 +70,10 @@ func execPublish(c *cli.Context) error {
if noFirebase {
options = append(options, client.WithNoFirebase())
}
return client.DefaultClient.Publish(topicURL, message, options...)
conf, err := loadConfig(c)
if err != nil {
return err
}
cl := client.New(conf)
return cl.Publish(topic, message, options...)
}

0 comments on commit f266afa

Please sign in to comment.