59 lines
2.0 KiB
C++
59 lines
2.0 KiB
C++
|
|
#include <exception>
|
|
#include <cstdlib>
|
|
#include <map>
|
|
#include <string>
|
|
#include <fstream>
|
|
#include <filesystem>
|
|
#include <chrono>
|
|
#include <iomanip>
|
|
|
|
|
|
#include "ip_to_geo.hpp"
|
|
#include "../third_party/include/GeoLite2PP.hpp"
|
|
|
|
loc_data iplookup(const std::string& ip) {
|
|
const char* env_db_path = std::getenv("DB_PATH");
|
|
std::string db_path = (env_db_path != nullptr) ? env_db_path : "data/GeoLite2-City.mmdb";
|
|
|
|
// Verify if the database file physically exists on the disk
|
|
if (!std::filesystem::exists(db_path)) {
|
|
std::ofstream error_file("error.log", std::ios::app);
|
|
if (error_file.is_open()) {
|
|
auto now = std::chrono::system_clock::now();
|
|
std::time_t now_time = std::chrono::system_clock::to_time_t(now);
|
|
|
|
error_file << "[" << std::put_time(std::localtime(&now_time), "%Y-%m-%d %H:%M:%S") << "] "
|
|
<< "Error: Database file missing at path: " << db_path << " during IP lookup for: " << ip << std::endl;
|
|
error_file.close();
|
|
}
|
|
|
|
return loc_data{};
|
|
}
|
|
|
|
loc_data location;
|
|
|
|
try {
|
|
GeoLite2PP::DB db(db_path);
|
|
std::map<std::string, std::string> geo_data = db.get_all_fields(ip, "en");
|
|
location.country = geo_data["country"];
|
|
location.subdivision = geo_data["subdivision"];
|
|
location.city = geo_data["city"];
|
|
location.latitutde = geo_data["latitude"];
|
|
location.longitude = geo_data["longitude"];
|
|
}
|
|
catch (const std::exception& e) {
|
|
std::ofstream error_file("error.log", std::ios::app);
|
|
if (error_file.is_open()) {
|
|
auto now = std::chrono::system_clock::now();
|
|
std::time_t now_time = std::chrono::system_clock::to_time_t(now);
|
|
|
|
error_file << "[" << std::put_time(std::localtime(&now_time), "%Y-%m-%d %H:%M:%S") << "] "
|
|
<< "Database failed to load: " << e.what() << std::endl;
|
|
|
|
error_file.close();
|
|
}
|
|
}
|
|
|
|
return location;
|
|
}; |