github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/main/commands/all/engineering/subscriptionEntriesExtract.go (about)

     1  package engineering
     2  
     3  import (
     4  	"archive/zip"
     5  	"encoding/json"
     6  	"flag"
     7  	"fmt"
     8  	"io"
     9  	"os"
    10  
    11  	"golang.org/x/crypto/sha3"
    12  
    13  	"github.com/v2fly/v2ray-core/v5/app/subscription/containers"
    14  	"github.com/v2fly/v2ray-core/v5/main/commands/base"
    15  )
    16  
    17  var cmdSubscriptionEntriesExtractInputName *string
    18  
    19  var cmdSubscriptionEntriesExtract = &base.Command{
    20  	UsageLine: "{{.Exec}} engineering subscriptionEntriesExtract",
    21  	Flag: func() flag.FlagSet {
    22  		fs := flag.NewFlagSet("", flag.ExitOnError)
    23  		cmdSubscriptionEntriesExtractInputName = fs.String("input", "", "")
    24  		return *fs
    25  	}(),
    26  	Run: func(cmd *base.Command, args []string) {
    27  		cmd.Flag.Parse(args)
    28  		inputReader := os.Stdin
    29  		if *cmdSubscriptionEntriesExtractInputName != "" {
    30  			file, err := os.Open(*cmdSubscriptionEntriesExtractInputName)
    31  			if err != nil {
    32  				base.Fatalf("%s", err)
    33  			}
    34  			inputReader = file
    35  			defer file.Close()
    36  		}
    37  		content, err := io.ReadAll(inputReader)
    38  		if err != nil {
    39  			base.Fatalf("%s", err)
    40  		}
    41  		parsed, err := containers.TryAllParsers(content, "")
    42  		if err != nil {
    43  			base.Fatalf("%s", err)
    44  		}
    45  		zipWriter := zip.NewWriter(os.Stdout)
    46  		{
    47  			writer, err := zipWriter.Create("meta.json")
    48  			if err != nil {
    49  				base.Fatalf("%s", err)
    50  			}
    51  			err = json.NewEncoder(writer).Encode(parsed.Metadata)
    52  			if err != nil {
    53  				base.Fatalf("%s", err)
    54  			}
    55  		}
    56  		for k, entry := range parsed.ServerSpecs {
    57  			hash := sha3.Sum256(entry.Content)
    58  			fileName := fmt.Sprintf("entry_%v_%x", k, hash[:8])
    59  			writer, err := zipWriter.Create(fileName)
    60  			if err != nil {
    61  				base.Fatalf("%s", err)
    62  			}
    63  			_, err = writer.Write(entry.Content)
    64  			if err != nil {
    65  				base.Fatalf("%s", err)
    66  			}
    67  		}
    68  		zipWriter.Close()
    69  	},
    70  }