github.com/iikira/iikira-go-utils@v0.0.0-20230610031953-f2cb11cde33a/requester/downloader/utils.go (about)

     1  package downloader
     2  
     3  import (
     4  	"github.com/iikira/iikira-go-utils/pcsverbose"
     5  	"github.com/iikira/iikira-go-utils/requester"
     6  	mathrand "math/rand"
     7  	"mime"
     8  	"net/url"
     9  	"path"
    10  	"regexp"
    11  	"strconv"
    12  	"time"
    13  )
    14  
    15  var (
    16  	// ContentRangeRE Content-Range 正则
    17  	ContentRangeRE = regexp.MustCompile(`^.*? \d*?-\d*?/(\d*?)$`)
    18  
    19  	// ranSource 随机数种子
    20  	ranSource = mathrand.NewSource(time.Now().UnixNano())
    21  
    22  	// ran 一个随机数实例
    23  	ran = mathrand.New(ranSource)
    24  )
    25  
    26  // RandomNumber 生成指定区间随机数
    27  func RandomNumber(min, max int) int {
    28  	if min > max {
    29  		min, max = max, min
    30  	}
    31  	return ran.Intn(max-min) + min
    32  }
    33  
    34  // GetFileName 获取文件名
    35  func GetFileName(uri string, client *requester.HTTPClient) (filename string, err error) {
    36  	if client == nil {
    37  		client = requester.NewHTTPClient()
    38  	}
    39  
    40  	resp, err := client.Req("HEAD", uri, nil, nil)
    41  	if resp != nil {
    42  		defer resp.Body.Close()
    43  	}
    44  	if err != nil {
    45  		return "", err
    46  	}
    47  
    48  	_, params, err := mime.ParseMediaType(resp.Header.Get("Content-Disposition"))
    49  	if err != nil {
    50  		pcsverbose.Verbosef("DEBUG: GetFileName ParseMediaType error: %s\n", err)
    51  		return path.Base(uri), nil
    52  	}
    53  
    54  	filename, err = url.QueryUnescape(params["filename"])
    55  	if err != nil {
    56  		return
    57  	}
    58  
    59  	if filename == "" {
    60  		filename = path.Base(uri)
    61  	}
    62  
    63  	return
    64  }
    65  
    66  // ParseContentRange 解析Content-Range
    67  func ParseContentRange(contentRange string) (contentLength int64) {
    68  	raw := ContentRangeRE.FindStringSubmatch(contentRange)
    69  	if len(raw) < 2 {
    70  		return -1
    71  	}
    72  
    73  	c, err := strconv.ParseInt(raw[1], 10, 64)
    74  	if err != nil {
    75  		return -1
    76  	}
    77  	return c
    78  }
    79  
    80  func fixCacheSize(size *int) {
    81  	if *size < 1024 {
    82  		*size = 1024
    83  	}
    84  }