DynuIPRefresher/src/IPRefresher.cpp

73 lines
1.9 KiB
C++
Raw Normal View History

//
// Created by lukas on 02.08.19.
//
#include "IPRefresher.h"
#include "FileLogger.h"
#include "api/IPAPI.h"
#include "api/DynuAPI.h"
#include "api/TelegramAPI.h"
#include "Config.h"
#include "Version.h"
#include <string>
#include <chrono>
#include <thread>
#include <Logger.h>
#include <climits>
void IPRefresher::checkIPAdress(bool force) {
2019-10-26 12:41:43 +00:00
FileLogger logger;
IPAPI ipapi;
std::string ip = ipapi.getGlobalIp();
if (ip.empty()) {
2020-04-30 09:30:41 +00:00
//no internet connection (or other error)
Logger::warning("no internet connection");
} else if (ip.find(':') == ULONG_MAX) {
// error when ip doesn't contain a :
Logger::warning("an error occured when getting the global ip");
} else {
std::string oldip = logger.readip();
if (oldip == ip && !force) {
Logger::message("no change -- ip: " + ip);
} else {
Logger::message("ip changed! -- from :" + oldip + "to: " + ip);
DynuAPI dynu;
2020-04-30 17:37:11 +00:00
dynu.init(Config::dynuapikey, Config::domainid, Config::domainname);
if (dynu.refreshIp(ip)) {
TelegramAPI tele;
2020-04-30 17:37:11 +00:00
tele.init(Config::telegramApiKey, Config::chatId);
tele.sendMessage(oldip + " moved to " + ip);
} else {
//error
Logger::error("failed to write ip to dynu api!");
}
logger.safeip(ip);
}
}
}
2020-04-30 10:16:29 +00:00
IPRefresher::IPRefresher() = default;
IPRefresher::IPRefresher(bool loop) {
2020-04-30 17:37:11 +00:00
if (loop) {
2020-04-30 09:30:41 +00:00
Logger::message("startup of service");
Logger::message("Version: " + Version::VERSION);
2020-04-30 17:37:11 +00:00
if (Config::readCredentials()) {
while (true) {
Logger::message("starting check");
checkIPAdress(false);
std::this_thread::sleep_for(std::chrono::milliseconds(300000));
}
} else {
std::cout << "incorrect credentials!" << std::endl;
2020-04-30 09:30:41 +00:00
}
}
}