Files
mattermost/app/svg.go
Dean Whillier df6b8ff768 [MM-13158] Initial attempt at extracting SVG dimensions (#10332)
* initial attempt at extracting svg dimensions

* rafactor SVG dimensions extraction

* pass SVG parsing errors to calling context

* tweaks to svg parsing placement

- also stopped trying to pre/post process SVG’s as images

* add svg parsing tests

* updates for PR change requests

* code review updates

* correct a conditional typo
2019-02-27 14:06:56 -05:00

57 lines
1.6 KiB
Go

// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package app
import (
"encoding/xml"
"io"
"regexp"
"strconv"
"github.com/pkg/errors"
)
type SVGInfo struct {
Width int
Height int
}
func parseSVG(svgReader io.Reader) (SVGInfo, error) {
var parsedSVG struct {
Width string `xml:"width,attr,omitempty"`
Height string `xml:"height,attr,omitempty"`
ViewBox string `xml:"viewBox,attr,omitempty"`
}
svgInfo := SVGInfo{
Width: 0,
Height: 0,
}
viewBoxPattern := regexp.MustCompile("^([0-9]+)[, ]+([0-9]+)[, ]+([0-9]+)[, ]+([0-9]+)$")
dimensionPattern := regexp.MustCompile("(?i)^([0-9]+)(?:px)?$")
// decode provided SVG
if err := xml.NewDecoder(svgReader).Decode(&parsedSVG); err != nil {
return svgInfo, err
}
// prefer viewbox for SVG dimensions over width/height
if viewBoxMatches := viewBoxPattern.FindStringSubmatch(parsedSVG.ViewBox); len(viewBoxMatches) == 5 {
svgInfo.Width, _ = strconv.Atoi(viewBoxMatches[3])
svgInfo.Height, _ = strconv.Atoi(viewBoxMatches[4])
} else if len(parsedSVG.Width) > 0 && len(parsedSVG.Height) > 0 {
widthMatches := dimensionPattern.FindStringSubmatch(parsedSVG.Width)
heightMatches := dimensionPattern.FindStringSubmatch(parsedSVG.Height)
if len(widthMatches) == 2 && len(heightMatches) == 2 {
svgInfo.Width, _ = strconv.Atoi(widthMatches[1])
svgInfo.Height, _ = strconv.Atoi(heightMatches[1])
}
}
// if width and/or height are still zero, create new error
if svgInfo.Width == 0 || svgInfo.Height == 0 {
return svgInfo, errors.New("unable to extract SVG dimensions")
}
return svgInfo, nil
}