Clash.Meta/rules/provider/parse.go

63 lines
1.9 KiB
Go
Raw Normal View History

package provider
import (
2023-06-15 22:45:02 +08:00
"errors"
"fmt"
2023-06-15 22:45:02 +08:00
"time"
2023-11-03 21:01:45 +08:00
"github.com/metacubex/mihomo/common/structure"
"github.com/metacubex/mihomo/component/resource"
C "github.com/metacubex/mihomo/constant"
P "github.com/metacubex/mihomo/constant/provider"
2023-06-15 22:45:02 +08:00
)
var (
errSubPath = errors.New("path is not subpath of home directory")
)
type ruleProviderSchema struct {
Type string `provider:"type"`
Behavior string `provider:"behavior"`
2023-06-15 22:45:02 +08:00
Path string `provider:"path,omitempty"`
URL string `provider:"url,omitempty"`
Proxy string `provider:"proxy,omitempty"`
2023-04-14 13:51:26 +08:00
Format string `provider:"format,omitempty"`
Interval int `provider:"interval,omitempty"`
}
2022-12-04 13:37:14 +08:00
func ParseRuleProvider(name string, mapping map[string]interface{}, parse func(tp, payload, target string, params []string, subRules map[string][]C.Rule) (parsed C.Rule, parseErr error)) (P.RuleProvider, error) {
schema := &ruleProviderSchema{}
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
if err := decoder.Decode(mapping, schema); err != nil {
return nil, err
}
2024-07-26 22:30:42 +08:00
behavior, err := P.ParseBehavior(schema.Behavior)
if err != nil {
return nil, err
}
2024-07-26 22:30:42 +08:00
format, err := P.ParseRuleFormat(schema.Format)
if err != nil {
return nil, err
2023-04-14 13:51:26 +08:00
}
var vehicle P.Vehicle
switch schema.Type {
case "file":
2023-06-15 22:45:02 +08:00
path := C.Path.Resolve(schema.Path)
vehicle = resource.NewFileVehicle(path)
case "http":
path := C.Path.GetPathByHash("rules", schema.URL)
2023-06-15 22:45:02 +08:00
if schema.Path != "" {
path = C.Path.Resolve(schema.Path)
2024-09-11 16:10:35 +08:00
if !C.Path.IsSafePath(path) {
2023-06-15 22:45:02 +08:00
return nil, fmt.Errorf("%w: %s", errSubPath, path)
}
}
2024-09-22 13:57:57 +08:00
vehicle = resource.NewHTTPVehicle(schema.URL, path, schema.Proxy, nil, resource.DefaultHttpTimeout)
default:
return nil, fmt.Errorf("unsupported vehicle type: %s", schema.Type)
}
2023-04-14 13:51:26 +08:00
return NewRuleSetProvider(name, behavior, format, time.Duration(uint(schema.Interval))*time.Second, vehicle, parse), nil
}