From f2bff1fd8089a3bd415743b9d8ad14dd9e906ee2 Mon Sep 17 00:00:00 2001 From: Melora Hugues Date: Sat, 11 Mar 2023 16:03:45 +0100 Subject: [PATCH] Add first working basic version for the sender --- .gitignore | 2 + client.py | 31 +++++++++++++ go.mod | 8 ++++ go.sum | 42 +++++++++++++++++ notifier/Makefile | 7 +++ notifier/config/config.go | 65 ++++++++++++++++++++++++++ notifier/listener/listener.go | 86 +++++++++++++++++++++++++++++++++++ notifier/logger/logger.go | 10 ++++ notifier/main.go | 79 ++++++++++++++++++++++++++++++++ notifier/sender/sender.go | 61 +++++++++++++++++++++++++ 10 files changed, 391 insertions(+) create mode 100644 client.py create mode 100644 go.mod create mode 100644 go.sum create mode 100644 notifier/Makefile create mode 100644 notifier/config/config.go create mode 100644 notifier/listener/listener.go create mode 100644 notifier/logger/logger.go create mode 100644 notifier/main.go create mode 100644 notifier/sender/sender.go diff --git a/.gitignore b/.gitignore index adf8f72..2ff740f 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,5 @@ # Go workspace file go.work +# Build directory +**/build diff --git a/client.py b/client.py new file mode 100644 index 0000000..6d77fb2 --- /dev/null +++ b/client.py @@ -0,0 +1,31 @@ +import argparse +import subprocess +import sys +from pathlib import Path + + +MSG_ROUTE = "/" + + +def send_post_request(sock_path: Path, route: str, msg: str) -> int: + command = ["/usr/bin/curl", "-X", "POST", "--unix-socket", str(sock_path), f"http://localhost{route}", "-d", msg] + ret = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if ret.returncode != 0: + print(f"Failed to send post request: {ret.stderr.decode()}") + return ret.returncode + print(ret.stdout.decode()) + print("OK") + return 0 + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + prog="telegram_notifier_client", + description="Interact with the listening sock for the Telegram notifier", + ) + parser.add_argument("-f", "--filename", type=str, help="Path for the listening sock", default="") + parser.add_argument("-i", "--input", type=str, help="Message to send", default="hello world") + + args = parser.parse_args() + + sys.exit(send_post_request(args.filename, MSG_ROUTE, args.input)) diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..6417fe0 --- /dev/null +++ b/go.mod @@ -0,0 +1,8 @@ +module git.faercol.me/faercol/telegram-notifier/notifier + +go 1.16 + +require ( + github.com/ahugues/go-telegram-api v0.2.0 + github.com/sirupsen/logrus v1.9.0 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..c0ac725 --- /dev/null +++ b/go.sum @@ -0,0 +1,42 @@ +github.com/ahugues/go-telegram-api v0.2.0 h1:wAY4qr0T0I2mgW1HxAZFdzhOdXuZ5WE4e8GNR4t7Yrs= +github.com/ahugues/go-telegram-api v0.2.0/go.mod h1:8I/JWxd9GYM7dHOgGmkRI3Ei1u+nGvzeR2knIMmFw7E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= +github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/notifier/Makefile b/notifier/Makefile new file mode 100644 index 0000000..a39e6c4 --- /dev/null +++ b/notifier/Makefile @@ -0,0 +1,7 @@ +.PHONY: build test + +build: + go build -o build/ + +test: + go test -v ./... diff --git a/notifier/config/config.go b/notifier/config/config.go new file mode 100644 index 0000000..1ddbeb7 --- /dev/null +++ b/notifier/config/config.go @@ -0,0 +1,65 @@ +package config + +import ( + "encoding/json" + "fmt" + "os" + + "github.com/sirupsen/logrus" +) + +type TelegramConfig struct { + ChannelID int64 `json:"channel_id"` + Token string `json:"token"` +} + +type LogConfig struct { + Level logrus.Level +} + +type jsonLogConfig struct { + Level string `json:"level"` +} + +type ListenerConfig struct { + SockPath string `json:"sock_path"` +} + +type Config struct { + Telegram TelegramConfig + Log LogConfig + Listener ListenerConfig +} + +type jsonConfig struct { + Telegram TelegramConfig `json:"telegram"` + Log jsonLogConfig `json:"log"` + Listener ListenerConfig `json:"listener"` +} + +func parseLevel(lvlStr string) logrus.Level { + for _, lvl := range logrus.AllLevels { + if lvl.String() == lvlStr { + return lvl + } + } + return logrus.InfoLevel +} + +func New(filepath string) (*Config, error) { + content, err := os.ReadFile(filepath) + if err != nil { + return nil, fmt.Errorf("failed to read config file %q: %w", filepath, err) + } + var jsonConf jsonConfig + if err := json.Unmarshal(content, &jsonConf); err != nil { + return nil, fmt.Errorf("failed to parse config file: %w", err) + } + return &Config{ + Telegram: jsonConf.Telegram, + Log: LogConfig{ + Level: parseLevel(jsonConf.Log.Level), + }, + Listener: jsonConf.Listener, + }, nil +} diff --git a/notifier/listener/listener.go b/notifier/listener/listener.go new file mode 100644 index 0000000..42a359b --- /dev/null +++ b/notifier/listener/listener.go @@ -0,0 +1,86 @@ +package listener + +import ( + "context" + "errors" + "fmt" + "io/ioutil" + "net" + "net/http" + "os" +) + +type Listener struct { + ctx context.Context + cancel context.CancelFunc + httpSrv *http.Server + exportChan chan string + errorChan chan error + listener net.Listener + handler *http.ServeMux +} + +func New(sockPath string) (*Listener, error) { + if err := os.Remove(sockPath); err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("failed to cleanup previously existing socket: %w", err) + } + + sock, err := net.Listen("unix", sockPath) + if err != nil { + return nil, fmt.Errorf("failed to create unix socket: %w", err) + } + + m := http.NewServeMux() + + return &Listener{ + handler: m, + httpSrv: &http.Server{ + Handler: m, + }, + listener: sock, + exportChan: make(chan string, 10), + errorChan: make(chan error, 10), + }, nil +} + +func (l *Listener) initMux() { + l.handler.HandleFunc("/", l.sendMessageHandler) +} + +func (l *Listener) Run(ctx context.Context) { + l.ctx, l.cancel = context.WithCancel(ctx) + l.initMux() + if err := l.httpSrv.Serve(l.listener); err != nil { + l.errorChan <- fmt.Errorf("failed to serve HTTP server: %w", err) + } +} + +func (l *Listener) sendMessage(message string) { + l.exportChan <- message +} + +func (l *Listener) sendMessageHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + + // TODO: use max length instead of writing everything + bod, err := ioutil.ReadAll(r.Body) + if err != nil { + l.errorChan <- fmt.Errorf("failed to read body: %w", err) + w.WriteHeader(http.StatusBadRequest) + return + } + + l.sendMessage(string(bod)) + w.WriteHeader(http.StatusOK) +} + +func (l *Listener) ExportChan() <-chan string { + return l.exportChan +} + +func (l *Listener) ErrorChan() <-chan error { + return l.errorChan +} diff --git a/notifier/logger/logger.go b/notifier/logger/logger.go new file mode 100644 index 0000000..1db7579 --- /dev/null +++ b/notifier/logger/logger.go @@ -0,0 +1,10 @@ +package logger + +import "github.com/sirupsen/logrus" + +var L logrus.Logger + +func Init(level logrus.Level) { + L = *logrus.New() + L.SetLevel(level) +} diff --git a/notifier/main.go b/notifier/main.go new file mode 100644 index 0000000..670176d --- /dev/null +++ b/notifier/main.go @@ -0,0 +1,79 @@ +package main + +import ( + "context" + "flag" + "os" + "os/signal" + + "git.faercol.me/faercol/telegram-notifier/notifier/notifier/config" + "git.faercol.me/faercol/telegram-notifier/notifier/notifier/listener" + "git.faercol.me/faercol/telegram-notifier/notifier/notifier/logger" + "git.faercol.me/faercol/telegram-notifier/notifier/notifier/sender" +) + +type cliArgs struct { + configPath string +} + +func parseArgs() *cliArgs { + configPath := flag.String("config", "", "Path to the JSON configuration file") + + flag.Parse() + + return &cliArgs{ + configPath: *configPath, + } +} + +func main() { + args := parseArgs() + + mainCtx, cancel := context.WithCancel(context.Background()) + + conf, err := config.New(args.configPath) + if err != nil { + panic(err) + } + + logger.Init(conf.Log.Level) + logger.L.Infof("Intialized logger with level %v", conf.Log.Level) + + logger.L.Debug("Initializing Telegram message sender") + + l, err := listener.New(conf.Listener.SockPath) + if err != nil { + logger.L.Fatalf("Failed to initialize listener: %s", err.Error()) + } + s := sender.New(conf, l.ExportChan()) + + go l.Run(mainCtx) + go s.Run(mainCtx) + + c := make(chan os.Signal, 1) + signal.Notify(c, os.Interrupt) + + logger.L.Info("Telegram message sender is operational") + +outerloop: + for { + select { + case <-c: + logger.L.Info("Stopping Telegram message sender") + cancel() + break outerloop + case <-s.Exit(): + logger.L.Fatal("Unexpected exit from the sender") + case err := <-l.ErrorChan(): + logger.L.Errorf("Unexpected error from listener: %s", err.Error()) + case err := <-s.ErrChan(): + logger.L.Errorf("Unexpected error from sender: %s", err.Error()) + } + } + + logger.L.Debug("Waiting for all services to shut down") + <-s.Exit() + + logger.L.Info("Telegram message sender successfully stopped") + os.Exit(0) +} diff --git a/notifier/sender/sender.go b/notifier/sender/sender.go new file mode 100644 index 0000000..371d691 --- /dev/null +++ b/notifier/sender/sender.go @@ -0,0 +1,61 @@ +package sender + +import ( + "context" + "time" + + "git.faercol.me/faercol/telegram-notifier/notifier/notifier/config" + "git.faercol.me/faercol/telegram-notifier/notifier/notifier/logger" + "github.com/ahugues/go-telegram-api/bot" + "github.com/ahugues/go-telegram-api/structs" + "github.com/sirupsen/logrus" +) + +type Sender struct { + ctx context.Context + cancel context.CancelFunc + tgBot bot.Bot + tgChatID int64 + timeGetter func() time.Time + errChan chan error + exitChan chan struct{} + msgChan <-chan string + logger *logrus.Logger +} + +func (s *Sender) Run(ctx context.Context) { + s.ctx, s.cancel = context.WithCancel(ctx) + for { + select { + case msg := <-s.msgChan: + s.logger.Debug("Sending a new message") + s.tgBot.SendMessage(s.ctx, s.tgChatID, msg, structs.FormattingMarkdownV2) + case <-s.ctx.Done(): + s.logger.Info("Stopping Telegram sender") + s.exitChan <- struct{}{} + return + } + } +} + +func (s *Sender) ErrChan() <-chan error { + return s.errChan +} + +func (s *Sender) Exit() <-chan struct{} { + return s.exitChan +} + +func New(config *config.Config, msgChan <-chan string) *Sender { + tgBot := bot.New(config.Telegram.Token) + + return &Sender{ + tgBot: tgBot, + tgChatID: config.Telegram.ChannelID, + timeGetter: time.Now, + errChan: make(chan error, 10), + exitChan: make(chan struct{}, 1), + logger: &logger.L, + msgChan: msgChan, + } +}