Clash.Meta/component/geodata/standard/standard.go

93 lines
2.3 KiB
Go
Raw Normal View History

2021-07-01 22:49:29 +08:00
package standard
import (
"fmt"
2021-10-28 00:06:55 +08:00
"io"
2021-07-01 22:49:29 +08:00
"os"
"strings"
2023-11-03 21:01:45 +08:00
"github.com/metacubex/mihomo/component/geodata"
"github.com/metacubex/mihomo/component/geodata/router"
C "github.com/metacubex/mihomo/constant"
2022-02-23 01:00:27 +08:00
2021-07-01 22:49:29 +08:00
"google.golang.org/protobuf/proto"
)
func ReadFile(path string) ([]byte, error) {
reader, err := os.Open(path)
if err != nil {
return nil, err
}
defer func(reader *os.File) {
_ = reader.Close()
}(reader)
2021-07-01 22:49:29 +08:00
2021-10-28 00:06:55 +08:00
return io.ReadAll(reader)
2021-07-01 22:49:29 +08:00
}
func ReadAsset(file string) ([]byte, error) {
return ReadFile(C.Path.GetAssetLocation(file))
}
2022-06-03 16:50:05 +08:00
func loadIP(geoipBytes []byte, country string) ([]*router.CIDR, error) {
2021-07-01 22:49:29 +08:00
var geoipList router.GeoIPList
if err := proto.Unmarshal(geoipBytes, &geoipList); err != nil {
return nil, err
}
for _, geoip := range geoipList.Entry {
if strings.EqualFold(geoip.CountryCode, country) {
return geoip.Cidr, nil
}
}
2022-06-03 16:50:05 +08:00
return nil, fmt.Errorf("country %s not found", country)
2021-07-01 22:49:29 +08:00
}
2022-06-03 16:50:05 +08:00
func loadSite(geositeBytes []byte, list string) ([]*router.Domain, error) {
2021-07-01 22:49:29 +08:00
var geositeList router.GeoSiteList
if err := proto.Unmarshal(geositeBytes, &geositeList); err != nil {
return nil, err
}
for _, site := range geositeList.Entry {
if strings.EqualFold(site.CountryCode, list) {
return site.Domain, nil
}
}
2022-06-03 16:50:05 +08:00
return nil, fmt.Errorf("list %s not found", list)
2021-07-01 22:49:29 +08:00
}
type standardLoader struct{}
2022-06-03 16:50:05 +08:00
func (d standardLoader) LoadSiteByPath(filename, list string) ([]*router.Domain, error) {
geositeBytes, err := ReadAsset(filename)
if err != nil {
return nil, fmt.Errorf("failed to open file: %s, base error: %s", filename, err.Error())
}
return loadSite(geositeBytes, list)
}
func (d standardLoader) LoadSiteByBytes(geositeBytes []byte, list string) ([]*router.Domain, error) {
return loadSite(geositeBytes, list)
}
func (d standardLoader) LoadIPByPath(filename, country string) ([]*router.CIDR, error) {
geoipBytes, err := ReadAsset(filename)
if err != nil {
return nil, fmt.Errorf("failed to open file: %s, base error: %s", filename, err.Error())
}
return loadIP(geoipBytes, country)
2021-07-01 22:49:29 +08:00
}
2022-06-03 16:50:05 +08:00
func (d standardLoader) LoadIPByBytes(geoipBytes []byte, country string) ([]*router.CIDR, error) {
return loadIP(geoipBytes, country)
2021-07-01 22:49:29 +08:00
}
func init() {
geodata.RegisterGeoDataLoaderImplementationCreator("standard", func() geodata.LoaderImplementation {
return standardLoader{}
})
}