geoip: use context.service

This commit is contained in:
undefined committed 2022-10-04 23:54:25 +08:00
1 parent 63c9c00d1d
commit d94e3e650a
6 files changed
+65 -64

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
import fs from 'fs';
import { Reader } from 'maxmind';
import { Context, findFileSync, 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 function apply() {
Context.service('geoip', class GeoIPService extends Service {
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;
}
});
}
-35
View File
@@ -1,35 +0,0 @@
import 'hydrooj';
import fs from 'fs';
import { Reader } from 'maxmind';
import { findFileSync } from '@hydrooj/utils/lib/utils';
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 function 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 const provider = '<a href="http://www.maxmind.com" target="_blank">MaxMind</a>';
global.Hydro.lib.geoip = { provider, lookup };
+1 -4
View File
@@ -1,7 +1,7 @@
{
"name": "@hydrooj/geoip",
"version": "1.2.3",
"main": "package.json",
"main": "index.ts",
"repository": "git@github.com:hydro-dev/Hydro.git",
"author": "undefined <i@undefined.moe>",
"license": "AGPL-3.0-or-later",
@@ -11,8 +11,5 @@
"preferUnplugged": true,
"scripts": {
"prepublish": "./download.sh"
},
"peerDependencies": {
"hydrooj": "*"
}
}