1
0
mirror of https://github.com/zu1k/nali.git synced 2025-01-23 21:59:02 +08:00
nali/internal/app/cdn.go

87 lines
1.7 KiB
Go
Raw Normal View History

2020-07-18 14:18:54 +08:00
package app
import (
"fmt"
"log"
"path/filepath"
"regexp"
"strings"
"github.com/zu1k/nali/constant"
2021-03-26 16:28:41 +08:00
"github.com/zu1k/nali/internal/tools"
2020-07-18 14:18:54 +08:00
"github.com/zu1k/nali/pkg/cdn"
)
var (
cdnDB cdn.CDN
domainRe *regexp.Regexp
)
func init() {
2021-03-26 16:28:41 +08:00
domainRe = regexp.MustCompile(`[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+`)
2020-07-18 14:18:54 +08:00
}
func InitCDNDB() {
cdnDB = cdn.NewCDN(filepath.Join(constant.HomePath, "cdn.json"))
}
func ParseCDNs(str []string) {
for _, cname := range str {
name := find(cname)
fmt.Printf("%s [%s]\n", cname, name)
}
}
func find(cname string) string {
baseCname := parseBaseCname(cname)
if baseCname == "" {
return "无法解析"
}
cdnResult, found := cdnDB.Data[baseCname]
if found {
return cdnResult.Name
}
2020-09-09 09:58:52 +08:00
if strings.Contains(baseCname, "kunlun") {
return "阿里云 CDN"
}
2020-07-18 14:18:54 +08:00
return "未找到"
}
func ReplaceCDNInString(str string) (result string) {
2020-07-18 14:26:22 +08:00
done := make(map[string]bool)
2020-07-18 14:18:54 +08:00
cnames := domainRe.FindAllString(str, -1)
result = str
for _, cname := range cnames {
name := find(cname)
if name != "未找到" && name != "无法解析" {
2020-07-18 14:26:22 +08:00
if _, found := done[cname]; found {
continue
}
result = tools.AddInfoDomain(result, cname, name)
2020-07-18 14:26:22 +08:00
done[cname] = true
2020-07-18 14:18:54 +08:00
}
}
return
}
func parseBaseCname(domain string) string {
hostParts := strings.Split(domain, ".")
if len(hostParts) < 2 {
return domain
}
baseCname := hostParts[len(hostParts)-2] + "." + hostParts[len(hostParts)-1]
return baseCname
}
func UpdateDB() {
filePath := filepath.Join(constant.HomePath, "cdn.json")
log.Println("正在下载最新 CDN数据库...")
2020-07-22 07:25:01 +08:00
_, err := cdn.Download(filePath)
2020-07-18 14:18:54 +08:00
if err != nil {
log.Fatalln("下载失败", err.Error())
return
}
}