1
0
mirror of https://github.com/nitezs/sub2clash.git synced 2024-12-23 14:34:41 -05:00

♻️ Refactor code

🔥 Remove update detection
This commit is contained in:
Nite07 2024-04-23 14:47:53 +08:00
parent ebc91d8aad
commit ac4ad3c8aa
16 changed files with 39 additions and 94 deletions

View File

@ -9,10 +9,10 @@ import (
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
"sub2clash/common"
"sub2clash/logger" "sub2clash/logger"
"sub2clash/model" "sub2clash/model"
"sub2clash/parser" "sub2clash/parser"
"sub2clash/utils"
"sub2clash/validator" "sub2clash/validator"
"go.uber.org/zap" "go.uber.org/zap"
@ -32,7 +32,7 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
template = query.Template template = query.Template
} }
if strings.HasPrefix(template, "http") { if strings.HasPrefix(template, "http") {
templateBytes, err = utils.LoadSubscription(template, query.Refresh) templateBytes, err = common.LoadSubscription(template, query.Refresh)
if err != nil { if err != nil {
logger.Logger.Debug( logger.Logger.Debug(
"load template failed", zap.String("template", template), zap.Error(err), "load template failed", zap.String("template", template), zap.Error(err),
@ -44,7 +44,7 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
if err != nil { if err != nil {
return nil, errors.New("加载模板失败: " + err.Error()) return nil, errors.New("加载模板失败: " + err.Error())
} }
templateBytes, err = utils.LoadTemplate(unescape) templateBytes, err = common.LoadTemplate(unescape)
if err != nil { if err != nil {
logger.Logger.Debug( logger.Logger.Debug(
"load template failed", zap.String("template", template), zap.Error(err), "load template failed", zap.String("template", template), zap.Error(err),
@ -61,7 +61,7 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
var proxyList []model.Proxy var proxyList []model.Proxy
// 加载订阅 // 加载订阅
for i := range query.Subs { for i := range query.Subs {
data, err := utils.LoadSubscription(query.Subs[i], query.Refresh) data, err := common.LoadSubscription(query.Subs[i], query.Refresh)
subName := "" subName := ""
if strings.Contains(query.Subs[i], "#") { if strings.Contains(query.Subs[i], "#") {
subName = query.Subs[i][strings.LastIndex(query.Subs[i], "#")+1:] subName = query.Subs[i][strings.LastIndex(query.Subs[i], "#")+1:]
@ -78,7 +78,7 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
if err != nil { if err != nil {
reg, _ := regexp.Compile("(ssr|ss|vmess|trojan|vless|hysteria|hy2|hysteria2)://") reg, _ := regexp.Compile("(ssr|ss|vmess|trojan|vless|hysteria|hy2|hysteria2)://")
if reg.Match(data) { if reg.Match(data) {
p := utils.ParseProxy(strings.Split(string(data), "\n")...) p := common.ParseProxy(strings.Split(string(data), "\n")...)
newProxies = p newProxies = p
} else { } else {
// 如果无法直接解析尝试Base64解码 // 如果无法直接解析尝试Base64解码
@ -91,7 +91,7 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
) )
return nil, errors.New("加载订阅失败: " + err.Error()) return nil, errors.New("加载订阅失败: " + err.Error())
} }
p := utils.ParseProxy(strings.Split(base64, "\n")...) p := common.ParseProxy(strings.Split(base64, "\n")...)
newProxies = p newProxies = p
} }
} else { } else {
@ -106,7 +106,7 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
} }
// 添加自定义节点 // 添加自定义节点
if len(query.Proxies) != 0 { if len(query.Proxies) != 0 {
proxyList = append(proxyList, utils.ParseProxy(query.Proxies...)...) proxyList = append(proxyList, common.ParseProxy(query.Proxies...)...)
} }
// 给节点添加订阅名称 // 给节点添加订阅名称
for i := range proxyList { for i := range proxyList {
@ -181,7 +181,7 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
} }
// 将新增节点都添加到临时变量 t 中,防止策略组排序错乱 // 将新增节点都添加到临时变量 t 中,防止策略组排序错乱
var t = &model.Subscription{} var t = &model.Subscription{}
utils.AddProxy(t, query.AutoTest, query.Lazy, clashType, proxyList...) common.AddProxy(t, query.AutoTest, query.Lazy, clashType, proxyList...)
// 排序策略组 // 排序策略组
switch query.Sort { switch query.Sort {
case "sizeasc": case "sizeasc":
@ -200,9 +200,9 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
// 处理自定义规则 // 处理自定义规则
for _, v := range query.Rules { for _, v := range query.Rules {
if v.Prepend { if v.Prepend {
utils.PrependRules(temp, v.Rule) common.PrependRules(temp, v.Rule)
} else { } else {
utils.AppendRules(temp, v.Rule) common.AppendRules(temp, v.Rule)
} }
} }
// 处理自定义 ruleProvider // 处理自定义 ruleProvider
@ -217,11 +217,11 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
Interval: 3600, Interval: 3600,
} }
if v.Prepend { if v.Prepend {
utils.PrependRuleProvider( common.PrependRuleProvider(
temp, v.Name, v.Group, provider, temp, v.Name, v.Group, provider,
) )
} else { } else {
utils.AppenddRuleProvider( common.AppenddRuleProvider(
temp, v.Name, v.Group, provider, temp, v.Name, v.Group, provider,
) )
} }
@ -273,7 +273,7 @@ func MergeSubAndTemplate(temp *model.Subscription, sub *model.Subscription, igcg
if !igcg { if !igcg {
if len(key) == 2 { if len(key) == 2 {
newProxies = append( newProxies = append(
newProxies, countryGroupMap[utils.GetContryName(key)].Proxies..., newProxies, countryGroupMap[common.GetContryName(key)].Proxies...,
) )
} }
} }

View File

@ -6,11 +6,11 @@ import (
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
"sub2clash/common"
"sub2clash/common/database"
"sub2clash/config" "sub2clash/config"
"sub2clash/logger" "sub2clash/logger"
"sub2clash/model" "sub2clash/model"
"sub2clash/utils"
"sub2clash/utils/database"
"sub2clash/validator" "sub2clash/validator"
"time" "time"
@ -30,7 +30,7 @@ func ShortLinkGenHandler(c *gin.Context) {
return return
} }
// 生成hash // 生成hash
hash := utils.RandomString(config.Default.ShortLinkLength) hash := common.RandomString(config.Default.ShortLinkLength)
var item model.ShortLink var item model.ShortLink
result := database.FindShortLinkByUrl(params.Url, &item) result := database.FindShortLinkByUrl(params.Url, &item)
if result.Error == nil { if result.Error == nil {
@ -51,7 +51,7 @@ func ShortLinkGenHandler(c *gin.Context) {
// 如果记录存在则重新生成hash直到记录不存在 // 如果记录存在则重新生成hash直到记录不存在
result = database.FindShortLinkByHash(hash, &item) result = database.FindShortLinkByHash(hash, &item)
for result.Error == nil { for result.Error == nil {
hash = utils.RandomString(config.Default.ShortLinkLength) hash = common.RandomString(config.Default.ShortLinkLength)
result = database.FindShortLinkByHash(hash, &item) result = database.FindShortLinkByHash(hash, &item)
} }
// 创建记录 // 创建记录
@ -116,7 +116,7 @@ func ShortLinkGetConfigHandler(c *gin.Context) {
// 更新最后访问时间 // 更新最后访问时间
shortLink.LastRequestTime = time.Now().Unix() shortLink.LastRequestTime = time.Now().Unix()
database.SaveShortLink(&shortLink) database.SaveShortLink(&shortLink)
get, err := utils.Get("http://localhost:" + strconv.Itoa(config.Default.Port) + "/" + shortLink.Url) get, err := common.Get("http://localhost:" + strconv.Itoa(config.Default.Port) + "/" + shortLink.Url)
if err != nil { if err != nil {
logger.Logger.Debug("get short link data failed", zap.Error(err)) logger.Logger.Debug("get short link data failed", zap.Error(err))
c.String(500, "请求错误: "+err.Error()) c.String(500, "请求错误: "+err.Error())

View File

@ -6,7 +6,7 @@ import (
"log" "log"
"net/http" "net/http"
"sub2clash/api/handler" "sub2clash/api/handler"
"sub2clash/config" "sub2clash/constant"
"sub2clash/middleware" "sub2clash/middleware"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@ -32,9 +32,9 @@ func SetRoute(r *gin.Engine) {
) )
r.GET( r.GET(
"/", func(c *gin.Context) { "/", func(c *gin.Context) {
version := config.Version version := constant.Version
if len(config.Version) > 7 { if len(constant.Version) > 7 {
version = config.Version[:7] version = constant.Version[:7]
} }
c.HTML( c.HTML(
200, "index.html", gin.H{ 200, "index.html", gin.H{

View File

@ -2,9 +2,9 @@ package database
import ( import (
"path/filepath" "path/filepath"
"sub2clash/common"
"sub2clash/logger" "sub2clash/logger"
"sub2clash/model" "sub2clash/model"
"sub2clash/utils"
"github.com/glebarez/sqlite" "github.com/glebarez/sqlite"
"go.uber.org/zap" "go.uber.org/zap"
@ -15,7 +15,7 @@ var DB *gorm.DB
func ConnectDB() error { func ConnectDB() error {
// 用上面的数据库连接初始化 gorm // 用上面的数据库连接初始化 gorm
err := utils.MKDir("data") err := common.MKDir("data")
if err != nil { if err != nil {
return err return err
} }

View File

@ -1,4 +1,4 @@
package utils package common
import ( import (
"errors" "errors"

View File

@ -1,4 +1,4 @@
package utils package common
import ( import (
"errors" "errors"

View File

@ -1,4 +1,4 @@
package utils package common
import ( import (
"strings" "strings"

View File

@ -1,4 +1,4 @@
package utils package common
import "math/rand" import "math/rand"

View File

@ -1,4 +1,4 @@
package utils package common
import ( import (
"fmt" "fmt"

View File

@ -1,4 +1,4 @@
package utils package common
import ( import (
"crypto/sha256" "crypto/sha256"

View File

@ -1,4 +1,4 @@
package utils package common
import ( import (
"errors" "errors"

View File

@ -1,4 +1,4 @@
package utils package common
import ( import (
"os" "os"

View File

@ -3,7 +3,6 @@ package config
import ( import (
"errors" "errors"
"os" "os"
"regexp"
"strconv" "strconv"
"github.com/joho/godotenv" "github.com/joho/godotenv"
@ -22,18 +21,8 @@ type Config struct {
} }
var Default *Config var Default *Config
var Version string
var Dev string var Dev string
func init() {
reg := regexp.MustCompile(`^v\d+\.\d+\.\d+$`)
if reg.MatchString(Version) {
Dev = "false"
} else {
Dev = "true"
}
}
func LoadConfig() error { func LoadConfig() error {
Default = &Config{ Default = &Config{
MetaTemplate: "template_meta.yaml", MetaTemplate: "template_meta.yaml",

3
constant/version.go Normal file
View File

@ -0,0 +1,3 @@
package constant
var Version = "dev"

22
main.go
View File

@ -5,10 +5,10 @@ import (
"io" "io"
"strconv" "strconv"
"sub2clash/api" "sub2clash/api"
"sub2clash/common"
"sub2clash/common/database"
"sub2clash/config" "sub2clash/config"
"sub2clash/logger" "sub2clash/logger"
"sub2clash/utils"
"sub2clash/utils/database"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"go.uber.org/zap" "go.uber.org/zap"
@ -23,7 +23,7 @@ var templateClash string
func init() { func init() {
var err error var err error
// 创建文件夹 // 创建文件夹
err = utils.MkEssentialDir() err = common.MkEssentialDir()
if err != nil { if err != nil {
logger.Logger.Panic("create essential dir failed", zap.Error(err)) logger.Logger.Panic("create essential dir failed", zap.Error(err))
} }
@ -34,22 +34,8 @@ func init() {
if err != nil { if err != nil {
logger.Logger.Panic("load config failed", zap.Error(err)) logger.Logger.Panic("load config failed", zap.Error(err))
} }
// 检查更新
if config.Dev != "true" {
go func() {
update, newVersion, err := utils.CheckUpdate()
if err != nil {
logger.Logger.Warn("check update failed", zap.Error(err))
}
if update {
logger.Logger.Info("new version is available", zap.String("version", newVersion))
}
}()
} else {
logger.Logger.Info("running in dev mode")
}
// 写入默认模板 // 写入默认模板
err = utils.WriteDefalutTemplate(templateMeta, templateClash) err = common.WriteDefalutTemplate(templateMeta, templateClash)
if err != nil { if err != nil {
logger.Logger.Panic("write default template failed", zap.Error(err)) logger.Logger.Panic("write default template failed", zap.Error(err))
} }

View File

@ -1,33 +0,0 @@
package utils
import (
"encoding/json"
"errors"
"io"
"sub2clash/config"
"sub2clash/model"
)
func CheckUpdate() (bool, string, error) {
get, err := Get("https://api.github.com/repos/nitezs/sub2clash/tags")
if err != nil {
return false, "", errors.New("get version info failed" + err.Error())
}
var version model.Tags
all, err := io.ReadAll(get.Body)
if err != nil {
return false, "", errors.New("get version info failed" + err.Error())
}
err = json.Unmarshal(all, &version)
if err != nil {
return false, "", errors.New("get version info failed" + err.Error())
}
if version[0].Name == config.Version {
return false, "", nil
} else {
return true, version[0].Name, nil
}
}