Files
TTW_Bot/fcreatenotify.cpp
T
2026-02-07 08:28:56 +03:00

441 lines
15 KiB
C++

#include "fcreatenotify.h"
#include "udatabase.h"
#include "ui_fcreatenotify.h"
#include <QFileDialog>
#include <QDebug>
#include <QMessageBox>
#include <QDir>
#include <QCloseEvent>
#include <QDesktopServices>
#include <QApplication>
#include "filemanager.h"
FCreateNotify::FCreateNotify(uDataBase *database, QWidget *parent) :
QDialog(parent),
ui(new Ui::FCreateNotify),
m_isEditMode(false),
m_database(database),
m_existingServerName(""),
m_server(nullptr), // Добавьте
m_notificationCounter(0) // Добавьте
{
ui->setupUi(this);
FileManager::instance().initializeFolderStructure();
// Создаем структуру папок для статических файлов
QDir appDir(QApplication::applicationDirPath());
appDir.mkpath("sounds");
appDir.mkpath("fonts");
appDir.mkpath("imgs");
// Заполняем ComboBox событиями
QStringList events = {
"donation", "follow", "subscription", "raid",
"bits", "host", "merch", "goal", "poll", "prediction"
};
// Устанавливаем значения по умолчанию
ui->edtHeader->setText("Тестовый пользователь");
ui->edtMessage->setText("Это тестовое уведомление!");
// Включаем кнопки
ui->btnTest->setEnabled(true);
ui->btnAdd->setEnabled(true);
// Информация для пользователя
ui->btnTest->setToolTip("Создать тестовое уведомление и открыть браузер");
ui->btnAdd->setToolTip("Добавить уведомление для отображения");
}
FCreateNotify::~FCreateNotify()
{
delete ui;
}
void FCreateNotify::closeEvent(QCloseEvent *event)
{
// Останавливаем сервер при закрытии окна
if (m_server) {
m_server->stop();
}
QDialog::closeEvent(event);
}
void FCreateNotify::createServer()
{
if (m_server) {
m_server->stop();
delete m_server;
m_server = nullptr;
}
// Получаем настройки из формы
FSettingsWS *settingsWS = ui->widget;
if (!settingsWS) {
QMessageBox::warning(this, "Ошибка", "Не найдены настройки сервера");
return;
}
// Получаем порт из настроек
int port = settingsWS->sbPort->value();
// Создаем сервер с полученным портом
m_server = new HttpServer( this);
// Запускаем сервер
if (m_server->start(port)) {
} else {
QMessageBox::warning(this, "Ошибка",
QString("Не удалось запустить сервер уведомлений на порту %1").arg(port));
}
}
void FCreateNotify::on_btnTest_clicked()
{
// Создаем сервер с текущими настройками
createServer();
if (!m_server) {
QMessageBox::warning(this, "Ошибка", "Не удалось создать сервер");
return;
}
// Создаем тестовое уведомление
createNotification(true);
}
void FCreateNotify::createNotification(bool isTest)
{
if (!m_server) {
QMessageBox::warning(this, "Ошибка", "Сервер не запущен");
return;
}
m_notificationCounter++;
Notification notif;
// Заголовок
notif.nickname = ui->edtHeader->text().isEmpty() ?
QString("Тест %1").arg(m_notificationCounter) :
ui->edtHeader->text();
// Сообщение
notif.content = ui->edtMessage->text().isEmpty() ?
QString("Тестовое сообщение #%1").arg(m_notificationCounter) :
ui->edtMessage->text();
// Картинка
QString imgPath = ui->edtFileImg->text();
if (!imgPath.isEmpty() && QFile::exists(imgPath)) {
QString newFileName;
if (FileManager::instance().copyToUserData(imgPath, FileManager::WebServerImages,
FileManager::CopyWithNewName, &newFileName)) {
notif.url = FileManager::instance().getWebPath(FileManager::WebServerImages, newFileName);
}
}
// Звук
QString soundPath = ui->edtFileSong->text();
if (!soundPath.isEmpty() && QFile::exists(soundPath)) {
QString newFileName;
if (FileManager::instance().copyToUserData(soundPath, FileManager::WebServerSounds,
FileManager::CopyWithNewName, &newFileName)) {
notif.soundURL = FileManager::instance().getWebPath(FileManager::WebServerSounds, newFileName);
}
}
// ПОЛУЧАЕМ НАСТРОЙКИ ИЗ ВИДЖЕТОВ
// 1. Получаем настройки цвета блока из FColorSetting
FColorSetting *colorSetting = ui->wBlock;
if (colorSetting) {
// Получаем выбранный цвет блока
QColor blockColor = colorSetting->cbBlockColor->currentData().value<QColor>();
if (!blockColor.isValid()) {
blockColor = QColor(colorSetting->cbBlockColor->currentText());
}
// ПРИМЕНЯЕМ ПРОЗРАЧНОСТЬ БЛОКА УВЕДОМЛЕНИЯ
int blockTransparency = colorSetting->hsBlockTransparant->value(); // 0-100
// Преобразуем 0-100 в 0-255
int alpha = (blockTransparency * 255) / 100;
blockColor.setAlpha(alpha);
notif.blockColor = blockColor.name(QColor::HexArgb); // Включаем альфа-канал
// Получаем выбранный цвет границы
QColor borderColor = colorSetting->cbBorderColor->currentData().value<QColor>();
if (!borderColor.isValid()) {
borderColor = QColor(colorSetting->cbBorderColor->currentText());
}
notif.borderColor = borderColor.name();
// Получаем размер границы
notif.borderSize = colorSetting->sbBorderSize->value();
// Получаем цвет фона СТРАНИЦЫ (не блока!)
QColor pageBackgroundColor = colorSetting->cbBackgroundColor->currentData().value<QColor>();
if (!pageBackgroundColor.isValid()) {
pageBackgroundColor = QColor(colorSetting->cbBackgroundColor->currentText());
}
notif.pageBackgroundColor = pageBackgroundColor.name();
}
// 2. Получаем настройки шрифта заголовка из FFontSetting
FFontSetting *fontHeaderSetting = ui->wFont;
if (fontHeaderSetting) {
// Получаем выбранный шрифт заголовка
notif.titleFamily = fontHeaderSetting->cbFontStyle->currentText();
// Получаем размер шрифта заголовка
notif.titleSize = fontHeaderSetting->sbFontSize->value();
// Получаем цвет шрифта заголовка
QColor titleColor = fontHeaderSetting->cbFontColor->currentData().value<QColor>();
if (!titleColor.isValid()) {
titleColor = QColor(fontHeaderSetting->cbFontColor->currentText());
}
notif.titleColor = titleColor.name();
}
// 3. Получаем настройки шрифта сообщения из FFontSetting
FFontSetting *fontMessageSetting = ui->wFont_2;
if (fontMessageSetting) {
// Получаем выбранный шрифт сообщения
notif.contentFamily = fontMessageSetting->cbFontStyle->currentText();
// Получаем размер шрифта сообщения
notif.contentSize = fontMessageSetting->sbFontSize->value();
// Получаем цвет шрифта сообщения
QColor contentColor = fontMessageSetting->cbFontColor->currentData().value<QColor>();
if (!contentColor.isValid()) {
contentColor = QColor(fontMessageSetting->cbFontColor->currentText());
}
notif.contentColor = contentColor.name();
}
// 4. Получаем настройки веб-сервера из FSettingsWS
FSettingsWS *settingsWS = ui->widget;
if (settingsWS) {
// Получаем время отображения уведомления
notif.duration = settingsWS->sbTime->value();
} else {
// Значение по умолчанию, если виджет не найден
notif.duration = 15;
}
// Добавляем уведомление на сервер
m_server->addNotification(notif);
if (!isTest) {
// Очищаем только если это не тест
ui->edtHeader->clear();
ui->edtMessage->clear();
}
}
void FCreateNotify::on_btnOpenImg_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this,
"Выберите изображение",
"",
"Images (*.png *.jpg *.jpeg *.gif *.bmp *.svg)");
if (!fileName.isEmpty()) {
ui->edtFileImg->setText(fileName);
}
}
void FCreateNotify::on_btnOpenSong_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this,
"Выберите звуковой файл",
"",
"Audio files (*.mp3 *.wav *.ogg *.flac)");
if (!fileName.isEmpty()) {
ui->edtFileSong->setText(fileName);
}
}
void FCreateNotify::onServerStarted(bool success)
{
if (success) {
ui->btnTest->setEnabled(true);
ui->btnAdd->setEnabled(true);
QString url = QString("http://localhost:%1").arg(m_server->port());
ui->btnTest->setText("Тест (" + url + ")");
} else {
ui->btnTest->setEnabled(false);
ui->btnAdd->setEnabled(false);
QMessageBox::warning(this, "Ошибка", "Не удалось запустить веб-сервер");
}
}
void FCreateNotify::setEditMode(bool isEditMode)
{
m_isEditMode = isEditMode;
if (isEditMode) {
ui->btnAdd->setText("Изменить");
setWindowTitle("TTW Bot app: Редактировать уведомления");
} else {
ui->btnAdd->setText("Создать");
setWindowTitle("TTW Bot app: Создать уведомления");
}
}
void FCreateNotify::loadExistingServer(HttpServer *server, const QString &name)
{
if (!server) return;
m_isEditMode = true;
m_server = server;
m_existingServerName = name;
setEditMode(true);
// Устанавливаем порт
FSettingsWS *settingsWS = ui->widget;
if (settingsWS) {
settingsWS->sbPort->setValue(server->port());
settingsWS->sbTime->setValue(server->getDuration());
}
// Устанавливаем название
ui->lineEdit->setText(name); // Предполагается, что есть lineEdit для имени
// Устанавливаем цвета
FColorSetting *colorSetting = ui->wBlock;
if (colorSetting) {
colorSetting->cbBlockColor->setCurrentText(server->getBlockColor());
colorSetting->cbBorderColor->setCurrentText(server->getBorderColor());
colorSetting->sbBorderSize->setValue(server->getBorderSize());
colorSetting->cbBackgroundColor->setCurrentText(server->getPageBackgroundColor());
colorSetting->hsBlockTransparant->setValue(server->getTransparency());
}
// Устанавливаем шрифты
FFontSetting *fontHeaderSetting = ui->wFont;
if (fontHeaderSetting) {
QString titleFamily;
int titleSize;
QString titleColor;
server->getTitleFont(titleFamily, titleSize, titleColor);
fontHeaderSetting->cbFontStyle->setCurrentText(titleFamily);
fontHeaderSetting->sbFontSize->setValue(titleSize);
fontHeaderSetting->cbFontColor->setCurrentText(titleColor);
}
FFontSetting *fontMessageSetting = ui->wFont_2;
if (fontMessageSetting) {
QString contentFamily;
int contentSize;
QString contentColor;
server->getContentFont(contentFamily, contentSize, contentColor);
fontMessageSetting->cbFontStyle->setCurrentText(contentFamily);
fontMessageSetting->sbFontSize->setValue(contentSize);
fontMessageSetting->cbFontColor->setCurrentText(contentColor);
}
}
// Обновите on_btnAdd_clicked для поддержки редактирования:
void FCreateNotify::on_btnAdd_clicked()
{
if (m_isEditMode && m_server) {
// Режим редактирования
FSettingsWS *settingsWS = ui->widget;
FColorSetting *colorSetting = ui->wBlock;
FFontSetting *fontHeaderSetting = ui->wFont;
FFontSetting *fontMessageSetting = ui->wFont_2;
if (!settingsWS || !colorSetting || !fontHeaderSetting || !fontMessageSetting) {
QMessageBox::warning(this, "Ошибка", "Не найдены настройки сервера");
return;
}
int newPort = settingsWS->sbPort->value();
bool portChanged = (newPort != m_server->port());
if (portChanged) {
m_server->stop();
delete m_server;
m_server = nullptr;
createServer();
}
if (!m_server) {
QMessageBox::warning(this, "Ошибка", "Не удалось обновить сервер");
return;
}
// Применяем настройки к серверу
// Цвета
m_server->setBlockColor(colorSetting->cbBlockColor->currentText());
m_server->setBorderColor(colorSetting->cbBorderColor->currentText());
m_server->setBorderSize(colorSetting->sbBorderSize->value());
m_server->setPageBackgroundColor(colorSetting->cbBackgroundColor->currentText());
m_server->setTransparency(colorSetting->hsBlockTransparant->value());
// Шрифты
m_server->setTitleFont(
fontHeaderSetting->cbFontStyle->currentText(),
fontHeaderSetting->sbFontSize->value(),
fontHeaderSetting->cbFontColor->currentText()
);
m_server->setContentFont(
fontMessageSetting->cbFontStyle->currentText(),
fontMessageSetting->sbFontSize->value(),
fontMessageSetting->cbFontColor->currentText()
);
// Длительность
m_server->setDuration(settingsWS->sbTime->value());
QString newName = ui->lineEdit->text();
if (newName.isEmpty()) {
newName = QString("Уведомления (порт %1)").arg(m_server->port());
}
emit serverUpdated(m_server, newName);
accept();
} else {
// Режим создания (существующий код)
createServer();
if (!m_server) {
QMessageBox::warning(this, "Ошибка", "Не удалось создать сервер");
return;
}
createNotification(false);
QString name = ui->lineEdit->text();
if (name.isEmpty()) {
name = QString("Уведомления (порт %1)").arg(m_server->port());
}
emit serverCreated(m_server, name);
m_server = nullptr;
accept();
}
}