This commit is contained in:
2023-09-12 18:40:24 +08:00
commit d894fea89e
25 changed files with 2179 additions and 0 deletions

23
utils/get.go Normal file
View File

@ -0,0 +1,23 @@
package utils
import (
"net/http"
"time"
)
func GetWithRetry(url string) (resp *http.Response, err error) {
retryTimes := 3
haveTried := 0
retryDelay := time.Second // 延迟1秒再重试
for haveTried < retryTimes {
get, err := http.Get(url)
if err != nil {
haveTried++
time.Sleep(retryDelay)
continue
} else {
return get, nil
}
}
return nil, err
}

105
utils/proxy.go Normal file
View File

@ -0,0 +1,105 @@
package utils
import (
"sort"
"strings"
"sub/model"
"sub/parser"
)
func GetContryCode(proxy model.Proxy) string {
keys := make([]string, 0, len(model.CountryKeywords))
for k := range model.CountryKeywords {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
if strings.Contains(strings.ToLower(proxy.Name), strings.ToLower(k)) {
return model.CountryKeywords[k]
}
}
return "其他地区"
}
var skipGroups = map[string]bool{
"手动切换": true,
"全球直连": true,
"广告拦截": true,
"应用进化": true,
}
func AddProxy(sub *model.Subscription, proxies ...model.Proxy) {
newContryNames := make([]string, 0, len(proxies))
for p := range proxies {
proxy := proxies[p]
sub.Proxies = append(sub.Proxies, proxy)
haveProxyGroup := false
for i := range sub.ProxyGroups {
group := &sub.ProxyGroups[i]
groupName := []rune(group.Name)
proxyName := []rune(proxy.Name)
if string(groupName[:2]) == string(proxyName[:2]) || GetContryCode(proxy) == group.Name {
group.Proxies = append(group.Proxies, proxy.Name)
haveProxyGroup = true
}
if group.Name == "手动切换" {
group.Proxies = append(group.Proxies, proxy.Name)
}
}
if !haveProxyGroup {
contryCode := GetContryCode(proxy)
newGroup := model.ProxyGroup{
Name: contryCode,
Type: "select",
Proxies: []string{proxy.Name},
}
newContryNames = append(newContryNames, contryCode)
sub.ProxyGroups = append(sub.ProxyGroups, newGroup)
}
}
newContryNamesMap := make(map[string]bool)
for _, n := range newContryNames {
newContryNamesMap[n] = true
}
for i := range sub.ProxyGroups {
if !skipGroups[sub.ProxyGroups[i].Name] && !newContryNamesMap[sub.ProxyGroups[i].Name] {
newProxies := make(
[]string, len(newContryNames), len(newContryNames)+len(sub.ProxyGroups[i].Proxies),
)
copy(newProxies, newContryNames)
sub.ProxyGroups[i].Proxies = append(newProxies, sub.ProxyGroups[i].Proxies...)
}
}
}
func ParseProxy(proxies ...string) []model.Proxy {
var result []model.Proxy
for _, proxy := range proxies {
if proxy != "" {
var proxyItem model.Proxy
var err error
// 解析节点
if strings.HasPrefix(proxy, "ss://") {
proxyItem, err = parser.ParseSS(proxy)
}
if strings.HasPrefix(proxy, "trojan://") {
proxyItem, err = parser.ParseTrojan(proxy)
}
if strings.HasPrefix(proxy, "vmess://") {
proxyItem, err = parser.ParseVmess(proxy)
}
if strings.HasPrefix(proxy, "vless://") {
proxyItem, err = parser.ParseVless(proxy)
}
if strings.HasPrefix(proxy, "ssr://") {
proxyItem, err = parser.ParseShadowsocksR(proxy)
}
if err == nil {
result = append(result, proxyItem)
}
}
}
return result
}

54
utils/rule.go Normal file
View File

@ -0,0 +1,54 @@
package utils
import (
"fmt"
"gopkg.in/yaml.v3"
"io"
"sub/model"
)
func AddRulesByUrl(sub *model.Subscription, url string, proxy string) {
get, err := GetWithRetry(url)
if err != nil {
fmt.Println(err)
return
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
fmt.Println(err)
}
}(get.Body)
bytes, err := io.ReadAll(get.Body)
if err != nil {
fmt.Println(err)
return
}
var payload model.Payload
err = yaml.Unmarshal(bytes, &payload)
if err != nil {
fmt.Println(err)
return
}
for i := range payload.Rules {
payload.Rules[i] = payload.Rules[i] + "," + proxy
}
AddRules(sub, payload.Rules...)
}
func AddRuleProvider(
sub *model.Subscription, providerName string, proxy string, provider model.RuleProvider,
) {
if sub.RuleProviders == nil {
sub.RuleProviders = make(map[string]model.RuleProvider)
}
sub.RuleProviders[providerName] = provider
AddRules(
sub,
fmt.Sprintf("RULE-SET,%s,%s", providerName, proxy),
)
}
func AddRules(sub *model.Subscription, rules ...string) {
sub.Rules = append(rules, sub.Rules...)
}

85
utils/sub.go Normal file
View File

@ -0,0 +1,85 @@
package utils
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io"
"os"
"path/filepath"
"time"
)
var subsDir = "subs"
func LoadSubscription(url string, refresh bool) ([]byte, error) {
if refresh {
return FetchSubscriptionFromAPI(url)
}
hash := md5.Sum([]byte(url))
fileName := filepath.Join(subsDir, hex.EncodeToString(hash[:])+".yaml")
const refreshInterval = 5 * 60 // 5分钟
stat, err := os.Stat(fileName)
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
return FetchSubscriptionFromAPI(url)
}
lastGetTime := stat.ModTime().Unix() // 单位是秒
if lastGetTime+refreshInterval > time.Now().Unix() {
file, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
fmt.Println(err)
}
}(file)
subContent, err := io.ReadAll(file)
if err != nil {
return nil, err
}
return subContent, nil
}
return FetchSubscriptionFromAPI(url)
}
func FetchSubscriptionFromAPI(url string) ([]byte, error) {
hash := md5.Sum([]byte(url))
fileName := filepath.Join(subsDir, hex.EncodeToString(hash[:])+".yaml")
resp, err := GetWithRetry(url)
if err != nil {
return nil, err
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
fmt.Println(err)
}
}(resp.Body)
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
file, err := os.Create(fileName)
if err != nil {
return nil, err
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
fmt.Println(err)
}
}(file)
_, err = file.Write(data)
if err != nil {
return nil, fmt.Errorf("failed to write to sub.yaml: %w", err)
}
if err != nil {
return nil, fmt.Errorf("failed to unmarshal yaml: %w", err)
}
return data, nil
}

36
utils/template.go Normal file
View File

@ -0,0 +1,36 @@
package utils
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
)
// LoadTemplate 加载模板
// template 模板文件名
func LoadTemplate(template string) (string, error) {
tPath := filepath.Join("templates", template)
if _, err := os.Stat(tPath); err == nil {
file, err := os.Open(tPath)
if err != nil {
return "", err
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
fmt.Println(err)
}
}(file)
result, err := io.ReadAll(file)
if err != nil {
return "", err
}
if err != nil {
return "", err
}
return string(result), nil
}
return "", errors.New("模板文件不存在")
}