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