processthread.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. #include "processthread.h"
  2. #include "api/configapi.h"
  3. #include "appevent.h"
  4. #include "processmodel.h"
  5. #include "qjsonarray.h"
  6. #include "qjsonobject.h"
  7. #include <cwf/sqldatabasestorage.h>
  8. #include <optional>
  9. #include "api/processapi.h"
  10. #include "qjsonvalue.h"
  11. #include "qlist.h"
  12. #include "qmessagebox.h"
  13. #include "qnamespace.h"
  14. #include "basemainTr.h"
  15. CWF::SqlDatabaseStorage storage("QSQLITE", "localhost", "postgres", "postgres", "1234", 5432);
  16. // 将 FILETIME 转换为 Unix 时间戳
  17. static qint64 fileTimeToUnixTimestamp(FILETIME ft)
  18. {
  19. // FILETIME 是自 1601 年以来的 100 毫微秒数
  20. ULARGE_INTEGER ull;
  21. ull.LowPart = ft.dwLowDateTime;
  22. ull.HighPart = ft.dwHighDateTime;
  23. // FILETIME 和 时间戳的 基础时间不一样
  24. // 转换为秒,并减去 1601 到 1970 年之间的秒数
  25. if (ull.QuadPart / 10000000LL > 11644473600LL) {
  26. qint64 timestamp = ull.QuadPart / 10000000LL - 11644473600LL;
  27. return timestamp;
  28. }
  29. return ull.QuadPart / 10000000LL;
  30. }
  31. QString convertSecondsToTimeFormat(int totalSeconds)
  32. {
  33. int days = totalSeconds / (24 * 3600); // 计算天数
  34. int hours = (totalSeconds % (24 * 3600)) / 3600; // 计算小时
  35. int minutes = (totalSeconds % 3600) / 60; // 计算分钟
  36. int seconds = totalSeconds % 60; // 计算秒数
  37. // 返回格式化后的字符串,并使用 tr() 标记可翻译的文本
  38. return QString(Tr::tr("%1days%2hours%3minutes%4seconds"))
  39. .arg(days)
  40. .arg(hours)
  41. .arg(minutes)
  42. .arg(seconds);
  43. }
  44. ///
  45. /// \brief 转换到分钟
  46. /// \param totalSeconds
  47. /// \return
  48. ///
  49. QString convertSecondsToMinutesTimeFormat(int totalSeconds)
  50. {
  51. // 只计算分钟
  52. int minutes = totalSeconds / 60;
  53. return QString::number(minutes);
  54. }
  55. void ProcessThread::sendExitTime(qint64 updataTime)
  56. {
  57. ProcessModel processModel{storage};
  58. // 在数据库 获取 不是这个更新日期的数据
  59. CWF::SqlQueryManager qry(storage);
  60. qry.select("*", processModel.getTableName())
  61. .where(QString("updataTime != '%1' OR updataTime IS NULL").arg(updataTime));
  62. qry.prepare();
  63. QJsonObject jsonObject = qry.exec();
  64. QJsonArray jsonArray = qry.toJson();
  65. QJsonArray sendJsonArray;
  66. if (jsonArray.size() > 0) {
  67. for (const auto &json : jsonArray) {
  68. const QJsonObject object = json.toObject();
  69. QJsonObject sendObject;
  70. sendObject.insert("pid", object["pid"]);
  71. sendObject.insert("pid_name", object["processName"]);
  72. sendObject.insert("begin_time", object["creationTime"]);
  73. sendObject.insert("end_time", object["exitTime"]);
  74. sendObject.insert("last_check_time", object["updataTime"]);
  75. sendObject.insert("status", 1);
  76. sendObject.insert("notes", "");
  77. sendJsonArray.append(sendObject);
  78. }
  79. }
  80. // 上传 后 删除
  81. if (sendJsonArray.size() > 0) {
  82. TC::ProcessApi processApi(sendJsonArray);
  83. bool isSendok = processApi.post();
  84. if (isSendok) {
  85. // 移除发送到服务器的本地数据
  86. CWF::SqlQueryManager qry(storage);
  87. qry.remove(processModel.getTableName(),
  88. QString("updataTime != '%1' OR updataTime IS NULL").arg(updataTime));
  89. qry.prepare();
  90. QJsonObject jsonObject = qry.exec();
  91. QJsonArray jsonArray = qry.toJson();
  92. }
  93. }
  94. bool isok = false;
  95. QVariant timeVariant = AppEvent::instance()->configReadValue("ProcessOutTime", &isok);
  96. int time = 0;
  97. if (isok) {
  98. time = timeVariant.toLongLong();
  99. } else {
  100. // 服务器时间
  101. TC::ConfigApi configApi("swrunTime");
  102. std::optional<QVariant> value = configApi.get();
  103. if (value.has_value()) {
  104. time = value.value().toInt();
  105. }
  106. }
  107. QVariant messageBoxPointX = QVariant();
  108. QVariant messageBoxPointY = QVariant();
  109. QVariant messageText = QVariant("");
  110. QVariant messageTitle = QVariant(Tr::tr("Tips"));
  111. {
  112. TC::ConfigApi configApi("messageBoxPointX");
  113. std::optional<QVariant> value = configApi.get();
  114. if (value.has_value()) {
  115. messageBoxPointX = value.value().toInt();
  116. }
  117. }
  118. {
  119. TC::ConfigApi configApi("messageBoxPointY");
  120. std::optional<QVariant> value = configApi.get();
  121. if (value.has_value()) {
  122. messageBoxPointY = value.value().toInt();
  123. }
  124. }
  125. {
  126. TC::ConfigApi configApi("messageText");
  127. std::optional<QVariant> value = configApi.get();
  128. if (value.has_value()) {
  129. messageText = value.value().toString();
  130. }
  131. }
  132. {
  133. TC::ConfigApi configApi("messageTitle");
  134. std::optional<QVariant> value = configApi.get();
  135. if (value.has_value()) {
  136. messageTitle = value.value().toString();
  137. }
  138. }
  139. QMap<QString, QString> messageProcessName;
  140. TC::ProcessNameApi processNameApi;
  141. QJsonArray array = processNameApi.get();
  142. for (const auto item : array) {
  143. if (item.isObject()) {
  144. const auto object = item.toObject();
  145. const QString name = object["name"].toString();
  146. const QString zhName = object["chinese_name"].toString();
  147. if (object.contains("is_prompt")) {
  148. if (object["is_prompt"].toInt() == 2) {
  149. messageProcessName[name] = zhName;
  150. };
  151. }
  152. }
  153. }
  154. // messageProcessName["WeChat.exe"] = "WeChat.exe";
  155. // 提示
  156. // SELECT * FROM ProcessTime WHERE (updataTime - lastAlertTime) > 1565;
  157. if (time > 0) {
  158. CWF::SqlQueryManager qry(storage);
  159. qry.select("*", processModel.getTableName())
  160. .where(QString("(updataTime - lastAlertTime) > %1").arg(time));
  161. qry.prepare();
  162. QJsonObject jsonObject = qry.exec();
  163. QJsonArray jsonArray = qry.toJson();
  164. const QStringList keys = messageProcessName.keys();
  165. for (const auto &value : jsonArray) {
  166. // SLDWORKS.exe
  167. const QJsonObject object = value.toObject();
  168. const QString processName = object["processName"].toString();
  169. const qint64 runTime = object["exitTime"].toVariant().toLongLong()
  170. - object["creationTime"].toVariant().toLongLong();
  171. for (const QString &key : keys) {
  172. if (processName.compare(key, Qt::CaseSensitivity::CaseInsensitive) == 0) {
  173. // QVariant messageBoxPointX = QVariant();
  174. // QVariant messageBoxPointY = QVariant();
  175. // QVariant messageText = QVariant("");
  176. // QVariant messageTitle = QVariant(Tr::tr("Tips"));
  177. // Program A has been used for 20 minutes, please exercise
  178. // const QString text = QString(tr("program %1 %3 run time :%2")
  179. // .arg(messageProcessName[key])
  180. // .arg(convertSecondsToTimeFormat(runTime))
  181. // .arg(messageText.toString()));
  182. const QString text = QString(tr("Program %1 has been used for %2 minutes%3")
  183. .arg(messageProcessName[key])
  184. .arg(convertSecondsToMinutesTimeFormat(runTime))
  185. .arg(messageText.toString()));
  186. emit messageBox(text, messageBoxPointX, messageBoxPointY, messageTitle);
  187. }
  188. }
  189. // 更新 lastAlertTime
  190. ProcessModel processModel{storage};
  191. processModel.buildFromJson(object);
  192. // 更新 消息时间
  193. processModel.setLastAlertTime(updataTime);
  194. processModel.save();
  195. }
  196. }
  197. }
  198. bool ProcessThread::upDataProcessSql()
  199. {
  200. std::vector<std::shared_ptr<ProcessMonitor::ProcessInfo>> timeProcessVector
  201. = processMonitor.checkProcesses();
  202. // 退出时间默认当前时间 然后更新
  203. auto exitTimestamp = QDateTime::currentSecsSinceEpoch();
  204. auto updataTimestamp = QDateTime::currentSecsSinceEpoch();
  205. QStringList sqlValues;
  206. for (auto timeProcess : timeProcessVector) {
  207. qint64 timestamp = fileTimeToUnixTimestamp(timeProcess->creationTime);
  208. ProcessModel processModel{storage};
  209. CWF::SqlQueryManager qry(storage);
  210. qry.select("*", processModel.getTableName())
  211. .where(QString("pid == '%1' AND processName == '%2'")
  212. .arg(timeProcess->pid)
  213. .arg(timeProcess->processName.c_str()));
  214. qry.prepare();
  215. QJsonObject jsonObject = qry.exec();
  216. if (jsonObject["success"].toBool()) {
  217. // 查询或者替换 ?
  218. QJsonArray array = qry.toJson();
  219. if (array.size() > 0) {
  220. // 替换
  221. for (const QJsonValue &info : array) {
  222. const QJsonObject object = info.toObject();
  223. //数据还原到 结构体
  224. processModel.buildFromJson(object);
  225. // 更新 结束时间
  226. processModel.setExitTime(exitTimestamp);
  227. processModel.setUpdataTime(updataTimestamp);
  228. processModel.save();
  229. }
  230. } else {
  231. // 插入数据
  232. processModel.setProcessName(timeProcess->processName.c_str());
  233. processModel.setPid(timeProcess->pid);
  234. processModel.setCreationTime(timestamp);
  235. processModel.setExitTime(exitTimestamp);
  236. processModel.setUpdataTime(updataTimestamp);
  237. processModel.setLastAlertTime(updataTimestamp);
  238. processModel.save();
  239. }
  240. }
  241. // qDebug().noquote().nospace() << jsonObject << qry.toJson();
  242. // jsonObject.insert("begin_time", object["creationTime"]);
  243. // jsonObject.insert("end_time", object["exitTime"]);
  244. // jsonObject.insert("last_check_time", object["updataTime"]);
  245. // jsonObject.insert("status", 1);
  246. // jsonObject.insert("notes", "");
  247. // FILETIME ft = timeProcess->creationTime;
  248. // FILETIME currentTime;
  249. // GetSystemTimeAsFileTime(&currentTime);
  250. // ULARGE_INTEGER creation, current;
  251. // creation.LowPart = ft.dwLowDateTime;
  252. // creation.HighPart = ft.dwHighDateTime;
  253. // current.LowPart = currentTime.dwLowDateTime;
  254. // current.HighPart = currentTime.dwHighDateTime;
  255. // ULONGLONG elapsedSeconds = (current.QuadPart - creation.QuadPart) / 10000000;
  256. // // 计算天、小时、分钟和秒
  257. // ULONGLONG days = elapsedSeconds / 86400; // 1天 = 86400秒
  258. // ULONGLONG hours = (elapsedSeconds % 86400) / 3600; // 1小时 = 3600秒
  259. // ULONGLONG minutes = (elapsedSeconds % 3600) / 60; // 1分钟 = 60秒
  260. // ULONGLONG seconds = elapsedSeconds % 60; // 剩余秒数
  261. // // 打印进程的运行时间
  262. // qDebug() << QString::fromStdString(timeProcess->processName) //
  263. // << days << hours << minutes << seconds << timestamp;
  264. /*
  265. INSERT OR REPLACE INTO ProcessTime (pid, processName, creationTime, exitTime)
  266. VALUES
  267. (123, 'process1', strftime('%s', 'now'), strftime('%s', 'now')),
  268. (124, 'process2', strftime('%s', 'now'), strftime('%s', 'now')),
  269. (125, 'process3', strftime('%s', 'now'), strftime('%s', 'now'));
  270. */
  271. // sqlValues.append(QString("(%1,'%2',%3,%4,%5)")
  272. // .arg(timeProcess->pid) // pid
  273. // .arg(timeProcess->processName.c_str()) // 进程名
  274. // .arg(timestamp) // 开始时间戳
  275. // .arg(exitTimestamp) // 结束时间戳
  276. // .arg(updataTimestamp)); // 数据更新时间
  277. }
  278. // const QString query = QString(
  279. // R"(INSERT OR REPLACE INTO ProcessTime
  280. // (pid, processName, creationTime, exitTime, updataTime)
  281. // VALUES
  282. // %1)")
  283. // .arg(sqlValues.join(","));
  284. // // 使用上述插入或者替换
  285. // // 首先查找
  286. // QString where;
  287. // CWF::SqlQueryManager qry(storage);
  288. // QJsonObject jsonObject = qry.exec(query);
  289. // 发送更新后的数据
  290. sendExitTime(updataTimestamp);
  291. // if (jsonObject.contains("success")) {
  292. // if (jsonObject["success"].toBool()) {
  293. // return true;
  294. // }
  295. // }
  296. return false;
  297. }
  298. ProcessThread::ProcessThread(
  299. QObject *parent)
  300. : QThread{parent}
  301. {}
  302. void ProcessThread::run()
  303. {
  304. ProcessModel processModel{storage};
  305. processModel.updateDB();
  306. {
  307. const QString query = QString("CREATE UNIQUE INDEX %2_%3_unique ON %1 (%2, %3);")
  308. .arg(processModel.getTableName())
  309. .arg("pid")
  310. .arg("processName");
  311. CWF::SqlQuery qry(storage);
  312. qry.exec(query);
  313. }
  314. QElapsedTimer timer; // 创建高精度计时器
  315. timer.start(); // 启动计时器
  316. upDataProcessSql();
  317. while (true) {
  318. // 校验网络
  319. if (timer.elapsed() >= 30 * 1000) { // 检查是否经过1分钟
  320. timer.restart(); // 重新启动计时器
  321. upDataProcessSql();
  322. }
  323. msleep(1000); // 休息1秒
  324. }
  325. }