github.com/ashishbhate/mattermost-server@v5.11.1+incompatible/app/svg.go (about)

     1  // Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
     2  // See License.txt for license information.
     3  
     4  package app
     5  
     6  import (
     7  	"encoding/xml"
     8  	"io"
     9  	"regexp"
    10  	"strconv"
    11  
    12  	"github.com/pkg/errors"
    13  )
    14  
    15  type SVGInfo struct {
    16  	Width  int
    17  	Height int
    18  }
    19  
    20  func parseSVG(svgReader io.Reader) (SVGInfo, error) {
    21  	var parsedSVG struct {
    22  		Width   string `xml:"width,attr,omitempty"`
    23  		Height  string `xml:"height,attr,omitempty"`
    24  		ViewBox string `xml:"viewBox,attr,omitempty"`
    25  	}
    26  	svgInfo := SVGInfo{
    27  		Width:  0,
    28  		Height: 0,
    29  	}
    30  	viewBoxPattern := regexp.MustCompile("^([0-9]+)[, ]+([0-9]+)[, ]+([0-9]+)[, ]+([0-9]+)$")
    31  	dimensionPattern := regexp.MustCompile("(?i)^([0-9]+)(?:px)?$")
    32  
    33  	// decode provided SVG
    34  	if err := xml.NewDecoder(svgReader).Decode(&parsedSVG); err != nil {
    35  		return svgInfo, err
    36  	}
    37  
    38  	// prefer viewbox for SVG dimensions over width/height
    39  	if viewBoxMatches := viewBoxPattern.FindStringSubmatch(parsedSVG.ViewBox); len(viewBoxMatches) == 5 {
    40  		svgInfo.Width, _ = strconv.Atoi(viewBoxMatches[3])
    41  		svgInfo.Height, _ = strconv.Atoi(viewBoxMatches[4])
    42  	} else if len(parsedSVG.Width) > 0 && len(parsedSVG.Height) > 0 {
    43  		widthMatches := dimensionPattern.FindStringSubmatch(parsedSVG.Width)
    44  		heightMatches := dimensionPattern.FindStringSubmatch(parsedSVG.Height)
    45  		if len(widthMatches) == 2 && len(heightMatches) == 2 {
    46  			svgInfo.Width, _ = strconv.Atoi(widthMatches[1])
    47  			svgInfo.Height, _ = strconv.Atoi(heightMatches[1])
    48  		}
    49  	}
    50  
    51  	// if width and/or height are still zero, create new error
    52  	if svgInfo.Width == 0 || svgInfo.Height == 0 {
    53  		return svgInfo, errors.New("unable to extract SVG dimensions")
    54  	}
    55  	return svgInfo, nil
    56  }