github.com/qjfoidnh/BaiduPCS-Go@v0.0.0-20231011165705-caa18a3765f3/baidupcs/internal/panhome/parse.go (about)

     1  package panhome
     2  
     3  import (
     4  	"errors"
     5  	"io/ioutil"
     6  	"net/http"
     7  	"net/url"
     8  	"regexp"
     9  	"unsafe"
    10  )
    11  
    12  var (
    13  	signInfoRE         = regexp.MustCompile(`"sign1":"(.*?)"[\s\S]*"sign3":"(.*?)","timestamp":(\d*?),`)
    14  	ErrCookieInvalid   = errors.New("cookie is invalid")
    15  	ErrUnknownLocation = errors.New("unknown location")
    16  	ErrMatchPanHome    = errors.New("网盘首页数据匹配出错")
    17  )
    18  
    19  func (ph *PanHome) getSignInfo() error {
    20  	ph.client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
    21  		return http.ErrUseLastResponse
    22  	}
    23  	u := *panBaiduComURL
    24  	u.Path = "/disk/home"
    25  	resp, err := ph.client.Req(http.MethodGet, u.String(), nil, map[string]string{
    26  		"User-Agent": PanHomeUserAgent,
    27  	})
    28  	if resp != nil {
    29  		defer resp.Body.Close()
    30  	}
    31  	if err != nil {
    32  		return err
    33  	}
    34  
    35  	loc := resp.Header.Get("Location")
    36  	switch loc {
    37  	case "/":
    38  		return ErrCookieInvalid
    39  	case "":
    40  		//pass
    41  	default:
    42  		locU, err := url.Parse(loc)
    43  		if err != nil {
    44  			return ErrUnknownLocation
    45  		}
    46  		if locU.Host == "passport.baidu.com" {
    47  			return ErrCookieInvalid
    48  		}
    49  		return ErrUnknownLocation
    50  	}
    51  
    52  	body, err := ioutil.ReadAll(resp.Body)
    53  	if err != nil {
    54  		return err
    55  	}
    56  
    57  	matchRes := signInfoRE.FindSubmatch(body)
    58  	if len(matchRes) <= 3 {
    59  		return ErrMatchPanHome
    60  	}
    61  
    62  	ph.sign1 = []rune(*(*string)(unsafe.Pointer(&matchRes[1])))
    63  	ph.sign3 = []rune(*(*string)(unsafe.Pointer(&matchRes[2])))
    64  	ph.timestamp = *(*string)(unsafe.Pointer(&matchRes[3]))
    65  	return nil
    66  }