16 Commits
v1.3.3 ... GUI

Author SHA1 Message Date
b5b352f83d namespace for IPRefresher instead of class 2020-05-15 13:57:09 +02:00
3b32f60190 added return codes for IPrefresher refresh method.
error messages in gui.
2020-05-14 23:08:19 +02:00
0eea7095e0 added better thread management
cross compilation features.
2020-05-10 18:10:44 +02:00
ab772aac55 further gui developments 2020-05-10 15:00:51 +02:00
c25996a925 first qt gui steps 2020-05-09 23:08:23 +02:00
826386e849 define cached files globally/ including last test job 2020-05-08 17:28:19 +02:00
25f32dc4f4 cache whole project between jobs 2020-05-08 17:23:19 +02:00
2b863c6050 keep data between stages 2020-05-08 17:20:11 +02:00
a43b730b53 multistaging ci 2020-05-08 17:17:20 +02:00
309aefee2e added a build badge 2020-05-08 17:02:46 +02:00
713e7a1f95 everywhere same code header
reformatings
cdoc
2020-05-08 16:45:27 +02:00
12de026842 Update .gitlab-ci.yml 2020-05-07 18:08:31 +00:00
463853dbd7 Unit test framework (#10)
* add first Unit Test
with gtest and cmake dependencies

* optionally build tests or not
added some realistic tests

* added ci compatible run configuration

* added test dependencies -lpthread -lm to work in debian correctly

* added some docs
and option infos
2020-05-07 19:58:16 +02:00
335bcf1259 wrong variable name 2020-05-07 16:19:59 +02:00
db4c71d7fe don't use find_package for libconfig, no default package in debian/libconfig installation 2020-05-07 16:17:47 +02:00
ba4af36df0 * new class for IP utils
* method to check telegram support out of config
* getters in Config.cpp
* lots of reformatings and cdoc
2020-05-07 14:54:40 +02:00
28 changed files with 708 additions and 174 deletions

View File

@ -1,17 +1,49 @@
image: luki42/dynuiprefresher_build:latest image: luki42/dynuiprefresher_build:latest
stages: stages:
- cmake
- build - build
- build_package
- test
cache:
paths:
- build/
- src/
- inc/
- tests/
- postinst
cmake:
stage: cmake
script:
- cmake -S . -B build
build: build:
stage: build stage: build
script: script:
- cmake -S . -B build
- cd build - cd build
- make - make
- make package
artifacts: artifacts:
paths: paths:
- "build/bin/*" - "build/bin/*"
- "build/packages/*"
build_package:
stage: build_package
script:
- cd build
- make package
artifacts:
paths:
- "build/packages/*"
test:
stage: test
script:
- cd build
- make test
- make build-xml
artifacts:
reports:
junit: build/report.xml

View File

@ -5,21 +5,27 @@
## libcurl (with sources) ## libcurl (with sources)
## libconfig (with sources) ## libconfig (with sources)
# #
# documenation build needs doxygen to be installed. # for documenation build doxygen needs to be installed.
# for test build gtest needs to be installed.
cmake_minimum_required(VERSION 3.13) cmake_minimum_required(VERSION 3.13)
project(iprefresher DESCRIPTION "Dynu ip refresher") project(iprefresher DESCRIPTION "Dynu ip refresher")
SET(PROJECT_VERSION 1.3.3) SET(PROJECT_VERSION 1.3.3)
SET(CMAKE_CXX_STANDARD 17)
# CONFIGURATION # CONFIGURATION
SET(CMAKE_BUILD_TYPE Release) # manually SET build type (Release / Debug) SET(CMAKE_BUILD_TYPE Release) # manually SET build type (Release / Debug)
SET(LIB_METHOD STATIC) #SHARED / STATIC SET(LIB_METHOD STATIC) #SHARED / STATIC
option(BUILD_DOC "Build documentation" OFF) # additional dependency for Doxygen option(BUILD_DOC "Build documentation" ON) # additional dependency for Doxygen
option(PACKAGING "Allow Packaging to <exe>, <deb> or <rpm>" ON) # additional dependencies for RPMbuild,dpkg or NSIS option(PACKAGING "Allow Packaging to <exe>, <deb> or <rpm>" ON) # additional dependencies for RPMbuild,dpkg or NSIS
option(TESTS "Build Tests" ON) # additional dependencies for GTEST - to build tests
option(GUI "Build GUI elements" ON) # additional dependencies to QT libraries needed
set(WinBuild false) set(WinBuild false)
# helper variables
SET(CMAKE_CXX_STANDARD 17)
string(TIMESTAMP TIMESTAMP_NOW "%d.%m.%Y")
SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
@ -93,6 +99,10 @@ if (${WinBuild})
message(STATUS "Using LIBCONFIG++ lib(s): ${LIBCONFIG++_LIBRARIES}") message(STATUS "Using LIBCONFIG++ lib(s): ${LIBCONFIG++_LIBRARIES}")
include_directories(${LIBCONFIG++_INCLUDE_DIRS} inc) include_directories(${LIBCONFIG++_INCLUDE_DIRS} inc)
if (${GUI})
set(CMAKE_PREFIX_PATH "/usr/${TOOLCHAIN_PREFIX}/sys-root/mingw/lib/cmake")
endif ()
else () else ()
find_package(CURL REQUIRED) find_package(CURL REQUIRED)
if (CURL_INCLUDE_DIRS AND CURL_LIBRARIES) if (CURL_INCLUDE_DIRS AND CURL_LIBRARIES)
@ -106,15 +116,31 @@ else ()
message("") message("")
# libconfig # libconfig
FIND_PACKAGE(libconfig++ REQUIRED) FIND_PATH(LIBCONFIG++_INCLUDE_DIRS
if (LIBCONFIG++_INCLUDE_DIRS AND LIBCONFIG++_LIBRARY_DIRS) NAMES libconfig.h++
message(STATUS "Found libconfig version: ${LIBCONFIG++_VERSION}") PATHS /usr/include /usr/local/include) # search for libconfig include headers
FIND_LIBRARY(LIBCONFIG++_LIBRARIES
NAMES config++
PATHS /usr/lib /usr/local/lib) # search for actual lib
if (LIBCONFIG++_INCLUDE_DIRS AND LIBCONFIG++_LIBRARIES)
message(STATUS "Fount libconfig!")
message(STATUS "Using libconfig include dir(s): ${LIBCONFIG++_INCLUDE_DIRS}") message(STATUS "Using libconfig include dir(s): ${LIBCONFIG++_INCLUDE_DIRS}")
message(STATUS "Using libconfig lib(s): ${LIBCONFIG++_LIBRARY_DIRS}") message(STATUS "Using libconfig lib(s): ${LIBCONFIG++_LIBRARIES}")
else () else ()
message(FATAL_ERROR "Could not find CURL") message(FATAL_ERROR "Could not find LIBCONFIG")
endif () endif ()
include_directories(${LIBCONFIG++_INCLUDE_DIRS} inc)
include_directories(${LIBCONFIG_INCLUDE_DIRS})
endif ()
if (${GUI})
set(CMAKE_AUTOMOC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
find_package(Qt5Widgets REQUIRED)
find_package(Qt5PrintSupport REQUIRED)
find_package(Qt5Sql REQUIRED)
endif () endif ()
message("") message("")
@ -123,8 +149,18 @@ message("")
FILE(READ ${CMAKE_SOURCE_DIR}/config/iprefresher.cfg SAMPLECONFIG) FILE(READ ${CMAKE_SOURCE_DIR}/config/iprefresher.cfg SAMPLECONFIG)
#add version header #add version header
FILE(WRITE ${CMAKE_SOURCE_DIR}/inc/Version.h FILE(WRITE ${CMAKE_SOURCE_DIR}/inc/Version.h
"\#pragma once "/**
* Version header to store Version, Config dir and a Sample config
* Do not edit this file manually, it is generated by the cmake script!
*
* @author Lukas Heiligenbrunner
* @date ${TIMESTAMP_NOW}
*/
#pragma once
#include <string> #include <string>
namespace Version { namespace Version {
const std::string VERSION = \"${PROJECT_VERSION}\"; const std::string VERSION = \"${PROJECT_VERSION}\";
const std::string ConfigDir = \"${CONFIG_PATH}\"; const std::string ConfigDir = \"${CONFIG_PATH}\";
@ -138,20 +174,40 @@ add_library(api ${LIB_METHOD}
src/api/DynuAPI.cpp src/api/DynuAPI.cpp
src/api/IPAPI.cpp) src/api/IPAPI.cpp)
add_library(logger ${LIB_METHOD} add_library(dynuiprefresher ${LIB_METHOD}
src/FileLogger.cpp
src/Logger.cpp)
SET(SOURCE
src/main.cpp
src/IPRefresher.cpp src/IPRefresher.cpp
src/Config.cpp) src/Config.cpp
src/IpHelper.cpp
src/FileLogger.cpp
src/Logger.cpp
)
add_executable(iprefresher ${SOURCE}) add_executable(iprefresher src/main.cpp)
# LINK generated LIBS # # LINK generated LIBS #
target_link_libraries(iprefresher api logger ${CURL_LIBRARIES} ${LIBCONFIG++_LIBRARIES}) target_link_libraries(iprefresher dynuiprefresher api ${CURL_LIBRARIES} ${LIBCONFIG++_LIBRARIES})
if (${GUI})
set(QT5_LIBRARIES Qt5::Widgets Qt5::PrintSupport Qt5::Sql)
set(UI_SOURCES
src/gui/mainwindow.ui
)
#
# Generate necessary headers from .ui files. (qmake lets `uic` do this job.)
# hint from [Cross-platform Qt5 project using cmake](http://stackoverflow.com/questions/21174586/cross-platform-qt5-project-using-cmake)
#
qt5_wrap_ui(UI_GENERATED_HEADERS ${UI_SOURCES})
add_executable(iprefresher-gui
src/maingui.cpp
src/gui/MainWindow.cpp
src/gui/MainWindow.h ${UI_GENERATED_HEADERS})
# LINK generated LIBS #
target_link_libraries(iprefresher-gui -lpthread dynuiprefresher api ${CURL_LIBRARIES} ${LIBCONFIG++_LIBRARIES} ${QT5_LIBRARIES})
endif ()
# setting install targets # setting install targets
IF (NOT ${WinBuild}) IF (NOT ${WinBuild})
@ -201,6 +257,8 @@ if (${PACKAGING})
# generate post script for checking if configuration already exists # generate post script for checking if configuration already exists
FILE(WRITE ${CMAKE_SOURCE_DIR}/postinst FILE(WRITE ${CMAKE_SOURCE_DIR}/postinst
"#!/bin/bash "#!/bin/bash
# Post installation script for linux packages
# do not edit this file manually, it is generated by the cmake script
if [ ! -f ${CONFIG_PATH} ]; then if [ ! -f ${CONFIG_PATH} ]; then
cat > ${CONFIG_PATH} <<- EOM cat > ${CONFIG_PATH} <<- EOM
${SAMPLECONFIG}EOM ${SAMPLECONFIG}EOM
@ -285,4 +343,43 @@ if (BUILD_DOC)
message(STATUS "Doxygen need to be installed to generate the doxygen documentation") message(STATUS "Doxygen need to be installed to generate the doxygen documentation")
endif (DOXYGEN_FOUND) endif (DOXYGEN_FOUND)
message("") message("")
endif (BUILD_DOC) endif (BUILD_DOC)
# Test Cases
if (TESTS)
include(GoogleTest)
mark_as_advanced(
BUILD_GMOCK BUILD_GTEST BUILD_SHARED_LIBS
gmock_build_tests gtest_build_samples gtest_build_tests
gtest_disable_pthreads gtest_force_shared_crt gtest_hide_internal_symbols
)
enable_testing()
macro(package_add_test TESTNAME)
# create an exectuable in which the tests will be stored
add_executable(${TESTNAME} ${ARGN})
# link the Google test infrastructure, mocking library, and a default main fuction to
target_link_libraries(${TESTNAME} gtest gtest_main -lpthread -lm dynuiprefresher api ${CURL_LIBRARIES} ${LIBCONFIG++_LIBRARIES})
# see https://cmake.org/cmake/help/v3.10/module/GoogleTest.html for more options to pass to it
gtest_discover_tests(${TESTNAME}
WORKING_DIRECTORY ${PROJECT_DIR}
EXTRA_ARGS --gtest_output=xml:report.xml -VV
PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY "${PROJECT_DIR}"
)
set_target_properties(${TESTNAME} PROPERTIES FOLDER tests)
endmacro()
package_add_test(test1 tests/UnitTest.cpp ${SOURCE})
add_custom_target(build-test
"${CMAKE_COMMAND}" --build "${CMAKE_BINARY_DIR}" --target test
DEPENDS ${PROJECT_NAME}
COMMENT "Packing ${PROJECT_NAME}")
add_custom_target(build-xml
"bin/test1" --gtest_output="xml:report.xml"
DEPENDS ${PROJECT_NAME}
COMMENT "Packing ${PROJECT_NAME}")
ENDIF ()

View File

@ -1,3 +1,4 @@
[![pipeline status](http://gitlab.heili.eu/lukas/dynuiprefresher/badges/master/pipeline.svg)](http://gitlab.heili.eu/lukas/dynuiprefresher/-/commits/master)
# DynuIPRefresher # DynuIPRefresher
A lightweight C++ application to setup a service for refreshing a dynamic IP to the Dynu servers. A lightweight C++ application to setup a service for refreshing a dynamic IP to the Dynu servers.
Dynu.com is a free DDns service and provides an API. Dynu.com is a free DDns service and provides an API.

View File

@ -1,6 +1,9 @@
// /**
// Created by lukas on 11.02.20. * A static class to manage the configuration file, read/write parameters to it.
// *
* @author Lukas Heiligenbrunner
* @date 11.02.2020
*/
#pragma once #pragma once
@ -8,20 +11,12 @@
class Config { class Config {
public: public:
static std::string dynuapikey;
static std::string domainid; //id of the dynu domain
static std::string domainname;
static std::string telegramApiKey;
static std::string chatId;
/** /**
* read configuration out of config file * read configuration out of config file
* *
* @return success of config read * @return success of config read
*/ */
static bool readCredentials(); static bool readConfig();
/** /**
* validate config file * validate config file
@ -30,5 +25,62 @@ public:
*/ */
static bool validateConfig(); static bool validateConfig();
/**
* check if telegram credentials in config are set
* @return is supported?
*/
static bool isTelegramSupported();
/** Getters **/
/**
* encapsulated getter for DynuApiKey
* @return api key
*/
static const std::string &getDynuapikey();
/**
* encapsulated getter for DomainId
* @return DomainId
*/
static const std::string &getDomainid();
/**
* encapsulated getter for Domainname
* @return Domainname
*/
static const std::string &getDomainname();
/**
* encapsulated getter for TelegramApiKey
* @return TelegramApiKey
*/
static const std::string &getTelegramApiKey();
/**
* encapsulated getter for ChatId
* @return ChatId
*/
static const std::string &getChatId();
private: private:
/**
* private constructor --> don't allow instance of this class
*/
Config();
/**
* helper variable for managing telegram Support
*/
static bool telegramSupport;
/**
* helper variables for storing keys and ids
*/
static std::string dynuapikey;
static std::string domainid; //id of the dynu domain
static std::string domainname;
static std::string telegramApiKey;
static std::string chatId;
}; };

View File

@ -1,6 +1,9 @@
// /**
// Created by lukas on 05.05.19. * Read and write current ip to a temp file to remember last ip until restart
// *
* @author Lukas Heiligenbrunner
* @date 05.05.2019
*/
#pragma once #pragma once

View File

@ -1,25 +1,33 @@
// /**
// Created by lukas on 02.08.19. * IPrefresher library
// * - start checking ip once
* - or in loop mode
*
* @author Lukas Heiligenbrunner
* @date 06.04.2019
*/
#pragma once #pragma once
class IPRefresher { namespace IPRefresher {
public: /**
* Status return-codes for startUpService
*/
namespace Status_Code {
const int SUCCESS = 1;
const int ERROR = -1;
const int ERROR_NO_INTERNET = -2;
const int NOREFRESH = 0;
}
/** /**
* refresh ip address on Dynu server * refresh ip address on Dynu server
*/ */
void checkIPAdress(bool force); bool checkIPAdress(bool force);
/**
* default constructor
*/
IPRefresher();
/** /**
* start the service in loop mode * start the service in loop mode
* every 5 minutes the ip is checked an refreshed (needed for .service) * every 5 minutes the ip is checked an refreshed (needed for .service)
* @param loop true->loopmode on
*/ */
explicit IPRefresher(bool loop); void startUpService(int interval = 300);
}; }

22
inc/IpHelper.h Normal file
View File

@ -0,0 +1,22 @@
/**
* A helper class for general IP String actions
*
* @author Lukas Heiligenbrunner
* @date 07.05.2020
*/
#pragma once
#include <string>
class IpHelper {
public:
/**
* check if ip is valid
* @param ip ip address to test
* @return validity
*/
static bool isIpValid(std::string ip);
private:
};

View File

@ -1,6 +1,10 @@
// /**
// Created by lukas on 26.10.19. * Fancy console log output format
// * todo log level support
*
* @author Lukas Heiligenbrunner
* @date 26.10.2019
*/
#pragma once #pragma once

View File

@ -1,6 +1,11 @@
// /**
// Created by lukas on 06.04.19. * API class
// * - manages all curl download stuff
* - easy POST/GET requests
*
* @author Lukas Heiligenbrunner
* @date 06.04.2019
*/
#pragma once #pragma once
@ -25,7 +30,10 @@ public:
* @param headers header fields * @param headers header fields
* @return return string of server * @return return string of server
*/ */
std::string request(std::string myurl, bool post, Hashmap<std::string, std::string> &map, std::vector<std::string> &headers); std::string request(std::string myurl,
bool post,
Hashmap<std::string, std::string> &map,
std::vector<std::string> &headers);
private: private:
static size_t write_data(void *buffer, size_t size, size_t buffersize, FILE *stream); static size_t write_data(void *buffer, size_t size, size_t buffersize, FILE *stream);

View File

@ -1,19 +1,22 @@
// /**
// Created by lukas on 18.06.19. * Dynu API - Refresh the IP
// *
* @author Lukas Heiligenbrunner
* @date 18.06.2019
*/
#pragma once #pragma once
#include "API.h" #include "API.h"
class DynuAPI : API{ class DynuAPI : API {
public: public:
/** /**
* refresh the ip of domain on Dynu server * refresh the ip of domain on Dynu server
* @param ip new ip * @param ip new ip
* @return request status * @return request status
*/ */
int refreshIp(std::string ip); bool refreshIp(std::string ip);
/** /**
* init Telegram api with apikey and chatid * init Telegram api with apikey and chatid
@ -21,10 +24,21 @@ public:
* @param domainId ID of domain received by Dynu * @param domainId ID of domain received by Dynu
* @param domainName domainname to refresh * @param domainName domainname to refresh
*/ */
void init(const std::string& dynuApiKey, const std::string& domainId, const std::string& domainName); void init(const std::string &dynuApiKey, const std::string &domainId, const std::string &domainName);
private:
std::string dynuapikey; // Dynu API key
std::string domainid; //id of the dynu domain private:
/**
* Dynu API Key
*/
std::string dynuapikey;
/**
* Dynu Domain ID
*/
std::string domainid;
/**
* Domain name eg. "mydomain.dynu.net"
*/
std::string domainname; std::string domainname;
}; };

View File

@ -1,6 +1,9 @@
// /**
// Created by lukas on 07.04.19. * A Hashmap class for easier Key-Value maps
// *
* @author Lukas Heiligenbrunner
* @date 07.04.2019
*/
#pragma once #pragma once

View File

@ -1,6 +1,9 @@
// /**
// Created by lukas on 18.06.19. * IPAPI for getting global ip of current network
// *
* @author Lukas Heiligenbrunner
* @date 18.06.2019
*/
#pragma once #pragma once
@ -8,7 +11,7 @@
#include <string> #include <string>
class IPAPI : API{ class IPAPI : API {
public: public:
/** /**
* get global ip of current internet connection * get global ip of current internet connection

View File

@ -1,6 +1,9 @@
// /**
// Created by lukas on 08.05.19. * Telegram API for sending message to specific chat
// *
* @author Lukas Heiligenbrunner
* @date 08.05.2019
*/
#pragma once #pragma once
@ -14,7 +17,7 @@ public:
* send telegram Message to predefined destination * send telegram Message to predefined destination
* @param text message * @param text message
*/ */
int sendMessage(const std::string& text); int sendMessage(const std::string &text);
/** /**
* init Telegram api with apikey and chatid * init Telegram api with apikey and chatid

View File

@ -1,7 +1,3 @@
//
// Created by lukas on 11.02.20.
//
#include "Config.h" #include "Config.h"
#include "Logger.h" #include "Logger.h"
#include "Version.h" #include "Version.h"
@ -18,10 +14,11 @@ std::string Config::domainname;
std::string Config::telegramApiKey; std::string Config::telegramApiKey;
std::string Config::chatId; std::string Config::chatId;
bool Config::readCredentials() { bool Config::telegramSupport;
bool Config::readConfig() {
libconfig::Config cfg; libconfig::Config cfg;
try { try {
// todo make dynamic here
cfg.readFile(Version::ConfigDir.c_str()); cfg.readFile(Version::ConfigDir.c_str());
} }
catch (const libconfig::FileIOException &fioex) { catch (const libconfig::FileIOException &fioex) {
@ -33,7 +30,7 @@ bool Config::readCredentials() {
myfile << Version::SAMPLECONFIG; myfile << Version::SAMPLECONFIG;
myfile.close(); myfile.close();
} else { } else {
std::cout << "error creating file" << std::endl; Logger::error("error creating file");
} }
return false; return false;
@ -52,11 +49,15 @@ bool Config::readCredentials() {
// optional parameters // optional parameters
telegramApiKey = (std::string) cfg.lookup("telegramApiKey"); telegramApiKey = (std::string) cfg.lookup("telegramApiKey");
chatId = (std::string) cfg.lookup("chatId"); chatId = (std::string) cfg.lookup("chatId");
telegramSupport = true;
} }
catch (const libconfig::SettingNotFoundException &nfex) { catch (const libconfig::SettingNotFoundException &nfex) {
// triggered if setting is missing in config // triggered if setting is missing in config
if (!(std::strcmp("telegramApiKey", nfex.getPath()) == 0 || std::strcmp("chatId", nfex.getPath()) == 0)) { if (!(std::strcmp("telegramApiKey", nfex.getPath()) == 0 || std::strcmp("chatId", nfex.getPath()) == 0)) {
std::cerr << "No '" << nfex.getPath() << "' setting in configuration file." << std::endl; std::cerr << "No '" << nfex.getPath() << "' setting in configuration file." << std::endl;
} else {
Logger::message("no Telegram support - fields in config not set");
telegramSupport = false;
} }
} }
// check if needed values aren't empty // check if needed values aren't empty
@ -83,27 +84,57 @@ bool Config::validateConfig() {
try { try {
// needed parameters // needed parameters
if (((std::string) cfg.lookup("dynuapikey")).empty()) { if (((std::string) cfg.lookup("dynuapikey")).empty()) {
Logger::warning("required parameter dynuapikey seems to be empty."); Logger::warning("required parameter \"dynuapikey\" seems to be empty.");
return false; return false;
} }
if (((std::string) cfg.lookup("domainid")).empty()) { if (((std::string) cfg.lookup("domainid")).empty()) {
Logger::warning("required parameter domainid seems to be empty."); Logger::warning("required parameter \"domainid\" seems to be empty.");
return false; return false;
} }
if (((std::string) cfg.lookup("domainname")).empty()) { if (((std::string) cfg.lookup("domainname")).empty()) {
Logger::warning("required parameter domainname seems to be empty."); Logger::warning("required parameter \"domainname\" seems to be empty.");
return false; return false;
} }
// optional parameters // optional parameters
cfg.lookup("telegramApiKey"); cfg.lookup("telegramApiKey");
cfg.lookup("chatId"); cfg.lookup("chatId");
telegramSupport = true;
} }
catch (const libconfig::SettingNotFoundException &nfex) { catch (const libconfig::SettingNotFoundException &nfex) {
// triggered if setting is missing in config // triggered if setting is missing in config
if (!(std::strcmp("telegramApiKey", nfex.getPath()) == 0 || std::strcmp("chatId", nfex.getPath()) == 0)) { if (!(std::strcmp("telegramApiKey", nfex.getPath()) == 0 || std::strcmp("chatId", nfex.getPath()) == 0)) {
std::cerr << "No '" << nfex.getPath() << "' setting in configuration file." << std::endl; std::cerr << "No '" << nfex.getPath() << "' setting in configuration file." << std::endl;
return false; return false;
} else {
Logger::message("no Telegram support - fields in config not set");
telegramSupport = false;
} }
} }
return true; return true;
} }
bool Config::isTelegramSupported() {
return telegramSupport;
}
const std::string &Config::getDynuapikey() {
return dynuapikey;
}
const std::string &Config::getDomainid() {
return domainid;
}
const std::string &Config::getDomainname() {
return domainname;
}
const std::string &Config::getTelegramApiKey() {
return telegramApiKey;
}
const std::string &Config::getChatId() {
return chatId;
}
Config::Config() = default;

View File

@ -1,12 +1,8 @@
//
// Created by lukas on 05.05.19.
//
#include "FileLogger.h" #include "FileLogger.h"
#include "IpHelper.h"
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <climits>
void FileLogger::safeip(std::string ip) { void FileLogger::safeip(std::string ip) {
std::ofstream out; std::ofstream out;
@ -25,8 +21,8 @@ std::string FileLogger::readip() {
in >> ip; in >> ip;
// when received ip has no : return 0.0.0.0 // when received ip has no . return 0.0.0.0
if (ip.find(':') == ULONG_MAX) if (!IpHelper::isIpValid(ip))
return "0.0.0.0"; return "0.0.0.0";
else else
return ip; return ip;

View File

@ -1,7 +1,3 @@
//
// Created by lukas on 02.08.19.
//
#include "IPRefresher.h" #include "IPRefresher.h"
#include "FileLogger.h" #include "FileLogger.h"
#include "api/IPAPI.h" #include "api/IPAPI.h"
@ -9,14 +5,15 @@
#include "api/TelegramAPI.h" #include "api/TelegramAPI.h"
#include "Config.h" #include "Config.h"
#include "Version.h" #include "Version.h"
#include "IpHelper.h"
#include <string>
#include <chrono> #include <chrono>
#include <thread> #include <thread>
#include <Logger.h> #include <Logger.h>
#include <climits>
void IPRefresher::checkIPAdress(bool force) { using namespace IPRefresher;
bool IPRefresher::checkIPAdress(bool force) {
FileLogger logger; FileLogger logger;
IPAPI ipapi; IPAPI ipapi;
@ -25,48 +22,52 @@ void IPRefresher::checkIPAdress(bool force) {
if (ip.empty()) { if (ip.empty()) {
//no internet connection (or other error) //no internet connection (or other error)
Logger::warning("no internet connection"); Logger::warning("no internet connection");
} else if (ip.find(':') == ULONG_MAX) { return Status_Code::ERROR_NO_INTERNET;
} else if (!IpHelper::isIpValid(ip)) {
// error when ip doesn't contain a : // error when ip doesn't contain a :
Logger::warning("an error occured when getting the global ip"); Logger::warning("an error occured when getting the global ip");
return Status_Code::ERROR;
} else { } else {
std::string oldip = logger.readip(); std::string oldip = logger.readip();
if (oldip == ip && !force) { if (oldip == ip && !force) {
Logger::message("no change -- ip: " + ip); Logger::message("no change -- ip: " + ip);
return Status_Code::NOREFRESH;
} else { } else {
Logger::message("ip changed! -- from :" + oldip + "to: " + ip); Logger::message("ip changed! -- from :" + oldip + "to: " + ip);
DynuAPI dynu; DynuAPI dynu;
dynu.init(Config::dynuapikey, Config::domainid, Config::domainname); dynu.init(Config::getDynuapikey(), Config::getDomainid(), Config::getDomainname());
// actual refresh of IP in api - here
bool result = dynu.refreshIp(ip);
if (dynu.refreshIp(ip)) { if (result && Config::isTelegramSupported()) {
TelegramAPI tele; TelegramAPI tele;
tele.init(Config::telegramApiKey, Config::chatId); tele.init(Config::getTelegramApiKey(), Config::getChatId());
tele.sendMessage(oldip + " moved to " + ip); tele.sendMessage(oldip + " moved to " + ip);
} else { } else if (!result) {
//error //error
Logger::error("failed to write ip to dynu api!"); Logger::error("failed to write ip to dynu api!");
return Status_Code::ERROR;
} }
logger.safeip(ip); logger.safeip(ip);
return result ? Status_Code::SUCCESS : Status_Code::ERROR;
} }
} }
} }
IPRefresher::IPRefresher() = default; void IPRefresher::startUpService(int interval) {
Logger::message("startup of service");
IPRefresher::IPRefresher(bool loop) { Logger::message("Version: " + Version::VERSION);
if (loop) { if (Config::readConfig()) {
Logger::message("startup of service"); while (true) {
Logger::message("Version: " + Version::VERSION); Logger::message("starting check");
if (Config::readCredentials()) { checkIPAdress(false);
while (true) { std::this_thread::sleep_for(std::chrono::milliseconds(interval * 1000));
Logger::message("starting check");
checkIPAdress(false);
std::this_thread::sleep_for(std::chrono::milliseconds(300000));
}
} else {
std::cout << "incorrect credentials!" << std::endl;
} }
} else {
std::cout << "incorrect credentials!" << std::endl;
} }
} }

7
src/IpHelper.cpp Normal file
View File

@ -0,0 +1,7 @@
#include "IpHelper.h"
#include <climits>
bool IpHelper::isIpValid(std::string ip) {
return (ip.find('.') != ULONG_MAX);
}

View File

@ -1,7 +1,3 @@
//
// Created by lukas on 26.10.19.
//
#include "Logger.h" #include "Logger.h"
#include <sstream> #include <sstream>

View File

@ -1,7 +1,3 @@
//
// Created by lukas on 06.04.19.
//
#include "api/API.h" #include "api/API.h"
#include <sstream> #include <sstream>

View File

@ -1,10 +1,6 @@
//
// Created by lukas on 18.06.19.
//
#include "api/DynuAPI.h" #include "api/DynuAPI.h"
int DynuAPI::refreshIp(std:: string ip) { bool DynuAPI::refreshIp(std::string ip) {
Hashmap<std::string, std::string> args; Hashmap<std::string, std::string> args;
args.add("name", domainname); args.add("name", domainname);
args.add("ipv4Address", ip); args.add("ipv4Address", ip);
@ -16,15 +12,11 @@ int DynuAPI::refreshIp(std:: string ip) {
const std::string dynurepl = request("https://api.dynu.com/v2/dns/" + domainid, true, args, headers); const std::string dynurepl = request("https://api.dynu.com/v2/dns/" + domainid, true, args, headers);
if (dynurepl != "{\"statusCode\":200}") { return (dynurepl == "{\"statusCode\":200}");
return -1;
} else {
return 1;
}
} }
void DynuAPI::init(const std::string& dynuApiKey, const std::string& domainId, const std::string& domainName) { void DynuAPI::init(const std::string &dynuApiKey, const std::string &domainId, const std::string &domainName) {
this->dynuapikey=dynuApiKey; this->dynuapikey = dynuApiKey;
this->domainid=domainId; this->domainid = domainId;
this->domainname=domainName; this->domainname = domainName;
} }

View File

@ -1,9 +1,5 @@
//
// Created by lukas on 18.06.19.
//
#include "api/IPAPI.h" #include "api/IPAPI.h"
std::string IPAPI::getGlobalIp() { std::string IPAPI::getGlobalIp() {
return request("https://api.ipify.org"); return request("https://api.ipify.org");
} }

View File

@ -1,13 +1,9 @@
//
// Created by lukas on 08.05.19.
//
#include "api/TelegramAPI.h" #include "api/TelegramAPI.h"
#include "Logger.h" #include "Logger.h"
#include <climits> #include <climits>
int TelegramAPI::sendMessage(const std::string& text) { int TelegramAPI::sendMessage(const std::string &text) {
Hashmap<std::string, std::string> args; Hashmap<std::string, std::string> args;
args.add("chat_id", chatid); args.add("chat_id", chatid);
args.add("text", text); args.add("text", text);

84
src/gui/MainWindow.cpp Normal file
View File

@ -0,0 +1,84 @@
#include "MainWindow.h"
#include "ui_mainwindow.h"
#include "api/IPAPI.h"
#include "IPRefresher.h"
#include "Config.h"
#include "Logger.h"
#include <thread>
MainWindow::MainWindow() : QMainWindow(), ui(new Ui::MainWindow) {
ui->setupUi(this);
// needs to be defined with new -- would be termintated after this constructor.
new std::thread([this]() {
IPAPI ipapi;
std::string ip = ipapi.getGlobalIp();
Logger::message("Current global IP: " + ip);
std::string msg = "Your current global IP: " + ip;
this->ui->labelCurrentIP->setText(msg.c_str());
});
// set config info label and initial check if config is valid
ui->labelConfig->setText(Config::validateConfig() ? "Config is: OK" : "Config is: NOT OK");
connect(ui->buttonCheckConfig, SIGNAL(clicked()), this, SLOT(checkConfigBtn()));
connect(ui->buttonRefreshIP, SIGNAL(clicked()), this, SLOT(refreshIPBtn()));
connect(this, SIGNAL(appendLogField(QString)), ui->textLog, SLOT(appendPlainText(QString)));
}
MainWindow::~MainWindow() {
// todo check if disconnects are really necessary
disconnect(ui->buttonCheckConfig);
disconnect(ui->buttonRefreshIP);
delete ui;
}
void MainWindow::checkConfigBtn() {
Logger::message("checking config!");
appendLogField("checking config!");
if (Config::validateConfig()) {
Logger::message("Config file is OK");
appendLogField("Config file is OK");
ui->labelConfig->setText("Config is: OK");
} else {
Logger::error("There are errors in config file!");
appendLogField("There are errors in config file!");
}
appendLogField("");
}
void MainWindow::refreshIPBtn() {
Logger::message("start refreshing Dynu IP.");
appendLogField("");
appendLogField("start refreshing Dynu IP.");
new std::thread([this]() {
if (Config::readConfig()) {
int code = IPRefresher::checkIPAdress(false);
switch (code) {
case IPRefresher::Status_Code::SUCCESS:
appendLogField("successfully refreshed IP!");
break;
case IPRefresher::Status_Code::NOREFRESH:
appendLogField("IP is already correct.");
break;
case IPRefresher::Status_Code::ERROR_NO_INTERNET:
appendLogField("Error: No Internet connection");
break;
case IPRefresher::Status_Code::ERROR:
appendLogField("An error occured while refreshing.");
break;
default:
appendLogField("An unknown error code occured");
}
} else {
std::cout << "incorrect credentials!" << std::endl;
}
Logger::message("Finished refreshing Dynu IP.");
this->appendLogField("Finished refreshing Dynu IP.");
});
}

50
src/gui/MainWindow.h Normal file
View File

@ -0,0 +1,50 @@
/**
* Main GUI controller - User IO handlings
*
* @author Lukas Heiligenbrunner
* @date 09.05.2020
*/
#pragma once
#include <QtWidgets/QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow {
Q_OBJECT
public:
/**
* constructor with basic initializations
*/
explicit MainWindow();
/**
* destruct all gui elements
*/
~MainWindow();
private:
Ui::MainWindow *ui;
private slots:
/**
* executed click handler for config button
*/
void checkConfigBtn();
/**
* executed click handler for refresh btn
*/
void refreshIPBtn();
signals:
/**
* append a String line to the Log field
*
* @param QString string to be appended
*/
void appendLogField(QString);
};

103
src/gui/mainwindow.ui Normal file
View File

@ -0,0 +1,103 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>823</width>
<height>618</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QPushButton" name="buttonRefreshIP">
<property name="geometry">
<rect>
<x>290</x>
<y>300</y>
<width>91</width>
<height>33</height>
</rect>
</property>
<property name="text">
<string>Refresh IP</string>
</property>
</widget>
<widget class="QLabel" name="labelCurrentIP">
<property name="geometry">
<rect>
<x>40</x>
<y>60</y>
<width>301</width>
<height>17</height>
</rect>
</property>
<property name="text">
<string>Your current global IP:</string>
</property>
</widget>
<widget class="QPlainTextEdit" name="textLog">
<property name="enabled">
<bool>false</bool>
</property>
<property name="geometry">
<rect>
<x>40</x>
<y>410</y>
<width>691</width>
<height>191</height>
</rect>
</property>
<property name="cursor" stdset="0">
<cursorShape>IBeamCursor</cursorShape>
</property>
</widget>
<widget class="QLabel" name="label_2">
<property name="geometry">
<rect>
<x>40</x>
<y>380</y>
<width>64</width>
<height>17</height>
</rect>
</property>
<property name="text">
<string>Log:</string>
</property>
</widget>
<widget class="QPushButton" name="buttonCheckConfig">
<property name="geometry">
<rect>
<x>270</x>
<y>140</y>
<width>91</width>
<height>33</height>
</rect>
</property>
<property name="text">
<string>Check Config</string>
</property>
</widget>
<widget class="QLabel" name="labelConfig">
<property name="geometry">
<rect>
<x>270</x>
<y>180</y>
<width>141</width>
<height>17</height>
</rect>
</property>
<property name="text">
<string>Config is: undefined</string>
</property>
</widget>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>

View File

@ -1,15 +1,9 @@
//
// Created by lukas on 18.06.19.
//
#include "Version.h" #include "Version.h"
#include "IPRefresher.h" #include "IPRefresher.h"
#include "Logger.h" #include "Logger.h"
#include "Config.h" #include "Config.h"
#include "api/IPAPI.h" #include "api/IPAPI.h"
#include <iostream>
/** /**
* application entry point * application entry point
*/ */
@ -27,20 +21,19 @@ int main(int argc, char *argv[]) {
} else if (firstarg == "-v" || firstarg == "--version") { } else if (firstarg == "-v" || firstarg == "--version") {
std::cout << "Version " << Version::VERSION << std::endl; std::cout << "Version " << Version::VERSION << std::endl;
} else if (firstarg == "-f" || firstarg == "--force") { } else if (firstarg == "-f" || firstarg == "--force") {
IPRefresher ipr; if (Config::readConfig()) {
if (Config::readCredentials()) { IPRefresher::checkIPAdress(true);
ipr.checkIPAdress(true);
} else { } else {
std::cout << "incorrect credentials!" << std::endl; std::cout << "incorrect credentials!" << std::endl;
} }
} else if (firstarg == "-l" || firstarg == "--loop") { } else if (firstarg == "-l" || firstarg == "--loop") {
IPRefresher(true); IPRefresher::startUpService(true);
} else if (firstarg == "-c" || firstarg == "--checkconfig") { } else if (firstarg == "-c" || firstarg == "--checkconfig") {
if (Config::validateConfig()) { if (Config::validateConfig()) {
Logger::message("Config file is OK"); Logger::message("Config file is OK");
} else { } else {
Logger::warning("There are errors in config file!"); Logger::error("There are errors in config file!");
return -1; return -1;
} }
} else if (firstarg == "-ip" || firstarg == "--currentip") { } else if (firstarg == "-ip" || firstarg == "--currentip") {
@ -50,10 +43,9 @@ int main(int argc, char *argv[]) {
Logger::message("wrong arguments! -h for help"); Logger::message("wrong arguments! -h for help");
} }
} else { } else {
IPRefresher ipr;
Logger::message("starting check"); Logger::message("starting check");
if (Config::readCredentials()) { if (Config::readConfig()) {
ipr.checkIPAdress(false); IPRefresher::checkIPAdress(false);
} else { } else {
std::cout << "incorrect credentials!" << std::endl; std::cout << "incorrect credentials!" << std::endl;
} }

14
src/maingui.cpp Normal file
View File

@ -0,0 +1,14 @@
#include <QApplication>
#include "gui/MainWindow.h"
/**
* application entry point
*/
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
MainWindow w;
w.setWindowTitle("startUpService");
w.show();
return QApplication::exec();
}

30
tests/UnitTest.cpp Normal file
View File

@ -0,0 +1,30 @@
//
// Created by lukas on 06.05.20.
//
#include <FileLogger.h>
#include <api/IPAPI.h>
#include <climits>
#include "gtest/gtest.h"
/**
* Test if default ip is 0.0.0.0 when last ip file doesn't exist.
*/
TEST(ReadIp, testzeroIpIfNotExists) {
FileLogger logger;
std::string oldip = logger.readip();
ASSERT_EQ(oldip, "0.0.0.0");
}
/**
* Test if default ip is 0.0.0.0 when last ip file doesn't exist.
*/
TEST(IPAPI, testIpAPIcheckIPSyntax) {
IPAPI ipapi;
std::string ip = ipapi.getGlobalIp();
if (ip.find('.') == ULONG_MAX) {
// error when ip doesn't contain a .
ASSERT_TRUE(false);
} else {
ASSERT_TRUE(true);
}
}