2022-01-22 14:10:45 +00:00
|
|
|
package provider
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"github.com/Dreamacro/clash/common/structure"
|
2022-07-11 13:30:34 +00:00
|
|
|
"github.com/Dreamacro/clash/component/resource"
|
2022-01-22 14:10:45 +00:00
|
|
|
C "github.com/Dreamacro/clash/constant"
|
|
|
|
P "github.com/Dreamacro/clash/constant/provider"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ruleProviderSchema struct {
|
|
|
|
Type string `provider:"type"`
|
|
|
|
Behavior string `provider:"behavior"`
|
|
|
|
Path string `provider:"path"`
|
|
|
|
URL string `provider:"url,omitempty"`
|
|
|
|
Interval int `provider:"interval,omitempty"`
|
|
|
|
}
|
|
|
|
|
2022-06-10 05:36:09 +00:00
|
|
|
func ParseRuleProvider(name string, mapping map[string]interface{}, parse func(tp, payload, target string, params []string) (parsed C.Rule, parseErr error)) (P.RuleProvider, error) {
|
2022-01-22 14:10:45 +00:00
|
|
|
schema := &ruleProviderSchema{}
|
|
|
|
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
|
|
|
if err := decoder.Decode(mapping, schema); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
var behavior P.RuleType
|
|
|
|
|
|
|
|
switch schema.Behavior {
|
|
|
|
case "domain":
|
|
|
|
behavior = P.Domain
|
|
|
|
case "ipcidr":
|
|
|
|
behavior = P.IPCIDR
|
|
|
|
case "classical":
|
|
|
|
behavior = P.Classical
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("unsupported behavior type: %s", schema.Behavior)
|
|
|
|
}
|
|
|
|
|
|
|
|
path := C.Path.Resolve(schema.Path)
|
|
|
|
var vehicle P.Vehicle
|
|
|
|
switch schema.Type {
|
|
|
|
case "file":
|
2022-07-11 13:30:34 +00:00
|
|
|
vehicle = resource.NewFileVehicle(path)
|
2022-01-22 14:10:45 +00:00
|
|
|
case "http":
|
2022-07-11 13:30:34 +00:00
|
|
|
vehicle = resource.NewHTTPVehicle(schema.URL, path)
|
2022-01-22 14:10:45 +00:00
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("unsupported vehicle type: %s", schema.Type)
|
|
|
|
}
|
|
|
|
|
2022-06-10 05:36:09 +00:00
|
|
|
return NewRuleSetProvider(name, behavior, time.Duration(uint(schema.Interval))*time.Second, vehicle, parse), nil
|
2022-01-22 14:10:45 +00:00
|
|
|
}
|