github.com/yaling888/clash@v1.53.0/component/script/proxy_providers.go (about)

     1  package script
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"go.starlark.net/starlark"
     7  
     8  	C "github.com/yaling888/clash/constant"
     9  )
    10  
    11  var _ starlark.Mapping = (*ProxyProviders)(nil)
    12  
    13  type ProxyProviders struct {
    14  	starlark.Value
    15  }
    16  
    17  func (p *ProxyProviders) Type() string {
    18  	return "proxy_providers"
    19  }
    20  
    21  func (p *ProxyProviders) Get(value starlark.Value) (v starlark.Value, found bool, err error) {
    22  	defer func() {
    23  		if err != nil {
    24  			err = fmt.Errorf("call proxy_providers error: %w", err)
    25  		}
    26  	}()
    27  
    28  	var name starlark.String
    29  	if name, found = value.(starlark.String); !found {
    30  		err = fmt.Errorf("invalid key type")
    31  		return
    32  	}
    33  	providerName := name.GoString()
    34  
    35  	var proxies []C.Proxy
    36  	if proxies, found = C.GetScriptProxyProviders()[providerName]; !found {
    37  		err = fmt.Errorf("provider [%s] not found", providerName)
    38  		return
    39  	}
    40  
    41  	var array []starlark.Value
    42  	for _, proxy := range proxies {
    43  		dict := starlark.NewDict(3)
    44  		err = dict.SetKey(starlark.String("name"), starlark.String(proxy.Name()))
    45  		if err != nil {
    46  			return
    47  		}
    48  		err = dict.SetKey(starlark.String("alive"), starlark.Bool(proxy.Alive()))
    49  		if err != nil {
    50  			return
    51  		}
    52  		err = dict.SetKey(starlark.String("delay"), starlark.MakeUint64(uint64(proxy.LastDelay())))
    53  		if err != nil {
    54  			return
    55  		}
    56  		array = append(array, dict)
    57  	}
    58  
    59  	v = starlark.NewList(array)
    60  	return
    61  }
    62  
    63  func newProxyProviders() *ProxyProviders {
    64  	return &ProxyProviders{}
    65  }