-
-
Notifications
You must be signed in to change notification settings - Fork 340
/
Copy pathindex.ts
41 lines (36 loc) · 1.39 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { Reader } from 'maxmind';
import {
Context, findFileSync, fs, Service,
} from 'hydrooj';
const buffer = fs.readFileSync(findFileSync('@hydrooj/geoip/GeoLite2-City.mmdb'));
const reader = new Reader(buffer);
export interface Result {
location?: string,
continent?: string,
country?: string,
city?: string,
display: string
}
export default class GeoIPService extends Service {
constructor(ctx: Context) {
super(ctx, 'geoip', true);
}
provider = '<a href="http://www.maxmind.com" target="_blank">MaxMind</a>';
lookup(ip: string, locale: string): Result {
const res: any = reader.get(ip);
if (!res) return { display: 'Unknown address'.translate(locale) };
const ret: Result = { display: '' };
if (res.location) ret.location = res.location;
if (res.continent) ret.continent = res.continent.names[locale] || res.continent.names.en;
if (res.country || res.registered_country) {
ret.country = (res.country || res.registered_country).names[locale]
|| (res.country || res.registered_country).names.en;
}
if (res.city) ret.city = res.city.names[locale] || res.city.names.en;
ret.display = `${ret.continent} ${ret.country}${ret.city ? ` ${ret.city}` : ''}`;
return ret;
}
}
export async function apply(ctx: Context) {
ctx.set('geoip', new GeoIPService(ctx));
}