#include "fcreatenotify.h" #include "ui_fcreatenotify.h" #include #include #include #include #include #include #include FCreateNotify::FCreateNotify(QWidget *parent) : QDialog(parent), ui(new Ui::FCreateNotify), m_server(nullptr), m_notificationCounter(0) { ui->setupUi(this); // Создаем структуру папок для статических файлов 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->cbEvent->addItems(events); ui->cbEvent->setCurrentIndex(0); // Устанавливаем значения по умолчанию ui->edtHeader->setText("Тестовый пользователь"); ui->edtMessage->setText("Это тестовое уведомление!"); // Включаем кнопки ui->btnTest->setEnabled(true); ui->btnAdd->setEnabled(true); // Информация для пользователя ui->btnTest->setToolTip("Создать тестовое уведомление и открыть браузер"); ui->btnAdd->setToolTip("Добавить уведомление для отображения"); m_server = new HttpServer(nullptr); } 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::on_btnAdd_clicked() { // Создаем сервер с текущими настройками createServer(); if (!m_server) { QMessageBox::warning(this, "Ошибка", "Не удалось создать сервер"); return; } // Получаем название сервера QString name = QString("Уведомления (порт %1)").arg(m_server->port()); // Отправляем сигнал с созданным сервером emit serverCreated(m_server, name); // Закрываем окно accept(); } 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(); // Добавляем тип события notif.content = QString("[%1] %2") .arg(ui->cbEvent->currentText()) .arg(notif.content); // Картинка QString imgPath = ui->edtFileImg->text(); if (!imgPath.isEmpty() && QFile::exists(imgPath)) { QFileInfo imgInfo(imgPath); QString destFileName = imgInfo.fileName(); QString destPath = getAbsolutePath("imgs/" + destFileName); // Копируем, если файл еще не существует if (!QFile::exists(destPath)) { QFile::copy(imgPath, destPath); } notif.url = "/imgs/" + destFileName; } // Звук QString soundPath = ui->edtFileSong->text(); if (!soundPath.isEmpty() && QFile::exists(soundPath)) { QFileInfo soundInfo(soundPath); QString destFileName = soundInfo.fileName(); QString destPath = getAbsolutePath("sounds/" + destFileName); // Копируем, если файл еще не существует if (!QFile::exists(destPath)) { QFile::copy(soundPath, destPath); } notif.soundURL = "/sounds/" + destFileName; } // ПОЛУЧАЕМ НАСТРОЙКИ ИЗ ВИДЖЕТОВ // 1. Получаем настройки цвета блока из FColorSetting FColorSetting *colorSetting = ui->wBlock; if (colorSetting) { // Получаем выбранный цвет блока QColor blockColor = colorSetting->cbBlockColor->currentData().value(); 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(); if (!borderColor.isValid()) { borderColor = QColor(colorSetting->cbBorderColor->currentText()); } notif.borderColor = borderColor.name(); // Получаем размер границы notif.borderSize = colorSetting->sbBorderSize->value(); // Получаем цвет фона СТРАНИЦЫ (не блока!) QColor pageBackgroundColor = colorSetting->cbBackgroundColor->currentData().value(); 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(); 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(); 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::copyFileToAppDir(const QString &sourcePath, const QString &destSubDir) { QFileInfo sourceInfo(sourcePath); QString destPath = getAbsolutePath(destSubDir + "/" + sourceInfo.fileName()); // Копируем файл, если он еще не существует или изменился if (!QFile::exists(destPath) || QFileInfo(sourcePath).lastModified() > QFileInfo(destPath).lastModified()) { QFile::remove(destPath); // Удаляем старую версию if (QFile::copy(sourcePath, destPath)) { } else { } } } QString FCreateNotify::getAbsolutePath(const QString &relativePath) { return QApplication::applicationDirPath() + "/" + relativePath; } 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, "Ошибка", "Не удалось запустить веб-сервер"); } }