Procházet zdrojové kódy

修复 潜在的bug 添加 host 处理

zhuizhu před 1 rokem
rodič
revize
8e6c3ad70e
7 změnil soubory, kde provedl 222 přidání a 111 odebrání
  1. 6 0
      basemain.pro
  2. 52 0
      hostthread.cpp
  3. 10 0
      hostthread.h
  4. 7 17
      main.cpp
  5. 10 3
      messagequeue.cpp
  6. 9 8
      processmonitor.cpp
  7. 128 83
      processthread.cpp

+ 6 - 0
basemain.pro

@@ -12,6 +12,7 @@ include($$PWD/qtsingleapplication/qtsingleapplication.pri)
 
 SOURCES += \
         appevent.cpp \
+        hostthread.cpp \
         main.cpp \
         messagequeue.cpp \
         processmodel.cpp \
@@ -29,6 +30,7 @@ else: unix:!android: target.path = /opt/$${TARGET}/bin
 HEADERS += \
     appevent.h \
     basemainTr.h \
+    hostthread.h \
     messagequeue.h \
     processmodel.h \
     processmonitor.h \
@@ -48,3 +50,7 @@ CONFIG(debug, debug|release) {
 CONFIG += lrelease
 CONFIG += embed_translations
 TRANSLATIONS += basemain_zh_CN.ts
+msvc {
+    QMAKE_CFLAGS += /utf-8
+    QMAKE_CXXFLAGS += /utf-8
+}

+ 52 - 0
hostthread.cpp

@@ -0,0 +1,52 @@
+#include "hostthread.h"
+#include "qdebug.h"
+
+#include <QFile>
+#include <QString>
+#include <QTextStream>
+
+static bool modifyHostsFile(const QString &hostname, const QString &ipAddress)
+{
+    QString hostsFilePath;
+
+#ifdef Q_OS_WIN
+    hostsFilePath = "C:/Windows/System32/drivers/etc/hosts";
+#else
+    hostsFilePath = "/etc/hosts";
+#endif
+
+    // 打开hosts文件
+    QFile file(hostsFilePath);
+    if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) {
+        qWarning() << "无法打开文件" << hostsFilePath;
+        return false;
+    }
+
+    // 读取文件内容
+    QTextStream stream(&file);
+    QString fileContent = stream.readAll();
+    qDebug() << fileContent;
+    // 检查是否已经包含该映射
+    if (fileContent.contains(hostname)) {
+        qDebug() << "该域名映射已经存在";
+        file.close();
+        return true;
+    }
+
+    // 添加新的映射
+    file.seek(file.size());                         // 将文件指针移动到文件末尾
+    stream << "\n" << ipAddress << " " << hostname; // 添加映射
+
+    file.close();
+    qDebug() << "已成功修改 hosts 文件";
+    return true;
+}
+
+HostThread::HostThread()
+{
+    if (modifyHostsFile("example.com", "127.0.0.1")) {
+        qDebug() << "Hosts 文件已成功更新。";
+    } else {
+        qDebug() << "修改失败。";
+    }
+}

+ 10 - 0
hostthread.h

@@ -0,0 +1,10 @@
+#ifndef HOSTTHREAD_H
+#define HOSTTHREAD_H
+
+class HostThread
+{
+public:
+    HostThread();
+};
+
+#endif // HOSTTHREAD_H

+ 7 - 17
main.cpp

@@ -12,7 +12,6 @@
 #include "messagequeue.h"
 #include "processthread.h"
 #include "qdatetime.h"
-#include "qmessagebox.h"
 #include "qobject.h"
 #include "qtsingleapplication.h"
 #include "updaterthread.h"
@@ -69,19 +68,16 @@ void redirectOutputToLogFile()
     });
 }
 
+
 int main(int argc, char *argv[])
 {
     // QApplication a(argc, argv);
     SharedTools::QtSingleApplication a("BaseMainApp", argc, argv);
-    if (a.isRunning()) {
-        a.sendMessage("", 1000);
-        return 0;
-    }
     QDir dir;
     dir.mkdir("log"); // 创建日志目录
     addToStartup();   // 开机启动
 
-    // redirectOutputToLogFile(); // 日志
+    redirectOutputToLogFile(); // 日志
     a.setApplicationVersion("1.1.2");
     a.setQuitOnLastWindowClosed(false);
 
@@ -93,6 +89,11 @@ int main(int argc, char *argv[])
     parser.addOption(debugOption);
     parser.process(a);
 
+    if (a.isRunning()) {
+        a.sendMessage("", 1000);
+        return 0;
+    }
+
     QTranslator translator;
     const QStringList uiLanguages = QLocale::system().uiLanguages();
     for (const QString &locale : uiLanguages) {
@@ -109,17 +110,6 @@ int main(int argc, char *argv[])
     MessageQueue messageQueue;
 
     QObject::connect(&Process, &ProcessThread::messageBox, &messageQueue, &MessageQueue::addMessage);
-    // QObject::connect(&Process, &ProcessThread::messageBox, [](const QString &text) {
-    //     QMetaObject::invokeMethod(
-    //         QApplication::instance(),
-    //         [text]() {
-    //             QMessageBox messageBox;
-    //             messageBox.setWindowModality(Qt::NonModal);
-    //             messageBox.setText(text);
-    //             messageBox.exec();
-    //         },
-    //         Qt::QueuedConnection);
-    // });
     QObject::connect(&Process, &ProcessThread::finished, &Process, &QObject::deleteLater);
     thread.start();
     Process.start();

+ 10 - 3
messagequeue.cpp

@@ -3,7 +3,13 @@
 
 #include <QApplication>
 #include <QMessageBox>
-
+static bool isNumeric(const QVariant &variant)
+{
+    int type = variant.type();
+    return (type == QMetaType::Int || type == QMetaType::UInt || type == QMetaType::Double
+            || type == QMetaType::Float || type == QMetaType::Long || type == QMetaType::ULong
+            || type == QMetaType::LongLong || type == QMetaType::ULongLong);
+}
 void MessageQueue::processQueue()
 {
     if (isProcessing || messageQueue.isEmpty()) {
@@ -16,7 +22,8 @@ void MessageQueue::processQueue()
     QVariant messageBoxPointX = this->messageBoxPointX;
     QVariant messageBoxPointY = this->messageBoxPointY;
     QVariant messageTitle = this->messageTitle;
-    qDebug() << "currentMessage" << currentMessage;
+    qDebug() << "currentMessage" << currentMessage << messageBoxPointX << messageBoxPointY
+             << messageTitle;
     // 在主线程中显示消息框
     QMetaObject::invokeMethod(
         QApplication::instance(),
@@ -27,7 +34,7 @@ void MessageQueue::processQueue()
             int y = messageBoxPointY.toInt(&isokY);
             qDebug() << x << y << isokX << isokY;
             QMessageBox *messageBox = new QMessageBox;
-            if (isokX && isokY) {
+            if (isokX && isokY && isNumeric(messageBoxPointX) && isNumeric(messageBoxPointY)) {
                 messageBox->move(x, y);
             }
             QString title = messageTitle.toString();

+ 9 - 8
processmonitor.cpp

@@ -1,6 +1,5 @@
 #include "processmonitor.h"
-BOOL EnablePrivilege(
-    LPCWSTR privilege)
+BOOL EnablePrivilege(LPCWSTR privilege)
 {
     HANDLE hToken;
     TOKEN_PRIVILEGES tp;
@@ -93,14 +92,17 @@ std::vector<std::shared_ptr<ProcessMonitor::ProcessInfo>> ProcessMonitor::checkP
     }
     return timeProcess;
 }
-DWORD ProcessMonitor::getRootPid(
-    DWORD pid)
+DWORD ProcessMonitor::getRootPid(DWORD pid)
 {
     if (mapData.find(pid) != mapData.end()) {
-        if (pid == mapData[pid]->parentPid) {
+        const auto value = mapData.at(pid);
+        if (pid == value->pid) {
             return pid;
         }
-        DWORD id = getRootPid(mapData[pid]->parentPid);
+        if (pid == value->parentPid) {
+            return pid;
+        }
+        DWORD id = getRootPid(value->parentPid);
         if (id == -1) {
             return pid;
         }
@@ -119,8 +121,7 @@ std::set<std::shared_ptr<ProcessMonitor::ProcessInfo>> ProcessMonitor::root()
     }
     return roots;
 }
-std::shared_ptr<ProcessMonitor::ProcessInfo> ProcessMonitor::getProcessInfo(
-    DWORD pid)
+std::shared_ptr<ProcessMonitor::ProcessInfo> ProcessMonitor::getProcessInfo(DWORD pid)
 {
     std::shared_ptr<ProcessInfo> info = std::make_shared<ProcessInfo>();
     // ProcessInfo info;

+ 128 - 83
processthread.cpp

@@ -59,6 +59,24 @@ QString convertSecondsToMinutesTimeFormat(int totalSeconds)
 }
 void ProcessThread::sendExitTime(qint64 updataTime)
 {
+    TC::ProcessNameApi processNameApi;
+    QJsonArray serverArray = processNameApi.get();
+
+    // 获取过滤名单
+    QSet<QString> filter;
+    for (const QJsonValue &item : serverArray) {
+        if (!item.isObject()) {
+            return;
+        }
+        const QJsonObject object = item.toObject();
+        const QString name = object["name"].toString();
+        if (object.contains("is_confirmed")) {
+            if (object["is_confirmed"].toInt() == 2) {
+                filter.insert(name);
+            }
+        }
+    }
+
     ProcessModel processModel{storage};
     // 在数据库 获取 不是这个更新日期的数据
 
@@ -74,6 +92,8 @@ void ProcessThread::sendExitTime(qint64 updataTime)
     if (jsonArray.size() > 0) {
         for (const auto &json : jsonArray) {
             const QJsonObject object = json.toObject();
+
+            const QString name = object["processName"].toString();
             QJsonObject sendObject;
             sendObject.insert("pid", object["pid"]);
             sendObject.insert("pid_name", object["processName"]);
@@ -82,7 +102,11 @@ void ProcessThread::sendExitTime(qint64 updataTime)
             sendObject.insert("last_check_time", object["updataTime"]);
             sendObject.insert("status", 1);
             sendObject.insert("notes", "");
-            sendJsonArray.append(sendObject);
+
+            // 存在过滤里面的 不发送数据
+            if (!filter.contains(name)) {
+                sendJsonArray.append(sendObject);
+            }
         }
     }
     // 上传 后 删除
@@ -100,21 +124,6 @@ void ProcessThread::sendExitTime(qint64 updataTime)
             QJsonArray jsonArray = qry.toJson();
         }
     }
-    bool isok = false;
-    QVariant timeVariant = AppEvent::instance()->configReadValue("ProcessOutTime", &isok);
-
-    int time = 0;
-    if (isok) {
-        time = timeVariant.toLongLong();
-    } else {
-        // 服务器时间
-        TC::ConfigApi configApi("swrunTime");
-        std::optional<QVariant> value = configApi.get();
-        if (value.has_value()) {
-            time = value.value().toInt();
-        }
-    }
-
     QVariant messageBoxPointX = QVariant();
     QVariant messageBoxPointY = QVariant();
     QVariant messageText = QVariant("");
@@ -123,99 +132,135 @@ void ProcessThread::sendExitTime(qint64 updataTime)
         TC::ConfigApi configApi("messageBoxPointX");
         std::optional<QVariant> value = configApi.get();
         if (value.has_value()) {
-            messageBoxPointX = value.value().toInt();
+            messageBoxPointX = value.value();
         }
     }
     {
         TC::ConfigApi configApi("messageBoxPointY");
         std::optional<QVariant> value = configApi.get();
         if (value.has_value()) {
-            messageBoxPointY = value.value().toInt();
+            messageBoxPointY = value.value();
         }
     }
     {
         TC::ConfigApi configApi("messageText");
         std::optional<QVariant> value = configApi.get();
         if (value.has_value()) {
-            messageText = value.value().toString();
+            messageText = value.value();
         }
     }
     {
         TC::ConfigApi configApi("messageTitle");
         std::optional<QVariant> value = configApi.get();
         if (value.has_value()) {
-            messageTitle = value.value().toString();
+            messageTitle = value.value();
         }
     }
 
-    QMap<QString, QString> messageProcessName;
-
-    TC::ProcessNameApi processNameApi;
-    QJsonArray array = processNameApi.get();
-    for (const auto item : array) {
-        if (item.isObject()) {
-            const auto object = item.toObject();
-
-            const QString name = object["name"].toString();
-            const QString zhName = object["chinese_name"].toString();
-            if (object.contains("is_prompt")) {
-                if (object["is_prompt"].toInt() == 2) {
-                    messageProcessName[name] = zhName;
-                };
-            }
+    for (const QJsonValue &item : serverArray) {
+        if (!item.isObject()) {
+            return;
         }
-    }
-    // messageProcessName["WeChat.exe"] = "WeChat.exe";
-
-    // 提示
-    // SELECT * FROM ProcessTime  WHERE (updataTime - lastAlertTime) > 1565;
-    if (time > 0) {
-        CWF::SqlQueryManager qry(storage);
-        qry.select("*", processModel.getTableName())
-            .where(QString("(updataTime - lastAlertTime) > %1").arg(time));
-        qry.prepare();
-        QJsonObject jsonObject = qry.exec();
-        QJsonArray jsonArray = qry.toJson();
-
-        const QStringList keys = messageProcessName.keys();
-
-        for (const auto &value : jsonArray) {
-            // SLDWORKS.exe
-
-            const QJsonObject object = value.toObject();
-            const QString processName = object["processName"].toString();
-            const qint64 runTime = object["exitTime"].toVariant().toLongLong()
-                                   - object["creationTime"].toVariant().toLongLong();
-
-            for (const QString &key : keys) {
-                if (processName.compare(key, Qt::CaseSensitivity::CaseInsensitive) == 0) {
-                    // QVariant messageBoxPointX = QVariant();
-                    // QVariant messageBoxPointY = QVariant();
-                    // QVariant messageText = QVariant("");
-                    // QVariant messageTitle = QVariant(Tr::tr("Tips"));
-                    // Program A has been used for 20 minutes, please exercise
-
-                    // const QString text = QString(tr("program %1 %3 run time :%2")
-                    //                                  .arg(messageProcessName[key])
-                    //                                  .arg(convertSecondsToTimeFormat(runTime))
-                    //                                  .arg(messageText.toString()));
-
-                    const QString text = QString(tr("Program %1 has been used for %2 minutes%3")
-                                                     .arg(messageProcessName[key])
-                                                     .arg(convertSecondsToMinutesTimeFormat(runTime))
-                                                     .arg(messageText.toString()));
-                    emit messageBox(text, messageBoxPointX, messageBoxPointY, messageTitle);
+        const QJsonObject object = item.toObject();
+
+        const QString name = object["name"].toString();
+        const QString zhName = object["chinese_name"].toString();
+        if (object.contains("is_prompt")) {
+            if (object["is_prompt"].toInt() == 2) {
+                const QString name = object["name"].toString();
+                const QString zhName = object["chinese_name"].toString();
+                const int time = object["prompt_time"].toInt();
+                if (time > 0) {
+                    const QString whereTime = QString("(updataTime - lastAlertTime) > %1").arg(time);
+                    const QString whereProcessName = QString("processName = '%1'").arg(name);
+                    const QString whereUpdataTime = QString("updataTime = '%1'").arg(updataTime);
+                    CWF::SqlQueryManager qry(storage);
+                    qry.select("*", processModel.getTableName())
+                        .where(QString("%1 AND %2 AND %3")
+                                   .arg(whereTime)
+                                   .arg(whereProcessName)
+                                   .arg(whereUpdataTime));
+                    qry.prepare();
+                    QJsonObject jsonObject = qry.exec();
+                    QJsonArray jsonArray = qry.toJson();
+                    qDebug() << jsonArray;
+                    for (const auto &value : jsonArray) {
+                        const QJsonObject object = value.toObject();
+                        const QString processName = object["processName"].toString();
+                        const qint64 runTime = object["exitTime"].toVariant().toLongLong()
+                                               - object["creationTime"].toVariant().toLongLong();
+
+                        const QString text = QString(
+                            tr("Program %1 has been used for %2 minutes%3")
+                                .arg(zhName)
+                                .arg(convertSecondsToMinutesTimeFormat(runTime))
+                                .arg(messageText.toString()));
+                        emit messageBox(text, messageBoxPointX, messageBoxPointY, messageTitle);
+
+                        // 更新 lastAlertTime
+                        ProcessModel processModel{storage};
+                        processModel.buildFromJson(object);
+                        // 更新 消息时间
+                        processModel.setLastAlertTime(updataTime);
+                        processModel.save();
+                    }
                 }
             }
-
-            // 更新 lastAlertTime
-            ProcessModel processModel{storage};
-            processModel.buildFromJson(object);
-            // 更新 消息时间
-            processModel.setLastAlertTime(updataTime);
-            processModel.save();
         }
     }
+
+    // for (const QJsonValue &item : array) {
+    //     if (item.isObject()) {
+    //         const QJsonObject object = item.toObject();
+
+    //         const QString name = object["name"].toString();
+    //         const QString zhName = object["chinese_name"].toString();
+    //         if (object.contains("is_prompt")) {
+    //             if (object["is_prompt"].toInt() == 2) {
+    //                 messageProcessName[name] = zhName;
+    //             };
+    //         }
+    //     }
+    // }
+    // qDebug() << messageProcessName;
+    // // SELECT * FROM ProcessTime  WHERE (updataTime - lastAlertTime) > 1565;
+    // if (time > 0) {
+    //     const QString whereTime = QString("(updataTime - lastAlertTime) > %1").arg(time);
+    //     const QString whereProcessName = QString("processName = '%1'").arg("WeChat.exe");
+    //     CWF::SqlQueryManager qry(storage);
+    //     qry.select("*", processModel.getTableName()).where(whereTime);
+    //     qry.prepare();
+    //     QJsonObject jsonObject = qry.exec();
+    //     QJsonArray jsonArray = qry.toJson();
+
+    //     const QStringList keys = messageProcessName.keys();
+
+    //     for (const auto &value : jsonArray) {
+    //         // SLDWORKS.exe
+
+    //         const QJsonObject object = value.toObject();
+    //         const QString processName = object["processName"].toString();
+    //         const qint64 runTime = object["exitTime"].toVariant().toLongLong()
+    //                                - object["creationTime"].toVariant().toLongLong();
+
+    //         for (const QString &key : keys) {
+    //             if (processName.compare(key, Qt::CaseSensitivity::CaseInsensitive) == 0) {
+    //                 const QString text = QString(tr("Program %1 has been used for %2 minutes%3")
+    //                                                  .arg(messageProcessName[key])
+    //                                                  .arg(convertSecondsToMinutesTimeFormat(runTime))
+    //                                                  .arg(messageText.toString()));
+    //                 emit messageBox(text, messageBoxPointX, messageBoxPointY, messageTitle);
+    //             }
+    //         }
+
+    //         // 更新 lastAlertTime
+    //         ProcessModel processModel{storage};
+    //         processModel.buildFromJson(object);
+    //         // 更新 消息时间
+    //         processModel.setLastAlertTime(updataTime);
+    //         processModel.save();
+    //     }
+    // }
 }
 
 bool ProcessThread::upDataProcessSql()