media: Also consider extension in FromContent

As used in `resources.GetRemote`.

This will now reject image files with text and text files with images.
This commit is contained in:
Bjørn Erik Pedersen
2021-12-21 10:35:33 +01:00
parent ce04011096
commit 6779117f72
7 changed files with 85 additions and 43 deletions

View File

@@ -110,21 +110,30 @@ func (c *Client) FromRemote(uri string, optionsm map[string]interface{}) (resour
}
}
var extensionHint string
var extensionHints []string
if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 {
extensionHint = arr[0]
contentType := res.Header.Get("Content-Type")
// mime.ExtensionsByType gives a long list of extensions for text/plain,
// just use ".txt".
if strings.HasPrefix(contentType, "text/plain") {
extensionHints = []string{".txt"}
} else {
exts, _ := mime.ExtensionsByType(contentType)
if exts != nil {
extensionHints = exts
}
}
// Look for a file extention
if extensionHint == "" {
// Look for a file extention. If it's .txt, look for a more specific.
if extensionHints == nil || extensionHints[0] == ".txt" {
if ext := path.Ext(filename); ext != "" {
extensionHint = ext
extensionHints = []string{ext}
}
}
// Now resolve the media type primarily using the content.
mediaType := media.FromContent(c.rs.MediaTypes, extensionHint, body)
mediaType := media.FromContent(c.rs.MediaTypes, extensionHints, body)
if mediaType.IsZero() {
return nil, errors.Errorf("failed to resolve media type for remote resource %q", uri)
}
@@ -140,7 +149,6 @@ func (c *Client) FromRemote(uri string, optionsm map[string]interface{}) (resour
},
RelTargetFilename: filepath.Clean(resourceID),
})
}
func (c *Client) validateFromRemoteArgs(uri string, options fromRemoteOptions) error {
@@ -213,7 +221,7 @@ func (o fromRemoteOptions) BodyReader() io.Reader {
}
func decodeRemoteOptions(optionsm map[string]interface{}) (fromRemoteOptions, error) {
var options = fromRemoteOptions{
options := fromRemoteOptions{
Method: "GET",
}
@@ -224,5 +232,4 @@ func decodeRemoteOptions(optionsm map[string]interface{}) (fromRemoteOptions, er
options.Method = strings.ToUpper(options.Method)
return options, nil
}