traxxx/src/utils/resolve-place.js

86 lines
2.3 KiB
JavaScript
Executable File

'use strict';
const config = require('config');
const knex = require('../knex');
const logger = require('../logger')(__filename);
const http = require('./http');
const slugify = require('./slugify');
const argv = require('../argv');
const redis = require('../redis');
async function resolvePlace(query) {
if (!query) {
return null;
}
const cacheKey = `place-${slugify(query)}`;
const cachedPlace = await redis.hGetAll(cacheKey);
if (argv.placeCache !== false && await redis.exists(cacheKey)) {
await redis.expire(cacheKey, 3600 * 24 * 30);
logger.debug(`Using cached place '${cacheKey}' for query '${query}': ${JSON.stringify(cachedPlace)}`);
return cachedPlace;
}
// query is a nationality, lookup would get weird results (British resolves to British, Northern Ireland)
const country = await knex('countries')
.where('nationality', 'ilike', `%${query}%`)
.orWhere('alpha3', 'ilike', `%${query}%`)
.orWhere('alpha2', 'ilike', `%${query}%`)
.orderBy('priority', 'desc')
.first();
if (country) {
return {
country: country.alpha2,
};
}
try {
// https://operations.osmfoundation.org/policies/nominatim/
const res = await http.get(`https://nominatim.openstreetmap.org/search?q=${encodeURI(query)}&format=json&accept-language=en&addressdetails=1`, {
headers: {
'User-Agent': config.location.userAgent,
},
interval: 1000,
concurrency: 1,
});
const [item] = res.body;
if (item && item.address) {
const rawPlace = item.address;
const place = {};
if (item.class === 'place' || item.class === 'boundary') {
const location = rawPlace[item.type] || rawPlace.city || rawPlace.place || rawPlace.town;
if (location) {
place.place = location;
place.city = rawPlace.city || location;
}
}
if (rawPlace.state) place.state = rawPlace.state;
if (rawPlace.country_code) place.country = rawPlace.country_code.toUpperCase();
if (rawPlace.continent) place.continent = rawPlace.continent;
logger.debug(`Resolved place '${query}' to ${JSON.stringify(place)}`);
await redis.hSet(cacheKey, place);
await redis.expire(cacheKey, 3600 * 24 * 30);
return place;
}
} catch (error) {
logger.error(`Failed to resolve place '${query}': ${error.message}`);
}
return null;
}
module.exports = resolvePlace;