refactor(config): simplify MIME type lookup

This commit is contained in:
ayn2op 2026-08-31 18:41:04 -04:00
parent 0509f47775
commit 5e4018a742
3 changed files with 10 additions and 11 deletions

View file

@ -8,6 +8,7 @@ import (
"os"
"path"
"path/filepath"
"slices"
"sync"
"unicode/utf8"
@ -198,18 +199,16 @@ func (types *MIMETypes) UnmarshalTOML(value any) error {
return nil
}
func (types MIMETypes) Allows(mediaType string) bool {
func (types MIMETypes) Has(mediaType string) bool {
mediaType, _, err := mime.ParseMediaType(mediaType)
if err != nil {
return false
}
for _, pattern := range types {
if matches, _ := path.Match(pattern, mediaType); matches {
return true
}
}
return false
return slices.ContainsFunc(types, func(pattern string) bool {
matches, _ := path.Match(pattern, mediaType)
return matches
})
}
func applyDefaults(cfg *Config) {

View file

@ -146,7 +146,7 @@ func TestLoad(t *testing.T) {
})
}
func TestMIMETypesAllows(t *testing.T) {
func TestMIMETypesHas(t *testing.T) {
tests := []struct {
name string
allowed MIMETypes
@ -164,8 +164,8 @@ func TestMIMETypesAllows(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.allowed.Allows(tt.mediaType); got != tt.wantAllowed {
t.Fatalf("Allows(%q) = %v, want %v", tt.mediaType, got, tt.wantAllowed)
if got := tt.allowed.Has(tt.mediaType); got != tt.wantAllowed {
t.Fatalf("Has(%q) = %v, want %v", tt.mediaType, got, tt.wantAllowed)
}
})
}

View file

@ -1141,7 +1141,7 @@ func (ml *messagesList) openAttachment(attachment discord.Attachment) tview.Cmd
}
func (ml *messagesList) confirmAttachment(attachment discord.Attachment, action tview.Cmd) tview.Cmd {
if !ml.cfg.AllowedMIMETypes.Allows(attachment.ContentType) {
if !ml.cfg.AllowedMIMETypes.Has(attachment.ContentType) {
return ui.ShowModal(
"This attachment type is not allowed and may be unsafe. Continue anyway?",
ui.ModalButton{Label: "No"},