-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom_config.go
More file actions
523 lines (461 loc) · 15.1 KB
/
Copy pathcustom_config.go
File metadata and controls
523 lines (461 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
package handler
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"clash-config-store/internal/middleware"
"clash-config-store/internal/model"
"clash-config-store/internal/repository"
"clash-config-store/internal/util"
"github.com/gin-gonic/gin"
)
// ListCustomConfigs 列出当前用户所有自定义配置
func ListCustomConfigs(c *gin.Context) {
userID := middleware.CurrentUserID(c)
var configs []model.CustomConfig
if err := repository.DB.Where("user_id = ?", userID).Find(&configs).Error; err != nil {
Fail(c, http.StatusInternalServerError, "查询失败")
return
}
OK(c, configs)
}
// customConfigRequest 创建/更新自定义配置的请求体
type customConfigRequest struct {
Name string `json:"name" binding:"required"`
Proxies []map[string]interface{} `json:"proxies"`
ProxyGroups []map[string]interface{} `json:"proxy_groups"`
Rules []string `json:"rules"`
RuleProviderIDs []uint `json:"rule_provider_ids"`
HostedRuleSetIDs []uint `json:"hosted_rule_set_ids"`
}
type customConfigTransferPayload struct {
Name string `json:"name"`
Proxies []map[string]interface{} `json:"proxies"`
ProxyGroups []map[string]interface{} `json:"proxy_groups"`
Rules []string `json:"rules"`
RuleProviderIDs []uint `json:"rule_provider_ids"`
HostedRuleSetIDs []uint `json:"hosted_rule_set_ids"`
}
// CreateCustomConfig 创建自定义配置
func CreateCustomConfig(c *gin.Context) {
userID := middleware.CurrentUserID(c)
var req customConfigRequest
if err := c.ShouldBindJSON(&req); err != nil {
BindFail(c, err)
return
}
if err := validateCustomConfigRequest(userID, &req); err != nil {
Fail(c, http.StatusBadRequest, err.Error())
return
}
req.RuleProviderIDs, req.HostedRuleSetIDs, _ = normalizeCustomConfigRuleSetRefs(userID, req.RuleProviderIDs, req.HostedRuleSetIDs)
cfg := &model.CustomConfig{
UserID: userID,
Name: req.Name,
Proxies: nullSliceMaps(req.Proxies),
ProxyGroups: nullSliceMaps(req.ProxyGroups),
Rules: nullSliceStrings(req.Rules),
RuleProviderIDs: nullSliceUints(req.RuleProviderIDs),
HostedRuleSetIDs: nullSliceUints(req.HostedRuleSetIDs),
}
if err := repository.DB.Create(cfg).Error; err != nil {
Fail(c, http.StatusInternalServerError, "创建失败")
return
}
OK(c, cfg)
}
// CloneCustomConfig 克隆现有自定义配置
func CloneCustomConfig(c *gin.Context) {
userID := middleware.CurrentUserID(c)
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
Fail(c, http.StatusBadRequest, "无效的 ID")
return
}
var cfg model.CustomConfig
if err := repository.DB.Where("id = ? AND user_id = ?", id, userID).First(&cfg).Error; err != nil {
Fail(c, http.StatusNotFound, "配置不存在或无权限")
return
}
clone := &model.CustomConfig{
UserID: userID,
Name: uniqueCustomConfigName(userID, cfg.Name+" - 副本"),
Proxies: cloneSliceMaps(cfg.Proxies),
ProxyGroups: cloneSliceMaps(cfg.ProxyGroups),
Rules: cloneSliceStrings(cfg.Rules),
RuleProviderIDs: cloneSliceUints(cfg.RuleProviderIDs),
HostedRuleSetIDs: cloneSliceUints(cfg.HostedRuleSetIDs),
}
if err := repository.DB.Create(clone).Error; err != nil {
Fail(c, http.StatusInternalServerError, "克隆失败")
return
}
OK(c, clone)
}
// GetCustomConfig 获取自定义配置详情
func GetCustomConfig(c *gin.Context) {
userID := middleware.CurrentUserID(c)
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
Fail(c, http.StatusBadRequest, "无效的 ID")
return
}
var cfg model.CustomConfig
if err := repository.DB.Where("id = ? AND user_id = ?", id, userID).First(&cfg).Error; err != nil {
Fail(c, http.StatusNotFound, "配置不存在或无权限")
return
}
OK(c, cfg)
}
// UpdateCustomConfig 更新自定义配置
func UpdateCustomConfig(c *gin.Context) {
userID := middleware.CurrentUserID(c)
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
Fail(c, http.StatusBadRequest, "无效的 ID")
return
}
var cfg model.CustomConfig
if err := repository.DB.Where("id = ? AND user_id = ?", id, userID).First(&cfg).Error; err != nil {
Fail(c, http.StatusNotFound, "配置不存在或无权限")
return
}
var req customConfigRequest
if err := c.ShouldBindJSON(&req); err != nil {
BindFail(c, err)
return
}
if err := validateCustomConfigRequest(userID, &req); err != nil {
Fail(c, http.StatusBadRequest, err.Error())
return
}
req.RuleProviderIDs, req.HostedRuleSetIDs, _ = normalizeCustomConfigRuleSetRefs(userID, req.RuleProviderIDs, req.HostedRuleSetIDs)
cfg.Name = req.Name
cfg.Proxies = nullSliceMaps(req.Proxies)
cfg.ProxyGroups = nullSliceMaps(req.ProxyGroups)
cfg.Rules = nullSliceStrings(req.Rules)
cfg.RuleProviderIDs = nullSliceUints(req.RuleProviderIDs)
cfg.HostedRuleSetIDs = nullSliceUints(req.HostedRuleSetIDs)
if err := repository.DB.Save(&cfg).Error; err != nil {
Fail(c, http.StatusInternalServerError, "更新失败")
return
}
OK(c, cfg)
}
// DeleteCustomConfig 删除自定义配置
func DeleteCustomConfig(c *gin.Context) {
userID := middleware.CurrentUserID(c)
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
Fail(c, http.StatusBadRequest, "无效的 ID")
return
}
var cfg model.CustomConfig
if err := repository.DB.Where("id = ? AND user_id = ?", id, userID).First(&cfg).Error; err != nil {
Fail(c, http.StatusNotFound, "配置不存在或无权限")
return
}
if err := repository.DB.Delete(&cfg).Error; err != nil {
Fail(c, http.StatusInternalServerError, "删除失败")
return
}
OKMsg(c, "删除成功", nil)
}
// ExportCustomConfig 导出可回灌的 JSON 快照
func ExportCustomConfig(c *gin.Context) {
userID := middleware.CurrentUserID(c)
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
Fail(c, http.StatusBadRequest, "无效的 ID")
return
}
var cfg model.CustomConfig
if err := repository.DB.Where("id = ? AND user_id = ?", id, userID).First(&cfg).Error; err != nil {
Fail(c, http.StatusNotFound, "配置不存在或无权限")
return
}
payload := customConfigTransferPayload{
Name: cfg.Name,
Proxies: nullSliceMaps(cfg.Proxies),
ProxyGroups: nullSliceMaps(cfg.ProxyGroups),
Rules: nullSliceStrings(cfg.Rules),
RuleProviderIDs: nullSliceUints(cfg.RuleProviderIDs),
HostedRuleSetIDs: nullSliceUints(cfg.HostedRuleSetIDs),
}
data, err := json.MarshalIndent(payload, "", " ")
if err != nil {
Fail(c, http.StatusInternalServerError, "导出失败")
return
}
filename := sanitizeExportFilename(cfg.Name, uint(id))
c.Header("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
c.Data(http.StatusOK, "application/json; charset=utf-8", data)
}
// ImportCustomConfig 导入自定义配置 JSON 快照
func ImportCustomConfig(c *gin.Context) {
userID := middleware.CurrentUserID(c)
var req customConfigTransferPayload
if err := c.ShouldBindJSON(&req); err != nil {
BindFail(c, err)
return
}
req.Name = strings.TrimSpace(req.Name)
if req.Name == "" {
req.Name = "导入配置"
}
createReq := customConfigRequest{
Name: uniqueCustomConfigName(userID, req.Name),
Proxies: nullSliceMaps(req.Proxies),
ProxyGroups: nullSliceMaps(req.ProxyGroups),
Rules: nullSliceStrings(req.Rules),
RuleProviderIDs: nullSliceUints(req.RuleProviderIDs),
HostedRuleSetIDs: nullSliceUints(req.HostedRuleSetIDs),
}
if err := validateCustomConfigRequest(userID, &createReq); err != nil {
Fail(c, http.StatusBadRequest, err.Error())
return
}
createReq.RuleProviderIDs, createReq.HostedRuleSetIDs, _ = normalizeCustomConfigRuleSetRefs(userID, createReq.RuleProviderIDs, createReq.HostedRuleSetIDs)
cfg := &model.CustomConfig{
UserID: userID,
Name: createReq.Name,
Proxies: createReq.Proxies,
ProxyGroups: createReq.ProxyGroups,
Rules: createReq.Rules,
RuleProviderIDs: createReq.RuleProviderIDs,
HostedRuleSetIDs: createReq.HostedRuleSetIDs,
}
if err := repository.DB.Create(cfg).Error; err != nil {
Fail(c, http.StatusInternalServerError, "导入失败")
return
}
OK(c, cfg)
}
// PreviewCustomConfig 生成当前配置的 YAML 预览(不依赖订阅,仅用于编辑器实时预览)
func PreviewCustomConfig(c *gin.Context) {
userID := middleware.CurrentUserID(c)
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
Fail(c, http.StatusBadRequest, "无效的 ID")
return
}
var cfg model.CustomConfig
if err := repository.DB.Where("id = ? AND user_id = ?", id, userID).First(&cfg).Error; err != nil {
Fail(c, http.StatusNotFound, "配置不存在或无权限")
return
}
// 加载关联规则集
ruleProviderInputs, err := loadCustomConfigRuleProviderInputs(userID, cfg.RuleProviderIDs, cfg.HostedRuleSetIDs)
if err != nil {
Fail(c, http.StatusBadRequest, err.Error())
return
}
// preview 没有真实订阅源数据,use: 展开留空(生成订阅时才会注入)
yamlBytes, err := util.BuildMihomoConfig(
"",
nil,
cfg.Proxies,
cfg.ProxyGroups,
cfg.Rules,
"append",
ruleProviderInputs,
nil,
)
if err != nil {
Fail(c, http.StatusInternalServerError, "YAML 生成失败: "+err.Error())
return
}
c.Data(http.StatusOK, "text/plain; charset=utf-8", yamlBytes)
}
// validateCustomConfigRequest 校验自定义配置请求
func validateCustomConfigRequest(userID uint, req *customConfigRequest) error {
for i, p := range req.Proxies {
name, _ := p["name"].(string)
if strings.TrimSpace(name) == "" {
return fmt.Errorf("proxies[%d] 缺少非空 name", i)
}
typ, _ := p["type"].(string)
if strings.TrimSpace(typ) == "" {
return fmt.Errorf("proxies[%d] 缺少非空 type", i)
}
}
for i, g := range req.ProxyGroups {
name, _ := g["name"].(string)
if strings.TrimSpace(name) == "" {
return fmt.Errorf("proxy_groups[%d] 缺少非空 name", i)
}
typ, _ := g["type"].(string)
if strings.TrimSpace(typ) == "" {
return fmt.Errorf("proxy_groups[%d] 缺少非空 type", i)
}
}
for i, rule := range req.Rules {
if err := util.ValidateMihomoRuleLine(rule); err != nil {
return fmt.Errorf("rules[%d]: %w", i, err)
}
}
if _, _, err := normalizeCustomConfigRuleSetRefs(userID, req.RuleProviderIDs, req.HostedRuleSetIDs); err != nil {
return err
}
return nil
}
// nullSliceMaps 将 nil 切片统一为空切片,避免 JSON 输出 null
func nullSliceMaps(s []map[string]interface{}) []map[string]interface{} {
if s == nil {
return []map[string]interface{}{}
}
return s
}
func nullSliceStrings(s []string) []string {
if s == nil {
return []string{}
}
return s
}
func nullSliceUints(s []uint) []uint {
if s == nil {
return []uint{}
}
return s
}
func cloneSliceMaps(s []map[string]interface{}) []map[string]interface{} {
if len(s) == 0 {
return []map[string]interface{}{}
}
data, err := json.Marshal(s)
if err != nil {
return []map[string]interface{}{}
}
var out []map[string]interface{}
if err := json.Unmarshal(data, &out); err != nil {
return []map[string]interface{}{}
}
return out
}
func cloneSliceStrings(s []string) []string {
if len(s) == 0 {
return []string{}
}
return append([]string(nil), s...)
}
func cloneSliceUints(s []uint) []uint {
if len(s) == 0 {
return []uint{}
}
return append([]uint(nil), s...)
}
func loadCustomConfigRuleProviderInputs(userID uint, ruleProviderIDs []uint, hostedRuleSetIDs []uint) ([]util.RuleProviderInput, error) {
ruleProviderIDs, hostedRuleSetIDs, err := normalizeCustomConfigRuleSetRefs(userID, ruleProviderIDs, hostedRuleSetIDs)
if err != nil {
return nil, err
}
inputs := make([]util.RuleProviderInput, 0, len(ruleProviderIDs)+len(hostedRuleSetIDs))
if len(ruleProviderIDs) > 0 {
var rps []model.RuleProvider
if err := repository.DB.
Where("id IN ?", ruleProviderIDs).
Where("user_id = ? OR is_preset = ?", userID, true).
Find(&rps).Error; err != nil {
return nil, err
}
for _, rp := range rps {
inputs = append(inputs, util.RuleProviderInput{
Name: rp.Name,
Type: rp.Type,
URL: rp.URL,
Behavior: rp.Behavior,
Format: rp.Format,
Interval: rp.Interval,
})
}
}
if len(hostedRuleSetIDs) > 0 {
var hosted []model.HostedRuleSet
if err := repository.DB.
Where("id IN ? AND user_id = ?", hostedRuleSetIDs, userID).
Find(&hosted).Error; err != nil {
return nil, err
}
for _, hrs := range hosted {
inputs = append(inputs, util.RuleProviderInput{
Name: hrs.Name,
Type: "http",
URL: util.RuleSetPublicURL(hrs.Token, hrs.Name),
Behavior: hrs.Behavior,
Format: hrs.Format,
Interval: 86400,
})
}
}
return inputs, nil
}
func normalizeCustomConfigRuleSetRefs(userID uint, ruleProviderIDs []uint, hostedRuleSetIDs []uint) ([]uint, []uint, error) {
normalizedRuleProviderIDs := make([]uint, 0, len(ruleProviderIDs))
normalizedHostedRuleSetIDs := append([]uint(nil), hostedRuleSetIDs...)
hostedSeen := make(map[uint]struct{}, len(normalizedHostedRuleSetIDs))
names := make(map[string]struct{})
for _, id := range normalizedHostedRuleSetIDs {
hostedSeen[id] = struct{}{}
}
if len(ruleProviderIDs) > 0 {
var rps []model.RuleProvider
if err := repository.DB.
Where("id IN ?", ruleProviderIDs).
Where("user_id = ? OR is_preset = ?", userID, true).
Find(&rps).Error; err != nil {
return nil, nil, err
}
for _, rp := range rps {
if _, exists := names[rp.Name]; exists {
return nil, nil, fmt.Errorf("规则集名称 %q 重复,请先调整名称", rp.Name)
}
names[rp.Name] = struct{}{}
normalizedRuleProviderIDs = append(normalizedRuleProviderIDs, rp.ID)
}
}
if len(normalizedHostedRuleSetIDs) > 0 {
var hosted []model.HostedRuleSet
if err := repository.DB.
Where("id IN ? AND user_id = ?", normalizedHostedRuleSetIDs, userID).
Find(&hosted).Error; err != nil {
return nil, nil, err
}
validHostedIDs := make([]uint, 0, len(hosted))
for _, hrs := range hosted {
if _, exists := names[hrs.Name]; exists {
return nil, nil, fmt.Errorf("规则集名称 %q 重复,请先调整名称", hrs.Name)
}
names[hrs.Name] = struct{}{}
validHostedIDs = append(validHostedIDs, hrs.ID)
}
normalizedHostedRuleSetIDs = validHostedIDs
}
return normalizedRuleProviderIDs, normalizedHostedRuleSetIDs, nil
}
func uniqueCustomConfigName(userID uint, baseName string) string {
baseName = strings.TrimSpace(baseName)
if baseName == "" {
baseName = "未命名配置"
}
name := baseName
for i := 2; ; i++ {
var count int64
repository.DB.Model(&model.CustomConfig{}).
Where("user_id = ? AND name = ?", userID, name).
Count(&count)
if count == 0 {
return name
}
name = fmt.Sprintf("%s %d", baseName, i)
}
}
func sanitizeExportFilename(name string, id uint) string {
name = strings.TrimSpace(name)
if name == "" {
name = "config"
}
replacer := strings.NewReplacer("/", "-", "\\", "-", " ", "-", "\"", "", "'", "")
return fmt.Sprintf("custom-config-%s-%d.json", replacer.Replace(name), id)
}