aboutsummaryrefslogtreecommitdiff
path: root/telegram/utils.go
diff options
context:
space:
mode:
authorBohdan Horbeshko <bodqhrohro@gmail.com>2023-07-22 17:46:35 +0300
committerBohdan Horbeshko <bodqhrohro@gmail.com>2023-07-22 17:46:35 +0300
commit748366ad6a9dc4b2a269d5499ae1d5d7e8526762 (patch)
tree11af2e901a14cd9483abbd4e30a2ce024ad8488f /telegram/utils.go
parenteadef987be11dc22a89c2aad990814bd89add770 (diff)
Avoid webpage preview updates being sent as message edits (by hash matching)
Diffstat (limited to 'telegram/utils.go')
-rw-r--r--telegram/utils.go57
1 files changed, 57 insertions, 0 deletions
diff --git a/telegram/utils.go b/telegram/utils.go
index 9486349..4835696 100644
--- a/telegram/utils.go
+++ b/telegram/utils.go
@@ -2,8 +2,10 @@ package telegram
import (
"crypto/sha1"
+ "encoding/binary"
"fmt"
"github.com/pkg/errors"
+ "hash/maphash"
"io"
"io/ioutil"
"net/http"
@@ -1384,3 +1386,58 @@ func (c *Client) getCarbonFullJids(isOutgoing bool, ignoredResource string) []st
}
return jids
}
+
+func (c *Client) calculateMessageHash(messageId int64, content client.MessageContent) uint64 {
+ var h maphash.Hash
+ h.SetSeed(c.msgHashSeed)
+
+ buf8 := make([]byte, 8)
+ binary.BigEndian.PutUint64(buf8, uint64(messageId))
+ h.Write(buf8)
+
+ if content != nil && content.MessageContentType() == client.TypeMessageText {
+ textContent, ok := content.(*client.MessageText)
+ if !ok {
+ uhOh()
+ }
+
+ if textContent.Text != nil {
+ h.WriteString(textContent.Text.Text)
+ for _, entity := range textContent.Text.Entities {
+ buf4 := make([]byte, 4)
+ binary.BigEndian.PutUint32(buf4, uint32(entity.Offset))
+ h.Write(buf4)
+ binary.BigEndian.PutUint32(buf4, uint32(entity.Length))
+ h.Write(buf4)
+ h.WriteString(entity.Type.TextEntityTypeType())
+ }
+ }
+ }
+
+ return h.Sum64()
+}
+
+func (c *Client) updateLastMessageHash(chatId, messageId int64, content client.MessageContent) {
+ c.locks.lastMsgHashesLock.Lock()
+ defer c.locks.lastMsgHashesLock.Unlock()
+
+ c.lastMsgHashes[chatId] = c.calculateMessageHash(messageId, content)
+}
+
+func (c *Client) hasLastMessageHashChanged(chatId, messageId int64, content client.MessageContent) bool {
+ c.locks.lastMsgHashesLock.Lock()
+ defer c.locks.lastMsgHashesLock.Unlock()
+
+ oldHash, ok := c.lastMsgHashes[chatId]
+ newHash := c.calculateMessageHash(messageId, content)
+
+ if !ok {
+ log.Warnf("Last message hash for chat %v does not exist", chatId)
+ }
+ log.WithFields(log.Fields{
+ "old hash": oldHash,
+ "new hash": newHash,
+ }).Info("Message hashes")
+
+ return !ok || oldHash != newHash
+}