From 9e37c86b67ce0b1b9285e4e2da295c3291eb32e4 Mon Sep 17 00:00:00 2001 From: Michael Mayer Date: Sun, 20 Sep 2020 15:12:45 +0200 Subject: [PATCH] Backend: Fallback to file extension for mime type detection Signed-off-by: Michael Mayer --- pkg/fs/filetype.go | 9 +++++++++ pkg/fs/filetype_test.go | 37 +++++++++++++++++++++++++++++++++++++ pkg/fs/mime.go | 8 +++++--- 3 files changed, 51 insertions(+), 3 deletions(-) diff --git a/pkg/fs/filetype.go b/pkg/fs/filetype.go index 206ecfbcc..1f77d6e5e 100644 --- a/pkg/fs/filetype.go +++ b/pkg/fs/filetype.go @@ -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 "" +} diff --git a/pkg/fs/filetype_test.go b/pkg/fs/filetype_test.go index 7f55774f9..a355844a3 100644 --- a/pkg/fs/filetype_test.go +++ b/pkg/fs/filetype_test.go @@ -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) + }) +} diff --git a/pkg/fs/mime.go b/pkg/fs/mime.go index 464ecd0c8..e5060b307 100644 --- a/pkg/fs/mime.go +++ b/pkg/fs/mime.go @@ -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 "" } }