github.com/vnforks/kid/v5@v5.22.1-0.20200408055009-b89d99c65676/app/download.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package app
     5  
     6  import (
     7  	"io/ioutil"
     8  	"net/url"
     9  	"time"
    10  
    11  	"github.com/vnforks/kid/v5/model"
    12  	"github.com/pkg/errors"
    13  )
    14  
    15  const (
    16  	// HTTP_REQUEST_TIMEOUT defines a high timeout for downloading large files
    17  	// from an external URL to avoid slow connections from failing to install.
    18  	HTTP_REQUEST_TIMEOUT = 1 * time.Hour
    19  )
    20  
    21  func (a *App) DownloadFromURL(downloadURL string) ([]byte, error) {
    22  	if !model.IsValidHttpUrl(downloadURL) {
    23  		return nil, errors.Errorf("invalid url %s", downloadURL)
    24  	}
    25  
    26  	u, err := url.ParseRequestURI(downloadURL)
    27  	if err != nil {
    28  		return nil, errors.Errorf("failed to parse url %s", downloadURL)
    29  	}
    30  	if !*a.Config().PluginSettings.AllowInsecureDownloadUrl && u.Scheme != "https" {
    31  		return nil, errors.Errorf("insecure url not allowed %s", downloadURL)
    32  	}
    33  
    34  	client := a.HTTPService().MakeClient(true)
    35  	client.Timeout = HTTP_REQUEST_TIMEOUT
    36  
    37  	resp, err := client.Get(downloadURL)
    38  	if err != nil {
    39  		return nil, errors.Wrapf(err, "failed to fetch from %s", downloadURL)
    40  	}
    41  	defer resp.Body.Close()
    42  
    43  	return ioutil.ReadAll(resp.Body)
    44  }