1
0
Fork 0
hswro-alarm-bot/sender_worker.go

73 lines
1.6 KiB
Go
Raw Normal View History

2024-02-10 23:13:31 +00:00
package main
import (
2024-02-11 21:48:05 +00:00
"log"
2024-02-10 23:13:31 +00:00
"strings"
"sync"
)
type GenericMessage struct {
2024-02-11 13:56:03 +00:00
chatId int64
msg string
2024-02-10 23:13:31 +00:00
}
type Sender interface {
Send(msg GenericMessage) error
}
2024-02-11 10:51:41 +00:00
type Sleeper interface {
Sleep(ch chan<- interface{})
}
2024-02-11 21:48:05 +00:00
func tgSenderWorker(tgEvents <-chan GenericMessage, s Sender, wg *sync.WaitGroup, sleeper Sleeper, logger *log.Logger) {
logger.Print("Starting")
2024-02-10 23:13:31 +00:00
wg.Add(1)
defer wg.Done()
messagesToSend := make(map[int64]*strings.Builder)
waitingStarted := false
timeoutEvents := make(chan interface{})
loop:
2024-02-10 23:13:31 +00:00
for {
select {
2024-02-11 13:56:03 +00:00
case ev, ok := <-tgEvents:
2024-02-10 23:13:31 +00:00
if !ok {
break loop
2024-02-10 23:13:31 +00:00
}
// Collect all messages to send them at once
2024-02-11 13:56:03 +00:00
_, messageBuilderExists := messagesToSend[ev.chatId]
2024-02-10 23:13:31 +00:00
if !messageBuilderExists {
2024-02-11 13:56:03 +00:00
messagesToSend[ev.chatId] = &strings.Builder{}
2024-02-10 23:13:31 +00:00
}
2024-02-11 13:56:03 +00:00
messagesToSend[ev.chatId].WriteString(ev.msg)
messagesToSend[ev.chatId].WriteRune('\n')
2024-02-10 23:13:31 +00:00
if !waitingStarted {
2024-02-11 21:48:05 +00:00
logger.Print("Waiting for more messages to arrive before sending...")
2024-02-10 23:13:31 +00:00
waitingStarted = true
2024-02-11 10:51:41 +00:00
sleeper.Sleep(timeoutEvents)
2024-02-10 23:13:31 +00:00
}
case <-timeoutEvents:
2024-02-11 21:48:05 +00:00
logger.Print("Time's up, sending all messages we've got for now.")
2024-02-10 23:13:31 +00:00
waitingStarted = false
2024-02-11 13:56:03 +00:00
for chatId, msgBuilder := range messagesToSend {
err := s.Send(GenericMessage{chatId, msgBuilder.String()})
2024-02-10 23:13:31 +00:00
if err != nil {
// TODO: handle it better
panic(err)
}
2024-02-11 13:56:03 +00:00
delete(messagesToSend, chatId)
2024-02-10 23:13:31 +00:00
}
}
}
2024-02-10 23:13:31 +00:00
2024-02-11 21:48:05 +00:00
logger.Print("Exiting")
// If anything is left to be sent, send it now
2024-02-11 13:56:03 +00:00
for chatId, msgBuilder := range messagesToSend {
err := s.Send(GenericMessage{chatId, msgBuilder.String()})
if err != nil {
// TODO: handle it better
panic(err)
2024-02-10 23:13:31 +00:00
}
}
}