github.com/inazumav/sing-box@v0.0.0-20230926072359-ab51429a14f1/experimental/clashapi.go (about)

     1  package experimental
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  	"github.com/sagernet/sing/common"
     7  	"github.com/inazumav/sing-box/adapter"
     8  	"github.com/inazumav/sing-box/log"
     9  	"github.com/inazumav/sing-box/option"
    10  )
    11  
    12  type ClashServerConstructor = func(ctx context.Context, router adapter.Router, logFactory log.ObservableFactory, options option.ClashAPIOptions) (adapter.ClashServer, error)
    13  
    14  var clashServerConstructor ClashServerConstructor
    15  
    16  func RegisterClashServerConstructor(constructor ClashServerConstructor) {
    17  	clashServerConstructor = constructor
    18  }
    19  
    20  func NewClashServer(ctx context.Context, router adapter.Router, logFactory log.ObservableFactory, options option.ClashAPIOptions) (adapter.ClashServer, error) {
    21  	if clashServerConstructor == nil {
    22  		return nil, os.ErrInvalid
    23  	}
    24  	return clashServerConstructor(ctx, router, logFactory, options)
    25  }
    26  
    27  func CalculateClashModeList(options option.Options) []string {
    28  	var clashMode []string
    29  	for _, dnsRule := range common.PtrValueOrDefault(options.DNS).Rules {
    30  		if dnsRule.DefaultOptions.ClashMode != "" && !common.Contains(clashMode, dnsRule.DefaultOptions.ClashMode) {
    31  			clashMode = append(clashMode, dnsRule.DefaultOptions.ClashMode)
    32  		}
    33  		for _, defaultRule := range dnsRule.LogicalOptions.Rules {
    34  			if defaultRule.ClashMode != "" && !common.Contains(clashMode, defaultRule.ClashMode) {
    35  				clashMode = append(clashMode, defaultRule.ClashMode)
    36  			}
    37  		}
    38  	}
    39  	for _, rule := range common.PtrValueOrDefault(options.Route).Rules {
    40  		if rule.DefaultOptions.ClashMode != "" && !common.Contains(clashMode, rule.DefaultOptions.ClashMode) {
    41  			clashMode = append(clashMode, rule.DefaultOptions.ClashMode)
    42  		}
    43  		for _, defaultRule := range rule.LogicalOptions.Rules {
    44  			if defaultRule.ClashMode != "" && !common.Contains(clashMode, defaultRule.ClashMode) {
    45  				clashMode = append(clashMode, defaultRule.ClashMode)
    46  			}
    47  		}
    48  	}
    49  	return clashMode
    50  }