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"
"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)
}