forked from ChakshuGautam/geoquery.in
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
398 lines (380 loc) · 13.8 KB
/
app.js
File metadata and controls
398 lines (380 loc) · 13.8 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import {Reader} from '@maxmind/geoip2-node';
import * as turf from '@turf/turf'
import {Router} from '@stricjs/router';
import * as fs from 'fs';
import Bun from 'bun';
import express from 'express';
import swagger from './util/swagger';
import config from './config.json';
import Logger from './util/logger';
import { Level, LocationSearch } from './location.search';
const buffer = fs.readFileSync(`${import.meta.dir}/db.mmdb`);
const reader = Reader.openBuffer(buffer);
const logger = new Logger('app.js');
const locationSearch = new LocationSearch(`${import.meta.dir}/geojson-data/PARSED_MASTER_LOCATION_NAMES.json`);
const swaggerApp = express();
swagger(swaggerApp);
const GeoLocationLevel = {
VILLAGE: 'VILLAGE',
SUBDISTRICT: 'SUBDISTRICT',
DISTRICT: 'DISTRICT',
STATE: 'STATE'
}
// Check if required geojson files exists
const geoJsonFilesPath = `${import.meta.dir}/geojson-data`;
fs.readdir(geoJsonFilesPath, (err, files) => {
if (err) {
logger.error(`Error reading folder: ${err}`);
process.exit();
}
for (const locationLevel of config.requiredGeoLocationLevels) {
const geoJsonFileName = `${config.country}_${locationLevel}.geojson`;
if (!files.includes(geoJsonFileName)) {
logger.error(`Required GeoJson file: ${geoJsonFileName} not present`);
process.exit();
}
}
});
const geoJsonFiles = {};
for (const locationLevel of config.requiredGeoLocationLevels) {
const geoJsonFileName = `${config.country}_${locationLevel}`;
geoJsonFiles[geoJsonFileName] = JSON.parse(fs.readFileSync(`${geoJsonFilesPath}/${geoJsonFileName}.geojson`, 'utf8'));
logger.info(`Loaded GeoJson file: ${geoJsonFileName}`);
}
// format the success response data
const formatSuccessResponse = (data) => {
return {
status: 'success',
continent: data.continent && data.continent.names ? data.continent.names.en : '',
continentCode: data.continent && data.continent.code ? data.continent.code : '',
country: data.country && data.country.names ? data.country.names.en : '',
countryCode: data.country && data.country.code ? data.country.code : '',
region: data.subdivisions && data.subdivisions[0] ? data.subdivisions[0].isoCode : '',
regionName: data.subdivisions && data.subdivisions[0] && data.subdivisions[0].names ? data.subdivisions[0].names.en : '',
city: data.city && data.city.names ? data.city.names.en : '',
zip: data.postal ? data.postal.code : '',
lat: data.location && data.location.latitude ? data.location.latitude : '',
lon: data.location && data.location.longitude ? data.location.longitude : '',
timezone: data.location && data.location.timeZone ? data.location.timeZone : '',
proxy: data.traits ? (data.traits.isAnonymousProxy || data.traits.isAnonymousVpn || data.traits.isTorExitNode) : '',
hosting: data.traits ? data.traits.isHostingProvider : '',
query: data.traits && data.traits.ipAddress ? data.traits.ipAddress : ''
};
};
// format the georev success response
const formatGeorevSuccessResponse = (data) => {
logger.info(`GeoRev Success Response: ${JSON.stringify(data)}`);
return {
status: 'success',
state: data.stname ? data.stname : '',
district: data.dtname ? data.dtname : '',
subDistrict: data.sdtname ? data.sdtname : ''
}
};
// format the error response data
const formatErrorResponse = (error, ip) => {
logger.error(`Error processing IP: ${ip}, Error: ${error.name}`);
return {
status: "fail",
message: error.name,
query: ip
}
}
const formatCentroidResponse = (data, latitude, longitude) => {
logger.info(`Centroid Success Response: ${JSON.stringify(data)}`);
return {
status: 'success',
state: data.stname ? data.stname : '',
district: data.dtname ? data.dtname : '',
subDistrict: data.sdtname ? data.sdtname : '',
city: '',
block: '',
village: '',
lat: latitude,
lon: longitude
}
}
function isPointInMultiPolygon(multiPolygon, point) {
logger.info(`Checking if point is in MultiPolygon`);
return multiPolygon.geometry.coordinates.some(polygonCoordinates => {
const poly = turf.polygon(polygonCoordinates);
return turf.booleanContains(poly, point);
});
}
function individualQuery(country, geoLocationLevel, coordinates) {
const pointToSearch = turf.point(coordinates);
for (let feature of geoJsonFiles[`${country}_${geoLocationLevel}`].features) {
if (feature.geometry.type === 'Polygon') {
logger.info(`Checking if point is in Polygon`);
let poly = turf.polygon(feature.geometry.coordinates, feature.properties);
if (turf.booleanContains(poly, pointToSearch)) {
logger.info(`Point is in Polygon`);
return poly.properties;
}
} else if (feature.geometry.type === 'MultiPolygon') {
logger.info(`Checking if point is in MultiPolygon`);
if (isPointInMultiPolygon(feature, pointToSearch)) {
logger.info(`Point is in MultiPolygon`);
return feature.properties;
}
}
}
}
export const app = new Router()
.get('/', () => new Response(Bun.file(__dirname + '/www/index.html')))
.get('/city/:ip', (ctx) => {
if (ctx.params.ip === '') {
return Response.json({
message: 'No IP provided in params'
}, { status: 400 })
}
try {
const resp = reader.city(ctx.params.ip);
logger.info(`City Success Response: ${JSON.stringify(resp)}`);
return Response.json(formatSuccessResponse(resp));
} catch (error) {
logger.error(`Error processing IP: ${ctx.params.ip}, Error: ${error.name}`);
return Response.json({
message: `Error processing IP: ${ctx.params.ip}, Error: ${error.name}`
}, { status: 404 });
}
})
.post('/city/batch', async (req) => {
try {
logger.info(`Batch City Request: ${JSON.stringify(req)}`);
const ips = await req.json(); // Extract the 'ips' array from the request body
// Create an array of promises, each promise resolves to the city corresponding to the IP address
const promises = ips.map(async (ip) => {
let response;
try {
response = reader.city(ip);
logger.info(`City Success Response: ${JSON.stringify(response)}`);
return formatSuccessResponse(response);
} catch (error) {
logger.error(`Error processing IP: ${ip}, Error: ${error.name}`);
return formatErrorResponse(error,ip);
}
});
// Wait for all promises to settle and collect the results
const results = await Promise.all(promises);
logger.info(`Batch City Success Response: ${JSON.stringify(results)}`);
return Response.json(results, { status: 200 });
} catch (error) {
logger.error(`Error processing IP addresses: ${error.name}`);
return new Response('Error processing IP addresses', { status: 500 });
}
})
.get('/georev', (ctx) => {
try {
let url = new URL(ctx.url);
let latitude = url.searchParams.get('lat');
let longitude = url.searchParams.get('lon');
if (!latitude || !longitude) {
logger.error(`lat lon query missing`);
return Response.json({
status: 'fail',
error: `lat lon query missing`
}, { status: 400 });
}
// Searching for SUBDISTRICT GeoLocation Level
let resp = individualQuery(config.country, GeoLocationLevel.SUBDISTRICT, [longitude, latitude])
if (!resp) {
logger.error(`No GeoLocation found for lat: ${latitude}, lon ${longitude}`);
return Response.json({
status: "fail",
error: `No GeoLocation found for lat: ${latitude}, lon ${longitude}`
}, { status: 404 });
}
logger.info(`GeoRev Success Response: ${JSON.stringify(resp)}`);
return Response.json(formatGeorevSuccessResponse(resp));
} catch (error) {
logger.error(`Error processing lat lon: ${error.name}`);
return Response.json({
status: "fail",
error: error.message
}, { status: 500 })
}
})
.get('/location/:locationlevel/centroid', async (ctx) => {
try {
let url = new URL(ctx.url);
const locationLevel = ctx.params.locationlevel;
if (!Object.keys(GeoLocationLevel).includes(locationLevel)) {
logger.error(`Unsupported GeoLocation Level: ${locationLevel}`);
return Response.json({
status: 'fail',
error: `Unsupported GeoLocation Level: ${locationLevel}`
}, { status: 400});
}
let query = url.searchParams.get('query');
if (!query) {
logger.error(`No ${locationLevel} query found`);
return Response.json({
status: 'fail',
error: `No ${locationLevel} query found`
}, { status: 400 });
}
let queryFeature;
for (const feature of geoJsonFiles[`${config.country}_${locationLevel}`].features) {
if (feature.properties.levelLocationName.toLowerCase() === query.toLowerCase()) {
queryFeature = feature;
}
}
if (!queryFeature) {
logger.error(`No ${locationLevel} found with name: ${query}`);
return Response.json({
status: 'fail',
error: `No ${locationLevel} found with name: ${query}`
}, { status: 404 });
}
let polygonFeature;
if (queryFeature.geometry.type === 'Polygon') {
polygonFeature = turf.polygon(queryFeature.geometry.coordinates);
} else {
polygonFeature = turf.multiPolygon(queryFeature.geometry.coordinates);
}
const centroid = turf.centroid(polygonFeature);
const longitude = centroid.geometry.coordinates[0];
const latitude = centroid.geometry.coordinates[1];
logger.info(`Centroid Success Response: ${JSON.stringify(queryFeature.properties)}`);
return Response.json(formatCentroidResponse(queryFeature.properties, latitude, longitude), { status : 200 })
} catch (error) {
logger.error(`Error processing ${locationLevel} query: ${error.name}`);
return Response.json({
status: 'fail',
error: error.name
}, { status: 500 });
}
})
.post('/location/:locationlevel/fuzzysearch', async (req) => {
try {
let reqBody = await req.json();
const locationLevel = req.params.locationlevel;
if (!Object.keys(GeoLocationLevel).includes(locationLevel)) {
return Response.json({
status: 'fail',
error: `Unsupported GeoLocation Level: ${locationLevel}`
}, { status: 400});
}
let query = reqBody.query;
if (!query) {
return Response.json({
status: 'fail',
error: `No ${locationLevel} query found`
}, { status: 400 });
}
let filter = reqBody.filter;
let filterArray = [];
if (filter) {
for (const filterKey of Object.keys(filter)) {
if (!Object.keys(GeoLocationLevel).includes(filterKey)) {
return Response.json({
status: 'fail',
error: `Unsupported GeoLocation Level Filter: ${filterKey}`,
}, { status: 400 })
}
filterArray.push({
level: Level[`${filterKey}`],
query: filter[filterKey],
});
}
}
let searchLevel;
switch (locationLevel) {
case 'STATE':
searchLevel = Level.STATE;
break;
case 'DISTRICT':
searchLevel = Level.DISTRICT;
break;
case 'SUBDISTRICT':
searchLevel = Level.SUBDISTRICT;
break;
case 'VILLAGE':
searchLevel = Level.VILLAGE;
break;
default:
// Unreachable
break;
}
const queryResponse = locationSearch.fuzzySearch(searchLevel, query, filterArray);
return Response.json({
matches: queryResponse
}, { status: 200 });
} catch (error) {
return Response.json({
status: 'fail',
error: error.name
}, { status: 500 });
}
})
.post('/location/:locationlevel/fuzzysearch', async (req) => {
try {
let reqBody = await req.json();
const locationLevel = req.params.locationlevel;
if (!Object.keys(GeoLocationLevel).includes(locationLevel)) {
return Response.json({
status: 'fail',
error: `Unsupported GeoLocation Level: ${locationLevel}`
}, { status: 400});
}
let query = reqBody.query;
if (!query) {
return Response.json({
status: 'fail',
error: `No ${locationLevel} query found`
}, { status: 400 });
}
let filter = reqBody.filter;
let filterArray = [];
if (filter) {
for (const filterKey of Object.keys(filter)) {
if (!Object.keys(GeoLocationLevel).includes(filterKey)) {
return Response.json({
status: 'fail',
error: `Unsupported GeoLocation Level Filter: ${filterKey}`,
}, { status: 400 })
}
filterArray.push({
level: Level[`${filterKey}`],
query: filter[filterKey],
});
}
}
let searchLevel;
switch (locationLevel) {
case 'STATE':
searchLevel = Level.STATE;
break;
case 'DISTRICT':
searchLevel = Level.DISTRICT;
break;
case 'SUBDISTRICT':
searchLevel = Level.SUBDISTRICT;
break;
case 'VILLAGE':
searchLevel = Level.VILLAGE;
break;
default:
// Unreachable
break;
}
const queryResponse = locationSearch.fuzzySearch(searchLevel, query, filterArray);
return Response.json({
matches: queryResponse
}, { status: 200 });
} catch (error) {
return Response.json({
status: 'fail',
error: error.name
}, { status: 500 });
}
});
app.use(404, () => {
logger.error(`404 Not Found`);
return new Response(Bun.file(import.meta.dir + '/www/404.html'))
});
app.port = (process.env.PORT || 3000);
app.hostname = '0.0.0.0';
swaggerApp.listen(3001, () => logger.info('Swagger listening on port 3000'));
app.listen();