Backend: Fallback to file extension for mime type detection

Signed-off-by: Michael Mayer <michael@liquidbytes.net>
This commit is contained in:
Michael Mayer 2020-09-20 15:12:45 +02:00
parent fb43754d8a
commit 9e37c86b67
3 changed files with 51 additions and 3 deletions

View file

@ -228,3 +228,12 @@ func (t FileType) FindFirst(fileName string, dirs []string, baseDir string, stri
return ""
}
// NormalizedExt returns the file extension without dot and in lowercase.
func NormalizedExt(fileName string) string {
if dot := strings.LastIndex(fileName, "."); dot != -1 && len(fileName[dot+1:]) >= 1 {
return strings.ToLower(fileName[dot+1:])
}
return ""
}

View file

@ -133,3 +133,40 @@ func TestFileType_FindFirst(t *testing.T) {
assert.Equal(t, Abs("testdata/directory/example.bmp"), result)
})
}
func TestNormalizedExt(t *testing.T) {
t.Run("none", func(t *testing.T) {
result := NormalizedExt("testdata/test")
assert.Equal(t, "", result)
})
t.Run("dot", func(t *testing.T) {
result := NormalizedExt("testdata/test.")
assert.Equal(t, "", result)
})
t.Run("test.z", func(t *testing.T) {
result := NormalizedExt("testdata/test.z")
assert.Equal(t, "z", result)
})
t.Run("test.jpg", func(t *testing.T) {
result := NormalizedExt("testdata/test.jpg")
assert.Equal(t, "jpg", result)
})
t.Run("test.PNG", func(t *testing.T) {
result := NormalizedExt("testdata/test.PNG")
assert.Equal(t, "png", result)
})
t.Run("test.MOV", func(t *testing.T) {
result := NormalizedExt("testdata/test.MOV")
assert.Equal(t, "mov", result)
})
t.Run("test.xmp", func(t *testing.T) {
result := NormalizedExt("testdata/test.xMp")
assert.Equal(t, "xmp", result)
})
}

View file

@ -30,9 +30,11 @@ func MimeType(filename string) string {
if _, err := handle.Read(buffer); err != nil {
return ""
} else if t, err := filetype.Get(buffer); err != nil {
return ""
} else {
} else if t, err := filetype.Get(buffer); err == nil && t != filetype.Unknown {
return t.MIME.Value
} else if t := filetype.GetType(NormalizedExt(filename)); t != filetype.Unknown {
return t.MIME.Value
} else {
return ""
}
}