2019-10-27 16:54:23 +08:00
|
|
|
package ipgeo
|
|
|
|
|
|
|
|
import (
|
|
|
|
"flag"
|
|
|
|
"log"
|
2019-11-17 03:51:15 +08:00
|
|
|
|
|
|
|
"git.eve.moe/jackyyf/navigator/mapping/elf"
|
|
|
|
"github.com/ipipdotnet/ipdb-go"
|
|
|
|
"go.starlark.net/starlark"
|
|
|
|
"go.starlark.net/starlarkstruct"
|
2019-10-27 16:54:23 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
requiredFields = []string{
|
|
|
|
"country_name",
|
|
|
|
"region_name",
|
|
|
|
"city_name",
|
|
|
|
"isp_domain",
|
|
|
|
"country_code",
|
|
|
|
"continent_code",
|
|
|
|
}
|
|
|
|
ipipdb = flag.String("ipdb-database", "ipip.db", "path to ipip database")
|
|
|
|
db *ipdb.City
|
|
|
|
)
|
|
|
|
|
2019-11-17 03:51:15 +08:00
|
|
|
func Initialize() {
|
2019-10-27 16:54:23 +08:00
|
|
|
var err error
|
|
|
|
db, err = ipdb.NewCity(*ipipdb)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalln("Unable to open ipdb:", err.Error())
|
|
|
|
}
|
|
|
|
if !db.IsIPv4() {
|
|
|
|
log.Fatalln("This IPIP.net database has no IPv4 information!")
|
|
|
|
}
|
|
|
|
{
|
|
|
|
fields := db.Fields()
|
|
|
|
for _, requiredField := range requiredFields {
|
|
|
|
ok := false
|
|
|
|
for _, field := range fields {
|
|
|
|
if field == requiredField {
|
|
|
|
ok = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !ok {
|
2019-11-17 03:51:15 +08:00
|
|
|
log.Fatalln("This IPIP.net database has no required field",
|
|
|
|
requiredField)
|
2019-10-27 16:54:23 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func Get() *ipdb.City {
|
|
|
|
return db
|
|
|
|
}
|
2019-11-17 03:51:15 +08:00
|
|
|
|
|
|
|
func init() {
|
|
|
|
elf.RegisterFunc("geoLookup",
|
|
|
|
func(t *starlark.Thread, b *starlark.Builtin, args starlark.Tuple,
|
|
|
|
kwargs []starlark.Tuple) (starlark.Value, error) {
|
|
|
|
var ip string
|
|
|
|
if err := starlark.UnpackArgs(b.Name(), args, kwargs,
|
|
|
|
"ip", &ip); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
result, err := db.FindInfo(ip, "EN")
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return starlarkstruct.FromStringDict(
|
|
|
|
starlark.String("IPDBCityInfo"),
|
|
|
|
starlark.StringDict{
|
|
|
|
"CountryName": starlark.String(result.CountryName),
|
|
|
|
"RegionName": starlark.String(result.RegionName),
|
|
|
|
"CityName": starlark.String(result.CityName),
|
|
|
|
"IspDomain": starlark.String(result.IspDomain),
|
|
|
|
"CountryCode": starlark.String(result.CountryCode),
|
|
|
|
"ContinentCode": starlark.String(result.ContinentCode),
|
|
|
|
}), nil
|
|
|
|
})
|
|
|
|
}
|