2018-07-12 23:28:38 +08:00
|
|
|
package adapters
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2018-08-07 14:45:24 +08:00
|
|
|
"sort"
|
2018-07-12 23:28:38 +08:00
|
|
|
|
|
|
|
C "github.com/Dreamacro/clash/constant"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Selector struct {
|
|
|
|
name string
|
|
|
|
selected C.Proxy
|
2018-07-18 21:50:16 +08:00
|
|
|
proxies map[string]C.Proxy
|
2018-07-12 23:28:38 +08:00
|
|
|
}
|
|
|
|
|
2018-10-02 15:26:36 +08:00
|
|
|
type SelectorOption struct {
|
|
|
|
Name string `proxy:"name"`
|
|
|
|
Proxies []string `proxy:"proxies"`
|
|
|
|
}
|
|
|
|
|
2018-07-12 23:28:38 +08:00
|
|
|
func (s *Selector) Name() string {
|
|
|
|
return s.name
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Selector) Type() C.AdapterType {
|
|
|
|
return C.Selector
|
|
|
|
}
|
|
|
|
|
2018-09-30 12:25:52 +08:00
|
|
|
func (s *Selector) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
|
|
|
return s.selected.Generator(metadata)
|
2018-07-12 23:28:38 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Selector) Now() string {
|
|
|
|
return s.selected.Name()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Selector) All() []string {
|
|
|
|
var all []string
|
2018-07-18 21:50:16 +08:00
|
|
|
for k := range s.proxies {
|
2018-07-12 23:28:38 +08:00
|
|
|
all = append(all, k)
|
|
|
|
}
|
2018-08-07 14:45:24 +08:00
|
|
|
sort.Strings(all)
|
2018-07-12 23:28:38 +08:00
|
|
|
return all
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Selector) Set(name string) error {
|
2018-07-18 21:50:16 +08:00
|
|
|
proxy, exist := s.proxies[name]
|
2018-07-12 23:28:38 +08:00
|
|
|
if !exist {
|
|
|
|
return errors.New("Proxy does not exist")
|
|
|
|
}
|
|
|
|
s.selected = proxy
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-10-18 23:24:04 +08:00
|
|
|
func NewSelector(name string, proxies []C.Proxy) (*Selector, error) {
|
2018-07-18 21:50:16 +08:00
|
|
|
if len(proxies) == 0 {
|
2018-07-12 23:28:38 +08:00
|
|
|
return nil, errors.New("Provide at least one proxy")
|
|
|
|
}
|
|
|
|
|
|
|
|
mapping := make(map[string]C.Proxy)
|
2018-10-18 23:24:04 +08:00
|
|
|
for _, proxy := range proxies {
|
|
|
|
mapping[proxy.Name()] = proxy
|
2018-07-12 23:28:38 +08:00
|
|
|
}
|
2018-10-18 23:24:04 +08:00
|
|
|
|
2018-07-12 23:28:38 +08:00
|
|
|
s := &Selector{
|
|
|
|
name: name,
|
2018-07-18 21:50:16 +08:00
|
|
|
proxies: mapping,
|
2018-10-18 23:24:04 +08:00
|
|
|
selected: proxies[0],
|
2018-07-12 23:28:38 +08:00
|
|
|
}
|
|
|
|
return s, nil
|
|
|
|
}
|