mirror of
https://github.com/bestnite/sub2clash.git
synced 2025-04-19 12:55:55 +08:00
Compare commits
No commits in common. "main" and "v0.1.0-alpha.4" have entirely different histories.
main
...
v0.1.0-alp
1
.gitattributes
vendored
1
.gitattributes
vendored
@ -1 +0,0 @@
|
|||||||
* text=auto eol=lf
|
|
3
.gitignore
vendored
3
.gitignore
vendored
@ -5,5 +5,4 @@ logs
|
|||||||
data
|
data
|
||||||
.env
|
.env
|
||||||
.vscode/settings.json
|
.vscode/settings.json
|
||||||
test
|
test
|
||||||
*test.go
|
|
2
.vscode/launch.json
vendored
2
.vscode/launch.json
vendored
@ -5,7 +5,7 @@
|
|||||||
"type": "go",
|
"type": "go",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"mode": "debug",
|
"mode": "debug",
|
||||||
"program": "${workspaceFolder}",
|
"program": "${workspaceFolder}/main.go",
|
||||||
"output": "${workspaceFolder}/dist/main.exe",
|
"output": "${workspaceFolder}/dist/main.exe",
|
||||||
"buildFlags": "-ldflags '-X sub2clash/constant.Version=dev'"
|
"buildFlags": "-ldflags '-X sub2clash/constant.Version=dev'"
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,7 @@
|
|||||||
# sub2clash
|
# sub2clash
|
||||||
|
|
||||||
|
> Sing-box 用户?看看另一个项目 [sub2sing-box](https://github.com/nitezs/sub2sing-box)
|
||||||
|
|
||||||
将订阅链接转换为 Clash、Clash.Meta 配置
|
将订阅链接转换为 Clash、Clash.Meta 配置
|
||||||
[预览](https://www.nite07.com/sub)
|
[预览](https://www.nite07.com/sub)
|
||||||
|
|
||||||
@ -17,7 +19,6 @@
|
|||||||
- Trojan
|
- Trojan
|
||||||
- Hysteria (Clash.Meta)
|
- Hysteria (Clash.Meta)
|
||||||
- Hysteria2 (Clash.Meta)
|
- Hysteria2 (Clash.Meta)
|
||||||
- Socks5
|
|
||||||
|
|
||||||
## 使用
|
## 使用
|
||||||
|
|
||||||
|
@ -2,17 +2,16 @@ package handler
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"sub2clash/config"
|
||||||
"github.com/nitezs/sub2clash/config"
|
"sub2clash/model"
|
||||||
"github.com/nitezs/sub2clash/model"
|
"sub2clash/validator"
|
||||||
"github.com/nitezs/sub2clash/validator"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
func SubmodHandler(c *gin.Context) {
|
func SubmodHandler(c *gin.Context) {
|
||||||
|
// 从请求中获取参数
|
||||||
query, err := validator.ParseQuery(c)
|
query, err := validator.ParseQuery(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.String(http.StatusBadRequest, err.Error())
|
c.String(http.StatusBadRequest, err.Error())
|
||||||
@ -23,7 +22,7 @@ func SubmodHandler(c *gin.Context) {
|
|||||||
c.String(http.StatusInternalServerError, err.Error())
|
c.String(http.StatusInternalServerError, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// 输出
|
||||||
if query.NodeListMode {
|
if query.NodeListMode {
|
||||||
nodelist := model.NodeList{}
|
nodelist := model.NodeList{}
|
||||||
nodelist.Proxies = sub.Proxies
|
nodelist.Proxies = sub.Proxies
|
||||||
|
@ -9,12 +9,11 @@ import (
|
|||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sub2clash/common"
|
||||||
"github.com/nitezs/sub2clash/common"
|
"sub2clash/logger"
|
||||||
"github.com/nitezs/sub2clash/logger"
|
"sub2clash/model"
|
||||||
"github.com/nitezs/sub2clash/model"
|
"sub2clash/parser"
|
||||||
"github.com/nitezs/sub2clash/parser"
|
"sub2clash/validator"
|
||||||
"github.com/nitezs/sub2clash/validator"
|
|
||||||
|
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
@ -23,17 +22,17 @@ import (
|
|||||||
func BuildSub(clashType model.ClashType, query validator.SubValidator, template string) (
|
func BuildSub(clashType model.ClashType, query validator.SubValidator, template string) (
|
||||||
*model.Subscription, error,
|
*model.Subscription, error,
|
||||||
) {
|
) {
|
||||||
|
// 定义变量
|
||||||
var temp = &model.Subscription{}
|
var temp = &model.Subscription{}
|
||||||
var sub = &model.Subscription{}
|
var sub = &model.Subscription{}
|
||||||
var err error
|
var err error
|
||||||
var templateBytes []byte
|
var templateBytes []byte
|
||||||
|
// 加载模板
|
||||||
if query.Template != "" {
|
if query.Template != "" {
|
||||||
template = query.Template
|
template = query.Template
|
||||||
}
|
}
|
||||||
if strings.HasPrefix(template, "http") {
|
if strings.HasPrefix(template, "http") {
|
||||||
templateBytes, err = common.LoadSubscription(template, query.Refresh, query.UserAgent)
|
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),
|
||||||
@ -53,16 +52,16 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
|
|||||||
return nil, errors.New("加载模板失败: " + err.Error())
|
return nil, errors.New("加载模板失败: " + err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 解析模板
|
||||||
err = yaml.Unmarshal(templateBytes, &temp)
|
err = yaml.Unmarshal(templateBytes, &temp)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Logger.Debug("parse template failed", zap.Error(err))
|
logger.Logger.Debug("parse template failed", zap.Error(err))
|
||||||
return nil, errors.New("解析模板失败: " + err.Error())
|
return nil, errors.New("解析模板失败: " + err.Error())
|
||||||
}
|
}
|
||||||
var proxyList []model.Proxy
|
var proxyList []model.Proxy
|
||||||
|
// 加载订阅
|
||||||
for i := range query.Subs {
|
for i := range query.Subs {
|
||||||
data, err := common.LoadSubscription(query.Subs[i], query.Refresh, query.UserAgent)
|
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:]
|
||||||
@ -73,7 +72,7 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
|
|||||||
)
|
)
|
||||||
return nil, errors.New("加载订阅失败: " + err.Error())
|
return nil, errors.New("加载订阅失败: " + err.Error())
|
||||||
}
|
}
|
||||||
|
// 解析订阅
|
||||||
err = yaml.Unmarshal(data, &sub)
|
err = yaml.Unmarshal(data, &sub)
|
||||||
var newProxies []model.Proxy
|
var newProxies []model.Proxy
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -82,7 +81,7 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
|
|||||||
p := common.ParseProxy(strings.Split(string(data), "\n")...)
|
p := common.ParseProxy(strings.Split(string(data), "\n")...)
|
||||||
newProxies = p
|
newProxies = p
|
||||||
} else {
|
} else {
|
||||||
|
// 如果无法直接解析,尝试Base64解码
|
||||||
base64, err := parser.DecodeBase64(string(data))
|
base64, err := parser.DecodeBase64(string(data))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Logger.Debug(
|
logger.Logger.Debug(
|
||||||
@ -105,31 +104,28 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
|
|||||||
}
|
}
|
||||||
proxyList = append(proxyList, newProxies...)
|
proxyList = append(proxyList, newProxies...)
|
||||||
}
|
}
|
||||||
|
// 添加自定义节点
|
||||||
if len(query.Proxies) != 0 {
|
if len(query.Proxies) != 0 {
|
||||||
proxyList = append(proxyList, common.ParseProxy(query.Proxies...)...)
|
proxyList = append(proxyList, common.ParseProxy(query.Proxies...)...)
|
||||||
}
|
}
|
||||||
|
// 给节点添加订阅名称
|
||||||
for i := range proxyList {
|
for i := range proxyList {
|
||||||
if proxyList[i].SubName != "" {
|
if proxyList[i].SubName != "" {
|
||||||
proxyList[i].Name = strings.TrimSpace(proxyList[i].SubName) + " " + strings.TrimSpace(proxyList[i].Name)
|
proxyList[i].Name = strings.TrimSpace(proxyList[i].SubName) + " " + strings.TrimSpace(proxyList[i].Name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 去掉配置相同的节点
|
||||||
proxies := make(map[string]*model.Proxy)
|
proxies := make(map[string]*model.Proxy)
|
||||||
newProxies := make([]model.Proxy, 0, len(proxyList))
|
newProxies := make([]model.Proxy, 0, len(proxyList))
|
||||||
for i := range proxyList {
|
for i := range proxyList {
|
||||||
key := proxyList[i].Server + strconv.Itoa(proxyList[i].Port) + proxyList[i].Type + proxyList[i].UUID + proxyList[i].Password
|
key := proxyList[i].Server + strconv.Itoa(proxyList[i].Port) + proxyList[i].Type + proxyList[i].UUID + proxyList[i].Password
|
||||||
if proxyList[i].Network == "ws" {
|
|
||||||
key += proxyList[i].WSOpts.Path + proxyList[i].WSOpts.Headers["Host"]
|
|
||||||
}
|
|
||||||
if _, exist := proxies[key]; !exist {
|
if _, exist := proxies[key]; !exist {
|
||||||
proxies[key] = &proxyList[i]
|
proxies[key] = &proxyList[i]
|
||||||
newProxies = append(newProxies, proxyList[i])
|
newProxies = append(newProxies, proxyList[i])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
proxyList = newProxies
|
proxyList = newProxies
|
||||||
|
// 删除节点
|
||||||
if strings.TrimSpace(query.Remove) != "" {
|
if strings.TrimSpace(query.Remove) != "" {
|
||||||
newProxyList := make([]model.Proxy, 0, len(proxyList))
|
newProxyList := make([]model.Proxy, 0, len(proxyList))
|
||||||
for i := range proxyList {
|
for i := range proxyList {
|
||||||
@ -138,17 +134,17 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
|
|||||||
logger.Logger.Debug("remove regexp compile failed", zap.Error(err))
|
logger.Logger.Debug("remove regexp compile failed", zap.Error(err))
|
||||||
return nil, errors.New("remove 参数非法: " + err.Error())
|
return nil, errors.New("remove 参数非法: " + err.Error())
|
||||||
}
|
}
|
||||||
|
// 删除匹配到的节点
|
||||||
if removeReg.MatchString(proxyList[i].Name) {
|
if removeReg.MatchString(proxyList[i].Name) {
|
||||||
continue
|
continue // 如果匹配到要删除的元素,跳过该元素,不添加到新切片中
|
||||||
}
|
}
|
||||||
newProxyList = append(newProxyList, proxyList[i])
|
newProxyList = append(newProxyList, proxyList[i]) // 将要保留的元素添加到新切片中
|
||||||
}
|
}
|
||||||
proxyList = newProxyList
|
proxyList = newProxyList
|
||||||
}
|
}
|
||||||
|
// 重命名
|
||||||
if len(query.ReplaceKeys) != 0 {
|
if len(query.ReplaceKeys) != 0 {
|
||||||
|
// 创建重命名正则表达式
|
||||||
replaceRegs := make([]*regexp.Regexp, 0, len(query.ReplaceKeys))
|
replaceRegs := make([]*regexp.Regexp, 0, len(query.ReplaceKeys))
|
||||||
for _, v := range query.ReplaceKeys {
|
for _, v := range query.ReplaceKeys {
|
||||||
replaceReg, err := regexp.Compile(v)
|
replaceReg, err := regexp.Compile(v)
|
||||||
@ -159,7 +155,7 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
|
|||||||
replaceRegs = append(replaceRegs, replaceReg)
|
replaceRegs = append(replaceRegs, replaceReg)
|
||||||
}
|
}
|
||||||
for i := range proxyList {
|
for i := range proxyList {
|
||||||
|
// 重命名匹配到的节点
|
||||||
for j, v := range replaceRegs {
|
for j, v := range replaceRegs {
|
||||||
if v.MatchString(proxyList[i].Name) {
|
if v.MatchString(proxyList[i].Name) {
|
||||||
proxyList[i].Name = v.ReplaceAllString(
|
proxyList[i].Name = v.ReplaceAllString(
|
||||||
@ -169,7 +165,7 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 重名检测
|
||||||
names := make(map[string]int)
|
names := make(map[string]int)
|
||||||
for i := range proxyList {
|
for i := range proxyList {
|
||||||
if _, exist := names[proxyList[i].Name]; exist {
|
if _, exist := names[proxyList[i].Name]; exist {
|
||||||
@ -179,14 +175,14 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
|
|||||||
names[proxyList[i].Name] = 0
|
names[proxyList[i].Name] = 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// trim
|
||||||
for i := range proxyList {
|
for i := range proxyList {
|
||||||
proxyList[i].Name = strings.TrimSpace(proxyList[i].Name)
|
proxyList[i].Name = strings.TrimSpace(proxyList[i].Name)
|
||||||
}
|
}
|
||||||
|
// 将新增节点都添加到临时变量 t 中,防止策略组排序错乱
|
||||||
var t = &model.Subscription{}
|
var t = &model.Subscription{}
|
||||||
common.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":
|
||||||
sort.Sort(model.ProxyGroupsSortBySize(t.ProxyGroups))
|
sort.Sort(model.ProxyGroupsSortBySize(t.ProxyGroups))
|
||||||
@ -199,9 +195,9 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
|
|||||||
default:
|
default:
|
||||||
sort.Sort(model.ProxyGroupsSortByName(t.ProxyGroups))
|
sort.Sort(model.ProxyGroupsSortByName(t.ProxyGroups))
|
||||||
}
|
}
|
||||||
|
// 合并新节点和模板
|
||||||
MergeSubAndTemplate(temp, t, query.IgnoreCountryGrooup)
|
MergeSubAndTemplate(temp, t, query.IgnoreCountryGrooup)
|
||||||
|
// 处理自定义规则
|
||||||
for _, v := range query.Rules {
|
for _, v := range query.Rules {
|
||||||
if v.Prepend {
|
if v.Prepend {
|
||||||
common.PrependRules(temp, v.Rule)
|
common.PrependRules(temp, v.Rule)
|
||||||
@ -209,7 +205,7 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
|
|||||||
common.AppendRules(temp, v.Rule)
|
common.AppendRules(temp, v.Rule)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 处理自定义 ruleProvider
|
||||||
for _, v := range query.RuleProviders {
|
for _, v := range query.RuleProviders {
|
||||||
hash := sha256.Sum224([]byte(v.Url))
|
hash := sha256.Sum224([]byte(v.Url))
|
||||||
name := hex.EncodeToString(hash[:])
|
name := hex.EncodeToString(hash[:])
|
||||||
@ -234,7 +230,8 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
|
|||||||
}
|
}
|
||||||
|
|
||||||
func MergeSubAndTemplate(temp *model.Subscription, sub *model.Subscription, igcg bool) {
|
func MergeSubAndTemplate(temp *model.Subscription, sub *model.Subscription, igcg bool) {
|
||||||
|
// 只合并节点、策略组
|
||||||
|
// 统计所有国家策略组名称
|
||||||
var countryGroupNames []string
|
var countryGroupNames []string
|
||||||
for _, proxyGroup := range sub.ProxyGroups {
|
for _, proxyGroup := range sub.ProxyGroups {
|
||||||
if proxyGroup.IsCountryGrop {
|
if proxyGroup.IsCountryGrop {
|
||||||
@ -247,9 +244,9 @@ func MergeSubAndTemplate(temp *model.Subscription, sub *model.Subscription, igcg
|
|||||||
for _, proxy := range sub.Proxies {
|
for _, proxy := range sub.Proxies {
|
||||||
proxyNames = append(proxyNames, proxy.Name)
|
proxyNames = append(proxyNames, proxy.Name)
|
||||||
}
|
}
|
||||||
|
// 将订阅中的节点添加到模板中
|
||||||
temp.Proxies = append(temp.Proxies, sub.Proxies...)
|
temp.Proxies = append(temp.Proxies, sub.Proxies...)
|
||||||
|
// 将订阅中的策略组添加到模板中
|
||||||
for i := range temp.ProxyGroups {
|
for i := range temp.ProxyGroups {
|
||||||
if temp.ProxyGroups[i].IsCountryGrop {
|
if temp.ProxyGroups[i].IsCountryGrop {
|
||||||
continue
|
continue
|
||||||
|
@ -3,17 +3,16 @@ package handler
|
|||||||
import (
|
import (
|
||||||
_ "embed"
|
_ "embed"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"sub2clash/config"
|
||||||
"github.com/nitezs/sub2clash/config"
|
"sub2clash/model"
|
||||||
"github.com/nitezs/sub2clash/model"
|
"sub2clash/validator"
|
||||||
"github.com/nitezs/sub2clash/validator"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
func SubHandler(c *gin.Context) {
|
func SubHandler(c *gin.Context) {
|
||||||
|
// 从请求中获取参数
|
||||||
query, err := validator.ParseQuery(c)
|
query, err := validator.ParseQuery(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.String(http.StatusBadRequest, err.Error())
|
c.String(http.StatusBadRequest, err.Error())
|
||||||
@ -24,7 +23,7 @@ func SubHandler(c *gin.Context) {
|
|||||||
c.String(http.StatusInternalServerError, err.Error())
|
c.String(http.StatusInternalServerError, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// 输出
|
||||||
if query.NodeListMode {
|
if query.NodeListMode {
|
||||||
nodelist := model.NodeList{}
|
nodelist := model.NodeList{}
|
||||||
nodelist.Proxies = sub.Proxies
|
nodelist.Proxies = sub.Proxies
|
||||||
|
@ -7,11 +7,11 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/nitezs/sub2clash/common"
|
"sub2clash/common"
|
||||||
"github.com/nitezs/sub2clash/common/database"
|
"sub2clash/common/database"
|
||||||
"github.com/nitezs/sub2clash/config"
|
"sub2clash/config"
|
||||||
"github.com/nitezs/sub2clash/model"
|
"sub2clash/model"
|
||||||
"github.com/nitezs/sub2clash/validator"
|
"sub2clash/validator"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
@ -32,41 +32,16 @@ func GenerateLinkHandler(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var hash string
|
hash, err := generateUniqueHash()
|
||||||
var password string
|
if err != nil {
|
||||||
var err error
|
respondWithError(c, http.StatusInternalServerError, "生成短链接失败")
|
||||||
|
return
|
||||||
if params.CustomID != "" {
|
|
||||||
// 检查自定义ID是否已存在
|
|
||||||
exists, err := database.CheckShortLinkHashExists(params.CustomID)
|
|
||||||
if err != nil {
|
|
||||||
respondWithError(c, http.StatusInternalServerError, "数据库错误")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if exists {
|
|
||||||
respondWithError(c, http.StatusBadRequest, "短链已存在")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
hash = params.CustomID
|
|
||||||
password = params.Password
|
|
||||||
} else {
|
|
||||||
// 自动生成短链ID和密码
|
|
||||||
hash, err = generateUniqueHash()
|
|
||||||
if err != nil {
|
|
||||||
respondWithError(c, http.StatusInternalServerError, "生成短链接失败")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if params.Password == "" {
|
|
||||||
password = common.RandomString(8) // 生成8位随机密码
|
|
||||||
} else {
|
|
||||||
password = params.Password
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
shortLink := model.ShortLink{
|
shortLink := model.ShortLink{
|
||||||
Hash: hash,
|
Hash: hash,
|
||||||
Url: params.Url,
|
Url: params.Url,
|
||||||
Password: password,
|
Password: params.Password,
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := database.SaveShortLink(&shortLink); err != nil {
|
if err := database.SaveShortLink(&shortLink); err != nil {
|
||||||
@ -74,12 +49,10 @@ func GenerateLinkHandler(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 返回生成的短链ID和密码
|
if params.Password != "" {
|
||||||
response := map[string]string{
|
hash += "?password=" + params.Password
|
||||||
"hash": hash,
|
|
||||||
"password": password,
|
|
||||||
}
|
}
|
||||||
c.JSON(http.StatusOK, response)
|
c.String(http.StatusOK, hash)
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateUniqueHash() (string, error) {
|
func generateUniqueHash() (string, error) {
|
||||||
@ -101,27 +74,11 @@ func UpdateLinkHandler(c *gin.Context) {
|
|||||||
respondWithError(c, http.StatusBadRequest, "参数错误: "+err.Error())
|
respondWithError(c, http.StatusBadRequest, "参数错误: "+err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 先获取原有的短链接
|
|
||||||
existingLink, err := database.FindShortLinkByHash(params.Hash)
|
|
||||||
if err != nil {
|
|
||||||
respondWithError(c, http.StatusNotFound, "未找到短链接")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// 验证密码
|
|
||||||
if existingLink.Password != params.Password {
|
|
||||||
respondWithError(c, http.StatusUnauthorized, "密码错误")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// 更新URL,但保持原密码不变
|
|
||||||
shortLink := model.ShortLink{
|
shortLink := model.ShortLink{
|
||||||
Hash: params.Hash,
|
Hash: params.Hash,
|
||||||
Url: params.Url,
|
Url: params.Url,
|
||||||
Password: existingLink.Password, // 保持原密码不变
|
Password: params.Password,
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := database.SaveShortLink(&shortLink); err != nil {
|
if err := database.SaveShortLink(&shortLink); err != nil {
|
||||||
respondWithError(c, http.StatusInternalServerError, "数据库错误")
|
respondWithError(c, http.StatusInternalServerError, "数据库错误")
|
||||||
return
|
return
|
||||||
@ -131,7 +88,7 @@ func UpdateLinkHandler(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func GetRawConfHandler(c *gin.Context) {
|
func GetRawConfHandler(c *gin.Context) {
|
||||||
|
// 获取动态路由参数
|
||||||
hash := c.Param("hash")
|
hash := c.Param("hash")
|
||||||
password := c.Query("password")
|
password := c.Query("password")
|
||||||
|
|
||||||
@ -140,24 +97,27 @@ func GetRawConfHandler(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 查询数据库中的短链接
|
||||||
shortLink, err := database.FindShortLinkByHash(hash)
|
shortLink, err := database.FindShortLinkByHash(hash)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.String(http.StatusNotFound, "未找到短链接或密码错误")
|
c.String(http.StatusNotFound, "未找到短链接或密码错误")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 校验密码
|
||||||
if shortLink.Password != "" && shortLink.Password != password {
|
if shortLink.Password != "" && shortLink.Password != password {
|
||||||
c.String(http.StatusNotFound, "未找到短链接或密码错误")
|
c.String(http.StatusNotFound, "未找到短链接或密码错误")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 更新最后访问时间
|
||||||
shortLink.LastRequestTime = time.Now().Unix()
|
shortLink.LastRequestTime = time.Now().Unix()
|
||||||
err = database.SaveShortLink(shortLink)
|
err = database.SaveShortLink(shortLink)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
respondWithError(c, http.StatusInternalServerError, "数据库错误")
|
respondWithError(c, http.StatusInternalServerError, "数据库错误")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// 请求短链接指向的URL
|
||||||
response, err := http.Get("http://localhost:" + strconv.Itoa(config.Default.Port) + "/" + shortLink.Url)
|
response, err := http.Get("http://localhost:" + strconv.Itoa(config.Default.Port) + "/" + shortLink.Url)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
respondWithError(c, http.StatusInternalServerError, "请求错误: "+err.Error())
|
respondWithError(c, http.StatusInternalServerError, "请求错误: "+err.Error())
|
||||||
@ -165,35 +125,13 @@ func GetRawConfHandler(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
|
|
||||||
|
// 读取响应内容
|
||||||
all, err := io.ReadAll(response.Body)
|
all, err := io.ReadAll(response.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
respondWithError(c, http.StatusInternalServerError, "读取错误: "+err.Error())
|
respondWithError(c, http.StatusInternalServerError, "读取错误: "+err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 返回响应内容
|
||||||
c.String(http.StatusOK, string(all))
|
c.String(http.StatusOK, string(all))
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetRawConfUriHandler(c *gin.Context) {
|
|
||||||
|
|
||||||
hash := c.Query("hash")
|
|
||||||
password := c.Query("password")
|
|
||||||
|
|
||||||
if strings.TrimSpace(hash) == "" {
|
|
||||||
c.String(http.StatusBadRequest, "参数错误")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
shortLink, err := database.FindShortLinkByHash(hash)
|
|
||||||
if err != nil {
|
|
||||||
c.String(http.StatusNotFound, "未找到短链接或密码错误")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if shortLink.Password != "" && shortLink.Password != password {
|
|
||||||
c.String(http.StatusNotFound, "未找到短链接或密码错误")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.String(http.StatusOK, shortLink.Url)
|
|
||||||
}
|
|
||||||
|
@ -5,10 +5,9 @@ import (
|
|||||||
"html/template"
|
"html/template"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"sub2clash/api/handler"
|
||||||
"github.com/nitezs/sub2clash/api/handler"
|
"sub2clash/constant"
|
||||||
"github.com/nitezs/sub2clash/constant"
|
"sub2clash/middleware"
|
||||||
"github.com/nitezs/sub2clash/middleware"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
@ -45,5 +44,4 @@ func SetRoute(r *gin.Engine) {
|
|||||||
r.GET("/s/:hash", handler.GetRawConfHandler)
|
r.GET("/s/:hash", handler.GetRawConfHandler)
|
||||||
r.POST("/short", handler.GenerateLinkHandler)
|
r.POST("/short", handler.GenerateLinkHandler)
|
||||||
r.PUT("/short", handler.UpdateLinkHandler)
|
r.PUT("/short", handler.UpdateLinkHandler)
|
||||||
r.GET("/short", handler.GetRawConfUriHandler)
|
|
||||||
}
|
}
|
||||||
|
@ -75,12 +75,6 @@
|
|||||||
<label for="proxy">节点分享链接:</label>
|
<label for="proxy">节点分享链接:</label>
|
||||||
<textarea class="form-control" id="proxy" name="proxy" placeholder="每行输入一个节点分享链接" rows="5"></textarea>
|
<textarea class="form-control" id="proxy" name="proxy" placeholder="每行输入一个节点分享链接" rows="5"></textarea>
|
||||||
</div>
|
</div>
|
||||||
<!-- User Agent -->
|
|
||||||
<div class="form-group mb-3">
|
|
||||||
<label for="user-agent">ua标识:</label>
|
|
||||||
<textarea class="form-control" id="user-agent" name="user-agent"
|
|
||||||
placeholder="用于获取订阅的http请求中的user-agent标识(可选)" rows="3"></textarea>
|
|
||||||
</div>
|
|
||||||
<!-- Refresh -->
|
<!-- Refresh -->
|
||||||
<div class="form-check mb-3">
|
<div class="form-check mb-3">
|
||||||
<input class="form-check-input" id="refresh" name="refresh" type="checkbox" />
|
<input class="form-check-input" id="refresh" name="refresh" type="checkbox" />
|
||||||
@ -147,26 +141,23 @@
|
|||||||
<div class="form-group mb-5">
|
<div class="form-group mb-5">
|
||||||
<label for="apiLink">配置链接:</label>
|
<label for="apiLink">配置链接:</label>
|
||||||
<div class="input-group mb-2">
|
<div class="input-group mb-2">
|
||||||
<input class="form-control bg-light" id="apiLink" type="text" placeholder="链接" readonly style="cursor: not-allowed;" />
|
<input class="form-control" id="apiLink" type="text" placeholder="链接" />
|
||||||
<button class="btn btn-primary" onclick="copyToClipboard('apiLink',this)" type="button">
|
<button class="btn btn-primary" onclick="copyToClipboard('apiLink',this)" type="button">
|
||||||
复制链接
|
复制链接
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="input-group mb-2">
|
<div class="input-group">
|
||||||
<input class="form-control" id="customId" type="text" placeholder="短链ID(可选)" />
|
<input class="form-control" id="apiShortLink" type="text" placeholder="链接" />
|
||||||
<input class="form-control" id="password" type="text" placeholder="密码(可选)" />
|
<input class="form-control" id="password" type="text" placeholder="密码" />
|
||||||
<button class="btn btn-primary" onclick="generateShortLink()" type="button">
|
<button class="btn btn-primary" onclick="generateShortLink()" type="button">
|
||||||
生成短链
|
生成短链
|
||||||
</button>
|
</button>
|
||||||
<button class="btn btn-primary" onclick="copyToClipboard('apiShortLink',this)" type="button">
|
|
||||||
复制短链
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div class="input-group">
|
|
||||||
<input class="form-control bg-light" id="apiShortLink" type="text" placeholder="短链接" readonly style="cursor: not-allowed;" />
|
|
||||||
<button class="btn btn-primary" onclick="updateShortLink()" type="button">
|
<button class="btn btn-primary" onclick="updateShortLink()" type="button">
|
||||||
更新短链
|
更新短链
|
||||||
</button>
|
</button>
|
||||||
|
<button class="btn btn-primary" onclick="copyToClipboard('apiShortLink',this)" type="button">
|
||||||
|
复制短链
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@ -181,5 +172,4 @@
|
|||||||
</div>
|
</div>
|
||||||
</body>
|
</body>
|
||||||
<script src="./static/index.js"></script>
|
<script src="./static/index.js"></script>
|
||||||
|
|
||||||
</html>
|
</html>
|
@ -1,15 +1,3 @@
|
|||||||
function setInputReadOnly(input, readonly) {
|
|
||||||
if (readonly) {
|
|
||||||
input.readOnly = true;
|
|
||||||
input.classList.add('bg-light');
|
|
||||||
input.style.cursor = 'not-allowed';
|
|
||||||
} else {
|
|
||||||
input.readOnly = false;
|
|
||||||
input.classList.remove('bg-light');
|
|
||||||
input.style.cursor = 'auto';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function clearExistingValues() {
|
function clearExistingValues() {
|
||||||
// 清除简单输入框和复选框的值
|
// 清除简单输入框和复选框的值
|
||||||
document.getElementById("endpoint").value = "clash";
|
document.getElementById("endpoint").value = "clash";
|
||||||
@ -24,23 +12,7 @@ function clearExistingValues() {
|
|||||||
document.getElementById("remove").value = "";
|
document.getElementById("remove").value = "";
|
||||||
document.getElementById("apiLink").value = "";
|
document.getElementById("apiLink").value = "";
|
||||||
document.getElementById("apiShortLink").value = "";
|
document.getElementById("apiShortLink").value = "";
|
||||||
|
document.getElementById("password").value = "";
|
||||||
// 恢复短链ID和密码输入框状态
|
|
||||||
const customIdInput = document.getElementById("customId");
|
|
||||||
const passwordInput = document.getElementById("password");
|
|
||||||
const generateButton = document.querySelector('button[onclick="generateShortLink()"]');
|
|
||||||
|
|
||||||
customIdInput.value = "";
|
|
||||||
setInputReadOnly(customIdInput, false);
|
|
||||||
|
|
||||||
passwordInput.value = "";
|
|
||||||
setInputReadOnly(passwordInput, false);
|
|
||||||
|
|
||||||
// 恢复生成短链按钮状态
|
|
||||||
generateButton.disabled = false;
|
|
||||||
generateButton.classList.remove('btn-secondary');
|
|
||||||
generateButton.classList.add('btn-primary');
|
|
||||||
|
|
||||||
document.getElementById("nodeList").checked = false;
|
document.getElementById("nodeList").checked = false;
|
||||||
|
|
||||||
// 清除由 createRuleProvider, createReplace, 和 createRule 创建的所有额外输入组
|
// 清除由 createRuleProvider, createReplace, 和 createRule 创建的所有额外输入组
|
||||||
@ -94,11 +66,6 @@ function generateURI() {
|
|||||||
// alert("订阅链接和节点分享链接不能同时为空!");
|
// alert("订阅链接和节点分享链接不能同时为空!");
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取订阅user-agent标识
|
|
||||||
const userAgent = document.getElementById("user-agent").value;
|
|
||||||
queryParams.push(`userAgent=${encodeURIComponent(userAgent)}`);
|
|
||||||
|
|
||||||
// 获取复选框的值
|
// 获取复选框的值
|
||||||
const refresh = document.getElementById("refresh").checked;
|
const refresh = document.getElementById("refresh").checked;
|
||||||
queryParams.push(`refresh=${refresh ? "true" : "false"}`);
|
queryParams.push(`refresh=${refresh ? "true" : "false"}`);
|
||||||
@ -144,16 +111,17 @@ function generateURI() {
|
|||||||
queryParams.push(`ruleProvider=${encodeURIComponent(providers.join(","))}`);
|
queryParams.push(`ruleProvider=${encodeURIComponent(providers.join(","))}`);
|
||||||
|
|
||||||
let ruleList = [];
|
let ruleList = [];
|
||||||
for (let i = 0; i < rules.length / 2; i++) {
|
for (let i = 0; i < rules.length / 3; i++) {
|
||||||
if (rules[i * 2].value.trim() !== "") {
|
if (rules[i * 3].value.trim() !== "") {
|
||||||
let rule = rules[i * 2].value;
|
let rule = rules[i * 3].value;
|
||||||
let prepend = rules[i * 2 + 1].value;
|
let prepend = rules[i * 3 + 1].value;
|
||||||
|
let group = rules[i * 3 + 2].value;
|
||||||
// 是否存在空值
|
// 是否存在空值
|
||||||
if (rule.trim() === "" || prepend.trim() === "") {
|
if (rule.trim() === "" || prepend.trim() === "" || group.trim() === "") {
|
||||||
// alert("Rule 中存在空值,请检查后重试!");
|
// alert("Rule 中存在空值,请检查后重试!");
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
ruleList.push(`[${rule},${prepend}]`);
|
ruleList.push(`[${rule},${prepend},${group}]`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
queryParams.push(`rule=${encodeURIComponent(ruleList.join(","))}`);
|
queryParams.push(`rule=${encodeURIComponent(ruleList.join(","))}`);
|
||||||
@ -207,41 +175,13 @@ async function parseInputURL() {
|
|||||||
let hash = url.pathname.substring(url.pathname.lastIndexOf("/s/") + 3);
|
let hash = url.pathname.substring(url.pathname.lastIndexOf("/s/") + 3);
|
||||||
let q = new URLSearchParams();
|
let q = new URLSearchParams();
|
||||||
let password = url.searchParams.get("password");
|
let password = url.searchParams.get("password");
|
||||||
if (password === null) {
|
|
||||||
alert("仅可解析加密短链");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
q.append("hash", hash);
|
q.append("hash", hash);
|
||||||
q.append("password", password);
|
q.append("password", password);
|
||||||
try {
|
try {
|
||||||
const response = await axios.get("./short?" + q.toString());
|
const response = await axios.get("./short?" + q.toString());
|
||||||
url = new URL(window.location.href + response.data);
|
url = new URL(window.location.href + response.data);
|
||||||
|
document.querySelector("#apiShortLink").value = inputURL;
|
||||||
// 回显配置链接
|
document.querySelector("#password").value = password;
|
||||||
const apiLinkInput = document.querySelector("#apiLink");
|
|
||||||
apiLinkInput.value = `${window.location.origin}${window.location.pathname}${response.data}`;
|
|
||||||
setInputReadOnly(apiLinkInput, true);
|
|
||||||
|
|
||||||
// 回显短链相关信息
|
|
||||||
const apiShortLinkInput = document.querySelector("#apiShortLink");
|
|
||||||
apiShortLinkInput.value = inputURL;
|
|
||||||
setInputReadOnly(apiShortLinkInput, true);
|
|
||||||
|
|
||||||
// 设置短链ID和密码,并设置为只读
|
|
||||||
const customIdInput = document.querySelector("#customId");
|
|
||||||
const passwordInput = document.querySelector("#password");
|
|
||||||
const generateButton = document.querySelector('button[onclick="generateShortLink()"]');
|
|
||||||
|
|
||||||
customIdInput.value = hash;
|
|
||||||
setInputReadOnly(customIdInput, true);
|
|
||||||
|
|
||||||
passwordInput.value = password;
|
|
||||||
setInputReadOnly(passwordInput, true);
|
|
||||||
|
|
||||||
// 禁用生成短链按钮
|
|
||||||
generateButton.disabled = true;
|
|
||||||
generateButton.classList.add('btn-secondary');
|
|
||||||
generateButton.classList.remove('btn-primary');
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
alert("获取短链失败,请检查密码!");
|
alert("获取短链失败,请检查密码!");
|
||||||
@ -307,17 +247,6 @@ async function parseInputURL() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (params.has("userAgent")) {
|
|
||||||
document.getElementById("user-agent").value = decodeURIComponent(
|
|
||||||
params.get("userAgent")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (params.has("ignoreCountryGroup")) {
|
|
||||||
document.getElementById("igcg").checked =
|
|
||||||
params.get("ignoreCountryGroup") === "true";
|
|
||||||
}
|
|
||||||
|
|
||||||
if (params.has("replace")) {
|
if (params.has("replace")) {
|
||||||
parseAndFillReplaceParams(decodeURIComponent(params.get("replace")));
|
parseAndFillReplaceParams(decodeURIComponent(params.get("replace")));
|
||||||
}
|
}
|
||||||
@ -381,12 +310,13 @@ function parseAndFillRuleProviderParams(ruleProviderParams) {
|
|||||||
function parseAndFillRuleParams(ruleParams) {
|
function parseAndFillRuleParams(ruleParams) {
|
||||||
const ruleGroup = document.getElementById("ruleGroup");
|
const ruleGroup = document.getElementById("ruleGroup");
|
||||||
let matches;
|
let matches;
|
||||||
const regex = /\[(.*?),(.*?)\]/g;
|
const regex = /\[(.*?),(.*?),(.*?)\]/g;
|
||||||
const str = decodeURIComponent(ruleParams);
|
const str = decodeURIComponent(ruleParams);
|
||||||
while ((matches = regex.exec(str)) !== null) {
|
while ((matches = regex.exec(str)) !== null) {
|
||||||
const div = createRule();
|
const div = createRule();
|
||||||
div.children[0].value = matches[1];
|
div.children[0].value = matches[1];
|
||||||
div.children[1].value = matches[2];
|
div.children[1].value = matches[2];
|
||||||
|
div.children[2].value = matches[3];
|
||||||
ruleGroup.appendChild(div);
|
ruleGroup.appendChild(div);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -436,6 +366,7 @@ function createRule() {
|
|||||||
div.innerHTML = `
|
div.innerHTML = `
|
||||||
<input type="text" class="form-control" name="rule" placeholder="Rule">
|
<input type="text" class="form-control" name="rule" placeholder="Rule">
|
||||||
<input type="text" class="form-control" name="rule" placeholder="Prepend">
|
<input type="text" class="form-control" name="rule" placeholder="Prepend">
|
||||||
|
<input type="text" class="form-control" name="rule" placeholder="Group">
|
||||||
<button type="button" class="btn btn-danger" onclick="removeElement(this)">删除</button>
|
<button type="button" class="btn btn-danger" onclick="removeElement(this)">删除</button>
|
||||||
`;
|
`;
|
||||||
return div;
|
return div;
|
||||||
@ -491,25 +422,21 @@ function generateURL() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
apiLink.value = `${window.location.origin}${window.location.pathname}${uri}`;
|
apiLink.value = `${window.location.origin}${window.location.pathname}${uri}`;
|
||||||
setInputReadOnly(apiLink, true);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function generateShortLink() {
|
function generateShortLink() {
|
||||||
const apiShortLink = document.getElementById("apiShortLink");
|
const apiShortLink = document.getElementById("apiShortLink");
|
||||||
const password = document.getElementById("password");
|
const password = document.getElementById("password");
|
||||||
const customId = document.getElementById("customId");
|
|
||||||
let uri = generateURI();
|
let uri = generateURI();
|
||||||
if (uri === "") {
|
if (uri === "") {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
axios
|
axios
|
||||||
.post(
|
.post(
|
||||||
"./short",
|
"./short",
|
||||||
{
|
{
|
||||||
url: uri,
|
url: uri,
|
||||||
password: password.value.trim(),
|
password: password.value.trim(),
|
||||||
customId: customId.value.trim()
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
headers: {
|
headers: {
|
||||||
@ -518,20 +445,11 @@ function generateShortLink() {
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
.then((response) => {
|
.then((response) => {
|
||||||
// 设置返回的短链ID和密码
|
apiShortLink.value = `${window.location.origin}${window.location.pathname}s/${response.data}`;
|
||||||
customId.value = response.data.hash;
|
|
||||||
password.value = response.data.password;
|
|
||||||
// 生成完整的短链接
|
|
||||||
const shortLink = `${window.location.origin}${window.location.pathname}s/${response.data.hash}?password=${response.data.password}`;
|
|
||||||
apiShortLink.value = shortLink;
|
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
if (error.response && error.response.data) {
|
alert("生成短链失败,请重试!");
|
||||||
alert(error.response.data);
|
|
||||||
} else {
|
|
||||||
alert("生成短链失败,请重试!");
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -544,7 +462,7 @@ function updateShortLink() {
|
|||||||
hash = u.pathname.substring(u.pathname.lastIndexOf("/s/") + 3);
|
hash = u.pathname.substring(u.pathname.lastIndexOf("/s/") + 3);
|
||||||
}
|
}
|
||||||
if (password.value.trim() === "") {
|
if (password.value.trim() === "") {
|
||||||
alert("请输入原密码进行验证!");
|
alert("请输入密码!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let uri = generateURI();
|
let uri = generateURI();
|
||||||
@ -566,17 +484,11 @@ function updateShortLink() {
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
.then((response) => {
|
.then((response) => {
|
||||||
alert(`短链 ${hash} 更新成功!`);
|
alert("更新短链成功!");
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
if (error.response && error.response.status === 401) {
|
alert(error.response.data);
|
||||||
alert("密码错误,请输入正确的原密码!");
|
|
||||||
} else if (error.response && error.response.data) {
|
|
||||||
alert(error.response.data);
|
|
||||||
} else {
|
|
||||||
alert("更新短链失败,请重试!");
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -5,7 +5,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
|
||||||
"github.com/nitezs/sub2clash/model"
|
"sub2clash/model"
|
||||||
|
|
||||||
"go.etcd.io/bbolt"
|
"go.etcd.io/bbolt"
|
||||||
)
|
)
|
||||||
@ -13,14 +13,16 @@ import (
|
|||||||
var DB *bbolt.DB
|
var DB *bbolt.DB
|
||||||
|
|
||||||
func ConnectDB() error {
|
func ConnectDB() error {
|
||||||
|
// 确保数据目录存在
|
||||||
path := filepath.Join("data", "sub2clash.db")
|
path := filepath.Join("data", "sub2clash.db")
|
||||||
|
// 打开或创建数据库文件
|
||||||
db, err := bbolt.Open(path, 0600, nil)
|
db, err := bbolt.Open(path, 0600, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
DB = db
|
DB = db
|
||||||
|
|
||||||
|
// 确保存储桶存在
|
||||||
return db.Update(func(tx *bbolt.Tx) error {
|
return db.Update(func(tx *bbolt.Tx) error {
|
||||||
_, err := tx.CreateBucketIfNotExists([]byte("ShortLinks"))
|
_, err := tx.CreateBucketIfNotExists([]byte("ShortLinks"))
|
||||||
return err
|
return err
|
||||||
|
@ -2,53 +2,31 @@ package common
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"sub2clash/config"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/nitezs/sub2clash/config"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type GetConfig struct {
|
func Get(url string) (resp *http.Response, err error) {
|
||||||
userAgent string
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetOption func(*GetConfig)
|
|
||||||
|
|
||||||
func WithUserAgent(userAgent string) GetOption {
|
|
||||||
return func(config *GetConfig) {
|
|
||||||
config.userAgent = userAgent
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func Get(url string, options ...GetOption) (resp *http.Response, err error) {
|
|
||||||
retryTimes := config.Default.RequestRetryTimes
|
retryTimes := config.Default.RequestRetryTimes
|
||||||
haveTried := 0
|
haveTried := 0
|
||||||
retryDelay := time.Second
|
retryDelay := time.Second // 延迟1秒再重试
|
||||||
getConfig := GetConfig{}
|
|
||||||
for _, option := range options {
|
|
||||||
option(&getConfig)
|
|
||||||
}
|
|
||||||
var req *http.Request
|
|
||||||
var get *http.Response
|
|
||||||
for haveTried < retryTimes {
|
for haveTried < retryTimes {
|
||||||
client := &http.Client{}
|
client := &http.Client{}
|
||||||
//client.Timeout = time.Second * 10
|
//client.Timeout = time.Second * 10
|
||||||
req, err = http.NewRequest("GET", url, nil)
|
req, err := http.NewRequest("GET", url, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
haveTried++
|
haveTried++
|
||||||
time.Sleep(retryDelay)
|
time.Sleep(retryDelay)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if getConfig.userAgent != "" {
|
get, err := client.Do(req)
|
||||||
req.Header.Set("User-Agent", getConfig.userAgent)
|
|
||||||
}
|
|
||||||
get, err = client.Do(req)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
haveTried++
|
haveTried++
|
||||||
time.Sleep(retryDelay)
|
time.Sleep(retryDelay)
|
||||||
continue
|
continue
|
||||||
} else {
|
} else {
|
||||||
|
// 如果文件大小大于设定,直接返回错误
|
||||||
if get != nil && get.ContentLength > config.Default.RequestMaxFileSize {
|
if get != nil && get.ContentLength > config.Default.RequestMaxFileSize {
|
||||||
return nil, errors.New("文件过大")
|
return nil, errors.New("文件过大")
|
||||||
}
|
}
|
||||||
@ -56,5 +34,5 @@ func Get(url string, options ...GetOption) (resp *http.Response, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
return nil, fmt.Errorf("请求失败:%v", err)
|
return nil, err
|
||||||
}
|
}
|
||||||
|
@ -2,17 +2,16 @@ package common
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"strings"
|
"strings"
|
||||||
|
"sub2clash/constant"
|
||||||
"github.com/nitezs/sub2clash/constant"
|
"sub2clash/logger"
|
||||||
"github.com/nitezs/sub2clash/logger"
|
"sub2clash/model"
|
||||||
"github.com/nitezs/sub2clash/model"
|
"sub2clash/parser"
|
||||||
"github.com/nitezs/sub2clash/parser"
|
|
||||||
|
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetContryName(countryKey string) string {
|
func GetContryName(countryKey string) string {
|
||||||
|
// 创建一个切片包含所有的国家映射
|
||||||
countryMaps := []map[string]string{
|
countryMaps := []map[string]string{
|
||||||
model.CountryFlag,
|
model.CountryFlag,
|
||||||
model.CountryChineseName,
|
model.CountryChineseName,
|
||||||
@ -20,9 +19,11 @@ func GetContryName(countryKey string) string {
|
|||||||
model.CountryEnglishName,
|
model.CountryEnglishName,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 对每一个映射进行检查
|
||||||
for i, countryMap := range countryMaps {
|
for i, countryMap := range countryMaps {
|
||||||
if i == 2 {
|
if i == 2 {
|
||||||
|
// 对ISO匹配做特殊处理
|
||||||
|
// 根据常用分割字符分割字符串
|
||||||
splitChars := []string{"-", "_", " "}
|
splitChars := []string{"-", "_", " "}
|
||||||
key := make([]string, 0)
|
key := make([]string, 0)
|
||||||
for _, splitChar := range splitChars {
|
for _, splitChar := range splitChars {
|
||||||
@ -33,9 +34,9 @@ func GetContryName(countryKey string) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 对每一个分割后的字符串进行检查
|
||||||
for _, v := range key {
|
for _, v := range key {
|
||||||
|
// 如果匹配到了国家
|
||||||
if country, ok := countryMap[strings.ToUpper(v)]; ok {
|
if country, ok := countryMap[strings.ToUpper(v)]; ok {
|
||||||
return country
|
return country
|
||||||
}
|
}
|
||||||
@ -55,7 +56,7 @@ func AddProxy(
|
|||||||
lazy bool, clashType model.ClashType, proxies ...model.Proxy,
|
lazy bool, clashType model.ClashType, proxies ...model.Proxy,
|
||||||
) {
|
) {
|
||||||
proxyTypes := model.GetSupportProxyTypes(clashType)
|
proxyTypes := model.GetSupportProxyTypes(clashType)
|
||||||
|
// 添加节点
|
||||||
for _, proxy := range proxies {
|
for _, proxy := range proxies {
|
||||||
if !proxyTypes[proxy.Type] {
|
if !proxyTypes[proxy.Type] {
|
||||||
continue
|
continue
|
||||||
@ -105,7 +106,7 @@ func ParseProxy(proxies ...string) []model.Proxy {
|
|||||||
if proxy != "" {
|
if proxy != "" {
|
||||||
var proxyItem model.Proxy
|
var proxyItem model.Proxy
|
||||||
var err error
|
var err error
|
||||||
|
// 解析节点
|
||||||
if strings.HasPrefix(proxy, constant.ShadowsocksPrefix) {
|
if strings.HasPrefix(proxy, constant.ShadowsocksPrefix) {
|
||||||
proxyItem, err = parser.ParseShadowsocks(proxy)
|
proxyItem, err = parser.ParseShadowsocks(proxy)
|
||||||
}
|
}
|
||||||
@ -127,9 +128,6 @@ func ParseProxy(proxies ...string) []model.Proxy {
|
|||||||
if strings.HasPrefix(proxy, constant.HysteriaPrefix) {
|
if strings.HasPrefix(proxy, constant.HysteriaPrefix) {
|
||||||
proxyItem, err = parser.ParseHysteria(proxy)
|
proxyItem, err = parser.ParseHysteria(proxy)
|
||||||
}
|
}
|
||||||
if strings.HasPrefix(proxy, constant.SocksPrefix) {
|
|
||||||
proxyItem, err = parser.ParseSocks(proxy)
|
|
||||||
}
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
result = append(result, proxyItem)
|
result = append(result, proxyItem)
|
||||||
} else {
|
} else {
|
||||||
|
@ -3,7 +3,7 @@ package common
|
|||||||
import "math/rand"
|
import "math/rand"
|
||||||
|
|
||||||
func RandomString(length int) string {
|
func RandomString(length int) string {
|
||||||
|
// 生成随机字符串
|
||||||
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||||
var result []byte
|
var result []byte
|
||||||
for i := 0; i < length; i++ {
|
for i := 0; i < length; i++ {
|
||||||
|
@ -3,8 +3,7 @@ package common
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sub2clash/model"
|
||||||
"github.com/nitezs/sub2clash/model"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func PrependRuleProvider(
|
func PrependRuleProvider(
|
||||||
|
@ -8,18 +8,17 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"sub2clash/config"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/nitezs/sub2clash/config"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var subsDir = "subs"
|
var subsDir = "subs"
|
||||||
var fileLock sync.RWMutex
|
var fileLock sync.RWMutex
|
||||||
|
|
||||||
func LoadSubscription(url string, refresh bool, userAgent string) ([]byte, error) {
|
func LoadSubscription(url string, refresh bool) ([]byte, error) {
|
||||||
if refresh {
|
if refresh {
|
||||||
return FetchSubscriptionFromAPI(url, userAgent)
|
return FetchSubscriptionFromAPI(url)
|
||||||
}
|
}
|
||||||
hash := sha256.Sum224([]byte(url))
|
hash := sha256.Sum224([]byte(url))
|
||||||
fileName := filepath.Join(subsDir, hex.EncodeToString(hash[:]))
|
fileName := filepath.Join(subsDir, hex.EncodeToString(hash[:]))
|
||||||
@ -28,9 +27,9 @@ func LoadSubscription(url string, refresh bool, userAgent string) ([]byte, error
|
|||||||
if !os.IsNotExist(err) {
|
if !os.IsNotExist(err) {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return FetchSubscriptionFromAPI(url, userAgent)
|
return FetchSubscriptionFromAPI(url)
|
||||||
}
|
}
|
||||||
lastGetTime := stat.ModTime().Unix()
|
lastGetTime := stat.ModTime().Unix() // 单位是秒
|
||||||
if lastGetTime+config.Default.CacheExpire > time.Now().Unix() {
|
if lastGetTime+config.Default.CacheExpire > time.Now().Unix() {
|
||||||
file, err := os.Open(fileName)
|
file, err := os.Open(fileName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -49,13 +48,13 @@ func LoadSubscription(url string, refresh bool, userAgent string) ([]byte, error
|
|||||||
}
|
}
|
||||||
return subContent, nil
|
return subContent, nil
|
||||||
}
|
}
|
||||||
return FetchSubscriptionFromAPI(url, userAgent)
|
return FetchSubscriptionFromAPI(url)
|
||||||
}
|
}
|
||||||
|
|
||||||
func FetchSubscriptionFromAPI(url string, userAgent string) ([]byte, error) {
|
func FetchSubscriptionFromAPI(url string) ([]byte, error) {
|
||||||
hash := sha256.Sum224([]byte(url))
|
hash := sha256.Sum224([]byte(url))
|
||||||
fileName := filepath.Join(subsDir, hex.EncodeToString(hash[:]))
|
fileName := filepath.Join(subsDir, hex.EncodeToString(hash[:]))
|
||||||
resp, err := Get(url, WithUserAgent(userAgent))
|
resp, err := Get(url)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
@ -7,6 +7,8 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// LoadTemplate 加载模板
|
||||||
|
// templates 模板文件名
|
||||||
func LoadTemplate(template string) ([]byte, error) {
|
func LoadTemplate(template string) ([]byte, error) {
|
||||||
tPath := filepath.Join("templates", template)
|
tPath := filepath.Join("templates", template)
|
||||||
if _, err := os.Stat(tPath); err == nil {
|
if _, err := os.Stat(tPath); err == nil {
|
||||||
|
@ -3,8 +3,7 @@ package common
|
|||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"sub2clash/config"
|
||||||
"github.com/nitezs/sub2clash/config"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func writeTemplate(path string, template string) error {
|
func writeTemplate(path string, template string) error {
|
||||||
|
@ -9,5 +9,4 @@ const (
|
|||||||
TrojanPrefix string = "trojan://"
|
TrojanPrefix string = "trojan://"
|
||||||
VLESSPrefix string = "vless://"
|
VLESSPrefix string = "vless://"
|
||||||
VMessPrefix string = "vmess://"
|
VMessPrefix string = "vmess://"
|
||||||
SocksPrefix string = "socks"
|
|
||||||
)
|
)
|
||||||
|
2
go.mod
2
go.mod
@ -1,4 +1,4 @@
|
|||||||
module github.com/nitezs/sub2clash
|
module sub2clash
|
||||||
|
|
||||||
go 1.21
|
go 1.21
|
||||||
|
|
||||||
|
29
main.go
29
main.go
@ -4,12 +4,11 @@ import (
|
|||||||
_ "embed"
|
_ "embed"
|
||||||
"io"
|
"io"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"sub2clash/api"
|
||||||
"github.com/nitezs/sub2clash/api"
|
"sub2clash/common"
|
||||||
"github.com/nitezs/sub2clash/common"
|
"sub2clash/common/database"
|
||||||
"github.com/nitezs/sub2clash/common/database"
|
"sub2clash/config"
|
||||||
"github.com/nitezs/sub2clash/config"
|
"sub2clash/logger"
|
||||||
"github.com/nitezs/sub2clash/logger"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
@ -23,24 +22,24 @@ var templateClash string
|
|||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
var err error
|
var err error
|
||||||
|
// 创建文件夹
|
||||||
err = common.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))
|
||||||
}
|
}
|
||||||
|
// 加载配置
|
||||||
err = config.LoadConfig()
|
err = config.LoadConfig()
|
||||||
|
// 初始化日志
|
||||||
logger.InitLogger(config.Default.LogLevel)
|
logger.InitLogger(config.Default.LogLevel)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Logger.Panic("load config failed", zap.Error(err))
|
logger.Logger.Panic("load config failed", zap.Error(err))
|
||||||
}
|
}
|
||||||
|
// 写入默认模板
|
||||||
err = common.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))
|
||||||
}
|
}
|
||||||
|
// 连接数据库
|
||||||
err = database.ConnectDB()
|
err = database.ConnectDB()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Logger.Panic("database connect failed", zap.Error(err))
|
logger.Logger.Panic("database connect failed", zap.Error(err))
|
||||||
@ -49,13 +48,13 @@ func init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
// 设置运行模式
|
||||||
gin.SetMode(gin.ReleaseMode)
|
gin.SetMode(gin.ReleaseMode)
|
||||||
|
// 关闭 Gin 的日志输出
|
||||||
gin.DefaultWriter = io.Discard
|
gin.DefaultWriter = io.Discard
|
||||||
|
// 创建路由
|
||||||
r := gin.Default()
|
r := gin.Default()
|
||||||
|
// 设置路由
|
||||||
api.SetRoute(r)
|
api.SetRoute(r)
|
||||||
logger.Logger.Info("server is running at http://localhost:" + strconv.Itoa(config.Default.Port))
|
logger.Logger.Info("server is running at http://localhost:" + strconv.Itoa(config.Default.Port))
|
||||||
err := r.Run(":" + strconv.Itoa(config.Default.Port))
|
err := r.Run(":" + strconv.Itoa(config.Default.Port))
|
||||||
|
@ -2,10 +2,9 @@ package middleware
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"sub2clash/logger"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/nitezs/sub2clash/logger"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
)
|
)
|
||||||
|
@ -14,7 +14,6 @@ func GetSupportProxyTypes(clashType ClashType) map[string]bool {
|
|||||||
"ssr": true,
|
"ssr": true,
|
||||||
"vmess": true,
|
"vmess": true,
|
||||||
"trojan": true,
|
"trojan": true,
|
||||||
"socks5": true,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if clashType == ClashMeta {
|
if clashType == ClashMeta {
|
||||||
@ -26,7 +25,6 @@ func GetSupportProxyTypes(clashType ClashType) map[string]bool {
|
|||||||
"vless": true,
|
"vless": true,
|
||||||
"hysteria": true,
|
"hysteria": true,
|
||||||
"hysteria2": true,
|
"hysteria2": true,
|
||||||
"socks5": true,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
@ -1,5 +1,8 @@
|
|||||||
package model
|
package model
|
||||||
|
|
||||||
|
// https://zh.wikipedia.org/wiki/%E5%8C%BA%E5%9F%9F%E6%8C%87%E7%A4%BA%E7%AC%A6
|
||||||
|
// https://zh.wikipedia.org/zh-sg/ISO_3166-1%E4%BA%8C%E4%BD%8D%E5%AD%97%E6%AF%8D%E4%BB%A3%E7%A0%81
|
||||||
|
|
||||||
var CountryEnglishName = map[string]string{
|
var CountryEnglishName = map[string]string{
|
||||||
"Andorra": "安道尔(AD)",
|
"Andorra": "安道尔(AD)",
|
||||||
"United Arab Emirates": "阿联酋(AE)",
|
"United Arab Emirates": "阿联酋(AE)",
|
||||||
|
132
model/proxy.go
132
model/proxy.go
@ -5,83 +5,62 @@ type SmuxStruct struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Proxy struct {
|
type Proxy struct {
|
||||||
Name string `yaml:"name,omitempty"`
|
Name string `yaml:"name,omitempty"`
|
||||||
Server string `yaml:"server,omitempty"`
|
Server string `yaml:"server,omitempty"`
|
||||||
Port int `yaml:"port,omitempty"`
|
Port int `yaml:"port,omitempty"`
|
||||||
Type string `yaml:"type,omitempty"`
|
Type string `yaml:"type,omitempty"`
|
||||||
Cipher string `yaml:"cipher,omitempty"`
|
Cipher string `yaml:"cipher,omitempty"`
|
||||||
Username string `yaml:"username,omitempty"`
|
Password string `yaml:"password,omitempty"`
|
||||||
Password string `yaml:"password,omitempty"`
|
UDP bool `yaml:"udp,omitempty"`
|
||||||
UDP bool `yaml:"udp,omitempty"`
|
UUID string `yaml:"uuid,omitempty"`
|
||||||
UUID string `yaml:"uuid,omitempty"`
|
Network string `yaml:"network,omitempty"`
|
||||||
Network string `yaml:"network,omitempty"`
|
Flow string `yaml:"flow,omitempty"`
|
||||||
Flow string `yaml:"flow,omitempty"`
|
TLS bool `yaml:"tls,omitempty"`
|
||||||
TLS bool `yaml:"tls,omitempty"`
|
ClientFingerprint string `yaml:"client-fingerprint,omitempty"`
|
||||||
ClientFingerprint string `yaml:"client-fingerprint,omitempty"`
|
Plugin string `yaml:"plugin,omitempty"`
|
||||||
Plugin string `yaml:"plugin,omitempty"`
|
PluginOpts map[string]any `yaml:"plugin-opts,omitempty"`
|
||||||
PluginOpts map[string]any `yaml:"plugin-opts,omitempty"`
|
Smux SmuxStruct `yaml:"smux,omitempty"`
|
||||||
Smux SmuxStruct `yaml:"smux,omitempty"`
|
Sni string `yaml:"sni,omitempty"`
|
||||||
Sni string `yaml:"sni,omitempty"`
|
AllowInsecure bool `yaml:"allow-insecure,omitempty"`
|
||||||
AllowInsecure bool `yaml:"allow-insecure,omitempty"`
|
Fingerprint string `yaml:"fingerprint,omitempty"`
|
||||||
Fingerprint string `yaml:"fingerprint,omitempty"`
|
SkipCertVerify bool `yaml:"skip-cert-verify,omitempty"`
|
||||||
SkipCertVerify bool `yaml:"skip-cert-verify,omitempty"`
|
Alpn []string `yaml:"alpn,omitempty"`
|
||||||
Alpn []string `yaml:"alpn,omitempty"`
|
XUDP bool `yaml:"xudp,omitempty"`
|
||||||
XUDP bool `yaml:"xudp,omitempty"`
|
Servername string `yaml:"servername,omitempty"`
|
||||||
Servername string `yaml:"servername,omitempty"`
|
WSOpts WSOptions `yaml:"ws-opts,omitempty"`
|
||||||
WSOpts WSOptions `yaml:"ws-opts,omitempty"`
|
AlterID int `yaml:"alterId,omitempty"`
|
||||||
AlterID int `yaml:"alterId,omitempty"`
|
GrpcOpts GrpcOptions `yaml:"grpc-opts,omitempty"`
|
||||||
GrpcOpts GrpcOptions `yaml:"grpc-opts,omitempty"`
|
RealityOpts RealityOptions `yaml:"reality-opts,omitempty"`
|
||||||
RealityOpts RealityOptions `yaml:"reality-opts,omitempty"`
|
Protocol string `yaml:"protocol,omitempty"`
|
||||||
Protocol string `yaml:"protocol,omitempty"`
|
Obfs string `yaml:"obfs,omitempty"`
|
||||||
Obfs string `yaml:"obfs,omitempty"`
|
ObfsParam string `yaml:"obfs-param,omitempty"`
|
||||||
ObfsParam string `yaml:"obfs-param,omitempty"`
|
ProtocolParam string `yaml:"protocol-param,omitempty"`
|
||||||
ProtocolParam string `yaml:"protocol-param,omitempty"`
|
Remarks []string `yaml:"remarks,omitempty"`
|
||||||
Remarks []string `yaml:"remarks,omitempty"`
|
HTTPOpts HTTPOptions `yaml:"http-opts,omitempty"`
|
||||||
HTTPOpts HTTPOptions `yaml:"http-opts,omitempty"`
|
HTTP2Opts HTTP2Options `yaml:"h2-opts,omitempty"`
|
||||||
HTTP2Opts HTTP2Options `yaml:"h2-opts,omitempty"`
|
PacketAddr bool `yaml:"packet-addr,omitempty"`
|
||||||
PacketAddr bool `yaml:"packet-addr,omitempty"`
|
PacketEncoding string `yaml:"packet-encoding,omitempty"`
|
||||||
PacketEncoding string `yaml:"packet-encoding,omitempty"`
|
GlobalPadding bool `yaml:"global-padding,omitempty"`
|
||||||
GlobalPadding bool `yaml:"global-padding,omitempty"`
|
AuthenticatedLength bool `yaml:"authenticated-length,omitempty"`
|
||||||
AuthenticatedLength bool `yaml:"authenticated-length,omitempty"`
|
UDPOverTCP bool `yaml:"udp-over-tcp,omitempty"`
|
||||||
UDPOverTCP bool `yaml:"udp-over-tcp,omitempty"`
|
UDPOverTCPVersion int `yaml:"udp-over-tcp-version,omitempty"`
|
||||||
UDPOverTCPVersion int `yaml:"udp-over-tcp-version,omitempty"`
|
SubName string `yaml:"-"`
|
||||||
SubName string `yaml:"-"`
|
Up string `yaml:"up,omitempty"`
|
||||||
Up string `yaml:"up,omitempty"`
|
Down string `yaml:"down,omitempty"`
|
||||||
Down string `yaml:"down,omitempty"`
|
CustomCA string `yaml:"ca,omitempty"`
|
||||||
CustomCA string `yaml:"ca,omitempty"`
|
CustomCAString string `yaml:"ca-str,omitempty"`
|
||||||
CustomCAString string `yaml:"ca-str,omitempty"`
|
CWND int `yaml:"cwnd,omitempty"`
|
||||||
CWND int `yaml:"cwnd,omitempty"`
|
Auth string `yaml:"auth,omitempty"`
|
||||||
Auth string `yaml:"auth,omitempty"`
|
ReceiveWindowConn int `yaml:"recv-window-conn,omitempty"`
|
||||||
ReceiveWindowConn int `yaml:"recv-window-conn,omitempty"`
|
ReceiveWindow int `yaml:"recv-window,omitempty"`
|
||||||
ReceiveWindow int `yaml:"recv-window,omitempty"`
|
DisableMTUDiscovery bool `yaml:"disable-mtu-discovery,omitempty"`
|
||||||
DisableMTUDiscovery bool `yaml:"disable-mtu-discovery,omitempty"`
|
FastOpen bool `yaml:"fast-open,omitempty"`
|
||||||
FastOpen bool `yaml:"fast-open,omitempty"`
|
HopInterval int `yaml:"hop-interval,omitempty"`
|
||||||
HopInterval int `yaml:"hop-interval,omitempty"`
|
Ports string `yaml:"ports,omitempty"`
|
||||||
Ports string `yaml:"ports,omitempty"`
|
AuthStringOLD string `yaml:"auth_str,omitempty"`
|
||||||
AuthStringOLD string `yaml:"auth_str,omitempty"`
|
AuthString string `yaml:"auth-str,omitempty"`
|
||||||
AuthString string `yaml:"auth-str,omitempty"`
|
|
||||||
Ip string `yaml:"ip,omitempty"`
|
|
||||||
Ipv6 string `yaml:"ipv6,omitempty"`
|
|
||||||
PrivateKey string `yaml:"private-key,omitempty"`
|
|
||||||
Workers int `yaml:"workers,omitempty"`
|
|
||||||
MTU int `yaml:"mtu,omitempty"`
|
|
||||||
PersistentKeepalive int `yaml:"persistent-keepalive,omitempty"`
|
|
||||||
Peers []WireGuardPeerOption `yaml:"peers,omitempty"`
|
|
||||||
RemoteDnsResolve bool `yaml:"remote-dns-resolve,omitempty"`
|
|
||||||
Dns []string `yaml:"dns,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type WireGuardPeerOption struct {
|
|
||||||
Server string `yaml:"server"`
|
|
||||||
Port int `yaml:"port"`
|
|
||||||
PublicKey string `yaml:"public-key,omitempty"`
|
|
||||||
PreSharedKey string `yaml:"pre-shared-key,omitempty"`
|
|
||||||
Reserved []uint8 `yaml:"reserved,omitempty"`
|
|
||||||
AllowedIPs []string `yaml:"allowed-ips,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type _Proxy Proxy
|
|
||||||
|
|
||||||
func (p Proxy) MarshalYAML() (interface{}, error) {
|
func (p Proxy) MarshalYAML() (interface{}, error) {
|
||||||
switch p.Type {
|
switch p.Type {
|
||||||
case "vmess":
|
case "vmess":
|
||||||
@ -98,7 +77,6 @@ func (p Proxy) MarshalYAML() (interface{}, error) {
|
|||||||
return ProxyToHysteria(p), nil
|
return ProxyToHysteria(p), nil
|
||||||
case "hysteria2":
|
case "hysteria2":
|
||||||
return ProxyToHysteria2(p), nil
|
return ProxyToHysteria2(p), nil
|
||||||
default:
|
|
||||||
return _Proxy(p), nil
|
|
||||||
}
|
}
|
||||||
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
@ -9,12 +9,12 @@ type ProxyGroup struct {
|
|||||||
Type string `yaml:"type,omitempty"`
|
Type string `yaml:"type,omitempty"`
|
||||||
Name string `yaml:"name,omitempty"`
|
Name string `yaml:"name,omitempty"`
|
||||||
Proxies []string `yaml:"proxies,omitempty"`
|
Proxies []string `yaml:"proxies,omitempty"`
|
||||||
IsCountryGrop bool `yaml:"-"`
|
IsCountryGrop bool `yaml:"-"` // 是否是国家分组
|
||||||
Url string `yaml:"url,omitempty"`
|
Url string `yaml:"url,omitempty"`
|
||||||
Interval int `yaml:"interval,omitempty"`
|
Interval int `yaml:"interval,omitempty"`
|
||||||
Tolerance int `yaml:"tolerance,omitempty"`
|
Tolerance int `yaml:"tolerance,omitempty"`
|
||||||
Lazy bool `yaml:"lazy"`
|
Lazy bool `yaml:"lazy"`
|
||||||
Size int `yaml:"-"`
|
Size int `yaml:"-"` // 代理数量
|
||||||
DisableUDP bool `yaml:"disable-udp,omitempty"`
|
DisableUDP bool `yaml:"disable-udp,omitempty"`
|
||||||
Strategy string `yaml:"strategy,omitempty"`
|
Strategy string `yaml:"strategy,omitempty"`
|
||||||
Icon string `yaml:"icon,omitempty"`
|
Icon string `yaml:"icon,omitempty"`
|
||||||
@ -42,15 +42,16 @@ func (p ProxyGroupsSortBySize) Len() int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p ProxyGroupsSortByName) Less(i, j int) bool {
|
func (p ProxyGroupsSortByName) Less(i, j int) bool {
|
||||||
|
// 定义一组备选语言:首选英语,其次中文
|
||||||
tags := []language.Tag{
|
tags := []language.Tag{
|
||||||
language.English,
|
language.English,
|
||||||
language.Chinese,
|
language.Chinese,
|
||||||
}
|
}
|
||||||
matcher := language.NewMatcher(tags)
|
matcher := language.NewMatcher(tags)
|
||||||
|
|
||||||
|
// 假设我们的请求语言是 "zh"(中文),则使用匹配器找到最佳匹配的语言
|
||||||
bestMatch, _, _ := matcher.Match(language.Make("zh"))
|
bestMatch, _, _ := matcher.Match(language.Make("zh"))
|
||||||
|
// 使用最佳匹配的语言进行排序
|
||||||
c := collate.New(bestMatch)
|
c := collate.New(bestMatch)
|
||||||
return c.CompareString(p[i].Name, p[j].Name) < 0
|
return c.CompareString(p[i].Name, p[j].Name) < 0
|
||||||
}
|
}
|
||||||
|
@ -7,11 +7,11 @@ type Hysteria struct {
|
|||||||
Port int `yaml:"port,omitempty"`
|
Port int `yaml:"port,omitempty"`
|
||||||
Ports string `yaml:"ports,omitempty"`
|
Ports string `yaml:"ports,omitempty"`
|
||||||
Protocol string `yaml:"protocol,omitempty"`
|
Protocol string `yaml:"protocol,omitempty"`
|
||||||
ObfsProtocol string `yaml:"obfs-protocol,omitempty"`
|
ObfsProtocol string `yaml:"obfs-protocol,omitempty"` // compatible with Stash
|
||||||
Up string `yaml:"up"`
|
Up string `yaml:"up"`
|
||||||
UpSpeed int `yaml:"up-speed,omitempty"`
|
UpSpeed int `yaml:"up-speed,omitempty"` // compatible with Stash
|
||||||
Down string `yaml:"down"`
|
Down string `yaml:"down"`
|
||||||
DownSpeed int `yaml:"down-speed,omitempty"`
|
DownSpeed int `yaml:"down-speed,omitempty"` // compatible with Stash
|
||||||
Auth string `yaml:"auth,omitempty"`
|
Auth string `yaml:"auth,omitempty"`
|
||||||
AuthStringOLD string `yaml:"auth_str,omitempty"`
|
AuthStringOLD string `yaml:"auth_str,omitempty"`
|
||||||
AuthString string `yaml:"auth-str,omitempty"`
|
AuthString string `yaml:"auth-str,omitempty"`
|
||||||
|
@ -103,6 +103,7 @@ type IPTables struct {
|
|||||||
DnsRedirect bool `yaml:"dns-redirect,omitempty" json:"dns-redirect"`
|
DnsRedirect bool `yaml:"dns-redirect,omitempty" json:"dns-redirect"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// EBpf config
|
||||||
type EBpf struct {
|
type EBpf struct {
|
||||||
RedirectToTun []string `yaml:"redirect-to-tun,omitempty" json:"redirect-to-tun"`
|
RedirectToTun []string `yaml:"redirect-to-tun,omitempty" json:"redirect-to-tun"`
|
||||||
AutoRedir []string `yaml:"auto-redir,omitempty" json:"auto-redir"`
|
AutoRedir []string `yaml:"auto-redir,omitempty" json:"auto-redir"`
|
||||||
|
@ -7,7 +7,7 @@ import (
|
|||||||
|
|
||||||
func DecodeBase64(s string) (string, error) {
|
func DecodeBase64(s string) (string, error) {
|
||||||
s = strings.TrimSpace(s)
|
s = strings.TrimSpace(s)
|
||||||
|
// url safe
|
||||||
if strings.Contains(s, "-") || strings.Contains(s, "_") {
|
if strings.Contains(s, "-") || strings.Contains(s, "_") {
|
||||||
s = strings.Replace(s, "-", "+", -1)
|
s = strings.Replace(s, "-", "+", -1)
|
||||||
s = strings.Replace(s, "_", "/", -1)
|
s = strings.Replace(s, "_", "/", -1)
|
||||||
|
@ -1,13 +1,11 @@
|
|||||||
package parser
|
package parser
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sub2clash/constant"
|
||||||
"github.com/nitezs/sub2clash/constant"
|
"sub2clash/model"
|
||||||
"github.com/nitezs/sub2clash/model"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseHysteria(proxy string) (model.Proxy, error) {
|
func ParseHysteria(proxy string) (model.Proxy, error) {
|
||||||
@ -15,31 +13,25 @@ func ParseHysteria(proxy string) (model.Proxy, error) {
|
|||||||
return model.Proxy{}, &ParseError{Type: ErrInvalidPrefix, Raw: proxy}
|
return model.Proxy{}, &ParseError{Type: ErrInvalidPrefix, Raw: proxy}
|
||||||
}
|
}
|
||||||
|
|
||||||
link, err := url.Parse(proxy)
|
proxy = strings.TrimPrefix(proxy, constant.HysteriaPrefix)
|
||||||
if err != nil {
|
urlParts := strings.SplitN(proxy, "?", 2)
|
||||||
|
if len(urlParts) != 2 {
|
||||||
return model.Proxy{}, &ParseError{
|
return model.Proxy{}, &ParseError{
|
||||||
Type: ErrInvalidStruct,
|
Type: ErrInvalidStruct,
|
||||||
Message: "url parse error",
|
Message: "missing character '?' in url",
|
||||||
Raw: proxy,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
server := link.Hostname()
|
|
||||||
if server == "" {
|
|
||||||
return model.Proxy{}, &ParseError{
|
|
||||||
Type: ErrInvalidStruct,
|
|
||||||
Message: "missing server host",
|
|
||||||
Raw: proxy,
|
Raw: proxy,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
portStr := link.Port()
|
serverInfo := strings.SplitN(urlParts[0], ":", 2)
|
||||||
if portStr == "" {
|
if len(serverInfo) != 2 {
|
||||||
return model.Proxy{}, &ParseError{
|
return model.Proxy{}, &ParseError{
|
||||||
Type: ErrInvalidStruct,
|
Type: ErrInvalidStruct,
|
||||||
Message: "missing server port",
|
Message: "missing server host or port",
|
||||||
Raw: proxy,
|
Raw: proxy,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
server, portStr := serverInfo[0], serverInfo[1]
|
||||||
|
|
||||||
port, err := ParsePort(portStr)
|
port, err := ParsePort(portStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -50,9 +42,16 @@ func ParseHysteria(proxy string) (model.Proxy, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
query := link.Query()
|
params, err := url.ParseQuery(urlParts[1])
|
||||||
|
if err != nil {
|
||||||
|
return model.Proxy{}, &ParseError{
|
||||||
|
Type: ErrCannotParseParams,
|
||||||
|
Raw: proxy,
|
||||||
|
Message: err.Error(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
protocol, auth, insecure, upmbps, downmbps, obfs, alpnStr := query.Get("protocol"), query.Get("auth"), query.Get("insecure"), query.Get("upmbps"), query.Get("downmbps"), query.Get("obfs"), query.Get("alpn")
|
protocol, auth, insecure, upmbps, downmbps, obfs, alpnStr := params.Get("protocol"), params.Get("auth"), params.Get("insecure"), params.Get("upmbps"), params.Get("downmbps"), params.Get("obfs"), params.Get("alpn")
|
||||||
insecureBool, err := strconv.ParseBool(insecure)
|
insecureBool, err := strconv.ParseBool(insecure)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
insecureBool = false
|
insecureBool = false
|
||||||
@ -64,11 +63,10 @@ func ParseHysteria(proxy string) (model.Proxy, error) {
|
|||||||
alpn = strings.Split(alpnStr, ",")
|
alpn = strings.Split(alpnStr, ",")
|
||||||
}
|
}
|
||||||
|
|
||||||
remarks := link.Fragment
|
remarks := server + ":" + portStr
|
||||||
if remarks == "" {
|
if params.Get("remarks") != "" {
|
||||||
remarks = fmt.Sprintf("%s:%s", server, portStr)
|
remarks = params.Get("remarks")
|
||||||
}
|
}
|
||||||
remarks = strings.TrimSpace(remarks)
|
|
||||||
|
|
||||||
result := model.Proxy{
|
result := model.Proxy{
|
||||||
Type: "hysteria",
|
Type: "hysteria",
|
||||||
@ -79,7 +77,7 @@ func ParseHysteria(proxy string) (model.Proxy, error) {
|
|||||||
Down: downmbps,
|
Down: downmbps,
|
||||||
Auth: auth,
|
Auth: auth,
|
||||||
Obfs: obfs,
|
Obfs: obfs,
|
||||||
SkipCertVerify: insecureBool,
|
SkipCertVerify: insecure == "1",
|
||||||
Alpn: alpn,
|
Alpn: alpn,
|
||||||
Protocol: protocol,
|
Protocol: protocol,
|
||||||
AllowInsecure: insecureBool,
|
AllowInsecure: insecureBool,
|
||||||
|
@ -1,12 +1,10 @@
|
|||||||
package parser
|
package parser
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sub2clash/constant"
|
||||||
"github.com/nitezs/sub2clash/constant"
|
"sub2clash/model"
|
||||||
"github.com/nitezs/sub2clash/model"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseHysteria2(proxy string) (model.Proxy, error) {
|
func ParseHysteria2(proxy string) (model.Proxy, error) {
|
||||||
@ -15,53 +13,64 @@ func ParseHysteria2(proxy string) (model.Proxy, error) {
|
|||||||
return model.Proxy{}, &ParseError{Type: ErrInvalidPrefix, Raw: proxy}
|
return model.Proxy{}, &ParseError{Type: ErrInvalidPrefix, Raw: proxy}
|
||||||
}
|
}
|
||||||
|
|
||||||
link, err := url.Parse(proxy)
|
proxy = strings.TrimPrefix(proxy, constant.Hysteria2Prefix1)
|
||||||
if err != nil {
|
proxy = strings.TrimPrefix(proxy, constant.Hysteria2Prefix2)
|
||||||
|
urlParts := strings.SplitN(proxy, "@", 2)
|
||||||
|
if len(urlParts) != 2 {
|
||||||
return model.Proxy{}, &ParseError{
|
return model.Proxy{}, &ParseError{
|
||||||
Type: ErrInvalidStruct,
|
Type: ErrInvalidStruct,
|
||||||
Message: "url parse error",
|
Message: "missing character '@' in url",
|
||||||
|
Raw: proxy,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
password := urlParts[0]
|
||||||
|
|
||||||
|
serverInfo := strings.SplitN(urlParts[1], "/?", 2)
|
||||||
|
if len(serverInfo) != 2 {
|
||||||
|
return model.Proxy{}, &ParseError{
|
||||||
|
Type: ErrInvalidStruct,
|
||||||
|
Message: "missing params in url",
|
||||||
|
Raw: proxy,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
paramStr := serverInfo[1]
|
||||||
|
|
||||||
|
serverAndPort := strings.SplitN(serverInfo[0], ":", 2)
|
||||||
|
var server string
|
||||||
|
var portStr string
|
||||||
|
if len(serverAndPort) == 1 {
|
||||||
|
portStr = "443"
|
||||||
|
} else if len(serverAndPort) == 2 {
|
||||||
|
server, portStr = serverAndPort[0], serverAndPort[1]
|
||||||
|
} else {
|
||||||
|
return model.Proxy{}, &ParseError{
|
||||||
|
Type: ErrInvalidStruct,
|
||||||
|
Message: "missing server host or port",
|
||||||
Raw: proxy,
|
Raw: proxy,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
username := link.User.Username()
|
|
||||||
password, exist := link.User.Password()
|
|
||||||
if !exist {
|
|
||||||
password = username
|
|
||||||
}
|
|
||||||
|
|
||||||
query := link.Query()
|
|
||||||
server := link.Hostname()
|
|
||||||
if server == "" {
|
|
||||||
return model.Proxy{}, &ParseError{
|
|
||||||
Type: ErrInvalidStruct,
|
|
||||||
Message: "missing server host",
|
|
||||||
Raw: proxy,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
portStr := link.Port()
|
|
||||||
if portStr == "" {
|
|
||||||
return model.Proxy{}, &ParseError{
|
|
||||||
Type: ErrInvalidStruct,
|
|
||||||
Message: "missing server port",
|
|
||||||
Raw: proxy,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
port, err := ParsePort(portStr)
|
port, err := ParsePort(portStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return model.Proxy{}, &ParseError{
|
return model.Proxy{}, &ParseError{
|
||||||
Type: ErrInvalidPort,
|
Type: ErrInvalidPort,
|
||||||
Raw: portStr,
|
Message: err.Error(),
|
||||||
|
Raw: proxy,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
network, obfs, obfsPassword, pinSHA256, insecure, sni := query.Get("network"), query.Get("obfs"), query.Get("obfs-password"), query.Get("pinSHA256"), query.Get("insecure"), query.Get("sni")
|
|
||||||
enableTLS := pinSHA256 != "" || sni != ""
|
params, err := url.ParseQuery(paramStr)
|
||||||
insecureBool := insecure == "1"
|
if err != nil {
|
||||||
remarks := link.Fragment
|
return model.Proxy{}, &ParseError{
|
||||||
if remarks == "" {
|
Type: ErrCannotParseParams,
|
||||||
remarks = fmt.Sprintf("%s:%s", server, portStr)
|
Raw: proxy,
|
||||||
|
Message: err.Error(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
remarks = strings.TrimSpace(remarks)
|
|
||||||
|
remarks, network, obfs, obfsPassword, pinSHA256, insecure, sni := params.Get("name"), params.Get("network"), params.Get("obfs"), params.Get("obfs-password"), params.Get("pinSHA256"), params.Get("insecure"), params.Get("sni")
|
||||||
|
enableTLS := pinSHA256 != ""
|
||||||
|
insecureBool := insecure == "1"
|
||||||
|
|
||||||
result := model.Proxy{
|
result := model.Proxy{
|
||||||
Type: "hysteria2",
|
Type: "hysteria2",
|
||||||
|
@ -1,98 +1,83 @@
|
|||||||
package parser
|
package parser
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sub2clash/constant"
|
||||||
"github.com/nitezs/sub2clash/constant"
|
"sub2clash/model"
|
||||||
"github.com/nitezs/sub2clash/model"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseShadowsocks(proxy string) (model.Proxy, error) {
|
func ParseShadowsocks(proxy string) (model.Proxy, error) {
|
||||||
if !strings.HasPrefix(proxy, constant.ShadowsocksPrefix) {
|
if !strings.HasPrefix(proxy, constant.ShadowsocksPrefix) {
|
||||||
return model.Proxy{}, &ParseError{Type: ErrInvalidPrefix, Raw: proxy}
|
return model.Proxy{}, &ParseError{Type: ErrInvalidPrefix, Raw: proxy}
|
||||||
}
|
}
|
||||||
if !strings.Contains(proxy, "@") {
|
|
||||||
s := strings.SplitN(proxy, "#", 2)
|
proxy = strings.TrimPrefix(proxy, constant.ShadowsocksPrefix)
|
||||||
d, err := DecodeBase64(strings.TrimPrefix(s[0], "ss://"))
|
urlParts := strings.SplitN(proxy, "@", 2)
|
||||||
|
if len(urlParts) != 2 {
|
||||||
|
return model.Proxy{}, &ParseError{
|
||||||
|
Type: ErrInvalidStruct,
|
||||||
|
Message: "missing character '@' in url",
|
||||||
|
Raw: proxy,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var serverAndPort []string
|
||||||
|
if !strings.Contains(urlParts[0], ":") {
|
||||||
|
decoded, err := DecodeBase64(urlParts[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return model.Proxy{}, &ParseError{
|
return model.Proxy{}, &ParseError{
|
||||||
Type: ErrInvalidStruct,
|
Type: ErrInvalidStruct,
|
||||||
Message: "url parse error",
|
Message: "invalid base64 encoded",
|
||||||
Raw: proxy,
|
Raw: proxy,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(s) == 2 {
|
urlParts[0] = decoded
|
||||||
proxy = "ss://" + d + "#" + s[1]
|
|
||||||
} else {
|
|
||||||
proxy = "ss://" + d
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
link, err := url.Parse(proxy)
|
credentials := strings.SplitN(urlParts[0], ":", 2)
|
||||||
if err != nil {
|
if len(credentials) != 2 {
|
||||||
return model.Proxy{}, &ParseError{
|
return model.Proxy{}, &ParseError{
|
||||||
Type: ErrInvalidStruct,
|
Type: ErrInvalidStruct,
|
||||||
Message: "url parse error",
|
Message: "missing server host or port",
|
||||||
Raw: proxy,
|
Raw: proxy,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
method, password := credentials[0], credentials[1]
|
||||||
|
|
||||||
server := link.Hostname()
|
serverInfo := strings.SplitN(urlParts[1], "#", 2)
|
||||||
if server == "" {
|
serverAndPort = strings.SplitN(serverInfo[0], ":", 2)
|
||||||
|
server, portStr := serverAndPort[0], serverAndPort[1]
|
||||||
|
if len(serverInfo) != 2 {
|
||||||
return model.Proxy{}, &ParseError{
|
return model.Proxy{}, &ParseError{
|
||||||
Type: ErrInvalidStruct,
|
Type: ErrInvalidStruct,
|
||||||
Message: "missing server host",
|
Message: "missing server host or port",
|
||||||
Raw: proxy,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
portStr := link.Port()
|
|
||||||
if portStr == "" {
|
|
||||||
return model.Proxy{}, &ParseError{
|
|
||||||
Type: ErrInvalidStruct,
|
|
||||||
Message: "missing server port",
|
|
||||||
Raw: proxy,
|
Raw: proxy,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
port, err := ParsePort(portStr)
|
port, err := ParsePort(portStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return model.Proxy{}, &ParseError{
|
return model.Proxy{}, &ParseError{
|
||||||
Type: ErrInvalidStruct,
|
Type: ErrInvalidPort,
|
||||||
Raw: proxy,
|
Message: err.Error(),
|
||||||
|
Raw: proxy,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
method := link.User.Username()
|
var remarks string
|
||||||
password, _ := link.User.Password()
|
if len(serverInfo) == 2 {
|
||||||
|
unescape, err := url.QueryUnescape(serverInfo[1])
|
||||||
if password == "" {
|
|
||||||
user, err := DecodeBase64(method)
|
|
||||||
if err == nil {
|
|
||||||
methodAndPass := strings.SplitN(user, ":", 2)
|
|
||||||
if len(methodAndPass) == 2 {
|
|
||||||
method = methodAndPass[0]
|
|
||||||
password = methodAndPass[1]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if isLikelyBase64(password) {
|
|
||||||
password, err = DecodeBase64(password)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return model.Proxy{}, &ParseError{
|
return model.Proxy{}, &ParseError{
|
||||||
Type: ErrInvalidStruct,
|
Type: ErrInvalidStruct,
|
||||||
Message: "password decode error",
|
Message: "cannot unescape remarks",
|
||||||
Raw: proxy,
|
Raw: proxy,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
remarks = strings.TrimSpace(unescape)
|
||||||
|
} else {
|
||||||
|
remarks = strings.TrimSpace(server + ":" + portStr)
|
||||||
}
|
}
|
||||||
|
|
||||||
remarks := link.Fragment
|
|
||||||
if remarks == "" {
|
|
||||||
remarks = fmt.Sprintf("%s:%s", server, portStr)
|
|
||||||
}
|
|
||||||
remarks = strings.TrimSpace(remarks)
|
|
||||||
|
|
||||||
result := model.Proxy{
|
result := model.Proxy{
|
||||||
Type: "ss",
|
Type: "ss",
|
||||||
Cipher: method,
|
Cipher: method,
|
||||||
@ -104,17 +89,3 @@ func ParseShadowsocks(proxy string) (model.Proxy, error) {
|
|||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func isLikelyBase64(s string) bool {
|
|
||||||
if len(s)%4 == 0 && strings.HasSuffix(s, "=") && !strings.Contains(strings.TrimSuffix(s, "="), "=") {
|
|
||||||
s = strings.TrimSuffix(s, "=")
|
|
||||||
chars := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
|
||||||
for _, c := range s {
|
|
||||||
if !strings.ContainsRune(chars, c) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
@ -4,9 +4,8 @@ import (
|
|||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sub2clash/constant"
|
||||||
"github.com/nitezs/sub2clash/constant"
|
"sub2clash/model"
|
||||||
"github.com/nitezs/sub2clash/model"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseShadowsocksR(proxy string) (model.Proxy, error) {
|
func ParseShadowsocksR(proxy string) (model.Proxy, error) {
|
||||||
@ -28,14 +27,7 @@ func ParseShadowsocksR(proxy string) (model.Proxy, error) {
|
|||||||
protocol := parts[2]
|
protocol := parts[2]
|
||||||
method := parts[3]
|
method := parts[3]
|
||||||
obfs := parts[4]
|
obfs := parts[4]
|
||||||
password, err := DecodeBase64(parts[5])
|
password := parts[5]
|
||||||
if err != nil {
|
|
||||||
return model.Proxy{}, &ParseError{
|
|
||||||
Type: ErrInvalidStruct,
|
|
||||||
Raw: proxy,
|
|
||||||
Message: err.Error(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
port, err := ParsePort(parts[1])
|
port, err := ParsePort(parts[1])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return model.Proxy{}, &ParseError{
|
return model.Proxy{}, &ParseError{
|
||||||
|
@ -1,79 +0,0 @@
|
|||||||
package parser
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"github.com/nitezs/sub2clash/constant"
|
|
||||||
"github.com/nitezs/sub2clash/model"
|
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
func ParseSocks(proxy string) (model.Proxy, error) {
|
|
||||||
if !strings.HasPrefix(proxy, constant.SocksPrefix) {
|
|
||||||
return model.Proxy{}, &ParseError{Type: ErrInvalidPrefix, Raw: proxy}
|
|
||||||
}
|
|
||||||
link, err := url.Parse(proxy)
|
|
||||||
if err != nil {
|
|
||||||
return model.Proxy{}, &ParseError{
|
|
||||||
Type: ErrInvalidStruct,
|
|
||||||
Message: "url parse error",
|
|
||||||
Raw: proxy,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
server := link.Hostname()
|
|
||||||
if server == "" {
|
|
||||||
return model.Proxy{}, &ParseError{
|
|
||||||
Type: ErrInvalidStruct,
|
|
||||||
Message: "missing server host",
|
|
||||||
Raw: proxy,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
portStr := link.Port()
|
|
||||||
if portStr == "" {
|
|
||||||
return model.Proxy{}, &ParseError{
|
|
||||||
Type: ErrInvalidStruct,
|
|
||||||
Message: "missing server port",
|
|
||||||
Raw: proxy,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
port, err := ParsePort(portStr)
|
|
||||||
if err != nil {
|
|
||||||
return model.Proxy{}, &ParseError{
|
|
||||||
Type: ErrInvalidPort,
|
|
||||||
Raw: portStr,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
remarks := link.Fragment
|
|
||||||
if remarks == "" {
|
|
||||||
remarks = fmt.Sprintf("%s:%s", server, portStr)
|
|
||||||
}
|
|
||||||
remarks = strings.TrimSpace(remarks)
|
|
||||||
|
|
||||||
encodeStr := link.User.Username()
|
|
||||||
var username, password string
|
|
||||||
if encodeStr != "" {
|
|
||||||
decodeStr, err := DecodeBase64(encodeStr)
|
|
||||||
splitStr := strings.Split(decodeStr, ":")
|
|
||||||
if err != nil {
|
|
||||||
return model.Proxy{}, &ParseError{
|
|
||||||
Type: ErrInvalidStruct,
|
|
||||||
Message: "url parse error",
|
|
||||||
Raw: proxy,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
username = splitStr[0]
|
|
||||||
if len(splitStr) == 2 {
|
|
||||||
password = splitStr[1]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return model.Proxy{
|
|
||||||
Type: "socks5",
|
|
||||||
Name: remarks,
|
|
||||||
Server: server,
|
|
||||||
Port: port,
|
|
||||||
Username: username,
|
|
||||||
Password: password,
|
|
||||||
}, nil
|
|
||||||
|
|
||||||
}
|
|
@ -1,43 +1,55 @@
|
|||||||
package parser
|
package parser
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sub2clash/constant"
|
||||||
"github.com/nitezs/sub2clash/constant"
|
"sub2clash/model"
|
||||||
"github.com/nitezs/sub2clash/model"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ParseTrojan 解析给定的Trojan代理URL并返回Proxy结构。
|
||||||
func ParseTrojan(proxy string) (model.Proxy, error) {
|
func ParseTrojan(proxy string) (model.Proxy, error) {
|
||||||
if !strings.HasPrefix(proxy, constant.TrojanPrefix) {
|
if !strings.HasPrefix(proxy, constant.TrojanPrefix) {
|
||||||
return model.Proxy{}, &ParseError{Type: ErrInvalidPrefix, Raw: proxy}
|
return model.Proxy{}, &ParseError{Type: ErrInvalidPrefix, Raw: proxy}
|
||||||
}
|
}
|
||||||
|
|
||||||
link, err := url.Parse(proxy)
|
proxy = strings.TrimPrefix(proxy, constant.TrojanPrefix)
|
||||||
if err != nil {
|
urlParts := strings.SplitN(proxy, "@", 2)
|
||||||
|
if len(urlParts) != 2 {
|
||||||
return model.Proxy{}, &ParseError{
|
return model.Proxy{}, &ParseError{
|
||||||
Type: ErrInvalidStruct,
|
Type: ErrInvalidStruct,
|
||||||
Message: "url parse error",
|
Message: "missing character '@' in url",
|
||||||
|
Raw: proxy,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
password := strings.TrimSpace(urlParts[0])
|
||||||
|
|
||||||
|
serverInfo := strings.SplitN(urlParts[1], "#", 2)
|
||||||
|
serverAndPortAndParams := strings.SplitN(serverInfo[0], "?", 2)
|
||||||
|
if len(serverAndPortAndParams) != 2 {
|
||||||
|
return model.Proxy{}, &ParseError{
|
||||||
|
Type: ErrInvalidStruct,
|
||||||
|
Message: "missing character '?' in url",
|
||||||
Raw: proxy,
|
Raw: proxy,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
password := link.User.Username()
|
serverAndPort := strings.SplitN(serverAndPortAndParams[0], ":", 2)
|
||||||
server := link.Hostname()
|
if len(serverAndPort) != 2 {
|
||||||
if server == "" {
|
|
||||||
return model.Proxy{}, &ParseError{
|
return model.Proxy{}, &ParseError{
|
||||||
Type: ErrInvalidStruct,
|
Type: ErrInvalidStruct,
|
||||||
Message: "missing server host",
|
Message: "missing server host or port",
|
||||||
Raw: proxy,
|
Raw: proxy,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
portStr := link.Port()
|
server, portStr := serverAndPort[0], serverAndPort[1]
|
||||||
if portStr == "" {
|
|
||||||
|
params, err := url.ParseQuery(serverAndPortAndParams[1])
|
||||||
|
if err != nil {
|
||||||
return model.Proxy{}, &ParseError{
|
return model.Proxy{}, &ParseError{
|
||||||
Type: ErrInvalidStruct,
|
Type: ErrCannotParseParams,
|
||||||
Message: "missing server port",
|
|
||||||
Raw: proxy,
|
Raw: proxy,
|
||||||
|
Message: err.Error(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -50,14 +62,14 @@ func ParseTrojan(proxy string) (model.Proxy, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
remarks := link.Fragment
|
remarks := ""
|
||||||
if remarks == "" {
|
if len(serverInfo) == 2 {
|
||||||
remarks = fmt.Sprintf("%s:%s", server, portStr)
|
remarks, _ = url.QueryUnescape(strings.TrimSpace(serverInfo[1]))
|
||||||
|
} else {
|
||||||
|
remarks = serverAndPort[0]
|
||||||
}
|
}
|
||||||
remarks = strings.TrimSpace(remarks)
|
|
||||||
|
|
||||||
query := link.Query()
|
network, security, alpnStr, sni, pbk, sid, fp, path, host, serviceName := params.Get("type"), params.Get("security"), params.Get("alpn"), params.Get("sni"), params.Get("pbk"), params.Get("sid"), params.Get("fp"), params.Get("path"), params.Get("host"), params.Get("serviceName")
|
||||||
network, security, alpnStr, sni, pbk, sid, fp, path, host, serviceName := query.Get("type"), query.Get("security"), query.Get("alpn"), query.Get("sni"), query.Get("pbk"), query.Get("sid"), query.Get("fp"), query.Get("path"), query.Get("host"), query.Get("serviceName")
|
|
||||||
|
|
||||||
var alpn []string
|
var alpn []string
|
||||||
if strings.Contains(alpnStr, ",") {
|
if strings.Contains(alpnStr, ",") {
|
||||||
@ -66,6 +78,9 @@ func ParseTrojan(proxy string) (model.Proxy, error) {
|
|||||||
alpn = nil
|
alpn = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// enableUTLS := fp != ""
|
||||||
|
|
||||||
|
// 构建Proxy结构体
|
||||||
result := model.Proxy{
|
result := model.Proxy{
|
||||||
Type: "trojan",
|
Type: "trojan",
|
||||||
Server: server,
|
Server: server,
|
||||||
@ -101,6 +116,14 @@ func ParseTrojan(proxy string) (model.Proxy, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// if network == "http" {
|
||||||
|
// // 未查到相关支持文档
|
||||||
|
// }
|
||||||
|
|
||||||
|
// if network == "quic" {
|
||||||
|
// // 未查到相关支持文档
|
||||||
|
// }
|
||||||
|
|
||||||
if network == "grpc" {
|
if network == "grpc" {
|
||||||
result.GrpcOpts = model.GrpcOptions{
|
result.GrpcOpts = model.GrpcOptions{
|
||||||
GrpcServiceName: serviceName,
|
GrpcServiceName: serviceName,
|
||||||
|
@ -1,12 +1,10 @@
|
|||||||
package parser
|
package parser
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sub2clash/constant"
|
||||||
"github.com/nitezs/sub2clash/constant"
|
"sub2clash/model"
|
||||||
"github.com/nitezs/sub2clash/model"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseVless(proxy string) (model.Proxy, error) {
|
func ParseVless(proxy string) (model.Proxy, error) {
|
||||||
@ -14,24 +12,34 @@ func ParseVless(proxy string) (model.Proxy, error) {
|
|||||||
return model.Proxy{}, &ParseError{Type: ErrInvalidPrefix, Raw: proxy}
|
return model.Proxy{}, &ParseError{Type: ErrInvalidPrefix, Raw: proxy}
|
||||||
}
|
}
|
||||||
|
|
||||||
link, err := url.Parse(proxy)
|
urlParts := strings.SplitN(strings.TrimPrefix(proxy, constant.VLESSPrefix), "@", 2)
|
||||||
if err != nil {
|
if len(urlParts) != 2 {
|
||||||
return model.Proxy{}, &ParseError{
|
return model.Proxy{}, &ParseError{
|
||||||
Type: ErrInvalidStruct,
|
Type: ErrInvalidStruct,
|
||||||
Message: "url parse error",
|
Message: "missing character '@' in url",
|
||||||
Raw: proxy,
|
Raw: proxy,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
server := link.Hostname()
|
serverInfo := strings.SplitN(urlParts[1], "#", 2)
|
||||||
if server == "" {
|
serverAndPortAndParams := strings.SplitN(serverInfo[0], "?", 2)
|
||||||
|
if len(serverAndPortAndParams) != 2 {
|
||||||
return model.Proxy{}, &ParseError{
|
return model.Proxy{}, &ParseError{
|
||||||
Type: ErrInvalidStruct,
|
Type: ErrInvalidStruct,
|
||||||
Message: "missing server host",
|
Message: "missing character '?' in url",
|
||||||
Raw: proxy,
|
Raw: proxy,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
portStr := link.Port()
|
|
||||||
|
serverAndPort := strings.SplitN(serverAndPortAndParams[0], ":", 2)
|
||||||
|
if len(serverAndPort) != 2 {
|
||||||
|
return model.Proxy{}, &ParseError{
|
||||||
|
Type: ErrInvalidStruct,
|
||||||
|
Message: "missing server host or port",
|
||||||
|
Raw: proxy,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
server, portStr := serverAndPort[0], serverAndPort[1]
|
||||||
port, err := ParsePort(portStr)
|
port, err := ParsePort(portStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return model.Proxy{}, &ParseError{
|
return model.Proxy{}, &ParseError{
|
||||||
@ -41,10 +49,40 @@ func ParseVless(proxy string) (model.Proxy, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
query := link.Query()
|
params, err := url.ParseQuery(serverAndPortAndParams[1])
|
||||||
uuid := link.User.Username()
|
if err != nil {
|
||||||
flow, security, alpnStr, sni, insecure, fp, pbk, sid, path, host, serviceName, _type := query.Get("flow"), query.Get("security"), query.Get("alpn"), query.Get("sni"), query.Get("allowInsecure"), query.Get("fp"), query.Get("pbk"), query.Get("sid"), query.Get("path"), query.Get("host"), query.Get("serviceName"), query.Get("type")
|
return model.Proxy{}, &ParseError{
|
||||||
|
Type: ErrCannotParseParams,
|
||||||
|
Raw: proxy,
|
||||||
|
Message: err.Error(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
remarks := ""
|
||||||
|
if len(serverInfo) == 2 {
|
||||||
|
if strings.Contains(serverInfo[1], "|") {
|
||||||
|
remarks = strings.SplitN(serverInfo[1], "|", 2)[1]
|
||||||
|
} else {
|
||||||
|
remarks, err = url.QueryUnescape(serverInfo[1])
|
||||||
|
if err != nil {
|
||||||
|
return model.Proxy{}, &ParseError{
|
||||||
|
Type: ErrCannotParseParams,
|
||||||
|
Raw: proxy,
|
||||||
|
Message: err.Error(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
remarks, err = url.QueryUnescape(server)
|
||||||
|
if err != nil {
|
||||||
|
return model.Proxy{}, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
uuid := strings.TrimSpace(urlParts[0])
|
||||||
|
flow, security, alpnStr, sni, insecure, fp, pbk, sid, path, host, serviceName, _type := params.Get("flow"), params.Get("security"), params.Get("alpn"), params.Get("sni"), params.Get("allowInsecure"), params.Get("fp"), params.Get("pbk"), params.Get("sid"), params.Get("path"), params.Get("host"), params.Get("serviceName"), params.Get("type")
|
||||||
|
|
||||||
|
// enableUTLS := fp != ""
|
||||||
insecureBool := insecure == "1"
|
insecureBool := insecure == "1"
|
||||||
var alpn []string
|
var alpn []string
|
||||||
if strings.Contains(alpnStr, ",") {
|
if strings.Contains(alpnStr, ",") {
|
||||||
@ -52,11 +90,6 @@ func ParseVless(proxy string) (model.Proxy, error) {
|
|||||||
} else {
|
} else {
|
||||||
alpn = nil
|
alpn = nil
|
||||||
}
|
}
|
||||||
remarks := link.Fragment
|
|
||||||
if remarks == "" {
|
|
||||||
remarks = fmt.Sprintf("%s:%s", server, portStr)
|
|
||||||
}
|
|
||||||
remarks = strings.TrimSpace(remarks)
|
|
||||||
|
|
||||||
result := model.Proxy{
|
result := model.Proxy{
|
||||||
Type: "vless",
|
Type: "vless",
|
||||||
@ -72,7 +105,7 @@ func ParseVless(proxy string) (model.Proxy, error) {
|
|||||||
result.Alpn = alpn
|
result.Alpn = alpn
|
||||||
result.Sni = sni
|
result.Sni = sni
|
||||||
result.AllowInsecure = insecureBool
|
result.AllowInsecure = insecureBool
|
||||||
result.ClientFingerprint = fp
|
result.Fingerprint = fp
|
||||||
}
|
}
|
||||||
|
|
||||||
if security == "reality" {
|
if security == "reality" {
|
||||||
@ -82,7 +115,6 @@ func ParseVless(proxy string) (model.Proxy, error) {
|
|||||||
PublicKey: pbk,
|
PublicKey: pbk,
|
||||||
ShortID: sid,
|
ShortID: sid,
|
||||||
}
|
}
|
||||||
result.ClientFingerprint = fp
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if _type == "ws" {
|
if _type == "ws" {
|
||||||
@ -96,6 +128,10 @@ func ParseVless(proxy string) (model.Proxy, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// if _type == "quic" {
|
||||||
|
// // 未查到相关支持文档
|
||||||
|
// }
|
||||||
|
|
||||||
if _type == "grpc" {
|
if _type == "grpc" {
|
||||||
result.Network = "grpc"
|
result.Network = "grpc"
|
||||||
result.GrpcOpts = model.GrpcOptions{
|
result.GrpcOpts = model.GrpcOptions{
|
||||||
@ -104,11 +140,6 @@ func ParseVless(proxy string) (model.Proxy, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if _type == "http" {
|
if _type == "http" {
|
||||||
result.HTTPOpts = model.HTTPOptions{}
|
|
||||||
result.HTTPOpts.Headers = map[string][]string{}
|
|
||||||
|
|
||||||
result.HTTPOpts.Path = strings.Split(path, ",")
|
|
||||||
|
|
||||||
hosts, err := url.QueryUnescape(host)
|
hosts, err := url.QueryUnescape(host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return model.Proxy{}, &ParseError{
|
return model.Proxy{}, &ParseError{
|
||||||
@ -118,9 +149,10 @@ func ParseVless(proxy string) (model.Proxy, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
result.Network = "http"
|
result.Network = "http"
|
||||||
if hosts != "" {
|
result.HTTPOpts = model.HTTPOptions{
|
||||||
result.HTTPOpts.Headers["host"] = strings.Split(host, ",")
|
Headers: map[string][]string{"Host": strings.Split(hosts, ",")},
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
|
@ -5,9 +5,8 @@ import (
|
|||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sub2clash/constant"
|
||||||
"github.com/nitezs/sub2clash/constant"
|
"sub2clash/model"
|
||||||
"github.com/nitezs/sub2clash/model"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseVmess(proxy string) (model.Proxy, error) {
|
func ParseVmess(proxy string) (model.Proxy, error) {
|
||||||
@ -101,6 +100,10 @@ func ParseVmess(proxy string) (model.Proxy, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// if vmess.Net == "quic" {
|
||||||
|
// // 未查到相关支持文档
|
||||||
|
// }
|
||||||
|
|
||||||
if vmess.Net == "grpc" {
|
if vmess.Net == "grpc" {
|
||||||
result.GrpcOpts = model.GrpcOptions{
|
result.GrpcOpts = model.GrpcOptions{
|
||||||
GrpcServiceName: vmess.Path,
|
GrpcServiceName: vmess.Path,
|
||||||
|
@ -3,11 +3,10 @@ package validator
|
|||||||
type ShortLinkGenValidator struct {
|
type ShortLinkGenValidator struct {
|
||||||
Url string `form:"url" binding:"required"`
|
Url string `form:"url" binding:"required"`
|
||||||
Password string `form:"password"`
|
Password string `form:"password"`
|
||||||
CustomID string `form:"customId"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type GetUrlValidator struct {
|
type GetUrlValidator struct {
|
||||||
Hash string `form:"hash" binding:"required"`
|
Hash string `form:"hash" binding:"required"` // Hash: 短链接
|
||||||
Password string `form:"password"`
|
Password string `form:"password"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -31,7 +31,6 @@ type SubValidator struct {
|
|||||||
ReplaceTo []string `form:"-" binding:""`
|
ReplaceTo []string `form:"-" binding:""`
|
||||||
NodeListMode bool `form:"nodeList,default=false" binding:""`
|
NodeListMode bool `form:"nodeList,default=false" binding:""`
|
||||||
IgnoreCountryGrooup bool `form:"ignoreCountryGroup,default=false" binding:""`
|
IgnoreCountryGrooup bool `form:"ignoreCountryGroup,default=false" binding:""`
|
||||||
UserAgent string `form:"userAgent" binding:""`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type RuleProviderStruct struct {
|
type RuleProviderStruct struct {
|
||||||
@ -111,7 +110,7 @@ func ParseQuery(c *gin.Context) (SubValidator, error) {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
// 校验 Rule-Provider 是否有重名
|
||||||
names := make(map[string]bool)
|
names := make(map[string]bool)
|
||||||
for _, ruleProvider := range query.RuleProviders {
|
for _, ruleProvider := range query.RuleProviders {
|
||||||
if _, ok := names[ruleProvider.Name]; ok {
|
if _, ok := names[ruleProvider.Name]; ok {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user