Feature: verify mmdb on initial

This commit is contained in:
Dreamacro 2020-04-16 19:12:25 +08:00
parent 5c03613858
commit 84f627f302
2 changed files with 33 additions and 5 deletions

View File

@ -22,6 +22,14 @@ func LoadFromBytes(buffer []byte) {
})
}
func Verify() bool {
instance, err := geoip2.Open(C.Path.MMDB())
if err == nil {
instance.Close()
}
return err == nil
}
func Instance() *geoip2.Reader {
once.Do(func() {
var err error

View File

@ -6,6 +6,7 @@ import (
"net/http"
"os"
"github.com/Dreamacro/clash/component/mmdb"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/log"
)
@ -27,6 +28,28 @@ func downloadMMDB(path string) (err error) {
return err
}
func initMMDB() error {
if _, err := os.Stat(C.Path.MMDB()); os.IsNotExist(err) {
log.Infoln("Can't find MMDB, start download")
if err := downloadMMDB(C.Path.MMDB()); err != nil {
return fmt.Errorf("Can't download MMDB: %s", err.Error())
}
}
if !mmdb.Verify() {
log.Warnln("MMDB invalid, remove and download")
if err := os.Remove(C.Path.MMDB()); err != nil {
return fmt.Errorf("Can't remove invalid MMDB: %s", err.Error())
}
if err := downloadMMDB(C.Path.MMDB()); err != nil {
return fmt.Errorf("Can't download MMDB: %s", err.Error())
}
}
return nil
}
// Init prepare necessary files
func Init(dir string) error {
// initial homedir
@ -48,11 +71,8 @@ func Init(dir string) error {
}
// initial mmdb
if _, err := os.Stat(C.Path.MMDB()); os.IsNotExist(err) {
log.Infoln("Can't find MMDB, start download")
if err := downloadMMDB(C.Path.MMDB()); err != nil {
return fmt.Errorf("Can't download MMDB: %s", err.Error())
}
if err := initMMDB(); err != nil {
return fmt.Errorf("Can't initial MMDB: %w", err)
}
return nil
}