github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/app/subscription/entries/nonnative/converter.go (about)

     1  package nonnative
     2  
     3  import (
     4  	"io/fs"
     5  
     6  	"github.com/v2fly/v2ray-core/v5/app/subscription/entries"
     7  	"github.com/v2fly/v2ray-core/v5/app/subscription/entries/nonnative/nonnativeifce"
     8  	"github.com/v2fly/v2ray-core/v5/app/subscription/entries/outbound"
     9  	"github.com/v2fly/v2ray-core/v5/app/subscription/specs"
    10  	"github.com/v2fly/v2ray-core/v5/common"
    11  )
    12  
    13  type nonNativeConverter struct {
    14  	matcher *DefMatcher
    15  }
    16  
    17  func (n *nonNativeConverter) ConvertToAbstractServerConfig(rawConfig []byte, kindHint string) (*specs.SubscriptionServerConfig, error) {
    18  	nonNativeLink := ExtractAllValuesFromBytes(rawConfig)
    19  	nonNativeLink.Values["_kind"] = kindHint
    20  	result, err := n.matcher.ExecuteAll(nonNativeLink)
    21  	if err != nil {
    22  		return nil, newError("failed to find working converting template").Base(err)
    23  	}
    24  	outboundParser := outbound.NewOutboundEntriesParser()
    25  	outboundEntries, err := outboundParser.ConvertToAbstractServerConfig(result, "")
    26  	if err != nil {
    27  		return nil, newError("failed to parse template output as outbound entries").Base(err)
    28  	}
    29  	return outboundEntries, nil
    30  }
    31  
    32  func NewNonNativeConverter(fs fs.FS) (entries.Converter, error) {
    33  	matcher := NewDefMatcher()
    34  	if fs == nil {
    35  		err := matcher.LoadEmbeddedDefinitions()
    36  		if err != nil {
    37  			return nil, newError("failed to load embedded definitions").Base(err)
    38  		}
    39  	} else {
    40  		err := matcher.LoadDefinitions(fs)
    41  		if err != nil {
    42  			return nil, newError("failed to load provided definitions").Base(err)
    43  		}
    44  	}
    45  	return &nonNativeConverter{matcher: matcher}, nil
    46  }
    47  
    48  func init() {
    49  	common.Must(entries.RegisterConverter("nonnative", common.Must2(NewNonNativeConverter(nil)).(entries.Converter)))
    50  	nonnativeifce.NewNonNativeConverterConstructor = NewNonNativeConverter
    51  }