Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/MHSanaei/3x-ui.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHamidreza Ghavami <70919649+hamid-gh98@users.noreply.github.com>2023-05-20 18:59:28 +0300
committerHamidreza Ghavami <70919649+hamid-gh98@users.noreply.github.com>2023-05-20 18:59:28 +0300
commit8c5648eb09b0d6d1479f102156e8a548ed478caa (patch)
tree79f9bef907105c54c49ffde81f9808f260fbdf00 /web/global
parent4dfe527f203cbae9b90e77e876fcfd90803bcb26 (diff)
FIX callback query and BUTTON_DATA_INVALID error with hashStorage
Diffstat (limited to 'web/global')
-rw-r--r--web/global/hashStorage.go91
1 files changed, 91 insertions, 0 deletions
diff --git a/web/global/hashStorage.go b/web/global/hashStorage.go
new file mode 100644
index 00000000..099a54ed
--- /dev/null
+++ b/web/global/hashStorage.go
@@ -0,0 +1,91 @@
+package global
+
+import (
+ "crypto/md5"
+ "encoding/hex"
+ "sync"
+ "time"
+)
+
+type HashEntry struct {
+ Hash string
+ Value string
+ Timestamp time.Time
+}
+
+type HashStorage struct {
+ sync.RWMutex
+ Data map[string]HashEntry
+ Expiration time.Duration
+ ForceSave bool
+}
+
+func NewHashStorage(expiration time.Duration, forceSave bool) *HashStorage {
+ return &HashStorage{
+ Data: make(map[string]HashEntry),
+ Expiration: expiration,
+ ForceSave: forceSave,
+ }
+}
+
+func (h *HashStorage) AddHash(query string) string {
+ if h.ForceSave {
+ return h.saveValue(query)
+ }
+
+ // we only need to hash for more than 64 chars by default
+ if len(query) <= 64 {
+ return query
+ }
+
+ return h.saveValue(query)
+}
+
+func (h *HashStorage) saveValue(query string) string {
+ h.Lock()
+ defer h.Unlock()
+
+ md5Hash := md5.Sum([]byte(query))
+ md5HashString := hex.EncodeToString(md5Hash[:])
+
+ entry := HashEntry{
+ Hash: md5HashString,
+ Value: query,
+ Timestamp: time.Now(),
+ }
+
+ h.Data[md5HashString] = entry
+
+ return md5HashString
+}
+
+func (h *HashStorage) GetValue(hash string) string {
+ h.RLock()
+ defer h.RUnlock()
+
+ entry, exists := h.Data[hash]
+ if !exists {
+ return hash
+ }
+ return entry.Value
+}
+
+func (h *HashStorage) RemoveExpiredHashes() {
+ h.Lock()
+ defer h.Unlock()
+
+ now := time.Now()
+
+ for hash, entry := range h.Data {
+ if now.Sub(entry.Timestamp) > h.Expiration {
+ delete(h.Data, hash)
+ }
+ }
+}
+
+func (h *HashStorage) Reset() {
+ h.Lock()
+ defer h.Unlock()
+
+ h.Data = make(map[string]HashEntry)
+}