From ba045a947f7247c6ce9f022598b0b351c992c2ca Mon Sep 17 00:00:00 2001 From: Noah Date: Tue, 11 Jun 2024 14:17:15 -0500 Subject: [PATCH] Fix messages being deleted as they are added to the queue (fix #26) --- matrix.go | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/matrix.go b/matrix.go index 99c7944..e39c9d6 100644 --- a/matrix.go +++ b/matrix.go @@ -6,6 +6,7 @@ import ( "fmt" "log" "strings" + "sync" "time" "maunium.net/go/mautrix" @@ -31,12 +32,17 @@ type MatrixCommand struct { } // Output queue. -var MatrixOut []MatrixMessage +var MatrixOut struct { + queue []MatrixMessage + mux sync.Mutex +} // sendMessage sends a message through Matrix. func sendMessage(msg MatrixMessage) { log.Print(msg.text) - MatrixOut = append(MatrixOut, msg) + MatrixOut.mux.Lock() + MatrixOut.queue = append(MatrixOut.queue, msg) + MatrixOut.mux.Unlock() } // sendError sends an error through Matrix. @@ -116,15 +122,16 @@ func initMatrix() { go func() { for range time.Tick(time.Second * 2) { - if len(MatrixOut) > 0 { + MatrixOut.mux.Lock() + if len(MatrixOut.queue) > 0 { text := "" - for i, msg := range MatrixOut { + for i, msg := range MatrixOut.queue { text += msg.text - if i != len(MatrixOut) { + if i != len(MatrixOut.queue) { text += "\n" } } - MatrixOut = []MatrixMessage{} + MatrixOut.queue = []MatrixMessage{} _, err := client.SendMessageEvent(context.Background(), id.RoomID(configuration.matrix.room_id), event.EventMessage, @@ -135,6 +142,7 @@ func initMatrix() { continue } } + MatrixOut.mux.Unlock() } }()