From 9a84e9a8b6b7a6f953301e54f19cdf4be73592e1 Mon Sep 17 00:00:00 2001
From: Bohdan Horbeshko <bodqhrohro@gmail.com>
Date: Sat, 3 Jun 2023 00:20:03 -0400
Subject: Store message ids in Badger DB

---
 xmpp/component.go       | 10 +++++++++-
 xmpp/gateway/gateway.go |  4 ++++
 xmpp/handlers.go        |  2 +-
 3 files changed, 14 insertions(+), 2 deletions(-)

(limited to 'xmpp')

diff --git a/xmpp/component.go b/xmpp/component.go
index 0f23d50..f0c481d 100644
--- a/xmpp/component.go
+++ b/xmpp/component.go
@@ -7,6 +7,7 @@ import (
 	"sync"
 	"time"
 
+	"dev.narayana.im/narayana/telegabber/badger"
 	"dev.narayana.im/narayana/telegabber/config"
 	"dev.narayana.im/narayana/telegabber/persistence"
 	"dev.narayana.im/narayana/telegabber/telegram"
@@ -38,7 +39,7 @@ var sizeRegex = regexp.MustCompile("\\A([0-9]+) ?([KMGTPE]?B?)\\z")
 
 // NewComponent starts a new component and wraps it in
 // a stream manager that you should start yourself
-func NewComponent(conf config.XMPPConfig, tc config.TelegramConfig) (*xmpp.StreamManager, *xmpp.Component, error) {
+func NewComponent(conf config.XMPPConfig, tc config.TelegramConfig, idsPath string) (*xmpp.StreamManager, *xmpp.Component, error) {
 	var err error
 
 	gateway.Jid, err = stanza.NewJid(conf.Jid)
@@ -53,6 +54,8 @@ func NewComponent(conf config.XMPPConfig, tc config.TelegramConfig) (*xmpp.Strea
 		}
 	}
 
+	gateway.IdsDB = badger.IdsDBOpen(idsPath)
+
 	tgConf = tc
 
 	if tc.Content.Quota != "" {
@@ -163,6 +166,8 @@ func heartbeat(component *xmpp.Component) {
 			// it would be resolved on the next iteration
 			SaveSessions()
 		}
+
+		gateway.IdsDB.Gc()
 	}
 }
 
@@ -240,6 +245,9 @@ func Close(component *xmpp.Component) {
 	// save sessions
 	SaveSessions()
 
+	// flush the ids database
+	gateway.IdsDB.Close()
+
 	// close stream
 	component.Disconnect()
 }
diff --git a/xmpp/gateway/gateway.go b/xmpp/gateway/gateway.go
index 534ee7e..29c8a07 100644
--- a/xmpp/gateway/gateway.go
+++ b/xmpp/gateway/gateway.go
@@ -6,6 +6,7 @@ import (
 	"strings"
 	"sync"
 
+	"dev.narayana.im/narayana/telegabber/badger"
 	"dev.narayana.im/narayana/telegabber/xmpp/extensions"
 
 	log "github.com/sirupsen/logrus"
@@ -30,6 +31,9 @@ var QueueLock = sync.Mutex{}
 // Jid stores the component's JID object
 var Jid *stanza.Jid
 
+// IdsDB provides a disk-backed bidirectional dictionary of Telegram and XMPP ids
+var IdsDB badger.IdsDB
+
 // DirtySessions denotes that some Telegram session configurations
 // were changed and need to be re-flushed to the YamlDB
 var DirtySessions = false
diff --git a/xmpp/handlers.go b/xmpp/handlers.go
index 780478a..5178acd 100644
--- a/xmpp/handlers.go
+++ b/xmpp/handlers.go
@@ -139,7 +139,7 @@ func HandleMessage(s xmpp.Sender, p stanza.Packet) {
 				}
 			}
 
-			session.ProcessOutgoingMessage(toID, text, msg.From, replyId)
+			session.ProcessOutgoingMessage(toID, text, msg.From, msg.Id, replyId)
 			return
 		} else {
 			toJid, err := stanza.NewJid(msg.To)
-- 
cgit v1.2.3