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

     1  package filesystem
     2  
     3  import (
     4  	"context"
     5  	"strings"
     6  
     7  	"github.com/cloudreve/Cloudreve/v3/pkg/util"
     8  )
     9  
    10  /* ==========
    11  	 验证器
    12     ==========
    13  */
    14  
    15  // 文件/路径名保留字符
    16  var reservedCharacter = []string{"\\", "?", "*", "<", "\"", ":", ">", "/", "|"}
    17  
    18  // ValidateLegalName 验证文件名/文件夹名是否合法
    19  func (fs *FileSystem) ValidateLegalName(ctx context.Context, name string) bool {
    20  	// 是否包含保留字符
    21  	for _, value := range reservedCharacter {
    22  		if strings.Contains(name, value) {
    23  			return false
    24  		}
    25  	}
    26  
    27  	// 是否超出长度限制
    28  	if len(name) >= 256 {
    29  		return false
    30  	}
    31  
    32  	// 是否为空限制
    33  	if len(name) == 0 {
    34  		return false
    35  	}
    36  
    37  	// 结尾不能是空格
    38  	if strings.HasSuffix(name, " ") {
    39  		return false
    40  	}
    41  
    42  	return true
    43  }
    44  
    45  // ValidateFileSize 验证上传的文件大小是否超出限制
    46  func (fs *FileSystem) ValidateFileSize(ctx context.Context, size uint64) bool {
    47  	if fs.Policy.MaxSize == 0 {
    48  		return true
    49  	}
    50  	return size <= fs.Policy.MaxSize
    51  }
    52  
    53  // ValidateCapacity 验证并扣除用户容量
    54  func (fs *FileSystem) ValidateCapacity(ctx context.Context, size uint64) bool {
    55  	return fs.User.IncreaseStorage(size)
    56  }
    57  
    58  // ValidateExtension 验证文件扩展名
    59  func (fs *FileSystem) ValidateExtension(ctx context.Context, fileName string) bool {
    60  	// 不需要验证
    61  	if len(fs.Policy.OptionsSerialized.FileType) == 0 {
    62  		return true
    63  	}
    64  
    65  	return util.IsInExtensionList(fs.Policy.OptionsSerialized.FileType, fileName)
    66  }