mirror of
https://github.com/bestnite/sub2clash.git
synced 2025-07-04 11:52:34 +08:00
Compare commits
28 Commits
Author | SHA1 | Date | |
---|---|---|---|
773424cdb0 | |||
edfd70a77d | |||
6f075ea44e | |||
6a5cfd35c9 | |||
ad7d2b98f6 | |||
38352d4cd7 | |||
fc21e35465 | |||
159a3562d4 | |||
34b85c8d63 | |||
3546396e3d | |||
be9df16b61 | |||
67e4121fa6 | |||
c1e9099156 | |||
429788a19f | |||
2339b7d256 | |||
06c9858866 | |||
8d06ab3175 | |||
f166c6a54a | |||
c0e6b62625 | |||
354379b12a | |||
4f4a633035 | |||
be9bdd269e | |||
6b08b2cb86 | |||
38dbea4a2a | |||
1788541e04 | |||
d38d5bcb70 | |||
918521682c | |||
3318f5f2db |
@ -5,3 +5,4 @@ REQUEST_RETRY_TIMES=3
|
||||
REQUEST_MAX_FILE_SIZE=1048576
|
||||
CACHE_EXPIRE=300
|
||||
LOG_LEVEL=info
|
||||
BASE_PATH=/
|
6
.github/workflows/docker.yml
vendored
6
.github/workflows/docker.yml
vendored
@ -47,6 +47,9 @@ jobs:
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
build-args: |
|
||||
dev=true
|
||||
version=${{ github.sha }}
|
||||
push: true
|
||||
tags: ghcr.io/${{ github.repository }}:${{ steps.set_tag.outputs.tag }}
|
||||
|
||||
@ -56,6 +59,9 @@ jobs:
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
build-args: |
|
||||
dev=false
|
||||
version=${{ steps.set_tag.outputs.tag }}
|
||||
push: true
|
||||
tags: |
|
||||
ghcr.io/${{ github.repository }}:${{ steps.set_tag.outputs.tag }}
|
||||
|
48
.github/workflows/go.yml
vendored
48
.github/workflows/go.yml
vendored
@ -23,12 +23,10 @@ jobs:
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
LDFLAGS="-s -w"
|
||||
LDFLAGS="-s -w -X config.Version=${{ github.ref_name }}"
|
||||
|
||||
# Linux
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags="$LDFLAGS" -o output/sub2clash-linux-386 main.go
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="$LDFLAGS" -o output/sub2clash-linux-amd64 main.go
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm go build -ldflags="$LDFLAGS" -o output/sub2clash-linux-arm main.go
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="$LDFLAGS" -o output/sub2clash-linux-arm64 main.go
|
||||
|
||||
# Darwin
|
||||
@ -36,9 +34,7 @@ jobs:
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags="$LDFLAGS" -o output/sub2clash-darwin-arm64 main.go
|
||||
|
||||
# Windows
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags="$LDFLAGS" -o output/sub2clash-windows-386.exe main.go
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="$LDFLAGS" -o output/sub2clash-windows-amd64.exe main.go
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=arm go build -ldflags="$LDFLAGS" -o output/sub2clash-windows-arm.exe main.go
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=arm64 go build -ldflags="$LDFLAGS" -o output/sub2clash-windows-arm64.exe main.go
|
||||
|
||||
- name: Create Release
|
||||
@ -52,16 +48,6 @@ jobs:
|
||||
draft: false
|
||||
prerelease: false
|
||||
|
||||
- name: Upload Release Asset (Linux 386)
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
asset_path: ./output/sub2clash-linux-386
|
||||
asset_name: sub2clash-linux-386
|
||||
asset_content_type: application/octet-stream
|
||||
|
||||
- name: Upload Release Asset (Linux amd64)
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
@ -72,16 +58,6 @@ jobs:
|
||||
asset_name: sub2clash-linux-amd64
|
||||
asset_content_type: application/octet-stream
|
||||
|
||||
- name: Upload Release Asset (Linux arm)
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
asset_path: ./output/sub2clash-linux-arm
|
||||
asset_name: sub2clash-linux-arm
|
||||
asset_content_type: application/octet-stream
|
||||
|
||||
- name: Upload Release Asset (Linux arm64)
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
@ -112,16 +88,6 @@ jobs:
|
||||
asset_name: sub2clash-darwin-arm64
|
||||
asset_content_type: application/octet-stream
|
||||
|
||||
- name: Upload Release Asset (Windows 386)
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ steps.create_release.outputs.up
|
||||
asset_path: ./output/sub2clash-windows-386.exe
|
||||
asset_name: sub2clash-windows-386.exe
|
||||
asset_content_type: application/octet-stream
|
||||
|
||||
- name: Upload Release Asset (Windows amd64)
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
@ -132,22 +98,12 @@ jobs:
|
||||
asset_name: sub2clash-windows-amd64.exe
|
||||
asset_content_type: application/octet-stream
|
||||
|
||||
- name: Upload Release Asset (Windows arm)
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
asset_path: ./output/sub2clash-windows-arm.exe
|
||||
asset_name: sub2clash-windows-arm.exe
|
||||
asset_content_type: application/octet-stream
|
||||
|
||||
- name: Upload Release Asset (Windows arm64)
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ steps.create_release.outputs.up
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
asset_path: ./output/sub2clash-windows-arm64.exe
|
||||
asset_name: sub2clash-windows-arm64.exe
|
||||
asset_content_type: application/octet-stream
|
||||
|
3
.gitignore
vendored
3
.gitignore
vendored
@ -3,4 +3,5 @@ dist
|
||||
subs
|
||||
test
|
||||
logs
|
||||
dist/
|
||||
sub2clash.db
|
||||
.env
|
||||
|
@ -1,6 +1,6 @@
|
||||
before:
|
||||
hooks:
|
||||
- go mod tidy
|
||||
#before:
|
||||
# hooks:
|
||||
# - go mod tidy
|
||||
builds:
|
||||
- env:
|
||||
- CGO_ENABLED=0
|
||||
@ -10,10 +10,8 @@ builds:
|
||||
- darwin
|
||||
goarch:
|
||||
- amd64
|
||||
- arm
|
||||
- arm64
|
||||
- 386
|
||||
ldflags:
|
||||
- -s -w
|
||||
- -s -w -X sub2clash/config.Version={{ .Version }}
|
||||
no_unique_dist_dir: true
|
||||
binary: "{{ .ProjectName }}-{{ .Os }}-{{ .Arch }}"
|
37
API_README.md
Normal file
37
API_README.md
Normal file
@ -0,0 +1,37 @@
|
||||
# `/clash`, `/meta`
|
||||
|
||||
获取 Clash/Clash.Meta 配置链接
|
||||
|
||||
| Query 参数 | 类型 | 是否必须 | 默认值 | 说明 |
|
||||
|--------------|--------|-------------------|-----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| sub | string | sub/proxy 至少有一项存在 | - | 订阅链接,可以在链接结尾加上`#名称`,来给订阅中的节点加上统一前缀(可以输入多个,用 `,` 分隔) |
|
||||
| proxy | string | sub/proxy 至少有一项存在 | - | 节点分享链接(可以输入多个,用 `,` 分隔) |
|
||||
| refresh | bool | 否 | `false` | 强制刷新配置(默认缓存 5 分钟) |
|
||||
| template | string | 否 | - | 外部模板链接或内部模板名称 |
|
||||
| ruleProvider | string | 否 | - | 格式 `[Behavior,Url,Group,Prepend,Name],[Behavior,Url,Group,Prepend,Name]...`,其中 `Group` 是该规则集使用的策略组名,`Prepend` 为 bool 类型,如果为 `true` 规则将被添加到规则列表顶部,否则添加到规则列表底部(会调整到MATCH规则之前) |
|
||||
| rule | string | 否 | - | 格式 `[Rule,Prepend],[Rule,Prepend]...`,其中 `Prepend` 为 bool 类型,如果为 `true` 规则将被添加到规则列表顶部,否则添加到规则列表底部(会调整到MATCH规则之前) |
|
||||
| autoTest | bool | 否 | `false` | 国家策略组是否自动测速 |
|
||||
| lazy | bool | 否 | `false` | 自动测速是否启用 lazy |
|
||||
| sort | string | 否 | `nameasc` | 国家策略组排序策略,可选值 `nameasc`、`namedesc`、`sizeasc`、`sizedesc` |
|
||||
| replace | string | 否 | - | 通过正则表达式重命名节点,格式 `[<ReplaceKey>,<ReplaceTo>],[<ReplaceKey>,<ReplaceTo>]...` |
|
||||
| remove | string | 否 | - | 通过正则表达式删除节点 |
|
||||
| nodeList | bool | 否 | `false` | 只输出节点 | |
|
||||
|
||||
# `/short`
|
||||
|
||||
获取短链,Content-Type 为 `application/json`
|
||||
具体参考使用可以参考 [api\templates\index.html](api/static/index.html)
|
||||
|
||||
| Body 参数 | 类型 | 是否必须 | 默认值 | 说明 |
|
||||
|----------|--------|------|-----|------------------|
|
||||
| url | string | 是 | - | 需要转换的 Query 参数部分 |
|
||||
| password | string | 否 | - | 短链密码 |
|
||||
|
||||
# `/s/:hash`
|
||||
|
||||
短链跳转
|
||||
`hash` 为动态路由参数,可以通过 `/short` 接口获取
|
||||
|
||||
| Query 参数 | 类型 | 是否必须 | 默认值 | 说明 |
|
||||
|----------|--------|------|-----|------|
|
||||
| password | string | 否 | - | 短链密码 |
|
@ -9,8 +9,12 @@ WORKDIR /app
|
||||
COPY . .
|
||||
RUN go mod download
|
||||
|
||||
# 获取参数
|
||||
ARG version
|
||||
ARG dev
|
||||
|
||||
# 使用 -ldflags 参数进行编译
|
||||
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o sub2clash main.go
|
||||
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w -X sub2clash/config.Version=${version} -X sub2clash/config.Dev=${dev}" -o sub2clash main.go
|
||||
|
||||
FROM alpine:latest
|
||||
|
||||
|
30
README.md
30
README.md
@ -26,7 +26,7 @@
|
||||
可以通过编辑 .env 文件来修改默认配置,docker 直接添加环境变量
|
||||
|
||||
| 变量名 | 说明 | 默认值 |
|
||||
|-----------------------|----------------------------------------|-----------------------|
|
||||
|-----------------------|-----------------------------------------------------------|-----------------------|
|
||||
| PORT | 端口 | `8011` |
|
||||
| META_TEMPLATE | meta 模板文件名 | `template_meta.yaml` |
|
||||
| CLASH_TEMPLATE | clash 模板文件名 | `template_clash.yaml` |
|
||||
@ -34,26 +34,22 @@
|
||||
| REQUEST_MAX_FILE_SIZE | Get 请求订阅文件最大大小(byte) | `1048576` |
|
||||
| CACHE_EXPIRE | 订阅缓存时间(秒) | `300` |
|
||||
| LOG_LEVEL | 日志等级,可选值 `debug`,`info`,`warn`,`error` | `info` |
|
||||
| SHORT_LINK_LENGTH | 短链长度 | `6` |
|
||||
|
||||
### API
|
||||
|
||||
#### `/clash`, `/meta`
|
||||
[API文档](./API_README.md)
|
||||
|
||||
获取 Clash/Clash.Meta 配置链接
|
||||
### 模板
|
||||
|
||||
| Query 参数 | 类型 | 是否必须 | 默认值 | 说明 |
|
||||
|--------------|--------|-------------------|-----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| sub | string | sub/proxy 至少有一项存在 | - | 订阅链接(可以输入多个,用 `,` 分隔) |
|
||||
| proxy | string | sub/proxy 至少有一项存在 | - | 节点分享链接(可以输入多个,用 `,` 分隔) |
|
||||
| refresh | bool | 否 | `false` | 强制刷新配置(默认缓存 5 分钟) |
|
||||
| template | string | 否 | - | 外部模板链接或内部模板名称 |
|
||||
| ruleProvider | string | 否 | - | 格式 `[Behavior,Url,Group,Prepend,Name],[Behavior,Url,Group,Prepend,Name]...`,其中 `Group` 是该规则集所走的策略组名,`Prepend` 为 bool 类型,如果为 `true` 规则将被添加到规则列表顶部,否则添加到规则列表底部(会调整到MATCH规则之前) |
|
||||
| rule | string | 否 | - | 格式 `[Rule,Prepend],[Rule,Prepend]...`,其中 `Prepend` 为 bool 类型,如果为 `true` 规则将被添加到规则列表顶部,否则添加到规则列表底部(会调整到MATCH规则之前) |
|
||||
| autoTest | bool | 否 | `false` | 指定国家策略组是否自动测速 |
|
||||
| lazy | bool | 否 | `false` | 自动测速是否启用 lazy |
|
||||
| sort | string | 否 | `nameasc` | 国家策略组排序策略,可选值 `nameasc`、`namedesc`、`sizeasc`、`sizedesc` |
|
||||
可以通过变量自定义模板中的策略组代理节点
|
||||
解释的不太清楚,可以参考下方默认模板
|
||||
|
||||
## 默认模板
|
||||
- `<all>` 为添加所有节点
|
||||
- `<countries>` 为添加所有国家策略组
|
||||
- `<地区二位字母代码>` 为添加指定地区所有节点,例如 `<hk>` 将添加所有香港节点
|
||||
|
||||
#### 默认模板
|
||||
|
||||
- [Clash](./templates/template_clash.yaml)
|
||||
- [Clash.Meta](./templates/template_meta.yaml)
|
||||
@ -61,7 +57,3 @@
|
||||
## 已知问题
|
||||
|
||||
[代理链接解析](./parser)还没有经过严格测试,可能会出现解析错误的情况,如果出现问题请提交 issue
|
||||
|
||||
## TODO
|
||||
|
||||
- [ ] 可视化面板
|
@ -5,6 +5,7 @@ import (
|
||||
"gopkg.in/yaml.v3"
|
||||
"net/http"
|
||||
"sub2clash/config"
|
||||
"sub2clash/model"
|
||||
"sub2clash/validator"
|
||||
)
|
||||
|
||||
@ -15,12 +16,23 @@ func SubmodHandler(c *gin.Context) {
|
||||
c.String(http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
sub, err := BuildSub(query, config.Default.ClashTemplate)
|
||||
sub, err := BuildSub(model.Clash, query, config.Default.ClashTemplate)
|
||||
if err != nil {
|
||||
c.String(http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
// 输出
|
||||
if query.NodeListMode {
|
||||
nodelist := model.NodeList{}
|
||||
nodelist.Proxies = sub.Proxies
|
||||
marshal, err := yaml.Marshal(nodelist)
|
||||
if err != nil {
|
||||
c.String(http.StatusInternalServerError, "YAML序列化失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
c.String(http.StatusOK, string(marshal))
|
||||
return
|
||||
}
|
||||
marshal, err := yaml.Marshal(sub)
|
||||
if err != nil {
|
||||
c.String(http.StatusInternalServerError, "YAML序列化失败: "+err.Error())
|
||||
|
@ -1,25 +1,29 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"go.uber.org/zap"
|
||||
"gopkg.in/yaml.v3"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sub2clash/logger"
|
||||
"sub2clash/model"
|
||||
"sub2clash/parser"
|
||||
"sub2clash/utils"
|
||||
"sub2clash/validator"
|
||||
)
|
||||
|
||||
func BuildSub(query validator.SubQuery, template string) (
|
||||
func BuildSub(clashType model.ClashType, query validator.SubValidator, template string) (
|
||||
*model.Subscription, error,
|
||||
) {
|
||||
// 定义变量
|
||||
var temp *model.Subscription
|
||||
var sub *model.Subscription
|
||||
var temp = &model.Subscription{}
|
||||
var sub = &model.Subscription{}
|
||||
var err error
|
||||
var templateBytes []byte
|
||||
// 加载模板
|
||||
@ -30,51 +34,167 @@ func BuildSub(query validator.SubQuery, template string) (
|
||||
if err != nil {
|
||||
templateBytes, err = utils.LoadTemplate(template)
|
||||
if err != nil {
|
||||
logger.Logger.Debug(
|
||||
"load template failed", zap.String("template", template), zap.Error(err),
|
||||
)
|
||||
return nil, errors.New("加载模板失败: " + err.Error())
|
||||
}
|
||||
} else {
|
||||
templateBytes, err = utils.LoadSubscription(template, query.Refresh)
|
||||
if err != nil {
|
||||
logger.Logger.Debug(
|
||||
"load template failed", zap.String("template", template), zap.Error(err),
|
||||
)
|
||||
return nil, errors.New("加载模板失败: " + err.Error())
|
||||
}
|
||||
}
|
||||
// 解析模板
|
||||
err = yaml.Unmarshal(templateBytes, &temp)
|
||||
if err != nil {
|
||||
logger.Logger.Debug("parse template failed", zap.Error(err))
|
||||
return nil, errors.New("解析模板失败: " + err.Error())
|
||||
}
|
||||
var proxyList []model.Proxy
|
||||
// 加载订阅
|
||||
for i := range query.Subs {
|
||||
data, err := utils.LoadSubscription(query.Subs[i], query.Refresh)
|
||||
subName := ""
|
||||
if strings.Contains(query.Subs[i], "#") {
|
||||
subName = query.Subs[i][strings.LastIndex(query.Subs[i], "#")+1:]
|
||||
}
|
||||
if err != nil {
|
||||
logger.Logger.Debug(
|
||||
"load subscription failed", zap.String("url", query.Subs[i]), zap.Error(err),
|
||||
)
|
||||
return nil, errors.New("加载订阅失败: " + err.Error())
|
||||
}
|
||||
// 解析订阅
|
||||
var proxyList []model.Proxy
|
||||
err = yaml.Unmarshal(data, &sub)
|
||||
newProxies := make([]model.Proxy, 0)
|
||||
if err != nil {
|
||||
reg, _ := regexp.Compile("(ssr|ss|vmess|trojan|http|https)://")
|
||||
reg, _ := regexp.Compile("(ssr|ss|vmess|trojan|vless)://")
|
||||
if reg.Match(data) {
|
||||
proxyList = utils.ParseProxy(strings.Split(string(data), "\n")...)
|
||||
p := utils.ParseProxy(strings.Split(string(data), "\n")...)
|
||||
newProxies = p
|
||||
} else {
|
||||
// 如果无法直接解析,尝试Base64解码
|
||||
base64, err := parser.DecodeBase64(string(data))
|
||||
if err != nil {
|
||||
logger.Logger.Debug(
|
||||
"parse subscription failed", zap.String("url", query.Subs[i]),
|
||||
zap.String("data", string(data)),
|
||||
zap.Error(err),
|
||||
)
|
||||
return nil, errors.New("加载订阅失败: " + err.Error())
|
||||
}
|
||||
proxyList = utils.ParseProxy(strings.Split(base64, "\n")...)
|
||||
p := utils.ParseProxy(strings.Split(base64, "\n")...)
|
||||
newProxies = p
|
||||
}
|
||||
} else {
|
||||
proxyList = sub.Proxies
|
||||
newProxies = sub.Proxies
|
||||
}
|
||||
utils.AddProxy(sub, query.AutoTest, query.Lazy, query.Sort, proxyList...)
|
||||
if subName != "" {
|
||||
for i := range newProxies {
|
||||
newProxies[i].SubName = subName
|
||||
}
|
||||
// 处理自定义代理
|
||||
utils.AddProxy(
|
||||
sub, query.AutoTest, query.Lazy, query.Sort,
|
||||
utils.ParseProxy(query.Proxies...)...,
|
||||
}
|
||||
proxyList = append(proxyList, newProxies...)
|
||||
}
|
||||
// 添加自定义节点
|
||||
if len(query.Proxies) != 0 {
|
||||
proxyList = append(proxyList, utils.ParseProxy(query.Proxies...)...)
|
||||
}
|
||||
// 给节点添加订阅名称
|
||||
for i := range proxyList {
|
||||
if proxyList[i].SubName != "" {
|
||||
proxyList[i].Name = strings.TrimSpace(proxyList[i].SubName) + " " + strings.TrimSpace(proxyList[i].Name)
|
||||
}
|
||||
}
|
||||
// 去掉配置相同的节点
|
||||
proxies := make(map[string]*model.Proxy)
|
||||
newProxies := make([]model.Proxy, 0, len(proxyList))
|
||||
for i := range proxyList {
|
||||
key := proxyList[i].Server + ":" + strconv.Itoa(proxyList[i].Port) + ":" + proxyList[i].Type
|
||||
if _, exist := proxies[key]; !exist {
|
||||
proxies[key] = &proxyList[i]
|
||||
newProxies = append(newProxies, proxyList[i])
|
||||
}
|
||||
}
|
||||
proxyList = newProxies
|
||||
// 删除节点
|
||||
if strings.TrimSpace(query.Remove) != "" {
|
||||
newProxyList := make([]model.Proxy, 0, len(proxyList))
|
||||
for i := range proxyList {
|
||||
removeReg, err := regexp.Compile(query.Remove)
|
||||
if err != nil {
|
||||
logger.Logger.Debug("remove regexp compile failed", zap.Error(err))
|
||||
return nil, errors.New("remove 参数非法: " + err.Error())
|
||||
}
|
||||
// 删除匹配到的节点
|
||||
if removeReg.MatchString(proxyList[i].Name) {
|
||||
continue // 如果匹配到要删除的元素,跳过该元素,不添加到新切片中
|
||||
}
|
||||
newProxyList = append(newProxyList, proxyList[i]) // 将要保留的元素添加到新切片中
|
||||
}
|
||||
proxyList = newProxyList
|
||||
}
|
||||
// 重命名
|
||||
if len(query.ReplaceKeys) != 0 {
|
||||
// 创建重命名正则表达式
|
||||
replaceRegs := make([]*regexp.Regexp, 0, len(query.ReplaceKeys))
|
||||
for _, v := range query.ReplaceKeys {
|
||||
replaceReg, err := regexp.Compile(v)
|
||||
if err != nil {
|
||||
logger.Logger.Debug("replace regexp compile failed", zap.Error(err))
|
||||
return nil, errors.New("replace 参数非法: " + err.Error())
|
||||
}
|
||||
replaceRegs = append(replaceRegs, replaceReg)
|
||||
}
|
||||
for i := range proxyList {
|
||||
// 重命名匹配到的节点
|
||||
for j, v := range replaceRegs {
|
||||
if err != nil {
|
||||
logger.Logger.Debug("replace regexp compile failed", zap.Error(err))
|
||||
return nil, errors.New("replaceName 参数非法: " + err.Error())
|
||||
}
|
||||
if v.MatchString(proxyList[i].Name) {
|
||||
proxyList[i].Name = v.ReplaceAllString(
|
||||
proxyList[i].Name, query.ReplaceTo[j],
|
||||
)
|
||||
MergeSubAndTemplate(temp, sub)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 重名检测
|
||||
names := make(map[string]int)
|
||||
for i := range proxyList {
|
||||
if _, exist := names[proxyList[i].Name]; exist {
|
||||
proxyList[i].Name = proxyList[i].Name + " " + strconv.Itoa(names[proxyList[i].Name])
|
||||
}
|
||||
names[proxyList[i].Name] = names[proxyList[i].Name] + 1
|
||||
}
|
||||
// trim
|
||||
for i := range proxyList {
|
||||
proxyList[i].Name = strings.TrimSpace(proxyList[i].Name)
|
||||
}
|
||||
// 将新增节点都添加到临时变量 t 中,防止策略组排序错乱
|
||||
var t = &model.Subscription{}
|
||||
utils.AddProxy(t, query.AutoTest, query.Lazy, clashType, proxyList...)
|
||||
// 排序策略组
|
||||
switch query.Sort {
|
||||
case "sizeasc":
|
||||
sort.Sort(model.ProxyGroupsSortBySize(t.ProxyGroups))
|
||||
case "sizedesc":
|
||||
sort.Sort(sort.Reverse(model.ProxyGroupsSortBySize(t.ProxyGroups)))
|
||||
case "nameasc":
|
||||
sort.Sort(model.ProxyGroupsSortByName(t.ProxyGroups))
|
||||
case "namedesc":
|
||||
sort.Sort(sort.Reverse(model.ProxyGroupsSortByName(t.ProxyGroups)))
|
||||
default:
|
||||
sort.Sort(model.ProxyGroupsSortByName(t.ProxyGroups))
|
||||
}
|
||||
// 合并新节点和模板
|
||||
MergeSubAndTemplate(temp, t)
|
||||
// 处理自定义规则
|
||||
for _, v := range query.Rules {
|
||||
if v.Prepend {
|
||||
@ -85,7 +205,7 @@ func BuildSub(query validator.SubQuery, template string) (
|
||||
}
|
||||
// 处理自定义 ruleProvider
|
||||
for _, v := range query.RuleProviders {
|
||||
hash := md5.Sum([]byte(v.Url))
|
||||
hash := sha256.Sum224([]byte(v.Url))
|
||||
name := hex.EncodeToString(hash[:])
|
||||
provider := model.RuleProvider{
|
||||
Type: "http",
|
||||
@ -118,28 +238,45 @@ func MergeSubAndTemplate(temp *model.Subscription, sub *model.Subscription) {
|
||||
)
|
||||
}
|
||||
}
|
||||
var proxyNames []string
|
||||
for _, proxy := range sub.Proxies {
|
||||
proxyNames = append(proxyNames, proxy.Name)
|
||||
}
|
||||
// 将订阅中的节点添加到模板中
|
||||
temp.Proxies = append(temp.Proxies, sub.Proxies...)
|
||||
// 将订阅中的策略组添加到模板中
|
||||
skipGroups := []string{"全球直连", "广告拦截", "手动切换"}
|
||||
for i := range temp.ProxyGroups {
|
||||
skip := false
|
||||
for _, v := range skipGroups {
|
||||
if strings.Contains(temp.ProxyGroups[i].Name, v) {
|
||||
if v == "手动切换" {
|
||||
proxies := make([]string, 0, len(sub.Proxies))
|
||||
for _, p := range sub.Proxies {
|
||||
proxies = append(proxies, p.Name)
|
||||
}
|
||||
temp.ProxyGroups[i].Proxies = proxies
|
||||
}
|
||||
skip = true
|
||||
if temp.ProxyGroups[i].IsCountryGrop {
|
||||
continue
|
||||
}
|
||||
newProxies := make([]string, 0, len(temp.ProxyGroups[i].Proxies))
|
||||
countryGroupMap := make(map[string]model.ProxyGroup)
|
||||
for _, v := range sub.ProxyGroups {
|
||||
if v.IsCountryGrop {
|
||||
countryGroupMap[v.Name] = v
|
||||
}
|
||||
if !skip {
|
||||
temp.ProxyGroups[i].Proxies = append(temp.ProxyGroups[i].Proxies, countryGroupNames...)
|
||||
}
|
||||
for j := range temp.ProxyGroups[i].Proxies {
|
||||
reg := regexp.MustCompile("<(.*?)>")
|
||||
if reg.Match([]byte(temp.ProxyGroups[i].Proxies[j])) {
|
||||
key := reg.FindStringSubmatch(temp.ProxyGroups[i].Proxies[j])[1]
|
||||
switch key {
|
||||
case "all":
|
||||
newProxies = append(newProxies, proxyNames...)
|
||||
case "countries":
|
||||
newProxies = append(newProxies, countryGroupNames...)
|
||||
default:
|
||||
if len(key) == 2 {
|
||||
newProxies = append(
|
||||
newProxies, countryGroupMap[utils.GetContryName(key)].Proxies...,
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
newProxies = append(newProxies, temp.ProxyGroups[i].Proxies[j])
|
||||
}
|
||||
}
|
||||
temp.ProxyGroups[i].Proxies = newProxies
|
||||
}
|
||||
temp.ProxyGroups = append(temp.ProxyGroups, sub.ProxyGroups...)
|
||||
}
|
||||
|
@ -6,6 +6,7 @@ import (
|
||||
"gopkg.in/yaml.v3"
|
||||
"net/http"
|
||||
"sub2clash/config"
|
||||
"sub2clash/model"
|
||||
"sub2clash/validator"
|
||||
)
|
||||
|
||||
@ -16,12 +17,23 @@ func SubHandler(c *gin.Context) {
|
||||
c.String(http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
sub, err := BuildSub(query, config.Default.MetaTemplate)
|
||||
sub, err := BuildSub(model.ClashMeta, query, config.Default.MetaTemplate)
|
||||
if err != nil {
|
||||
c.String(http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
// 输出
|
||||
if query.NodeListMode {
|
||||
nodelist := model.NodeList{}
|
||||
nodelist.Proxies = sub.Proxies
|
||||
marshal, err := yaml.Marshal(nodelist)
|
||||
if err != nil {
|
||||
c.String(http.StatusInternalServerError, "YAML序列化失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
c.String(http.StatusOK, string(marshal))
|
||||
return
|
||||
}
|
||||
marshal, err := yaml.Marshal(sub)
|
||||
if err != nil {
|
||||
c.String(http.StatusInternalServerError, "YAML序列化失败: "+err.Error())
|
||||
|
108
api/controller/short_link.go
Normal file
108
api/controller/short_link.go
Normal file
@ -0,0 +1,108 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sub2clash/config"
|
||||
"sub2clash/logger"
|
||||
"sub2clash/model"
|
||||
"sub2clash/utils"
|
||||
"sub2clash/utils/database"
|
||||
"sub2clash/validator"
|
||||
"time"
|
||||
)
|
||||
|
||||
func ShortLinkGenHandler(c *gin.Context) {
|
||||
// 从请求中获取参数
|
||||
var params validator.ShortLinkGenValidator
|
||||
if err := c.ShouldBind(¶ms); err != nil {
|
||||
c.String(400, "参数错误: "+err.Error())
|
||||
}
|
||||
if strings.TrimSpace(params.Url) == "" {
|
||||
c.String(400, "参数错误")
|
||||
return
|
||||
}
|
||||
// 生成hash
|
||||
hash := utils.RandomString(config.Default.ShortLinkLength)
|
||||
var item model.ShortLink
|
||||
result := database.FindShortLinkByUrl(params.Url, &item)
|
||||
if result.Error == nil {
|
||||
if item.Password != params.Password {
|
||||
item.Password = params.Password
|
||||
database.SaveShortLink(&item)
|
||||
c.String(200, item.Hash+"?password="+params.Password)
|
||||
} else {
|
||||
c.String(200, item.Hash)
|
||||
}
|
||||
return
|
||||
} else {
|
||||
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
|
||||
c.String(500, "数据库错误: "+result.Error.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
// 如果记录存在则重新生成hash,直到记录不存在
|
||||
result = database.FindShortLinkByHash(hash, &item)
|
||||
for result.Error == nil {
|
||||
hash = utils.RandomString(config.Default.ShortLinkLength)
|
||||
result = database.FindShortLinkByHash(hash, &item)
|
||||
}
|
||||
// 创建记录
|
||||
database.FirstOrCreateShortLink(
|
||||
&model.ShortLink{
|
||||
Hash: hash,
|
||||
Url: params.Url,
|
||||
LastRequestTime: -1,
|
||||
Password: params.Password,
|
||||
},
|
||||
)
|
||||
// 返回短链接
|
||||
if params.Password != "" {
|
||||
hash += "?password=" + params.Password
|
||||
}
|
||||
c.String(200, hash)
|
||||
}
|
||||
|
||||
func ShortLinkGetHandler(c *gin.Context) {
|
||||
// 获取动态路由
|
||||
hash := c.Param("hash")
|
||||
password := c.Query("password")
|
||||
if strings.TrimSpace(hash) == "" {
|
||||
c.String(400, "参数错误")
|
||||
return
|
||||
}
|
||||
// 查询数据库
|
||||
var shortLink model.ShortLink
|
||||
result := database.FindShortLinkByHash(hash, &shortLink)
|
||||
// 重定向
|
||||
if result.Error != nil {
|
||||
c.String(404, "未找到短链接或密码错误")
|
||||
return
|
||||
}
|
||||
if shortLink.Password != "" && shortLink.Password != password {
|
||||
c.String(404, "未找到短链接或密码错误")
|
||||
return
|
||||
}
|
||||
// 更新最后访问时间
|
||||
shortLink.LastRequestTime = time.Now().Unix()
|
||||
database.SaveShortLink(&shortLink)
|
||||
get, err := utils.Get("http://localhost:" + strconv.Itoa(config.Default.Port) + "/" + shortLink.Url)
|
||||
if err != nil {
|
||||
logger.Logger.Debug("get short link data failed", zap.Error(err))
|
||||
c.String(500, "请求错误: "+err.Error())
|
||||
return
|
||||
}
|
||||
all, err := io.ReadAll(get.Body)
|
||||
if err != nil {
|
||||
logger.Logger.Debug("read short link data failed", zap.Error(err))
|
||||
c.String(500, "读取错误: "+err.Error())
|
||||
return
|
||||
}
|
||||
c.String(http.StatusOK, string(all))
|
||||
}
|
44
api/route.go
44
api/route.go
@ -1,13 +1,47 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"github.com/gin-gonic/gin"
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"sub2clash/api/controller"
|
||||
"sub2clash/config"
|
||||
"sub2clash/middleware"
|
||||
)
|
||||
|
||||
//go:embed static
|
||||
var staticFiles embed.FS
|
||||
|
||||
func SetRoute(r *gin.Engine) {
|
||||
r.Use(middleware.ZapLogger())
|
||||
|
||||
// 使用内嵌的模板文件
|
||||
tpl, err := template.ParseFS(staticFiles, "static/*")
|
||||
if err != nil {
|
||||
log.Fatalf("Error parsing templates: %v", err)
|
||||
}
|
||||
r.SetHTMLTemplate(tpl)
|
||||
|
||||
r.GET(
|
||||
"/static/*filepath", func(c *gin.Context) {
|
||||
c.FileFromFS("static/"+c.Param("filepath"), http.FS(staticFiles))
|
||||
},
|
||||
)
|
||||
r.GET(
|
||||
"/", func(c *gin.Context) {
|
||||
version := config.Version
|
||||
if len(config.Version) > 7 {
|
||||
version = config.Version[:7]
|
||||
}
|
||||
c.HTML(
|
||||
200, "index.html", gin.H{
|
||||
"Version": version,
|
||||
},
|
||||
)
|
||||
},
|
||||
)
|
||||
r.GET(
|
||||
"/clash", func(c *gin.Context) {
|
||||
controller.SubmodHandler(c)
|
||||
@ -18,4 +52,14 @@ func SetRoute(r *gin.Engine) {
|
||||
controller.SubHandler(c)
|
||||
},
|
||||
)
|
||||
r.POST(
|
||||
"/short", func(c *gin.Context) {
|
||||
controller.ShortLinkGenHandler(c)
|
||||
},
|
||||
)
|
||||
r.GET(
|
||||
"/s/:hash", func(c *gin.Context) {
|
||||
controller.ShortLinkGetHandler(c)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
258
api/static/index.html
Normal file
258
api/static/index.html
Normal file
@ -0,0 +1,258 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
|
||||
<title>sub2clash</title>
|
||||
<!-- Bootstrap CSS -->
|
||||
<link
|
||||
crossorigin="anonymous"
|
||||
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css"
|
||||
integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<!-- Bootstrap JS -->
|
||||
<script
|
||||
crossorigin="anonymous"
|
||||
integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
|
||||
src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"
|
||||
></script>
|
||||
<!-- Axios -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/axios@latest/dist/axios.min.js"></script>
|
||||
<script src="./static/index.js"></script>
|
||||
<style>
|
||||
.container {
|
||||
max-width: 800px;
|
||||
}
|
||||
|
||||
.btn-xs {
|
||||
padding: 2px 2px; /* 调整内边距以减小按钮大小 */
|
||||
font-size: 10px; /* 设置字体大小 */
|
||||
line-height: 1.2; /* 调整行高 */
|
||||
border-radius: 3px; /* 可选的边框半径调整 */
|
||||
height: 25px;
|
||||
width: 25px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="bg-light">
|
||||
<div class="container mt-5">
|
||||
<div class="mb-4">
|
||||
<h2>sub2clash</h2>
|
||||
<span class="text-muted fst-italic"
|
||||
>通用订阅链接转 Clash(Meta) 配置工具
|
||||
<a
|
||||
href="https://github.com/nitezs/sub2clash#clash-meta"
|
||||
target="_blank"
|
||||
>使用文档</a
|
||||
></span
|
||||
>
|
||||
</div>
|
||||
|
||||
<!-- Input URL -->
|
||||
<div class="form-group mb-5">
|
||||
<label for="apiLink">解析链接:</label>
|
||||
<div class="input-group mb-2">
|
||||
<input
|
||||
class="form-control"
|
||||
id="urlInput"
|
||||
type="text"
|
||||
placeholder="通过生成的链接重新填写下方设置"
|
||||
/>
|
||||
<button
|
||||
class="btn btn-primary"
|
||||
onclick="parseInputURL()"
|
||||
type="button"
|
||||
>
|
||||
解析
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- API Endpoint -->
|
||||
<div class="form-group mb-3">
|
||||
<label for="endpoint">客户端类型:</label>
|
||||
<select class="form-control" id="endpoint" name="endpoint">
|
||||
<option value="clash">Clash</option>
|
||||
<option value="meta">Clash.Meta</option>
|
||||
</select>
|
||||
</div>
|
||||
<!-- Template -->
|
||||
<div class="form-group mb-3">
|
||||
<label for="template">模板链接或名称:</label>
|
||||
<input
|
||||
class="form-control"
|
||||
id="template"
|
||||
name="template"
|
||||
placeholder="输入外部模板链接或内部模板名称(可选)"
|
||||
type="text"
|
||||
/>
|
||||
</div>
|
||||
<!-- Subscription Link -->
|
||||
<div class="form-group mb-3">
|
||||
<label for="sub">订阅链接:</label>
|
||||
<textarea
|
||||
class="form-control"
|
||||
id="sub"
|
||||
name="sub"
|
||||
placeholder="每行输入一个订阅链接"
|
||||
rows="5"
|
||||
></textarea>
|
||||
</div>
|
||||
<!-- Proxy Link -->
|
||||
<div class="form-group mb-3">
|
||||
<label for="proxy">节点分享链接:</label>
|
||||
<textarea
|
||||
class="form-control"
|
||||
id="proxy"
|
||||
name="proxy"
|
||||
placeholder="每行输入一个节点分享链接"
|
||||
rows="5"
|
||||
></textarea>
|
||||
</div>
|
||||
<!-- Refresh -->
|
||||
<div class="form-check mb-3">
|
||||
<input
|
||||
class="form-check-input"
|
||||
id="refresh"
|
||||
name="refresh"
|
||||
type="checkbox"
|
||||
/>
|
||||
<label class="form-check-label" for="refresh">强制重新获取订阅</label>
|
||||
</div>
|
||||
<!-- Node List -->
|
||||
<div class="form-check mb-3">
|
||||
<input
|
||||
class="form-check-input"
|
||||
id="nodeList"
|
||||
name="nodeList"
|
||||
type="checkbox"
|
||||
/>
|
||||
<label class="form-check-label" for="nodeList">输出为 Node List</label>
|
||||
</div>
|
||||
<!-- Auto Test -->
|
||||
<div class="form-check mb-3">
|
||||
<input
|
||||
class="form-check-input"
|
||||
id="autoTest"
|
||||
name="autoTest"
|
||||
type="checkbox"
|
||||
/>
|
||||
<label class="form-check-label" for="autoTest"
|
||||
>国家策略组自动测速</label
|
||||
>
|
||||
</div>
|
||||
<!-- Lazy -->
|
||||
<div class="form-check mb-3">
|
||||
<input class="form-check-input" id="lazy" name="lazy" type="checkbox" />
|
||||
<label class="form-check-label" for="lazy"
|
||||
>自动测速启用 lazy 模式</label
|
||||
>
|
||||
</div>
|
||||
<!-- Rule Provider -->
|
||||
<div class="form-group mb-3" id="ruleProviderGroup">
|
||||
<label>Rule Provider:</label>
|
||||
<button
|
||||
class="btn btn-primary mb-1 btn-xs"
|
||||
onclick="addRuleProvider()"
|
||||
type="button"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
<!-- Rule -->
|
||||
<div class="form-group mb-3" id="ruleGroup">
|
||||
<label>规则:</label>
|
||||
<button
|
||||
class="btn btn-primary mb-1 btn-xs"
|
||||
onclick="addRule()"
|
||||
type="button"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
<!-- Sort -->
|
||||
<div class="form-group mb-3">
|
||||
<label for="sort">国家策略组排序规则:</label>
|
||||
<select class="form-control" id="sort" name="sort">
|
||||
<option value="nameasc">名称(升序)</option>
|
||||
<option value="namedesc">名称(降序)</option>
|
||||
<option value="sizeasc">节点数量(升序)</option>
|
||||
<option value="sizedesc">节点数量(降序)</option>
|
||||
</select>
|
||||
</div>
|
||||
<!-- Remove -->
|
||||
<div class="form-group mb-3">
|
||||
<label for="remove">排除节点:</label>
|
||||
<input
|
||||
class="form-control"
|
||||
type="text"
|
||||
name="remove"
|
||||
id="remove"
|
||||
placeholder="正则表达式"
|
||||
/>
|
||||
</div>
|
||||
<!-- Rename -->
|
||||
<div class="form-group mb-3" id="replaceGroup">
|
||||
<label>节点名称替换:</label>
|
||||
<button
|
||||
class="btn btn-primary mb-1 btn-xs"
|
||||
onclick="addReplace()"
|
||||
type="button"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Display the API Link -->
|
||||
<div class="form-group mb-5">
|
||||
<label for="apiLink">配置链接:</label>
|
||||
<div class="input-group mb-2">
|
||||
<input class="form-control" id="apiLink" readonly type="text" />
|
||||
<button class="btn btn-primary" onclick="generateURL()" type="button">
|
||||
生成链接
|
||||
</button>
|
||||
<button
|
||||
class="btn btn-primary"
|
||||
onclick="copyToClipboard('apiLink',this)"
|
||||
type="button"
|
||||
>
|
||||
复制链接
|
||||
</button>
|
||||
</div>
|
||||
<div class="input-group">
|
||||
<input class="form-control" id="apiShortLink" readonly type="text" />
|
||||
<input
|
||||
class="form-control"
|
||||
id="password"
|
||||
type="text"
|
||||
placeholder="密码"
|
||||
/>
|
||||
<button
|
||||
class="btn btn-primary"
|
||||
onclick="generateShortLink()"
|
||||
type="button"
|
||||
>
|
||||
生成短链
|
||||
</button>
|
||||
<button
|
||||
class="btn btn-primary"
|
||||
onclick="copyToClipboard('apiShortLink',this)"
|
||||
type="button"
|
||||
>
|
||||
复制短链
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- footer-->
|
||||
<footer>
|
||||
<p class="text-center">
|
||||
Powered by
|
||||
<a class="link-primary" href="https://github.com/nitezs/sub2clash"
|
||||
>sub2clash</a
|
||||
>
|
||||
</p>
|
||||
<p class="text-center">Version {{.Version}}</p>
|
||||
</footer>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
415
api/static/index.js
Normal file
415
api/static/index.js
Normal file
@ -0,0 +1,415 @@
|
||||
function clearExistingValues() {
|
||||
// 清除简单输入框和复选框的值
|
||||
document.getElementById("endpoint").value = "clash";
|
||||
document.getElementById("sub").value = "";
|
||||
document.getElementById("proxy").value = "";
|
||||
document.getElementById("refresh").checked = false;
|
||||
document.getElementById("autoTest").checked = false;
|
||||
document.getElementById("lazy").checked = false;
|
||||
document.getElementById("template").value = "";
|
||||
document.getElementById("sort").value = "nameasc";
|
||||
document.getElementById("remove").value = "";
|
||||
document.getElementById("apiLink").value = "";
|
||||
document.getElementById("apiShortLink").value = "";
|
||||
document.getElementById("password").value = "";
|
||||
document.getElementById("nodeList").checked = false;
|
||||
|
||||
// 清除由 createRuleProvider, createReplace, 和 createRule 创建的所有额外输入组
|
||||
clearInputGroup("ruleProviderGroup");
|
||||
clearInputGroup("replaceGroup");
|
||||
clearInputGroup("ruleGroup");
|
||||
}
|
||||
|
||||
function generateURI() {
|
||||
const queryParams = [];
|
||||
|
||||
// 获取 API Endpoint
|
||||
const endpoint = document.getElementById("endpoint").value;
|
||||
|
||||
// 获取并组合订阅链接
|
||||
let subLines = document
|
||||
.getElementById("sub")
|
||||
.value.split("\n")
|
||||
.filter((line) => line.trim() !== "");
|
||||
let noSub = false;
|
||||
// 去除 subLines 中空元素
|
||||
subLines = subLines.map((item) => {
|
||||
if (item !== "") {
|
||||
return item;
|
||||
}
|
||||
});
|
||||
if (subLines.length > 0) {
|
||||
queryParams.push(`sub=${encodeURIComponent(subLines.join(","))}`);
|
||||
} else {
|
||||
noSub = true;
|
||||
}
|
||||
|
||||
// 获取并组合节点分享链接
|
||||
let proxyLines = document
|
||||
.getElementById("proxy")
|
||||
.value.split("\n")
|
||||
.filter((line) => line.trim() !== "");
|
||||
let noProxy = false;
|
||||
// 去除 proxyLines 中空元素
|
||||
proxyLines = proxyLines.map((item) => {
|
||||
if (item !== "") {
|
||||
return item;
|
||||
}
|
||||
});
|
||||
if (proxyLines.length > 0) {
|
||||
queryParams.push(`proxy=${encodeURIComponent(proxyLines.join(","))}`);
|
||||
} else {
|
||||
noProxy = true;
|
||||
}
|
||||
if (noSub && noProxy) {
|
||||
alert("订阅链接和节点分享链接不能同时为空!");
|
||||
return "";
|
||||
}
|
||||
// 获取复选框的值
|
||||
const refresh = document.getElementById("refresh").checked;
|
||||
queryParams.push(`refresh=${refresh ? "true" : "false"}`);
|
||||
const autoTest = document.getElementById("autoTest").checked;
|
||||
queryParams.push(`autoTest=${autoTest ? "true" : "false"}`);
|
||||
const lazy = document.getElementById("lazy").checked;
|
||||
queryParams.push(`lazy=${lazy ? "true" : "false"}`);
|
||||
const nodeList = document.getElementById("nodeList").checked;
|
||||
queryParams.push(`nodeList=${nodeList ? "true" : "false"}`);
|
||||
|
||||
// 获取模板链接或名称(如果存在)
|
||||
const template = document.getElementById("template").value;
|
||||
if (template.trim() !== "") {
|
||||
queryParams.push(`template=${encodeURIComponent(template)}`);
|
||||
}
|
||||
|
||||
// 获取Rule Provider和规则
|
||||
const ruleProviders = document.getElementsByName("ruleProvider");
|
||||
const rules = document.getElementsByName("rule");
|
||||
let providers = [];
|
||||
for (let i = 0; i < ruleProviders.length / 5; i++) {
|
||||
let baseIndex = i * 5;
|
||||
let behavior = ruleProviders[baseIndex].value;
|
||||
let url = ruleProviders[baseIndex + 1].value;
|
||||
let group = ruleProviders[baseIndex + 2].value;
|
||||
let prepend = ruleProviders[baseIndex + 3].value;
|
||||
let name = ruleProviders[baseIndex + 4].value;
|
||||
// 是否存在空值
|
||||
if (
|
||||
behavior.trim() === "" ||
|
||||
url.trim() === "" ||
|
||||
group.trim() === "" ||
|
||||
prepend.trim() === "" ||
|
||||
name.trim() === ""
|
||||
) {
|
||||
alert("Rule Provider 中存在空值,请检查后重试!");
|
||||
return "";
|
||||
}
|
||||
providers.push(`[${behavior},${url},${group},${prepend},${name}]`);
|
||||
}
|
||||
queryParams.push(`ruleProvider=${encodeURIComponent(providers.join(","))}`);
|
||||
|
||||
let ruleList = [];
|
||||
for (let i = 0; i < rules.length / 3; i++) {
|
||||
if (rules[i * 3].value.trim() !== "") {
|
||||
let rule = rules[i * 3].value;
|
||||
let prepend = rules[i * 3 + 1].value;
|
||||
let group = rules[i * 3 + 2].value;
|
||||
// 是否存在空值
|
||||
if (rule.trim() === "" || prepend.trim() === "" || group.trim() === "") {
|
||||
alert("Rule 中存在空值,请检查后重试!");
|
||||
return "";
|
||||
}
|
||||
ruleList.push(`[${rule},${prepend},${group}]`);
|
||||
}
|
||||
}
|
||||
queryParams.push(`rule=${encodeURIComponent(ruleList.join(","))}`);
|
||||
|
||||
// 获取排序策略
|
||||
const sort = document.getElementById("sort").value;
|
||||
queryParams.push(`sort=${sort}`);
|
||||
|
||||
// 获取删除节点的正则表达式
|
||||
const remove = document.getElementById("remove").value;
|
||||
if (remove.trim() !== "") {
|
||||
queryParams.push(`remove=${encodeURIComponent(remove)}`);
|
||||
}
|
||||
|
||||
// 获取替换节点名称的正则表达式
|
||||
let replaceList = [];
|
||||
const replaces = document.getElementsByName("replace");
|
||||
for (let i = 0; i < replaces.length / 2; i++) {
|
||||
let replaceStr = `<${replaces[i * 2].value}>`;
|
||||
let replaceTo = `<${replaces[i * 2 + 1].value}>`;
|
||||
if (replaceStr.trim() === "") {
|
||||
alert("重命名设置中存在空值,请检查后重试!");
|
||||
return "";
|
||||
}
|
||||
replaceList.push(`[${replaceStr},${replaceTo}]`);
|
||||
}
|
||||
queryParams.push(`replace=${encodeURIComponent(replaceList.join(","))}`);
|
||||
|
||||
return `${endpoint}?${queryParams.join("&")}`;
|
||||
}
|
||||
|
||||
// 将输入框中的 URL 解析为参数
|
||||
function parseInputURL() {
|
||||
// 获取输入框中的 URL
|
||||
const inputURL = document.getElementById("urlInput").value;
|
||||
|
||||
if (!inputURL) {
|
||||
alert("请输入有效的链接!");
|
||||
return;
|
||||
}
|
||||
|
||||
let url;
|
||||
try {
|
||||
url = new URL(inputURL);
|
||||
} catch (_) {
|
||||
alert("无效的链接!");
|
||||
return;
|
||||
}
|
||||
|
||||
// 清除现有的输入框值
|
||||
clearExistingValues();
|
||||
|
||||
// 获取查询参数
|
||||
const params = new URLSearchParams(url.search);
|
||||
|
||||
// 分配值到对应的输入框
|
||||
const pathSections = url.pathname.split("/");
|
||||
const lastSection = pathSections[pathSections.length - 1];
|
||||
const clientTypeSelect = document.getElementById("endpoint");
|
||||
switch (lastSection.toLowerCase()) {
|
||||
case "meta":
|
||||
clientTypeSelect.value = "meta";
|
||||
break;
|
||||
case "clash":
|
||||
default:
|
||||
clientTypeSelect.value = "clash";
|
||||
break;
|
||||
}
|
||||
|
||||
if (params.has("sub")) {
|
||||
document.getElementById("sub").value = decodeURIComponent(params.get("sub"))
|
||||
.split(",")
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
if (params.has("proxy")) {
|
||||
document.getElementById("proxy").value = decodeURIComponent(
|
||||
params.get("proxy"),
|
||||
)
|
||||
.split(",")
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
if (params.has("refresh")) {
|
||||
document.getElementById("refresh").checked =
|
||||
params.get("refresh") === "true";
|
||||
}
|
||||
|
||||
if (params.has("autoTest")) {
|
||||
document.getElementById("autoTest").checked =
|
||||
params.get("autoTest") === "true";
|
||||
}
|
||||
|
||||
if (params.has("lazy")) {
|
||||
document.getElementById("lazy").checked = params.get("lazy") === "true";
|
||||
}
|
||||
|
||||
if (params.has("template")) {
|
||||
document.getElementById("template").value = decodeURIComponent(
|
||||
params.get("template"),
|
||||
);
|
||||
}
|
||||
|
||||
if (params.has("sort")) {
|
||||
document.getElementById("sort").value = params.get("sort");
|
||||
}
|
||||
|
||||
if (params.has("remove")) {
|
||||
document.getElementById("remove").value = decodeURIComponent(
|
||||
params.get("remove"),
|
||||
);
|
||||
}
|
||||
|
||||
if (params.has("replace")) {
|
||||
parseAndFillReplaceParams(decodeURIComponent(params.get("replace")));
|
||||
}
|
||||
|
||||
if (params.has("ruleProvider")) {
|
||||
parseAndFillRuleProviderParams(
|
||||
decodeURIComponent(params.get("ruleProvider")),
|
||||
);
|
||||
}
|
||||
|
||||
if (params.has("rule")) {
|
||||
parseAndFillRuleParams(decodeURIComponent(params.get("rule")));
|
||||
}
|
||||
|
||||
if (params.has("nodeList")) {
|
||||
document.getElementById("nodeList").checked =
|
||||
params.get("nodeList") === "true";
|
||||
}
|
||||
}
|
||||
|
||||
function clearInputGroup(groupId) {
|
||||
// 清空第二个之后的child
|
||||
const group = document.getElementById(groupId);
|
||||
while (group.children.length > 2) {
|
||||
group.removeChild(group.lastChild);
|
||||
}
|
||||
}
|
||||
|
||||
function parseAndFillReplaceParams(replaceParams) {
|
||||
const replaceGroup = document.getElementById("replaceGroup");
|
||||
let matches;
|
||||
const regex = /\[(<.*?>),(<.*?>)\]/g;
|
||||
const str = decodeURIComponent(replaceParams);
|
||||
while ((matches = regex.exec(str)) !== null) {
|
||||
const div = createReplace();
|
||||
const original = matches[1].slice(1, -1); // Remove < and >
|
||||
const replacement = matches[2].slice(1, -1); // Remove < and >
|
||||
|
||||
div.children[0].value = original;
|
||||
div.children[1].value = replacement;
|
||||
replaceGroup.appendChild(div);
|
||||
}
|
||||
}
|
||||
|
||||
function parseAndFillRuleProviderParams(ruleProviderParams) {
|
||||
const ruleProviderGroup = document.getElementById("ruleProviderGroup");
|
||||
let matches;
|
||||
const regex = /\[(.*?),(.*?),(.*?),(.*?),(.*?)\]/g;
|
||||
const str = decodeURIComponent(ruleProviderParams);
|
||||
while ((matches = regex.exec(str)) !== null) {
|
||||
const div = createRuleProvider();
|
||||
div.children[0].value = matches[1];
|
||||
div.children[1].value = matches[2];
|
||||
div.children[2].value = matches[3];
|
||||
div.children[3].value = matches[4];
|
||||
div.children[4].value = matches[5];
|
||||
ruleProviderGroup.appendChild(div);
|
||||
}
|
||||
}
|
||||
|
||||
function parseAndFillRuleParams(ruleParams) {
|
||||
const ruleGroup = document.getElementById("ruleGroup");
|
||||
let matches;
|
||||
const regex = /\[(.*?),(.*?),(.*?)\]/g;
|
||||
const str = decodeURIComponent(ruleParams);
|
||||
while ((matches = regex.exec(str)) !== null) {
|
||||
const div = createRule();
|
||||
div.children[0].value = matches[1];
|
||||
div.children[1].value = matches[2];
|
||||
div.children[2].value = matches[3];
|
||||
ruleGroup.appendChild(div);
|
||||
}
|
||||
}
|
||||
|
||||
async function copyToClipboard(elem, e) {
|
||||
const apiLinkInput = document.querySelector(`#${elem}`).value;
|
||||
try {
|
||||
await navigator.clipboard.writeText(apiLinkInput);
|
||||
let text = e.textContent;
|
||||
e.addEventListener("mouseout", function () {
|
||||
e.textContent = text;
|
||||
});
|
||||
e.textContent = "复制成功";
|
||||
} catch (err) {
|
||||
console.error("复制到剪贴板失败:", err);
|
||||
}
|
||||
}
|
||||
|
||||
function createRuleProvider() {
|
||||
const div = document.createElement("div");
|
||||
div.classList.add("input-group", "mb-2");
|
||||
div.innerHTML = `
|
||||
<input type="text" class="form-control" name="ruleProvider" placeholder="Behavior">
|
||||
<input type="text" class="form-control" name="ruleProvider" placeholder="Url">
|
||||
<input type="text" class="form-control" name="ruleProvider" placeholder="Group">
|
||||
<input type="text" class="form-control" name="ruleProvider" placeholder="Prepend">
|
||||
<input type="text" class="form-control" name="ruleProvider" placeholder="Name">
|
||||
<button type="button" class="btn btn-danger" onclick="removeElement(this)">删除</button>
|
||||
`;
|
||||
return div;
|
||||
}
|
||||
|
||||
function createReplace() {
|
||||
const div = document.createElement("div");
|
||||
div.classList.add("input-group", "mb-2");
|
||||
div.innerHTML = `
|
||||
<input type="text" class="form-control" name="replace" placeholder="原字符串(正则表达式)">
|
||||
<input type="text" class="form-control" name="replace" placeholder="替换为(可为空)">
|
||||
<button type="button" class="btn btn-danger" onclick="removeElement(this)">删除</button>
|
||||
`;
|
||||
return div;
|
||||
}
|
||||
|
||||
function createRule() {
|
||||
const div = document.createElement("div");
|
||||
div.classList.add("input-group", "mb-2");
|
||||
div.innerHTML = `
|
||||
<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="Group">
|
||||
<button type="button" class="btn btn-danger" onclick="removeElement(this)">删除</button>
|
||||
`;
|
||||
return div;
|
||||
}
|
||||
|
||||
function addRuleProvider() {
|
||||
const div = createRuleProvider();
|
||||
document.getElementById("ruleProviderGroup").appendChild(div);
|
||||
}
|
||||
|
||||
function addRule() {
|
||||
const div = createRule();
|
||||
document.getElementById("ruleGroup").appendChild(div);
|
||||
}
|
||||
|
||||
function addReplace() {
|
||||
const div = createReplace();
|
||||
document.getElementById("replaceGroup").appendChild(div);
|
||||
}
|
||||
|
||||
function removeElement(button) {
|
||||
button.parentElement.remove();
|
||||
}
|
||||
|
||||
function generateURL() {
|
||||
const apiLink = document.getElementById("apiLink");
|
||||
let uri = generateURI();
|
||||
if (uri === "") {
|
||||
return;
|
||||
}
|
||||
apiLink.value = `${window.location.origin}${window.location.pathname}${uri}`;
|
||||
}
|
||||
|
||||
function generateShortLink() {
|
||||
const apiShortLink = document.getElementById("apiShortLink");
|
||||
const password = document.getElementById("password");
|
||||
let uri = generateURI();
|
||||
if (uri === "") {
|
||||
return;
|
||||
}
|
||||
axios
|
||||
.post(
|
||||
"./short",
|
||||
{
|
||||
url: uri,
|
||||
password: password.value.trim(),
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
},
|
||||
)
|
||||
.then((response) => {
|
||||
apiShortLink.value = `${window.location.origin}${window.location.pathname}s/${response.data}`;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error);
|
||||
alert("生成短链失败,请重试!");
|
||||
});
|
||||
}
|
@ -1,6 +1,7 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/joho/godotenv"
|
||||
"os"
|
||||
"strconv"
|
||||
@ -14,11 +15,15 @@ type Config struct {
|
||||
RequestMaxFileSize int64
|
||||
CacheExpire int64
|
||||
LogLevel string
|
||||
//BasePath string
|
||||
ShortLinkLength int
|
||||
}
|
||||
|
||||
var Default *Config
|
||||
var Version string
|
||||
var Dev string
|
||||
|
||||
func init() {
|
||||
func LoadConfig() error {
|
||||
Default = &Config{
|
||||
MetaTemplate: "template_meta.yaml",
|
||||
ClashTemplate: "template_clash.yaml",
|
||||
@ -27,15 +32,14 @@ func init() {
|
||||
Port: 8011,
|
||||
CacheExpire: 60 * 5,
|
||||
LogLevel: "info",
|
||||
//BasePath: "/",
|
||||
ShortLinkLength: 6,
|
||||
}
|
||||
err := godotenv.Load()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = godotenv.Load()
|
||||
if os.Getenv("PORT") != "" {
|
||||
atoi, err := strconv.Atoi(os.Getenv("PORT"))
|
||||
if err != nil {
|
||||
panic("PORT invalid")
|
||||
return errors.New("PORT invalid")
|
||||
}
|
||||
Default.Port = atoi
|
||||
}
|
||||
@ -48,25 +52,39 @@ func init() {
|
||||
if os.Getenv("REQUEST_RETRY_TIMES") != "" {
|
||||
atoi, err := strconv.Atoi(os.Getenv("REQUEST_RETRY_TIMES"))
|
||||
if err != nil {
|
||||
panic("REQUEST_RETRY_TIMES invalid")
|
||||
return errors.New("REQUEST_RETRY_TIMES invalid")
|
||||
}
|
||||
Default.RequestRetryTimes = atoi
|
||||
}
|
||||
if os.Getenv("REQUEST_MAX_FILE_SIZE") != "" {
|
||||
atoi, err := strconv.Atoi(os.Getenv("REQUEST_MAX_FILE_SIZE"))
|
||||
if err != nil {
|
||||
panic("REQUEST_MAX_FILE_SIZE invalid")
|
||||
return errors.New("REQUEST_MAX_FILE_SIZE invalid")
|
||||
}
|
||||
Default.RequestMaxFileSize = int64(atoi)
|
||||
}
|
||||
if os.Getenv("CACHE_EXPIRE") != "" {
|
||||
atoi, err := strconv.Atoi(os.Getenv("CACHE_EXPIRE"))
|
||||
if err != nil {
|
||||
panic("CACHE_EXPIRE invalid")
|
||||
return errors.New("CACHE_EXPIRE invalid")
|
||||
}
|
||||
Default.CacheExpire = int64(atoi)
|
||||
}
|
||||
if os.Getenv("LOG_LEVEL") != "" {
|
||||
Default.LogLevel = os.Getenv("LOG_LEVEL")
|
||||
}
|
||||
//if os.Getenv("BASE_PATH") != "" {
|
||||
// Default.BasePath = os.Getenv("BASE_PATH")
|
||||
// if Default.BasePath[len(Default.BasePath)-1] != '/' {
|
||||
// Default.BasePath += "/"
|
||||
// }
|
||||
//}
|
||||
if os.Getenv("SHORT_LINK_LENGTH") != "" {
|
||||
atoi, err := strconv.Atoi(os.Getenv("SHORT_LINK_LENGTH"))
|
||||
if err != nil {
|
||||
return errors.New("SHORT_LINK_LENGTH invalid")
|
||||
}
|
||||
Default.ShortLinkLength = atoi
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
@ -8,8 +8,9 @@ services:
|
||||
ports:
|
||||
- "8011:8011"
|
||||
volumes:
|
||||
- ./templates:/app/templates
|
||||
- ./logs:/app/logs
|
||||
- ./templates:/app/templates
|
||||
- ./data:/app/data
|
||||
# environment:
|
||||
# - PORT=8011
|
||||
# - META_TEMPLATE=template_meta.yaml
|
||||
|
17
go.mod
17
go.mod
@ -4,21 +4,30 @@ go 1.21
|
||||
|
||||
require (
|
||||
github.com/gin-gonic/gin v1.9.1
|
||||
github.com/glebarez/sqlite v1.9.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
go.uber.org/zap v1.25.0
|
||||
go.uber.org/zap v1.26.0
|
||||
golang.org/x/text v0.13.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
gorm.io/gorm v1.25.4
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bytedance/sonic v1.10.1 // indirect
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
|
||||
github.com/chenzhuoyu/iasm v0.9.0 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
github.com/glebarez/go-sqlite v1.21.2 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.15.4 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/google/go-cmp v0.5.9 // indirect
|
||||
github.com/google/uuid v1.3.0 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.5 // indirect
|
||||
github.com/leodido/go-urn v1.2.4 // indirect
|
||||
@ -26,6 +35,7 @@ require (
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.11 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
@ -33,6 +43,9 @@ require (
|
||||
golang.org/x/crypto v0.13.0 // indirect
|
||||
golang.org/x/net v0.15.0 // indirect
|
||||
golang.org/x/sys v0.12.0 // indirect
|
||||
golang.org/x/text v0.13.0 // indirect
|
||||
google.golang.org/protobuf v1.31.0 // indirect
|
||||
modernc.org/libc v1.22.5 // indirect
|
||||
modernc.org/mathutil v1.5.0 // indirect
|
||||
modernc.org/memory v1.5.0 // indirect
|
||||
modernc.org/sqlite v1.23.1 // indirect
|
||||
)
|
||||
|
37
go.sum
37
go.sum
@ -1,5 +1,3 @@
|
||||
github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A=
|
||||
github.com/benbjohnson/clock v1.3.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
|
||||
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
|
||||
github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM=
|
||||
github.com/bytedance/sonic v1.10.1 h1:7a1wuFXL1cMy7a3f7/VFcEtriuXQnUBhtoVfOZiaysc=
|
||||
@ -13,12 +11,18 @@ github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLI
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
|
||||
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
|
||||
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
|
||||
github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo=
|
||||
github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k=
|
||||
github.com/glebarez/sqlite v1.9.0 h1:Aj6bPA12ZEx5GbSF6XADmCkYXlljPNUY+Zf1EQxynXs=
|
||||
github.com/glebarez/sqlite v1.9.0/go.mod h1:YBYCoyupOao60lzp1MVBLEjZfgkq0tdB1voAQ09K9zw=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
@ -30,9 +34,18 @@ github.com/go-playground/validator/v10 v10.15.4/go.mod h1:9iXMNT7sEkjXb0I+enO7QX
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
|
||||
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
@ -54,6 +67,9 @@ github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6
|
||||
github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
@ -73,8 +89,8 @@ go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk=
|
||||
go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.25.0 h1:4Hvk6GtkucQ790dqmj7l1eEnRdKm3k3ZUrUMS2d5+5c=
|
||||
go.uber.org/zap v1.25.0/go.mod h1:JIAUzQIH94IC4fOJQm7gMmBJP5k7wQfdcnYdPoEXJYk=
|
||||
go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo=
|
||||
go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so=
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/arch v0.5.0 h1:jpGode6huXQxcskEIpOCvrU+tzo81b6+oFLUYXWtH/Y=
|
||||
golang.org/x/arch v0.5.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
@ -88,7 +104,6 @@ golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
|
||||
@ -98,5 +113,15 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/gorm v1.25.4 h1:iyNd8fNAe8W9dvtlgeRI5zSVZPsq3OpcTu37cYcpCmw=
|
||||
gorm.io/gorm v1.25.4/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
|
||||
modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE=
|
||||
modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY=
|
||||
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
|
||||
modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
|
||||
modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds=
|
||||
modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=
|
||||
modernc.org/sqlite v1.23.1 h1:nrSBg4aRQQwq59JpvGEQ15tNxoO5pX/kUjcRNwSAGQM=
|
||||
modernc.org/sqlite v1.23.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk=
|
||||
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||
|
@ -4,8 +4,6 @@ import (
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
"path/filepath"
|
||||
"sub2clash/config"
|
||||
"sub2clash/utils"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
@ -13,9 +11,11 @@ import (
|
||||
var (
|
||||
Logger *zap.Logger
|
||||
lock sync.Mutex
|
||||
logLevel string
|
||||
)
|
||||
|
||||
func init() {
|
||||
func InitLogger(level string) {
|
||||
logLevel = level
|
||||
buildLogger()
|
||||
go rotateLogs()
|
||||
}
|
||||
@ -24,7 +24,7 @@ func buildLogger() {
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
var level zapcore.Level
|
||||
switch config.Default.LogLevel {
|
||||
switch logLevel {
|
||||
case "error":
|
||||
level = zap.ErrorLevel
|
||||
case "debug":
|
||||
@ -36,10 +36,6 @@ func buildLogger() {
|
||||
default:
|
||||
level = zap.InfoLevel
|
||||
}
|
||||
err := utils.MKDir("logs")
|
||||
if err != nil {
|
||||
panic("创建日志失败" + err.Error())
|
||||
}
|
||||
zapConfig := zap.NewProductionConfig()
|
||||
zapConfig.Encoding = "console"
|
||||
zapConfig.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
|
||||
@ -47,9 +43,10 @@ func buildLogger() {
|
||||
zapConfig.OutputPaths = []string{"stdout", getLogFileName("info")}
|
||||
zapConfig.ErrorOutputPaths = []string{"stderr", getLogFileName("error")}
|
||||
zapConfig.Level = zap.NewAtomicLevelAt(level)
|
||||
var err error
|
||||
Logger, err = zapConfig.Build()
|
||||
if err != nil {
|
||||
panic("创建日志失败" + err.Error())
|
||||
panic("log failed" + err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
|
69
main.go
69
main.go
@ -5,13 +5,12 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"sub2clash/api"
|
||||
"sub2clash/config"
|
||||
"sub2clash/logger"
|
||||
"sub2clash/utils"
|
||||
"sub2clash/utils/database"
|
||||
)
|
||||
|
||||
//go:embed templates/template_meta.yaml
|
||||
@ -20,39 +19,45 @@ var templateMeta string
|
||||
//go:embed templates/template_clash.yaml
|
||||
var templateClash string
|
||||
|
||||
func writeTemplate(path string, template string) error {
|
||||
tPath := filepath.Join(
|
||||
"templates", path,
|
||||
)
|
||||
if _, err := os.Stat(tPath); os.IsNotExist(err) {
|
||||
file, err := os.Create(tPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func(file *os.File) {
|
||||
_ = file.Close()
|
||||
}(file)
|
||||
_, err = file.WriteString(template)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
if err := utils.MKDir("subs"); err != nil {
|
||||
os.Exit(1)
|
||||
var err error
|
||||
// 创建文件夹
|
||||
err = utils.MkEssentialDir()
|
||||
if err != nil {
|
||||
logger.Logger.Panic("create essential dir failed", zap.Error(err))
|
||||
}
|
||||
if err := utils.MKDir("templates"); err != nil {
|
||||
os.Exit(1)
|
||||
// 加载配置
|
||||
err = config.LoadConfig()
|
||||
// 初始化日志
|
||||
logger.InitLogger(config.Default.LogLevel)
|
||||
if err != nil {
|
||||
logger.Logger.Panic("load config failed", zap.Error(err))
|
||||
}
|
||||
if err := writeTemplate(config.Default.MetaTemplate, templateMeta); err != nil {
|
||||
os.Exit(1)
|
||||
// 检查更新
|
||||
if config.Dev != "true" {
|
||||
go func() {
|
||||
update, newVersion, err := utils.CheckUpdate()
|
||||
if err != nil {
|
||||
logger.Logger.Warn("check update failed", zap.Error(err))
|
||||
}
|
||||
if err := writeTemplate(config.Default.ClashTemplate, templateClash); err != nil {
|
||||
os.Exit(1)
|
||||
if update {
|
||||
logger.Logger.Info("new version is available", zap.String("version", newVersion))
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
logger.Logger.Info("running in dev mode")
|
||||
}
|
||||
// 写入默认模板
|
||||
err = utils.WriteDefalutTemplate(templateMeta, templateClash)
|
||||
if err != nil {
|
||||
logger.Logger.Panic("write default template failed", zap.Error(err))
|
||||
}
|
||||
// 连接数据库
|
||||
err = database.ConnectDB()
|
||||
if err != nil {
|
||||
logger.Logger.Panic("database connect failed", zap.Error(err))
|
||||
}
|
||||
logger.Logger.Info("database connect success")
|
||||
}
|
||||
|
||||
func main() {
|
||||
@ -64,10 +69,10 @@ func main() {
|
||||
r := gin.Default()
|
||||
// 设置路由
|
||||
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))
|
||||
if err != nil {
|
||||
logger.Logger.Error("Server run error", zap.Error(err))
|
||||
logger.Logger.Error("server running failed", zap.Error(err))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
29
model/clash.go
Normal file
29
model/clash.go
Normal file
@ -0,0 +1,29 @@
|
||||
package model
|
||||
|
||||
type ClashType int
|
||||
|
||||
const (
|
||||
Clash ClashType = 1 + iota
|
||||
ClashMeta
|
||||
)
|
||||
|
||||
func GetSupportProxyTypes(clashType ClashType) map[string]bool {
|
||||
if clashType == Clash {
|
||||
return map[string]bool{
|
||||
"ss": true,
|
||||
"ssr": true,
|
||||
"vmess": true,
|
||||
"trojan": true,
|
||||
}
|
||||
}
|
||||
if clashType == ClashMeta {
|
||||
return map[string]bool{
|
||||
"ss": true,
|
||||
"ssr": true,
|
||||
"vmess": true,
|
||||
"trojan": true,
|
||||
"vless": true,
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
12
model/github.go
Normal file
12
model/github.go
Normal file
@ -0,0 +1,12 @@
|
||||
package model
|
||||
|
||||
type Tags []struct {
|
||||
Name string `json:"name"`
|
||||
ZipballUrl string `json:"zipball_url"`
|
||||
TarballUrl string `json:"tarball_url"`
|
||||
Commit struct {
|
||||
Sha string `json:"sha"`
|
||||
Url string `json:"url"`
|
||||
}
|
||||
NodeId string `json:"node_id"`
|
||||
}
|
@ -1,51 +1,9 @@
|
||||
package model
|
||||
|
||||
type PluginOptsStruct struct {
|
||||
Mode string `yaml:"mode"`
|
||||
}
|
||||
|
||||
type SmuxStruct struct {
|
||||
Enabled bool `yaml:"enable"`
|
||||
}
|
||||
|
||||
type HeaderStruct struct {
|
||||
Host string `yaml:"Host"`
|
||||
}
|
||||
|
||||
type WSOptsStruct struct {
|
||||
Path string `yaml:"path,omitempty"`
|
||||
Headers HeaderStruct `yaml:"headers,omitempty"`
|
||||
MaxEarlyData int `yaml:"max-early-data,omitempty"`
|
||||
EarlyDataHeaderName string `yaml:"early-data-header-name,omitempty"`
|
||||
}
|
||||
|
||||
type Vmess struct {
|
||||
V string `json:"v"`
|
||||
Ps string `json:"ps"`
|
||||
Add string `json:"add"`
|
||||
Port string `json:"port"`
|
||||
Id string `json:"id"`
|
||||
Aid string `json:"aid"`
|
||||
Scy string `json:"scy"`
|
||||
Net string `json:"net"`
|
||||
Type string `json:"type"`
|
||||
Host string `json:"host"`
|
||||
Path string `json:"path"`
|
||||
Tls string `json:"tls"`
|
||||
Sni string `json:"sni"`
|
||||
Alpn string `json:"alpn"`
|
||||
Fp string `json:"fp"`
|
||||
}
|
||||
|
||||
type GRPCOptsStruct struct {
|
||||
GRPCServiceName string `yaml:"grpc-service-name,omitempty"`
|
||||
}
|
||||
|
||||
type RealityOptsStruct struct {
|
||||
PublicKey string `yaml:"public-key,omitempty"`
|
||||
ShortId string `yaml:"short-id,omitempty"`
|
||||
}
|
||||
|
||||
type Proxy struct {
|
||||
Name string `yaml:"name,omitempty"`
|
||||
Server string `yaml:"server,omitempty"`
|
||||
@ -59,10 +17,8 @@ type Proxy struct {
|
||||
Flow string `yaml:"flow,omitempty"`
|
||||
TLS bool `yaml:"tls,omitempty"`
|
||||
ClientFingerprint string `yaml:"client-fingerprint,omitempty"`
|
||||
UdpOverTcp bool `yaml:"udp-over-tcp,omitempty"`
|
||||
UdpOverTcpVersion string `yaml:"udp-over-tcp-version,omitempty"`
|
||||
Plugin string `yaml:"plugin,omitempty"`
|
||||
PluginOpts PluginOptsStruct `yaml:"plugin-opts,omitempty"`
|
||||
PluginOpts map[string]any `yaml:"plugin-opts,omitempty"`
|
||||
Smux SmuxStruct `yaml:"smux,omitempty"`
|
||||
Sni string `yaml:"sni,omitempty"`
|
||||
AllowInsecure bool `yaml:"allow-insecure,omitempty"`
|
||||
@ -71,13 +27,38 @@ type Proxy struct {
|
||||
Alpn []string `yaml:"alpn,omitempty"`
|
||||
XUDP bool `yaml:"xudp,omitempty"`
|
||||
Servername string `yaml:"servername,omitempty"`
|
||||
WSOpts WSOptsStruct `yaml:"ws-opts,omitempty"`
|
||||
AlterID string `yaml:"alterId,omitempty"`
|
||||
GRPCOpts GRPCOptsStruct `yaml:"grpc-opts,omitempty"`
|
||||
RealityOpts RealityOptsStruct `yaml:"reality-opts,omitempty"`
|
||||
WSOpts WSOptions `yaml:"ws-opts,omitempty"`
|
||||
AlterID int `yaml:"alterId,omitempty"`
|
||||
GrpcOpts GrpcOptions `yaml:"grpc-opts,omitempty"`
|
||||
RealityOpts RealityOptions `yaml:"reality-opts,omitempty"`
|
||||
Protocol string `yaml:"protocol,omitempty"`
|
||||
Obfs string `yaml:"obfs,omitempty"`
|
||||
ObfsParam string `yaml:"obfs-param,omitempty"`
|
||||
ProtocolParam string `yaml:"protocol-param,omitempty"`
|
||||
Remarks []string `yaml:"remarks,omitempty"`
|
||||
HTTPOpts HTTPOptions `yaml:"http-opts,omitempty"`
|
||||
HTTP2Opts HTTP2Options `yaml:"h2-opts,omitempty"`
|
||||
PacketAddr bool `yaml:"packet-addr,omitempty"`
|
||||
PacketEncoding string `yaml:"packet-encoding,omitempty"`
|
||||
GlobalPadding bool `yaml:"global-padding,omitempty"`
|
||||
AuthenticatedLength bool `yaml:"authenticated-length,omitempty"`
|
||||
UDPOverTCP bool `yaml:"udp-over-tcp,omitempty"`
|
||||
UDPOverTCPVersion int `yaml:"udp-over-tcp-version,omitempty"`
|
||||
SubName string `yaml:"-"`
|
||||
}
|
||||
|
||||
func (p Proxy) MarshalYAML() (interface{}, error) {
|
||||
switch p.Type {
|
||||
case "vmess":
|
||||
return ProxyToVmess(p), nil
|
||||
case "ss":
|
||||
return ProxyToShadowSocks(p), nil
|
||||
case "ssr":
|
||||
return ProxyToShadowSocksR(p), nil
|
||||
case "vless":
|
||||
return ProxyToVless(p), nil
|
||||
case "trojan":
|
||||
return ProxyToTrojan(p), nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
@ -17,6 +17,44 @@ type ProxyGroup struct {
|
||||
Size int `yaml:"-"`
|
||||
}
|
||||
|
||||
type SelectProxyGroup struct {
|
||||
Name string `yaml:"name,omitempty"`
|
||||
Type string `yaml:"type,omitempty"`
|
||||
Proxies []string `yaml:"proxies,omitempty"`
|
||||
}
|
||||
|
||||
type UrlTestProxyGroup struct {
|
||||
Name string `yaml:"name,omitempty"`
|
||||
Type string `yaml:"type,omitempty"`
|
||||
Proxies []string `yaml:"proxies,omitempty"`
|
||||
Url string `yaml:"url,omitempty"`
|
||||
Interval int `yaml:"interval,omitempty"`
|
||||
Tolerance int `yaml:"tolerance,omitempty"`
|
||||
Lazy bool `yaml:"lazy"`
|
||||
}
|
||||
|
||||
func (p ProxyGroup) MarshalYAML() (interface{}, error) {
|
||||
switch p.Type {
|
||||
case "select":
|
||||
return SelectProxyGroup{
|
||||
Name: p.Name,
|
||||
Type: p.Type,
|
||||
Proxies: p.Proxies,
|
||||
}, nil
|
||||
case "url-test":
|
||||
return UrlTestProxyGroup{
|
||||
Name: p.Name,
|
||||
Type: p.Type,
|
||||
Proxies: p.Proxies,
|
||||
Url: p.Url,
|
||||
Interval: p.Interval,
|
||||
Tolerance: p.Tolerance,
|
||||
Lazy: p.Lazy,
|
||||
}, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type ProxyGroupsSortByName []ProxyGroup
|
||||
type ProxyGroupsSortBySize []ProxyGroup
|
||||
|
||||
@ -39,7 +77,6 @@ func (p ProxyGroupsSortByName) Less(i, j int) bool {
|
||||
bestMatch, _, _ := matcher.Match(language.Make("zh"))
|
||||
// 使用最佳匹配的语言进行排序
|
||||
c := collate.New(bestMatch)
|
||||
|
||||
return c.CompareString(p[i].Name, p[j].Name) < 0
|
||||
}
|
||||
|
||||
|
33
model/proxy_shadowsocks.go
Normal file
33
model/proxy_shadowsocks.go
Normal file
@ -0,0 +1,33 @@
|
||||
package model
|
||||
|
||||
type ShadowSocks struct {
|
||||
Type string `yaml:"type"`
|
||||
Name string `yaml:"name"`
|
||||
Server string `yaml:"server"`
|
||||
Port int `yaml:"port"`
|
||||
Password string `yaml:"password"`
|
||||
Cipher string `yaml:"cipher"`
|
||||
UDP bool `yaml:"udp,omitempty"`
|
||||
Plugin string `yaml:"plugin,omitempty"`
|
||||
PluginOpts map[string]any `yaml:"plugin-opts,omitempty"`
|
||||
UDPOverTCP bool `yaml:"udp-over-tcp,omitempty"`
|
||||
UDPOverTCPVersion int `yaml:"udp-over-tcp-version,omitempty"`
|
||||
ClientFingerprint string `yaml:"client-fingerprint,omitempty"`
|
||||
}
|
||||
|
||||
func ProxyToShadowSocks(p Proxy) ShadowSocks {
|
||||
return ShadowSocks{
|
||||
Type: "ss",
|
||||
Name: p.Name,
|
||||
Server: p.Server,
|
||||
Port: p.Port,
|
||||
Password: p.Password,
|
||||
Cipher: p.Cipher,
|
||||
UDP: p.UDP,
|
||||
Plugin: p.Plugin,
|
||||
PluginOpts: p.PluginOpts,
|
||||
UDPOverTCP: p.UDPOverTCP,
|
||||
UDPOverTCPVersion: p.UDPOverTCPVersion,
|
||||
ClientFingerprint: p.ClientFingerprint,
|
||||
}
|
||||
}
|
31
model/proxy_shadowsocksr.go
Normal file
31
model/proxy_shadowsocksr.go
Normal file
@ -0,0 +1,31 @@
|
||||
package model
|
||||
|
||||
type ShadowSocksR struct {
|
||||
Type string `yaml:"type"`
|
||||
Name string `yaml:"name"`
|
||||
Server string `yaml:"server"`
|
||||
Port int `yaml:"port"`
|
||||
Password string `yaml:"password"`
|
||||
Cipher string `yaml:"cipher"`
|
||||
Obfs string `yaml:"obfs"`
|
||||
ObfsParam string `yaml:"obfs-param,omitempty"`
|
||||
Protocol string `yaml:"protocol"`
|
||||
ProtocolParam string `yaml:"protocol-param,omitempty"`
|
||||
UDP bool `yaml:"udp,omitempty"`
|
||||
}
|
||||
|
||||
func ProxyToShadowSocksR(p Proxy) ShadowSocksR {
|
||||
return ShadowSocksR{
|
||||
Type: "ssr",
|
||||
Name: p.Name,
|
||||
Server: p.Server,
|
||||
Port: p.Port,
|
||||
Password: p.Password,
|
||||
Cipher: p.Cipher,
|
||||
Obfs: p.Obfs,
|
||||
ObfsParam: p.ObfsParam,
|
||||
Protocol: p.Protocol,
|
||||
ProtocolParam: p.ProtocolParam,
|
||||
UDP: p.UDP,
|
||||
}
|
||||
}
|
39
model/proxy_trojan.go
Normal file
39
model/proxy_trojan.go
Normal file
@ -0,0 +1,39 @@
|
||||
package model
|
||||
|
||||
type Trojan struct {
|
||||
Type string `yaml:"type"`
|
||||
Name string `yaml:"name"`
|
||||
Server string `yaml:"server"`
|
||||
Port int `yaml:"port"`
|
||||
Password string `yaml:"password"`
|
||||
ALPN []string `yaml:"alpn,omitempty"`
|
||||
SNI string `yaml:"sni,omitempty"`
|
||||
SkipCertVerify bool `yaml:"skip-cert-verify,omitempty"`
|
||||
Fingerprint string `yaml:"fingerprint,omitempty"`
|
||||
UDP bool `yaml:"udp,omitempty"`
|
||||
Network string `yaml:"network,omitempty"`
|
||||
RealityOpts RealityOptions `yaml:"reality-opts,omitempty"`
|
||||
GrpcOpts GrpcOptions `yaml:"grpc-opts,omitempty"`
|
||||
WSOpts WSOptions `yaml:"ws-opts,omitempty"`
|
||||
ClientFingerprint string `yaml:"client-fingerprint,omitempty"`
|
||||
}
|
||||
|
||||
func ProxyToTrojan(p Proxy) Trojan {
|
||||
return Trojan{
|
||||
Type: "trojan",
|
||||
Name: p.Name,
|
||||
Server: p.Server,
|
||||
Port: p.Port,
|
||||
Password: p.Password,
|
||||
ALPN: p.Alpn,
|
||||
SNI: p.Sni,
|
||||
SkipCertVerify: p.SkipCertVerify,
|
||||
Fingerprint: p.Fingerprint,
|
||||
UDP: p.UDP,
|
||||
Network: p.Network,
|
||||
RealityOpts: p.RealityOpts,
|
||||
GrpcOpts: p.GrpcOpts,
|
||||
WSOpts: p.WSOpts,
|
||||
ClientFingerprint: p.ClientFingerprint,
|
||||
}
|
||||
}
|
57
model/proxy_vless.go
Normal file
57
model/proxy_vless.go
Normal file
@ -0,0 +1,57 @@
|
||||
package model
|
||||
|
||||
type Vless struct {
|
||||
Type string `yaml:"type"`
|
||||
Name string `yaml:"name"`
|
||||
Server string `yaml:"server"`
|
||||
Port int `yaml:"port"`
|
||||
UUID string `yaml:"uuid"`
|
||||
Flow string `yaml:"flow,omitempty"`
|
||||
TLS bool `yaml:"tls,omitempty"`
|
||||
ALPN []string `yaml:"alpn,omitempty"`
|
||||
UDP bool `yaml:"udp,omitempty"`
|
||||
PacketAddr bool `yaml:"packet-addr,omitempty"`
|
||||
XUDP bool `yaml:"xudp,omitempty"`
|
||||
PacketEncoding string `yaml:"packet-encoding,omitempty"`
|
||||
Network string `yaml:"network,omitempty"`
|
||||
RealityOpts RealityOptions `yaml:"reality-opts,omitempty"`
|
||||
HTTPOpts HTTPOptions `yaml:"http-opts,omitempty"`
|
||||
HTTP2Opts HTTP2Options `yaml:"h2-opts,omitempty"`
|
||||
GrpcOpts GrpcOptions `yaml:"grpc-opts,omitempty"`
|
||||
WSOpts WSOptions `yaml:"ws-opts,omitempty"`
|
||||
WSPath string `yaml:"ws-path,omitempty"`
|
||||
WSHeaders map[string]string `yaml:"ws-headers,omitempty"`
|
||||
SkipCertVerify bool `yaml:"skip-cert-verify,omitempty"`
|
||||
Fingerprint string `yaml:"fingerprint,omitempty"`
|
||||
ServerName string `yaml:"servername,omitempty"`
|
||||
ClientFingerprint string `yaml:"client-fingerprint,omitempty"`
|
||||
}
|
||||
|
||||
func ProxyToVless(p Proxy) Vless {
|
||||
return Vless{
|
||||
Type: "vless",
|
||||
Name: p.Name,
|
||||
Server: p.Server,
|
||||
Port: p.Port,
|
||||
UUID: p.UUID,
|
||||
Flow: p.Flow,
|
||||
TLS: p.TLS,
|
||||
ALPN: p.Alpn,
|
||||
UDP: p.UDP,
|
||||
PacketAddr: p.PacketAddr,
|
||||
XUDP: p.XUDP,
|
||||
PacketEncoding: p.PacketEncoding,
|
||||
Network: p.Network,
|
||||
RealityOpts: p.RealityOpts,
|
||||
HTTPOpts: p.HTTPOpts,
|
||||
HTTP2Opts: p.HTTP2Opts,
|
||||
GrpcOpts: p.GrpcOpts,
|
||||
WSOpts: p.WSOpts,
|
||||
WSPath: p.WSOpts.Path,
|
||||
WSHeaders: p.WSOpts.Headers,
|
||||
SkipCertVerify: p.SkipCertVerify,
|
||||
Fingerprint: p.Fingerprint,
|
||||
ServerName: p.Servername,
|
||||
ClientFingerprint: p.ClientFingerprint,
|
||||
}
|
||||
}
|
104
model/proxy_vmess.go
Normal file
104
model/proxy_vmess.go
Normal file
@ -0,0 +1,104 @@
|
||||
package model
|
||||
|
||||
type HTTPOptions struct {
|
||||
Method string `proxy:"method,omitempty"`
|
||||
Path []string `proxy:"path,omitempty"`
|
||||
Headers map[string][]string `proxy:"headers,omitempty"`
|
||||
}
|
||||
|
||||
type HTTP2Options struct {
|
||||
Host []string `proxy:"host,omitempty"`
|
||||
Path string `proxy:"path,omitempty"`
|
||||
}
|
||||
|
||||
type GrpcOptions struct {
|
||||
GrpcServiceName string `proxy:"grpc-service-name,omitempty"`
|
||||
}
|
||||
|
||||
type RealityOptions struct {
|
||||
PublicKey string `proxy:"public-key"`
|
||||
ShortID string `proxy:"short-id"`
|
||||
}
|
||||
|
||||
type WSOptions struct {
|
||||
Path string `proxy:"path,omitempty"`
|
||||
Headers map[string]string `proxy:"headers,omitempty"`
|
||||
MaxEarlyData int `proxy:"max-early-data,omitempty"`
|
||||
EarlyDataHeaderName string `proxy:"early-data-header-name,omitempty"`
|
||||
}
|
||||
|
||||
type VmessJson struct {
|
||||
V string `json:"v"`
|
||||
Ps string `json:"ps"`
|
||||
Add string `json:"add"`
|
||||
Port interface{} `json:"port"`
|
||||
Id string `json:"id"`
|
||||
Aid interface{} `json:"aid"`
|
||||
Scy string `json:"scy"`
|
||||
Net string `json:"net"`
|
||||
Type string `json:"type"`
|
||||
Host string `json:"host"`
|
||||
Path string `json:"path"`
|
||||
Tls string `json:"tls"`
|
||||
Sni string `json:"sni"`
|
||||
Alpn string `json:"alpn"`
|
||||
Fp string `json:"fp"`
|
||||
}
|
||||
|
||||
type Vmess struct {
|
||||
Type string `yaml:"type"`
|
||||
Name string `yaml:"name"`
|
||||
Server string `yaml:"server"`
|
||||
Port int `yaml:"port"`
|
||||
UUID string `yaml:"uuid"`
|
||||
AlterID int `yaml:"alterId"`
|
||||
Cipher string `yaml:"cipher"`
|
||||
UDP bool `yaml:"udp,omitempty"`
|
||||
Network string `yaml:"network,omitempty"`
|
||||
TLS bool `yaml:"tls,omitempty"`
|
||||
ALPN []string `yaml:"alpn,omitempty"`
|
||||
SkipCertVerify bool `yaml:"skip-cert-verify,omitempty"`
|
||||
Fingerprint string `yaml:"fingerprint,omitempty"`
|
||||
ServerName string `yaml:"servername,omitempty"`
|
||||
RealityOpts RealityOptions `yaml:"reality-opts,omitempty"`
|
||||
HTTPOpts HTTPOptions `yaml:"http-opts,omitempty"`
|
||||
HTTP2Opts HTTP2Options `yaml:"h2-opts,omitempty"`
|
||||
GrpcOpts GrpcOptions `yaml:"grpc-opts,omitempty"`
|
||||
WSOpts WSOptions `yaml:"ws-opts,omitempty"`
|
||||
PacketAddr bool `yaml:"packet-addr,omitempty"`
|
||||
XUDP bool `yaml:"xudp,omitempty"`
|
||||
PacketEncoding string `yaml:"packet-encoding,omitempty"`
|
||||
GlobalPadding bool `yaml:"global-padding,omitempty"`
|
||||
AuthenticatedLength bool `yaml:"authenticated-length,omitempty"`
|
||||
ClientFingerprint string `yaml:"client-fingerprint,omitempty"`
|
||||
}
|
||||
|
||||
func ProxyToVmess(p Proxy) Vmess {
|
||||
return Vmess{
|
||||
Type: "vmess",
|
||||
Name: p.Name,
|
||||
Server: p.Server,
|
||||
Port: p.Port,
|
||||
UUID: p.UUID,
|
||||
AlterID: p.AlterID,
|
||||
Cipher: p.Cipher,
|
||||
UDP: p.UDP,
|
||||
Network: p.Network,
|
||||
TLS: p.TLS,
|
||||
ALPN: p.Alpn,
|
||||
SkipCertVerify: p.SkipCertVerify,
|
||||
Fingerprint: p.Fingerprint,
|
||||
ServerName: p.Servername,
|
||||
RealityOpts: p.RealityOpts,
|
||||
HTTPOpts: p.HTTPOpts,
|
||||
HTTP2Opts: p.HTTP2Opts,
|
||||
GrpcOpts: p.GrpcOpts,
|
||||
WSOpts: p.WSOpts,
|
||||
PacketAddr: p.PacketAddr,
|
||||
XUDP: p.XUDP,
|
||||
PacketEncoding: p.PacketEncoding,
|
||||
GlobalPadding: p.GlobalPadding,
|
||||
AuthenticatedLength: p.AuthenticatedLength,
|
||||
ClientFingerprint: p.ClientFingerprint,
|
||||
}
|
||||
}
|
13
model/rule_provider.go
Normal file
13
model/rule_provider.go
Normal file
@ -0,0 +1,13 @@
|
||||
package model
|
||||
|
||||
type RuleProvider struct {
|
||||
Type string `yaml:"type,omitempty"`
|
||||
Behavior string `yaml:"behavior,omitempty"`
|
||||
Url string `yaml:"url,omitempty"`
|
||||
Path string `yaml:"path,omitempty"`
|
||||
Interval int `yaml:"interval,omitempty"`
|
||||
}
|
||||
|
||||
type Payload struct {
|
||||
Rules []string `yaml:"payload,omitempty"`
|
||||
}
|
8
model/short_link.go
Normal file
8
model/short_link.go
Normal file
@ -0,0 +1,8 @@
|
||||
package model
|
||||
|
||||
type ShortLink struct {
|
||||
Hash string `gorm:"primary_key"`
|
||||
Url string
|
||||
Password string
|
||||
LastRequestTime int64
|
||||
}
|
12
model/sub.go
12
model/sub.go
@ -13,14 +13,6 @@ type Subscription struct {
|
||||
RuleProviders map[string]RuleProvider `yaml:"rule-providers,omitempty,omitempty"`
|
||||
}
|
||||
|
||||
type RuleProvider struct {
|
||||
Type string `yaml:"type,omitempty"`
|
||||
Behavior string `yaml:"behavior,omitempty"`
|
||||
Url string `yaml:"url,omitempty"`
|
||||
Path string `yaml:"path,omitempty"`
|
||||
Interval int `yaml:"interval,omitempty"`
|
||||
}
|
||||
|
||||
type Payload struct {
|
||||
Rules []string `yaml:"payload,omitempty"`
|
||||
type NodeList struct {
|
||||
Proxies []Proxy `yaml:"proxies,omitempty"`
|
||||
}
|
||||
|
@ -2,9 +2,14 @@ package parser
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func DecodeBase64(s string) (string, error) {
|
||||
s = strings.TrimSpace(s)
|
||||
if len(s)%4 != 0 {
|
||||
s += strings.Repeat("=", 4-len(s)%4)
|
||||
}
|
||||
decodeStr, err := base64.StdEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
return "", err
|
||||
|
16
parser/ss.go
16
parser/ss.go
@ -1,7 +1,7 @@
|
||||
package parser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"errors"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
@ -12,35 +12,35 @@ import (
|
||||
func ParseSS(proxy string) (model.Proxy, error) {
|
||||
// 判断是否以 ss:// 开头
|
||||
if !strings.HasPrefix(proxy, "ss://") {
|
||||
return model.Proxy{}, fmt.Errorf("无效的 ss Url")
|
||||
return model.Proxy{}, errors.New("invalid ss Url")
|
||||
}
|
||||
// 分割
|
||||
parts := strings.SplitN(strings.TrimPrefix(proxy, "ss://"), "@", 2)
|
||||
if len(parts) != 2 {
|
||||
return model.Proxy{}, fmt.Errorf("无效的 ss Url")
|
||||
return model.Proxy{}, errors.New("invalid ss Url")
|
||||
}
|
||||
if !strings.Contains(parts[0], ":") {
|
||||
// 解码
|
||||
decoded, err := DecodeBase64(parts[0])
|
||||
if err != nil {
|
||||
return model.Proxy{}, err
|
||||
return model.Proxy{}, errors.New("invalid ss Url" + err.Error())
|
||||
}
|
||||
parts[0] = decoded
|
||||
}
|
||||
credentials := strings.SplitN(parts[0], ":", 2)
|
||||
if len(credentials) != 2 {
|
||||
return model.Proxy{}, fmt.Errorf("无效的 ss 凭证")
|
||||
return model.Proxy{}, errors.New("invalid ss Url")
|
||||
}
|
||||
// 分割
|
||||
serverInfo := strings.SplitN(parts[1], "#", 2)
|
||||
serverAndPort := strings.SplitN(serverInfo[0], ":", 2)
|
||||
if len(serverAndPort) != 2 {
|
||||
return model.Proxy{}, fmt.Errorf("无效的 ss 服务器和端口")
|
||||
return model.Proxy{}, errors.New("invalid ss Url")
|
||||
}
|
||||
// 转换端口字符串为数字
|
||||
port, err := strconv.Atoi(strings.TrimSpace(serverAndPort[1]))
|
||||
if err != nil {
|
||||
return model.Proxy{}, err
|
||||
return model.Proxy{}, errors.New("invalid ss Url" + err.Error())
|
||||
}
|
||||
// 返回结果
|
||||
result := model.Proxy{
|
||||
@ -56,7 +56,7 @@ func ParseSS(proxy string) (model.Proxy, error) {
|
||||
if len(serverInfo) == 2 {
|
||||
unescape, err := url.QueryUnescape(serverInfo[1])
|
||||
if err != nil {
|
||||
return model.Proxy{}, err
|
||||
return model.Proxy{}, errors.New("invalid ss Url" + err.Error())
|
||||
}
|
||||
result.Name = strings.TrimSpace(unescape)
|
||||
} else {
|
||||
|
@ -11,9 +11,10 @@ import (
|
||||
func ParseShadowsocksR(proxy string) (model.Proxy, error) {
|
||||
// 判断是否以 ssr:// 开头
|
||||
if !strings.HasPrefix(proxy, "ssr://") {
|
||||
return model.Proxy{}, fmt.Errorf("无效的 ssr Url")
|
||||
return model.Proxy{}, fmt.Errorf("invalid ssr Url")
|
||||
}
|
||||
var err error
|
||||
proxy = strings.TrimPrefix(proxy, "ssr://")
|
||||
if !strings.Contains(proxy, ":") {
|
||||
proxy, err = DecodeBase64(strings.TrimPrefix(proxy, "ssr://"))
|
||||
if err != nil {
|
||||
@ -21,7 +22,7 @@ func ParseShadowsocksR(proxy string) (model.Proxy, error) {
|
||||
}
|
||||
}
|
||||
// 分割
|
||||
detailsAndParams := strings.SplitN(strings.TrimPrefix(proxy, "ssr://"), "/?", 2)
|
||||
detailsAndParams := strings.SplitN(proxy, "/?", 2)
|
||||
parts := strings.Split(detailsAndParams[0], ":")
|
||||
params, err := url.ParseQuery(detailsAndParams[1])
|
||||
if err != nil {
|
||||
@ -32,7 +33,21 @@ func ParseShadowsocksR(proxy string) (model.Proxy, error) {
|
||||
if err != nil {
|
||||
return model.Proxy{}, err
|
||||
}
|
||||
var obfsParam string
|
||||
var protoParam string
|
||||
var remarks string
|
||||
if params.Get("obfsparam") != "" {
|
||||
obfsParam, err = DecodeBase64(params.Get("obfsparam"))
|
||||
}
|
||||
if params.Get("protoparam") != "" {
|
||||
protoParam, err = DecodeBase64(params.Get("protoparam"))
|
||||
}
|
||||
if params.Get("remarks") != "" {
|
||||
remarks, err = DecodeBase64(params.Get("remarks"))
|
||||
}
|
||||
|
||||
result := model.Proxy{
|
||||
Name: remarks,
|
||||
Type: "ssr",
|
||||
Server: parts[0],
|
||||
Port: port,
|
||||
@ -40,8 +55,13 @@ func ParseShadowsocksR(proxy string) (model.Proxy, error) {
|
||||
Cipher: parts[3],
|
||||
Obfs: parts[4],
|
||||
Password: parts[5],
|
||||
ObfsParam: params.Get("obfsparam"),
|
||||
ProtocolParam: params.Get("protoparam"),
|
||||
ObfsParam: obfsParam,
|
||||
ProtocolParam: protoParam,
|
||||
}
|
||||
|
||||
if result.Name == "" {
|
||||
result.Name = result.Server
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
@ -11,12 +11,12 @@ import (
|
||||
func ParseTrojan(proxy string) (model.Proxy, error) {
|
||||
// 判断是否以 trojan:// 开头
|
||||
if !strings.HasPrefix(proxy, "trojan://") {
|
||||
return model.Proxy{}, fmt.Errorf("无效的 trojan Url")
|
||||
return model.Proxy{}, fmt.Errorf("invalid trojan Url")
|
||||
}
|
||||
// 分割
|
||||
parts := strings.SplitN(strings.TrimPrefix(proxy, "trojan://"), "@", 2)
|
||||
if len(parts) != 2 {
|
||||
return model.Proxy{}, fmt.Errorf("无效的 trojan Url")
|
||||
return model.Proxy{}, fmt.Errorf("invalid trojan Url")
|
||||
}
|
||||
// 分割
|
||||
serverInfo := strings.SplitN(parts[1], "#", 2)
|
||||
@ -27,7 +27,7 @@ func ParseTrojan(proxy string) (model.Proxy, error) {
|
||||
return model.Proxy{}, err
|
||||
}
|
||||
if len(serverAndPort) != 2 {
|
||||
return model.Proxy{}, fmt.Errorf("无效的 trojan 服务器和端口")
|
||||
return model.Proxy{}, fmt.Errorf("invalid trojan")
|
||||
}
|
||||
// 处理端口
|
||||
port, err := strconv.Atoi(strings.TrimSpace(serverAndPort[1]))
|
||||
|
@ -11,12 +11,12 @@ import (
|
||||
func ParseVless(proxy string) (model.Proxy, error) {
|
||||
// 判断是否以 vless:// 开头
|
||||
if !strings.HasPrefix(proxy, "vless://") {
|
||||
return model.Proxy{}, fmt.Errorf("无效的 vless Url")
|
||||
return model.Proxy{}, fmt.Errorf("invalid vless Url")
|
||||
}
|
||||
// 分割
|
||||
parts := strings.SplitN(strings.TrimPrefix(proxy, "vless://"), "@", 2)
|
||||
if len(parts) != 2 {
|
||||
return model.Proxy{}, fmt.Errorf("无效的 vless Url")
|
||||
return model.Proxy{}, fmt.Errorf("invalid vless Url")
|
||||
}
|
||||
// 分割
|
||||
serverInfo := strings.SplitN(parts[1], "#", 2)
|
||||
@ -27,7 +27,7 @@ func ParseVless(proxy string) (model.Proxy, error) {
|
||||
return model.Proxy{}, err
|
||||
}
|
||||
if len(serverAndPort) != 2 {
|
||||
return model.Proxy{}, fmt.Errorf("无效的 vless 服务器和端口")
|
||||
return model.Proxy{}, fmt.Errorf("invalid vless")
|
||||
}
|
||||
// 处理端口
|
||||
port, err := strconv.Atoi(strings.TrimSpace(serverAndPort[1]))
|
||||
@ -47,7 +47,7 @@ func ParseVless(proxy string) (model.Proxy, error) {
|
||||
Flow: params.Get("flow"),
|
||||
Fingerprint: params.Get("fp"),
|
||||
Servername: params.Get("sni"),
|
||||
RealityOpts: model.RealityOptsStruct{
|
||||
RealityOpts: model.RealityOptions{
|
||||
PublicKey: params.Get("pbk"),
|
||||
},
|
||||
}
|
||||
@ -55,16 +55,16 @@ func ParseVless(proxy string) (model.Proxy, error) {
|
||||
result.Alpn = strings.Split(params.Get("alpn"), ",")
|
||||
}
|
||||
if params.Get("type") == "ws" {
|
||||
result.WSOpts = model.WSOptsStruct{
|
||||
result.WSOpts = model.WSOptions{
|
||||
Path: params.Get("path"),
|
||||
Headers: model.HeaderStruct{
|
||||
Host: params.Get("host"),
|
||||
Headers: map[string]string{
|
||||
"Host": params.Get("host"),
|
||||
},
|
||||
}
|
||||
}
|
||||
if params.Get("type") == "grpc" {
|
||||
result.GRPCOpts = model.GRPCOptsStruct{
|
||||
GRPCServiceName: params.Get("serviceName"),
|
||||
result.GrpcOpts = model.GrpcOptions{
|
||||
GrpcServiceName: params.Get("serviceName"),
|
||||
}
|
||||
}
|
||||
// 如果有节点名称
|
||||
|
@ -3,7 +3,6 @@ package parser
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sub2clash/model"
|
||||
@ -12,24 +11,42 @@ import (
|
||||
func ParseVmess(proxy string) (model.Proxy, error) {
|
||||
// 判断是否以 vmess:// 开头
|
||||
if !strings.HasPrefix(proxy, "vmess://") {
|
||||
return model.Proxy{}, fmt.Errorf("无效的 vmess Url")
|
||||
return model.Proxy{}, errors.New("invalid vmess url")
|
||||
}
|
||||
// 解码
|
||||
base64, err := DecodeBase64(strings.TrimPrefix(proxy, "vmess://"))
|
||||
if err != nil {
|
||||
return model.Proxy{}, errors.New("无效的 vmess Url")
|
||||
return model.Proxy{}, errors.New("invalid vmess url" + err.Error())
|
||||
}
|
||||
// 解析
|
||||
var vmess model.Vmess
|
||||
var vmess model.VmessJson
|
||||
err = json.Unmarshal([]byte(base64), &vmess)
|
||||
if err != nil {
|
||||
return model.Proxy{}, errors.New("无效的 vmess Url")
|
||||
return model.Proxy{}, errors.New("invalid vmess url" + err.Error())
|
||||
}
|
||||
// 处理端口
|
||||
port, err := strconv.Atoi(strings.TrimSpace(vmess.Port))
|
||||
// 解析端口
|
||||
port := 0
|
||||
switch vmess.Port.(type) {
|
||||
case string:
|
||||
port, err = strconv.Atoi(vmess.Port.(string))
|
||||
if err != nil {
|
||||
return model.Proxy{}, errors.New("无效的 vmess Url")
|
||||
return model.Proxy{}, errors.New("invalid vmess url" + err.Error())
|
||||
}
|
||||
case float64:
|
||||
port = int(vmess.Port.(float64))
|
||||
}
|
||||
// 解析Aid
|
||||
aid := 0
|
||||
switch vmess.Aid.(type) {
|
||||
case string:
|
||||
aid, err = strconv.Atoi(vmess.Aid.(string))
|
||||
if err != nil {
|
||||
return model.Proxy{}, errors.New("invalid vmess url" + err.Error())
|
||||
}
|
||||
case float64:
|
||||
aid = int(vmess.Aid.(float64))
|
||||
}
|
||||
// 设置默认值
|
||||
if vmess.Scy == "" {
|
||||
vmess.Scy = "auto"
|
||||
}
|
||||
@ -46,7 +63,7 @@ func ParseVmess(proxy string) (model.Proxy, error) {
|
||||
Server: vmess.Add,
|
||||
Port: port,
|
||||
UUID: vmess.Id,
|
||||
AlterID: vmess.Aid,
|
||||
AlterID: aid,
|
||||
Cipher: vmess.Scy,
|
||||
UDP: true,
|
||||
TLS: vmess.Tls == "tls",
|
||||
@ -57,10 +74,10 @@ func ParseVmess(proxy string) (model.Proxy, error) {
|
||||
Network: vmess.Net,
|
||||
}
|
||||
if vmess.Net == "ws" {
|
||||
result.WSOpts = model.WSOptsStruct{
|
||||
result.WSOpts = model.WSOptions{
|
||||
Path: vmess.Path,
|
||||
Headers: model.HeaderStruct{
|
||||
Host: vmess.Host,
|
||||
Headers: map[string]string{
|
||||
"Host": vmess.Host,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
@ -8,88 +8,104 @@ proxy-groups:
|
||||
- name: 节点选择
|
||||
type: select
|
||||
proxies:
|
||||
- <countries>
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
- name: 手动切换
|
||||
type: select
|
||||
proxies:
|
||||
- <all>
|
||||
- name: 电报消息
|
||||
type: select
|
||||
proxies:
|
||||
- <countries>
|
||||
- 节点选择
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
- name: OpenAi
|
||||
type: select
|
||||
proxies:
|
||||
- <countries>
|
||||
- 节点选择
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
- name: 油管视频
|
||||
type: select
|
||||
proxies:
|
||||
- <countries>
|
||||
- 节点选择
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
- name: 巴哈姆特
|
||||
type: select
|
||||
proxies:
|
||||
- <countries>
|
||||
- 节点选择
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
- name: 哔哩哔哩
|
||||
type: select
|
||||
proxies:
|
||||
- <countries>
|
||||
- 全球直连
|
||||
- name: 国外媒体
|
||||
type: select
|
||||
proxies:
|
||||
- <countries>
|
||||
- 节点选择
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
- name: 国内媒体
|
||||
type: select
|
||||
proxies:
|
||||
- <countries>
|
||||
- DIRECT
|
||||
- 手动切换
|
||||
- name: 谷歌FCM
|
||||
type: select
|
||||
proxies:
|
||||
- <countries>
|
||||
- DIRECT
|
||||
- 节点选择
|
||||
- 手动切换
|
||||
- name: 微软云盘
|
||||
type: select
|
||||
proxies:
|
||||
- <countries>
|
||||
- DIRECT
|
||||
- 节点选择
|
||||
- 手动切换
|
||||
- name: 微软服务
|
||||
type: select
|
||||
proxies:
|
||||
- <countries>
|
||||
- DIRECT
|
||||
- 节点选择
|
||||
- 手动切换
|
||||
- name: 苹果服务
|
||||
type: select
|
||||
proxies:
|
||||
- <countries>
|
||||
- DIRECT
|
||||
- 节点选择
|
||||
- 手动切换
|
||||
- name: 游戏平台
|
||||
type: select
|
||||
proxies:
|
||||
- <countries>
|
||||
- DIRECT
|
||||
- 节点选择
|
||||
- 手动切换
|
||||
- name: 网易音乐
|
||||
type: select
|
||||
proxies:
|
||||
- <countries>
|
||||
- DIRECT
|
||||
- 节点选择
|
||||
- name: 全球直连
|
||||
type: select
|
||||
proxies:
|
||||
- <countries>
|
||||
- DIRECT
|
||||
- 节点选择
|
||||
- name: 广告拦截
|
||||
@ -105,6 +121,7 @@ proxy-groups:
|
||||
- name: 漏网之鱼
|
||||
type: select
|
||||
proxies:
|
||||
- <countries>
|
||||
- 节点选择
|
||||
- DIRECT
|
||||
- 手动切换
|
||||
|
@ -8,34 +8,90 @@ proxy-groups:
|
||||
- name: 节点选择
|
||||
type: select
|
||||
proxies:
|
||||
- <countries>
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
- name: 手动切换
|
||||
type: select
|
||||
proxies:
|
||||
- name: 游戏平台
|
||||
- <all>
|
||||
- name: 游戏平台(中国)
|
||||
type: select
|
||||
proxies:
|
||||
- 节点选择
|
||||
- <countries>
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
- name: 游戏平台(全球)
|
||||
type: select
|
||||
proxies:
|
||||
- 节点选择
|
||||
- <countries>
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
- name: 巴哈姆特
|
||||
type: select
|
||||
proxies:
|
||||
- 节点选择
|
||||
- <countries>
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
- name: 哔哩哔哩
|
||||
type: select
|
||||
proxies:
|
||||
- 节点选择
|
||||
- <countries>
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
- name: 全球直连
|
||||
- name: Telegram
|
||||
type: select
|
||||
proxies:
|
||||
- DIRECT
|
||||
- 节点选择
|
||||
- <countries>
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
- name: OpenAI
|
||||
type: select
|
||||
proxies:
|
||||
- 节点选择
|
||||
- <countries>
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
- name: Youtube
|
||||
type: select
|
||||
proxies:
|
||||
- 节点选择
|
||||
- <countries>
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
- name: Microsoft
|
||||
type: select
|
||||
proxies:
|
||||
- 节点选择
|
||||
- <countries>
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
- name: Onedrive
|
||||
type: select
|
||||
proxies:
|
||||
- 节点选择
|
||||
- <countries>
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
- name: Apple
|
||||
type: select
|
||||
proxies:
|
||||
- 节点选择
|
||||
- <countries>
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
- name: Netflix
|
||||
type: select
|
||||
proxies:
|
||||
- 节点选择
|
||||
- <countries>
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
- name: 广告拦截
|
||||
type: select
|
||||
proxies:
|
||||
@ -45,17 +101,27 @@ proxy-groups:
|
||||
type: select
|
||||
proxies:
|
||||
- 节点选择
|
||||
- <countries>
|
||||
- 手动切换
|
||||
- DIRECT
|
||||
rules:
|
||||
- GEOSITE,private,全球直连
|
||||
- GEOIP,private,全球直连
|
||||
- GEOSITE,private,DIRECT,no-resolve
|
||||
- GEOIP,private,DIRECT
|
||||
- GEOSITE,category-ads-all,广告拦截
|
||||
- GEOSITE,CN,全球直连
|
||||
- GEOIP,CN,全球直连
|
||||
- GEOSITE,biliintl,哔哩哔哩
|
||||
- GEOSITE,microsoft,Microsoft
|
||||
- GEOSITE,apple,Apple
|
||||
- GEOSITE,netflix,Netflix
|
||||
- GEOIP,netflix,Netflix
|
||||
- GEOSITE,onedrive,Onedrive
|
||||
- GEOSITE,youtube,Youtube
|
||||
- GEOSITE,telegram,Telegram
|
||||
- GEOIP,telegram,Telegram
|
||||
- GEOSITE,openai,OpenAI
|
||||
- GEOSITE,bilibili,哔哩哔哩
|
||||
- GEOSITE,bahamut,巴哈姆特
|
||||
- GEOSITE,category-games,游戏平台
|
||||
- GEOSITE,category-games@cn,游戏平台(中国)
|
||||
- GEOSITE,category-games,游戏平台(全球)
|
||||
- GEOSITE,geolocation-!cn,节点选择
|
||||
- GEOSITE,CN,DIRECT
|
||||
- GEOIP,CN,DIRECT
|
||||
- MATCH,漏网之鱼
|
33
utils/check_update.go
Normal file
33
utils/check_update.go
Normal file
@ -0,0 +1,33 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"sub2clash/config"
|
||||
"sub2clash/model"
|
||||
)
|
||||
|
||||
func CheckUpdate() (bool, string, error) {
|
||||
get, err := Get("https://api.github.com/repos/nitezs/sub2clash/tags")
|
||||
if err != nil {
|
||||
return false, "", errors.New("get version info failed" + err.Error())
|
||||
|
||||
}
|
||||
var version model.Tags
|
||||
all, err := io.ReadAll(get.Body)
|
||||
if err != nil {
|
||||
return false, "", errors.New("get version info failed" + err.Error())
|
||||
|
||||
}
|
||||
err = json.Unmarshal(all, &version)
|
||||
if err != nil {
|
||||
return false, "", errors.New("get version info failed" + err.Error())
|
||||
|
||||
}
|
||||
if version[0].Name == config.Version {
|
||||
return false, "", nil
|
||||
} else {
|
||||
return true, version[0].Name, nil
|
||||
}
|
||||
}
|
58
utils/database/database.go
Normal file
58
utils/database/database.go
Normal file
@ -0,0 +1,58 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"github.com/glebarez/sqlite"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
"path/filepath"
|
||||
"sub2clash/logger"
|
||||
"sub2clash/model"
|
||||
"sub2clash/utils"
|
||||
)
|
||||
|
||||
var DB *gorm.DB
|
||||
|
||||
func ConnectDB() error {
|
||||
// 用上面的数据库连接初始化 gorm
|
||||
err := utils.MKDir("data")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
db, err := gorm.Open(
|
||||
sqlite.Open(filepath.Join("data", "sub2clash.db")), &gorm.Config{
|
||||
Logger: nil,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
DB = db
|
||||
err = db.AutoMigrate(&model.ShortLink{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func FindShortLinkByUrl(url string, shortLink *model.ShortLink) *gorm.DB {
|
||||
logger.Logger.Debug("find short link by url", zap.String("url", url))
|
||||
return DB.Where("url = ?", url).First(&shortLink)
|
||||
}
|
||||
|
||||
func FindShortLinkByHash(hash string, shortLink *model.ShortLink) *gorm.DB {
|
||||
logger.Logger.Debug("find short link by hash", zap.String("hash", hash))
|
||||
return DB.Where("hash = ?", hash).First(&shortLink)
|
||||
}
|
||||
|
||||
func SaveShortLink(shortLink *model.ShortLink) {
|
||||
logger.Logger.Debug("save short link", zap.String("hash", shortLink.Hash))
|
||||
DB.Save(shortLink)
|
||||
}
|
||||
|
||||
func FirstOrCreateShortLink(shortLink *model.ShortLink) {
|
||||
logger.Logger.Debug("first or create short link", zap.String("hash", shortLink.Hash))
|
||||
DB.FirstOrCreate(shortLink)
|
||||
}
|
10
utils/get.go
10
utils/get.go
@ -12,7 +12,15 @@ func Get(url string) (resp *http.Response, err error) {
|
||||
haveTried := 0
|
||||
retryDelay := time.Second // 延迟1秒再重试
|
||||
for haveTried < retryTimes {
|
||||
get, err := http.Get(url)
|
||||
client := &http.Client{}
|
||||
//client.Timeout = time.Second * 10
|
||||
req, err := http.NewRequest("GET", url, nil)
|
||||
if err != nil {
|
||||
haveTried++
|
||||
time.Sleep(retryDelay)
|
||||
continue
|
||||
}
|
||||
get, err := client.Do(req)
|
||||
if err != nil {
|
||||
haveTried++
|
||||
time.Sleep(retryDelay)
|
||||
|
30
utils/mkdir.go
Normal file
30
utils/mkdir.go
Normal file
@ -0,0 +1,30 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
)
|
||||
|
||||
func MKDir(dir string) error {
|
||||
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||
err := os.MkdirAll(dir, os.ModePerm)
|
||||
if err != nil {
|
||||
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func MkEssentialDir() error {
|
||||
if err := MKDir("subs"); err != nil {
|
||||
return errors.New("create subs dir failed" + err.Error())
|
||||
}
|
||||
if err := MKDir("templates"); err != nil {
|
||||
return errors.New("create templates dir failed" + err.Error())
|
||||
}
|
||||
if err := MKDir("logs"); err != nil {
|
||||
return errors.New("create logs dir failed" + err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
16
utils/os.go
16
utils/os.go
@ -1,16 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"os"
|
||||
)
|
||||
|
||||
func MKDir(dir string) error {
|
||||
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||
err := os.MkdirAll(dir, os.ModePerm)
|
||||
if err != nil {
|
||||
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
@ -1,13 +1,14 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"go.uber.org/zap"
|
||||
"strings"
|
||||
"sub2clash/logger"
|
||||
"sub2clash/model"
|
||||
"sub2clash/parser"
|
||||
)
|
||||
|
||||
func GetContryName(proxy model.Proxy) string {
|
||||
func GetContryName(countryKey string) string {
|
||||
// 创建一个切片包含所有的国家映射
|
||||
countryMaps := []map[string]string{
|
||||
model.CountryFlag,
|
||||
@ -17,27 +18,50 @@ func GetContryName(proxy model.Proxy) string {
|
||||
}
|
||||
|
||||
// 对每一个映射进行检查
|
||||
for _, countryMap := range countryMaps {
|
||||
for i, countryMap := range countryMaps {
|
||||
if i == 2 {
|
||||
// 对ISO匹配做特殊处理
|
||||
// 根据常用分割字符分割字符串
|
||||
splitChars := []string{"-", "_", " "}
|
||||
key := make([]string, 0)
|
||||
for _, splitChar := range splitChars {
|
||||
slic := strings.Split(countryKey, splitChar)
|
||||
for _, v := range slic {
|
||||
if len(v) == 2 {
|
||||
key = append(key, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
// 对每一个分割后的字符串进行检查
|
||||
for _, v := range key {
|
||||
// 如果匹配到了国家
|
||||
if country, ok := countryMap[strings.ToUpper(v)]; ok {
|
||||
return country
|
||||
}
|
||||
}
|
||||
}
|
||||
for k, v := range countryMap {
|
||||
if strings.Contains(proxy.Name, k) {
|
||||
if strings.Contains(countryKey, k) {
|
||||
return v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return "其他地区"
|
||||
}
|
||||
|
||||
func AddProxy(
|
||||
sub *model.Subscription, autotest bool, lazy bool, sortStrategy string,
|
||||
proxies ...model.Proxy,
|
||||
sub *model.Subscription, autotest bool,
|
||||
lazy bool, clashType model.ClashType, proxies ...model.Proxy,
|
||||
) {
|
||||
newCountryGroupNames := make([]string, 0)
|
||||
proxyTypes := model.GetSupportProxyTypes(clashType)
|
||||
// 添加节点
|
||||
for _, proxy := range proxies {
|
||||
if !proxyTypes[proxy.Type] {
|
||||
continue
|
||||
}
|
||||
sub.Proxies = append(sub.Proxies, proxy)
|
||||
haveProxyGroup := false
|
||||
countryName := GetContryName(proxy)
|
||||
countryName := GetContryName(proxy.Name)
|
||||
for i := range sub.ProxyGroups {
|
||||
group := &sub.ProxyGroups[i]
|
||||
|
||||
@ -76,29 +100,8 @@ func AddProxy(
|
||||
}
|
||||
}
|
||||
sub.ProxyGroups = append(sub.ProxyGroups, newGroup)
|
||||
newCountryGroupNames = append(newCountryGroupNames, countryName)
|
||||
}
|
||||
}
|
||||
// 统计国家策略组数量
|
||||
countryGroupCount := 0
|
||||
for i := range sub.ProxyGroups {
|
||||
if sub.ProxyGroups[i].IsCountryGrop {
|
||||
countryGroupCount++
|
||||
}
|
||||
}
|
||||
// 对国家策略组进行排序
|
||||
switch sortStrategy {
|
||||
case "sizeasc":
|
||||
sort.Sort(model.ProxyGroupsSortBySize(sub.ProxyGroups[:countryGroupCount]))
|
||||
case "sizedesc":
|
||||
sort.Sort(sort.Reverse(model.ProxyGroupsSortBySize(sub.ProxyGroups[:countryGroupCount])))
|
||||
case "nameasc":
|
||||
sort.Sort(model.ProxyGroupsSortByName(sub.ProxyGroups[:countryGroupCount]))
|
||||
case "namedesc":
|
||||
sort.Sort(sort.Reverse(model.ProxyGroupsSortByName(sub.ProxyGroups[:countryGroupCount])))
|
||||
default:
|
||||
sort.Sort(model.ProxyGroupsSortByName(sub.ProxyGroups[:countryGroupCount]))
|
||||
}
|
||||
}
|
||||
|
||||
func ParseProxy(proxies ...string) []model.Proxy {
|
||||
@ -125,6 +128,10 @@ func ParseProxy(proxies ...string) []model.Proxy {
|
||||
}
|
||||
if err == nil {
|
||||
result = append(result, proxyItem)
|
||||
} else {
|
||||
logger.Logger.Debug(
|
||||
"parse proxy failed", zap.String("proxy", proxy), zap.Error(err),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
13
utils/random_string.go
Normal file
13
utils/random_string.go
Normal file
@ -0,0 +1,13 @@
|
||||
package utils
|
||||
|
||||
import "math/rand"
|
||||
|
||||
func RandomString(length int) string {
|
||||
// 生成随机字符串
|
||||
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
var result []byte
|
||||
for i := 0; i < length; i++ {
|
||||
result = append(result, charset[rand.Intn(len(charset))])
|
||||
}
|
||||
return string(result)
|
||||
}
|
12
utils/sub.go
12
utils/sub.go
@ -1,7 +1,7 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
@ -19,7 +19,7 @@ func LoadSubscription(url string, refresh bool) ([]byte, error) {
|
||||
if refresh {
|
||||
return FetchSubscriptionFromAPI(url)
|
||||
}
|
||||
hash := md5.Sum([]byte(url))
|
||||
hash := sha256.Sum224([]byte(url))
|
||||
fileName := filepath.Join(subsDir, hex.EncodeToString(hash[:]))
|
||||
stat, err := os.Stat(fileName)
|
||||
if err != nil {
|
||||
@ -35,7 +35,9 @@ func LoadSubscription(url string, refresh bool) ([]byte, error) {
|
||||
return nil, err
|
||||
}
|
||||
defer func(file *os.File) {
|
||||
if file != nil {
|
||||
_ = file.Close()
|
||||
}
|
||||
}(file)
|
||||
fileLock.RLock()
|
||||
defer fileLock.RUnlock()
|
||||
@ -49,14 +51,16 @@ func LoadSubscription(url string, refresh bool) ([]byte, error) {
|
||||
}
|
||||
|
||||
func FetchSubscriptionFromAPI(url string) ([]byte, error) {
|
||||
hash := md5.Sum([]byte(url))
|
||||
hash := sha256.Sum224([]byte(url))
|
||||
fileName := filepath.Join(subsDir, hex.EncodeToString(hash[:]))
|
||||
resp, err := Get(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func(Body io.ReadCloser) {
|
||||
if Body != nil {
|
||||
_ = Body.Close()
|
||||
}
|
||||
}(resp.Body)
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
@ -67,7 +71,9 @@ func FetchSubscriptionFromAPI(url string) ([]byte, error) {
|
||||
return nil, err
|
||||
}
|
||||
defer func(file *os.File) {
|
||||
if file != nil {
|
||||
_ = file.Close()
|
||||
}
|
||||
}(file)
|
||||
fileLock.Lock()
|
||||
defer fileLock.Unlock()
|
||||
|
@ -8,7 +8,7 @@ import (
|
||||
)
|
||||
|
||||
// LoadTemplate 加载模板
|
||||
// template 模板文件名
|
||||
// templates 模板文件名
|
||||
func LoadTemplate(template string) ([]byte, error) {
|
||||
tPath := filepath.Join("templates", template)
|
||||
if _, err := os.Stat(tPath); err == nil {
|
||||
@ -17,7 +17,9 @@ func LoadTemplate(template string) ([]byte, error) {
|
||||
return nil, err
|
||||
}
|
||||
defer func(file *os.File) {
|
||||
if file != nil {
|
||||
_ = file.Close()
|
||||
}
|
||||
}(file)
|
||||
result, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
|
39
utils/write_default_template.go
Normal file
39
utils/write_default_template.go
Normal file
@ -0,0 +1,39 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sub2clash/config"
|
||||
)
|
||||
|
||||
func writeTemplate(path string, template string) error {
|
||||
tPath := filepath.Join(
|
||||
"templates", path,
|
||||
)
|
||||
if _, err := os.Stat(tPath); os.IsNotExist(err) {
|
||||
file, err := os.Create(tPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func(file *os.File) {
|
||||
if file != nil {
|
||||
_ = file.Close()
|
||||
}
|
||||
}(file)
|
||||
_, err = file.WriteString(template)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func WriteDefalutTemplate(templateMeta string, templateClash string) error {
|
||||
if err := writeTemplate(config.Default.MetaTemplate, templateMeta); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeTemplate(config.Default.ClashTemplate, templateClash); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
11
validator/short_link.go
Normal file
11
validator/short_link.go
Normal file
@ -0,0 +1,11 @@
|
||||
package validator
|
||||
|
||||
type ShortLinkGenValidator struct {
|
||||
Url string `form:"url" binding:"required"`
|
||||
Password string `form:"password"`
|
||||
}
|
||||
|
||||
type ShortLinkGetValidator struct {
|
||||
Hash string `form:"hash" binding:"required"`
|
||||
Password string `form:"password"`
|
||||
}
|
@ -1,7 +1,7 @@
|
||||
package validator
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
@ -11,7 +11,7 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
type SubQuery struct {
|
||||
type SubValidator struct {
|
||||
Sub string `form:"sub" binding:""`
|
||||
Subs []string `form:"-" binding:""`
|
||||
Proxy string `form:"proxy" binding:""`
|
||||
@ -25,6 +25,11 @@ type SubQuery struct {
|
||||
AutoTest bool `form:"autoTest,default=false" binding:""`
|
||||
Lazy bool `form:"lazy,default=false" binding:""`
|
||||
Sort string `form:"sort" binding:""`
|
||||
Remove string `form:"remove" binding:""`
|
||||
Replace string `form:"replace" binding:""`
|
||||
ReplaceKeys []string `form:"-" binding:""`
|
||||
ReplaceTo []string `form:"-" binding:""`
|
||||
NodeListMode bool `form:"nodeList,default=false" binding:""`
|
||||
}
|
||||
|
||||
type RuleProviderStruct struct {
|
||||
@ -40,19 +45,22 @@ type RuleStruct struct {
|
||||
Prepend bool
|
||||
}
|
||||
|
||||
func ParseQuery(c *gin.Context) (SubQuery, error) {
|
||||
var query SubQuery
|
||||
func ParseQuery(c *gin.Context) (SubValidator, error) {
|
||||
var query SubValidator
|
||||
if err := c.ShouldBind(&query); err != nil {
|
||||
return SubQuery{}, errors.New("参数错误: " + err.Error())
|
||||
return SubValidator{}, errors.New("参数错误: " + err.Error())
|
||||
}
|
||||
if query.Sub == "" && query.Proxy == "" {
|
||||
return SubQuery{}, errors.New("参数错误: sub 和 proxy 不能同时为空")
|
||||
return SubValidator{}, errors.New("参数错误: sub 和 proxy 不能同时为空")
|
||||
}
|
||||
if query.Sub != "" {
|
||||
query.Subs = strings.Split(query.Sub, ",")
|
||||
for i := range query.Subs {
|
||||
if !strings.HasPrefix(query.Subs[i], "http") {
|
||||
return SubValidator{}, errors.New("参数错误: sub 格式错误")
|
||||
}
|
||||
if _, err := url.ParseRequestURI(query.Subs[i]); err != nil {
|
||||
return SubQuery{}, errors.New("参数错误: " + err.Error())
|
||||
return SubValidator{}, errors.New("参数错误: " + err.Error())
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@ -67,7 +75,7 @@ func ParseQuery(c *gin.Context) (SubQuery, error) {
|
||||
uri, err := url.ParseRequestURI(query.Template)
|
||||
if err != nil {
|
||||
if strings.Contains(query.Template, string(os.PathSeparator)) {
|
||||
return SubQuery{}, err
|
||||
return SubValidator{}, err
|
||||
}
|
||||
}
|
||||
query.Template = uri.String()
|
||||
@ -79,16 +87,16 @@ func ParseQuery(c *gin.Context) (SubQuery, error) {
|
||||
length := len(ruleProviders)
|
||||
parts := strings.Split(ruleProviders[length-i-1][1], ",")
|
||||
if len(parts) < 4 {
|
||||
return SubQuery{}, errors.New("参数错误: ruleProvider 格式错误")
|
||||
return SubValidator{}, errors.New("参数错误: ruleProvider 格式错误")
|
||||
}
|
||||
u := parts[1]
|
||||
uri, err := url.ParseRequestURI(u)
|
||||
if err != nil {
|
||||
return SubQuery{}, errors.New("参数错误: " + err.Error())
|
||||
return SubValidator{}, errors.New("参数错误: " + err.Error())
|
||||
}
|
||||
u = uri.String()
|
||||
if len(parts) == 4 {
|
||||
hash := md5.Sum([]byte(u))
|
||||
hash := sha256.Sum224([]byte(u))
|
||||
parts = append(parts, hex.EncodeToString(hash[:]))
|
||||
}
|
||||
query.RuleProviders = append(
|
||||
@ -101,6 +109,14 @@ func ParseQuery(c *gin.Context) (SubQuery, error) {
|
||||
},
|
||||
)
|
||||
}
|
||||
// 校验 Rule-Provider 是否有重名
|
||||
names := make(map[string]bool)
|
||||
for _, ruleProvider := range query.RuleProviders {
|
||||
if _, ok := names[ruleProvider.Name]; ok {
|
||||
return SubValidator{}, errors.New("参数错误: Rule-Provider 名称重复")
|
||||
}
|
||||
names[ruleProvider.Name] = true
|
||||
}
|
||||
} else {
|
||||
query.RuleProviders = nil
|
||||
}
|
||||
@ -124,5 +140,17 @@ func ParseQuery(c *gin.Context) (SubQuery, error) {
|
||||
} else {
|
||||
query.Rules = nil
|
||||
}
|
||||
if strings.TrimSpace(query.Replace) != "" {
|
||||
reg := regexp.MustCompile(`\[<(.*?)>,<(.*?)>\]`)
|
||||
replaces := reg.FindAllStringSubmatch(query.Replace, -1)
|
||||
for i := range replaces {
|
||||
length := len(replaces[i])
|
||||
if length != 3 {
|
||||
return SubValidator{}, errors.New("参数错误: replace 格式错误")
|
||||
}
|
||||
query.ReplaceKeys = append(query.ReplaceKeys, replaces[i][1])
|
||||
query.ReplaceTo = append(query.ReplaceTo, replaces[i][2])
|
||||
}
|
||||
}
|
||||
return query, nil
|
||||
}
|
||||
|
Reference in New Issue
Block a user