Profanity update

Mii names now get normalised, and the bad word list's cache gets cleared if the profanity.txt file has been updated.
This commit is contained in:
Lilia 2024-12-15 12:51:40 -05:00
parent b20accb031
commit 0d2b3016f4

View File

@ -5,18 +5,42 @@ import (
"errors" "errors"
"os" "os"
"strings" "strings"
"time"
) )
var profanityFilePath = "./profanity.txt" var profanityFilePath = "./profanity.txt"
var profanityFileLines []string = nil 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 { 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) file, err := os.Open(profanityFilePath)
if err != nil { if err != nil {
return err return err
} }
defer file.Close() defer file.Close()
profanityFileLines = nil
scanner := bufio.NewScanner(file) scanner := bufio.NewScanner(file)
for scanner.Scan() { for scanner.Scan() {
line := scanner.Text() line := scanner.Text()
@ -32,16 +56,34 @@ func CacheProfanityFile() error {
return errors.New("the file '" + profanityFilePath + "' is empty") return errors.New("the file '" + profanityFilePath + "' is empty")
} }
lastModTime = fileInfo.ModTime()
return nil 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) { func IsBadWord(word string) (bool, error) {
if !isProfanityFileCached() { 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 { for _, line := range profanityFileLines {
if strings.EqualFold(line, word) { if strings.EqualFold(line, normalizedWord) {
return true, nil return true, nil
} }
} }
@ -50,5 +92,9 @@ func IsBadWord(word string) (bool, error) {
} }
func isProfanityFileCached() bool { func isProfanityFileCached() bool {
return profanityFileLines != nil fileInfo, err := os.Stat(profanityFilePath)
if err != nil {
return false
}
return profanityFileLines != nil && !fileInfo.ModTime().After(lastModTime)
} }