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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -3,7 +3,6 @@ package config
import (
"errors"
"os"
"regexp"
"strconv"
"github.com/joho/godotenv"
@ -22,18 +21,8 @@ type Config struct {
}
var Default *Config
var Version 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 {
Default = &Config{
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"
"strconv"
"sub2clash/api"
"sub2clash/common"
"sub2clash/common/database"
"sub2clash/config"
"sub2clash/logger"
"sub2clash/utils"
"sub2clash/utils/database"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
@ -23,7 +23,7 @@ var templateClash string
func init() {
var err error
// 创建文件夹
err = utils.MkEssentialDir()
err = common.MkEssentialDir()
if err != nil {
logger.Logger.Panic("create essential dir failed", zap.Error(err))
}
@ -34,22 +34,8 @@ func init() {
if err != nil {
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 {
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
}
}