简化文件名组装逻辑

This commit is contained in:
fantasticbin 2025-03-04 21:23:53 +08:00
parent 0e6e964b70
commit 418d08a7e8

View File

@ -27,6 +27,11 @@ type Crawler struct {
client *http.Client
}
type coverCode struct {
letters string
number int
}
func NewCrawler(avPath, outputPath string) *Crawler {
config := viper.New()
config.SetConfigName("config")
@ -99,7 +104,7 @@ func (c *Crawler) getCodeNum(s string) int {
}
// 获取封面代码列表
func (c *Crawler) getCoverCodeList(files []string) (coverList []string) {
func (c *Crawler) getCoverCodeList(files []string) (coverList []coverCode) {
for _, file := range files {
// 去除域名部分
if strings.IndexRune(file, '@') > 0 {
@ -116,46 +121,32 @@ func (c *Crawler) getCoverCodeList(files []string) (coverList []string) {
continue
}
format := "%s%05d"
if len(nameSlice[0]) > 4 {
format = "1%s%05d"
}
coverList = append(coverList, fmt.Sprintf(format, strings.ToLower(nameSlice[0]), num))
coverList = append(coverList, coverCode{
letters: strings.ToLower(nameSlice[0]),
number: num,
})
}
return coverList
}
// 获取封面图片
func (c *Crawler) fetchCoverImg(code string) error {
imgUrl := strings.ReplaceAll(c.config.GetString("crawler.url"), `*`, code)
func (c *Crawler) fetchCoverImg(code coverCode) error {
if len(code.letters) < 2 || code.number < 1 {
return nil
}
format := "%s%05d"
if len(code.letters) > 4 {
format = "1%s%05d"
}
codeStr := fmt.Sprintf(format, code.letters, code.number)
imgUrl := strings.ReplaceAll(c.config.GetString("crawler.url"), `*`, codeStr)
suffix := filepath.Ext(imgUrl)
startOffset := 0
// 如果第一个字符为 '1',则从下一个字符开始查找
if len(code) > 0 && code[0] == '1' {
startOffset = 1
}
// 获取号码所在的位置
splitIndex := strings.Index(code[startOffset:], "00")
if splitIndex == -1 || splitIndex+startOffset < 3 {
return nil
}
// 计算原始字符串中的真实位置
splitIndex += startOffset
// 分隔字母部分及数字部分
letters := code[startOffset:splitIndex]
numPart := code[splitIndex+2:]
if len(letters) == 0 || len(numPart) == 0 {
return nil
}
fileName := filepath.Join(c.outputPath, fmt.Sprintf("%s-%s%s",
strings.ToUpper(letters),
numPart,
fileName := filepath.Join(c.outputPath, fmt.Sprintf("%s-%d%s",
strings.ToUpper(code.letters),
code.number,
suffix,
))