Mailer 1.0.5
C++ daemon for sending order emails via SMTP
Loading...
Searching...
No Matches
Daemon Class Reference

Public Member Functions

 Daemon ()
 
 ~Daemon ()
 Деструктор. Освобождает INI-файл, логгирует остановку, отключается от PG.
 
void Stop ()
 Останавливает основной цикл демона.
 
void Run ()
 

Private Member Functions

int sendOrders (std::string tableName)
 
void ConnectPg ()
 
void DisconnectPg ()
 Отключается от PostgreSQL.
 
void StartTransaction ()
 Создаёт новую транзакцию PostgreSQL.
 
void AbortTransaction ()
 Откатывает текущую транзакцию.
 
void CommitTransaction ()
 Фиксирует текущую транзакцию.
 
void daemonSleep ()
 

Private Attributes

std::string name = "Mailer"
 
std::string version = "Dev"
 
mINI::INIFile * iniFile
 INI-файл конфигурации.
 
mINI::INIStructure ini
 Структура INI-данных в памяти.
 
std::string connectionStr = ""
 Строка подключения к PostgreSQL.
 
pqxx::connection * connection = NULL
 Соединение с PostgreSQL.
 
pqxx::work * trx = NULL
 Текущая транзакция.
 
Products::ProductsLog * productsLog = NULL
 Логирование старта/стопа в БД.
 
volatile std::atomic< bool > running = false
 Флаг работы демона.
 
int sleepPeriod = 60
 Пауза между итерациями (сек).
 

Detailed Description

Главный класс демона.

Управляет основным циклом: читает INI-конфиг, подключается к PostgreSQL, проверяет таблицы заказов и отправляет email через SMTP.

Definition at line 42 of file mailer.cpp.

Constructor & Destructor Documentation

◆ Daemon()

Daemon::Daemon ( )
inline

Конструктор.

Инициализирует логгер, читает INI-файл (или генерирует шаблон), регистрирует старт в таблице products_log.

Definition at line 48 of file mailer.cpp.

References getApplicationDirectory(), ini, iniFile, name, productsLog, and version.

◆ ~Daemon()

Daemon::~Daemon ( )
inline

Деструктор. Освобождает INI-файл, логгирует остановку, отключается от PG.

Definition at line 104 of file mailer.cpp.

References DisconnectPg(), iniFile, and productsLog.

Member Function Documentation

◆ AbortTransaction()

void Daemon::AbortTransaction ( )
inlineprivate

Откатывает текущую транзакцию.

Definition at line 326 of file mailer.cpp.

References trx.

Referenced by sendOrders().

◆ CommitTransaction()

void Daemon::CommitTransaction ( )
inlineprivate

Фиксирует текущую транзакцию.

Definition at line 334 of file mailer.cpp.

References trx.

Referenced by sendOrders().

◆ ConnectPg()

void Daemon::ConnectPg ( )
inlineprivate

Подключается к PostgreSQL.

Формирует строку подключения из секции [Postgres] INI-файла. Если подключение уже установлено и параметры не изменились — пропускает.

Exceptions
std::runtime_errorпри ошибке подключения.

Definition at line 286 of file mailer.cpp.

References connection, connectionStr, and ini.

Referenced by Run().

◆ daemonSleep()

void Daemon::daemonSleep ( )
inlineprivate

Пауза между итерациями цикла.

sleepPeriod читается из секции [Mailer] INI-файла на каждом вызове, поэтому изменение конфига применяется без перезапуска.

Definition at line 345 of file mailer.cpp.

References ini, and sleepPeriod.

Referenced by Run().

◆ DisconnectPg()

void Daemon::DisconnectPg ( )
inlineprivate

Отключается от PostgreSQL.

Definition at line 311 of file mailer.cpp.

References connection.

Referenced by ~Daemon().

◆ Run()

void Daemon::Run ( )
inline

Основной цикл демона.

На каждой итерации:

  • перечитывает INI-файл (конфиг обновляется на лету);
  • подключается к PostgreSQL;
  • проверяет tab_siteOrders и tab_mobileOrders на новые заказы;
  • отправляет email по каждому заказу;
  • переходит в сон на sleepPeriod секунд.

Definition at line 134 of file mailer.cpp.

References ConnectPg(), daemonSleep(), ini, iniFile, return_to_bottom, running, sendOrders(), and SUCCESS.

Referenced by main().

◆ sendOrders()

int Daemon::sendOrders ( std::string tableName)
inlineprivate

Проверяет таблицу заказов и отправляет email по каждому неотправленному.

SELECT unsent записей из tableName, группирует по ключу, формирует HTML-письмо с таблицей товаров, отправляет через EmailSender. При успехе отмечает sent=true.

Parameters
[in]tableNameИмя таблицы ("tab_siteOrders" или "tab_mobileOrders").
Returns
SUCCESS при успехе, FAILURE при ошибке SQL.

Definition at line 201 of file mailer.cpp.

References AbortTransaction(), EmailSender::addCcEmailAddr(), EmailSender::addRecvEmailAddr(), CommitTransaction(), FAILURE, ini, EmailSender::send(), EmailSender::setEmailContent(), StartTransaction(), SUCCESS, and trx.

Referenced by Run().

◆ StartTransaction()

void Daemon::StartTransaction ( )
inlineprivate

Создаёт новую транзакцию PostgreSQL.

Definition at line 320 of file mailer.cpp.

References connection, and trx.

Referenced by sendOrders().

◆ Stop()

void Daemon::Stop ( )
inline

Останавливает основной цикл демона.

Definition at line 124 of file mailer.cpp.

References running.

Referenced by main().

Member Data Documentation

◆ connection

pqxx::connection* Daemon::connection = NULL
private

Соединение с PostgreSQL.

Definition at line 185 of file mailer.cpp.

Referenced by ConnectPg(), DisconnectPg(), and StartTransaction().

◆ connectionStr

std::string Daemon::connectionStr = ""
private

Строка подключения к PostgreSQL.

Definition at line 184 of file mailer.cpp.

Referenced by ConnectPg().

◆ ini

mINI::INIStructure Daemon::ini
private

Структура INI-данных в памяти.

Definition at line 182 of file mailer.cpp.

Referenced by ConnectPg(), Daemon(), daemonSleep(), Run(), and sendOrders().

◆ iniFile

mINI::INIFile* Daemon::iniFile
private

INI-файл конфигурации.

Definition at line 181 of file mailer.cpp.

Referenced by Daemon(), Run(), and ~Daemon().

◆ name

std::string Daemon::name = "Mailer"
private

Definition at line 173 of file mailer.cpp.

Referenced by Daemon().

◆ productsLog

Products::ProductsLog* Daemon::productsLog = NULL
private

Логирование старта/стопа в БД.

Definition at line 188 of file mailer.cpp.

Referenced by Daemon(), and ~Daemon().

◆ running

volatile std::atomic<bool> Daemon::running = false
private

Флаг работы демона.

Definition at line 190 of file mailer.cpp.

Referenced by Run(), and Stop().

◆ sleepPeriod

int Daemon::sleepPeriod = 60
private

Пауза между итерациями (сек).

Definition at line 191 of file mailer.cpp.

Referenced by daemonSleep().

◆ trx

pqxx::work* Daemon::trx = NULL
private

Текущая транзакция.

Definition at line 186 of file mailer.cpp.

Referenced by AbortTransaction(), CommitTransaction(), sendOrders(), and StartTransaction().

◆ version

std::string Daemon::version = "Dev"
private

Definition at line 178 of file mailer.cpp.

Referenced by Daemon().


The documentation for this class was generated from the following file: