clash/adapter/provider/parser.go

68 lines
2 KiB
Go
Raw Normal View History

2019-12-08 04:17:24 +00:00
package provider
import (
"errors"
"fmt"
"github.com/Dreamacro/clash/component/resource"
2019-12-08 04:17:24 +00:00
"time"
"github.com/Dreamacro/clash/common/structure"
C "github.com/Dreamacro/clash/constant"
types "github.com/Dreamacro/clash/constant/provider"
2019-12-08 04:17:24 +00:00
)
2021-10-10 15:44:09 +00:00
var errVehicleType = errors.New("unsupport vehicle type")
2019-12-08 04:17:24 +00:00
type healthCheckSchema struct {
Enable bool `provider:"enable"`
URL string `provider:"url"`
Interval int `provider:"interval"`
Lazy bool `provider:"lazy,omitempty"`
2019-12-08 04:17:24 +00:00
}
type proxyProviderSchema struct {
Type string `provider:"type"`
Path string `provider:"path"`
URL string `provider:"url,omitempty"`
Interval int `provider:"interval,omitempty"`
Filter string `provider:"filter,omitempty"`
ExcludeFilter string `provider:"exclude-filter,omitempty"`
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
2019-12-08 04:17:24 +00:00
}
2022-03-16 04:10:13 +00:00
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
2019-12-08 04:17:24 +00:00
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
schema := &proxyProviderSchema{
HealthCheck: healthCheckSchema{
Lazy: true,
},
}
2019-12-08 04:17:24 +00:00
if err := decoder.Decode(mapping, schema); err != nil {
return nil, err
}
2021-03-23 17:00:21 +00:00
var hcInterval uint
2019-12-08 04:17:24 +00:00
if schema.HealthCheck.Enable {
hcInterval = uint(schema.HealthCheck.Interval)
2019-12-08 04:17:24 +00:00
}
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, hcInterval, schema.HealthCheck.Lazy)
2019-12-08 04:17:24 +00:00
2020-01-30 09:03:11 +00:00
path := C.Path.Resolve(schema.Path)
2019-12-08 04:17:24 +00:00
var vehicle types.Vehicle
2019-12-08 04:17:24 +00:00
switch schema.Type {
case "file":
vehicle = resource.NewFileVehicle(path)
2019-12-08 04:17:24 +00:00
case "http":
vehicle = resource.NewHTTPVehicle(schema.URL, path)
2019-12-08 04:17:24 +00:00
default:
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
}
interval := time.Duration(uint(schema.Interval)) * time.Second
filter := schema.Filter
excludeFilter := schema.ExcludeFilter
return NewProxySetProvider(name, interval, filter, excludeFilter, vehicle, hc)
2019-12-08 04:17:24 +00:00
}