github.com/chwjbn/xclash@v0.2.0/config/initial.go (about)

     1  package config
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"net/http"
     7  	"os"
     8  
     9  	"github.com/chwjbn/xclash/component/mmdb"
    10  	C "github.com/chwjbn/xclash/constant"
    11  	"github.com/chwjbn/xclash/log"
    12  )
    13  
    14  func downloadMMDB(path string) (err error) {
    15  	resp, err := http.Get("https://cdn.jsdelivr.net/gh/Dreamacro/maxmind-geoip@release/Country.mmdb")
    16  	if err != nil {
    17  		return
    18  	}
    19  	defer resp.Body.Close()
    20  
    21  	f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0o644)
    22  	if err != nil {
    23  		return err
    24  	}
    25  	defer f.Close()
    26  	_, err = io.Copy(f, resp.Body)
    27  
    28  	return err
    29  }
    30  
    31  func initMMDB() error {
    32  	if _, err := os.Stat(C.Path.MMDB()); os.IsNotExist(err) {
    33  		log.Infoln("Can't find MMDB, start download")
    34  		if err := downloadMMDB(C.Path.MMDB()); err != nil {
    35  			return fmt.Errorf("can't download MMDB: %s", err.Error())
    36  		}
    37  	}
    38  
    39  	if !mmdb.Verify() {
    40  		log.Warnln("MMDB invalid, remove and download")
    41  		if err := os.Remove(C.Path.MMDB()); err != nil {
    42  			return fmt.Errorf("can't remove invalid MMDB: %s", err.Error())
    43  		}
    44  
    45  		if err := downloadMMDB(C.Path.MMDB()); err != nil {
    46  			return fmt.Errorf("can't download MMDB: %s", err.Error())
    47  		}
    48  	}
    49  
    50  	return nil
    51  }
    52  
    53  // Init prepare necessary files
    54  func Init(dir string) error {
    55  	// initial homedir
    56  	if _, err := os.Stat(dir); os.IsNotExist(err) {
    57  		if err := os.MkdirAll(dir, 0o777); err != nil {
    58  			return fmt.Errorf("can't create config directory %s: %s", dir, err.Error())
    59  		}
    60  	}
    61  
    62  	// initial config.yaml
    63  	if _, err := os.Stat(C.Path.Config()); os.IsNotExist(err) {
    64  		log.Infoln("Can't find config, create a initial config file")
    65  		f, err := os.OpenFile(C.Path.Config(), os.O_CREATE|os.O_WRONLY, 0o644)
    66  		if err != nil {
    67  			return fmt.Errorf("can't create file %s: %s", C.Path.Config(), err.Error())
    68  		}
    69  		f.Write([]byte(`mixed-port: 7890`))
    70  		f.Close()
    71  	}
    72  
    73  	// initial mmdb
    74  	if err := initMMDB(); err != nil {
    75  		return fmt.Errorf("can't initial MMDB: %w", err)
    76  	}
    77  	return nil
    78  }