From 0d2b3016f4ac26b51ac4719a58d99cc98675b599 Mon Sep 17 00:00:00 2001 From: Lilia <58743698+lilousky@users.noreply.github.com> Date: Sun, 15 Dec 2024 12:51:40 -0500 Subject: [PATCH] Profanity update Mii names now get normalised, and the bad word list's cache gets cleared if the profanity.txt file has been updated. --- nas/profanity.go | 52 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 49 insertions(+), 3 deletions(-) diff --git a/nas/profanity.go b/nas/profanity.go index ce425a9..2b8cd14 100644 --- a/nas/profanity.go +++ b/nas/profanity.go @@ -5,18 +5,42 @@ import ( "errors" "os" "strings" + "time" ) var profanityFilePath = "./profanity.txt" var profanityFileLines []string = nil +var lastModTime time.Time + +var symbolEquivalences = map[rune]rune{ + '1': 'i', + '0': 'o', + '5': 's', + '4': 'a', + '3': 'e', + '7': 't', + '9': 'g', + '2': 'z', + '(': 'c', +} func CacheProfanityFile() error { + fileInfo, err := os.Stat(profanityFilePath) + if err != nil { + return err + } + + if !fileInfo.ModTime().After(lastModTime) && profanityFileLines != nil { + return nil + } + file, err := os.Open(profanityFilePath) if err != nil { return err } defer file.Close() + profanityFileLines = nil scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() @@ -32,16 +56,34 @@ func CacheProfanityFile() error { return errors.New("the file '" + profanityFilePath + "' is empty") } + lastModTime = fileInfo.ModTime() return nil } +func normalizeWord(word string) string { + var normalized strings.Builder + for _, char := range word { + if equivalent, exists := symbolEquivalences[char]; exists { + normalized.WriteRune(equivalent) + } else { + normalized.WriteRune(char) + } + } + return normalized.String() +} + func IsBadWord(word string) (bool, error) { if !isProfanityFileCached() { - return false, errors.New("the file '" + profanityFilePath + "' has not been cached") + err := CacheProfanityFile() + if err != nil { + return false, errors.New("the file '" + profanityFilePath + "' has not been cached") + } + } + normalizedWord := normalizeWord(word) for _, line := range profanityFileLines { - if strings.EqualFold(line, word) { + if strings.EqualFold(line, normalizedWord) { return true, nil } } @@ -50,5 +92,9 @@ func IsBadWord(word string) (bool, error) { } func isProfanityFileCached() bool { - return profanityFileLines != nil + fileInfo, err := os.Stat(profanityFilePath) + if err != nil { + return false + } + return profanityFileLines != nil && !fileInfo.ModTime().After(lastModTime) }