git » sdk » commit cb1476a

Update message in storage on duplicate

author Stephen Paul Weber
2023-11-15 03:55:19 UTC
committer Stephen Paul Weber
2023-11-15 03:55:19 UTC
parent d62d24054fd62aa66f499cdc7a7fa15a3d166a38

Update message in storage on duplicate

Instead of discarding. The dupe may have useful new data such as MAM ID

xmpp/ChatMessage.hx +2 -2
xmpp/persistence/browser.js +7 -3

diff --git a/xmpp/ChatMessage.hx b/xmpp/ChatMessage.hx
index 88a012a..4e9d83b 100644
--- a/xmpp/ChatMessage.hx
+++ b/xmpp/ChatMessage.hx
@@ -56,14 +56,14 @@ class ChatMessage {
 		if (msg.text != null && (msg.lang == null || msg.lang == "")) {
 			msg.lang = stanza.getChild("body")?.attr.get("xml:lang");
 		}
-		final to = stanza.attr.get("to");
-		msg.to = to == null ? null : JID.parse(to);
 		final from = stanza.attr.get("from");
 		msg.from = from == null ? null : JID.parse(from);
 		msg.sender = stanza.attr.get("type") == "groupchat" ? msg.from : msg.from?.asBare();
 		final localJid = JID.parse(localJidStr);
 		final localJidBare = localJid.asBare();
 		final domain = localJid.domain;
+		final to = stanza.attr.get("to");
+		msg.to = to == null ? localJid : JID.parse(to);
 
 		if (msg.from != null && msg.from.equals(localJidBare)) {
 			var carbon = stanza.getChild("received", "urn:xmpp:carbons:2");
diff --git a/xmpp/persistence/browser.js b/xmpp/persistence/browser.js
index 1094cfb..9c21d77 100644
--- a/xmpp/persistence/browser.js
+++ b/xmpp/persistence/browser.js
@@ -212,12 +212,16 @@ exports.xmpp.persistence = {
 			storeMessage: function(account, message) {
 				const tx = db.transaction(["messages"], "readwrite");
 				const store = tx.objectStore("messages");
+				if (!message.chatId()) throw "Cannot store a message with no chatId";
 				if (!message.serverId && !message.localId) throw "Cannot store a message with no id";
 				if (!message.serverId && message.isIncoming()) throw "Cannot store an incoming message with no server id";
 				if (message.serverId && !message.serverIdBy) throw "Cannot store a message with a server id and no by";
-				promisifyRequest(store.index("localId").get([account, message.chatId(), message.localId || []])).then((result) => {
-					if (result && !message.isIncoming() && result.direction === "MessageSent") return; // duplicate, we trust our own stanza ids
-
+				promisifyRequest(store.index("localId").openCursor(IDBKeyRange.only([account, message.chatId(), message.localId || []]))).then((result) => {
+					if (result?.value && !message.isIncoming() && result?.value.direction === "MessageSent") {
+						// Duplicate, we trust our own sent ids
+						return promisifyRequest(result.delete());
+					}
+				}).then(() => {
 					store.put(serializeMessage(account, message));
 				});
 			},