FIX hashStorage

This commit is contained in:
Hamidreza Ghavami 2023-05-20 21:46:42 +04:30
parent 8c5648eb09
commit 786a3ac992
No known key found for this signature in database
GPG key ID: 402C6797325182D9
2 changed files with 22 additions and 7 deletions

View file

@ -3,8 +3,10 @@ package global
import ( import (
"crypto/md5" "crypto/md5"
"encoding/hex" "encoding/hex"
"regexp"
"sync" "sync"
"time" "time"
"x-ui/util/common"
) )
type HashEntry struct { type HashEntry struct {
@ -59,15 +61,23 @@ func (h *HashStorage) saveValue(query string) string {
return md5HashString return md5HashString
} }
func (h *HashStorage) GetValue(hash string) string { func (h *HashStorage) GetValue(hash string) (string, error) {
h.RLock() h.RLock()
defer h.RUnlock() defer h.RUnlock()
entry, exists := h.Data[hash] entry, exists := h.Data[hash]
if !exists { if !exists {
return hash if h.isMD5(hash) {
return "", common.NewError("hash not found in storage!")
} }
return entry.Value return hash, nil
}
return entry.Value, nil
}
func (h *HashStorage) isMD5(hash string) bool {
match, _ := regexp.MatchString("^[a-f0-9]{32}$", hash)
return match
} }
func (h *HashStorage) RemoveExpiredHashes() { func (h *HashStorage) RemoveExpiredHashes() {

View file

@ -61,8 +61,9 @@ func (t *Tgbot) Start(i18nFS embed.FS) error {
return err return err
} }
// init hash storage // init hash storage => store callback queries
t.hashStorage = global.NewHashStorage(5*time.Minute, false) // NOTE: it only save the query if its length is more than 64 chars.
t.hashStorage = global.NewHashStorage(20*time.Minute, false)
tgBottoken, err := t.settingService.GetTgBotToken() tgBottoken, err := t.settingService.GetTgBotToken()
if err != nil || tgBottoken == "" { if err != nil || tgBottoken == "" {
@ -199,8 +200,12 @@ func (t *Tgbot) asnwerCallback(callbackQuery *telego.CallbackQuery, isAdmin bool
chatId := callbackQuery.Message.Chat.ID chatId := callbackQuery.Message.Chat.ID
if isAdmin { if isAdmin {
// get query from hash storage (if the query was <= 64 chars hash storage dont save the hash and return data itself) // get query from hash storage
decodedQuery := t.hashStorage.GetValue(callbackQuery.Data) decodedQuery, err := t.hashStorage.GetValue(callbackQuery.Data)
if err != nil {
t.SendMsgToTgbot(chatId, "Query not found! Please use the command again!")
return
}
dataArray := strings.Split(decodedQuery, " ") dataArray := strings.Split(decodedQuery, " ")
if len(dataArray) >= 2 && len(dataArray[1]) > 0 { if len(dataArray) >= 2 && len(dataArray[1]) > 0 {