github.com/cloudreve/Cloudreve/v3@v3.0.0-20240224133659-3edb00a6484c/pkg/hashid/hash.go (about)

     1  package hashid
     2  
     3  import (
     4  	"errors"
     5  
     6  	"github.com/cloudreve/Cloudreve/v3/pkg/conf"
     7  	"github.com/speps/go-hashids"
     8  )
     9  
    10  // ID类型
    11  const (
    12  	ShareID  = iota // 分享
    13  	UserID          // 用户
    14  	FileID          // 文件ID
    15  	FolderID        // 目录ID
    16  	TagID           // 标签ID
    17  	PolicyID        // 存储策略ID
    18  	SourceLinkID
    19  )
    20  
    21  var (
    22  	// ErrTypeNotMatch ID类型不匹配
    23  	ErrTypeNotMatch = errors.New("mismatched ID type.")
    24  )
    25  
    26  // HashEncode 对给定数据计算HashID
    27  func HashEncode(v []int) (string, error) {
    28  	hd := hashids.NewData()
    29  	hd.Salt = conf.SystemConfig.HashIDSalt
    30  
    31  	h, err := hashids.NewWithData(hd)
    32  	if err != nil {
    33  		return "", err
    34  	}
    35  
    36  	id, err := h.Encode(v)
    37  	if err != nil {
    38  		return "", err
    39  	}
    40  	return id, nil
    41  }
    42  
    43  // HashDecode 对给定数据计算原始数据
    44  func HashDecode(raw string) ([]int, error) {
    45  	hd := hashids.NewData()
    46  	hd.Salt = conf.SystemConfig.HashIDSalt
    47  
    48  	h, err := hashids.NewWithData(hd)
    49  	if err != nil {
    50  		return []int{}, err
    51  	}
    52  
    53  	return h.DecodeWithError(raw)
    54  
    55  }
    56  
    57  // HashID 计算数据库内主键对应的HashID
    58  func HashID(id uint, t int) string {
    59  	v, _ := HashEncode([]int{int(id), t})
    60  	return v
    61  }
    62  
    63  // DecodeHashID 计算HashID对应的数据库ID
    64  func DecodeHashID(id string, t int) (uint, error) {
    65  	v, _ := HashDecode(id)
    66  	if len(v) != 2 || v[1] != t {
    67  		return 0, ErrTypeNotMatch
    68  	}
    69  	return uint(v[0]), nil
    70  }