commit 676e8e4ff6287418f23499e30d3fde5755ede101 Author: admin Date: Sat Oct 10 19:15:31 2026 +0800 Initial commit: Crown Qt client/server project diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9669bf6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,86 @@ +## Visual Studio 缓存与用户配置 +.vs/ +*.suo +*.user +*.userosscache +*.sln.docstates +*.userprefs +*.VC.db +*.VC.opendb +*.opendb +*.sdf +*.opensdf +*.psess +*.vsp +*.vspx +*.sap +*.cachefile + +## 编译输出目录 +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +bld/ +[Bb]in/ +[Oo]bj/ + +## MSBuild / 编译器中间文件 +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.ilk +*.exp +*.lib +*.res +*.tlog +*.lastbuildstate +*.unsuccessfulbuild +*.recipe +*.FileListAbsolute.txt +*.CppClean.log + +## Qt / MSBuild 生成文件 +moc/ +uic/ +rcc/ +qmake/ +GeneratedFiles/ +moc_*.cpp +moc_*.h +ui_*.h +qrc_*.cpp +*.qmake.stash +qt_work.log +windeployqt.log +qt.natvis +*.aps + +## 可执行文件与动态库 +*.exe +*.dll + +## 运行时数据 +*.db +*.log +*.zip +*.ilk + +## 操作系统 +Thumbs.db +Desktop.ini +.DS_Store diff --git a/2025-06-16.txt b/2025-06-16.txt new file mode 100644 index 0000000..9ac206e --- /dev/null +++ b/2025-06-16.txt @@ -0,0 +1,44 @@ +服务端 会员网址 自动更新列表,输入框调宽,账号密码调窄 √ +跟单成功赔率 显示赔率 读取的赔率/成功的赔率 √ +跟单失败 原盘口 原赔率 ?改完未测试 +接受注单 接收时间没显示 √ 彻底修复 大小写问题 + +服务端时间切换显示 √ +客户端 会员网址自动更新列表 √ + + + +客户端不停止,直接关,有可能导致服务端闪退 + + + +失败可能需要更新赔率,盘口,现在只更新原因 +出现了重复跟单,跟单成功应该唯一 ? + + +金额判断->跟单失败空记录,补单空记录 // 缺代码,补全即可 √ +有时候跟单成功最新赔率不显示 应该是旧数据库格式问题 √ + + + +跟单项目默认值// +x掉缩小到任务栏√ +限制多开 √ + +服务端/客户端 开始后锁死配置 +客户端会员界面有时候点不动 +日志去掉 + +心跳/在线 + + + +616 666 6399 + +ba.al +https://www.webhostal.net/domain/ba.al +2020-01注册 + + +50 / 50000 + diff --git a/Crown.sln b/Crown.sln new file mode 100644 index 0000000..2857e86 --- /dev/null +++ b/Crown.sln @@ -0,0 +1,41 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.6.33829.357 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CrownServer", "CrownServer\Crown.vcxproj", "{67E7A149-F86D-481B-AF61-E98BA438B8C4}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CrownClient", "CrownClient\CrownClient.vcxproj", "{C339197A-FFBA-4AE7-81FA-325702162EC1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {67E7A149-F86D-481B-AF61-E98BA438B8C4}.Debug|x64.ActiveCfg = Debug|x64 + {67E7A149-F86D-481B-AF61-E98BA438B8C4}.Debug|x64.Build.0 = Debug|x64 + {67E7A149-F86D-481B-AF61-E98BA438B8C4}.Debug|x86.ActiveCfg = Debug|Win32 + {67E7A149-F86D-481B-AF61-E98BA438B8C4}.Debug|x86.Build.0 = Debug|Win32 + {67E7A149-F86D-481B-AF61-E98BA438B8C4}.Release|x64.ActiveCfg = Release|x64 + {67E7A149-F86D-481B-AF61-E98BA438B8C4}.Release|x64.Build.0 = Release|x64 + {67E7A149-F86D-481B-AF61-E98BA438B8C4}.Release|x86.ActiveCfg = Release|Win32 + {67E7A149-F86D-481B-AF61-E98BA438B8C4}.Release|x86.Build.0 = Release|Win32 + {C339197A-FFBA-4AE7-81FA-325702162EC1}.Debug|x64.ActiveCfg = Debug|x64 + {C339197A-FFBA-4AE7-81FA-325702162EC1}.Debug|x64.Build.0 = Debug|x64 + {C339197A-FFBA-4AE7-81FA-325702162EC1}.Debug|x86.ActiveCfg = Debug|Win32 + {C339197A-FFBA-4AE7-81FA-325702162EC1}.Debug|x86.Build.0 = Debug|Win32 + {C339197A-FFBA-4AE7-81FA-325702162EC1}.Release|x64.ActiveCfg = Release|x64 + {C339197A-FFBA-4AE7-81FA-325702162EC1}.Release|x64.Build.0 = Release|x64 + {C339197A-FFBA-4AE7-81FA-325702162EC1}.Release|x86.ActiveCfg = Release|Win32 + {C339197A-FFBA-4AE7-81FA-325702162EC1}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {93D0FBB0-047D-4D03-802F-8B22400F6CE7} + EndGlobalSection +EndGlobal diff --git a/CrownClient/Amount.cpp b/CrownClient/Amount.cpp new file mode 100644 index 0000000..38fd640 --- /dev/null +++ b/CrownClient/Amount.cpp @@ -0,0 +1,156 @@ +#include "Amount.h" +#include +#include "Global.h" + +Amount::Amount(QWidget *parent) + : QWidget(parent) +{ + ui.setupUi(this); + + // 设置窗口图标 + this->setWindowIcon(QIcon(":/images/Images/client.ico")); + // 设置窗口标题 + this->setWindowTitle("注单金额判断处理"); + // 设置为对话框窗口 + setWindowFlags(Qt::Dialog); + // 设置窗口仅有关闭按钮 + setWindowFlags(Qt::WindowCloseButtonHint); + // 设置窗口固定大小 + this->setFixedSize(460,700); + + ui.originalAmountLowerCheckBox->setChecked(g_config->originalAmountLowerGiveUpEnable()); + ui.originalAmountLowerEdit->setText(QString::number(g_config->originalAmountLower())); + ui.originalAmountHigherCheckBox->setChecked(g_config->originalAmountHigherGiveUpEnable()); + ui.originalAmountHigherEdit->setText(QString::number(g_config->originalAmountHigher())); + + ui.amountLowerCheckBox->setChecked(g_config->amountLowerEnable()); + ui.amountLowerEdit->setText(QString::number(g_config->amountLower())); + ui.amountLowerAddToRadio->setChecked(g_config->amountLowerAddToEnable()); + ui.amountLowerAddToEdit->setText(QString::number(g_config->amountLowerAddTo())); + ui.amountLowerGiveUpRadio->setChecked(g_config->amountLowerGiveUpEnable()); + + ui.amountHigherCheckBox->setChecked(g_config->amountHigherEnable()); + ui.amountHigherEdit->setText(QString::number(g_config->amountHigher())); + ui.amountHigherSubToRadio->setChecked(g_config->amountHigherSubToEnable()); + ui.amountHigherSubToEdit->setText(QString::number(g_config->amountHigherSubTo())); + ui.amountHigherGiveUpRadio->setChecked(g_config->amountHigherGiveUpEnable()); + + + if (g_config->amount_less_than_platform() == 0) + { + ui.amount_less_add->setChecked(true); + } + else + { + ui.amount_less_give_up->setChecked(true); + } + + if (g_config->amount_more_than_platform() == 0) + { + ui.amount_more_sub->setChecked(true); + } + else + { + ui.amount_more_give_up->setChecked(true); + } + + + //ui.halfAdjustEdit->setText(QString::number(g_config->carry())); + //ui.halfAdjustComboBox->setCurrentIndex(g_config->carryIndex()); + //ui.halfAdjustRadio->setChecked(g_config->carryHalfAdjustEnable()); + //ui.roundingRadio->setChecked(g_config->carryRoundingEnable()); + + //ui.minEdit->setText(QString::number(g_config->amountMin())); + //ui.maxEdit->setText(QString::number(g_config->amountMax())); + + //connect(ui.halfAdjustEdit,&QLineEdit::textChanged,this,&Amount::slotCalc); + //connect(ui.halfAdjustComboBox, static_cast(&QComboBox::currentIndexChanged), this, &Amount::slotCalc); + //connect(ui.halfAdjustRadio, &QRadioButton::clicked, this, &Amount::slotCalc); + //connect(ui.roundingRadio, &QRadioButton::clicked, this, &Amount::slotCalc); +} + +Amount::~Amount() +{} + +void Amount::slotCalc() +{ + // 保存 + g_config->setOriginalAmountLowerGiveUpEnable(ui.originalAmountLowerCheckBox->isChecked()); + g_config->setOriginalAmountLower(ui.originalAmountLowerEdit->text().toInt()); + g_config->setOriginalAmountHigherGiveUpEnable(ui.originalAmountHigherCheckBox->isChecked()); + g_config->setOriginalAmountHigher(ui.originalAmountHigherEdit->text().toInt()); + + + g_config->setAmountLowerEnable(ui.amountLowerCheckBox->isChecked()); + g_config->setAmountLower(ui.amountLowerEdit->text().toInt()); + g_config->setAmountLowerAddToEnable(ui.amountLowerAddToRadio->isChecked()); + g_config->setAmountLowerAddTo(ui.amountLowerAddToEdit->text().toInt()); + g_config->setAmountLowerGiveUpEnable(ui.amountLowerGiveUpRadio->isChecked()); + + g_config->setAmountHigherEnable(ui.amountHigherCheckBox->isChecked()); + g_config->setAmountHigher(ui.amountHigherEdit->text().toInt()); + g_config->setAmountHigherSubToEnable(ui.amountHigherSubToRadio->isChecked()); + g_config->setAmountHigherSubTo(ui.amountHigherSubToEdit->text().toInt()); + g_config->setAmountHigherGiveUpEnable(ui.amountHigherGiveUpRadio->isChecked()); + + if (ui.amount_less_add->isChecked()) + { + g_config->set_amount_less_than_platform(0); + } + else + { + g_config->set_amount_less_than_platform(1); + } + + if (ui.amount_more_sub->isChecked()) + { + g_config->set_amount_more_than_platform(0); + } + else + { + g_config->set_amount_more_than_platform(1); + } + + + + + //g_config->setCarry(ui.halfAdjustEdit->text().toInt()); + //g_config->setCarryIndex(ui.halfAdjustComboBox->currentIndex()); + //g_config->setCarryHalfAdjustEnable(ui.halfAdjustRadio->isChecked()); + //g_config->setCarryRoundingEnable(ui.roundingRadio->isChecked()); + + //g_config->setAmountMin(ui.minEdit->text().toInt()); + //g_config->setAmountMax(ui.maxEdit->text().toInt()); + + //ui.result->setText("结果:" + g_config->carry(ui.halfAdjustEdit->text())); +} + +void Amount::closeEvent(QCloseEvent * event) +{ + g_config->setOriginalAmountLowerGiveUpEnable(ui.originalAmountLowerCheckBox->isChecked()); + g_config->setOriginalAmountLower(ui.originalAmountLowerEdit->text().toInt()); + g_config->setOriginalAmountHigherGiveUpEnable(ui.originalAmountHigherCheckBox->isChecked()); + g_config->setOriginalAmountHigher(ui.originalAmountHigherEdit->text().toInt()); + + + g_config->setAmountLowerEnable(ui.amountLowerCheckBox->isChecked()); + g_config->setAmountLower(ui.amountLowerEdit->text().toInt()); + g_config->setAmountLowerAddToEnable(ui.amountLowerAddToRadio->isChecked()); + g_config->setAmountLowerAddTo(ui.amountLowerAddToEdit->text().toInt()); + g_config->setAmountLowerGiveUpEnable(ui.amountLowerGiveUpRadio->isChecked()); + + g_config->setAmountHigherEnable(ui.amountHigherCheckBox->isChecked()); + g_config->setAmountHigher(ui.amountHigherEdit->text().toInt()); + g_config->setAmountHigherSubToEnable(ui.amountHigherSubToRadio->isChecked()); + g_config->setAmountHigherSubTo(ui.amountHigherSubToEdit->text().toInt()); + g_config->setAmountHigherGiveUpEnable(ui.amountHigherGiveUpRadio->isChecked()); + + //g_config->setCarry(ui.halfAdjustEdit->text().toInt()); + //g_config->setCarryIndex(ui.halfAdjustComboBox->currentIndex()); + //g_config->setCarryHalfAdjustEnable(ui.halfAdjustRadio->isChecked()); + //g_config->setCarryRoundingEnable(ui.roundingRadio->isChecked()); + + //g_config->setAmountMin(ui.minEdit->text().toInt()); + //g_config->setAmountMax(ui.maxEdit->text().toInt()); + +} diff --git a/CrownClient/Amount.h b/CrownClient/Amount.h new file mode 100644 index 0000000..78fc088 --- /dev/null +++ b/CrownClient/Amount.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include "ui_Amount.h" + +class Amount : public QWidget +{ + Q_OBJECT + +public: + Amount(QWidget *parent = nullptr); + ~Amount(); +private: + void closeEvent(QCloseEvent* event); +private slots: + void slotCalc(); +private: + Ui::AmountClass ui; +}; diff --git a/CrownClient/Amount.ui b/CrownClient/Amount.ui new file mode 100644 index 0000000..f95948f --- /dev/null +++ b/CrownClient/Amount.ui @@ -0,0 +1,289 @@ + + + AmountClass + + + + 0 + 0 + 393 + 498 + + + + Amount + + + + + + + + + + + + 注单跟单金额小于平台最小值 + + + + + + + 加大到最小值 + + + false + + + + + + + 放弃注单 + + + true + + + + + + + + + + + + + + + + 放弃注单 + + + + + + + + 80 + 16777215 + + + + 50 + + + + + + + + 80 + 16777215 + + + + 50 + + + + + + + 处理方式 + + + + + + + 加大到 + + + true + + + + + + + 注单跟单金额小于 + + + + + + + + + + + + + + + + + 80 + 16777215 + + + + 10000 + + + + + + + 注单原始金额小于 + + + + + + + 注单原始金额大于 + + + + + + + 放弃注单 + + + + + + + + 80 + 16777215 + + + + 50 + + + + + + + 放弃注单 + + + + + + + + + + + + + + + + 注单跟单金额大于 + + + + + + + 处理方式 + + + + + + + + 80 + 16777215 + + + + 10000 + + + + + + + + 80 + 16777215 + + + + 10000 + + + + + + + 减小到 + + + true + + + + + + + 放弃注单 + + + + + + + + + + + + + + + + 注单跟单金额小于平台最小值 + + + + + + + 减小到最大值 + + + false + + + + + + + 放弃注单 + + + true + + + + + + + + + + + + diff --git a/CrownClient/AppInstanceManager.cpp b/CrownClient/AppInstanceManager.cpp new file mode 100644 index 0000000..24abbcb --- /dev/null +++ b/CrownClient/AppInstanceManager.cpp @@ -0,0 +1,44 @@ +#include "AppInstanceManager.h" +#include "Global.h" +#include "Utils.h" +static int number = Utils::instance().get_number_of_application_name(); +AppInstanceManager* AppInstanceManager::instance() { + static AppInstanceManager manager; + return &manager; +} + +AppInstanceManager::AppInstanceManager(QObject *parent) : QObject(parent) { + m_server = new QLocalServer(this); + if (m_server->listen("crown_client_instance" + QString::number(number))) { + connect(m_server, &QLocalServer::newConnection, [this]() { + QLocalSocket *socket = m_server->nextPendingConnection(); + connect(socket, &QLocalSocket::readyRead, [socket, this]() { + if (socket->readAll() == "ACTIVATE") { + emit raiseRequested(); // 触发激活信号 + } + socket->deleteLater(); + }); + }); + } +} + +void AppInstanceManager::notifyActivate() { + QLocalSocket socket; + socket.connectToServer("crown_client_instance" + QString::number(number)); + if (socket.waitForConnected(300)) { + socket.write("ACTIVATE"); + socket.waitForBytesWritten(); + } +} + + +bool AppInstanceManager::isAlreadyRunning() { + QLocalSocket socket; + socket.connectToServer("crown_client_instance" + QString::number(number)); // 固定名称,不要用版本号 + if (socket.waitForConnected(500)) { + socket.write("ACTIVATE"); // 发送激活指令 + socket.waitForBytesWritten(); + return true; // 已存在实例 + } + return false; // 无其他实例 +} \ No newline at end of file diff --git a/CrownClient/AppInstanceManager.h b/CrownClient/AppInstanceManager.h new file mode 100644 index 0000000..5e790bb --- /dev/null +++ b/CrownClient/AppInstanceManager.h @@ -0,0 +1,18 @@ +#pragma once +#include +#include + +class AppInstanceManager : public QObject { + Q_OBJECT +public: + static AppInstanceManager* instance(); + void notifyActivate(); // 向其他实例发送激活信号 + static bool isAlreadyRunning(); + +signals: + void raiseRequested(); // 触发窗口激活 + +private: + explicit AppInstanceManager(QObject *parent = nullptr); + QLocalServer *m_server; +}; \ No newline at end of file diff --git a/CrownClient/BetThread.cpp b/CrownClient/BetThread.cpp new file mode 100644 index 0000000..4cea841 --- /dev/null +++ b/CrownClient/BetThread.cpp @@ -0,0 +1,3450 @@ +#include "BetThread.h" +#include "Global.h" +#include "Utils.h" +#include +#include + +#include "PushMsg.h" + + +#include +BetThread::BetThread() +{ + qRegisterMetaType>>("QList>"); +} + +BetThread::~BetThread() +{ + +} + +void BetThread::run() +{ + while (!this->isInterruptionRequested()) { + QMutexLocker lock(&m_mutex); + + //// 获取账户限额 + //if (m_account_set_bk.isEmpty() || m_account_set_ft.isEmpty()) + //{ + // m_account_set_bk = get_account_set("BK"); + // m_account_set_ft = get_account_set("FT"); + // + // if (!m_account_set_bk.isEmpty() && !m_account_set_ft.isEmpty()) + // { + // emit log("获取篮球限额", QString("让球/大小/单双: %1").arg(m_account_set_bk["DT"])); + // emit log("获取篮球限额", QString("独赢: %1").arg(m_account_set_bk["M"])); + // emit log("获取篮球限额", QString("滚球让球/滚球大小/滚球单双: %1").arg(m_account_set_bk["R"])); + // emit log("获取篮球限额", QString("滚球其他: %1").arg(m_account_set_bk["RDT"])); + // emit log("获取篮球限额", QString("其他: %1").arg(m_account_set_bk["RE"])); + + // emit log("获取足球限额", QString("让球/大小/单双: %1").arg(m_account_set_ft["DT"])); + // emit log("获取足球限额", QString("独赢: %1").arg(m_account_set_ft["M"])); + // emit log("获取足球限额", QString("滚球让球/滚球大小/滚球单双: %1").arg(m_account_set_ft["R"])); + // emit log("获取足球限额", QString("滚球其他: %1").arg(m_account_set_ft["RDT"])); + // emit log("获取足球限额", QString("其他: %1").arg(m_account_set_ft["RE"])); + // } + // else + // { + // emit log("程序日志", "获取账户限额失败"); + // QThread::msleep(5000); + // continue; + // } + //} + + + // 获取订单列表 + auto accept_orders = g_config->get_accept_orders(); + auto screen_orders = g_config->get_screen_orders(); + auto success_orders = g_config->get_success_orders(); + auto failed_orders = g_config->get_failed_orders(); + auto rebet_orders = g_config->get_rebet_orders(); + + // 需要处理的订单 = 接收订单 + 失败订单(排除已补单的) + QList> need_bet_orders; + // 遍历接收注单 + for (auto order : accept_orders) + { + // 成功和筛选跳过 + bool alreadyProcessed = false; + for (auto success_order : success_orders) { + if (success_order["TID"] == order["TID"]) { + alreadyProcessed = true; + break; + } + } + for (auto screen_order : screen_orders) { + if (screen_order["TID"] == order["TID"]) { + alreadyProcessed = true; + break; + } + } + + // 失败记录补单原因但不跳过(需要尝试补单) + for (auto failed_order : failed_orders) { + if (failed_order["TID"] == order["TID"]) { + // 记录补单原因和次数 + order["REBET_TIMES"] = failed_order["REBET_TIMES"]; + order["REBET_REASON"] = failed_order["REASON"]; + break; + } + } + + if (alreadyProcessed) { + continue; + } + + need_bet_orders.append(order); + } + + for (auto order : need_bet_orders) + { + // 补单检测 + bool screen = false; + screen = screen_rebet(order); + if (!screen) + { + // 不补单无需添加筛选(可能需要做时间过滤?) + handleInvalidOrder(order); + continue; + } + + // 跟单队伍和赛事检测 + screen = screen_team_and_league(order); + if (!screen) + { + handleInvalidOrder(order); + continue; + } + // 原始金额检测 + screen = screen_original_gold(order); + if (!screen) + { + handleInvalidOrder(order); + continue; + } + // 代码获取及调整 + order["wtype"] = Utils::get_wtype_code(order); + order["rtype"] = Utils::get_rtype_code(order); + order["rtypeName"] = Utils::get_rtypename(order); + // 自动切换早盘/今日/滚球 + if (g_config->sessionAutoChangeEnable()) + { + order = Utils::auto_switch_session(order); + } + + // 跟单项目检测 + screen = screen_type(order); + if (!screen) + { + handleInvalidOrder(order); + continue; + } + // 赛事盘口检测 + screen = screen_handicap(order); + if (!screen) + { + handleInvalidOrder(order); + continue; + } + // 会员策略检测及调整 + if (!screen_user_policy(order)) + { + handleInvalidOrder(order); + continue; + } + // 查找赛事 + if (!get_game_list(order)) + { + handleFailedOrder(order); + continue; + } + // 查找盘口 + QList> handicaps = get_game_more(order); + + //if (handicaps.isEmpty()) + //{ + // handleFailedOrder(order); + // continue; + //} + //order["REASON"] = "测试"; + //handleInvalidOrder(order); + //continue; + // 盘口检测 + //continue; + if (!screen_con(order, handicaps)) + { + if (order["NEED_REBET"] == "TRUE") + { + handleFailedOrder(order); + continue; + } + else + { + handleInvalidOrder(order); + continue; + } + + } + //continue; + // 获取游戏信息 + if (!get_order_view(order)) + { + // 未匹配到游戏 + handleFailedOrder(order); + continue; + } + + // 限额检测 + if (!screen_gold(order)) + { + handleInvalidOrder(order); + continue; + } + // 比分检测 + if (!screen_score(order)) + { + handleFailedOrder(order); + continue; + } + + // 赔率检测 + if (!screen_ioratio(order)) + { + if (order["NEED_REBET"] == "TRUE") + { + handleFailedOrder(order); + continue; + } + else + { + handleInvalidOrder(order); + continue; + } + } + + // qDebug() << "投注金额:" << order["GOLD"]; + //if (order["GOLD"].toInt() > 1000) + //{ + // qDebug() << "金额异常"; + // continue; + //} + handleNormalOrder(order); + } + + + // 每次循环后休眠100ms,避免CPU空转 + QThread::msleep(1000); + } +} + +void BetThread::pause() +{ + m_mutex.lock(); +} + +void BetThread::resume() +{ + m_mutex.unlock(); +} + +void BetThread::exit() +{ + this->requestInterruption(); +} + + + + + + +QMap BetThread::get_account_set(QString gtype) +{ + QMap resultMap; + + // 1. 准备网络请求(保持不变) + QNetworkAccessManager manager; + QNetworkRequest request(QUrl(m_url + "transform.php?ver=" + m_ver)); + request.setRawHeader("Cookie", m_cookies.toUtf8()); + if (g_config->followDeviceType() == 0) + { + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + } + else + { + request.setRawHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/109.0.0.0"); + } + + // 2. 发送请求 + QNetworkReply* reply = manager.post(request, + QString("%1&p=get_account_set>ype=%2") + .arg(m_param).arg(gtype).toUtf8()); + +#ifdef _DEBUG + emit log("获取平台账户设置", QString("%1&p=get_account_set>ype=%2") + .arg(m_param).arg(gtype).toUtf8()); +#endif + reply->ignoreSslErrors(); + + // 3. 同步等待响应 + QEventLoop loop; + QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit); + loop.exec(); + + // 4. 错误处理 + if (reply->error() != QNetworkReply::NoError) { + qWarning() << "Network error:" << reply->errorString(); + reply->deleteLater(); + + emit log("获取平台限额", "网络异常"); + return resultMap; + } + + // 5. 解析XML(修改核心逻辑) + QXmlStreamReader xml(reply->readAll()); + reply->deleteLater(); + + bool validResponse = false; + const QStringList targetMarkets = { "DT", "M", "R", "RDT","RE" }; + + QString code; + while (!xml.atEnd() && !xml.hasError()) { + xml.readNext(); + + // 5.1 检查响应码 + if (xml.isStartElement() && xml.name() == "code") { + code = xml.readElementText(); + if (code == "error") + { + emit account_disconnect(); + return resultMap; + } + validResponse = (code == "607"); + } + + // 5.2 找到体育类型节点 + if (xml.isStartElement() && xml.name() == gtype) { + while (!(xml.isEndElement() && xml.name() == gtype)) { + xml.readNext(); + + // 5.3 提取所有市场限额 + if (xml.isStartElement() && targetMarkets.contains(xml.name().toString())) { + QString market = xml.name().toString(); + while (!(xml.isEndElement() && xml.name() == market)) { + xml.readNext(); + if (xml.isStartElement() && xml.name() == "min") { + QString minValue = xml.readElementText().remove(','); + //emit log(gtype, QString("%1 : %2").arg(market).arg(minValue)); + resultMap[market] = minValue.toInt(); + break; + } + } + } + } + } + } + + // 6. 最终检查 + if (!validResponse) { + emit log("获取平台限额检查", QString("代码错误: %1").arg(code)); + if (code == "607") + { + //emit log("检查代码","相等"); + } + else + { + //emit log("检查代码", "不相等"); + } +#ifdef _DEBUG + emit log("最终检查失败", "清空"); +#endif + resultMap.clear(); + } + + return resultMap; +} + +QString BetThread::get_market_by_wtype(const QString &wtype) +{ +#ifdef _DEBUG + emit log("订单wtype", QString("%1").arg(wtype)); +#endif + // DT 市场:让球、大小、单双 + if (wtype == "R" || wtype == "OU" || wtype == "EO" || wtype == "HR" || wtype == "HOU" || wtype == "HEO") { + return "DT"; + } + // M 市场:独赢 + else if (wtype == "M" || wtype == "HM") { + return "M"; + } + // R 市场:滚球让球、滚球大小、滚球单双 + else if (wtype == "RE" || wtype == "ROU" || wtype == "REO" || wtype == "HRE" || wtype == "HROU" || wtype == "HREO") { + return "R"; + } + // RDT 市场:滚球其他 + else if (wtype == "RG" || wtype == "RTS" || wtype == "RT" || wtype == "HRG" || wtype == "HRTS" || wtype == "HRT") { + return "RDT"; + } + // RE 市场:其他 + return "RE"; +} + +// 单注限额 +int BetThread::get_limit_amount(QString gtype, QString wtype) +{ + int amount = 0; + if (gtype == "FT") + { + amount = m_account_set_ft[get_market_by_wtype(wtype)]; + } + if (gtype == "BK") + { + amount = m_account_set_bk[get_market_by_wtype(wtype)]; + } + + return amount; +} + + + + + +// 处理失败订单 +void BetThread::handleFailedOrder(QMap& order) +{ + + //emit log("跟单失败", "失败原因:" + order["reason"]); + //emit log("跟单失败", "补单次数:" + order["rebet_times"]); + + // 播放失败声音 + if (g_config->followOrderFailedSoundEnable()) { + QString path = !g_config->followOrderFailedSoundPath().isEmpty() ? + g_config->followOrderFailedSoundPath() : ":/sound/sound/failed.wav"; + QSound::play(path); + } + + // 更新补单次数 + QMap updatedOrder = order; + //qDebug() << "原始跟单失败次数:" << updatedOrder["REBET_TIMES"]; + if (updatedOrder["REBET_TIMES"].isEmpty()) { + updatedOrder["REBET_TIMES"] = "0"; + } + else { + updatedOrder["REBET_TIMES"] = QString::number(updatedOrder["REBET_TIMES"].toInt() + 1); + } + + //qDebug() << "跟单失败次数:" << updatedOrder["REBET_TIMES"]; + // 添加到失败订单或补单记录 + if (updatedOrder["REBET_TIMES"] == "0") { + + if (!g_config->is_order_in_failed(updatedOrder["TID"])) { + push_bet_failed(order); + updatedOrder["DATETIME"] = QDateTime::currentDateTime().addSecs(-43200).toString("yyyy-MM-dd HH:mm:ss"); + g_config->add_failed_orders(updatedOrder); + emit signal_view_add_failed_order(updatedOrder); + } + } + else { + //qDebug() << "这是补单"; + QMap rebetRecord = updatedOrder; + rebetRecord["TID"] = updatedOrder["TID"] + "(" + updatedOrder["REBET_TIMES"] + ")"; + if (!g_config->is_order_in_rebet(rebetRecord["TID"])) { + + // 补单记录 暂时使用补单原因 + rebetRecord["DATETIME"] = QDateTime::currentDateTime().addSecs(-43200).toString("yyyy-MM-dd HH:mm:ss"); + rebetRecord["REASON"] = rebetRecord["REBET_REASON"]; + g_config->add_rebet_order(rebetRecord); + emit signal_view_add_rebet_order(rebetRecord); + } + + // 修改失败原因 + emit signal_view_alert_failed_order(updatedOrder); + g_config->alert_failed_order(updatedOrder); + } + + // 获取失败延迟时间 + int failedDelay = g_config->getRandomDelay(order["rtypeName"], "failed"); + //emit log("延迟", QString("跟单失败,延迟 %1 毫秒").arg(failedDelay)); + + // 失败延迟 + QEventLoop failedLoop; + QTimer::singleShot(failedDelay, &failedLoop, SLOT(quit())); + failedLoop.exec(); +} + + + +// 处理无效订单 +void BetThread::handleInvalidOrder(QMap& order) +{ + push_screen(order); + // 播放筛选订单声音 + if (g_config->screenOrderSoundEnable()) { + QString path = !g_config->screenOrderSoundPath().isEmpty() ? + g_config->screenOrderSoundPath() : ":/sound/sound/screen.wav"; + QSound::play(path); + } + + // 移除失败订单 + if (g_config->is_order_in_failed(order["TID"])) { + g_config->remove_failed_order(order["TID"]); + emit signal_view_remove_failed_order(order); + } + + // 添加到筛选订单 + if (!g_config->is_order_in_screen(order["TID"])) { + g_config->add_screen_order(order); + emit signal_view_add_screen_order(order); + } +} + + +// 处理普通订单 +void BetThread::handleNormalOrder(QMap& order) +{ + // 获取下单前延迟时间 + int beforeDelay = g_config->getRandomDelay(order["rtypeName"], "before"); + //emit log("延迟", QString("下单前,延迟 %1 毫秒").arg(beforeDelay)); + + // 下单前延迟 + QEventLoop beforeLoop; + QTimer::singleShot(beforeDelay, &beforeLoop, SLOT(quit())); + beforeLoop.exec(); + + bool rebet = false; + if (bet(order, rebet)) { + handleSuccessOrder(order); + } + // 下单失败 + else { + handleFailedOrder(order); + } +} + +// 处理成功订单 +void BetThread::handleSuccessOrder(QMap& order) +{ + + // 播放成功声音 + if (g_config->followOrderSuccessSoundEnable()) { + QString path = !g_config->followOrderSuccessSoundPath().isEmpty() ? + g_config->followOrderSuccessSoundPath() : ":/sound/sound/success.wav"; + QSound::play(path); + } + order["DATETIME"] = QDateTime::currentDateTime().addSecs(-43200).toString("yyyy-MM-dd HH:mm:ss"); + push_bet_success(order); + emit signal_bet_oder(order); + + // 获取成功延迟时间 + int successDelay = g_config->getRandomDelay(order["rtypeName"], "success"); + //emit log("延迟", QString("跟单成功,延迟 %1 毫秒").arg(successDelay)); + + // 成功延迟 + QEventLoop successLoop; + QTimer::singleShot(successDelay, &successLoop, SLOT(quit())); + successLoop.exec(); + + // 移除失败记录 + QList removeList; + removeList.append(order["TID"]); + g_config->remove_failed_orders(removeList); + emit signal_view_remove_failed_order(order); + + // 补单成功则添加补单记录 + if (!order["REBET_TIMES"].isEmpty()) { + QMap rebetRecord = order; + rebetRecord["TID"] = order["TID"] + "(" + order["REBET_TIMES"] + ")"; + if (!g_config->is_order_in_rebet(rebetRecord["TID"])) { + // 补单记录 暂时使用补单原因 + rebetRecord["REASON"] = rebetRecord["REBET_REASON"]; + g_config->add_rebet_order(rebetRecord); + emit signal_view_add_rebet_order(rebetRecord); + } + } + // 添加成功记录 + if (!g_config->is_order_in_success(order["TID"])) { + g_config->add_success_order(order); + emit signal_view_add_success_order(order); + } +} + + +bool BetThread::bet(QMap& order, bool & rebet) +{ + //bool order_view = get_order_view(order); + //if (!order_view) + //{ + // return false; + //} + + + //qDebug() << "开始检测注单盘口"; + + + //qDebug() << "过滤赔率结束1"; + rebet = true; + // 等待下单结果 + bool bet_result = ack_bet(order); + if (!bet_result) + { + return false; + } + return true; +} + + +// 完全按JS逻辑的分类函数 +inline bool isR(QString wtype) { + wtype = wtype.trimmed().toUpper(); + QStringList rTypes = { + "PRE","HPRE","PARE","PBRE","PCRE","PDRE","PERE","PFRE", + "R","HR","RE","HRE","PR","HPR","ARE","BRE","CRE","DRE","ERE","FRE", + "AR","BR","CR","DR","ER","FR","PAR","PBR","PCR","PDR","PER","PFR", + "BAR","CAR","DAR","EAR","FAR","W3" + }; + return rTypes.contains(wtype); +} + +inline bool isOU(QString wtype) { + wtype = wtype.trimmed().toUpper(); + QStringList ouTypes = { + "ROU","HROU","AROU","BROU","CROU","DROU","EROU","FROU", + "ROUH","ROUC","HRUH","HRUC","OU","HOU","AOU","BOU","COU","DOU","EOU","FOU", + "PAOU","PBOU","PCOU","PDOU","PEOU","PFOU","OUH","OUC","HOUH","HOUC", + "POU","HPOU","HPOUH","HPOUC","POUH","POUC","TARU","TBRU","TDRU","TERU" + }; + return ouTypes.contains(wtype); +} + +inline bool isEO(QString wtype) { + wtype = wtype.trimmed().toUpper(); + QStringList eoTypes = { + "EO","HEO","EOH","EOC","HEOH","HEOC","REO","HREO", + "REOH","REOC","HREOH","HREOC","PEO","HPEO" + }; + return eoTypes.contains(wtype); +} + +inline bool isWM(QString wtype) { + wtype = wtype.trimmed().toUpper(); + QStringList wmTypes = { "WM","RWM","HWM","HRWM" }; + return wmTypes.contains(wtype); +} + +// 独赢判断(M/RM + 对应的rtype) +inline bool isW3(QString wtype, QString rtype) { + wtype = wtype.trimmed().toUpper(); + rtype = rtype.trimmed().toUpper(); + + // 直接是M/RM + if (wtype == "M" || wtype == "RM") return true; + + // 通过rtype判断 + QStringList w3Rtypes = { + "MH","MC","MN","RMH","RMC","RMN","HMH","HMC","HMN","HRMH","HRMC","HRMN" + }; + return w3Rtypes.contains(rtype); +} + + + + +bool BetThread::get_order_view(QMap & order) +{ + // XXX_0 去除后缀 + order["wtype"] = Utils::instance().convertToBase(order["wtype"]); + // 临时测试 跟单盘口 + //order["odd_f_type"] = "H"; + //qDebug() << "跟单盘口:" << order["odd_f_type"]; + QNetworkAccessManager networkManager; + QNetworkRequest request; + request.setUrl(QUrl(m_url + "transform.php?ver=" + m_ver)); + request.setRawHeader("Accept", "*/*"); + request.setRawHeader("Cookie", m_cookies.toUtf8()); + request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); + if (g_config->followDeviceType() == 0) + { + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + } + else + { + request.setRawHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/109.0.0.0"); + } + request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); + request.setRawHeader("Origin", m_url.toUtf8()); + request.setRawHeader("Referer", m_url.toUtf8()); + + // 获取当前时间戳(皇冠时间) + QString timeStamp = QString::number(QDateTime::currentDateTime().addSecs(-43200).toTime_t()); + + // 下单队伍似乎反了 + QString p; + if (order["GT"] == "足球") + { + p = "FT_order_view"; + } + else + { + p = "Other_order_view"; + } + QString data = "p=" + p + "&" + m_param + "&odd_f_type=" + order["odd_f_type"] + "&gid=" + order["BET_GID"] + ">ype=" + Utils::gtype_map(order["GT"]) + "&wtype=" + Utils::instance().reverse_map_wtype(order["wtype"]) + "&chose_team=" + Utils::instance().get_chose_team(Utils::instance().reverse_map_rtype(order["rtype"]));// +order["team_bet"]; + + // qDebug() << "获取游戏信息(get_order_view) -> 请求地址:" << QUrl(QString(m_url + "transform.php?ver=" + m_ver)); + // qDebug() << "获取游戏信息(get_order_view) -> 请求参数:" << data; + QNetworkReply* reply = networkManager.post(request, data.toUtf8()); + // 忽略SSL证书错误 + reply->ignoreSslErrors(); + // 事件循环 + QEventLoop eventLoop; + // 连接信号和槽 + connect(&networkManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit())); + // 开始循环 + eventLoop.exec(); + + // 错误处理 + if (reply->error() != QNetworkReply::NoError) + { + QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); + qDebug("服务器响应错误代码: %d Qt错误代码:%d\n", statusCode.toInt(), (int)reply->error()); + qDebug(qPrintable(reply->errorString())); + reply->deleteLater(); + // 下单失败 -> 网络异常 + order["REASON"] = "网络异常"; + //emit log("离线调试", "get_order_view网络异常"); + return false; + } + + // xml转map + QByteArray result = reply->readAll(); + reply->deleteLater(); + QXmlStreamReader reader(result); + QMap game; + while (!reader.atEnd()) + { + reader.readNext(); + if (reader.name() != "serverresponse") + { + QString name = reader.name().toString(); + game[name] = reader.readElementText(); + } + } + qDebug() << "获取游戏信息(get_order_view) -> 返回信息:" << game; + //emit log("离线调试", QString("get_order_view code: %1").arg(game["code"])); + if (game["code"] == "error") + { + + emit log("账户状态", "账户掉线"); + emit account_disconnect(); + order["REASON"] = "账户掉线"; + qDebug() << "获取游戏信息(get_order_view) -> 返回信息:" << game; + return false; + } + if (game["code"] != "501") + { + // 失败 + order["REASON"] = Utils::instance().error(game["errormsg"]); + qDebug() << "获取游戏信息(get_order_view) -> 返回信息:" << game; + return false; + } + + //qDebug() << "[OrderView]" << game; + order["ts"] = game["ts"]; + + + // + order["con"] = game["con"];// 盘口线 通常与ratio相同 + auto toIntOk = [](const QVariant &v, bool &ok)->int { + ok = false; + QString s = v.toString().trimmed(); + if (s.isEmpty()) return 0; + bool localOk = false; + int n = s.toInt(&localOk); + ok = localOk; + return n; + }; + + // 小写优先,兼容大写 + QString hStr = game.contains("score_h") ? game.value("score_h").trimmed() + : game.contains("SCORE_H") ? game.value("SCORE_H").trimmed() + : QString(); + QString cStr = game.contains("score_c") ? game.value("score_c").trimmed() + : game.contains("SCORE_C") ? game.value("SCORE_C").trimmed() + : QString(); + + bool okH = false, okC = false; + int h = toIntOk(hStr, okH); + int c = toIntOk(cStr, okC); + + if (okH && okC) { + // 对齐JS格式:(h - c) + order["SCORE_NEW"] = QString("%1:%2").arg(h).arg(c); + } + else { + // 兜底用已有 score 字段(可能为空) + order["SCORE_NEW"] = game.contains("score") ? game.value("score").trimmed() : QString(); + } + + // ----- 按 JS transRatioStr 路径计算 spread(不保留 +1960 等后缀)----- + //auto upper = [](QString s) { return s.toUpper(); }; + + + + // 简化盘口处理逻辑 + //if (order["handicap"] != "") + //{ + + //} + + auto upper = [](QString s) { return s.trimmed().toUpper(); }; + QString chose = Utils::instance().get_chose_team(Utils::instance().reverse_map_rtype(order["rtype"])); + chose = upper(chose); + if (chose == "N") chose = "H"; + + // strong:H/C + QString strong = upper(game["strong"]); + + // wtype / keepwtype(若你有 keepwtype 则替换成它;没有就用 wtype) + QString wtype = upper(order["wtype"]); + QString keepwtype = order.contains("keepwtype") ? upper(order["keepwtype"]) : wtype; + + // 拿到原始 spread,并做“JS 样式”的规范化:去掉诸如 "+1960" 的后缀、不保留前导 ±(仅用于数值展示) + QString spreadSrc = game["spread"].trimmed(); + auto normalizeSpread = [](const QString& s0)->QString { + QString s = s0.trimmed(); + int delim = s.indexOf('+', 1); // 跳过可能的首字符 + if (delim > 0) s = s.left(delim); + if (!s.isEmpty() && (s.front() == '+' || s.front() == '-')) { + QString t = s; t.remove(0, 1); return t.trimmed(); + } + return s.trimmed(); + }; + QString ratioStr = normalizeSpread(spreadSrc); + + // 与 JS 等价的“是否需要加 ±”判断: + // JS 会对字符串做 Number(...) 再与 0 比较;如果无法转为数(如 "0 / 0.5"),得到 NaN,NaN != 0 为 true,应该“加符号”。 + const bool jsNeedsSign = [&](const QString& s) -> bool { + QString t = s.trimmed(); + if (t.isEmpty()) return false; // 空串不加符号 + bool ok = false; + t.toDouble(&ok); + if (!ok) return true; // NaN(如 "0 / 0.5")按需加符号 + return (t.toDouble() != 0.0); // 非 0 加符号;0 不加 + }(ratioStr); + + // 分支完全对齐 JS: + if (isOU(keepwtype)) { + // 大小类:不加 ±,直接显示数值 + order["ORDER_CON_NEW"] = ratioStr; + } + else if (!isR(keepwtype)) { + // 其它(单双/特殊玩法等):不显示盘口 + order["ORDER_CON_NEW"] = ""; + } + else { + // 让球 R 系 + if (isW3(wtype, order["rtype"])) { + // W3 特例:始终仅按 strong/chose 决定 ±,值用原始(规范化后的)ratioStr + QString sign = (strong == chose ? "-" : "+"); + order["ORDER_CON_NEW"] = ratioStr.isEmpty() ? "" : (sign + ratioStr); + } + else { + // 普通 R:ratioR != 0(或 NaN)才加 ±,与 JS 完全一致 + if (jsNeedsSign) { + QString sign = (strong == chose ? "-" : "+"); + order["ORDER_CON_NEW"] = ratioStr.isEmpty() ? "" : (sign + ratioStr); + } + else { + // 平手盘:显示数值不带 ±("0" 或 "0 / 0") + order["ORDER_CON_NEW"] = ratioStr; + } + } + } + // ----- end ----- + + order["ratio"] = game["ratio"]; + order["ioratio"] = game["ioratio"]; + order["IORATIO_NEW"] = game["ioratio"];// 赔率 + + + // 限额 + order["gold_gmin"] = game["gold_gmin"]; + order["gold_gmax"] = game["gold_gmax"]; + return true; +} + + + +/// +/// 槽函数 - 下单 +/// +/// 注单信息 +/// 下单结果 +bool BetThread::ack_bet(QMap& order) +{ + // + //qDebug() << "槽函数 -> 下单(slotBet) -> 注单信息: " << order; + // 网络请求 + QNetworkAccessManager networkManager; + QNetworkRequest request; + request.setUrl(QUrl(QString(m_url + "transform.php?ver=" + m_ver))); + request.setRawHeader("Accept", "*/*"); + request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); + if (g_config->followDeviceType() == 0) + { + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + } + else + { + request.setRawHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/109.0.0.0"); + } + + request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); + request.setRawHeader("Origin", m_url.toUtf8()); + request.setRawHeader("Referer", m_url.toUtf8()); + + // 获取当前时间戳 + QString timeStamp = QString::number(QDateTime::currentDateTime().addSecs(-43200).toMSecsSinceEpoch()); + + // 请求类型 + QString p; + if (order["GT"] == "足球") + { + p = "FT_bet"; + } + else + { + p = "Other_bet"; + } + + + QString data = "p=" + p + "&" + m_param + "&odd_f_type=" + order["odd_f_type"] + "&golds=" + order["GOLD"] + "&gid=" + order["BET_GID"] + ">ype=" + Utils::gtype_map(order["GT"]) + "&wtype=" + Utils::instance().reverse_map_wtype(order["wtype"]) + "&rtype=" + Utils::instance().reverse_map_rtype(order["rtype"]) + "&chose_team=" + Utils::instance().get_chose_team(Utils::instance().reverse_map_rtype(order["rtype"])) + "&ioratio=" + order["ioratio"] + "&con=" + order["con"] + "&ratio=" + order["ratio"] + "&autoOdd=Y×tamp=" + timeStamp + "×tamp2=" + order["ts"] + "&isRB=N&imp=N&ptype=" + order["ptype"] + "&isYesterday=N&f=1R"; + + + //qDebug() << "槽函数 -> 下单(slotBet) -> 请求地址: " << QUrl(m_url + "transform.php?ver=" + m_ver); + + //qDebug() << "槽函数 -> 下单(slotBet) -> 请求参数: " << data; + QNetworkReply* reply = networkManager.post(request, data.toUtf8()); + // 忽略SSL证书错误 + reply->ignoreSslErrors(); + // 事件循环 + QEventLoop eventLoop; + // 连接信号和槽 + connect(&networkManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit())); + // 开始循环 + eventLoop.exec(); + + // 错误处理 + if (reply->error() != QNetworkReply::NoError) + { + QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); + qDebug("服务器响应错误代码: %d Qt错误代码:%d\n", statusCode.toInt(), (int)reply->error()); + qDebug(qPrintable(reply->errorString())); + reply->deleteLater(); + // 错误原因 + order["REASON"] = "网络异常"; + //emit log("离线调试", "ack_bet网络异常"); + return false; + } + QByteArray result = reply->readAll(); + reply->deleteLater(); + QXmlStreamReader reader(result); + QMap game; + while (!reader.atEnd()) + { + reader.readNext(); + + + if (reader.name() != "serverresponse") + { + QString name = reader.name().toString(); + game[name] = reader.readElementText(); + } + + } + qDebug() << "槽函数 -> 下单 -> 返回数据: " << game; + //emit log("离线调试", QString("ack_bet code: %1").arg(game["code"])); + if (game["code"] == "error") + { + emit log("账户状态", "账户掉线"); + //emit log("调试日志", "ack_bet 账户掉线"); + emit account_disconnect(); + order["REASON"] = "账户掉线"; + return false; + } + if (game["code"] == "560") + { + + if (game["delaysec"].toInt() > 0 || game["dg"] == "Y" || game["dg_mode"] == "Y") + { + // 等待 + //this->waitForResult(order); + bool wait_result = wait_bet_result(order); + return wait_result; + } + else + { + + // 成功 + //emit log("内部调试", "跟单成功:" + result); + order["ticket_id"] = game["ticket_id"]; + return true; + } + } + else + { + //// 跟单失败延时 + //QEventLoop failed_loop; + //QTimer::singleShot(g_config->betFailedSleep(), &failed_loop, SLOT(quit())); + //failed_loop.exec(); // 进入循环,等待5000毫秒后退出 + //// 失败 + order["REASON"] = Utils::instance().error(game["errormsg"]); + return false; + } + + return true; +} + +bool BetThread::wait_bet_result(QMap& order) +{ + + QNetworkAccessManager networkManager; + QNetworkRequest request; + request.setUrl(QUrl(m_url + "transform.php?ver=" + m_ver)); + request.setRawHeader("Accept", "*/*"); + request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); + if (g_config->followDeviceType() == 0) + { + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + } + else + { + request.setRawHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/109.0.0.0"); + } + request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); + request.setRawHeader("Origin", m_url.toUtf8()); + request.setRawHeader("Referer", m_url.toUtf8()); + + // 获取当前时间戳 + QString timeStamp = QString::number(QDateTime::currentDateTime().addSecs(-43200).toMSecsSinceEpoch()); + + QString p; + if (order["GT"] == "足球") + { + p = "get_dangerous"; + } + else + { + // 下单保持 + p = "get_bethold"; + } + QString data = "p=" + p + "&" + m_param + "&type=xml&from=bet&tid=&uni_key=" + timeStamp; + + qDebug() << "网络请求 -> 等待下单结果(wait_bet_result) -> 请求地址:" << QUrl(QString(m_url + "transform.php?ver=" + m_ver)); + qDebug() << "网络请求 -> 等待下单结果(wait_bet_result) -> 请求参数:" << data; + QNetworkReply* reply = networkManager.post(request, data.toUtf8()); + // 忽略SSL证书错误 + reply->ignoreSslErrors(); + // 事件循环 + QEventLoop eventLoop; + // 连接信号和槽 + connect(&networkManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit())); + // 开始循环 + eventLoop.exec(); + + // 错误处理 + if (reply->error() != QNetworkReply::NoError) + { + QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); + qDebug("服务器响应错误代码: %d Qt错误代码:%d\n", statusCode.toInt(), (int)reply->error()); + qDebug(qPrintable(reply->errorString())); + reply->deleteLater(); + order["reason"] = "网络异常"; + //emit log("离线调试", "wait_bet_result网络异常"); + return false; + } + + // xml转map + QByteArray result = reply->readAll(); + reply->deleteLater(); + QXmlStreamReader reader(result); + QMap game; + while (!reader.atEnd()) + { + reader.readNext(); + if (reader.name() != "serverresponse") + { + QString name = reader.name().toString(); + game[name] = reader.readElementText(); + } + } + if (game["code"] == "error" || game["status_N"] == "error") + { + order["REASON"] = "账户掉线"; + emit log("账户状态", "账户掉线"); + emit log("调试日志", "ack_bet 账户掉线"); + emit account_disconnect(); + return false; + } + qDebug() << "网络请求 -> 获取游戏信息(wait_bet_result) -> 返回信息:" << game; + //emit log("离线调试", QString("status_N status: %1").arg(game["code"])); + // 继续等待 + if (game["status_N"] == "N") + { + QEventLoop failed_loop; + QTimer::singleShot(3000, &failed_loop, SLOT(quit())); + failed_loop.exec(); // 进入循环,等待5000毫秒后退出 + + return wait_bet_result(order); + } + + // 下单成功 + if (game["status_A"] == "A") + { + order["ticket_id"] = game["ticket_id"]; + // emit signalBetSuccess(order); + return true; + } + + // 跟单失败 + if (game["status_V"] == "V") + { + return false; + //// 跟单失败延时 + //QEventLoop failed_loop; + //QTimer::singleShot(g_config->betFailedSleep(), &failed_loop, SLOT(quit())); + //failed_loop.exec(); // 进入循环,等待5000毫秒后退出 + //// 失败 + //order["reason"] = Utils::instance().error(game["errormsg"]); + ////emit signalBetFailed(order); + //g_config->add_failed_orders(order); + //view_add_failed_order(order); + //// 补单 + //if (!order["rebetTimes"].isEmpty()) + //{ + // order["rebetTimes"] = "0"; + //} + + // 重新开始下单 + //emit signalOrderView(order); + // 加入补单列表 + // emit signalRebet(order); + //view_add_rebet_order(order); + // 被拒绝 + // 您的注单已被拒收。 + //emit signalBetFailed(order); + } + //if (game["status_7"] == "7") + //{ + + //} + //if (game["status_8"] == "8") + //{ + + //} + //if (game["status_R"] == "R") + //{ + + //} + + return true; +} + + +bool BetThread::get_game_list(QMap & order) +{ + QNetworkAccessManager networkManager; + QNetworkRequest request; + + // 请求头 + request.setUrl(QUrl(QString(m_url + "transform.php?ver=" + m_ver))); + request.setRawHeader("Accept", "*/*"); + request.setRawHeader("Cookie", m_cookies.toUtf8()); + request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); + request.setRawHeader("X-Requested-With", "XMLHttpRequest"); + if (g_config->followDeviceType() == 0) + { + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + } + else + { + request.setRawHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/109.0.0.0"); + } + request.setHeader(QNetworkRequest::ContentTypeHeader, QByteArray("application/x-www-form-urlencoded")); + request.setRawHeader("Origin", m_url.toUtf8()); + request.setRawHeader("Referer", m_url.toUtf8()); + request.setRawHeader("Host", QUrl(m_url).host().toUtf8()); + + // 皇冠时间戳 + QString ts = QString::number(QDateTime::currentDateTime().addSecs(-43200).toMSecsSinceEpoch()); + int randomMs = QRandomGenerator::global()->bounded(1000, 50001); // 生成1000-50000的随机数 + QString chgSortTS = QString::number(ts.toLongLong() + randomMs); + // 参数映射 + QString gtype = Utils::gtype_map(order.value("GT")).toLower(); + QString showtype = Utils::showtype_map(order.value("SESSION")); // live/today/early + QString rtype = (showtype == "live") ? "rb" : "r"; + QString filter = (showtype == "today" || showtype == "early") + ? Utils::gtype_map(order.value("GT")).toUpper() + : ""; + + if (showtype == "today") + { + if (order.value("GT") == "足球") + { + filter = "FT"; + } + else if (order.value("GT").contains("篮球")) + { + filter = "MIX"; // 今日 + } + } + if (showtype == "early") + { + filter = "FU"; + } + + + QString data = QString("%1&p=get_game_list&p3type=&date=all>ype=%2&showtype=%3&rtype=%4<ype=4&filter=%5&cupFantasy=N&sorttype=L&specialClick=&isFantasy=N&ts=%6&chgSortTS=%7") + .arg(m_param).arg(gtype).arg(showtype).arg(rtype).arg(filter).arg(ts).arg(chgSortTS); + + + request.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(data.toUtf8().size())); + + + + QNetworkReply* reply = networkManager.post(request, data.toUtf8()); + reply->ignoreSslErrors(); + QEventLoop eventLoop; + connect(&networkManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit())); + eventLoop.exec(); + + if (reply->error() != QNetworkReply::NoError) + { + QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); + qDebug() << "查找赛事请求地址:" << QUrl(m_url + "transform.php?ver=" + m_ver); + qDebug() << "查找赛事请求参数:" << data; + qDebug("服务器响应错误代码: %d Qt错误代码:%d\n", statusCode.toInt(), (int)reply->error()); + qDebug(qPrintable(reply->errorString())); + reply->deleteLater(); + order["REASON"] = "网络异常"; + return false; + } + QByteArray result = reply->readAll(); + reply->deleteLater(); + + + if (result.contains("error") || result.contains("doubleLogin") || result.contains("")) + { + qDebug() << "查找赛事请求地址:" << QUrl(m_url + "transform.php?ver=" + m_ver); + qDebug() << "查找赛事请求参数:" << data; + qDebug() << "原始返回:" << result.data(); + qDebug() << "请求失败: 账户掉线"; + order["REASON"] = "账户掉线"; + emit log("账户状态", "账户掉线"); + emit account_disconnect(); + return false; + } + + // 调试输出返回数据 + // qDebug() << "服务器返回数据长度:" << result.size(); + // qDebug() << "返回数据前200字符:" << result.left(200).data(); + + // 尝试解析JSON格式 + QJsonParseError jsonError; + QJsonDocument jsonDoc = QJsonDocument::fromJson(result, &jsonError); + + if (jsonError.error == QJsonParseError::NoError) + { + // JSON解析成功 + //qDebug() << "[get_game_list]成功解析为JSON格式"; + + QJsonObject rootObj = jsonDoc.object(); + + // 检查状态 + QString status = rootObj["status"].toString(); + if (status != "success") + { + qDebug() << "服务器返回错误状态:" << status; + order["REASON"] = "服务器返回错误状态"; + return false; + } + + // 获取response对象 + QJsonObject responseObj = rootObj["response"].toObject(); + + // 从phpData中获取总数据计数 + //QJsonObject phpDataObj = rootObj["phpData"].toObject(); + //int totalDataCount = phpDataObj["TOTALDATACOUNT"].toInt(); + //qDebug() << "总比赛数量:" << totalDataCount; + + // 解析比赛数据 + QList> games; + + // 遍历response中的所有GAME_X节点 + for (const QString& key : responseObj.keys()) + { + if (key.startsWith("GAME_")) + { + QJsonObject gameObj = responseObj[key].toObject(); + QMap gameMap; + + // 提取基本游戏信息 + gameMap["GID"] = gameObj["GID"].toString(); + gameMap["GIDM"] = gameObj["GIDM"].toString(); + gameMap["TEAM_H"] = gameObj["TEAM_H"].toString(); + gameMap["TEAM_C"] = gameObj["TEAM_C"].toString(); + gameMap["GNUM_H"] = gameObj["GNUM_H"].toString(); + gameMap["GNUM_C"] = gameObj["GNUM_C"].toString(); + gameMap["LID"] = gameObj["LID"].toString(); + gameMap["MT_ID"] = gameObj["MT_ID"].toString(); // JSON中的MT_ID相当于XML的ECID + gameMap["LEAGUE"] = gameObj["LEAGUE"].toString(); + gameMap["RUNNING"] = gameObj["RUNNING"].toString(); + gameMap["NOWSESSION"] = gameObj["NOWSESSION"].toString(); + gameMap["SCORE_H"] = gameObj["SCORE_H"].toString(); + gameMap["SCORE_C"] = gameObj["SCORE_C"].toString(); + + // 从original_json中提取额外的信息 + QJsonObject originalObj = rootObj["original_json"].toObject(); + QJsonObject originalResponse = originalObj["response"].toObject(); + if (originalResponse.contains(key)) + { + QJsonObject originalGameObj = originalResponse[key].toObject(); + if (!originalGameObj.isEmpty()) + { + // 添加原始数据中的字段 + gameMap["HGID"] = originalGameObj.value("HGID").toString(); + } + } + + // 如果没有HGID,使用GID + if (!gameMap.contains("HGID") || gameMap["HGID"].isEmpty()) + { + gameMap["HGID"] = gameMap["GID"]; + } + + //qDebug() << "解析到比赛:" << gameMap["TEAM_H"] << "vs" << gameMap["TEAM_C"] + // << "GID:" << gameMap["GID"] << "MT_ID:" << gameMap["MT_ID"]; + + games.append(gameMap); + } + } + + // 匹配比赛 + QString wantH = Utils::traditionalToSimplified(order.value("TEAM_H")); + QString wantC = Utils::traditionalToSimplified(order.value("TEAM_C")); + + QString wantNumH = order.value("NUM_H"); + QString wantNumC = order.value("NUM_C"); + + //qDebug() << "想要匹配的主队:" << wantH << "(" << wantNumH << ")"; + //qDebug() << "想要匹配的客队:" << wantC << "(" << wantNumC << ")"; + + QMap matchedGame; + bool gameFound = false; + + for (const auto& g : games) + { + QString gid = g.value("GID"); + if (gid.isEmpty()) continue; + + QString team_h = g.value("TEAM_H"); + QString team_c = g.value("TEAM_C"); + QString gnum_h = g.value("GNUM_H"); + QString gnum_c = g.value("GNUM_C"); + + //qDebug() << "检查比赛:" << team_h << "vs" << team_c + // << "编号:" << gnum_h << "-" << gnum_c; + + // 先尝试编号匹配 + if (!wantNumH.isEmpty() && !wantNumC.isEmpty() && + !gnum_h.isEmpty() && !gnum_c.isEmpty() && + wantNumH == gnum_h && wantNumC == gnum_c) { + matchedGame = g; gameFound = true; order["GID"] = gid; + //qDebug() << "编号匹配成功,GID:" << gid; + break; + } + + // 再尝试队名匹配 + if (!wantH.isEmpty() && !wantC.isEmpty() && + !team_h.isEmpty() && !team_c.isEmpty()) + { + // 标准化队名比较 + QString simpleTeamH = Utils::traditionalToSimplified(team_h); + QString simpleTeamC = Utils::traditionalToSimplified(team_c); + + if ((simpleTeamH == wantH && simpleTeamC == wantC) || + (team_h == wantH && team_c == wantC)) + { + matchedGame = g; gameFound = true; order["GID"] = gid; + //qDebug() << "队名匹配成功,GID:" << gid; + break; + } + } + } + + if (!gameFound) + { + qDebug() << "查找赛事请求地址:" << QUrl(m_url + "transform.php?ver=" + m_ver); + qDebug() << "查找赛事请求参数:" << data; + qDebug() << "解析到的比赛数量:" << games.size(); + for (const auto& g : games) + { + qDebug() << " - " << g.value("TEAM_H") << "vs" << g.value("TEAM_C") + << "编号:" << g.value("GNUM_H") << "-" << g.value("GNUM_C"); + } + qDebug() << "未找到匹配的比赛"; + order["REASON"] = "未匹配到比赛"; + return false; + } + + // 写入 ECID / LID + QString ecid = matchedGame.value("MT_ID"); // JSON中使用MT_ID作为ECID + QString lid = matchedGame.value("LID"); + QString hgid = matchedGame.value("HGID"); + QString league = matchedGame.value("LEAGUE"); + + // 如果ECID为空,使用GIDM + if (ecid.isEmpty()) + { + ecid = matchedGame.value("GIDM"); + } + + order["ECID"] = ecid; + order["LID"] = lid; + order["HGID"] = hgid; + if (!league.isEmpty()) order["LEAGUE"] = league; + + //qDebug() << "设置ECID:" << order["ECID"] << " LID:" << order["LID"] + // << " HGID:" << order["HGID"] << " 联赛:" << order["LEAGUE"]; + + if (order["WAGERS_TYPE"].contains("半场")) + { + order["BET_GID"] = hgid; + // qDebug() << "半场投注,使用BET_GID:" << hgid; + } + else + { + order["BET_GID"] = order["GID"]; + // qDebug() << "全场投注,使用BET_GID:" << order["GID"]; + } + + // 打印匹配到的比赛详情 + //qDebug() << "成功匹配到比赛:"; + //qDebug() << " 主队:" << matchedGame.value("TEAM_H"); + //qDebug() << " 客队:" << matchedGame.value("TEAM_C"); + //qDebug() << " 比分:" << matchedGame.value("SCORE_H") << ":" << matchedGame.value("SCORE_C"); + //qDebug() << " 状态:" << matchedGame.value("RUNNING"); + //qDebug() << " 当前节:" << matchedGame.value("NOWSESSION"); + + return true; + } + else + { + // JSON解析失败,尝试解析为XML(旧格式) + // qDebug() << "JSON解析失败:" << jsonError.errorString() << ",尝试解析为XML"; + + // 原有的XML解析逻辑 + auto parseGames = [&](const QByteArray& xml)->QList> { + QList> list; + QXmlStreamReader xr(xml); + QMap cur; + bool inGame = false; + while (!xr.atEnd()) + { + xr.readNext(); + if (xr.isStartElement()) + { + QString tag = xr.name().toString(); + QString tagUpper = tag.toUpper(); + if (tagUpper == "GAME" || tagUpper == "DATA" || tagUpper == "MATCH" || tagUpper == "ROW" || tagUpper == "ITEM" || tagUpper == "G") + { + inGame = true; + cur.clear(); + } + else if (inGame) + { + QString text = xr.readElementText(QXmlStreamReader::IncludeChildElements).trimmed(); + if (!text.isEmpty()) { cur[tag] = text; cur[tagUpper] = text; } + } + } + else if (xr.isEndElement()) + { + QString tagUpper = xr.name().toString().toUpper(); + if (inGame && (tagUpper == "GAME" || tagUpper == "DATA" || tagUpper == "MATCH" || tagUpper == "ROW" || tagUpper == "ITEM" || tagUpper == "G")) + { + inGame = false; + if (!cur.isEmpty()) list.append(cur); + cur.clear(); + } + } + } + return list; + }; + + QList> games = parseGames(result); + // qDebug() << "XML解析到比赛数量:" << games.size(); + + // 错误码 + QString code, errormsg; + for (const auto& it : games) + { + if (it.contains("CODE")) code = it.value("CODE"); + if (it.contains("ERRORMSG")) errormsg = it.value("ERRORMSG"); + } + if (code == "error") + { + qDebug() << "查找赛事请求地址:" << QUrl(m_url + "transform.php?ver=" + m_ver); + qDebug() << "查找赛事请求参数:" << data; + qDebug() << "原始XML返回:" << result.data(); + qDebug() << "服务器返回错误:" << errormsg; + order["REASON"] = "账户掉线"; + emit log("账户状态", "账户掉线"); + emit account_disconnect(); + return false; + } + + // 匹配比赛 + QString wantH = Utils::traditionalToSimplified(order.value("TEAM_H")); + QString wantC = Utils::traditionalToSimplified(order.value("TEAM_C")); + + QString wantNumH = order.value("NUM_H"); + QString wantNumC = order.value("NUM_C"); + + QMap matchedGame; + bool gameFound = false; + + for (const auto& g : games) + { + QString gid = g.value("GID"); if (gid.isEmpty()) gid = g.value("gid"); + if (gid.isEmpty()) continue; + + QString team_h = g.value("TEAM_H"); if (team_h.isEmpty()) team_h = g.value("team_h"); + QString team_c = g.value("TEAM_C"); if (team_c.isEmpty()) team_c = g.value("team_c"); + QString gnum_h = g.value("GNUM_H"); if (gnum_h.isEmpty()) gnum_h = g.value("gnum_h"); + QString gnum_c = g.value("GNUM_C"); if (gnum_c.isEmpty()) gnum_c = g.value("gnum_c"); + + if (!wantNumH.isEmpty() && !wantNumC.isEmpty() && + !gnum_h.isEmpty() && !gnum_c.isEmpty() && + wantNumH == gnum_h && wantNumC == gnum_c) { + matchedGame = g; gameFound = true; order["GID"] = gid; + qDebug() << "编号匹配成功,GID:" << gid; break; + } + if (!wantH.isEmpty() && !wantC.isEmpty() && + !team_h.isEmpty() && !team_c.isEmpty() && + team_h == wantH && team_c == wantC) { + matchedGame = g; gameFound = true; order["GID"] = gid; + qDebug() << "队名匹配成功,GID:" << gid; break; + } + } + + if (!gameFound) { + qDebug() << "查找赛事请求地址:" << QUrl(m_url + "transform.php?ver=" + m_ver); + qDebug() << "查找赛事请求参数:" << data; + qDebug() << "原始XML返回:" << result.data(); + qDebug() << "未找到匹配的比赛"; + order["REASON"] = "未匹配到比赛"; + return false; + } + + // 写入 ECID / LID(大小写兼容),顺便补充 HGID/LEAGUE + QString ecid = matchedGame.value("ECID"); if (ecid.isEmpty()) ecid = matchedGame.value("ecid"); + QString lid = matchedGame.value("LID"); if (lid.isEmpty()) lid = matchedGame.value("lid"); + QString hgid = matchedGame.value("HGID"); if (hgid.isEmpty()) hgid = matchedGame.value("hgid"); + QString league = matchedGame.value("LEAGUE"); if (league.isEmpty()) league = matchedGame.value("league"); + + if (ecid.isEmpty()) + { + ecid = matchedGame.value("GIDM"); + } + + order["ECID"] = ecid; + order["LID"] = lid; + if (!hgid.isEmpty()) order["HGID"] = hgid; + if (!league.isEmpty()) order["LEAGUE"] = league; + + qDebug() << "设置ECID:" << order["ECID"] << " LID:" << order["LID"] + << " HGID:" << order["HGID"] << " 联赛:" << order["LEAGUE"]; + + if (order["WAGERS_TYPE"].contains("半场")) + { + order["BET_GID"] = hgid; + } + else + { + order["BET_GID"] = order["GID"]; + } + + return true; + } +} + + + + + + + +QList> BetThread::get_game_more(QMap& order) +{ + QList> markets; + + // 清理上次残留 ptype + order.remove("ptype"); + + QNetworkAccessManager networkManager; + QNetworkRequest request; + request.setUrl(QUrl(QString(m_url + "transform.php?ver=" + m_ver))); + request.setRawHeader("Accept", "*/*"); + request.setRawHeader("Cookie", m_cookies.toUtf8()); + request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); + request.setRawHeader("X-Requested-With", "XMLHttpRequest"); + if (g_config->followDeviceType() == 0) + { + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + } + else + { + request.setRawHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/109.0.0.0"); + } + request.setHeader(QNetworkRequest::ContentTypeHeader, QByteArray("application/x-www-form-urlencoded")); + request.setRawHeader("Origin", m_url.toUtf8()); + request.setRawHeader("Referer", m_url.toUtf8()); + request.setRawHeader("Host", QUrl(m_url).host().toUtf8()); + + // 参数 + QString ts = QString::number(QDateTime::currentDateTime().addSecs(-43200).toMSecsSinceEpoch()); + QString gtype = Utils::gtype_map(order.value("GT")).toLower(); + QString showtype = Utils::showtype_map(order.value("SESSION")); // live/today/early + QString isRB = (showtype == "live") ? "Y" : "N"; + QString mode = "NORMAL"; // 请求参数 + QString filter = "All"; + QString ecid = order.value("ECID"); + QString lid = order.value("LID"); + + + QString data; + if (gtype == "ft") // 足球 + { + // 足球 + data = QString("%1&p=get_game_more>ype=%2&showtype=%3<ype=4&isRB=%4&%5specialClick=&mode=%6&from=game_more&filter=%7&ts=%8&ecid=%9") + .arg(m_param) + .arg(gtype) + .arg(showtype) + .arg(isRB) + .arg(lid.isEmpty() ? "" : QString("lid=%1&").arg(lid)) + .arg(mode) + .arg(filter) + .arg(ts) + .arg(ecid); + } + else + { + // 其他, 篮球 + data = QString("%1&p=get_game_more>ype=%2&showtype=%3<ype=4&isRB=%4&%5specialClick=&mode=%6&from=game_more&filter=%7&ts=%8&gid=%9&type=getMore") + .arg(m_param) + .arg(gtype) + .arg(showtype) + .arg(isRB) + .arg(lid.isEmpty() ? "" : QString("lid=%1&").arg(lid)) + .arg(mode) + .arg(filter) + .arg(ts) + .arg(order["GID"]); + } + + + request.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(data.toUtf8().size())); + // qDebug() << "更多玩法请求参数:" << data; + + QNetworkReply* reply = networkManager.post(request, data.toUtf8()); + reply->ignoreSslErrors(); + QEventLoop eventLoop; + connect(&networkManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit())); + eventLoop.exec(); + + if (reply->error() != QNetworkReply::NoError) + { + QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); + qDebug("更多玩法响应错误代码: %d Qt错误代码:%d\n", statusCode.toInt(), (int)reply->error()); + qDebug(qPrintable(reply->errorString())); + reply->deleteLater(); + order["REASON"] = "网络异常"; + qDebug() << "更多玩法XML返回:" << reply->readAll(); + return markets; + } + QByteArray result = reply->readAll(); + reply->deleteLater(); + + //qDebug() << "更多玩法返回:" << result.data(); + + + if (gtype == "ft") + { + // 足球使用xml解析 + // 工具 + auto nonZero = [](const QString& v)->bool { + if (v.isEmpty()) return false; + bool ok = false; double x = v.toDouble(&ok); + return ok ? (x > 0) : true; + }; + auto add = [&](const QString& model, const QString& ratio, const QString& ior, const QString& gid, const QString& hgid, const QString & strong)->void { + // 非盘口型可 ratio 为空,但赔率需有效 + if (ratio.isEmpty() && (ior.isEmpty() || !nonZero(ior))) return; + QMap c; + c["MODEL"] = model; + c["RATIO"] = ratio.trimmed(); + c["IORATIO"] = ior.trimmed(); + c["GID"] = gid; + c["HGID"] = hgid; + c["strong"] = strong; + if (order["STAGE"] == "全场") + { + c["BET_GID"] = gid; + } + else + { + c["BET_GID"] = hgid; + } + + + + //c["BET_GID"] = hgid.isEmpty() ? gid : hgid; + markets.append(c); + qDebug() << QString("提取盘口: MODEL=%1, RATIO=%2, IORATIO=%3, GID=%4, HGID=%5, BET_GID=%6 STRONG=%7") + .arg(model).arg(ratio).arg(ior).arg(gid).arg(hgid).arg(c["BET_GID"].arg(c["strong"])); + }; + + // 只提取与订单类型匹配的盘口 + const QString orderType = Utils::format_order_type(order); + const QString stage = order.value("STAGE", "全场"); + const QString wagersType = order.value("WAGERS_TYPE", ""); + const QString gt = order.value("GT", ""); + qDebug() << "订单类型:" << orderType << "场次:" << stage << "完整订单类型:" << wagersType << "运动类型:" << gt; + + // rtype(覆盖非滚球与滚球、半场等) + const QString rtype = Utils::get_rtype_code(order).toUpper(); + const QString wtype = Utils::get_wtype_code(order).toUpper(); + auto starts = [&](const QString& s, const QString& p)->bool { return s.startsWith(p, Qt::CaseInsensitive); }; + + QXmlStreamReader xr(result); + QMap cur; + bool inGame = false; + + // 标记:只有当CN/RN分支实际提取到盘口时,才设置 order["ptype"] + auto setPtypeIf = [&](const QString& ptype, bool extracted) { + if (extracted && !ptype.isEmpty() && !order.contains("ptype")) { + order["ptype"] = ptype; + //qDebug() << "设置ptype:" << ptype; + } + }; + + while (!xr.atEnd()) + { + xr.readNext(); + if (xr.isStartElement()) + { + const QString tag = xr.name().toString(); + if (tag.toUpper() == "GAME") { + inGame = true; + cur.clear(); + const QString gameMode = xr.attributes().value("mode").toString(); + const QString ptype = xr.attributes().value("ptype").toString(); + if (!gameMode.isEmpty()) cur["MODE"] = gameMode; + if (!ptype.isEmpty()) cur["PTYPE"] = ptype; + } + else if (inGame) + { + QString txt = xr.readElementText(QXmlStreamReader::IncludeChildElements).trimmed(); + if (!txt.isEmpty()) { cur[tag] = txt; cur[tag.toUpper()] = txt; } + } + } + else if (xr.isEndElement()) + { + if (inGame && xr.name().toString().compare("GAME", Qt::CaseInsensitive) == 0) + { + //qDebug() << "找到游戏节点: " << cur; + inGame = false; + + const QString gid = cur.value("GID"); + const QString hgid = cur.value("HGID"); + const QString gameMode = cur.value("MODE").toUpper(); + const QString ptype = cur.value("PTYPE"); + + + // QString market_tag = Utils::get_market(order.value("WAGERS_TYPE")); + // 专题:角球(CN) + if (wagersType.contains("角球") && gameMode != "CN") + { + continue; + } + // 专题:罚牌(RN) + if (wagersType.contains("罚牌") && gameMode != "RN") + { + continue; + } + + if (wagersType.contains("晋级") && gameMode != "RN") // 晋级???需要修复 + { + continue; + } + + if (wagersType.contains("点球(大小盘)") && gameMode != "PKOU") + { + continue; + } + + if (wagersType.contains("点球(让球盘)") && gameMode != "PKR") + { + continue; + } + + if (wagersType.contains("加时") && gameMode != "ET") + { + continue; + } + + if (wagersType.contains("冠军") && gameMode != "WI") + { + continue; + } + + // 会晋级 点球(大小盘) PKOU 点球(让球盘) PKR + // ET 加时 + + // 普通注单 (过滤角球和罚牌盘口) + //if (!wagersType.contains("角球") && !wagersType.contains("罚牌") + // && !wagersType.contains("晋级") && !wagersType.contains("冠军") + // && !wagersType.contains("加时") && !wagersType.contains("点球(大小盘)") + // && !wagersType.contains("点球(让球盘)") + // && (gameMode == "CN" || gameMode == "RN" || gameMode == "WI" || gameMode == "ET" || gameMode == "PKOU" || gameMode == "PKR")) + //{ + // continue; + //} + QString gtype = Utils::gtype_map(order.value("GT")).toUpper(); + if (!wagersType.contains("角球") && !wagersType.contains("罚牌") + && !wagersType.contains("晋级") && !wagersType.contains("冠军") + && !wagersType.contains("加时") && !wagersType.contains("点球(大小盘)") + && !wagersType.contains("点球(让球盘)") + && (gameMode.toUpper() != Utils::gtype_map(order.value("GT")).toUpper())) + { + continue; + } + + + bool extracted = false; + //qDebug() << "查找代码:" "sw_" + order["wtype"]; + if (cur.value("sw_" + order["wtype"]).compare("Y", Qt::CaseInsensitive) == 0) + { + // 篮球需要区分分节等 + if (order["GT"].contains("篮球")) + { + QString session = ""; + if (order["WAGERS_TYPE"].contains("上半场")) + { + session = "上半场"; + } + if (order["WAGERS_TYPE"].contains("下半场")) + { + session = "下半场"; + } + if (order["WAGERS_TYPE"].contains("第一节")) + { + session = "第一节"; + } + if (order["WAGERS_TYPE"].contains("第二节")) + { + session = "第二节"; + } + if (order["WAGERS_TYPE"].contains("第三节")) + { + session = "第三节"; + } + if (order["WAGERS_TYPE"].contains("第四节")) + { + session = "第四节"; + } + + if (cur.value("session") != session) + { + cur.clear(); + continue; + } + } + QString ior = cur.value("ior_" + order["rtype"]); + if (orderType == "让球" || orderType == "受让") + { + //qDebug() << "找到受让: " << cur; + if (order["WAGERS_TYPE"].contains("滚球")) + { + if (order["WAGERS_TYPE"].contains("半场")) + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_hre"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + else + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_re"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + } + else + { + if (order["GT"] == "足球") + { + if (order["WAGERS_TYPE"].contains("半场")) + { + add("_" + order["rtype"].toUpper(), cur.value("hratio"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + else + { + add("_" + order["rtype"].toUpper(), cur.value("ratio"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + } + else + { + add("_" + order["rtype"].toUpper(), cur.value("ratio"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + + } + } + else if (orderType == "大") + { + if (order["WAGERS_TYPE"].contains("滚球")) + { + if (order["WAGERS_TYPE"].contains("半场")) + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_hrouu"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + else + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_rouu"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + } + else + { + if (order["WAGERS_TYPE"].contains("半场")) + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_hu"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + else + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_u"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + } + } + else if (orderType == "小") + { + if (order["WAGERS_TYPE"].contains("滚球")) + { + if (order["WAGERS_TYPE"].contains("半场")) + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_hrouo"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + else + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_rouo"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + } + else + { + if (order["WAGERS_TYPE"].contains("半场")) + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_ho"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + else + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_o"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + } + } + + else if (orderType == "主队大") + { + if (order["WAGERS_TYPE"].contains("滚球")) + { + if (order["WAGERS_TYPE"].contains("半场")) + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_hrouho"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + else + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_rouho"), ior, gid, hgid, cur.value("strong")); extracted = true;// ok + } + } + else + { + if (order["WAGERS_TYPE"].contains("半场")) + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_houho"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + else + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_ouho"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + } + } + else if (orderType == "主队小") + { + if (order["WAGERS_TYPE"].contains("滚球")) + { + if (order["WAGERS_TYPE"].contains("半场")) + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_hrouhu"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + else + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_rouhu"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + } + else + { + if (order["WAGERS_TYPE"].contains("半场")) + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_houhu"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + else + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_ouhu"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + } + } + + + else if (orderType == "客队大") + { + if (order["WAGERS_TYPE"].contains("滚球")) + { + if (order["WAGERS_TYPE"].contains("半场")) + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_hrouco"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + else + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_rouco"), ior, gid, hgid, cur.value("strong")); extracted = true;// ok + } + } + else + { + if (order["WAGERS_TYPE"].contains("半场")) + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_houco"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + else + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_ouco"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + } + } + else if (orderType == "客队小") + { + if (order["WAGERS_TYPE"].contains("滚球")) + { + if (order["WAGERS_TYPE"].contains("半场")) + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_hroucu"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + else + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_roucu"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + } + else + { + if (order["WAGERS_TYPE"].contains("半场")) + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_houcu"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + else + { + add("_" + order["rtype"].toUpper(), cur.value("ratio_oucu"), ior, gid, hgid, cur.value("strong")); extracted = true; + } + } + } + + else + { + add("_" + order["rtype"].toUpper(), "", ior, gid, hgid, cur.value("strong")); extracted = true; + } + setPtypeIf(ptype, extracted); + } + cur.clear(); + + + } + } + } + + // 打印盘口数量 + qDebug() << QString("提取到盘口数量: %1").arg(markets.size()); + qDebug() << QString("最终ptype: %1").arg(order.value("ptype")); + + // 打印所有盘口信息 + for (int i = 0; i < markets.size(); ++i) { + const QMap& market = markets[i]; + qDebug() << QString("盘口[%1]: MODEL=%2, RATIO=%3, IORATIO=%4, GID=%5, HGID=%6, BET_GID=%7, STRONG=%8") + .arg(i + 1) + .arg(market.value("MODEL")) + .arg(market.value("RATIO")) + .arg(market.value("IORATIO")) + .arg(market.value("GID")) + .arg(market.value("HGID")) + .arg(market.value("BET_GID")) + .arg(market.value("strong")); + } + + if (markets.isEmpty()) { + order["REASON"] = "未提取到与订单类型匹配的盘口"; + } + return markets; + + } + else + { + // 篮球和其他使用json解析 + // 解析 JSON(参考后端返回结构: response.GAMES -> GAME0,GAME1... 每个 GAME 下可能有 PLAYS{}) + QJsonParseError jsonError; + QJsonDocument jsonDoc = QJsonDocument::fromJson(result, &jsonError); + + if (jsonError.error == QJsonParseError::NoError && jsonDoc.isObject()) + { + QJsonObject root = jsonDoc.object(); + QJsonObject response = root.value("response").toObject(); + QJsonObject GAMES = response.value("GAMES").toObject(); + // 添加调试信息 + for (auto it = GAMES.begin(); it != GAMES.end(); ++it) + { + // 查看正在处理的键 + QJsonObject gameObject = it.value().toObject(); + QString gid = gameObject.value("GID").toString(); + QString hgid = gameObject.value("HGID").toString(); + QJsonObject PLAYS = gameObject.value("PLAYS").toObject(); + + QString gopen = gameObject.value("GOPEN").toString(); + + // 添加GOPEN判断 + if (gopen != "Y") { + continue; // 跳过未开盘的game + } + + // ====== 在这里做MS判断(game级别) ====== + QString MS = gameObject.value("MS").toString(); + + + + // 遍历 PLAYS,查找对应的 rtype/ wtype + // 玩法层级与 XML 相似,关键字段名可能为 "SW_" / "IOR_" / ratio fields + // 这里用通用查找:如果在 plays 中存在 "IOR_" 就认为该玩法存在 + QString wantRtype = order.value("rtype"); + QString wantWtype = order.value("wtype"); + QString wantGtype = order.value("gtype"); + //qDebug() << "game object:" << gameObject; + qDebug() << "MS:" << MS; + qDebug() << "wantRtype" << wantRtype; + qDebug() << "gid" << gid; + qDebug() << order; + qDebug() << order["WAGERS_TYPE"]; + qDebug() << "---------------------"; + for (auto it = PLAYS.begin(); it != PLAYS.end(); ++it) + { + if (!it.value().isObject()) continue; + QJsonObject play = it.value().toObject(); + + // 检查 sw_ 开关 + QString swKey = QString("SW_%1").arg(wantWtype.toUpper()); + if (play.contains(swKey) && play.value(swKey).toString().compare("Y", Qt::CaseInsensitive) != 0) + { + //qDebug() << "SW过滤"; + continue; + } + + + // 读取赔率 ior + QString iorKey = QString("IOR_%1").arg(wantRtype.toUpper()); + QString ior = play.contains(iorKey) ? play.value(iorKey).toString() : QString(); + + // RATIO 盘口(字段需要映射) + QString ratioKey = Utils::instance().rtypeToRATIO(wantRtype, gtype).toUpper(); + QString ratio = play.contains(ratioKey) ? play.value(ratioKey).toString() : QString(); + + if (order["GT"].contains("篮球")) { + QString wagers = order["WAGERS_TYPE"]; + //qDebug() << order; + //qDebug() << wagers; + QString ms = MS.trimmed(); + + auto has = [&](const QString &pat)->bool { + return wagers.contains(pat, Qt::CaseInsensitive); + }; + + bool matched = false; + + // MS字段格式: {比赛ID}_{后缀} + // 后缀: 1=上半场, 2=下半场, 3=第一节, 4=第二节, 5=第三节, 6=第四节 + // MS为空 = 全场 + + if (ms.isEmpty()) { + + // 全场(不含节/半场) + if (has("全场") ||( !has("上半场") && !has("下半场") && + !has("第一节") && !has("第二节") && !has("第三节") && !has("第四节"))) { + // qDebug() << "匹配成功"; + matched = true; + } + } + else if (ms.contains("_")) { + QString suffix = ms.split("_").last(); + + if (suffix == "1") { + // 上半场(包含第一节+第二节) + if (has("上半场") || has("上半") || has("1H") || has("H1")) { + matched = true; + } + } + else if (suffix == "2") { + // 下半场(包含第三节+第四节) + if (has("下半场") || has("下半") || has("2H") || has("H2")) { + matched = true; + } + } + else if (suffix == "3") { + // 第一节 + if (has("第一节") || has("第1节") || has("1节") || has("Q1")) { + matched = true; + } + } + else if (suffix == "4") { + // 第二节 + if (has("第二节") || has("第2节") || has("2节") || has("Q2")) { + matched = true; + } + } + else if (suffix == "5") { + // 第三节 + if (has("第三节") || has("第3节") || has("3节") || has("Q3")) { + matched = true; + } + } + else if (suffix == "6") { + // 第四节 + if (has("第四节") || has("第4节") || has("4节") || has("Q4")) { + matched = true; + } + } + } + + if (!matched) { + // 兜底:直接用 MS 原始文本匹配 + if (!ms.isEmpty() && wagers.contains(ms, Qt::CaseInsensitive)) { + matched = true; + } + } + + if (!matched) { + continue; // 不匹配则跳过 + } + + // 匹配则加入 + if (!ior.isEmpty() || !ratio.isEmpty()) + { + + QMap c; + c["MODEL"] = "_" + wantRtype.toUpper(); + c["RATIO"] = ratio; + c["IORATIO"] = ior; + c["GID"] = gid; + c["HGID"] = hgid; + c["strong"] = gameObject.value("STRONG").toString(); + c["BET_GID"] = (order.value("STAGE") == "全场") ? gid : hgid; + qDebug() << "找到符合条件盘口:" << c; + markets.append(c); + } + } + + } + } + + + + } + else + { + qWarning() << "JSON 解析失败:" << jsonError.errorString(); + } + + if (markets.isEmpty()) { + order["REASON"] = "未提取到与订单类型匹配的盘口"; + } + // qDebug() << "返回盘口数量:" << markets.size(); + return markets; + + } + order["REASON"] = "未提取到与订单类型匹配的盘口"; + return QList>(); + + +} + + + + +void BetThread::setParam(QString url, QString ver, QString param, QString cookies) +{ + QMutexLocker lock(&m_mutex); + + + //url = url.trimmed(); + + //// 使用QUrl确保URL格式正确 + //QUrl qurl(url); + //if (!qurl.isValid() || qurl.scheme().isEmpty()) { + // qurl = QUrl("https://" + url); + //} + + //// 标准化URL:HTTPS协议 + 主机 + 路径(至少"/") + //if (!qurl.isValid()) { + + // emit log("账户状态", "皇冠网址异常重连"); + // emit account_disconnect(); + // // m_url = "https://example.com/"; + //} + //else { + // if (qurl.scheme() == "http") qurl.setScheme("https"); + // if (qurl.path().isEmpty()) qurl.setPath("/"); + // m_url = qurl.toString(QUrl::RemoveQuery | QUrl::RemoveFragment); + // if (!m_url.endsWith('/')) m_url += '/'; + //} + + m_url = Utils::normalizeUrl(url); + qDebug() << "设置参数 - URL:" << m_url; + if (m_url == "") + { + + emit log("账户状态", "皇冠网址异常重连"); + emit account_disconnect(); + } + + m_ver = ver; + m_param = param; + m_cookies = cookies; + + +} + +void BetThread::set_account_list(QList> account_list) +{ + QMutexLocker lock(&m_mutex); + m_account_list = account_list; +} + + +bool BetThread::screen_type(QMap& order) +{ + //////////////////////////////////////////////////////////////////////// + // 跟单设置 -> 跟单项目 + //////////////////////////////////////////////////////////////////////// + bool follow = false; + QList> follow_projects = g_config->betProject(); + QString order_format_wagers_type = Utils::format_wagers_type(order); + QString order_format_order_type = Utils::format_order_type(order); + for (int i = 0; i < follow_projects.count(); i++) + { + QMap follow_project = follow_projects[i]; + //qDebug() << follow_project; + // 判断球类 + if (order.value("GT") == follow_project["GT"] || (order.value("GT") == "篮球 / 美式足球" && follow_project["GT"] == "篮球")) + { + // 判断节(滚球/今日/早盘) + if (order["SESSION"] == follow_project["SESSION"]) + { + // 判断场次 + if (order["STAGE"] == follow_project["STAGE"] || follow_project["STAGE"] == "全部") + { + // 判断盘口类型 + if (order_format_wagers_type == follow_project["WAGERS_TYPE"]) + { + if (order_format_order_type == follow_project["ORDER_TYPE"]) + { + if (follow_project["ENABLE"] == "TRUE") + { + follow = true; + break; + } + } + } + + } + + + } + } + } + if (!follow) + { + //qDebug() << order_format_wagers_type << order.value("GT") << order["SESSION"] << order["STAGE"] << order_format_order_type << order.value("WAGERS_TYPE"); + order["REASON"] = QString("未启用跟单项目:%1").arg(order_format_wagers_type); + return false; + } + + int betDays = g_config->betDays(); + if (betDays != 0) + { + QDateTime betDateTime = QDateTime::fromString(order["DATETIME"], "yyyy-MM-dd HH:mm:ss"); + if (betDateTime.daysTo(QDateTime::currentDateTime()) > betDays) + { + order["REASON"] = "超出跟单日期"; + return false; + } + } + + // 跟单普通注单 + if (!g_config->betNormalOrder() && order["SRV_IP"].isEmpty()) + { + order["REASON"] = "未启用普通跟单类型"; + return false; + } + + // 跟单手机注单 + if (!g_config->betPhoneOrder() && order["SRV_IP"] == "手机") + { + order["REASON"] = "未启用手机跟单类型"; + return false; + } + + + //////////////////////////////////////////////////////////////////////// + // 跟单设置 -> 跟单类型 + //////////////////////////////////////////////////////////////////////// + QList followType = g_config->followType(); + if (!followType.contains("normal") && + ( + !order["WAGERS_TYPE"].contains("加时") && !order["WAGERS_TYPE"].contains("角球") && !order["WAGERS_TYPE"].contains("罚球") + && !order["WAGERS_TYPE"].contains("晋级") && !order["WAGERS_TYPE"].contains("冠军") && !order["WAGERS_TYPE"].contains("点球") + ) + ) + { + emit log("跟单类型", QString("订单号: %1 跟单类型(普通)未启用").arg(order["tid"])); + order["REASON"] = "跟单类型未启用 (普通)"; + return false; + } + if (!followType.contains("addTime") && order["WAGERS_TYPE"].contains("加时")) + { + emit log("跟单类型", QString("订单号: %1 跟单类型(加时)未启用").arg(order["tid"])); + order["REASON"] = "跟单类型未启用 (加时)"; + return false; + } + if (!followType.contains("corner") && order["WAGERS_TYPE"].contains("角球")) + { + emit log("跟单类型", QString("订单号: %1 跟单类型(角球)未启用").arg(order["tid"])); + order["REASON"] = "跟单类型未启用 (角球)"; + return false; + } + if (!followType.contains("free") && order["WAGERS_TYPE"].contains("罚球")) + { + emit log("跟单类型", QString("订单号: %1 跟单类型(罚球)未启用").arg(order["tid"])); + order["REASON"] = "跟单类型未启用 (罚球)"; + return false; + } + if (!followType.contains("promotion") && order["WAGERS_TYPE"].contains("晋级")) + { + emit log("跟单类型", QString("订单号: %1 跟单类型(晋级)未启用").arg(order["tid"])); + order["REASON"] = "跟单类型未启用 (晋级)"; + return false; + } + if (!followType.contains("champion") && order["WAGERS_TYPE"].contains("冠军")) + { + emit log("跟单类型", QString("订单号: %1 跟单类型(冠军)未启用").arg(order["tid"])); + order["REASON"] = "跟单类型未启用 (冠军)"; + return false; + } + if (!followType.contains("point") && order["WAGERS_TYPE"].contains("点球")) + { + //qDebug() << "设置窗口 -> 过滤注单 -> 跟单类型(点球)未启用"; + order["REASON"] = "跟单类型未启用 (点球)"; + return false; + } + + return true; +} + +bool BetThread::screen_team_and_league(QMap& order) +{ + + // 赛事筛选 + QList screenList = g_config->screenGameList(); + QList acceptList = g_config->acceptGameList(); + + // 队伍过滤 + for (int i = 0; i < screenList.count(); i++) + { + // 判断队伍 + if (screenList[i].contains(order["TEAM_H"]) || screenList[i].contains(order["TEAM_"])) + { + order["REASON"] = "队伍筛选"; + return false; + } + } + + bool acceptTeam = false; + for (int i = 0; i < screenList.count(); i++) + { + // 判断队伍 + if (acceptList[i].contains(order["TEAM_H"]) || acceptList[i].contains(order["TEAM_C"])) + { + acceptTeam = true; + break; + } + } + + + // 队伍未选择查找联盟 + if (!acceptTeam) + { + for (int i = 0; i < screenList.count(); i++) + { + // 判断联盟 + if (screenList[i] == order["LEAGUE"]) + { + order["REASON"] = "联盟筛选"; + return false; + } + } + + bool acceptLeague = false; + for (int i = 0; i < acceptList.count(); i++) + { + if (acceptList[i] == order["LEAGUE"]) + { + acceptLeague = true; + break; + } + } + + if (!acceptLeague) + { + // 未过滤获取联盟进行判断 + for (int i = 0; i < screenList.count(); i++) + { + // 判断联盟 + if (screenList[i] == "所有联盟") + { + order["REASON"] = "所有联盟筛选"; + return false; + } + } + } + } + + return true; +} + + +bool BetThread::screen_rebet(QMap& order) +{ + //////////////////////////////////////////////////////////////////////// + // 跟单设置 -> 补单筛选 + //////////////////////////////////////////////////////////////////////// + if (!order["REBET_TIMES"].isEmpty()) + { + // 补单筛选开关 + if (g_config->rebetScreenEnable()) + { + QList> list = g_config->rebetScreen(); + for (int i = 0; i < list.count(); i++) + { + QMap rebetScreen = list[i]; + if (rebetScreen["ENABLE"] == "TRUE") + { + // 补单原因 + if (order["REASON"].contains(rebetScreen["REASON"])) + { + // 最多次数 + int maxTimes = rebetScreen["TIMES"].toInt(); + // 达到原因累积次数放弃注单 + if (g_config->get_rebet_reason_times(order["TID"], order["REASON"]) >= maxTimes) + { + order["REASON"] = "失败原因达到最大补单次数"; + return false; + } + break; + } + } + + } + } + + //////////////////////////////////////////////////////////////////////// + // 跟单设置 -> 补单次数 + //////////////////////////////////////////////////////////////////////// + + // 达到补单次数延时 + if (order["REBET_TIMES"].toInt() == g_config->rebetSleepTimes()) + { + QEventLoop loop; + QTimer::singleShot(g_config->rebetSleep() * 1000, &loop, &QEventLoop::quit); + loop.exec(); + } + // 最多补单次数 + if (order["REBET_TIMES"].toInt() >= g_config->rebetMaxTimes()) + { + order["REASON"] = "超出最多补单次数"; + return false; + } + + } + + return true; +} + + +bool BetThread::screen_handicap(QMap& order) +{ + //////////////////////////////////////////////////////////////////////// + // 跟单设置 -> 赛事盘口 + //////////////////////////////////////////////////////////////////////// + // 同赛事对头单不跟 + if (g_config->gameOppositeEnable()) + { + if (!g_config->checkOppositeBet(order)) { + order["REASON"] = "同赛事对头单不跟"; + return false; + } + + } + // 同赛事盘口对头单不跟 + if (g_config->handicapOppositeEnable()) + { + QString type = Utils::instance().get_wagers_wtype_name(order["wtype"]); + if (type == "让球" && type == "大小") + { + if (!g_config->checkOppositeHandicap(order)) { + order["REASON"] = "同赛事盘口对头单不跟"; + return false; + } + } + + } + + + // 同赛事最多跟单次数 + if (g_config->gameFollowTimesMaxEnable()) + { + if (!g_config->check_game_follow_max_times(order)) + { + order["REASON"] = "超出[同赛事]最多跟单次数"; + return false; + } + + } + // 同赛事最多跟单金额 + if (g_config->gameFollowAmountMaxEnable()) + { + if (!g_config->check_game_follow_max_amount(order)) + { + order["REASON"] = "超出[同赛事]最多跟单金额"; + return false; + } + } + + // 同赛事盘口最多跟单次数 + if (g_config->handicapFollowTimesMaxEnable()) + { + if (!g_config->check_handicap_follow_max_times(order)) + { + order["REASON"] = "超出[同赛事盘口]最多跟单次数"; + return false; + } + } + // 同赛事盘口最多跟单金额 + if (g_config->handicapFollowAmountMaxEnable()) + { + if (!g_config->check_handicap_follow_max_amount(order)) + { + order["REASON"] = "超出[同赛事盘口]最多跟单金额"; + return false; + } + } + + return true; +} + +bool BetThread::screen_original_gold(QMap& order) +{ + //////////////////////////////////////////////////////////////////////// + // 跟单设置 -> 注单金额 + //////////////////////////////////////////////////////////////////////// + + // 注单原始金额小于 ?? 放弃注单 + if (g_config->originalAmountLowerGiveUpEnable()) + { + if (order["GOLD"].toFloat() < g_config->originalAmountLower()) + { + order["REASON"] = QString("注单原始金额小于 %1 放弃注单").arg(g_config->originalAmountLower()); + return false; + } + } + + // 注单原始金额大于 ?? 放弃注单 + if (g_config->originalAmountHigherGiveUpEnable()) + { + if (order["GOLD"].toFloat() > g_config->originalAmountHigher()) + { + order["REASON"] = QString("注单原始金额大于 %1 放弃注单").arg(g_config->originalAmountHigher()); + return false; + } + } + return true; +} + +bool BetThread::screen_gold(QMap& order) +{ + + + // 注单跟单金额小于 ?? 加大到 ?? / 放弃注单 + if (g_config->amountLowerEnable()) + { + if (order["GOLD"].toFloat() < g_config->amountLower()) + { + if (g_config->amountLowerAddToEnable()) + { + order["GOLD"] = QString::number(g_config->amountLowerAddTo()); + } + else if (g_config->amountLowerGiveUpEnable()) + { + + order["REASON"] = QString("注单跟单金额小于 %1 放弃注单").arg(g_config->amountLower()); + // 放弃注单 + return false; + } + } + } + // 注单跟单金额大于 ?? 减小到 ?? / 放弃注单 + if (g_config->amountHigherEnable()) + { + if (order["GOLD"].toFloat() > g_config->amountHigher()) + { + if (g_config->amountHigherSubToEnable()) + { + order["GOLD"] = QString::number(g_config->amountHigherSubTo()); + } + if (g_config->amountHigherGiveUpEnable()) + { + order["REASON"] = QString("注单跟单金额大于 %1 放弃注单").arg(g_config->amountHigher()); + // 放弃注单 + return false; + } + } + } + + + // 平台限额 + if (g_config->amount_less_than_platform() == 0) + { + if (order["GOLD"].toFloat() < order["gold_gmin"].toFloat()) + { + // 加大到最小限额 + order["GOLD"] = order["gold_gmin"]; + } + + } + else + { + if (order["GOLD"].toFloat() < order["gold_gmin"].toFloat()) + { + order["REASON"] = QString("注单跟单金额小于平台最小值: %1").arg(order["gold_gmin"]); + return false; + } + + } + + if (g_config->amount_more_than_platform() == 0) + { + if (order["GOLD"].toFloat() > order["gold_gmax"].toFloat()) + { + // 加大到最小限额 + order["GOLD"] = order["gold_gmax"]; + } + + } + else + { + if (order["GOLD"].toFloat() > order["gold_gmax"].toFloat()) + { + order["REASON"] = QString("注单跟单金额大于平台最大值: %1").arg(order["gold_gmax"]); + return false; + } + + } + + return true; +} + +/// +/// 过滤注单 +/// +/// 注单信息 +/// 返回true通过 返回false过滤 +bool BetThread::screen_user_policy(QMap& order) +{ + + //////////////////////////////////////////////////////////////////////// + // 跟单设置 -> 会员策略(会员>登3代理>登2代理>其他会员) + //////////////////////////////////////////////////////////////////////// + QList> list = g_config->setting(); + // 获取策略索引 + int row = 0; + // 是否存在匹配项目 + bool match = false; + bool account_checked = false; + // 匹配会员账号是否在列表中 + for (row = 0; row < list.count(); row++) + { + QString screenUsername = list[row]["username"]; + QString type = list[row]["type"]; + if (order["NAME0"] == screenUsername && type == "会员") // 处理点:加上其他会员,自身订单判断 + { + account_checked = (list[row]["enable"] == "true" ? true : false); + match = true; + break; + } + } + // 匹配登3代理 + if (!match) + { + for (row = 0; row < list.count(); row++) + { + QString screenUsername = list[row]["username"]; + QString type = list[row]["type"]; + // 判断代理 + if (type != "会员") + { + for (auto account : m_account_list) + { + // 先找到订单账户 + if (account["username"] == order["NAME0"]) + { + // 判断上级代理是否为登3代理 + if (screenUsername == account["up_username"]) + { + account_checked = (list[row]["enable"] == "true" ? true : false); + match = true; + break; + } + } + + } + } + } + } + // 匹配登2代理 + if (!match) + { + for (row = 0; row < list.count(); row++) + { + QString screenUsername = list[row]["username"]; + QString type = list[row]["type"]; + bool checked = list[row]["enable"] == "true" ? true : false; + // 判断是否为代理 + if (type != "会员") + { + for (auto account : m_account_list) + { + // 先找到订单账户 + if (account["username"] == order["NAME0"]) + { + // 判断上上级代理是否为登2代理 + if (screenUsername == account["up_up_username"]) + { + account_checked = (list[row]["enable"] == "true" ? true : false); + match = true; + break; + } + } + + } + } + } + } + // 匹配其他会员 + if (!match) + { + row = 0; // 第一行是固定其他会员 + account_checked = (list[row]["enable"] == "true" ? true : false); + } + + + // 判断是否启用 + if (!account_checked) + { + order["REASON"] = "会员未启用"; + return false; + } + + + + // 跟单方式[正跟/反跟] + QList> followTypeList = g_config->toMapList(list[row]["followType"]); + for (int i = 0; i < followTypeList.count(); i++) + { + QMap followType = followTypeList[i]; + + QString order_format_wagers_type = Utils::format_wagers_type(order); + QString order_format_order_type = Utils::format_order_type(order); + + //qDebug() << order; + //qDebug() << followType; + // 判断球类 + if (order.value("GT") == followType["GT"] || (order.value("GT") == "篮球 / 美式足球" && followType["GT"] == "篮球")) + { + // 判断节(滚球/今日/早盘) + if (order["SESSION"] == followType["SESSION"]) + { + // 判断场次 + if (order["STAGE"] == followType["STAGE"] || followType["STAGE"] == "全部") + { + if (order_format_order_type == followType["ORDER_TYPE"]) + { + if (followType["follow_betType"] == "false") + { + // 转换为反跟 + emit log("调试日志", QString("原始跟单:%1").arg(order["rtype"])); + order = Utils::instance().toContra(order); + emit log("调试日志", QString("调整跟单:%1").arg(order["rtype"])); + emit log("调试日志", "跟单方式:反跟"); + break; + } + } + // 判断盘口类型 + //if (order_format_wagers_type == followType["WAGERS_TYPE"]) + //{ + + //} + } + } + } + } + + // 跟单盘口 + QMap followHandicap; + followHandicap["hkEnable"] = list[row]["hkEnable"]; + followHandicap["hkChange"] = list[row]["hkChange"]; + followHandicap["masEnable"] = list[row]["masEnable"]; + followHandicap["masChange"] = list[row]["masChange"]; + followHandicap["idaEnable"] = list[row]["idaEnable"]; + followHandicap["idaChange"] = list[row]["idaChange"]; + followHandicap["eurEnable"] = list[row]["eurEnable"]; + followHandicap["eurChange"] = list[row]["eurChange"]; + if (order["ODDF_TYPE"] == "香港盘" || order["odd_f_type"] == "H") + { + if (followHandicap["hkEnable"] == "true") + { + order["ODDF_TYPE"] = followHandicap["hkType"]; + order["odd_f_type"] = followHandicap["hkChange"]; + } + else + { + order["ODDF_TYPE"] = "香港盘"; + order["odd_f_type"] = "H"; + } + } + else if (order["ODDF_TYPE"] == "马来盘" || order["odd_f_type"] == "M") + { + if (followHandicap["masEnable"] == "true") + { + order["ODDF_TYPE"] = followHandicap["masType"]; + order["odd_f_type"] = followHandicap["masChange"]; + } + else + { + order["ODDF_TYPE"] = "马来盘"; + order["odd_f_type"] = "M"; + } + } + else if (order["ODDF_TYPE"] == "印尼盘" || order["odd_f_type"] == "I") + { + if (followHandicap["idaEnable"] == "true") + { + order["ODDF_TYPE"] = followHandicap["idaType"]; + order["odd_f_type"] = followHandicap["idaChange"]; + } + else + { + order["ODDF_TYPE"] = "印尼盘"; + order["odd_f_type"] = "I"; + } + } + else if (order["ODDF_TYPE"] == "欧洲盘" || order["odd_f_type"] == "E") + { + if (followHandicap["eurEnable"] == "true") + { + order["ODDF_TYPE"] = followHandicap["eurType"]; + order["odd_f_type"] = followHandicap["eurChange"]; + } + else + { + order["ODDF_TYPE"] = "马来盘"; + order["odd_f_type"] = "E"; + } + } + + // 计算方式 + QString calcType = list[row]["calcType"]; + if (calcType == "固定金额") + { + QString fixed = list[row]["calcType_fixed"]; + order["GOLD"] = fixed; + } + else if (calcType == "缩放比率") + { + QString scale = list[row]["calcType_scale"]; + order["GOLD"] = QString::number(order["GOLD"].toInt() * scale.toFloat()); + } + else if (calcType == "项目设置") + { + QList> customList = g_config->toMapList(list[row]["calcType_custom"]); + for (int i = 0; i < customList.count(); i++) + { + QMap custom = customList[i]; + + QString order_format_wagers_type = Utils::format_wagers_type(order); + QString order_format_order_type = Utils::format_order_type(order); + // 判断球类 + if (order.value("GT") == custom["GT"] || (order.value("GT") == "篮球 / 美式足球" && custom["GT"] == "篮球")) + { + // 判断节(滚球/今日/早盘) + if (order["SESSION"] == custom["SESSION"]) + { + // 判断场次 + if (order["STAGE"] == custom["STAGE"] || custom["STAGE"] == "全部") + { + // 判断盘口类型 + if (order_format_wagers_type == custom["WAGERS_TYPE"]) + { + if (order_format_order_type == custom["ORDER_TYPE"]) + { + // 缩放比率 + if (custom["type"] == "scale") + { + // 可能存在问题 + order["GOLD"] = QString::number(order["GOLD"].toInt() * custom["value"].toFloat()); + } + // 固定金额 + if (custom["type"] == "fixed") + { + order["GOLD"] = custom["value"]; + } + } + } + } + } + + } + } + } + + + // 缺少盘口类型 + if (order["ODDF_TYPE"] == "" || order["odd_f_type"] == "") + { + if (g_config->lackType() == 0) + { + order["ODDF_TYPE"] = "香港盘"; + order["odd_f_type"] = "H"; + } + else + { + return false; + } + } + + // 金额取整 + order["GOLD"] = QString::number(order["GOLD"].toInt()); + + return true; +} + +bool BetThread::screen_score(QMap& order) +{ + // 跟单设置 -> 比分变化不跟 + if (g_config->ignoreScoreChangedEnable()) + { + if (order["SCORE"] != order["SCORE_NEW"]) + { + emit log("比分变化不跟", QString("订单号 %1 比分变化不跟 %2 %3").arg(order["TID"]).arg(order["SCORE"]).arg(order["SCORE_NEW"])); + order["REASON"] = "比分变化不跟"; + return false; + } + } + // 跟单设置 -> 只跟固定比分 + if (g_config->followFixedScoreEnable()) + { + if (order["SCORE_NEW"] != (g_config->fixedScoreMaster() + ":" + g_config->fixedScoreVisitor())) + { + emit log("只跟固定比分", QString("订单号 %1 只跟固定比分 %2:%3").arg(order["TID"]).arg(g_config->fixedScoreMaster()).arg(g_config->fixedScoreVisitor())); + order["REASON"] = "只跟固定比分"; + return false; + } + } + return true; +} + +bool BetThread::screen_ioratio(QMap& order) +{ + //////////////////////////////////////////////////////////////////////// + // 跟单设置 -> 注单赔率 + //////////////////////////////////////////////////////////////////////// + // 过滤赔率 + QList> oddsList = g_config->odds(); + for (int i = 0; i < oddsList.count(); i++) + { + QMap odds = oddsList[i]; + + if ((odds["GT"] == order["GT"] || (odds["GT"] == "篮球" && order.value("GT").contains("篮球"))) + && odds["ORDER_TYPE"] == Utils::format_order_type(order) + && (odds["STAGE"] == order.value("STAGE") || odds["STAGE"] == "全部") + && odds["SESSION"] == order["SESSION"]) + { + // 大于不跟 + if (odds["HIGH"].toFloat() < order["IORATIO_NEW"].toFloat() && odds["HIGH"].toFloat() != 0) + { + order["REASON"] = "赔率大于不跟"; + order["NEED_REBET"] = odds["REBET"]; + return false; + } + // 小于不跟 + if (odds["LOW"].toFloat() > order["IORATIO_NEW"].toFloat() && odds["LOW"].toFloat() != 0) + { + // QMap(("column", "2")("down", "3")("gtype", "FT")("high", "0")("low", "1")("projcet", "足球早盘全场")("project", "足球早盘全场")("row", "4")("rtype", "RC")("session", "FU")("type", "受让")("up", "2")) + + //emit log("赔率问题", "原始赔率:" + order["ioratio"] + "设置赔率:" + odds["low"]); + order["REASON"] = "赔率小于不跟"; + order["NEED_REBET"] = odds["REBET"]; + return false; + } + // 上涨不跟 + if (odds["UP"].toFloat() < order["IORATIO_NEW"].toFloat() - order["IORATIO"].toFloat() && odds["UP"].toFloat() != 0) + { + order["REASON"] = "赔率上涨不跟"; + order["NEED_REBET"] = odds["REBET"]; + return false; + } + // 下跌不跟 + if (odds["DOWN"].toFloat() < order["IORATIO"].toFloat() - order["IORATIO_NEW"].toFloat() && odds["DOWN"].toFloat() != 0) + { + order["REASON"] = "赔率下跌不跟"; + order["NEED_REBET"] = odds["REBET"]; + return false; + } + } + } + + return true; +} + +bool BetThread::screen_con(QMap& order, const QList>& marketCandidates) +{ + //////////////////////////////////////////////////////////////////////// + // 跟单设置 -> 注单盘口(优先查找原盘口) + //////////////////////////////////////////////////////////////////////// + QList> handicapList = g_config->handicap(); + + + // 先找到匹配的跟单策略 + QMap matchedStrategy; + for (int i = 0; i < handicapList.count(); i++) { + QMap handicap = handicapList[i]; + // 匹配赛事类型、玩法、场次 + if ((handicap["GT"] == order["GT"] || (handicap["GT"] == "篮球" && order.value("GT").contains("篮球"))) + && handicap["ORDER_TYPE"] == Utils::format_order_type(order) + && (handicap["STAGE"] == order.value("STAGE") || handicap["STAGE"] == "全部") + && handicap["SESSION"] == order["SESSION"]) { + matchedStrategy = handicap; + // qDebug() << "找到匹配策略:" << handicap; + break; + } + } + // 如果没有找到匹配策略,直接不再匹配, 返回成功 + if (matchedStrategy.isEmpty()) { + // 没有策略说明不是需要检测的类型 + order["REASON"] = "未找到匹配的盘口策略"; + return true; + } + + // 标准化盘口值比较函数 + auto normalizeHandicap = [](const QString& handicap) -> QString { + QString normalized = handicap.trimmed(); + // 移除所有空格 + normalized.remove(QRegularExpression("\\s+")); + // 统一正负号格式(+1.5 和 1.5 都视为相同) + if (normalized.startsWith("+")) { + normalized = normalized.mid(1); + } + if (normalized.startsWith("-")) { + normalized = normalized.mid(1); + } + return normalized; + }; + + QString originalHandicap; + if (Utils::format_order_type(order) == "让球" || Utils::format_order_type(order) == "受让") + { + originalHandicap = order["ORDER_CON"]; + } + else + { + originalHandicap = normalizeHandicap(order["ORDER_CON"]); + + } + + + QString ORDER_TYPE = matchedStrategy["ORDER_TYPE"]; + + // Utils::format_order_type(order); + + + + + // 下注RH,队伍H,C为+,强队H为- + // 下注RC,队伍C, C为- ,强队H为+ + + + // 主队让球H为- C为+ + // 客队受让H为+ C为- + + + // 分类所有盘口 + QMap originalMarket; // 原盘口 + QList> betterMarkets; // 变好盘口 + QList> worseMarkets; // 变差盘口 + QList> unchangedMarkets; // 未变化盘口 + + for (const QMap& market : marketCandidates) { + + QString marketHandicap = market["RATIO"]; + + // 处理让球盘口的正负号 + if (Utils::format_order_type(order) == "让球" || Utils::format_order_type(order) == "受让") + { + if (marketHandicap != "0") + { + if (Utils::format_order_type(order) == "让球") + { + if (market["strong"] == "H") + { + marketHandicap = "-" + marketHandicap; + } + else + { + marketHandicap = "+" + marketHandicap; + } + } + else if (Utils::format_order_type(order) == "受让") + { + if (market["strong"] == "H") + { + marketHandicap = "+" + marketHandicap; + } + else + { + marketHandicap = "-" + marketHandicap; + } + } + + } + } + else + { + marketHandicap = normalizeHandicap(market["RATIO"]); + + } + + + // 检查是否为原盘口 + if (marketHandicap.trimmed() == originalHandicap.trimmed()) { + originalMarket = market; + //qDebug() << "找到原盘口:" << market; + continue; + } + else + { + //qDebug() << "原始盘口:" << originalHandicap << "当前盘口:" << marketHandicap; + } + + // 检查盘口变化情况 这里似乎判断不了正负号 + MarketChange change = MARKET_INVALID; + if (ORDER_TYPE == "让球" || ORDER_TYPE == "受让") { + change = Utils::instance().checkHandicapChange(ORDER_TYPE.toStdString(), order["ORDER_CON"].toStdString(), marketHandicap.toStdString()); + + + //qDebug() << "检测原盘口" << order["ORDER_CON"] << "检测新盘口" << marketHandicap; + } + else if (ORDER_TYPE == "大" || ORDER_TYPE == "小") { + change = Utils::instance().checkOverUnderChange(ORDER_TYPE.toStdString(), order["ORDER_CON"].toStdString(), marketHandicap.toStdString()); + } + + if (change == MARKET_IMPROVED) { + betterMarkets.append(market); + //qDebug() << "找到变好盘口:" << market; + } + else if (change == MARKET_WORSENED) { + worseMarkets.append(market); + //qDebug() << "找到变差盘口:" << market; + } + else if (change == MARKET_UNCHANGED) { + unchangedMarkets.append(market); + //qDebug() << "找到未变化盘口:" << market; + } + } + + // 根据优先级选择盘口 + QMap selectedMarket; + QString selectionReason; + + // 1. 优先选择原盘口 + if (!originalMarket.isEmpty()) { + selectedMarket = originalMarket; + selectionReason = "原盘口"; + } + // 2. 其次选择变好的盘口 + else if (!betterMarkets.isEmpty()) { + selectedMarket = betterMarkets.first(); + selectionReason = "变好盘口"; + } + // 3. 最后选择变差的盘口 + else if (!worseMarkets.isEmpty()) { + selectedMarket = worseMarkets.first(); + selectionReason = "变差盘口"; + } + + qDebug() << "选择盘口:" << selectedMarket << "原因:" << selectionReason; + + // 如果没找到任何盘口,拒绝 + if (selectedMarket.isEmpty()) { + order["REASON"] = "未找到匹配的盘口"; + order["NEED_REBET"] = matchedStrategy["REBET"]; + return false; + } + + // 更新订单的盘口信息 + order["ORDER_CON_NEW"] = selectedMarket["RATIO"]; + order["IORATIO_NEW"] = selectedMarket["IORATIO"]; + order["HANDICAP_ID"] = selectedMarket.value("HANDICAP_ID", ""); + order["BET_GID"] = selectedMarket["BET_GID"]; + order["GID"] = selectedMarket["BET_GID"]; + // 根据策略判断是否跟单 + int reason_change_times = g_config->get_rebet_reason_times(order["TID"], "盘口变化不跟"); + int reason_bad_times = g_config->get_rebet_reason_times(order["TID"], "盘口变差不跟"); + + MarketChange finalChange = MARKET_INVALID; + if (ORDER_TYPE == "让球" || ORDER_TYPE == "受让") { + finalChange = Utils::instance().checkHandicapChange(ORDER_TYPE.toStdString(), order["ORDER_CON"].toStdString(), order["ORDER_CON_NEW"].toStdString()); + } + else if (ORDER_TYPE == "大" || ORDER_TYPE == "小") { + finalChange = Utils::instance().checkOverUnderChange(ORDER_TYPE.toStdString(), order["ORDER_CON"].toStdString(), order["ORDER_CON_NEW"].toStdString()); + } + + //qDebug() << "最终盘口变化:" << finalChange; + + // 判断盘口处理方式 + QString solution = matchedStrategy["solution"]; + + // 1. 盘口变化不跟(B/S/X/Z的初始阶段) + if (solution == "B" || + (solution == "S" && reason_change_times < 3) || + (solution == "X" && reason_change_times < 3) || + (solution == "Z" && reason_change_times < 3)) { + + // 只要盘口变化就拒绝 + if (MARKET_UNCHANGED != finalChange) { + order["REASON"] = "盘口变化不跟"; + order["NEED_REBET"] = matchedStrategy["REBET"]; + return false; + } + } + + // 2. 盘口变差不跟(C/S/Y/Z的后续阶段) + if (solution == "C" || + (solution == "S" && reason_bad_times >= 3) || + (solution == "Y" && reason_bad_times < 3) || + (solution == "Z" && reason_bad_times >= 3 && reason_bad_times < 6)) { + + if (MARKET_WORSENED == finalChange) { + order["REASON"] = "盘口变差不跟"; + order["NEED_REBET"] = matchedStrategy["REBET"]; + return false; + } + } + + qDebug() << "通过策略筛选,选择盘口:" << selectionReason; + return true; +} + + + + +void BetThread::push_bet_success(QMap order) +{ + PushMsg *worker = new PushMsg(); + QThread *workerThread = new QThread(); + + worker->moveToThread(workerThread); + + // 连接信号槽 + connect(workerThread, &QThread::started, [worker, order]() { + worker->push("bet_order_success", g_config->notice_account(), order); + }); + + connect(worker, &PushMsg::resultReady, [](const QString &result) { + //qDebug() << "Result:" << result; + }); + + connect(worker, &PushMsg::resultReady, workerThread, &QThread::quit); + connect(workerThread, &QThread::finished, worker, &PushMsg::deleteLater); + connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater); + + workerThread->start(); +} + +void BetThread::push_bet_failed(QMap order) +{ + PushMsg *worker = new PushMsg(); + QThread *workerThread = new QThread(); + + worker->moveToThread(workerThread); + + // 连接信号槽 + connect(workerThread, &QThread::started, [worker, order]() { + worker->push("bet_order_failed", g_config->notice_account(), order); + }); + + connect(worker, &PushMsg::resultReady, [](const QString &result) { + //qDebug() << "Result:" << result; + }); + + connect(worker, &PushMsg::resultReady, workerThread, &QThread::quit); + connect(workerThread, &QThread::finished, worker, &PushMsg::deleteLater); + connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater); + + workerThread->start(); +} + + +void BetThread::push_screen(QMap order) +{ + PushMsg *worker = new PushMsg(); + QThread *workerThread = new QThread(); + + worker->moveToThread(workerThread); + + // 连接信号槽 + connect(workerThread, &QThread::started, [worker, order]() { + worker->push("screen_order", g_config->notice_account(), order); + }); + + connect(worker, &PushMsg::resultReady, [](const QString &result) { + //qDebug() << "Result:" << result; + }); + + connect(worker, &PushMsg::resultReady, workerThread, &QThread::quit); + connect(workerThread, &QThread::finished, worker, &PushMsg::deleteLater); + connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater); + + workerThread->start(); +} + + diff --git a/CrownClient/BetThread.h b/CrownClient/BetThread.h new file mode 100644 index 0000000..af8955e --- /dev/null +++ b/CrownClient/BetThread.h @@ -0,0 +1,130 @@ +#pragma once +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class BetThread :public QThread +{ + Q_OBJECT +public: + BetThread(); + ~BetThread(); +signals: + void log(QString type, QString log); + //void update_orders(QList>); + void account_disconnect(); // 掉线 + + + void signal_view_add_screen_order(QMap order); + void signal_view_add_failed_order(QMap order); + void signal_view_add_success_order(QMap order); + void signal_view_add_rebet_order(QMap order); + void signal_view_alert_failed_order(QMap order); + void signal_view_remove_failed_order(QMap order); + // 防止重复跟单 + void signal_bet_oder(QMap order); + +public: + void run(); +private: + QMutex m_mutex; + + QString m_url; + QString m_ver; + QString m_param; + + // ltype根据用户获取 + QString m_ltype; + QString m_cookies; + + + QList m_user_list; + QList m_agent_list; + + QList> m_account_list; + + QMap m_account_set_ft; + QMap m_account_set_bk; + +public: + void pause(); + void resume(); + void exit(); //结束 +public: + void setParam(QString url, QString ver, QString param, QString cookies); + void set_account_list(QList> account_list); + + + void push_bet_success(QMap order); + void push_bet_failed(QMap order); + void push_screen(QMap order); +private: + // 获取账户设置(限额) + QMap BetThread::get_account_set(QString gtype); + // 获取账户设置(索引) + QString get_market_by_wtype(const QString &wtype); + + int get_limit_amount(QString gtype, QString wtype); + + + + // 处理筛选订单 + void handleInvalidOrder(QMap& order); + // 处理失败订单 + void handleFailedOrder(QMap& order); + // 处理普通订单 + void handleNormalOrder(QMap& order); + // 处理成功订单 + void handleSuccessOrder(QMap& order); + // 下单 + bool bet(QMap& order, bool & rebet); + + + // 获取最新赔率 + bool get_order_view(QMap& order);// 重写关键点 Other_order_view + // 确认下单 + bool ack_bet(QMap& order); // Other_bet + // 等待下单结果 + bool wait_bet_result(QMap& order); + + // 获取游戏列表信息 + bool get_game_list(QMap & order); + // 获取所有盘口 + QList> get_game_more(QMap& order); +private: + // 筛选补单 + bool screen_rebet(QMap & order); + // 筛选跟单项目 + bool screen_type(QMap& order); + // 筛选联盟和队伍 + bool screen_team_and_league(QMap& order); + // 筛选盘口变化 + bool screen_con(QMap& order, const QList>& marketCandidates); + + // 筛选赛事盘口 + bool screen_handicap(QMap& order); + + // 筛选注单原始金额 + bool screen_original_gold(QMap& order); + // 筛选注单下单金额 + bool screen_gold(QMap& order); + + // 筛选会员策略 + bool screen_user_policy(QMap& order); + // 筛选比分变化 + bool screen_score(QMap& order); + // 筛选赔率变化 + bool screen_ioratio(QMap& order); + +}; diff --git a/CrownClient/CheckBoxHeaderView.cpp b/CrownClient/CheckBoxHeaderView.cpp new file mode 100644 index 0000000..ed6425a --- /dev/null +++ b/CrownClient/CheckBoxHeaderView.cpp @@ -0,0 +1,74 @@ +#include "CheckBoxHeaderView.h" + +CheckBoxHeaderView::CheckBoxHeaderView(int checkColumnIndex, Qt::Orientation orientation, QWidget* parent) + :QHeaderView(orientation, parent) +{ + m_checkColIdx = checkColumnIndex; + m_isChecked = false; +} + +void CheckBoxHeaderView::setCheckStaus(bool isChecked) +{ + m_isChecked = isChecked; + this->updateSection(m_checkColIdx); +} + +bool CheckBoxHeaderView::getCheckStaus() +{ + return m_isChecked; +} + +/// +/// 绘制区域事件 +/// +/// 画笔 +/// 区域 +/// 索引 +void CheckBoxHeaderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const +{ + // 保存当前状态 + painter->save(); + // 绘制区域 + QHeaderView::paintSection(painter, rect, logicalIndex); + // 恢复状态 + painter->restore(); + + // 判断是否为所选行列 + if (logicalIndex == m_checkColIdx) + { + QStyleOptionButton option; + int width = 10; + + option.rect = QRect((rect.right() - rect.left()) / 2 - width / 2 + rect.left() - 1, (rect.bottom() - rect.top()) / 2 - width / 2 + rect.top() - 1, width, width); + + if (m_isChecked) + { + option.state = QStyle::State_Enabled | QStyle::State_On; + } + else + { + option.state = QStyle::State_Enabled | QStyle::State_Off; + } + + this->style()->drawControl(QStyle::CE_CheckBox, &option, painter); + } + +} + +/// +/// 鼠标按下事件 +/// +/// 事件 +void CheckBoxHeaderView::mousePressEvent(QMouseEvent* event) +{ + if (visualIndexAt(event->pos().x()) == m_checkColIdx) + { + if (m_isChecked) + m_isChecked = false; + else + m_isChecked = true; + this->updateSection(m_checkColIdx); + emit checkStausChange(m_isChecked); + } + QHeaderView::mousePressEvent(event); +} \ No newline at end of file diff --git a/CrownClient/CheckBoxHeaderView.h b/CrownClient/CheckBoxHeaderView.h new file mode 100644 index 0000000..38efd77 --- /dev/null +++ b/CrownClient/CheckBoxHeaderView.h @@ -0,0 +1,27 @@ +#pragma once +#include +#include +#include +#include + +// 参考 https://blog.csdn.net/wj584652425/article/details/125034684 + + +class CheckBoxHeaderView : public QHeaderView +{ + Q_OBJECT +public: + CheckBoxHeaderView(int checkColumnIndex, Qt::Orientation orientation, QWidget* parent = 0); + void setCheckStaus(bool isChecked); + bool getCheckStaus(); +signals: + void checkStausChange(bool); + +protected: + void paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const; + void mousePressEvent(QMouseEvent* event); + +private: + bool m_isChecked; + int m_checkColIdx; +}; \ No newline at end of file diff --git a/CrownClient/ComboBox.cpp b/CrownClient/ComboBox.cpp new file mode 100644 index 0000000..b13ecf7 --- /dev/null +++ b/CrownClient/ComboBox.cpp @@ -0,0 +1,243 @@ +#include "ComboBox.h" +#include +#include + +/// +/// 构造函数 +/// +/// 父类 +ComboBox::ComboBox(QWidget* parent) : QComboBox(parent) +, m_count(0) // 修复:初始化 m_count +{ + // 初始化列表容器 + listWidget = new QListWidget(this); // 修复:设置父对象 + // 设置模型 + this->setModel(listWidget->model()); + // 设置视图 + this->setView(listWidget); + // 清空 + this->clear(); + // 设置可编辑 + this->setEditable(true); + // 设置禁止重复 + this->setDuplicatesEnabled(false); + // 设置插入策略 + this->setInsertPolicy(QComboBox::NoInsert); +} + +/// +/// 添加项目 +/// +/// 文本 +void ComboBox::addItem(const QString& text) +{ + // 检查空内容 + if (text.trimmed().isEmpty()) { + // qDebug() << __FILE__ << __LINE__ << "Cannot add empty text!"; + // this->setToolTip("输入内容不能为空!"); + return; + } + + // 检查重复项(遍历现有项) + for (int i = 0; i < listWidget->count(); i++) { + QListWidgetItem* existingItem = listWidget->item(i); + ComboBoxItem* itemWidget = static_cast(listWidget->itemWidget(existingItem)); + if (itemWidget && text == itemWidget->getLabelText()) { + // qDebug() << "Item already exists:" << text; + // this->setToolTip("内容已存在!"); + return; + } + } + + // 修复:使用动态宽度计算 + int textWidth = fontMetrics().horizontalAdvance(text); + int buttonWidth = 30; // 按钮宽度 + int minWidth = textWidth + buttonWidth + 20; + + // 调整最小宽度 + if (this->minimumWidth() < minWidth) { + this->setMinimumWidth(minWidth); + } + + // 组合框项目 + ComboBoxItem* item = new ComboBoxItem(); + // 设置文本 + item->setLabelText(text); + + // 移除属性 + connect(item, &ComboBoxItem::signalRemoveProperty, this, &ComboBox::slotRemoveProperty); + // 显示点击条目 + connect(item, &ComboBoxItem::signalShowClicked, this, &ComboBox::slotCurrentText); + + // 条目 + QListWidgetItem* list_item = new QListWidgetItem(listWidget); + list_item->setSizeHint(QSize(minWidth, 25)); // 修复:设置合适的大小 + + item->setProperty("count", QString::number(m_count++)); + listWidget->setItemWidget(list_item, item); + + if (this->currentText().isEmpty()) + { + this->setCurrentText(text); + } +} + +/// +/// 添加列表 +/// +/// 列表 +void ComboBox::addItems(const QList& list) +{ + foreach(QString item, list) + { + addItem(item); + } +} + +/* 删除选择的文本,注意此处删除的是listwidget而不是combobox,combobox是一个空的内容 */ +void ComboBox::slotRemoveItem(const QString text) +{ + // qDebug() << "SlotRemoveItem/text = " << text; + for (int i = 0; i < listWidget->count(); i++) + { + QListWidgetItem* item = listWidget->item(i); + ComboBoxItem* clickitem = static_cast(listWidget->itemWidget(item)); + if (!clickitem) continue; + + QString labelText = clickitem->getLabelText(); + if (text == labelText) + { + listWidget->takeItem(i); + delete item; + + // 如果当前显示的文本是被删除的文本,清空显示 + if (this->currentText() == text) { + this->setCurrentText(""); + } + + // 刷新显示 + if (listWidget->count() > 0) + { + this->showPopup(); + } + else + { + this->hidePopup(); + } + break; + } + } +} + +/* 删除选择的属性对应的item,因为文本可能重复,但是设置的属性是唯一的,注意此处删除的是listwidget而不是combobox,combobox是一个空的内容 */ +void ComboBox::slotRemoveProperty(const QString PropertyStr) +{ + // qDebug() << "SlotRemoveProperty/text = " << PropertyStr; + int list_count = listWidget->count(); + for (int i = 0; i < list_count; i++) { + QListWidgetItem* item = listWidget->item(i); + ComboBoxItem* clickitem = static_cast(listWidget->itemWidget(item)); + if (!clickitem) continue; + + QString LabelText = clickitem->property("count").toString(); + if (PropertyStr == LabelText) { + QString itemText = clickitem->getLabelText(); + listWidget->takeItem(i); + delete item; + + // 如果当前显示的文本是被删除的文本,清空显示 + if (this->currentText() == itemText) { + this->setCurrentText(""); + } + + // 刷新显示 + if (listWidget->count() > 0) + { + this->showPopup(); + } + else + { + this->hidePopup(); + } + break; + } + } +} + +/* 设置当前combobox的显示文本 */ +void ComboBox::slotCurrentText(const QString text) +{ + this->setCurrentText(text); + hidePopup(); +} + +/// +/// 键盘释放事件 +/// +/// 事件 +void ComboBox::keyReleaseEvent(QKeyEvent* event) +{ + // 判断是否按下回车 + if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) + { + // 获取当前文本 + QString text = this->currentText(); + if (text.trimmed().isEmpty()) + { + return; + } + + // 清空编辑框文本但不关闭下拉框 + this->setEditText(""); + + // 判断是否过滤重复 + if (this->duplicatesEnabled() == false) + { + // 遍历QListWidget + for (int i = 0; i < listWidget->count(); i++) + { + QListWidgetItem* item = listWidget->item(i); + ComboBoxItem* itemWidget = static_cast(listWidget->itemWidget(item)); + if (!itemWidget) continue; + + QString labelText = itemWidget->getLabelText(); + if (text == labelText) + { + return; + } + } + } + this->addItem(text); + } + else + { + QComboBox::keyReleaseEvent(event); + } +} + +QString ComboBox::item(int index) +{ + if (index < 0 || index >= listWidget->count()) { + return QString(); + } + + QListWidgetItem* item = listWidget->item(index); + ComboBoxItem* itemWidget = static_cast(listWidget->itemWidget(item)); + if (!itemWidget) return QString(); + + return itemWidget->getLabelText(); +} + +QList ComboBox::items() +{ + QList list; + for (int i = 0; i < listWidget->count(); i++) + { + QListWidgetItem* item = listWidget->item(i); + ComboBoxItem* itemWidget = static_cast(listWidget->itemWidget(item)); + if (!itemWidget) continue; + + list.append(itemWidget->getLabelText()); + } + return list; +} \ No newline at end of file diff --git a/CrownClient/ComboBox.h b/CrownClient/ComboBox.h new file mode 100644 index 0000000..5380044 --- /dev/null +++ b/CrownClient/ComboBox.h @@ -0,0 +1,27 @@ +#pragma once +#include +#include +#include +#include +#include "ComboBoxItem.h" + +class ComboBox : public QComboBox +{ + Q_OBJECT +public: + explicit ComboBox(QWidget* parent = nullptr); + void addItem(const QString& text); + void addItems(const QList& list); + QString item(int index); + QList items(); +public slots: + void slotRemoveItem(const QString text); + void slotRemoveProperty(const QString PropertyStr); + void slotCurrentText(const QString text); +protected: + void keyReleaseEvent(QKeyEvent* event); +private: + QListWidget* listWidget; + int m_count; +}; + diff --git a/CrownClient/ComboBoxItem.cpp b/CrownClient/ComboBoxItem.cpp new file mode 100644 index 0000000..80bd1de --- /dev/null +++ b/CrownClient/ComboBoxItem.cpp @@ -0,0 +1,106 @@ +#include "ComboBoxItem.h" + +/// +/// 构造函数 +/// +/// 父类 +ComboBoxItem::ComboBoxItem(QWidget* parent) : QWidget(parent) +, m_mousePress(false) +, painter(nullptr) +{ + m_label = new QLabel(this); + m_button = new QPushButton(this); + + // 修复:正确创建和绘制叉号图标 + QPixmap pixmap(16, 16); + pixmap.fill(Qt::transparent); + + QPainter painter(&pixmap); + painter.setRenderHint(QPainter::Antialiasing, true); + QPen pen(Qt::black); + pen.setWidth(2); + painter.setPen(pen); + + // 绘制叉号 + painter.drawLine(4, 4, 12, 12); + painter.drawLine(12, 4, 4, 12); + painter.end(); + + // 设置按钮图片 + m_button->setIcon(QIcon(pixmap)); + m_button->setIconSize(QSize(12, 12)); + m_button->setFixedSize(20, 20); + // 设置风格 + m_button->setStyleSheet("QPushButton { border: none; background: transparent; }" + "QPushButton:hover { background: rgba(200, 200, 200, 100); border-radius: 3px; }"); + + // 点击事件 + connect(m_button, &QPushButton::clicked, [this] { + // 删除选项 + emit signalRemoveClicked(m_label->text()); + // 删除属性 + emit signalRemoveProperty(property("count").toString()); + }); + + // 水平布局 + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(5, 2, 5, 2); + layout->setSpacing(5); + + // 标签 + layout->addWidget(m_label); + // 弹簧 + layout->addStretch(); + // 按钮 + layout->addWidget(m_button); + + setLayout(layout); + setFixedHeight(25); // 修复:固定高度 +} + +/// +/// 设置项目文本 +/// +/// 文本 +void ComboBoxItem::setLabelText(QString text) +{ + m_label->setText(text); +} + +/// +/// 获取当前项目文本 +/// +/// 文本 +QString ComboBoxItem::getLabelText() +{ + return m_label->text(); +} + +/// +/// 鼠标按下事件 +/// +/// 事件 +void ComboBoxItem::mousePressEvent(QMouseEvent* event) +{ + if (event->button() == Qt::LeftButton) + { + m_mousePress = true; + } + QWidget::mousePressEvent(event); // 修复:调用父类事件 +} + +/// +/// 鼠标释放事件 +/// +/// 事件 +void ComboBoxItem::mouseReleaseEvent(QMouseEvent* event) +{ + if (m_mousePress && rect().contains(event->pos())) + { + // 发送信号 + qDebug() << "按下:" << m_label->text(); + emit signalShowClicked(m_label->text()); + } + m_mousePress = false; + QWidget::mouseReleaseEvent(event); // 修复:调用父类事件 +} \ No newline at end of file diff --git a/CrownClient/ComboBoxItem.h b/CrownClient/ComboBoxItem.h new file mode 100644 index 0000000..29edfea --- /dev/null +++ b/CrownClient/ComboBoxItem.h @@ -0,0 +1,31 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include + +class ComboBoxItem : public QWidget +{ + Q_OBJECT +public: + explicit ComboBoxItem(QWidget* parent = nullptr); + void setLabelText(QString text); + QString getLabelText(); +signals: + void signalRemoveClicked(const QString& text); + void signalRemoveProperty(const QString& text); + void signalShowClicked(const QString& text); +protected: + void mousePressEvent(QMouseEvent* event); + void mouseReleaseEvent(QMouseEvent* event); +private: + bool m_mousePress; + QPushButton* m_button; + QLabel* m_label; + QPixmap* m_pixmap; + QPainter* painter; + +}; diff --git a/CrownClient/Config.cpp b/CrownClient/Config.cpp new file mode 100644 index 0000000..690503e --- /dev/null +++ b/CrownClient/Config.cpp @@ -0,0 +1,5096 @@ +#include "Config.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "Global.h" +#include "Utils.h" + +Config::Config() +{ + + int number = Utils::instance().get_number_of_application_name(); + + // 确保目录存在 + + QString dataDir = QDir::homePath() + "/AppData/Roaming" + "/crown/"; + QDir dir(dataDir); + if (!dir.exists()) { + dir.mkpath("."); // 递归创建目录 + } + + QString setting_path = QDir::homePath() + "/AppData/Roaming" + QString("/crown/settings%1.ini").arg(number); + QString db_path = QDir::homePath() + "/AppData/Roaming" + QString("/crown/client%1.db").arg(number); + + + m_settings = new QSettings(setting_path, QSettings::IniFormat); + //qDebug() << QDir::homePath() + "/AppData/Roaming"; + //qDebug() << "数据库路径:"< testOrder = { + {"tid", "20520256499"}, + {"betDateTime", "2024-10-02 14:41:17"}, + /*{"acceptDateTime", "2024-10-02 14:59:41"},*/ + {"username", "dbo1abb123"}, + {"projectName", "足球滚球全场"}, + {"type", "(滚球) 让球"}, + {"league", "俄罗斯杯"}, + {"team_h", "格罗兹尼艾哈迈德"}, + {"team_c", "克拉斯诺达尔"}, + {"team_bet", "格罗兹尼艾哈迈德"}, // team_bet + {"handicap", "+0.5"}, + {"odds", "0.97"}, + {"gold", "50.0"}, + {"gtype", "FT"}, + {"session", "RB"}, + {"wtype", "RE"}, + {"rtype", "REH"}, + {"ptype", ""}, + {"rtypeName", "足球滚球全场"}, + {"gid", "7312853"}, + {"reason", "会员过滤注单"} + }; + //testOrder["acceptDateTime"] = QDateTime::currentDateTime().addSecs(-43200).toString("yyyy-MM-dd hh:mm:ss"); + //qDebug() << "测试时间:" << testOrder["acceptDateTime"]; + //if (testOrder["acceptDateTime"] == "") + //{ + // QMessageBox::information(nullptr, "BBB", "BBB"); + //} + //// 调用插入 + //this->add_accept_order(testOrder); + //this->add_screen_order(testOrder); + //this->add_success_order(testOrder); + //this->add_failed_orders(testOrder); + //this->add_rebet_order(testOrder); + +} + + +Config::~Config() +{ + // 考虑类销毁自动释放 + // m_db.close(); +} + + +QString Config::toJson(QList> list) +{ + QList>::iterator iter; + QJsonArray jsonArray; + for (iter = list.begin(); iter != list.end(); iter++) + { + QMap map = *iter; + QJsonObject dataJson; + for (int i = 0; i < map.keys().count(); i++) + { + dataJson.insert(map.keys()[i], map.value(map.keys()[i])); + } + + jsonArray.append(dataJson); + } + return QString(QJsonDocument(jsonArray).toJson()); +} + +QString Config::toJson(QList list) +{ + QList::iterator iter; + QJsonArray jsonArray; + for (iter = list.begin(); iter != list.end(); iter++) + { + QString string = *iter; + jsonArray.append(string); + } + return QString(QJsonDocument(jsonArray).toJson()); +} + +QList> Config::toMapList(QString data) +{ + QList> list; + QJsonArray jsonArray = QJsonDocument::fromJson(data.toStdString().c_str()).array(); + for (int i = 0; i < jsonArray.count(); i++) + { + QMap map; + map.clear(); + for (int j = 0; j < jsonArray[i].toObject().keys().count(); j++) + { + ; + QString key = jsonArray[i].toObject().keys().at(j); + map[key] = jsonArray[i].toObject()[key].toString(); + } + // qDebug() << map; + list.append(map); + } + + return list; +} + +QList Config::toStringList(QString data) +{ + QList list; + + QJsonArray jsonArray = QJsonDocument::fromJson(data.toStdString().c_str()).array(); + + for (int i = 0; i < jsonArray.count(); i++) + { + list.append(jsonArray[i].toString()); + } + + return list; +} + + + +QList> Config::betProject() +{ + m_mutex.lock(); + QString betProjectData = m_settings->value("Client/BetProject").toString(); + + // 如果配置为空,则创建默认全选配置 + if (betProjectData.isEmpty()) { + QList> defaultList; + + // 9行 (0-8) + for (int row = 0; row < 9; row++) { + // 15列 (0-14) + for (int col = 0; col < 15; col++) { + // 跳过第一列(0)和第二列(1),因为它们不是复选框 + if (col == 0 || col == 1) { + continue; + } + + // 跳过特殊行不需要的列 (6-8行, 第8列) + if ((row == 6 || row == 7 || row == 8) && col == 8) { + continue; + } + + QMap project; + project["ROW"] = QString::number(row); + project["COLUMN"] = QString::number(col); + project["ENABLE"] = "TRUE"; // 默认全部勾选 + + // 添加项目类型映射 + //-----------------------滚球---------------------------- + // 足球滚球全场让球 + if (row == 0 && col == 2) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "让球"; + project["ORDER_TYPE"] = "让球"; + } + // 足球滚球全场受让 + else if (row == 0 && col == 3) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "让球"; + project["ORDER_TYPE"] = "受让"; + } + // 足球滚球全场得分大 + else if (row == 0 && col == 4) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "大小"; + project["ORDER_TYPE"] = "大"; + } + // 足球滚球全场得分小 + else if (row == 0 && col == 5) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "大小"; + project["ORDER_TYPE"] = "小"; + } + // 足球滚球全场独赢主 + else if (row == 0 && col == 6) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢主"; + } + // 足球滚球全场独赢客 + else if (row == 0 && col == 7) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢客"; + } + // 足球滚球全场独赢和 + else if (row == 0 && col == 8) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢和"; + } + // 足球滚球全场单 + else if (row == 0 && col == 9) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "单双"; + project["ORDER_TYPE"] = "单"; + } + // 足球滚球全场双 + else if (row == 0 && col == 10) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "单双"; + project["ORDER_TYPE"] = "双"; + } + // 足球滚球全场主队大 + else if (row == 0 && col == 11) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "主大小"; + project["ORDER_TYPE"] = "主队大"; + } + // 足球滚球全场主队小 + else if (row == 0 && col == 12) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "主大小"; + project["ORDER_TYPE"] = "主队小"; + } + // 足球滚球全场客队大 + else if (row == 0 && col == 13) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "客大小"; + project["ORDER_TYPE"] = "客队大"; + } + // 足球滚球全场客队小 + else if (row == 0 && col == 14) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "客大小"; + project["ORDER_TYPE"] = "客队小"; + } + // 足球滚球上半场让球 + else if (row == 1 && col == 2) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "让球"; + project["ORDER_TYPE"] = "让球"; + } + // 足球滚球上半场受让 + else if (row == 1 && col == 3) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "让球"; + project["ORDER_TYPE"] = "受让"; + } + // 足球滚球上半场得分大 + else if (row == 1 && col == 4) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "大小"; + project["ORDER_TYPE"] = "大"; + } + // 足球滚球上半场得分小 + else if (row == 1 && col == 5) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "大小"; + project["ORDER_TYPE"] = "小"; + } + // 足球滚球上半场独赢主 + else if (row == 1 && col == 6) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢主"; + } + // 足球滚球上半场独赢客 + else if (row == 1 && col == 7) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢客"; + } + // 足球滚球上半场独赢和 + else if (row == 1 && col == 8) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢和"; + } + // 足球滚球上半场单 + else if (row == 1 && col == 9) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "单双"; + project["ORDER_TYPE"] = "单"; + } + // 足球滚球上半场双 + else if (row == 1 && col == 10) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "单双"; + project["ORDER_TYPE"] = "双"; + } + // 足球滚球上半场主队大 + else if (row == 1 && col == 11) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "主大小"; + project["ORDER_TYPE"] = "主队大"; + } + // 足球滚球上半场主队小 + else if (row == 1 && col == 12) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "主大小"; + project["ORDER_TYPE"] = "主队小"; + } + // 足球滚球上半场客队大 + else if (row == 1 && col == 13) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "客大小"; + project["ORDER_TYPE"] = "客队大"; + } + // 足球滚球上半场客队小 + else if (row == 1 && col == 14) { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "客大小"; + project["ORDER_TYPE"] = "客队小"; + } + //------------------------足球今日---------------- + // 足球今日全场让球 + else if (row == 2 && col == 2) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "让球"; + project["ORDER_TYPE"] = "让球"; + } + // 足球今日全场受让 + else if (row == 2 && col == 3) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "让球"; + project["ORDER_TYPE"] = "受让"; + } + // 足球今日全场得分大 + else if (row == 2 && col == 4) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "大小"; + project["ORDER_TYPE"] = "大"; + } + // 足球今日全场得分小 + else if (row == 2 && col == 5) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "大小"; + project["ORDER_TYPE"] = "小"; + } + // 足球今日全场独赢主 + else if (row == 2 && col == 6) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢主"; + } + // 足球今日全场独赢客 + else if (row == 2 && col == 7) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢客"; + } + // 足球今日全场独赢和 + else if (row == 2 && col == 8) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢和"; + } + // 足球今日全场单 + else if (row == 2 && col == 9) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "单双"; + project["ORDER_TYPE"] = "单"; + } + // 足球今日全场双 + else if (row == 2 && col == 10) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "单双"; + project["ORDER_TYPE"] = "双"; + } + // 足球今日全场主队大 + else if (row == 2 && col == 11) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "主大小"; + project["ORDER_TYPE"] = "主队大"; + } + // 足球今日全场主队小 + else if (row == 2 && col == 12) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "主大小"; + project["ORDER_TYPE"] = "主队小"; + } + // 足球今日全场客队大 + else if (row == 2 && col == 13) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "客大小"; + project["ORDER_TYPE"] = "客队大"; + } + // 足球今日全场客队小 + else if (row == 2 && col == 14) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "客大小"; + project["ORDER_TYPE"] = "客队小"; + } + // 足球今日上半场让球 + else if (row == 3 && col == 2) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "让球"; + project["ORDER_TYPE"] = "让球"; + } + // 足球今日上半场受让 + else if (row == 3 && col == 3) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "让球"; + project["ORDER_TYPE"] = "受让"; + } + // 足球今日上半场得分大 + else if (row == 3 && col == 4) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "大小"; + project["ORDER_TYPE"] = "大"; + } + // 足球今日上半场得分小 + else if (row == 3 && col == 5) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "大小"; + project["ORDER_TYPE"] = "小"; + } + // 足球今日上半场独赢主 + else if (row == 3 && col == 6) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢主"; + } + // 足球今日上半场独赢客 + else if (row == 3 && col == 7) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢客"; + } + // 足球今日上半场独赢和 + else if (row == 3 && col == 8) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢和"; + } + // 足球今日上半场单 + else if (row == 3 && col == 9) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "单双"; + project["ORDER_TYPE"] = "单"; + } + // 足球今日上半场双 + else if (row == 3 && col == 10) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "单双"; + project["ORDER_TYPE"] = "双"; + } + // 足球今日上半场主队大 + else if (row == 3 && col == 11) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "主大小"; + project["ORDER_TYPE"] = "客队大"; + } + // 足球今日上半场主队小 + else if (row == 3 && col == 12) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "主大小"; + project["ORDER_TYPE"] = "客队小"; + } + // 足球今日上半场客队大 + else if (row == 3 && col == 13) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "客大小"; + project["ORDER_TYPE"] = "客队大"; + } + // 足球今日上半场客队小 + else if (row == 3 && col == 14) { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "客大小"; + project["ORDER_TYPE"] = "客队小"; + } + // ----------------足球早盘------------------- + // 足球早盘全场让球 + else if (row == 4 && col == 2) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "让球"; + project["ORDER_TYPE"] = "让球"; + } + // 足球早盘全场受让 + else if (row == 4 && col == 3) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "让球"; + project["ORDER_TYPE"] = "受让"; + } + // 足球早盘全场得分大 + else if (row == 4 && col == 4) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "大小"; + project["ORDER_TYPE"] = "大"; + } + // 足球早盘全场得分小 + else if (row == 4 && col == 5) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "大小"; + project["ORDER_TYPE"] = "小"; + } + // 足球早盘全场独赢主 + else if (row == 4 && col == 6) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢主"; + } + // 足球早盘全场独赢客 + else if (row == 4 && col == 7) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢客"; + } + // 足球早盘全场独赢和 + else if (row == 4 && col == 8) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢和"; + } + // 足球早盘全场单 + else if (row == 4 && col == 9) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "单双"; + project["ORDER_TYPE"] = "单"; + } + // 足球早盘全场双 + else if (row == 4 && col == 10) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "单双"; + project["ORDER_TYPE"] = "双"; + } + // 足球早盘全场主队大 + else if (row == 4 && col == 11) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "主大小"; + project["ORDER_TYPE"] = "主队大"; + } + // 足球早盘全场主队小 + else if (row == 4 && col == 12) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "主大小"; + project["ORDER_TYPE"] = "主队小"; + } + // 足球早盘全场客队大 + else if (row == 4 && col == 13) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "客大小"; + project["ORDER_TYPE"] = "客队大"; + } + // 足球早盘全场客队小 + else if (row == 4 && col == 14) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "客大小"; + project["ORDER_TYPE"] = "客队小"; + } + // 足球早盘上半场让球 + else if (row == 5 && col == 2) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "让球"; + project["ORDER_TYPE"] = "让球"; + } + // 足球早盘上半场受让 + else if (row == 5 && col == 3) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "让球"; + project["ORDER_TYPE"] = "受让"; + } + // 足球早盘上半场得分大 + else if (row == 5 && col == 4) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "大小"; + project["ORDER_TYPE"] = "大"; + } + // 足球早盘上半场得分小 + else if (row == 5 && col == 5) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "大小"; + project["ORDER_TYPE"] = "小"; + } + // 足球早盘上半场独赢主 + else if (row == 5 && col == 6) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢主"; + } + // 足球早盘上半场独赢客 + else if (row == 5 && col == 7) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢客"; + } + // 足球早盘上半场独赢和 + else if (row == 5 && col == 8) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢和"; + } + // 足球早盘上半场单 + else if (row == 5 && col == 9) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "单双"; + project["ORDER_TYPE"] = "单"; + } + // 足球早盘上半场双 + else if (row == 5 && col == 10) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "单双"; + project["ORDER_TYPE"] = "双"; + } + // 足球早盘上半场主队大 + else if (row == 5 && col == 11) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "主大小"; + project["ORDER_TYPE"] = "主队大"; + } + // 足球早盘上半场主队小 + else if (row == 5 && col == 12) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "主大小"; + project["ORDER_TYPE"] = "主队小"; + } + // 足球早盘上半场客队大 + else if (row == 5 && col == 13) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "客大小"; + project["ORDER_TYPE"] = "客队大"; + } + // 足球早盘上半场客队小 + else if (row == 5 && col == 14) { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "客大小"; + project["ORDER_TYPE"] = "客队小"; + } + //------------------篮球滚球------------------ + // 篮球滚球全场让球 + else if (row == 6 && col == 2) { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "让球"; + project["ORDER_TYPE"] = "让球"; + } + // 篮球滚球全场受让 + else if (row == 6 && col == 3) { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "让球"; + project["ORDER_TYPE"] = "受让"; + } + // 篮球滚球全场得分大 + else if (row == 6 && col == 4) { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "大小"; + project["ORDER_TYPE"] = "大"; + } + // 篮球滚球全场得分小 + else if (row == 6 && col == 5) { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "大小"; + project["ORDER_TYPE"] = "小"; + } + // 篮球滚球全场独赢主 + else if (row == 6 && col == 6) { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢主"; + } + // 篮球滚球全场独赢客 + else if (row == 6 && col == 7) { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢客"; + } + // 篮球滚球全场单 + else if (row == 6 && col == 9) { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "单双"; + project["ORDER_TYPE"] = "单"; + } + // 篮球滚球全场双 + else if (row == 6 && col == 10) { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "单双"; + project["ORDER_TYPE"] = "双"; + } + // 篮球滚球全场主队大 + else if (row == 6 && col == 11) { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "主大小"; + project["ORDER_TYPE"] = "主队大"; + } + // 篮球滚球全场主队小 + else if (row == 6 && col == 12) { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "主大小"; + project["ORDER_TYPE"] = "主队小"; + } + // 篮球滚球全场客队大 + else if (row == 6 && col == 13) { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "客大小"; + project["ORDER_TYPE"] = "客队大"; + } + // 篮球滚球全场客队小 + else if (row == 6 && col == 14) { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "客大小"; + project["ORDER_TYPE"] = "客队小"; + } + //------------------篮球今日------------------ + // 篮球今日全场让球 + else if (row == 7 && col == 2) { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "让球"; + project["ORDER_TYPE"] = "让球"; + } + // 篮球今日全场受让 + else if (row == 7 && col == 3) { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "让球"; + project["ORDER_TYPE"] = "受让"; + } + // 篮球今日全场得分大 + else if (row == 7 && col == 4) { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "大小"; + project["ORDER_TYPE"] = "大"; + } + // 篮球今日全场得分小 + else if (row == 7 && col == 5) { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "大小"; + project["ORDER_TYPE"] = "小"; + } + // 篮球今日全场独赢主 + else if (row == 7 && col == 6) { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢主"; + } + // 篮球今日全场独赢客 + else if (row == 7 && col == 7) { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢客"; + } + // 篮球今日全场独赢和 + //else if (row == 7 && col == 8) { + // project["GT"] = "篮球"; + // project["SESSION"] = "今日"; + // project["STAGE"] = "全场"; + // project["WAGERS_TYPE"] = "独赢"; + // project["ORDER_TYPE"] = "独赢和"; + //} + // 篮球今日全场单 + else if (row == 7 && col == 9) { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "单双"; + project["ORDER_TYPE"] = "单"; + } + // 篮球今日全场双 + else if (row == 7 && col == 10) { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "单双"; + project["ORDER_TYPE"] = "双"; + } + // 篮球今日全场主队大 + else if (row == 7 && col == 11) { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "主大小"; + project["ORDER_TYPE"] = "主队大"; + } + // 篮球今日全场主队小 + else if (row == 7 && col == 12) { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "主大小"; + project["ORDER_TYPE"] = "主队小"; + } + // 篮球今日全场客队大 + else if (row == 7 && col == 13) { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "客大小"; + project["ORDER_TYPE"] = "客队大"; + } + // 篮球今日全场客队小 + else if (row == 7 && col == 14) { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "客大小"; + project["ORDER_TYPE"] = "客队小"; + } + //------------------篮球早盘------------------ + // 篮球早盘全场让球 + else if (row == 8 && col == 2) { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "让球"; + project["ORDER_TYPE"] = "让球"; + } + // 篮球早盘全场受让 + else if (row == 8 && col == 3) { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "让球"; + project["ORDER_TYPE"] = "受让"; + } + // 篮球早盘全场得分大 + else if (row == 8 && col == 4) { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "大小"; + project["ORDER_TYPE"] = "大"; + } + // 篮球早盘全场得分小 + else if (row == 8 && col == 5) { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "大小"; + project["ORDER_TYPE"] = "小"; + } + // 篮球早盘全场独赢主 + else if (row == 8 && col == 6) { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢主"; + } + // 篮球早盘全场独赢客 + else if (row == 8 && col == 7) { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "独赢"; + project["ORDER_TYPE"] = "独赢客"; + } + // 篮球早盘全场独赢和 + //else if (row == 8 && col == 8) { + // project["GT"] = "篮球"; + // project["SESSION"] = "早盘"; + // project["STAGE"] = "全部"; + // project["WAGERS_TYPE"] = "独赢"; + // project["ORDER_TYPE"] = "独赢和"; + //} + // 篮球早盘全场单 + else if (row == 8 && col == 9) { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "单双"; + project["ORDER_TYPE"] = "单"; + } + // 篮球早盘全场双 + else if (row == 8 && col == 10) { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "单双"; + project["ORDER_TYPE"] = "双"; + } + // 篮球早盘全场主队大 + else if (row == 8 && col == 11) { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "主大小"; + project["ORDER_TYPE"] = "主队大"; + } + // 篮球早盘全场主队小 + else if (row == 8 && col == 12) { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "主大小"; + project["ORDER_TYPE"] = "主队小"; + } + // 篮球早盘全场客队大 + else if (row == 8 && col == 13) { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "客大小"; + project["ORDER_TYPE"] = "客队大"; + } + // 篮球早盘全场客队小 + else if (row == 8 && col == 14) { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "客大小"; + project["ORDER_TYPE"] = "客队小"; + } + + defaultList.append(project); + } + } + + // 将默认配置转换为JSON并保存 + QJsonArray jsonArray; + for (const auto &map : defaultList) { + QJsonObject jsonObj; + for (auto it = map.begin(); it != map.end(); ++it) { + jsonObj[it.key()] = it.value(); + } + jsonArray.append(jsonObj); + } + + QJsonDocument doc(jsonArray); + betProjectData = doc.toJson(QJsonDocument::Compact); + m_settings->setValue("Client/BetProject", betProjectData); + } + + QList> list = toMapList(betProjectData); + m_mutex.unlock(); + return list; +} + +QString Config::verifyUsername() +{ + m_mutex.lock(); + QString username = m_settings->value("Client/VerifyUsername").toString(); + m_mutex.unlock(); + return username; +} + +void Config::setVerifyUsername(QString username) +{ + m_mutex.lock(); + m_settings->setValue("Client/VerifyUsername", QVariant::fromValue(username)); + m_mutex.unlock(); +} + +QString Config::verifyPassword() +{ + m_mutex.lock(); + QString password = m_settings->value("Client/VerifyPassword").toString(); + m_mutex.unlock(); + return password; +} + +void Config::setVerifyPassword(QString password) +{ + m_mutex.lock(); + m_settings->setValue("Client/VerifyPassword", QVariant::fromValue(password)); + m_mutex.unlock(); +} + +bool Config::autoLogin() +{ + m_mutex.lock(); + bool autoLogin = m_settings->value("Client/AutoLogin").toBool(); + m_mutex.unlock(); + return autoLogin; +} + +void Config::setAutoLogin(bool autoLogin) +{ + m_mutex.lock(); + m_settings->setValue("Client/AutoLogin", QVariant::fromValue(autoLogin)); + m_mutex.unlock(); +} + +bool Config::crownTime() +{ + m_mutex.lock(); + bool crownTime = m_settings->value("Server/CrownTime", false).toBool(); + m_mutex.unlock(); + return crownTime; +} + +void Config::setCrownTime(bool crownTime) +{ + m_mutex.lock(); + m_settings->setValue("Server/CrownTime", QVariant::fromValue(crownTime)); + m_mutex.unlock(); +} + +QDateTime Config::formatDateTime(QDateTime dateTime) +{ + m_mutex.lock(); + bool crownTime = m_settings->value("Server/CrownTime", false).toBool(); + m_mutex.unlock(); + if (crownTime) + { + return dateTime.addSecs(-43200); + } + return dateTime; +} + +bool Config::screenDateTimeEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/ScreenDateTimeEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setScreenDateTimeEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/ScreenDateTimeEnable", enable); + m_mutex.unlock(); +} + +QString Config::screenDateTime() +{ + m_mutex.lock(); + QString dateTime = m_settings->value("Client/ScreenDateTime", QDateTime::currentDateTime()).toString(); + m_mutex.unlock(); + return dateTime; +} + +void Config::setScreenDateTime(QString dateTime) +{ + m_mutex.lock(); + m_settings->setValue("Client/ScreenDateTime", dateTime); + m_mutex.unlock(); +} + +QList Config::client_url_list() +{ + m_mutex.lock(); + QList list = toStringList(m_settings->value("Server/UserUrlList").toString()); + + if (list.isEmpty()) + { + list.append("https://mos055.com/"); + } + m_mutex.unlock(); + return list; +} + +void Config::set_client_url_list(QList list) +{ + m_mutex.lock(); + m_settings->setValue("Server/UserUrlList", toJson(list)); + m_mutex.unlock(); +} + +QString Config::client_url() +{ + m_mutex.lock(); + QString default_url = m_settings->value("Client/Default_Client_URL", "https://mos055.com/").toString(); + m_mutex.unlock(); + return default_url; +} + +void Config::set_client_url(QString url) +{ + m_mutex.lock(); + m_settings->setValue("Client/Default_Client_URL", url); + m_mutex.unlock(); +} + +QList> Config::servers() +{ + m_mutex.lock(); + QString serversJson = m_settings->value("Client/Servers").toString(); + + // 如果配置为空,创建默认服务器列表 + if (serversJson.isEmpty()) { + QList> defaultServers; + + // 创建5个默认服务器配置 + for (int i = 0; i < 5; i++) { + QMap server; + server["enable"] = "true"; // 默认启用第一个服务器 + server["ip"] = "127.0.0.1"; + server["port"] = QString::number(11111 + (i * 11111)); + server["connectPassword"] = "88888"; + server["readTimes"] = "0"; + server["dataCount"] = "0"; + defaultServers.append(server); + } + m_mutex.unlock(); + return defaultServers; + } + + QList> list = toMapList(serversJson); + m_mutex.unlock(); + return list; +} + +void Config::setServers(QList> servers) +{ + m_mutex.lock(); + m_settings->setValue("Client/Servers", toJson(servers)); + m_mutex.unlock(); +} + +QString Config::clientSign() +{ + m_mutex.lock(); + QString sign = m_settings->value("Client/ClientSign", QUuid::createUuid().toString().remove("{").remove("}").remove("-").right(10)).toString(); + m_mutex.unlock(); + return sign; +} + +void Config::setClientSign(QString sign) +{ + m_mutex.lock(); + m_settings->setValue("Client/ClientSign", sign); + m_mutex.unlock(); +} + +int Config::readCount() +{ + m_mutex.lock(); + int count = m_settings->value("Client/ReadCount", 10).toInt(); + m_mutex.unlock(); + return count; +} + +void Config::setReadCount(int count) +{ + m_mutex.lock(); + m_settings->setValue("Client/ReadCount", count); + m_mutex.unlock(); +} + +int Config::readSleep() +{ + m_mutex.lock(); + int sleep = m_settings->value("Client/ReadSleep", 1).toInt(); + m_mutex.unlock(); + return sleep; +} + +void Config::setReadSleep(int sleep) +{ + m_mutex.lock(); + m_settings->setValue("Client/ReadSleep", sleep); + m_mutex.unlock(); +} + +bool Config::autoConnect() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/AutoConnect", true).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setAutoConnect(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/AutoConnect", enable); + m_mutex.unlock(); +} + + + +QString Config::username() +{ + m_mutex.lock(); + QString username = m_settings->value("Client/Username").toString(); + m_mutex.unlock(); + return username; +} + +void Config::setUsername(QString username) +{ + m_mutex.lock(); + m_settings->setValue("Client/Username", username); + m_mutex.unlock(); +} + + +QString Config::password() +{ + m_mutex.lock(); + QString password = m_settings->value("Client/Password").toString(); + m_mutex.unlock(); + return password; +} + +void Config::setPassword(QString password) +{ + m_mutex.lock(); + m_settings->setValue("Client/Password", password); + m_mutex.unlock(); +} + + + +QList> Config::usersList() +{ + m_mutex.lock(); + QList> list = toMapList(m_settings->value("Client/UsersList").toString()); + m_mutex.unlock(); + return list; +} + +void Config::setUsersList(QList> list) +{ + m_mutex.lock(); + m_settings->setValue("Client/UsersList", toJson(list)); + m_mutex.unlock(); +} + + +void Config::add_accept_order(QMap order) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + // 兜底:若未传接收时间,则用“皇冠时间=本地-12h” + QString acceptDt = order.value("ACCEPT_DATETIME"); + if (acceptDt.isEmpty()) { + acceptDt = QDateTime::currentDateTime().addSecs(-43200).toString("yyyy-MM-dd HH:mm:ss"); + } + + query.prepare( + "INSERT OR IGNORE INTO accept_orders(" + "TID, DATETIME, ACCEPT_DATETIME, NAME0, GT, WAGERS_TYPE, LEAGUE, " + "TEAM_H, TEAM_C, ORDER_TYPE, ORDER_CON, SCORE, IORATIO, GOLD, SRV_IP, " + "SESSION, STAGE, G_TIME, NUM_H, NUM_C, ODDF_TYPE, BET_TYPE" + ") VALUES(" + ":TID, :DATETIME, :ACCEPT_DATETIME, :NAME0, :GT, :WAGERS_TYPE, :LEAGUE, " + ":TEAM_H, :TEAM_C, :ORDER_TYPE, :ORDER_CON, :SCORE, :IORATIO, :GOLD, :SRV_IP, " + ":SESSION, :STAGE, :G_TIME, :NUM_H, :NUM_C, :ODDF_TYPE, :BET_TYPE)" + ); + + query.bindValue(":TID", order.value("TID")); + query.bindValue(":DATETIME", order.value("DATETIME")); + query.bindValue(":ACCEPT_DATETIME", acceptDt); + query.bindValue(":NAME0", order.value("NAME0")); + query.bindValue(":GT", order.value("GT")); + query.bindValue(":WAGERS_TYPE", order.value("WAGERS_TYPE")); + query.bindValue(":LEAGUE", order.value("LEAGUE")); + query.bindValue(":TEAM_H", order.value("TEAM_H")); + query.bindValue(":TEAM_C", order.value("TEAM_C")); + query.bindValue(":ORDER_TYPE", order.value("ORDER_TYPE")); + query.bindValue(":ORDER_CON", order.value("ORDER_CON")); + query.bindValue(":SCORE", order.value("SCORE")); + query.bindValue(":IORATIO", order.value("IORATIO").toDouble()); + query.bindValue(":GOLD", order.value("GOLD").toDouble()); + query.bindValue(":SRV_IP", order.value("SRV_IP")); + query.bindValue(":SESSION", order.value("SESSION")); + query.bindValue(":STAGE", order.value("STAGE")); + query.bindValue(":G_TIME", order.value("G_TIME")); + query.bindValue(":NUM_H", order.value("NUM_H")); + query.bindValue(":NUM_C", order.value("NUM_C")); + query.bindValue(":ODDF_TYPE", order.value("ODDF_TYPE")); + query.bindValue(":BET_TYPE", order.value("BET_TYPE")); + + if (!query.exec()) { + qDebug() << "[数据库] 接收注单插入失败:" << query.lastError(); + } +} + +QList> Config::get_accept_orders() +{ + QMutexLocker locker(&m_mutex); + QList> ordersList; + + QSqlQuery query(m_db); + QString sql = + "SELECT " + "TID, DATETIME, ACCEPT_DATETIME, NAME0, GT, WAGERS_TYPE, LEAGUE, " + "TEAM_H, TEAM_C, ORDER_TYPE, ORDER_CON, SCORE, IORATIO, GOLD, SRV_IP, " + "SESSION, STAGE, G_TIME, NUM_H, NUM_C, ODDF_TYPE, BET_TYPE " + "FROM accept_orders ORDER BY DATETIME DESC"; + + if (!query.exec(sql)) { + qDebug() << "[数据库] 查询接收注单失败:" << query.lastError(); + return ordersList; + } + + while (query.next()) { + QMap order; + order["TID"] = query.value("TID").toString(); + order["DATETIME"] = query.value("DATETIME").toString(); + order["ACCEPT_DATETIME"] = query.value("ACCEPT_DATETIME").toString(); + order["NAME0"] = query.value("NAME0").toString(); + order["GT"] = query.value("GT").toString(); + order["WAGERS_TYPE"] = query.value("WAGERS_TYPE").toString(); + order["LEAGUE"] = query.value("LEAGUE").toString(); + order["TEAM_H"] = query.value("TEAM_H").toString(); + order["TEAM_C"] = query.value("TEAM_C").toString(); + order["ORDER_TYPE"] = query.value("ORDER_TYPE").toString(); + order["ORDER_CON"] = query.value("ORDER_CON").toString(); + order["SCORE"] = query.value("SCORE").toString(); + order["IORATIO"] = query.value("IORATIO").toString(); + order["GOLD"] = query.value("GOLD").toString(); + order["SRV_IP"] = query.value("SRV_IP").toString(); + order["SESSION"] = query.value("SESSION").toString(); + order["STAGE"] = query.value("STAGE").toString(); + order["G_TIME"] = query.value("G_TIME").toString(); + order["NUM_H"] = query.value("NUM_H").toString(); + order["NUM_C"] = query.value("NUM_C").toString(); + order["ODDF_TYPE"] = query.value("ODDF_TYPE").toString(); + order["BET_TYPE"] = query.value("BET_TYPE").toString(); + ordersList.append(order); + } + + return ordersList; +} + +void Config::add_screen_order(QMap order) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + QString acceptDt = order.value("ACCEPT_DATETIME"); + if (acceptDt.isEmpty()) { + acceptDt = QDateTime::currentDateTime().addSecs(-43200).toString("yyyy-MM-dd HH:mm:ss"); + } + + query.prepare( + "INSERT INTO screen_orders(" + "TID, DATETIME, ACCEPT_DATETIME, NAME0, GT, WAGERS_TYPE, LEAGUE, " + "TEAM_H, TEAM_C, ORDER_TYPE, ORDER_CON, SCORE, IORATIO, GOLD, SRV_IP, " + "SESSION, STAGE, G_TIME, NUM_H, NUM_C, ODDF_TYPE, BET_TYPE, REASON" + ") VALUES(" + ":TID, :DATETIME, :ACCEPT_DATETIME, :NAME0, :GT, :WAGERS_TYPE, :LEAGUE, " + ":TEAM_H, :TEAM_C, :ORDER_TYPE, :ORDER_CON, :SCORE, :IORATIO, :GOLD, :SRV_IP, " + ":SESSION, :STAGE, :G_TIME, :NUM_H, :NUM_C, :ODDF_TYPE, :BET_TYPE, :REASON)" + ); + + query.bindValue(":TID", order.value("TID")); + query.bindValue(":DATETIME", order.value("DATETIME")); + query.bindValue(":ACCEPT_DATETIME", acceptDt); + query.bindValue(":NAME0", order.value("NAME0")); + query.bindValue(":GT", order.value("GT")); + query.bindValue(":WAGERS_TYPE", order.value("WAGERS_TYPE")); + query.bindValue(":LEAGUE", order.value("LEAGUE")); + query.bindValue(":TEAM_H", order.value("TEAM_H")); + query.bindValue(":TEAM_C", order.value("TEAM_C")); + query.bindValue(":ORDER_TYPE", order.value("ORDER_TYPE")); + query.bindValue(":ORDER_CON", order.value("ORDER_CON")); + query.bindValue(":SCORE", order.value("SCORE")); + query.bindValue(":IORATIO", order.value("IORATIO").toDouble()); + query.bindValue(":GOLD", order.value("GOLD").toDouble()); + query.bindValue(":SRV_IP", order.value("SRV_IP")); + query.bindValue(":SESSION", order.value("SESSION")); + query.bindValue(":STAGE", order.value("STAGE")); + query.bindValue(":G_TIME", order.value("G_TIME")); + query.bindValue(":NUM_H", order.value("NUM_H")); + query.bindValue(":NUM_C", order.value("NUM_C")); + query.bindValue(":ODDF_TYPE", order.value("ODDF_TYPE")); + query.bindValue(":BET_TYPE", order.value("BET_TYPE")); + query.bindValue(":REASON", order.value("REASON")); + + if (!query.exec()) { + qDebug() << "[数据库] 筛选注单插入失败:" << query.lastError(); + } +} + +QList> Config::get_screen_orders() +{ + QMutexLocker locker(&m_mutex); + QList> ordersList; + + QSqlQuery query(m_db); + QString sql = "SELECT * FROM screen_orders ORDER BY DATETIME DESC"; + + if (!query.exec(sql)) { + qDebug() << "[数据库] 查询筛选注单失败:" << query.lastError(); + return ordersList; + } + + while (query.next()) { + QMap order; + order["TID"] = query.value("TID").toString(); + order["DATETIME"] = query.value("DATETIME").toString(); + order["ACCEPT_DATETIME"] = query.value("ACCEPT_DATETIME").toString(); + order["NAME0"] = query.value("NAME0").toString(); + order["GT"] = query.value("GT").toString(); + order["WAGERS_TYPE"] = query.value("WAGERS_TYPE").toString(); + order["LEAGUE"] = query.value("LEAGUE").toString(); + order["TEAM_H"] = query.value("TEAM_H").toString(); + order["TEAM_C"] = query.value("TEAM_C").toString(); + order["ORDER_TYPE"] = query.value("ORDER_TYPE").toString(); + order["ORDER_CON"] = query.value("ORDER_CON").toString(); + order["SCORE"] = query.value("SCORE").toString(); + order["IORATIO"] = query.value("IORATIO").toString(); + order["GOLD"] = query.value("GOLD").toString(); + order["BET_TYPE"] = query.value("BET_TYPE").toString(); + order["SESSION"] = query.value("SESSION").toString(); + order["STAGE"] = query.value("STAGE").toString(); + order["G_TIME"] = query.value("G_TIME").toString(); + order["NUM_H"] = query.value("NUM_H").toString(); + order["NUM_C"] = query.value("NUM_C").toString(); + order["ODDF_TYPE"] = query.value("ODDF_TYPE").toString(); + order["REASON"] = query.value("REASON").toString(); + ordersList.append(order); + } + + return ordersList; +} + + +void Config::add_success_order(QMap order) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + m_db.transaction(); + + query.prepare( + "INSERT INTO success_orders(" + "TID, DATETIME, ACCEPT_DATETIME, NAME0, GT, WAGERS_TYPE, LEAGUE, " + "TEAM_H, TEAM_C, ORDER_TYPE, ORDER_CON, ORDER_CON_NEW, SCORE, SCORE_NEW, " + "IORATIO, IORATIO_NEW, GOLD, SRV_IP, SESSION, STAGE, G_TIME, " + "NUM_H, NUM_C, ODDF_TYPE, BET_TYPE" + ") VALUES(" + ":TID, :DATETIME, :ACCEPT_DATETIME, :NAME0, :GT, :WAGERS_TYPE, :LEAGUE, " + ":TEAM_H, :TEAM_C, :ORDER_TYPE, :ORDER_CON, :ORDER_CON_NEW, :SCORE, :SCORE_NEW, " + ":IORATIO, :IORATIO_NEW, :GOLD, :SRV_IP, :SESSION, :STAGE, :G_TIME, " + ":NUM_H, :NUM_C, :ODDF_TYPE, :BET_TYPE)" + ); + + QString acceptDt = order.value("ACCEPT_DATETIME"); + if (acceptDt.isEmpty()) { + acceptDt = QDateTime::currentDateTime().addSecs(-43200).toString("yyyy-MM-dd HH:mm:ss"); + } + + query.bindValue(":TID", order.value("TID")); + query.bindValue(":DATETIME", order.value("DATETIME")); + query.bindValue(":ACCEPT_DATETIME", acceptDt); + query.bindValue(":NAME0", order.value("NAME0")); + query.bindValue(":GT", order.value("GT")); + query.bindValue(":WAGERS_TYPE", order.value("WAGERS_TYPE")); + query.bindValue(":LEAGUE", order.value("LEAGUE")); + query.bindValue(":TEAM_H", order.value("TEAM_H")); + query.bindValue(":TEAM_C", order.value("TEAM_C")); + query.bindValue(":ORDER_TYPE", order.value("ORDER_TYPE")); + query.bindValue(":ORDER_CON", order.value("ORDER_CON")); + query.bindValue(":ORDER_CON_NEW", order.value("ORDER_CON_NEW")); + query.bindValue(":SCORE", order.value("SCORE")); + query.bindValue(":SCORE_NEW", order.value("SCORE_NEW")); + query.bindValue(":IORATIO", order.value("IORATIO").toDouble()); + query.bindValue(":IORATIO_NEW", order.value("IORATIO_NEW").toDouble()); + query.bindValue(":GOLD", order.value("GOLD").toDouble()); + query.bindValue(":SRV_IP", order.value("SRV_IP")); + query.bindValue(":SESSION", order.value("SESSION")); + query.bindValue(":STAGE", order.value("STAGE")); + query.bindValue(":G_TIME", order.value("G_TIME")); + query.bindValue(":NUM_H", order.value("NUM_H")); + query.bindValue(":NUM_C", order.value("NUM_C")); + query.bindValue(":ODDF_TYPE", order.value("ODDF_TYPE")); + query.bindValue(":BET_TYPE", order.value("BET_TYPE")); + + if (!query.exec()) { + qDebug() << "[数据库] 成功注单插入失败:" << query.lastError(); + m_db.rollback(); + return; + } + + if (!m_db.commit()) { + qDebug() << "[数据库] 事务提交失败:" << m_db.lastError(); + } +} + +QList> Config::get_success_orders() +{ + QMutexLocker locker(&m_mutex); + QList> list; + + QSqlQuery query(m_db); + if (!query.exec("SELECT * FROM success_orders ORDER BY DATETIME DESC")) { + qDebug() << "[数据库] 查询成功注单失败:" << query.lastError(); + return list; + } + while (query.next()) { + QMap o; + o["TID"] = query.value("TID").toString(); + o["DATETIME"] = query.value("DATETIME").toString(); + o["ACCEPT_DATETIME"] = query.value("ACCEPT_DATETIME").toString(); + o["NAME0"] = query.value("NAME0").toString(); + o["GT"] = query.value("GT").toString(); + o["WAGERS_TYPE"] = query.value("WAGERS_TYPE").toString(); + o["LEAGUE"] = query.value("LEAGUE").toString(); + o["TEAM_H"] = query.value("TEAM_H").toString(); + o["TEAM_C"] = query.value("TEAM_C").toString(); + o["ORDER_TYPE"] = query.value("ORDER_TYPE").toString(); + o["ORDER_CON"] = query.value("ORDER_CON").toString(); + o["ORDER_CON_NEW"] = query.value("ORDER_CON_NEW").toString(); + o["SCORE"] = query.value("SCORE").toString(); + o["SCORE_NEW"] = query.value("SCORE_NEW").toString(); + o["IORATIO"] = query.value("IORATIO").toString(); + o["IORATIO_NEW"] = query.value("IORATIO_NEW").toString(); + o["GOLD"] = query.value("GOLD").toString(); + o["SRV_IP"] = query.value("SRV_IP").toString(); + o["SESSION"] = query.value("SESSION").toString(); + o["STAGE"] = query.value("STAGE").toString(); + o["G_TIME"] = query.value("G_TIME").toString(); + o["NUM_H"] = query.value("NUM_H").toString(); + o["NUM_C"] = query.value("NUM_C").toString(); + o["ODDF_TYPE"] = query.value("ODDF_TYPE").toString(); + o["BET_TYPE"] = query.value("BET_TYPE").toString(); + list.append(o); + } + return list; +} + +void Config::add_failed_orders(QMap order) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + m_db.transaction(); + + query.prepare( + "INSERT OR IGNORE INTO failed_orders(" + "TID, DATETIME, ACCEPT_DATETIME, FOLLOW_DATETIME, FOLLOW_TID, NAME0, GT, WAGERS_TYPE, LEAGUE, " + "TEAM_H, TEAM_C, ORDER_TYPE, ORDER_CON, ORDER_CON_NEW, SCORE, SCORE_NEW, " + "IORATIO, IORATIO_NEW, GOLD, SRV_IP, SESSION, STAGE, G_TIME, NUM_H, NUM_C, " + "ODDF_TYPE, BET_TYPE, REASON, REBET_TIMES" + ") VALUES(" + ":TID, :DATETIME, :ACCEPT_DATETIME, :FOLLOW_DATETIME, :FOLLOW_TID, :NAME0, :GT, :WAGERS_TYPE, :LEAGUE, " + ":TEAM_H, :TEAM_C, :ORDER_TYPE, :ORDER_CON, :ORDER_CON_NEW, :SCORE, :SCORE_NEW, " + ":IORATIO, :IORATIO_NEW, :GOLD, :SRV_IP, :SESSION, :STAGE, :G_TIME, :NUM_H, :NUM_C, " + ":ODDF_TYPE, :BET_TYPE, :REASON, :REBET_TIMES)" + ); + + QString acceptDt = order.value("ACCEPT_DATETIME"); + if (acceptDt.isEmpty()) { + acceptDt = QDateTime::currentDateTime().addSecs(-43200).toString("yyyy-MM-dd HH:mm:ss"); + } + + query.bindValue(":TID", order.value("TID")); + query.bindValue(":DATETIME", order.value("DATETIME").isEmpty() ? order.value("betTime") : order.value("DATETIME")); + query.bindValue(":ACCEPT_DATETIME", acceptDt); + query.bindValue(":FOLLOW_DATETIME", order.value("FOLLOW_DATETIME")); + query.bindValue(":FOLLOW_TID", order.value("FOLLOW_TID")); + query.bindValue(":NAME0", order.value("NAME0")); + query.bindValue(":GT", order.value("GT")); + query.bindValue(":WAGERS_TYPE", order.value("WAGERS_TYPE")); + query.bindValue(":LEAGUE", order.value("LEAGUE")); + query.bindValue(":TEAM_H", order.value("TEAM_H")); + query.bindValue(":TEAM_C", order.value("TEAM_C")); + query.bindValue(":ORDER_TYPE", order.value("ORDER_TYPE")); + query.bindValue(":ORDER_CON", order.value("ORDER_CON")); + query.bindValue(":ORDER_CON_NEW", order.value("ORDER_CON_NEW")); + query.bindValue(":SCORE", order.value("SCORE")); + query.bindValue(":SCORE_NEW", order.value("SCORE_NEW")); + query.bindValue(":IORATIO", order.value("IORATIO").toDouble()); + query.bindValue(":IORATIO_NEW", order.value("IORATIO_NEW").toDouble()); + query.bindValue(":GOLD", order.value("GOLD").toDouble()); + query.bindValue(":SRV_IP", order.value("SRV_IP")); + query.bindValue(":SESSION", order.value("SESSION")); + query.bindValue(":STAGE", order.value("STAGE")); + query.bindValue(":G_TIME", order.value("G_TIME")); + query.bindValue(":NUM_H", order.value("NUM_H")); + query.bindValue(":NUM_C", order.value("NUM_C")); + query.bindValue(":ODDF_TYPE", order.value("ODDF_TYPE")); + query.bindValue(":BET_TYPE", order.value("BET_TYPE")); + query.bindValue(":REASON", order.value("REASON")); + query.bindValue(":REBET_TIMES", order.value("REBET_TIMES").toInt()); + + if (!query.exec()) { + qDebug() << "[数据库] 失败注单插入失败:" << query.lastError(); + m_db.rollback(); + return; + } + + + if (!m_db.commit()) { + qDebug() << "[数据库] 事务提交失败:" << m_db.lastError(); + } +} + +void Config::alert_failed_order(QMap order) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + m_db.transaction(); + query.prepare("UPDATE failed_orders SET REBET_TIMES = :REBET_TIMES, REASON = :REASON WHERE TID = :TID"); + query.bindValue(":REBET_TIMES", order.value("REBET_TIMES").toInt()); + query.bindValue(":REASON", order.value("REASON").isEmpty() ? "下单失败" : order.value("REASON")); + query.bindValue(":TID", order.value("TID")); + + if (!query.exec()) { + qDebug() << "[数据库] 更新失败注单失败:" << query.lastError(); + m_db.rollback(); + return; + } + if (!m_db.commit()) { + qDebug() << "[数据库] 事务提交失败:" << m_db.lastError(); + } +} + +QList> Config::get_failed_orders() +{ + QMutexLocker locker(&m_mutex); + QList> list; + + QSqlQuery query(m_db); + if (!query.exec("SELECT * FROM failed_orders ORDER BY DATETIME DESC")) { + qDebug() << "[数据库] 查询失败注单失败:" << query.lastError(); + return list; + } + while (query.next()) { + QMap o; + o["TID"] = query.value("TID").toString(); + o["DATETIME"] = query.value("DATETIME").toString(); + o["ACCEPT_DATETIME"] = query.value("ACCEPT_DATETIME").toString(); + o["FOLLOW_DATETIME"] = query.value("FOLLOW_DATETIME").toString(); + o["FOLLOW_TID"] = query.value("FOLLOW_TID").toString(); + o["NAME0"] = query.value("NAME0").toString(); + o["GT"] = query.value("GT").toString(); + o["WAGERS_TYPE"] = query.value("WAGERS_TYPE").toString(); + o["LEAGUE"] = query.value("LEAGUE").toString(); + o["TEAM_H"] = query.value("TEAM_H").toString(); + o["TEAM_C"] = query.value("TEAM_C").toString(); + o["ORDER_TYPE"] = query.value("ORDER_TYPE").toString(); + o["ORDER_CON"] = query.value("ORDER_CON").toString(); + o["ORDER_CON_NEW"] = query.value("ORDER_CON_NEW").toString(); + o["SCORE"] = query.value("SCORE").toString(); + o["SCORE_NEW"] = query.value("SCORE_NEW").toString(); + o["IORATIO"] = query.value("IORATIO").toString(); + o["IORATIO_NEW"] = query.value("IORATIO_NEW").toString(); + o["GOLD"] = query.value("GOLD").toString(); + o["SRV_IP"] = query.value("SRV_IP").toString(); + o["SESSION"] = query.value("SESSION").toString(); + o["STAGE"] = query.value("STAGE").toString(); + o["G_TIME"] = query.value("G_TIME").toString(); + o["NUM_H"] = query.value("NUM_H").toString(); + o["NUM_C"] = query.value("NUM_C").toString(); + o["ODDF_TYPE"] = query.value("ODDF_TYPE").toString(); + o["BET_TYPE"] = query.value("BET_TYPE").toString(); + o["REASON"] = query.value("REASON").toString(); + o["REBET_TIMES"] = query.value("REBET_TIMES").toString(); + + //qDebug() << "读取失败注单跟单次数:" << o["REBET_TIMES"]; + list.append(o); + } + return list; +} + +void Config::add_rebet_order(QMap order) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + // 安全转换函数 + auto safeToDouble = [](const QString& str) -> double { + if (str.isEmpty()) return 0.0; + bool ok; + double val = str.toDouble(&ok); + return ok ? val : 0.0; + }; + + auto safeToInt = [](const QString& str) -> int { + if (str.isEmpty()) return 0; + bool ok; + int val = str.toInt(&ok); + return ok ? val : 0; + }; + + query.prepare( + "INSERT INTO rebet_orders(" + "TID, DATETIME, ACCEPT_DATETIME, NAME0, GT, WAGERS_TYPE, LEAGUE, " + "TEAM_H, TEAM_C, ORDER_TYPE, ORDER_CON, ORDER_CON_NEW, SCORE, SCORE_NEW, " + "IORATIO, IORATIO_NEW, GOLD, SRV_IP, SESSION, STAGE, G_TIME, " + "NUM_H, NUM_C, ODDF_TYPE, BET_TYPE, REASON" + ") VALUES(" + ":TID, :DATETIME, :ACCEPT_DATETIME, :NAME0, :GT, :WAGERS_TYPE, :LEAGUE, " + ":TEAM_H, :TEAM_C, :ORDER_TYPE, :ORDER_CON, :ORDER_CON_NEW, :SCORE, :SCORE_NEW, " + ":IORATIO, :IORATIO_NEW, :GOLD, :SRV_IP, :SESSION, :STAGE, :G_TIME, " + ":NUM_H, :NUM_C, :ODDF_TYPE, :BET_TYPE, :REASON)" + ); + + // 绑定值 - 确保数据类型与表结构匹配 + query.bindValue(":TID", order.value("TID")); // TEXT 类型 + query.bindValue(":DATETIME", order.value("DATETIME")); + query.bindValue(":ACCEPT_DATETIME", order.value("ACCEPT_DATETIME")); + query.bindValue(":NAME0", order.value("NAME0")); + query.bindValue(":GT", order.value("GT")); + query.bindValue(":WAGERS_TYPE", order.value("WAGERS_TYPE")); + query.bindValue(":LEAGUE", order.value("LEAGUE")); + query.bindValue(":TEAM_H", order.value("TEAM_H")); + query.bindValue(":TEAM_C", order.value("TEAM_C")); + query.bindValue(":ORDER_TYPE", order.value("ORDER_TYPE")); + query.bindValue(":ORDER_CON", order.value("ORDER_CON")); + query.bindValue(":ORDER_CON_NEW", order.value("ORDER_CON_NEW")); + query.bindValue(":SCORE", order.value("SCORE")); + query.bindValue(":SCORE_NEW", order.value("SCORE_NEW")); + query.bindValue(":IORATIO", safeToDouble(order.value("IORATIO"))); + query.bindValue(":IORATIO_NEW", safeToDouble(order.value("IORATIO_NEW"))); + query.bindValue(":GOLD", safeToDouble(order.value("GOLD"))); + query.bindValue(":SRV_IP", order.value("SRV_IP")); + query.bindValue(":SESSION", order.value("SESSION")); + query.bindValue(":STAGE", order.value("STAGE")); + query.bindValue(":G_TIME", order.value("G_TIME")); + query.bindValue(":NUM_H", order.value("NUM_H")); // TEXT 类型 + query.bindValue(":NUM_C", order.value("NUM_C")); // TEXT 类型 + query.bindValue(":ODDF_TYPE", order.value("ODDF_TYPE")); + query.bindValue(":BET_TYPE", order.value("BET_TYPE")); + query.bindValue(":REASON", order.value("REASON")); + + if (!query.exec()) { + qDebug() << "[数据库] 补单记录插入失败:" << query.lastError(); + qDebug() << "[数据库] 错误详情:" << query.lastError().text(); + qDebug() << "[数据库] 执行的SQL:" << query.executedQuery(); + + // 打印所有绑定值以便调试 + QMap boundValues = query.boundValues(); + for (auto it = boundValues.begin(); it != boundValues.end(); ++it) { + qDebug() << "[数据库] 绑定值 -" << it.key() << ":" << it.value() << "类型:" << it.value().typeName(); + } + } + else { + //qDebug() << "[数据库] 补单记录插入成功,TID:" << order.value("TID"); + } +} + +QList> Config::get_rebet_orders() +{ + QMutexLocker locker(&m_mutex); + QList> list; + + QSqlQuery query(m_db); + if (!query.exec("SELECT * FROM rebet_orders ORDER BY DATETIME DESC")) { + qDebug() << "[数据库] 查询补单记录失败:" << query.lastError(); + return list; + } + while (query.next()) { + QMap o; + o["TID"] = query.value("TID").toString(); + o["DATETIME"] = query.value("DATETIME").toString(); + o["ACCEPT_DATETIME"] = query.value("ACCEPT_DATETIME").toString(); + o["NAME0"] = query.value("NAME0").toString(); + o["GT"] = query.value("GT").toString(); + o["WAGERS_TYPE"] = query.value("WAGERS_TYPE").toString(); + o["LEAGUE"] = query.value("LEAGUE").toString(); + o["TEAM_H"] = query.value("TEAM_H").toString(); + o["TEAM_C"] = query.value("TEAM_C").toString(); + o["ORDER_TYPE"] = query.value("ORDER_TYPE").toString(); + o["ORDER_CON"] = query.value("ORDER_CON").toString(); + o["ORDER_CON_NEW"] = query.value("ORDER_CON_NEW").toString(); + o["SCORE"] = query.value("SCORE").toString(); + o["SCORE_NEW"] = query.value("SCORE_NEW").toString(); + o["IORATIO"] = query.value("IORATIO").toString(); + o["IORATIO_NEW"] = query.value("IORATIO_NEW").toString(); + o["GOLD"] = query.value("GOLD").toString(); + o["SRV_IP"] = query.value("SRV_IP").toString(); + o["SESSION"] = query.value("SESSION").toString(); + o["STAGE"] = query.value("STAGE").toString(); + o["G_TIME"] = query.value("G_TIME").toString(); + o["NUM_H"] = query.value("NUM_H").toString(); + o["NUM_C"] = query.value("NUM_C").toString(); + o["ODDF_TYPE"] = query.value("ODDF_TYPE").toString(); + o["BET_TYPE"] = query.value("BET_TYPE").toString(); + o["REASON"] = query.value("REASON").toString(); + list.append(o); + } + return list; +} + + +bool Config::is_order_in_screen(const QString& tid) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + QString sql = "SELECT COUNT(*) FROM screen_orders WHERE TID = :TID"; + if (!query.prepare(sql)) { + qDebug() << "[数据库] 检查筛选注单存在性失败:" << query.lastError(); + return false; + } + + query.bindValue(":TID", tid); + if (!query.exec()) { + qDebug() << "[数据库] 执行筛选注单存在性查询失败:" << query.lastError(); + return false; + } + + if (query.next()) { + return query.value(0).toInt() > 0; + } + return false; +} + +bool Config::is_order_in_success(const QString& tid) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + QString sql = "SELECT COUNT(*) FROM success_orders WHERE TID = :TID"; + if (!query.prepare(sql)) { + qDebug() << "[数据库] 检查成功注单存在性失败:" << query.lastError(); + return false; + } + + query.bindValue(":TID", tid); + if (!query.exec()) { + qDebug() << "[数据库] 执行成功注单存在性查询失败:" << query.lastError(); + return false; + } + + if (query.next()) { + return query.value(0).toInt() > 0; + } + return false; +} + +bool Config::is_order_in_failed(const QString& tid) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + QString sql = "SELECT COUNT(*) FROM failed_orders WHERE TID = :TID"; + if (!query.prepare(sql)) { + qDebug() << "[数据库] 检查失败注单存在性失败:" << query.lastError(); + return false; + } + + query.bindValue(":TID", tid); + if (!query.exec()) { + qDebug() << "[数据库] 执行失败注单存在性查询失败:" << query.lastError(); + return false; + } + + if (query.next()) { + return query.value(0).toInt() > 0; + } + return false; +} + +bool Config::is_order_in_rebet(const QString& tid) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + // tid是纯数字,需要查询是否有该数字开头的补单记录 + QString sql = "SELECT COUNT(*) FROM rebet_orders WHERE TID LIKE :TID_PATTERN"; + if (!query.prepare(sql)) { + qDebug() << "[数据库] 检查补单记录存在性失败:" << query.lastError(); + return false; + } + + query.bindValue(":TID_PATTERN", tid + "(%"); // 匹配 "22682919971(%" + if (!query.exec()) { + qDebug() << "[数据库] 执行补单记录存在性查询失败:" << query.lastError(); + return false; + } + + if (query.next()) { + bool hasRebet = query.value(0).toInt() > 0; + + return hasRebet; + } + // qDebug() << "[数据库] 检查TID:" << tid << "补单记录不存在"; + return false; +} + + +void Config::setBetProject(QList> list) +{ + + m_mutex.lock(); + m_settings->setValue("Client/BetProject", toJson(list)); + m_mutex.unlock(); +} + +int Config::betDays() +{ + m_mutex.lock(); + int days = m_settings->value("Client/BetDays", 1).toInt(); + m_mutex.unlock(); + return days; +} + +void Config::setBetDays(int days) +{ + m_mutex.lock(); + m_settings->setValue("Client/BetDays", days); + m_mutex.unlock(); +} + +bool Config::betNormalOrder() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/BetNormalOrder", true).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setBetNormalOrder(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/BetNormalOrder", enable); + m_mutex.unlock(); +} + +bool Config::betPhoneOrder() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/BetPhoneOrder", true).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setBetPhoneOrder(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/BetPhoneOrder", enable); + m_mutex.unlock(); +} + +QList> Config::handicap() +{ + m_mutex.lock(); + QString handicapData = m_settings->value("Client/Handicap").toString(); + + // 如果配置为空,创建默认配置 + if (handicapData.isEmpty()) { + QList> defaultHandicap; + QStringList gameTypes = { "足球滚球全场", "足球滚球上半场", "足球今日全场", + "足球今日上半场", "足球早盘全场", "足球早盘上半场", + "篮球滚球全场", "篮球今日全场", "篮球早盘全场" }; + + // 定义列标题(不包括第一列和最后一列) + QStringList columnTypes = { "让球", "受让", "大", "小", "主队大", "主队小", "客队大", "客队小" }; + + for (int row = 0; row < gameTypes.size(); row++) { + // 添加8种盘口类型,默认值为"C" + for (int col = 0; col < columnTypes.size(); col++) { + QMap map; + + + // 添加项目类型信息以保持数据结构一致 + map = Utils::instance().type(gameTypes[row], columnTypes[col]); + //map["ORDER_TYPE"] = columnTypes[col]; + map["ROW"] = QString::number(row); + map["COLUMN"] = QString::number(col + 1); // 第一列是0,所以从1开始 + map["SOLUTION"] = "C"; + + // 默认补单 + map["REBET"] = "TRUE"; + + //map["project"] = typeMap["project"]; + //map["wtype"] = typeMap["wtype"]; + //map["rtype"] = typeMap["rtype"]; + + defaultHandicap.append(map); + } + + // 添加补单列,默认选中 + QMap rebetMap; + rebetMap["ROW"] = QString::number(row); + rebetMap["COLUMN"] = QString::number(columnTypes.size() + 1); // 最后一列 + rebetMap["REBET"] = "TRUE"; + rebetMap["project"] = gameTypes[row]; + defaultHandicap.append(rebetMap); + } + + m_mutex.unlock(); + return defaultHandicap; + } + + QList> list = toMapList(handicapData); + m_mutex.unlock(); + return list; +} + +void Config::setHandicap(QList> list) +{ + m_mutex.lock(); + m_settings->setValue("Client/Handicap", toJson(list)); + m_mutex.unlock(); +} + +bool Config::handicapProject() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/HandicapProject", true).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setHandicapProject(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/HandicapProject", enable); + m_mutex.unlock(); +} + +int Config::handicapProjectIndex() +{ + m_mutex.lock(); + int index = m_settings->value("Client/HandicapProjectIndex", 0).toInt(); + m_mutex.unlock(); + return index; +} + +void Config::setHandicapProjectIndex(int index) +{ + m_mutex.lock(); + m_settings->setValue("Client/HandicapProjectIndex", index); + m_mutex.unlock(); +} + +bool Config::handicapType() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/HandicapType", true).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setHandicapType(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/HandicapType", enable); + m_mutex.unlock(); +} + +int Config::handicapTypeIndex() +{ + m_mutex.lock(); + int index = m_settings->value("Client/HandicapTypeIndex", 0).toInt(); + m_mutex.unlock(); + return index; +} + +void Config::setHandicapTypeIndex(int index) +{ + m_mutex.lock(); + m_settings->setValue("Client/HandicapTypeIndex", index); + m_mutex.unlock(); +} + +QString Config::handicapMethod() +{ + m_mutex.lock(); + QString method = m_settings->value("Client/HandicapMethod").toString(); + m_mutex.unlock(); + return method; +} + +void Config::setHandicapMethod(QString method) +{ + m_mutex.lock(); + m_settings->setValue("Client/HandicapMethod", method); + m_mutex.unlock(); +} + +QList> Config::odds() +{ + m_mutex.lock(); + + QString oddsData = m_settings->value("Client/Odds").toString(); + + // 如果配置为空,设置默认值 + if (oddsData.isEmpty()) { + QList> defaultOdds; + + // 9行数据(对应9种游戏类型) + QStringList gameTypes = { + "足球滚球全场", "足球滚球上半场", "足球今日全场", + "足球今日上半场", "足球早盘全场", "足球早盘上半场", + "篮球滚球全部", "篮球今日全部", "篮球早盘全部" + }; + + // 列标题(与界面一致) + QStringList columnHeaders = { + "让球", "受让", "大", "小", "独赢主", "独赢客", "独赢和", + "单", "双", "主队大", "主队小", "客队大", "客队小", "补单" + }; + + for (int row = 0; row < 9; row++) { + // 前13列(赔率列) + for (int column = 0; column < 13; column++) { + QMap map; + map["ROW"] = QString::number(row); + map["COLUMN"] = QString::number(column + 1); // 第0列是项目名称 + map["project"] = gameTypes[row]; + map["ORDER_TYPE"] = columnHeaders[column]; + + // 默认不补单 + map["REBET"] = "FALSE"; + + // 设置默认的赔率值(与界面初始化一致) + map["HIGH"] = "0"; + map["UP"] = "0"; + map["LOW"] = "0"; + map["DOWN"] = "0"; + map["REBET"] = ""; // 空字符串表示这不是补单列 + + defaultOdds.append(map); + } + + // 第14列(补单列) + QMap rebetMap; + rebetMap["ROW"] = QString::number(row); + rebetMap["COLUMN"] = "14"; + rebetMap["project"] = gameTypes[row]; + rebetMap["ORDER_TYPE"] = "补单"; + rebetMap["REBET"] = "FALSE"; // 补单默认不选中 + rebetMap["HIGH"] = ""; + rebetMap["UP"] = ""; + rebetMap["LOW"] = ""; + rebetMap["DOWN"] = ""; + + defaultOdds.append(rebetMap); + } + + // 转换为JSON并保存 + QJsonArray jsonArray; + for (const auto& map : defaultOdds) { + QJsonObject obj; + for (auto it = map.begin(); it != map.end(); ++it) { + obj[it.key()] = it.value(); + } + jsonArray.append(obj); + } + + QJsonDocument doc(jsonArray); + oddsData = doc.toJson(QJsonDocument::Compact); + m_settings->setValue("Client/Odds", oddsData); + } + + QList> list = toMapList(oddsData); + m_mutex.unlock(); + return list; +} + +void Config::setOdds(QList> list) +{ + m_mutex.lock(); + m_settings->setValue("Client/Odds", toJson(list)); + m_mutex.unlock(); +} + +bool Config::oddsProject() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/OddsProjectEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setOddsProject(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/OddsProjectEnable", enable); + m_mutex.unlock(); +} + +int Config::oddsProjectIndex() +{ + m_mutex.lock(); + int index = m_settings->value("Client/OddsProjectIndex").toInt(); + m_mutex.unlock(); + return index; +} + +void Config::setOddsProjectIndex(int index) +{ + m_mutex.lock(); + m_settings->setValue("OddsProjectIndex", index); + m_mutex.unlock(); +} + +bool Config::oddsType() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/OddsTypeEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setOddsType(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/OddsTypeEnable", enable); + m_mutex.unlock(); +} + +int Config::oddsTypeIndex() +{ + m_mutex.lock(); + int index = m_settings->value("Client/OddsTypeIndex", 0).toInt(); + m_mutex.unlock(); + return index; +} + +void Config::setOddsTypeIndex(int index) +{ + m_mutex.lock(); + m_settings->setValue("Client/OddsTypeIndex", index); + m_mutex.unlock(); +} + +int Config::oddsHigh() +{ + m_mutex.lock(); + int value = m_settings->value("Client/OddsHigh", 0).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setOddsHigh(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/OddsHigh", value); + m_mutex.unlock(); +} + +int Config::oddsLow() +{ + m_mutex.lock(); + int value = m_settings->value("Client/OddsLow", 0).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setOddsLow(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/OddsLow", value); + m_mutex.unlock(); +} + +int Config::oddsUp() +{ + m_mutex.lock(); + int value = m_settings->value("Client/OddsUp", 0).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setOddsUp(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/OddsUp", value); + m_mutex.unlock(); +} + +int Config::oddsDown() +{ + m_mutex.lock(); + int value = m_settings->value("Client/OddsDown", 0).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setOddsDown(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/OddsDown", value); + m_mutex.unlock(); +} + +bool Config::originalAmountLowerGiveUpEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/OriginalAmountLowerGiveUpEnable", false).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setOriginalAmountLowerGiveUpEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/OriginalAmountLowerGiveUpEnable", enable); + m_mutex.unlock(); +} + +int Config::originalAmountLower() +{ + m_mutex.lock(); + int value = m_settings->value("Client/OriginalAmountLower", 50).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setOriginalAmountLower(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/OriginalAmountLower", value); + m_mutex.unlock(); +} + +bool Config::originalAmountHigherGiveUpEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/OriginalAmountHigherGiveUpEnable", false).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setOriginalAmountHigherGiveUpEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/OriginalAmountHigherGiveUpEnable", enable); + m_mutex.unlock(); +} + +int Config::originalAmountHigher() +{ + m_mutex.lock(); + int value = m_settings->value("Client/OriginalAmountHigher", 10000).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setOriginalAmountHigher(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/OriginalAmountHigher", value); + m_mutex.unlock(); +} + +bool Config::amountLowerEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("AmountLowerEnable").toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setAmountLowerEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/AmountLowerEnable", enable); + m_mutex.unlock(); +} + +int Config::amountLower() +{ + m_mutex.lock(); + int value = m_settings->value("Client/AmountLower", 50).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setAmountLower(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/AmountLower", value); + m_mutex.unlock(); +} + +bool Config::amountLowerAddToEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("AmountLowerAddToEnable", false).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setAmountLowerAddToEnable(bool enable) +{ +} + +bool Config::amountLowerGiveUpEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/AmountLowerGiveUpEnable", false).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setAmountLowerGiveUpEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/AmountLowerGiveUpEnable", enable); + m_mutex.unlock(); +} + +int Config::amountLowerAddTo() +{ + m_mutex.lock(); + int value = m_settings->value("Client/AmountLowerAddTo", 50).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setAmountLowerAddTo(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/AmountLowerAddTo", value); + m_mutex.unlock(); +} + +bool Config::amountHigherEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/AmountHigherEnable", false).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setAmountHigherEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/AmountHigherEnable", enable); + m_mutex.unlock(); +} + +int Config::amountHigher() +{ + m_mutex.lock(); + int value = m_settings->value("Client/AmountHigher", 10000).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setAmountHigher(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/AmountHigher", value); + m_mutex.unlock(); +} + +bool Config::amountHigherSubToEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/AmountHigherSubToEnable", false).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setAmountHigherSubToEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/AmountHigherSubToEnable", enable); + m_mutex.unlock(); +} + +bool Config::amountHigherGiveUpEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/AmountHigherGiveUpEnable", false).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setAmountHigherGiveUpEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/AmountHigherGiveUpEnable", enable); + m_mutex.unlock(); +} + +int Config::amountHigherSubTo() +{ + m_mutex.lock(); + int value = m_settings->value("Client/AmountHigheerSubTo", 10000).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setAmountHigherSubTo(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/AmountHigherSubTo", value); + m_mutex.unlock(); +} + +QString Config::carry(QString value) +{ + // 获取进位方式 + int carryIndex = this->carryIndex(); + int base = 1; + if (carryIndex == 0) + { + base = 1; + } + else if (carryIndex == 1) + { + base = 10; + } + else if (carryIndex == 2) + { + base = 100; + } + else if (carryIndex == 3) + { + base = 1000; + } + else if (carryIndex == 4) + { + base = 10000; + } + // 舍去余数 + if (carryRoundingEnable()) + { + qDebug() << "vaalue:" << value.toInt(); + qDebug() << "base:" << base; + qDebug() << "余数:" << value.toInt() % base; + qDebug() << "舍弃余数" << value.toInt() << "->" << QString::number(value.toInt() - value.toInt() % base); + return QString::number(value.toInt() - value.toInt() % base); + } + + // 默认四舍五入 + int factor = value.toInt() / base; + int mod = value.toInt() % base; + factor = (mod * 2 > base) ? (factor + 1) : factor; + int result = factor * base; + return QString::number(result); +} + +int Config::carry() +{ + m_mutex.lock(); + int value = m_settings->value("Client/Carry", 98765).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setCarry(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/Carry", value); + m_mutex.unlock(); +} + +int Config::carryIndex() +{ + m_mutex.lock(); + int index = m_settings->value("Client/CarryIndex", 0).toInt(); + m_mutex.unlock(); + return index; +} + +void Config::setCarryIndex(int index) +{ + m_mutex.lock(); + m_settings->setValue("Client/CarryIndex", index); + m_mutex.unlock(); +} + +bool Config::carryHalfAdjustEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/CarryHalfAdjustEnable", false).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setCarryHalfAdjustEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/CarryHalfAdjustEnable", enable); + m_mutex.unlock(); +} + +bool Config::carryRoundingEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/CarryRoundingEnable").toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setCarryRoundingEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/CarryRoundingEnable", enable); + m_mutex.unlock(); +} + +int Config::amountMin() +{ + m_mutex.lock(); + int value = m_settings->value("Client/AmountMin", 50).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setAmountMin(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/AmountMin", value); + m_mutex.unlock(); +} + +int Config::amountMax() +{ + m_mutex.lock(); + int value = m_settings->value("Client/AmountMax", 500000).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setAmountMax(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/AmountMax", value); + m_mutex.unlock(); +} + +int Config::amount_less_than_platform() +{ + m_mutex.lock(); + int value = m_settings->value("Client/AmountLessThanPlatform", 0).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::set_amount_less_than_platform(int type) +{ + m_mutex.lock(); + m_settings->setValue("Client/AmountLessThanPlatform", type); + m_mutex.unlock(); +} + +int Config::amount_more_than_platform() +{ + m_mutex.lock(); + int value = m_settings->value("Client/AmountMoreThanPlatform", 0).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::set_amount_more_than_platform(int type) +{ + m_mutex.lock(); + m_settings->setValue("Client/AmountMoreThanPlatform", type); + m_mutex.unlock(); +} + +bool Config::rebetScreenEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/RebetScreenEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setRebetScreenEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/RebetScreenEnable", enable); + m_mutex.unlock(); +} + +QList> Config::rebetScreen() +{ + m_mutex.lock(); + QList> list = toMapList(m_settings->value("Client/RebetScreen").toString()); + m_mutex.unlock(); + return list; +} + +void Config::setRebetScreen(QList> list) +{ + m_mutex.lock(); + m_settings->setValue("Client/RebetScreen", toJson(list)); + m_mutex.unlock(); +} + + +// 在Config.cpp中实现 +int Config::getDelay(const QString& gameType, const QString& resultType, bool getMin) +{ + m_mutex.lock(); + QList> sleepSettings = toMapList(m_settings->value("Client/Sleep").toString()); + m_mutex.unlock(); + + // 查找对应的游戏类型 + int targetRow = -1; + for (int i = 0; i < 9; i++) { + if (g_gameTypes[i] == gameType) { + targetRow = i; + break; + } + } + + if (targetRow == -1) { + qWarning() << "Unknown game type:" << gameType; + return getMin ? 3000 : 5000; // 返回默认值 + } + + // 确定列索引 + int column = -1; + if (resultType == "before") { + column = getMin ? 1 : 2; + } + else if (resultType == "success") { + column = getMin ? 3 : 4; + } + else if (resultType == "failed") { + column = getMin ? 5 : 6; + } + else { + qWarning() << "Unknown result type:" << resultType; + return getMin ? 3000 : 5000; // 返回默认值 + } + + // 查找对应的配置项 + for (const auto& setting : sleepSettings) { + if (setting["row"] == QString::number(targetRow) && + setting["column"] == QString::number(column)) { + return setting["sleep"].toInt(); + } + } + + // 没有找到配置,返回默认值 + return getMin ? 3000 : 5000; +} + +int Config::getRandomDelay(const QString& gameType, const QString& resultType) +{ + int minDelay = getDelay(gameType, resultType, true); + int maxDelay = getDelay(gameType, resultType, false); + + // 确保min <= max + if (minDelay > maxDelay) { + qSwap(minDelay, maxDelay); + } + + // 生成随机延迟 + return QRandomGenerator::global()->bounded(minDelay, maxDelay + 1); +} + +QList> Config::sleep() +{ + QList> defaultSettings; + + // 9种游戏类型 + for (int row = 0; row < 9; row++) { + // 6列延迟设置 (1-6列) + for (int col = 1; col <= 6; col++) { + QMap map; + map["project"] = g_gameTypes[row]; + map["row"] = QString::number(row); + map["column"] = QString::number(col); + map["type"] = QString::number(col); + + // 设置默认值: + // 奇数列(最小延迟): 3000 (3秒) + // 偶数列(最大延迟): 5000 (5秒) + map["sleep"] = (col % 2 == 1) ? "0" : "0"; + + defaultSettings.append(map); + } + } + + return defaultSettings; + //m_mutex.lock(); + //QList> list = toMapList(m_settings->value("Client/Sleep").toString()); + //m_mutex.unlock(); + //return list; +} + +void Config::setSleep(QList> list) +{ + m_mutex.lock(); + m_settings->setValue("Client/Sleep", toJson(list)); + m_mutex.unlock(); +} + +int Config::betBeforeSleepMin() +{ + m_mutex.lock(); + int value = m_settings->value("Client/BetBeforeSleepMin", 0).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setBetBeforeSleepMin(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/BetBeforeSleepMin", value); + m_mutex.unlock(); +} +int Config::betBeforeSleepMax() +{ + m_mutex.lock(); + int value = m_settings->value("Client/BetBeforeSleepMax", 0).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setBetBeforeSleepMax(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/BetBeforeSleepMax", value); + m_mutex.unlock(); +} + +int Config::betBeforeSleep() +{ + m_mutex.lock(); + int min = m_settings->value("Client/BetBeforeSleepMin").toInt(); + int max = m_settings->value("Client/BetBeforeSleepMax").toInt(); + min = min > 0 ? min : 1; + max = max > 0 ? max : 60; + srand(QTime(0, 0, 0).secsTo(QTime::currentTime())); + int interval = rand() % (max - min + 1) + min; + m_mutex.unlock(); + return interval; +} + + +int Config::betSuccessSleepMin() +{ + m_mutex.lock(); + int value = m_settings->value("Client/BetSuccessSleepMin", 0).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setBetSuccessSleepMin(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/BetSuccessSleepMin", value); + m_mutex.unlock(); +} +int Config::betSuccessSleepMax() +{ + m_mutex.lock(); + int value = m_settings->value("Client/BetSuccessSleepMax", 0).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setBetSuccessSleepMax(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/BetSuccessSleepMax", value); + m_mutex.unlock(); +} + +int Config::betSuccessSleep() +{ + m_mutex.lock(); + int min = m_settings->value("Client/BetSuccessSleepMin").toInt(); + int max = m_settings->value("Client/BetSuccessSleepMax").toInt(); + min = min > 0 ? min : 1; + max = max > 0 ? max : 60; + srand(QTime(0, 0, 0).secsTo(QTime::currentTime())); + int interval = rand() % (max - min + 1) + min; + m_mutex.unlock(); + return interval; +} + +int Config::betFailedSleepMin() +{ + m_mutex.lock(); + int value = m_settings->value("Client/BetFailedSleepMin", 0).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setBetFailedSleepMin(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/BetFailedSleepMin", value); + m_mutex.unlock(); +} +int Config::betFailedSleepMax() +{ + m_mutex.lock(); + int value = m_settings->value("Client/BetFailedSleepMax", 0).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setBetFailedSleepMax(int value) +{ + m_mutex.lock(); + m_settings->setValue("Client/BetFailedSleepMax", value); + m_mutex.unlock(); +} + +int Config::betFailedSleep() +{ + m_mutex.lock(); + int min = m_settings->value("Client/BetFailedSleepMin").toInt(); + int max = m_settings->value("Client/BetFailedSleepMax").toInt(); + min = min > 0 ? min : 1; + max = max > 0 ? max : 60; + srand(QTime(0, 0, 0).secsTo(QTime::currentTime())); + int interval = rand() % (max - min + 1) + min; + m_mutex.unlock(); + return interval; +} + +int Config::betBeforeCalcIndex() +{ + m_mutex.lock(); + int index = m_settings->value("Client/BetBeforeCalcIndex", 0).toInt(); + m_mutex.unlock(); + return index; +} + +void Config::setBetBeforeCalcIndex(int index) +{ + m_mutex.lock(); + m_settings->setValue("Client/BetBeforeCalcIndex", index); + m_mutex.unlock(); +} + +bool Config::sleepProjectEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/SleepProjectEnable", false).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setSleepProjectEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/SleepProjectEnable", enable); + m_mutex.unlock(); +} + +int Config::sleepProjectIndex() +{ + m_mutex.lock(); + int index = m_settings->value("Client/SleepProjectIndex", 0).toInt(); + m_mutex.unlock(); + return index; +} + +void Config::setSleepProjectIndex(int index) +{ + m_mutex.lock(); + m_settings->setValue("Client/SleepProjectIndex", index); + m_mutex.unlock(); +} + + +bool Config::acceptOrderSoundEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/AcceptOrderSoundEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +QString Config::acceptOrderSoundPath() +{ + m_mutex.lock(); + QString path = m_settings->value("Client/AcceptOrderSoundPath").toString(); + m_mutex.unlock(); + return path; +} + +void Config::setAcceptOrderSoundEnable(bool value) +{ + m_mutex.lock(); + m_settings->setValue("Client/AcceptOrderSoundEnable", value); + m_mutex.unlock(); +} + +void Config::setAcceptOrderSoundPath(QString path) +{ + m_mutex.lock(); + m_settings->setValue("Client/AcceptOrderSoundPath", path); + m_mutex.unlock(); +} + +bool Config::screenOrderSoundEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/ScreenOrderSoundEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +QString Config::screenOrderSoundPath() +{ + m_mutex.lock(); + QString path = m_settings->value("Client/ScreenOrderSoundPath").toString(); + m_mutex.unlock(); + return path; +} + +void Config::setScreenOrderSoundEnable(bool value) +{ + m_mutex.lock(); + m_settings->setValue("Client/ScreenOrderSoundEnable", value); + m_mutex.unlock(); +} + +void Config::setScreenOrderSoundPath(QString path) +{ + m_mutex.lock(); + m_settings->setValue("Client/ScreenOrderSoundPath", path); + m_mutex.unlock(); +} + +bool Config::followOrderSuccessSoundEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/FollowOrderSuccessSoundEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +QString Config::followOrderSuccessSoundPath() +{ + m_mutex.lock(); + QString path = m_settings->value("Client/FollowOrderSuccessSoundPath").toString(); + m_mutex.unlock(); + return path; +} + +void Config::setFollowOrderSuccessSoundEnable(bool value) +{ + m_mutex.lock(); + m_settings->setValue("Client/FollowOrderSuccessSoundEnable", value); + m_mutex.unlock(); +} + +void Config::setFollowOrderSuccessSoundPath(QString path) +{ + m_mutex.lock(); + m_settings->setValue("Client/FollowOrderSuccessSoundPath", path); + m_mutex.unlock(); +} + +bool Config::followOrderFailedSoundEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/FollowOrderFailedSoundEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +QString Config::followOrderFailedSoundPath() +{ + m_mutex.lock(); + QString path = m_settings->value("Client/FollowOrderFailedSoundPath").toString(); + m_mutex.unlock(); + return path; +} + +void Config::setFollowOrderFailedSoundEnable(bool value) +{ + m_mutex.lock(); + m_settings->setValue("Client/FolowOrderFailedSoundEnable", value); + m_mutex.unlock(); +} + +void Config::setFollowOrderFailedSoundPath(QString path) +{ + m_mutex.lock(); + m_settings->setValue("Client/FolowOrderFailedSoundPath", path); + m_mutex.unlock(); +} + + +bool Config::disconnectSoundEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/DisconnectSoundEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +QString Config::disconnectSoundPath() +{ + m_mutex.lock(); + QString path = m_settings->value("Client/DisconnectSoundPath").toString(); + m_mutex.unlock(); + return path; +} + +void Config::setDisconnectSoundEnable(bool value) +{ + m_mutex.lock(); + m_settings->setValue("Client/DisconnectSoundEnable", value); + m_mutex.unlock(); +} + +void Config::setDisconnectSoundPath(QString path) +{ + m_mutex.lock(); + m_settings->setValue("Client/DisconnectSoundPath", path); + m_mutex.unlock(); +} + + + +bool Config::pushFailedSoundEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/PushFailedSoundEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +QString Config::pushFailedSoundPath() +{ + m_mutex.lock(); + QString path = m_settings->value("Client/PushFailedSoundPath").toString(); + m_mutex.unlock(); + return path; +} + +void Config::setPushFailedSoundEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/PushFailedSoundEnable", enable); + m_mutex.unlock(); +} + +void Config::setPushFailedSoundPath(QString path) +{ + m_mutex.lock(); + m_settings->setValue("Client/PushFailedSoundPath", path); + m_mutex.unlock(); +} + + +bool Config::exitSoundEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/ExitSoundEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +QString Config::exitSoundPath() +{ + m_mutex.lock(); + QString path = m_settings->value("Client/ExitSoundPath").toString(); + m_mutex.unlock(); + return path; +} + +void Config::setExitSoundEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/ExitSoundEnable", enable); + m_mutex.unlock(); +} + +void Config::setExitSoundPath(QString path) +{ + m_mutex.lock(); + m_settings->setValue("Client/ExitSoundPath", path); + m_mutex.unlock(); +} + +bool Config::reloginSoundEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/ReloginSoundEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +QString Config::reloginSoundPath() +{ + m_mutex.lock(); + QString path = m_settings->value("Client/ReloginSoundPath").toString(); + m_mutex.unlock(); + return path; +} + +void Config::setReloginSoundEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/ReloginSoundEnable", enable); + m_mutex.unlock(); +} + +void Config::setReloginSoundPath(QString path) +{ + m_mutex.lock(); + m_settings->setValue("Client/ReloginSoundPath", path); + m_mutex.unlock(); +} + +bool Config::softUpdateSoundEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/SoftUpdateSoundEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +QString Config::softUpdateSoundPath() +{ + m_mutex.lock(); + QString path = m_settings->value("Client/SoftUpdateSoundPath").toString(); + m_mutex.unlock(); + return path; +} + +void Config::setSoftUpdateSoundEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/SoftUpdateSoundEnable", enable); + m_mutex.unlock(); +} + +void Config::setSoftUpdateSoundPath(QString path) +{ + m_mutex.lock(); + m_settings->setValue("Client/SoftUpdateSoundPath", path); + m_mutex.unlock(); +} + +int Config::session_calc_type() +{ + m_mutex.lock(); + int type = m_settings->value("Client/HandicapCalcType", 3).toInt(); + m_mutex.unlock(); + return type; +} + +void Config::set_session_calc_type(int type) +{ + m_mutex.lock(); + m_settings->setValue("Client/HandicapCalcType", type); + m_mutex.unlock(); +} + +bool Config::gameOppositeEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/GameOppositeEnable", false).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setGameOppositeEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/GameOppositeEnable", enable); + m_mutex.unlock(); +} + +bool Config::handicapOppositeEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/HandicapOppositeEnable", false).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setHandicapOppositeEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/HandicapOppositeEnable", enable); + m_mutex.unlock(); +} + +int Config::ptype_calc_type() +{ + m_mutex.lock(); + int type = m_settings->value("Client/SessionCalcType", 0).toInt(); + m_mutex.unlock(); + return type; +} + +void Config::set_ptype_calc_type(int type) +{ + m_mutex.lock(); + m_settings->setValue("Client/SessionCalcType", type); + m_mutex.unlock(); +} + +int Config::gameCalcType() +{ + m_mutex.lock(); + int type = m_settings->value("Client/GameCalcType", 2).toInt(); + m_mutex.unlock(); + return type; +} + +void Config::setGameCalcType(int type) +{ + m_mutex.lock(); + m_settings->setValue("Client/GameCalcType", type); + m_mutex.unlock(); +} + +bool Config::gameFollowTimesMaxEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/GameFollowTimesMaxEnable", false).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setGameFollowTimesMaxEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/GameFollowTimesMaxEnable", enable); + m_mutex.unlock(); +} + +int Config::gameFollowTimesMax() +{ + m_mutex.lock(); + int times = m_settings->value("Client/GameFollowTimesMax", 100).toInt(); + m_mutex.unlock(); + return times; +} + +void Config::setGameFollowTimesMax(int times) +{ + m_mutex.lock(); + m_settings->setValue("Client/GameFollowTimesMax", times); + m_mutex.unlock(); +} + +bool Config::gameFollowAmountMaxEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/FollowAmountMaxEnable", false).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setGameFollowAmountMaxEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/GameFollowAmountMaxEnable", enable); + m_mutex.unlock(); +} + +float Config::gameFollowAmountMax() +{ + m_mutex.lock(); + float amount = m_settings->value("Client/GameFollowAmountMax", 100000).toFloat(); + m_mutex.unlock(); + return amount; +} + +void Config::setGameFollowAmountMax(float amount) +{ + m_mutex.lock(); + m_settings->setValue("Client/GameFollowAmountMax", amount); + m_mutex.unlock(); +} + +bool Config::handicapFollowTimesMaxEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/HandicapFollowTimesMaxEnable", false).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setHandicapFollowTimesMaxEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/HandicapFollowTimesMaxEnable", enable); + m_mutex.unlock(); +} + +int Config::handicapFollowTimesMax() +{ + m_mutex.lock(); + int times = m_settings->value("Client/HandicapFollowTimesMax", 10).toInt(); + m_mutex.unlock(); + return times; +} + +void Config::setHandicapFollowTimesMax(int times) +{ + m_mutex.lock(); + m_settings->setValue("Client/HandicapFollowTimesMax", times); + m_mutex.unlock(); +} + +bool Config::handicapFollowAmountMaxEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/HandicapFollowAmountMaxEnable", false).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setHandicapFollowAmountMaxEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/HandicapFollowAmountMaxEnable", enable); + m_mutex.unlock(); +} + +float Config::handicapFollowAmountMax() +{ + m_mutex.lock(); + float amount = m_settings->value("Client/HandicapFollowAmountMax", 10000).toFloat(); + m_mutex.unlock(); + return amount; +} + +void Config::setHandicapFollowAmountMax(float amount) +{ + m_mutex.lock(); + m_settings->setValue("Client/HandicapFollowAmountMax", amount); + m_mutex.unlock(); +} + +QList> Config::setting() +{ + m_mutex.lock(); + QList> list = toMapList(m_settings->value("Client/SettingList").toString()); + m_mutex.unlock(); + + // 如果列表为空,添加默认的第一行设置 + if (list.isEmpty()) { + QMap defaultRow; + defaultRow["enable"] = "true"; // 默认勾选 + defaultRow["username"] = "其他会员"; + defaultRow["type"] = "会员"; + // 设置其他字段的默认值 + defaultRow["hkEnable"] = "true"; + defaultRow["hkChange"] = "H"; + defaultRow["masEnable"] = "true"; + defaultRow["masChange"] = "M"; + defaultRow["idaEnable"] = "true"; + defaultRow["idaChange"] = "I"; + defaultRow["eurEnable"] = "true"; + defaultRow["eurChange"] = "E"; + defaultRow["followType"] = "[]"; // 空列表的JSON表示 + defaultRow["calcType"] = "缩放比率"; + defaultRow["calcType_custom"] = "[]"; // 空列表的JSON表示 + defaultRow["calcType_scale"] = "1"; + defaultRow["calcType_fixed"] = "50"; + + list.append(defaultRow); + } + + return list; +} + +void Config::setSetting(QList> list) +{ + m_mutex.lock(); + m_settings->setValue("Client/SettingList", toJson(list)); + m_mutex.unlock(); +} + +QList Config::followType() +{ + m_mutex.lock(); + QList list = toStringList(m_settings->value("Client/FollowType").toString()); + if (list.isEmpty()) + { + list.append("normal"); + list.append("addTime"); + list.append("corner"); + list.append("free"); + list.append("promotion"); + list.append("champion"); + list.append("point"); + } + m_mutex.unlock(); + return list; +} + +void Config::setFollowType(QList list) +{ + m_mutex.lock(); + m_settings->setValue("Client/FollowType", toJson(list)); + m_mutex.unlock(); +} + +int Config::lackType() +{ + m_mutex.lock(); + int type = m_settings->value("Client/LackType", 0).toInt(); + m_mutex.unlock(); + return type; +} + +void Config::setLackType(int type) +{ + m_mutex.lock(); + m_settings->setValue("Client/LackType", type); + m_mutex.unlock(); +} + +int Config::followDeviceType() +{ + m_mutex.lock(); + int type = m_settings->value("Client/FollowDeviceType", 0).toInt(); + m_mutex.unlock(); + return type; +} + +void Config::setFollowDeviceType(int type) +{ + m_mutex.lock(); + m_settings->setValue("Client/FollowDeviceType", type); + m_mutex.unlock(); +} + +int Config::rebetMaxTimes() +{ + m_mutex.lock(); + int times = m_settings->value("Client/RebetMaxTimes", 100).toInt(); + m_mutex.unlock(); + return times; +} + +void Config::setReBetMaxTimes(int times) +{ + m_mutex.lock(); + m_settings->setValue("Client/RebetMaxTimes", times); + m_mutex.unlock(); +} + +int Config::rebetSleepTimes() +{ + m_mutex.lock(); + int times = m_settings->value("Client/RebetSleepTimes", 30).toInt(); + m_mutex.unlock(); + return times; +} + +void Config::setRebetSleepTimes(int times) +{ + m_mutex.lock(); + m_settings->setValue("Client/RebetSleepTimes", times); + m_mutex.unlock(); +} + +int Config::rebetSleep() +{ + m_mutex.lock(); + int sec = m_settings->value("Client/RebetSleep", 10).toInt(); + m_mutex.unlock(); + return sec; +} + +void Config::setRebetSleep(int sec) +{ + m_mutex.lock(); + m_settings->setValue("Client/RebetSleep", sec); + m_mutex.unlock(); +} + +bool Config::sessionAutoChangeEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/SessionAutoChangeEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setSessionAutoChangeEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/SessionAutoChangeEnable", enable); + m_mutex.unlock(); +} + +bool Config::ignoreScoreChangedEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/IgnoreScoreChangedEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setIgnoreScoreChangedEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/IgnoreScoreChangedEnable", enable); + m_mutex.unlock(); +} + +bool Config::followFixedScoreEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Client/FollowFixedScoreEnable", false).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setFollowFixedScoreEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Client/FollowFixedScoreEnable", enable); + m_mutex.unlock(); +} + +int Config::fixedScoreMaster() +{ + m_mutex.lock(); + int master = m_settings->value("Client/FixedScoreMaster", 0).toInt(); + m_mutex.unlock(); + return master; +} + +void Config::setFixedScoreMaster(int master) +{ + m_mutex.lock(); + m_settings->setValue("Client/FixedScoreMaster", master); + m_mutex.unlock(); +} + +int Config::fixedScoreVisitor() +{ + m_mutex.lock(); + int visitor = m_settings->value("Client/FixedScoreVisitor", 0).toInt(); + m_mutex.unlock(); + return visitor; +} + +void Config::setFixedScoreVisitor(int visitor) +{ + m_mutex.lock(); + m_settings->setValue("Client/FixedScoreVisitor", visitor); + m_mutex.unlock(); +} + + + +bool Config::notice_status() +{ + m_mutex.lock(); + bool status = m_settings->value("Client/NoticeStatus", false).toBool(); + m_mutex.unlock(); + return status; +} + +void Config::set_notice_status(bool status) +{ + m_mutex.lock(); + m_settings->setValue("Client/NoticeStatus", QVariant::fromValue(status)); + m_mutex.unlock(); +} + +QString Config::notice_account() +{ + m_mutex.lock(); + QString account = m_settings->value("Client/NoticeAccount").toString(); + m_mutex.unlock(); + return account; +} + +void Config::set_notice_account(QString account) +{ + m_mutex.lock(); + m_settings->setValue("Client/NoticeAccount", QVariant::fromValue(account)); + m_mutex.unlock(); +} + +QList Config::acceptGameList() +{ + m_mutex.lock(); + QList list = toStringList(m_settings->value("Client/AcceptGameList").toString()); + m_mutex.unlock(); + return list; +} + +QList Config::screenGameList() +{ + m_mutex.lock(); + QList list = toStringList(m_settings->value("Client/ScreenGameList").toString()); + m_mutex.unlock(); + return list; +} + +void Config::setAcceptGameList(QList list) +{ + m_mutex.lock(); + m_settings->setValue("Client/AcceptGameList", toJson(list)); + m_mutex.unlock(); +} + +void Config::setScreenGameList(QList list) +{ + m_mutex.lock(); + m_settings->setValue("Client/ScreenGameList", toJson(list)); + m_mutex.unlock(); +} + + + + +// 接收注单表操作 +bool Config::remove_accept_order(const QString& tid) { + return remove_order("accept_orders", tid); +} + +bool Config::remove_accept_orders(const QList& tidList) { + return remove_orders("accept_orders", tidList); +} + +bool Config::clear_accept_orders() { + return clear_table("accept_orders"); +} + +// 筛选注单表操作 +bool Config::remove_screen_order(const QString& tid) { + return remove_order("screen_orders", tid); +} + +bool Config::remove_screen_orders(const QList& tidList) { + return remove_orders("screen_orders", tidList); +} + +bool Config::clear_screen_orders() { + return clear_table("screen_orders"); +} + +// 成功注单表操作 +bool Config::remove_success_order(const QString& tid) { + return remove_order("success_orders", tid); +} + +bool Config::remove_success_orders(const QList& tidList) { + return remove_orders("success_orders", tidList); +} + +bool Config::clear_success_orders() { + return clear_table("success_orders"); +} + +// 失败注单表操作 +bool Config::remove_failed_order(const QString& tid) { + return remove_order("failed_orders", tid); +} + +bool Config::remove_failed_orders(const QList& tidList) { + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + QStringList placeholders; + for (int i = 0; i < tidList.size(); ++i) { + placeholders << QString(":TID%1").arg(i); + } + + query.prepare(QString("DELETE FROM failed_orders WHERE TID IN (%1)") + .arg(placeholders.join(","))); + + for (int i = 0; i < tidList.size(); ++i) { + query.bindValue(QString(":TID%1").arg(i), tidList[i]); + } + + if (!query.exec()) { + qDebug() << "[数据库] 批量删除失败注单失败:" << query.lastError(); + return false; + } + return true; +} + +bool Config::clear_failed_orders() { + return clear_table("failed_orders"); +} + +// 补单表操作 +bool Config::remove_rebet_order(const QString& tid) { + return remove_order("rebet_orders", tid); +} + +bool Config::remove_rebet_orders(const QList& tidList) { + return remove_orders("rebet_orders", tidList); +} + +bool Config::clear_rebet_orders() { + return clear_table("rebet_orders"); +} + +int Config::get_rebet_reason_times(const QString &tid, const QString &reason) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + // 使用参数化查询避免SQL注入 + QString sql = "SELECT COUNT(*) FROM rebet_orders WHERE TID = :TID AND REASON LIKE :REASON"; + if (!query.prepare(sql)) { + qDebug() << "[数据库] 检查筛选注单失败原因次数失败:" << query.lastError(); + return 0; // 统一返回0 + } + + query.bindValue(":TID", tid); + query.bindValue(":REASON", "%" + reason + "%"); // 如果需要前后通配符 + + if (!query.exec()) { + qDebug() << "[数据库] 执行筛选注单失败原因次数失败:" << query.lastError(); + return 0; + } + + if (query.next()) { + return query.value(0).toInt(); + } + + return 0; +} + +// 私有辅助方法 +bool Config::remove_order(const QString& tableName, const QString& tid) { + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + query.prepare(QString("DELETE FROM %1 WHERE tid = ?").arg(tableName)); + query.addBindValue(tid); + + if (!query.exec()) { + qDebug() << QString("[数据库] 删除%1记录失败:").arg(tableName) << query.lastError(); + return false; + } + return true; +} + +bool Config::remove_orders(const QString& tableName, const QList& tidList) { + if (tidList.isEmpty()) return true; + + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + QStringList placeholders; + for (int i = 0; i < tidList.size(); ++i) { + placeholders << QString(":tid%1").arg(i); + } + + query.prepare(QString("DELETE FROM %1 WHERE tid IN (%2)") + .arg(tableName) + .arg(placeholders.join(","))); + + for (int i = 0; i < tidList.size(); ++i) { + query.bindValue(QString(":tid%1").arg(i), tidList[i]); + } + + if (!query.exec()) { + qDebug() << QString("[数据库] 批量删除%1记录失败:").arg(tableName) << query.lastError(); + return false; + } + return true; +} + +bool Config::clear_table(const QString& tableName) { + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + if (!query.exec(QString("DELETE FROM %1").arg(tableName))) { + qDebug() << QString("[数据库] 清空%1失败:").arg(tableName) << query.lastError(); + return false; + } + return true; +} + + + + +/** + * 检查是否存在“同赛事对头单”(适用于独赢、单双) + * @return true=允许下注,false=存在对头单 + */ +bool Config::checkOppositeBet(const QMap &order) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + // 基础SQL查询 + QString sql = R"( + SELECT COUNT(*) + FROM success_orders + WHERE GT = :GT + AND LEAGUE = :LEAGUE + AND TEAM_C = :TEAM_C + AND TEAM_H = :TEAM_H + AND G_TIME = :G_TIME + AND ORDER_TYPE != :ORDER_TYPE + )"; + + // 根据配置策略添加不同的查询条件 + int session_calc_type = g_config->session_calc_type(); + + // 盘口计算类型策略 + switch (session_calc_type) { + case 0: // 早盘/今日/滚球 分别计算 + sql += " AND SESSION = :SESSION "; + break; + case 1: // 早盘+今日/滚球 分别计算 + sql += " AND (SESSION = :SESSION OR SESSION IN ('今日', '早盘')) "; + break; + case 2: // 早盘/今日+滚球 分别计算 + sql += " AND (SESSION = :SESSION OR SESSION = '滚球') "; + break; + case 3: // 早盘+今日+滚球 统一计算 + // 不需要额外条件,所有场次一起计算 + break; + } + + // 处理WAGERS_TYPE:去掉(滚球)前缀和可能的空格 + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) = :CLEAN_WTYPE "; + + query.prepare(sql); + + // 绑定必需参数 + query.bindValue(":GT", order["GT"]); + query.bindValue(":LEAGUE", order["LEAGUE"]); + query.bindValue(":TEAM_C", order["TEAM_C"]); + query.bindValue(":TEAM_H", order["TEAM_H"]); + query.bindValue(":G_TIME", order["G_TIME"]); + query.bindValue(":ORDER_TYPE", order["ORDER_TYPE"]); + // 处理WAGERS_TYPE:去掉(滚球)前缀和所有空格 + QString cleanWtype = order["WAGERS_TYPE"]; + cleanWtype = cleanWtype.replace("(滚球)", "").replace(" ", ""); + query.bindValue(":CLEAN_WTYPE", cleanWtype); + + // 根据策略绑定可选参数 + if (session_calc_type != 3) { // 如果不是统一计算模式 + query.bindValue(":SESSION", order["SESSION"]); + } + + if (query.exec() && query.next()) { + int oppositeCount = query.value(0).toInt(); + qDebug() << "Found" << oppositeCount << "opposite bets for order:" << order["TID"]; + return oppositeCount == 0; // 无对头单才返回true + } + + qWarning() << "Failed to check opposite bet for order:" << order["TID"] + << "Error:" << query.lastError().text(); + return true; // 查询失败默认允许 +} +/** + * 检查是否存在"同赛事盘口对头单"(适用于让球、大小) + * @return true=允许下注,false=存在对头单 + */ +bool Config::checkOppositeHandicap(const QMap &order) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + QString currentHandicap = order["ORDER_CON"]; + // 计算相反盘口 + QString oppositeHandicap = calculateOppositeHandicap(currentHandicap); + + // 查询相反盘口的订单(使用TRIM处理数据库中的空格) + QString sql = R"( + SELECT COUNT(*) + FROM success_orders + WHERE GT = :GT + AND LEAGUE = :LEAGUE + AND TEAM_C = :TEAM_C + AND TEAM_H = :TEAM_H + AND G_TIME = :G_TIME + AND ORDER_TYPE = :ORDER_TYPE + AND TRIM(ORDER_CON) = :opposite_handicap + )"; + + // 处理WAGERS_TYPE:去掉(滚球)前缀和可能的空格 + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) = :CLEAN_WTYPE "; + + // 根据配置策略添加不同的查询条件 + int session_calc_type = g_config->session_calc_type(); + + // 盘口计算类型策略 + switch (session_calc_type) { + case 0: // 早盘/今日/滚球 分别计算 + sql += " AND SESSION = :SESSION "; + break; + case 1: // 早盘+今日/滚球 分别计算 + sql += " AND (SESSION = :SESSION OR SESSION IN ('今日', '早盘')) "; + break; + case 2: // 早盘/今日+滚球 分别计算 + sql += " AND (SESSION = :SESSION OR SESSION = '滚球') "; + break; + case 3: // 早盘+今日+滚球 统一计算 + // 不需要额外条件,所有场次一起计算 + break; + } + + query.prepare(sql); + + // 绑定必需参数 + query.bindValue(":GT", order["GT"]); + query.bindValue(":LEAGUE", order["LEAGUE"]); + query.bindValue(":TEAM_C", order["TEAM_C"]); + query.bindValue(":TEAM_H", order["TEAM_H"]); + query.bindValue(":G_TIME", order["G_TIME"]); + query.bindValue(":ORDER_TYPE", order["ORDER_TYPE"]); + // 处理WAGERS_TYPE:去掉(滚球)前缀和所有空格 + QString cleanWtype = order["WAGERS_TYPE"]; + cleanWtype = cleanWtype.replace("(滚球)", "").replace(" ", ""); + query.bindValue(":CLEAN_WTYPE", cleanWtype); + + // 根据策略绑定可选参数 + if (session_calc_type != 3) { // 如果不是统一计算模式 + query.bindValue(":SESSION", order["SESSION"]); + } + if (query.exec() && query.next()) { + int oppositeCount = query.value(0).toInt(); + qDebug() << "Found" << oppositeCount << "opposite bets for order:" << order["TID"]; + return oppositeCount == 0; // 无对头单才返回true + } + + qWarning() << "Failed to check opposite bet for order:" << order["TID"] + << "Error:" << query.lastError().text(); + return true; // 查询失败默认允许 +} + +/** + * 检查同赛事最多跟单次数 + * @param order 订单信息 + * @return true=未超出限制(允许下单),false=超出限制(拒绝下单) + */ +bool Config::check_game_follow_max_times(const QMap &order) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + // 基础SQL查询 + QString sql = R"( + SELECT COUNT(*) + FROM success_orders + WHERE GT = :GT + AND LEAGUE = :LEAGUE + AND TEAM_C = :TEAM_C + AND TEAM_H = :TEAM_H + AND G_TIME = :G_TIME + )"; + + // 根据配置策略添加不同的查询条件 + int session_calc_type = g_config->session_calc_type(); + int ptype_calc_type = g_config->ptype_calc_type(); + int gameCalcType = g_config->gameCalcType(); + + // 辅助函数:清理WAGERS_TYPE中的(滚球)前缀和空格 + auto cleanWagersType = [](const QString &wtype) -> QString { + QString cleaned = wtype; + cleaned.replace("(滚球)", "").replace(" ", "").trimmed(); + return cleaned; + }; + + // 盘口计算类型策略 + switch (session_calc_type) { + case 0: // 早盘/今日/滚球 分别计算 + sql += " AND SESSION = :SESSION "; + break; + case 1: // 早盘+今日/滚球 分别计算 + sql += " AND (SESSION = :SESSION OR SESSION IN ('FT', 'FU')) "; + break; + case 2: // 早盘/今日+滚球 分别计算 + sql += " AND (SESSION = :SESSION OR SESSION = 'RB') "; + break; + case 3: // 早盘+今日+滚球 统一计算 + // 不需要额外条件,所有场次一起计算 + break; + } + + // 场次项目计算类型策略 + if (ptype_calc_type == 0) { + // 所有场次项目分别计算 + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) = :WAGERS_TYPE "; + sql += " AND STAGE = :STAGE";// 场次 + } + + // 游戏计算类型策略 + switch (gameCalcType) { + case 0: // 所有注单类型分别计算 + // 这里需要根据WAGERS_TYPE和ORDER_TYPE来精确匹配 + if (order["WAGERS_TYPE"].contains("让球")) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%让球%'"; + } + else if (order["WAGERS_TYPE"].contains("大 / 小") && + !order["WAGERS_TYPE"].contains(order["TEAM_H"]) && + !order["WAGERS_TYPE"].contains(order["TEAM_C"])) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%大/小%'"; + } + else if (order["WAGERS_TYPE"].contains("独赢")) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%独赢%'"; + } + else if (order["WAGERS_TYPE"].contains("单 / 双")) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%单/双%'"; + } + else if (order["WAGERS_TYPE"].contains("大 / 小") && + order["WAGERS_TYPE"].contains(order["TEAM_H"])) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%大/小%'"; + sql += " AND WAGERS_TYPE LIKE :team_h"; + } + else if (order["WAGERS_TYPE"].contains("大 / 小") && + order["WAGERS_TYPE"].contains(order["TEAM_C"])) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%大/小%'"; + sql += " AND WAGERS_TYPE LIKE :team_c"; + } + break; + + case 1: // [让球|大小|独赢|单双|主大小|客大小]分开计算 + sql += " AND ORDER_TYPE = :ORDER_TYPE"; + break; + + case 2: // 所有注单类型统一计算 + break; + } + + query.prepare(sql); + + // 绑定基础参数 + query.bindValue(":GT", order["GT"]); + query.bindValue(":LEAGUE", order["LEAGUE"]); + query.bindValue(":TEAM_C", order["TEAM_C"]); + query.bindValue(":TEAM_H", order["TEAM_H"]); + query.bindValue(":G_TIME", order["G_TIME"]); + + // 根据策略绑定可选参数 + if (session_calc_type != 3) { // 如果不是统一计算模式 + query.bindValue(":SESSION", order["SESSION"]); + } + + if (ptype_calc_type == 0) { // 如果场次项目分别计算 + QString cleanWtype = cleanWagersType(order["WAGERS_TYPE"]); + query.bindValue(":WAGERS_TYPE", cleanWtype); + query.bindValue(":STAGE",order["STAGE"]); + } + + // 绑定游戏类型相关参数 + switch (gameCalcType) { + case 0: // 所有注单类型分别计算 + if (order["WAGERS_TYPE"].contains("大 / 小") && + order["WAGERS_TYPE"].contains(order["TEAM_H"])) { + query.bindValue(":team_h", "%" + order["TEAM_H"] + "%"); + } + else if (order["WAGERS_TYPE"].contains("大 / 小") && + order["WAGERS_TYPE"].contains(order["TEAM_C"])) { + query.bindValue(":team_c", "%" + order["TEAM_C"] + "%"); + } + break; + + case 1: // [让球|大小|独赢|单双|主大小|客大小]分开计算 + query.bindValue(":ORDER_TYPE", order["ORDER_TYPE"]); + break; + + case 2: // 所有注单类型统一计算 + break; + } + + if (query.exec() && query.next()) { + int currentCount = query.value(0).toInt(); + int maxTimes = g_config->gameFollowTimesMax(); + + qDebug() << "Current follow times for game" << order["GT"] << ":" << currentCount + << ", Max allowed:" << maxTimes; + + // true表示未超出限制(允许),false表示超出限制(拒绝) + return currentCount < maxTimes; + } + + qWarning() << "Failed to check game follow times for order:" << order["GT"] + << "Error:" << query.lastError().text(); + return false; // 查询失败默认拒绝(出于安全考虑) +} + +/** + * 检查同赛事最多下注金额 + * @param order 订单信息 + * @return true=未超出限制(允许下单),false=超出限制(拒绝下单) + */ +bool Config::check_game_follow_max_amount(const QMap &order) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + // 基础SQL查询 - 改为求和金额 + QString sql = R"( + SELECT SUM(gold) + FROM success_orders + WHERE GT = :GT + AND LEAGUE = :LEAGUE + AND TEAM_C = :TEAM_C + AND TEAM_H = :TEAM_H + AND G_TIME = :G_TIME + )"; + + // 根据配置策略添加不同的查询条件 + int session_calc_type = g_config->session_calc_type(); + int ptype_calc_type = g_config->ptype_calc_type(); + int gameCalcType = g_config->gameCalcType(); + + // 辅助函数:清理WAGERS_TYPE中的(滚球)前缀和空格 + auto cleanWagersType = [](const QString &wtype) -> QString { + QString cleaned = wtype; + cleaned.replace("(滚球)", "").replace(" ", "").trimmed(); + return cleaned; + }; + + // 盘口计算类型策略 + switch (session_calc_type) { + case 0: // 早盘/今日/滚球 分别计算 + sql += " AND SESSION = :SESSION "; + break; + case 1: // 早盘+今日/滚球 分别计算 + sql += " AND (SESSION = :SESSION OR SESSION IN ('FT', 'FU')) "; + break; + case 2: // 早盘/今日+滚球 分别计算 + sql += " AND (SESSION = :SESSION OR SESSION = 'RB') "; + break; + case 3: // 早盘+今日+滚球 统一计算 + // 不需要额外条件,所有场次一起计算 + break; + } + + // 场次项目计算类型策略 + if (ptype_calc_type == 0) { + // 所有场次项目分别计算 + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) = :WAGERS_TYPE "; + sql += " AND STAGE = :STAGE";// 场次 + } + + // 游戏计算类型策略 + switch (gameCalcType) { + case 0: // 所有注单类型分别计算 + // 这里需要根据WAGERS_TYPE和ORDER_TYPE来精确匹配 + if (order["WAGERS_TYPE"].contains("让球")) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%让球%'"; + } + else if (order["WAGERS_TYPE"].contains("大 / 小") && + !order["WAGERS_TYPE"].contains(order["TEAM_H"]) && + !order["WAGERS_TYPE"].contains(order["TEAM_C"])) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%大/小%'"; + } + else if (order["WAGERS_TYPE"].contains("独赢")) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%独赢%'"; + } + else if (order["WAGERS_TYPE"].contains("单 / 双")) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%单/双%'"; + } + else if (order["WAGERS_TYPE"].contains("大 / 小") && + order["WAGERS_TYPE"].contains(order["TEAM_H"])) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%大/小%'"; + sql += " AND WAGERS_TYPE LIKE :team_h"; + } + else if (order["WAGERS_TYPE"].contains("大 / 小") && + order["WAGERS_TYPE"].contains(order["TEAM_C"])) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%大/小%'"; + sql += " AND WAGERS_TYPE LIKE :team_c"; + } + break; + + case 1: // [让球|大小|独赢|单双|主大小|客大小]分开计算 + sql += " AND ORDER_TYPE = :ORDER_TYPE"; + break; + + case 2: // 所有注单类型统一计算 + break; + } + + query.prepare(sql); + + // 绑定基础参数 + query.bindValue(":GT", order["GT"]); + query.bindValue(":LEAGUE", order["LEAGUE"]); + query.bindValue(":TEAM_C", order["TEAM_C"]); + query.bindValue(":TEAM_H", order["TEAM_H"]); + query.bindValue(":G_TIME", order["G_TIME"]); + + // 根据策略绑定可选参数 + if (session_calc_type != 3) { // 如果不是统一计算模式 + query.bindValue(":SESSION", order["SESSION"]); + } + + if (ptype_calc_type == 0) { // 如果场次项目分别计算 + QString cleanWtype = cleanWagersType(order["WAGERS_TYPE"]); + query.bindValue(":WAGERS_TYPE", cleanWtype); + query.bindValue(":STAGE", order["STAGE"]); + } + + // 绑定游戏类型相关参数 + switch (gameCalcType) { + case 0: // 所有注单类型分别计算 + if (order["WAGERS_TYPE"].contains("大 / 小") && + order["WAGERS_TYPE"].contains(order["TEAM_H"])) { + query.bindValue(":team_h", "%" + order["TEAM_H"] + "%"); + } + else if (order["WAGERS_TYPE"].contains("大 / 小") && + order["WAGERS_TYPE"].contains(order["TEAM_C"])) { + query.bindValue(":team_c", "%" + order["TEAM_C"] + "%"); + } + break; + + case 1: // [让球|大小|独赢|单双|主大小|客大小]分开计算 + query.bindValue(":ORDER_TYPE", order["ORDER_TYPE"]); + break; + + case 2: // 所有注单类型统一计算 + break; + } + + if (query.exec() && query.next()) { + // 获取当前总下注金额,注意SUM可能返回NULL + double currentAmount = 0.0; + if (!query.value(0).isNull()) { + currentAmount = query.value(0).toDouble(); + } + + // 加上当前订单的金额 + double orderAmount = order["GOLD"].toDouble(); + double totalAmount = currentAmount + orderAmount; + + double maxAmount = g_config->gameFollowAmountMax(); + + qDebug() << "Current bet amount for game" << order["GT"] << ":" << currentAmount + << ", Order amount:" << orderAmount + << ", Total will be:" << totalAmount + << ", Max allowed:" << maxAmount; + + // true表示未超出限制(允许),false表示超出限制(拒绝) + return totalAmount <= maxAmount; + } + + qWarning() << "Failed to check game bet amount for order:" << order["GT"] + << "Error:" << query.lastError().text(); + return false; // 查询失败默认拒绝(出于安全考虑) +} +/** + * 检查同赛事盘口最多跟单次数 + * @param order 订单信息 + * @return true=未超出限制(允许下单),false=超出限制(拒绝下单) + */ +bool Config::check_handicap_follow_max_times(const QMap &order) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + // 基础SQL查询 + QString sql = R"( + SELECT COUNT(*) + FROM success_orders + WHERE GT = :GT + AND LEAGUE = :LEAGUE + AND TEAM_C = :TEAM_C + AND TEAM_H = :TEAM_H + AND G_TIME = :G_TIME + AND ORDER_CON = :ORDER_CON + )"; + + // 根据配置策略添加不同的查询条件 + int session_calc_type = g_config->session_calc_type(); + int ptype_calc_type = g_config->ptype_calc_type(); + int gameCalcType = g_config->gameCalcType(); + + // 辅助函数:清理WAGERS_TYPE中的(滚球)前缀和空格 + auto cleanWagersType = [](const QString &wtype) -> QString { + QString cleaned = wtype; + cleaned.replace("(滚球)", "").replace(" ", "").trimmed(); + return cleaned; + }; + + // 盘口计算类型策略 + switch (session_calc_type) { + case 0: // 早盘/今日/滚球 分别计算 + sql += " AND SESSION = :SESSION "; + break; + case 1: // 早盘+今日/滚球 分别计算 + sql += " AND (SESSION = :SESSION OR SESSION IN ('FT', 'FU')) "; + break; + case 2: // 早盘/今日+滚球 分别计算 + sql += " AND (SESSION = :SESSION OR SESSION = 'RB') "; + break; + case 3: // 早盘+今日+滚球 统一计算 + // 不需要额外条件,所有场次一起计算 + break; + } + + // 场次项目计算类型策略 + if (ptype_calc_type == 0) { + // 所有场次项目分别计算 + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) = :WAGERS_TYPE "; + sql += " AND STAGE = :STAGE";// 场次 + } + + // 游戏计算类型策略 + switch (gameCalcType) { + case 0: // 所有注单类型分别计算 + // 这里需要根据WAGERS_TYPE和ORDER_TYPE来精确匹配 + if (order["WAGERS_TYPE"].contains("让球")) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%让球%'"; + } + else if (order["WAGERS_TYPE"].contains("大 / 小") && + !order["WAGERS_TYPE"].contains(order["TEAM_H"]) && + !order["WAGERS_TYPE"].contains(order["TEAM_C"])) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%大/小%'"; + } + else if (order["WAGERS_TYPE"].contains("独赢")) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%独赢%'"; + } + else if (order["WAGERS_TYPE"].contains("单 / 双")) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%单/双%'"; + } + else if (order["WAGERS_TYPE"].contains("大 / 小") && + order["WAGERS_TYPE"].contains(order["TEAM_H"])) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%大/小%'"; + sql += " AND WAGERS_TYPE LIKE :team_h"; + } + else if (order["WAGERS_TYPE"].contains("大 / 小") && + order["WAGERS_TYPE"].contains(order["TEAM_C"])) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%大/小%'"; + sql += " AND WAGERS_TYPE LIKE :team_c"; + } + break; + + case 1: // [让球|大小|独赢|单双|主大小|客大小]分开计算 + sql += " AND ORDER_TYPE = :ORDER_TYPE"; + break; + + case 2: // 所有注单类型统一计算 + break; + } + + query.prepare(sql); + + // 绑定基础参数 + query.bindValue(":GT", order["GT"]); + query.bindValue(":LEAGUE", order["LEAGUE"]); + query.bindValue(":TEAM_C", order["TEAM_C"]); + query.bindValue(":TEAM_H", order["TEAM_H"]); + query.bindValue(":G_TIME", order["G_TIME"]); + query.bindValue(":ORDER_CON",order["ORDER_CON"]); + + // 根据策略绑定可选参数 + if (session_calc_type != 3) { // 如果不是统一计算模式 + query.bindValue(":SESSION", order["SESSION"]); + } + + if (ptype_calc_type == 0) { // 如果场次项目分别计算 + QString cleanWtype = cleanWagersType(order["WAGERS_TYPE"]); + query.bindValue(":WAGERS_TYPE", cleanWtype); + query.bindValue(":STAGE", order["STAGE"]); + } + + // 绑定游戏类型相关参数 + switch (gameCalcType) { + case 0: // 所有注单类型分别计算 + if (order["WAGERS_TYPE"].contains("大 / 小") && + order["WAGERS_TYPE"].contains(order["TEAM_H"])) { + query.bindValue(":team_h", "%" + order["TEAM_H"] + "%"); + } + else if (order["WAGERS_TYPE"].contains("大 / 小") && + order["WAGERS_TYPE"].contains(order["TEAM_C"])) { + query.bindValue(":team_c", "%" + order["TEAM_C"] + "%"); + } + break; + + case 1: // [让球|大小|独赢|单双|主大小|客大小]分开计算 + query.bindValue(":ORDER_TYPE", order["ORDER_TYPE"]); + break; + + case 2: // 所有注单类型统一计算 + break; + } + + if (query.exec() && query.next()) { + int currentCount = query.value(0).toInt(); + int maxTimes = g_config->gameFollowTimesMax(); + + qDebug() << "Current follow times for game" << order["GT"] << ":" << currentCount + << ", Max allowed:" << maxTimes; + + // true表示未超出限制(允许),false表示超出限制(拒绝) + return currentCount < maxTimes; + } + + qWarning() << "Failed to check game follow times for order:" << order["GT"] + << "Error:" << query.lastError().text(); + return false; // 查询失败默认拒绝(出于安全考虑) +} + +/** + * 检查同赛事盘口最多下注金额 + * @param order 订单信息 + * @return true=未超出限制(允许下单),false=超出限制(拒绝下单) + */ +bool Config::check_handicap_follow_max_amount(const QMap &order) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + + // 基础SQL查询 - 改为求和金额 + QString sql = R"( + SELECT SUM(gold) + FROM success_orders + WHERE GT = :GT + AND LEAGUE = :LEAGUE + AND TEAM_C = :TEAM_C + AND TEAM_H = :TEAM_H + AND G_TIME = :G_TIME + AND ORDER_CON = :ORDER_CON + )"; + + // 根据配置策略添加不同的查询条件 + int session_calc_type = g_config->session_calc_type(); + int ptype_calc_type = g_config->ptype_calc_type(); + int gameCalcType = g_config->gameCalcType(); + + // 辅助函数:清理WAGERS_TYPE中的(滚球)前缀和空格 + auto cleanWagersType = [](const QString &wtype) -> QString { + QString cleaned = wtype; + cleaned.replace("(滚球)", "").replace(" ", "").trimmed(); + return cleaned; + }; + + // 盘口计算类型策略 + switch (session_calc_type) { + case 0: // 早盘/今日/滚球 分别计算 + sql += " AND SESSION = :SESSION "; + break; + case 1: // 早盘+今日/滚球 分别计算 + sql += " AND (SESSION = :SESSION OR SESSION IN ('FT', 'FU')) "; + break; + case 2: // 早盘/今日+滚球 分别计算 + sql += " AND (SESSION = :SESSION OR SESSION = 'RB') "; + break; + case 3: // 早盘+今日+滚球 统一计算 + // 不需要额外条件,所有场次一起计算 + break; + } + + // 场次项目计算类型策略 + if (ptype_calc_type == 0) { + // 所有场次项目分别计算 + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) = :WAGERS_TYPE "; + sql += " AND STAGE = :STAGE";// 场次 + } + + // 游戏计算类型策略 + switch (gameCalcType) { + case 0: // 所有注单类型分别计算 + // 这里需要根据WAGERS_TYPE和ORDER_TYPE来精确匹配 + if (order["WAGERS_TYPE"].contains("让球")) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%让球%'"; + } + else if (order["WAGERS_TYPE"].contains("大 / 小") && + !order["WAGERS_TYPE"].contains(order["TEAM_H"]) && + !order["WAGERS_TYPE"].contains(order["TEAM_C"])) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%大/小%'"; + } + else if (order["WAGERS_TYPE"].contains("独赢")) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%独赢%'"; + } + else if (order["WAGERS_TYPE"].contains("单 / 双")) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%单/双%'"; + } + else if (order["WAGERS_TYPE"].contains("大 / 小") && + order["WAGERS_TYPE"].contains(order["TEAM_H"])) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%大/小%'"; + sql += " AND WAGERS_TYPE LIKE :team_h"; + } + else if (order["WAGERS_TYPE"].contains("大 / 小") && + order["WAGERS_TYPE"].contains(order["TEAM_C"])) { + sql += " AND TRIM(REPLACE(REPLACE(WAGERS_TYPE, '(滚球)', ''), ' ', '')) LIKE '%大/小%'"; + sql += " AND WAGERS_TYPE LIKE :team_c"; + } + break; + + case 1: // [让球|大小|独赢|单双|主大小|客大小]分开计算 + sql += " AND ORDER_TYPE = :ORDER_TYPE"; + break; + + case 2: // 所有注单类型统一计算 + break; + } + + query.prepare(sql); + + // 绑定基础参数 + query.bindValue(":GT", order["GT"]); + query.bindValue(":LEAGUE", order["LEAGUE"]); + query.bindValue(":TEAM_C", order["TEAM_C"]); + query.bindValue(":TEAM_H", order["TEAM_H"]); + query.bindValue(":G_TIME", order["G_TIME"]); + query.bindValue(":ORDER_CON",order["ORDER_CON"]); + + // 根据策略绑定可选参数 + if (session_calc_type != 3) { // 如果不是统一计算模式 + query.bindValue(":SESSION", order["SESSION"]); + } + + if (ptype_calc_type == 0) { // 如果场次项目分别计算 + QString cleanWtype = cleanWagersType(order["WAGERS_TYPE"]); + query.bindValue(":WAGERS_TYPE", cleanWtype); + query.bindValue(":STAGE", order["STAGE"]); + } + + // 绑定游戏类型相关参数 + switch (gameCalcType) { + case 0: // 所有注单类型分别计算 + if (order["WAGERS_TYPE"].contains("大 / 小") && + order["WAGERS_TYPE"].contains(order["TEAM_H"])) { + query.bindValue(":team_h", "%" + order["TEAM_H"] + "%"); + } + else if (order["WAGERS_TYPE"].contains("大 / 小") && + order["WAGERS_TYPE"].contains(order["TEAM_C"])) { + query.bindValue(":team_c", "%" + order["TEAM_C"] + "%"); + } + break; + + case 1: // [让球|大小|独赢|单双|主大小|客大小]分开计算 + query.bindValue(":ORDER_TYPE", order["ORDER_TYPE"]); + break; + + case 2: // 所有注单类型统一计算 + break; + } + + if (query.exec() && query.next()) { + // 获取当前总下注金额,注意SUM可能返回NULL + double currentAmount = 0.0; + if (!query.value(0).isNull()) { + currentAmount = query.value(0).toDouble(); + } + + // 加上当前订单的金额 + double orderAmount = order["GOLD"].toDouble(); + double totalAmount = currentAmount + orderAmount; + + double maxAmount = g_config->gameFollowAmountMax(); + + qDebug() << "Current bet amount for game" << order["GT"] << ":" << currentAmount + << ", Order amount:" << orderAmount + << ", Total will be:" << totalAmount + << ", Max allowed:" << maxAmount; + + // true表示未超出限制(允许),false表示超出限制(拒绝) + return totalAmount <= maxAmount; + } + + qWarning() << "Failed to check game bet amount for order:" << order["GT"] + << "Error:" << query.lastError().text(); + return false; // 查询失败默认拒绝(出于安全考虑) +} + + +/** + * 计算相反盘口(处理空格) + * @param handicap 原始盘口 + * @return 相反盘口(已去除空格) + */ +QString Config::calculateOppositeHandicap(const QString &handicap) +{ + // 先去除前后空格 + QString trimmedHandicap = handicap.trimmed(); + + if (trimmedHandicap.isEmpty() || trimmedHandicap == "0") { + return trimmedHandicap; + } + + // 处理分数盘口 + if (trimmedHandicap.contains("/")) { + QStringList parts = trimmedHandicap.split("/", Qt::SkipEmptyParts); + if (parts.size() == 2) { + QString firstPart = parts[0].trimmed(); + QString secondPart = parts[1].trimmed(); + + QString firstOpposite = calculateSimpleOpposite(firstPart); + QString secondOpposite = calculateSimpleOpposite(secondPart); + return firstOpposite + "/" + secondOpposite; + } + } + + return calculateSimpleOpposite(trimmedHandicap); +} + +/** + * 计算简单盘口的相反值 + */ +QString Config::calculateSimpleOpposite(const QString &handicap) +{ + QString trimmed = handicap.trimmed(); + + if (trimmed.isEmpty()) { + return trimmed; + } + + if (trimmed.startsWith("+")) { + return "-" + trimmed.mid(1).trimmed(); + } + else if (trimmed.startsWith("-")) { + return "+" + trimmed.mid(1).trimmed(); + } + else { + return "-" + trimmed; + } +} + diff --git a/CrownClient/Config.h b/CrownClient/Config.h new file mode 100644 index 0000000..abce7ec --- /dev/null +++ b/CrownClient/Config.h @@ -0,0 +1,630 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +class Config : public QObject +{ + Q_OBJECT +public: + Config(); + ~Config(); + +private: + // 互斥体 + QMutex m_mutex; + // 配置文件 + QSettings* m_settings; +public: + QString toJson(QList> data); + QString toJson(QList data); + QList> toMapList(QString data); + QList toStringList(QString data); + +public: + // 网络验证 -> 用户名 + QString verifyUsername(); + // 网络验证 -> 保存用户名 + void setVerifyUsername(QString username); + // 网络验证 -> 密码 + QString verifyPassword(); + // 网络验证 -> 保存密码 + void setVerifyPassword(QString password); + // 网络验证 -> 自动登录状态 + bool autoLogin(); + // 网络验证 -> 保存自动登录状态 + void setAutoLogin(bool autoLogin); +public: + // 主界面 -> 皇冠时间状态 + bool crownTime(); + // 主界面 -> 设置皇冠时间状态 + void setCrownTime(bool crownTime); + QDateTime formatDateTime(QDateTime dateTime); +public: + QList> usersList(); + void setUsersList(QList>); +public: + // 主界面 -> 过滤时间状态 + bool screenDateTimeEnable(); + // 主界面 -> 保存过滤时间状态 + void setScreenDateTimeEnable(bool enable); + // 主界面 -> 过滤时间 + QString screenDateTime(); + // 主界面 -> 保存过滤时间 + void setScreenDateTime(QString dateTime); + + // 主界面 -> 网址列表 + QList client_url_list(); + // 主界面 -> 设置网址列表 + void set_client_url_list(QList list); + // 主界面 -> 默认网址 + QString client_url(); + // 主界面 -> 设置默认网址 + void set_client_url(QString url); + + + // 主界面 -> 帐号 + QString username(); + // 主界面 -> 设置帐号 + void setUsername(QString username); + // 主界面 -> 密码 + QString password(); + // 主界面 -> 设置密码 + void setPassword(QString password); + +public: + // 连接设置 -> 服务器列表 + QList> servers(); + // 连接设置 -> 保存服务器列表 + void setServers(QList> servers); + // 连接设置 -> 客户端标志 + QString clientSign(); + // 连接设置 -> 保存客户端标志 + void setClientSign(QString sign); + // 连接设置 -> 一次读取数量 + int readCount(); + // 连接设置 -> 保存一次读取数量 + void setReadCount(int count); + // 连接设置 -> 读取延迟 + int readSleep(); + // 连接设置 -> 保存一次读取延迟 + void setReadSleep(int sleep); + // 连接设置 -> 自动连接状态 + bool autoConnect(); + // 连接设置 -> 保存自动连接状态 + void setAutoConnect(bool enable); + + +public: + // 跟单项目 -> 跟单项目列表 + QList> betProject(); + // 跟单项目 -> 设置跟单项目列表 + void setBetProject(QList> list); + // 跟单项目 -> 跟单几天内注单 + int betDays(); + // 跟单项目 -> 设置跟单几天内注单 + void setBetDays(int days); + // 跟单项目 -> 是否跟单普通注单 + bool betNormalOrder(); + // 跟单项目 -> 设置是否跟单普通注单 + void setBetNormalOrder(bool enable); + // 跟单项目 -> 是否跟单手机注单 + bool betPhoneOrder(); + // 跟单项目 -> 设置是否跟单手机注单 + void setBetPhoneOrder(bool enable); +public: + // 注单盘口 -> 注单盘口列表 + QList> handicap(); + // 注单盘口 -> 设置注单盘口列表 + void setHandicap(QList> list); + // 注单盘口 -> 注单项目勾选 + bool handicapProject(); + // 注单盘口 -> 设置注单项目勾选 + void setHandicapProject(bool enable); + // 注单盘口 -> 注单项目索引 + int handicapProjectIndex(); + // 注单盘口 -> 设置注单项目索引 + void setHandicapProjectIndex(int index); + // 注单盘口 -> 注单类型勾选 + bool handicapType(); + // 注单盘口 -> 设置注单类型勾选 + void setHandicapType(bool enable); + // 注单盘口 -> 注单类型索引 + int handicapTypeIndex(); + // 注单盘口 -> 设置注单类型索引 + void setHandicapTypeIndex(int index); + // 注单盘口 -> 盘口处理方式 + QString handicapMethod(); + // 注单盘口 -> 设置盘口处理方式 + void setHandicapMethod(QString method); +public: + // 注单赔率 -> 赔率列表 + QList> odds(); + // 注单赔率 -> 设置赔率列表 + void setOdds(QList> list); + // 注单赔率 -> 注单项目勾选 + bool oddsProject(); + // 注单赔率 -> 设置注单项目勾选 + void setOddsProject(bool enable); + // 注单赔率 -> 注单项目索引 + int oddsProjectIndex(); + // 注单赔率 -> 设置注单项目索引 + void setOddsProjectIndex(int index); + // 注单赔率 -> 注单类型勾选 + bool oddsType(); + // 注单赔率 -> 设置注单类型勾选 + void setOddsType(bool enable); + // 注单赔率 -> 注单类型索引 + int oddsTypeIndex(); + // 注单赔率 -> 设置注单类型索引 + void setOddsTypeIndex(int index); + // 注单赔率 -> 大于多少不跟 + int oddsHigh(); + // 注单赔率 -> 设置大于多少不跟 + void setOddsHigh(int value); + // 注单赔率 -> 小于多少不跟 + int oddsLow(); + // 注单赔率 -> 设置小于多少不跟 + void setOddsLow(int value); + // 注单赔率 -> 上涨多少不跟 + int oddsUp(); + // 注单赔率 -> 设置上涨多少不跟 + void setOddsUp(int value); + // 注单赔率 -> 下降多少不跟 + int oddsDown(); + // 注单赔率 -> 设置下降多少不跟 + void setOddsDown(int value); + + // 模拟测试 -> 没做 +public: + // 注单金额 -> 注单原始金额小于多少放弃注单勾选 + bool originalAmountLowerGiveUpEnable(); + // 注单金额 -> 设置注单原始金额小于多少放弃注单勾选 + void setOriginalAmountLowerGiveUpEnable(bool enable); + // 注单金额 -> 注单原始金额小于多少放弃注单 + int originalAmountLower(); + // 注单金额 -> 设置注单原始金额小于多少放弃注单 + void setOriginalAmountLower(int value); + // 注单金额 -> 注单原始金额大于多少放弃注单勾选 + bool originalAmountHigherGiveUpEnable(); + // 注单金额 -> 设置注单原始金额大于多少放弃勾选 + void setOriginalAmountHigherGiveUpEnable(bool enable); + // 注单金额 -> 注单原始金额大于多少放弃注单 + int originalAmountHigher(); + // 注单金额 -> 设置注单原始金额大于多少放弃注单 + void setOriginalAmountHigher(int value); + // 注单金额 -> 注单跟单金额小于多少执行处理勾选 + bool amountLowerEnable(); + // 注单金额 -> 设置注单跟单金额小于多少执行处理勾选 + void setAmountLowerEnable(bool enable); + // 注单金额 -> 注单跟单金额小于多少执行处理 + int amountLower(); + // 注单金额 -> 设置注单跟单金额小于多少执行处理 + void setAmountLower(int value); + // 注单金额 -> 注单金额小于多少增加到多少金额勾选 + bool amountLowerAddToEnable(); + // 注单金额 -> 设置注单金额小于多少增加到多少金额勾选 + void setAmountLowerAddToEnable(bool enable); + // 注单金额 -> 注单金额小于多少增加到多少金额 + int amountLowerAddTo(); + // 注单金额 -> 设置注单金额小于多少增加到多少金额 + void setAmountLowerAddTo(int value); + // 注单金额 -> 注单金额小于多少放弃注单勾选 + bool amountLowerGiveUpEnable (); + // 注单金额 -> 设置注单金额小于多少放弃注单勾选 + void setAmountLowerGiveUpEnable(bool enable); + + // 注单金额 -> 注单原始金额大于多少拆分勾选 + bool amountHigherEnable(); + // 注单金额 -> 设置注单原始金额大于多少拆分勾选 + void setAmountHigherEnable(bool enable); + // 注单金额 -> 注单原始金额大于多少拆分 + int amountHigher(); + // 注单金额 -> 设置注单原始金额大于多少拆分 + void setAmountHigher(int value); + // 注单金额 -> 注单原始金额大于多少拆分勾选 + bool amountHigherSubToEnable(); + // 注单金额 -> 设置注单原始金额大于多少拆分勾选 + void setAmountHigherSubToEnable(bool enable); + // 注单金额 -> 注单原始金额大于多少放弃勾选 + bool amountHigherGiveUpEnable(); + // 注单金额 -> 设置注单原始金额大于多少放弃勾选 + void setAmountHigherGiveUpEnable(bool enable); + // 注单金额 -> 注单原始金额大于多少拆分到多少 + int amountHigherSubTo(); + // 注单金额 -> 设置注单原始金额大于多少拆分到多少 + void setAmountHigherSubTo(int value); + + // 注单金额 -> 进位 + QString carry(QString value); + // 注单金额 -> 进位演示金额 + int carry(); + // 注单金额 -> 设置进位演示金额 + void setCarry(int value); + // 注单金额 -> 进位方式索引 + int carryIndex(); + // 注单金额 -> 设置进位方式索引 + void setCarryIndex(int index); + // 注单金额 -> 四舍五入勾选 + bool carryHalfAdjustEnable(); + // 注单金额 -> 设置四舍五入勾选 + void setCarryHalfAdjustEnable(bool enable); + // 注单金额 -> 舍去余数勾选 + bool carryRoundingEnable(); + // 注单金额 -> 设置舍去余数勾选 + void setCarryRoundingEnable(bool enable); + // 注单金额 -> 单注最低限额 + int amountMin(); + // 注单金额 -> 设置单注最低限额 + void setAmountMin(int value); + // 注单金额 -> 单注最大金额 + int amountMax(); + // 注单金额 -> 设置单注最大金额 + void setAmountMax(int value); + + + // 金额小于平台最小值 + int amount_less_than_platform(); + void set_amount_less_than_platform(int type); + + // 金额大于平台最大值 + int amount_more_than_platform(); + void set_amount_more_than_platform(int type); +public: + // 补单筛选 -> 启用筛选勾选 + bool rebetScreenEnable(); + // 补单筛选 -> 设置启用筛选勾选 + void setRebetScreenEnable(bool enable); + // 补单筛选 -> 补单原因列表 + QList> rebetScreen(); + // 补单筛选 -> 设置补单原因列表 + void setRebetScreen(QList> list); + +public: + // 接收游戏列表 + QList acceptGameList(); + // 过滤游戏列表 + QList screenGameList(); + // 设置接收游戏列表 + void setAcceptGameList(QList list); + // 设置过滤游戏列表 + void setScreenGameList(QList list); +public: + int getDelay(const QString& gameType, const QString& resultType, bool getMin); + int getRandomDelay(const QString& gameType, const QString& resultType); + + // 跟单延迟 -> 列表 + QList> sleep(); + // 跟单延迟 -> 设置列表 + void setSleep(QList> list); + // 跟单延迟 -> 跟单之前最小延迟 + int betBeforeSleepMin(); + // 跟单延迟 -> 设置跟单之前最小延迟 + void setBetBeforeSleepMin(int value); + // 跟单延迟 -> 跟单之前最大延迟 + int betBeforeSleepMax(); + // 跟单延迟 -> 设置跟单之前最大延迟 + void setBetBeforeSleepMax(int value); + // 跟单延迟 -> 跟单之前延迟 + int betBeforeSleep(); + // 跟单延迟 -> 跟单成功最小延迟 + int betSuccessSleepMin(); + // 跟单延迟 -> 设置跟单成功最小延迟 + void setBetSuccessSleepMin(int value); + // 跟单延迟 -> 跟单成功最大延迟 + int betSuccessSleepMax(); + // 跟单延迟 -> 设置跟单成功最大延迟 + void setBetSuccessSleepMax(int value); + // 跟单延迟 -> 跟单成功延迟 + int betSuccessSleep(); + + // 跟单延迟 -> 跟单失败最小延迟 + int betFailedSleepMin(); + // 跟单延迟 -> 设置跟单失败最小延迟 + void setBetFailedSleepMin(int value); + // 跟单延迟 -> 跟单失败最大延迟 + int betFailedSleepMax(); + // 跟单延迟 -> 设置跟单失败最大延迟 + void setBetFailedSleepMax(int value); + // 跟单延迟 -> 跟单失败延迟 + int betFailedSleep(); + + // 跟单延迟 -> 跟单之前开始计算方式索引 + int betBeforeCalcIndex(); + // 跟单延迟 -> 设置跟单之前开始计算方式索引 + void setBetBeforeCalcIndex(int index); + // 跟单延迟 -> 注单项目勾选 + bool sleepProjectEnable(); + // 跟单延迟 -> 设置注单项目勾选 + void setSleepProjectEnable(bool enable); + // 跟单延迟 -> 注单项目索引 + int sleepProjectIndex(); + // 跟单延迟 -> 设置注单项目索引 + void setSleepProjectIndex(int index); + +public: + // 声音设置 -> 接收注单勾选 + bool acceptOrderSoundEnable(); + // 声音设置 -> 接收注单路径 + QString acceptOrderSoundPath(); + // 声音设置 -> 设置接收注单勾选 + void setAcceptOrderSoundEnable(bool value); + // 声音设置 -> 设置接收注单路径 + void setAcceptOrderSoundPath(QString path); + // 声音设置 -> 过滤注单勾选 + bool screenOrderSoundEnable(); + // 声音设置 -> 过滤注单路径 + QString screenOrderSoundPath(); + // 声音设置 -> 设置过滤注单勾选 + void setScreenOrderSoundEnable(bool value); + // 声音设置 -> 设置过滤注单路径 + void setScreenOrderSoundPath(QString path); + // 声音设置-> 跟单成功勾选 + bool followOrderSuccessSoundEnable(); + // 声音设置 -> 跟单成功路径 + QString followOrderSuccessSoundPath(); + // 声音设置 -> 设置跟单成功勾选 + void setFollowOrderSuccessSoundEnable(bool value); + // 声音设置 -> 设置跟单成功路径 + void setFollowOrderSuccessSoundPath(QString path); + // 声音设置 -> 跟单失败勾选 + bool followOrderFailedSoundEnable(); + // 声音设置 -> 跟单失败路径 + QString followOrderFailedSoundPath(); + // 声音设置 -> 设置跟单失败勾选 + void setFollowOrderFailedSoundEnable(bool value); + // 声音设置 -> 设置跟单失败路径 + void setFollowOrderFailedSoundPath(QString path); + // 声音设置 -> 断开连接勾选 + bool disconnectSoundEnable(); + // 声音设置 -> 断开连接路径 + QString disconnectSoundPath(); + // 声音设置 -> 设置断开连接勾选 + void setDisconnectSoundEnable(bool value); + // 声音设置 -> 设置断开连接路径 + void setDisconnectSoundPath(QString path); + // 声音设置 -> 推送失败勾选 + bool pushFailedSoundEnable(); + // 声音设置 -> 推送失败路径 + QString pushFailedSoundPath(); + // 声音设置 -> 设置推送失败勾选 + void setPushFailedSoundEnable(bool value); + // 声音设置 -> 设置推送失败路径 + void setPushFailedSoundPath(QString path); + // 声音设置 -> 强制退出勾选 + bool exitSoundEnable(); + // 声音设置 -> 强制退出路径 + QString exitSoundPath(); + // 声音设置 -> 设置强制退出勾选 + void setExitSoundEnable(bool value); + // 声音设置 -> 设置强制退出路径 + void setExitSoundPath(QString path); + // 声音设置 -> 重新登录勾选 + bool reloginSoundEnable(); + // 声音设置 -> 重新登录路径 + QString reloginSoundPath(); + // 声音设置 -> 设置重新登录勾选 + void setReloginSoundEnable(bool value); + // 声音设置 -> 设置重新登录路径 + void setReloginSoundPath(QString path); + // 声音设置 -> 软件更新勾选 + bool softUpdateSoundEnable(); + // 声音设置 -> 软件更新路径 + QString softUpdateSoundPath(); + // 声音设置 -> 设置软件更新勾选 + void setSoftUpdateSoundEnable(bool value); + // 声音设置 -> 设置软件更新路径 + void setSoftUpdateSoundPath(QString path); + + +public: + // 赛事盘口 -> 阶段(session)计算方式索引 + int session_calc_type(); + // 赛事盘口 -> 设置结算(session)计算方式索引 + void set_session_calc_type(int type); + // 赛事盘口 -> 计算赛事盘口相反值 + QString calculateOppositeHandicap(const QString &handicap); + // 赛事盘口 -> 计算赛事盘口相反值简单版 + QString calculateSimpleOpposite(const QString &handicap); + // 赛事盘口 -> 同赛事对头单不跟勾选 + bool gameOppositeEnable(); + // 赛事盘口 -> 设置同赛事对头单不跟勾选 + void setGameOppositeEnable(bool enable); + // 赛事盘口 -> 同赛事盘口对头单不跟 + bool handicapOppositeEnable(); + // 赛事盘口 -> 设置同赛事盘口对头单不跟 + void setHandicapOppositeEnable(bool enable); + // 赛事盘口 -> 场次项目计算方式索引 + int ptype_calc_type(); + // 赛事盘口 -> 设置场次项目计算方式索引 + void set_ptype_calc_type(int type); + // 赛事盘口 -> 注单类型计算方式索引 + int gameCalcType(); + // 赛事盘口 -> 设置注单类型计算方式索引 + void setGameCalcType(int type); + // 赛事盘口 -> 同赛事最多跟单次数勾选 + bool gameFollowTimesMaxEnable(); + // 赛事盘口 -> 设置同赛事最多跟单次数勾选 + void setGameFollowTimesMaxEnable(bool enable); + // 赛事盘口 -> 同赛事最多跟单次数 + int gameFollowTimesMax(); + // 赛事盘口 -> 设置同赛事最多跟单次数 + void setGameFollowTimesMax(int times); + // 赛事盘口 -> 同赛事最多跟单金额勾选 + bool gameFollowAmountMaxEnable(); + // 赛事盘口 -> 设置同赛事最多跟单金额勾选 + void setGameFollowAmountMaxEnable(bool enable); + // 赛事盘口 -> 同赛事最多跟单金额 + float gameFollowAmountMax(); + // 赛事盘口 -> 设置同赛事最多跟单金额 + void setGameFollowAmountMax(float amount); + // 赛事盘口 -> 同赛事盘口最多跟单次数勾选 + bool handicapFollowTimesMaxEnable(); + // 赛事盘口 -> 设置同赛事盘口最多跟单次数勾选 + void setHandicapFollowTimesMaxEnable(bool enable); + // 赛事盘口 -> 同赛事盘口最多跟单次数 + int handicapFollowTimesMax(); + // 赛事盘口 -> 设置同赛事盘口最多跟单次数 + void setHandicapFollowTimesMax(int times); + // 赛事盘口 -> 同赛事盘口最多跟单金额勾选 + bool handicapFollowAmountMaxEnable(); + // 赛事盘口 -> 设置同赛事盘口最多跟单金额勾选 + void setHandicapFollowAmountMaxEnable(bool enable); + // 赛事盘口 - > 同赛事盘口最多跟单金额 + float handicapFollowAmountMax(); + // 赛事盘口 -> 设置同赛事盘口最多跟单金额 + void setHandicapFollowAmountMax(float amount); + + bool checkOppositeBet(const QMap &order); + bool checkOppositeHandicap(const QMap &order); + + + // 赛事盘口 -> 检查同赛事最大跟单次数 + bool check_game_follow_max_times(const QMap &order); + // 赛事盘口 -> 检查同赛事最多跟单金额 + bool check_game_follow_max_amount(const QMap &order); + // 赛事盘口 -> 检查同赛事盘口最大跟单次数 + bool check_handicap_follow_max_times(const QMap &order); + // 赛事盘口 -> 检查同赛事盘口最大跟单金额 + bool check_handicap_follow_max_amount(const QMap &order); +public: + // 跟单设置 -> 帐号跟单方式列表 + QList> setting(); + // 跟单设置 -> 设置帐号跟单方式列表 + void setSetting(QList> list); + // 跟单设置 -> 跟单类型 + QList followType(); + // 跟单设置 -> 设置跟单类型 + void setFollowType(QList list); + // 跟单设置 -> 跟单会员缺少所需盘口类型执行方式索引 + int lackType(); + // 跟单设置 -> 设置跟单会员缺少所需盘口类型执行方式索引 + void setLackType(int type); + // 跟单设置 -> 跟单设备类型索引 + int followDeviceType(); + // 跟单设置 -> 设置跟单设备类型索引 + void setFollowDeviceType(int type); + // 跟单设置 -> 最多补单次数 + int rebetMaxTimes(); + // 跟单设置 -> 设置最多补单次数 + void setReBetMaxTimes(int times); + // 跟单设置 -> 补单达到多少次延迟 + int rebetSleepTimes(); + // 跟单设置 -> 设置补单达到多少次延迟 + void setRebetSleepTimes(int times); + // 跟单设置 -> 达到补单次数延迟时间 + int rebetSleep(); + // 跟单设置 -> 设置达到补单次数延迟时间 + void setRebetSleep(int sec); + // 跟单设置 -> 自动改变盘口勾选 + bool sessionAutoChangeEnable(); + // 跟单设置 -> 设置自动改变盘口勾选 + void setSessionAutoChangeEnable(bool enable); + // 跟单设置 -> 比分变化不跟勾选 + bool ignoreScoreChangedEnable(); + // 跟单设置 -> 设置比分变化不跟勾选 + void setIgnoreScoreChangedEnable(bool enable); + // 跟单设置 -> 只跟固定比分勾选 + bool followFixedScoreEnable(); + // 跟单设置 -> 设置只跟固定比分勾选 + void setFollowFixedScoreEnable(bool enable); + // 跟单设置 -> 只跟固定比分主队比分 + int fixedScoreMaster(); + // 跟单设置 -> 设置只跟固定比分主队比分 + void setFixedScoreMaster(int master); + // 跟单设置 -> 只跟固定比分客队比分 + int fixedScoreVisitor(); + // 跟单设置 -> 设置只跟固定比分客队比分 + void setFixedScoreVisitor(int visitor); +public: + // 通知状态 + bool notice_status(); + // 设置通知状态 + void set_notice_status(bool status); + // 通知账户 + QString notice_account(); + // 设置通知账户 + void set_notice_account(QString account); +private: + // 订单数据库 + QSqlDatabase m_db; +public: + // 接收注单入库 + void add_accept_order(QMap order); + // 读取接收注单数据库 + QList> get_accept_orders(); + + // 加入筛选注单数据库 + void add_screen_order(QMap order); + // 读取筛选注单数据库 + QList> get_screen_orders(); + + // 成功注单入库 + void add_success_order(QMap order); + // 读取成功注单数据库列表 + QList> get_success_orders(); + + // 失败注单入库 + void add_failed_orders(QMap order); + // 更新补单次数 + void alert_failed_order(QMap order); + // 读取失败注单数据库列表 + QList> get_failed_orders(); + // 删除失败注单 + // bool remove_failed_orders(QList tidList); + + // 补单记录入库 + void add_rebet_order(QMap order); + // 读取补单记录数据库列表 + QList> get_rebet_orders(); + + + + + // 订单存在性检查 + bool is_order_in_screen(const QString& tid); + bool is_order_in_success(const QString& tid); + bool is_order_in_failed(const QString& tid); + bool is_order_in_rebet(const QString& tid); + + // 各表专用删除函数 + bool clear_table(const QString& tableName); + bool remove_order(const QString& tableName, const QString& tid); + bool remove_orders(const QString& tableName, const QList& tidList); + + bool remove_accept_order(const QString& tid); + bool remove_accept_orders(const QList& tidList); + + bool remove_screen_order(const QString& tid); + bool remove_screen_orders(const QList& tidList); + + bool remove_success_order(const QString& tid); + bool remove_success_orders(const QList& tidList); + + bool remove_failed_order(const QString& tid); + bool remove_failed_orders(const QList& tidList); + + bool remove_rebet_order(const QString& tid); + bool remove_rebet_orders(const QList& tidList); + + // 清空表函数 + bool clear_accept_orders(); + bool clear_screen_orders(); + bool clear_success_orders(); + bool clear_failed_orders(); + bool clear_rebet_orders(); + + + // 检查补单原因次数 + int get_rebet_reason_times(const QString& tid, const QString& reason); + + +}; \ No newline at end of file diff --git a/CrownClient/Connect.cpp b/CrownClient/Connect.cpp new file mode 100644 index 0000000..06d71dd --- /dev/null +++ b/CrownClient/Connect.cpp @@ -0,0 +1,765 @@ +#include "Connect.h" +#include "CheckBoxHeaderView.h" +#include +#include "Global.h" +#include + +Connect::Connect(QWidget *parent) + : QWidget(parent) +{ + ui.setupUi(this); + // 设置窗口图标 + this->setWindowIcon(QIcon(":/images/Images/client.ico")); + // 设置窗口标题 + this->setWindowTitle("连接服务"); + // 设置为对话框窗口 + setWindowFlags(Qt::Dialog); + // 设置窗口仅有关闭按钮 + setWindowFlags(Qt::WindowCloseButtonHint); + // 设置固定大小 + setFixedSize(925, 413); + + // 初始化表格 + ui.tableWidget->setColumnCount(7); + ui.tableWidget->setHorizontalHeaderLabels({ "启用","地址","端口","密码","状态","读取次数","读取数据" }); + ui.tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + ui.tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); + ui.tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch); + ui.tableWidget->horizontalHeader()->resizeSection(0, 50); + + // 默认插入5条服务端数据 + for (int row = 0; row < 5; row++) + { + // 插入一行 + ui.tableWidget->insertRow(row); + + // 选择框 + QWidget* widget = new QWidget(); + QHBoxLayout* layout = new QHBoxLayout(); + QCheckBox* box = new QCheckBox(); + layout->addWidget(box); + layout->setContentsMargins(0, 0, 0, 0); + layout->setAlignment(box, Qt::AlignCenter); + widget->setLayout(layout); + ui.tableWidget->setCellWidget(row, 0, widget); + + // IP + ui.tableWidget->setItem(row, 1, new QTableWidgetItem("127.0.0.1")); + ui.tableWidget->item(row, 1)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + + // 端口 + ui.tableWidget->setItem(row, 2, new QTableWidgetItem(QString::number(8080 + row))); + ui.tableWidget->item(row, 2)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + + // 连接密码 + ui.tableWidget->setItem(row, 3, new QTableWidgetItem("88888")); + ui.tableWidget->item(row, 3)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + + // 状态 + ui.tableWidget->setItem(row, 4, new QTableWidgetItem("断开")); + // 禁止编辑 + ui.tableWidget->item(row, 4)->setFlags(ui.tableWidget->item(row, 4)->flags() & (~Qt::ItemIsEditable)); + ui.tableWidget->item(row, 4)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + ui.tableWidget->item(row, 4)->setForeground(QBrush(QColor(255, 00, 00))); + + // 读取次数 + ui.tableWidget->setItem(row, 5, new QTableWidgetItem("0")); + // 禁止编辑 + ui.tableWidget->item(row, 5)->setFlags(ui.tableWidget->item(row, 5)->flags() & (~Qt::ItemIsEditable)); + ui.tableWidget->item(row, 5)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + + // 数据数量 + ui.tableWidget->setItem(row, 6, new QTableWidgetItem("0")); + // 禁止编辑 + ui.tableWidget->item(row, 6)->setFlags(ui.tableWidget->item(row, 5)->flags() & (~Qt::ItemIsEditable)); + ui.tableWidget->item(row, 6)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + } + + // 服务端信息 + QList> servers = g_config->servers(); + for (int row = 0; row < servers.count(); row++) + { + QCheckBox* checkBox = reinterpret_cast(ui.tableWidget->cellWidget(row, 0)->layout()->itemAt(0)->widget()); + if (servers[row]["enable"] == "true") + { + checkBox->setChecked(true); + } + ui.tableWidget->item(row, 1)->setText(servers[row]["ip"]); + ui.tableWidget->item(row, 2)->setText(servers[row]["port"]); + ui.tableWidget->item(row, 3)->setText(servers[row]["connectPassword"]); + ui.tableWidget->item(row, 5)->setText(servers[row]["readTimes"]); + ui.tableWidget->item(row, 6)->setText(servers[row]["dataCount"]); + + TcpSocket* client = new TcpSocket(); + if (!client) + { + qWarning() << "TCP 客户端创建失败"; + } + connect(client, &TcpSocket::signalDataRecv, this, &Connect::slotDateRecv, Qt::QueuedConnection); + // 连接事件 + connect(client, &TcpSocket::connected, this, &Connect::slotOnConnected, Qt::QueuedConnection); + // 断开事件 + connect(client, &TcpSocket::disconnected, this, &Connect::slotOnDisconnected, Qt::QueuedConnection); + // 连接加入列表 + m_clients.append(client); + + } + + // 客户标识 + ui.clientSignEdit->setText(g_config->clientSign()); + // 读取数量 + ui.readNumberEdit->setText(QString::number(g_config->readCount())); + // 读取延时 + ui.readSleepEdit->setText(QString::number(g_config->readSleep())); + // 自动连接 + ui.autoConnectCheckBox->setChecked(g_config->autoConnect()); + + // 按钮点击事件 + connect(ui.connectButton, &QPushButton::clicked, this, &Connect::slotConnect); + connect(ui.disconnectButton, &QPushButton::clicked, this, &Connect::slotDisconnect); + + // 自动连接 + if (g_config->autoConnect()) + { + // 禁用连接按钮 + ui.connectButton->setDisabled(true); + // 启用断开按钮 + ui.disconnectButton->setEnabled(true); + + + emit ui.connectButton->clicked(); + //slotConnect(); + + //// 连接服务端 + //QHostAddress ip = QHostAddress(ui.tableWidget->item(row, 1)->text()); + //qintptr port = ui.tableWidget->item(row, 2)->text().toInt(); + //client->connectToHost(ip, port); + + } + + // 读取订单定时器 + m_timer = new QTimer(this); + connect(m_timer, &QTimer::timeout, this, &Connect::slotUpdateOrders, Qt::QueuedConnection); + + +} + +Connect::~Connect() +{ + //qDebug() << "Connect 析构开始"; + + // 停止定时器 + if (m_timer) { + m_timer->stop(); + delete m_timer; + m_timer = nullptr; + } + if (m_tcpCheckTimer) { + m_tcpCheckTimer->stop(); + delete m_tcpCheckTimer; + m_tcpCheckTimer = nullptr; + } + + // 释放 m_clients 中的 TcpSocket 对象 + for (auto client : m_clients) { + if (client) { + client->disconnect(); + client->abort(); + client->deleteLater(); + } + } + m_clients.clear(); + + //qDebug() << "Connect 析构完成"; +} + +/// +/// TCP连接连接 +/// +void Connect::slotOnConnected() +{ + //qDebug() << "TCP 连接"; + for (int i = 0; i < m_clients.count(); i++) + { + if (m_clients[i] && m_clients[i]->state() == QAbstractSocket::ConnectedState) + { + ui.tableWidget->item(i, 4)->setText("连接"); + ui.tableWidget->item(i, 4)->setForeground(QBrush(QColor(0, 255, 0))); + ui.tableWidget->item(i, 4)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + + // 发送读取用户列表封包 + QString sendData = "ReadUsers|"+ui.tableWidget->item(i, 3)->text() +"|InitUsers"; + //qDebug() << "发送读取用户封包:" << sendData; + emit m_clients[i]->signalSendData(sendData.toUtf8()); + + } + } + this->updateState(); // Update overall state +} + +/// +/// TCP连接断开 +/// +void Connect::slotOnDisconnected() +{ + //qDebug() << "TCP 断开连接"; + // 查找断开连接的客户端并更新状态 + for (int i = 0; i < m_clients.count(); i++) { + //qDebug() << m_clients[i]->state(); + if (m_clients[i] && m_clients[i]->state() == QAbstractSocket::UnconnectedState) { + ui.tableWidget->item(i, 4)->setText("断开"); + ui.tableWidget->item(i, 4)->setForeground(QBrush(QColor(255, 0, 0))); + ui.tableWidget->item(i, 4)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + } + } + + // 播放连接断开声音 + if (g_config->disconnectSoundEnable()) + { + if (!g_config->disconnectSoundPath().isEmpty()) + { + QSound::play(g_config->disconnectSoundPath()); + } + else + { + QSound::play(":/sound/sound/disconnect.wav"); + } + } + + // 更新整体状态 + this->updateState(); +} + +/// +/// 槽函数 -> 重连 +/// +void Connect::handleError(QAbstractSocket::SocketError socketError) +{ + //qDebug() << "Connect 重连开始 : " << socketError; + for (int i = 0; i < ui.tableWidget->rowCount(); i++) + { + + // 检查是否启用 + QCheckBox* checkBox = reinterpret_cast(ui.tableWidget->cellWidget(i, 0)->layout()->itemAt(0)->widget()); + if (!checkBox->isChecked()) { + continue; // 跳过未启用的行 + } + + //qDebug() << "重连服务端[]:" << i << m_clients[i]->error(); + if (m_clients[i] && m_clients[i]->state() == QAbstractSocket::UnconnectedState) + { + //qDebug() << "重连服务端:" << i; + //ui.tableWidget->item(i, 4)->setText("断开"); // Set to "断开" initially + //ui.tableWidget->item(i, 4)->setForeground(QBrush(QColor(255, 00, 00))); + //ui.tableWidget->item(i, 4)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + + // 重新连接 + QHostAddress ip = QHostAddress(ui.tableWidget->item(i, 1)->text()); + qintptr port = ui.tableWidget->item(i, 2)->text().toInt(); + //qDebug() << "自动重连到:" << ip.toString() << ":" << port; + m_clients[i]->connectToHost(ip, port); + } + } + + //// 通过连接按钮状态判断是否是异常断开 + //if (!ui.connectButton->isEnabled()) + //{ + + //} +} + +/// +/// 协议类型解析 +/// +PROTOCOL Connect::ProtocolType(QString data) +{ + QStringList list = data.split("|"); + if (list.count() == 0) + { + return Error; + } + QString protocol = list[0]; + if (protocol == "Login") + { + return Login; + } + else if (protocol == "LoginSuccess") + { + return LoginSuccess; + } + else if (protocol == "LoginFailed") + { + return LoginFailed; + } + else if (protocol == "ReadOrders") + { + return ReadOrders; + } + else if (protocol == "ReadUsers") + { + return ReadUsers; + } + else if (protocol == "FollowBet") + { + return FollowBet; + } + else if (protocol == "Logout") + { + return Logout; + } + return Error; +} + +/// +/// 更新状态 +/// +void Connect::updateState() +{ + //qDebug() << "更新连接状态"; + + // 有连接成功则为连接成功状态 + for (int i = 0; i < ui.tableWidget->rowCount(); i++) + { + // **检查是否启用** + QCheckBox* checkBox = reinterpret_cast(ui.tableWidget->cellWidget(i, 0)->layout()->itemAt(0)->widget()); + if (!checkBox->isChecked()) { + continue; // 跳过未启用的行 + } + + if (ui.tableWidget->item(i, 4)->text() == "连接") + { + //qDebug() << "发现已连接状态,发出连接成功信号"; + emit signalStateChange(2); + return; + } + } + + // 没有连接成功检查是否有等待连接 + for (int i = 0; i < ui.tableWidget->rowCount(); i++) + { + // **检查是否启用** + QCheckBox* checkBox = reinterpret_cast(ui.tableWidget->cellWidget(i, 0)->layout()->itemAt(0)->widget()); + if (!checkBox->isChecked()) { + continue; // 跳过未启用的行 + } + + if (ui.tableWidget->item(i, 4)->text() == "等待") + { + //qDebug() << "发现等待状态,发出等待连接信号"; + emit signalStateChange(1); + return; + } + } + + // 没有连接成功和等待连接更新为连接断开状态 + //qDebug() << "所有连接都断开,发出断开信号"; + emit signalStateChange(0); +} + +/// +/// 同步连接状态 +/// +void Connect::syncConnectionState() +{ + //qDebug() << "同步连接状态"; + for (int i = 0; i < m_clients.count(); i++) + { + + // **检查是否启用** + QCheckBox* checkBox = reinterpret_cast(ui.tableWidget->cellWidget(i, 0)->layout()->itemAt(0)->widget()); + if (!checkBox->isChecked()) { + continue; // 跳过未启用的行 + } + + if (m_clients[i]) + { + QAbstractSocket::SocketState socketState = m_clients[i]->state(); + QString currentText = ui.tableWidget->item(i, 4)->text(); + //qDebug() << "行:" << i << ",当前状态:" << currentText << ",TCP状态:" << socketState; + + // 根据TCP状态同步UI状态 + if (socketState == QAbstractSocket::UnconnectedState) { + if (currentText != "断开") { + //qDebug() << "TCP已断开,同步状态为断开"; + ui.tableWidget->item(i, 4)->setText("断开"); + ui.tableWidget->item(i, 4)->setForeground(QBrush(QColor(255, 0, 0))); + ui.tableWidget->item(i, 4)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + } + } + else if (socketState == QAbstractSocket::ConnectedState) { + if (currentText == "断开") { + //qDebug() << "TCP已连接,同步状态为等待"; + ui.tableWidget->item(i, 4)->setText("等待"); + ui.tableWidget->item(i, 4)->setForeground(QBrush(QColor(248, 213, 104))); + ui.tableWidget->item(i, 4)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + } + // 如果启用了自动连接且状态是"等待",自动发送Login包 + if (ui.autoConnectCheckBox->isChecked() && currentText == "等待") { + //qDebug() << "自动连接启用,状态为等待,发送Login包"; + QString sendData = "Login|" + ui.tableWidget->item(i, 3)->text(); + emit m_clients[i]->signalSendData(sendData.toUtf8()); + } + } + else if (socketState == QAbstractSocket::ConnectingState) { + if (currentText != "连接中") { + //qDebug() << "TCP连接中,同步状态为连接中"; + ui.tableWidget->item(i, 4)->setText("连接中"); + ui.tableWidget->item(i, 4)->setForeground(QBrush(QColor(0, 0, 255))); + ui.tableWidget->item(i, 4)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + } + } + } + } + + // 更新整体状态 + this->updateState(); +} + +// 数据到达 +void Connect::slotDateRecv(qintptr socketDecriptor, QByteArray data) +{ + QString dataStr = QString::fromUtf8(data); + //qDebug() << "[通信] 收到数据: " << dataStr; + + // 解析协议类型 + PROTOCOL type = ProtocolType(dataStr); + if (type == LoginSuccess) + { + //qDebug() << "[连接流程]服务端返回登录成功"; + for (int row = 0; row < m_clients.count(); row++) + { + if (m_clients[row] && m_clients[row]->socketDescriptor() == socketDecriptor) + { + //qDebug() << "Login成功,行:" << row << ",状态设为连接"; + ui.tableWidget->item(row, 4)->setText("连接"); + ui.tableWidget->item(row, 4)->setForeground(QBrush(QColor(00, 255, 00))); + ui.tableWidget->item(row, 4)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + + // 发送读取用户列表封包 + QString sendData = "ReadUsers|InitUsers"; + //qDebug() << "发送读取用户封包:" << sendData; + emit m_clients[row]->signalSendData(sendData.toUtf8()); + break; // 找到对应的客户端后退出循环 + } + } + // 发出已连接状态信号 + emit signalStateChange(2); + } + else if (type == LoginFailed) + { + //qDebug() << "[连接流程]服务端返回登录失败"; + // 找到对应的客户端,状态设为断开 + for (int row = 0; row < m_clients.count(); row++) + { + if (m_clients[row] && m_clients[row]->socketDescriptor() == socketDecriptor) + { + //qDebug() << "Login失败,行:" << row << ",状态设为断开"; + ui.tableWidget->item(row, 4)->setText("断开"); + ui.tableWidget->item(row, 4)->setForeground(QBrush(QColor(255, 0, 0))); + ui.tableWidget->item(row, 4)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + break; + } + } + // 更新整体状态 + this->updateState(); + } + else if (type == ReadOrders) + { + //qDebug() << "接收注单!!!"; + QStringList list = dataStr.split("|"); + //qDebug() << "客户端连接 -> 数据分割:" << list.count(); + + if (list.count() == 2) + { + QString json = list[1]; + //qDebug() << "客户端连接 -> 读取订单:" << json; + QList> orders = g_config->toMapList(json); + if (orders.count() > 0) + { + emit signalUpdateOrders(orders); + // 更新读取数量 + emit signalReadOrdersCount(orders.count()); + + // 找到对应的客户端行号并更新表格 + for (int row = 0; row < m_clients.count(); row++) + { + if (m_clients[row] && m_clients[row]->socketDescriptor() == socketDecriptor) + { + // 直接调用函数更新读取次数和数量 + updateReadTimes(row, 1); // 每次读取+1 + updateReadCount(row, orders.count()); // 增加订单数量 + break; + } + } + } + } + } + else if (type == ReadUsers) + { + QStringList list = dataStr.split("|"); + // qDebug() << "[ReadUsers]数据分割:" << list.count(); + if (list.count() == 2) + { + QString json = list[1]; + QList> users = g_config->toMapList(json); + emit signalUpdateUsers(users); + } + } +} + +// 定时器读取新订单 +void Connect::slotUpdateOrders() +{ + emit signalReadOrdersTimes(); + for (int i = 0; i < m_clients.count(); i++) + { + // **检查是否启用** + QCheckBox* checkBox = reinterpret_cast(ui.tableWidget->cellWidget(i, 0)->layout()->itemAt(0)->widget()); + if (!checkBox->isChecked()) { + continue; // 跳过未启用的行 + } + + if (m_clients.count() > i) + { + // 登录+客户标识 + if (m_clients[i]) + { + if (m_clients[i]->state() == QAbstractSocket::ConnectedState && + ui.tableWidget->item(i, 4)->text() == "连接") // 只有已登录的连接才发送读取请求 + { + // 发送读取信息封包 + + // 根据配置转换为皇冠时间读取 + QString time; + if (g_config->screenDateTimeEnable()) + { + if (g_config->crownTime()) + { + time = g_config->screenDateTime(); + } + else + { + //qDebug() << "本地时间" + g_config->screenDateTime(); + time = QDateTime::fromString(g_config->screenDateTime()).addSecs(-43200).toString("yyyy-MM-dd HH:mm:ss"); + } + } + QString sendData = "ReadOrders|" + ui.tableWidget->item(i, 3)->text() + "|" + ui.clientSignEdit->text() + "|" + time + "|" + ui.readNumberEdit->text(); + //qDebug() << "请求读取:" << sendData; + emit m_clients[i]->signalSendData(sendData.toUtf8()); + + + // 定时器发送读取信息封包 + sendData = "ReadUsers|" + ui.tableWidget->item(i, 3)->text() +"|UpdateUsers" ; + //qDebug() << "定时器发送读取信息封包:" << sendData; + emit m_clients[i]->signalSendData(sendData.toUtf8()); + } + } + } + } +} + +/// +/// 启动读取订单定时器 +/// +void Connect::slotStart() +{ + if (!m_timer->isActive()) + { + m_timer->start(ui.readSleepEdit->text().toInt() * 1000); + } +} + +/// +/// 暂停读取订单定时器 +/// +void Connect::slotStop() +{ + if (m_timer->isActive()) + { + m_timer->stop(); + } +} + +void Connect::slotFlushAccount() +{ + for (int i = 0; i < m_clients.count(); i++) + { + // 检查是否启用 + QCheckBox* checkBox = reinterpret_cast(ui.tableWidget->cellWidget(i, 0)->layout()->itemAt(0)->widget()); + if (!checkBox->isChecked()) { + continue; // 跳过未启用的行 + } + + if (m_clients[i] && m_clients[i]->state() == QAbstractSocket::ConnectedState) + { + // 发送读取用户列表封包 + QString sendData = "ReadUsers|" + ui.tableWidget->item(i, 3)->text() + "|InitUsers"; + //qDebug() << "发送读取用户封包:" << sendData; + emit m_clients[i]->signalSendData(sendData.toUtf8()); + + } + } +} + +/// +/// 发送跟单注单信息 +/// +/// +void Connect::slotFollowBet(QMap order) +{ + for (int i = 0; i < m_clients.count(); i++) + { + if (m_clients.count() > i) + { + // 登录+客户标识 + if (m_clients[i]) + { + if (m_clients[i]->state() == QAbstractSocket::ConnectedState && + ui.tableWidget->item(i, 4)->text() == "连接") // 只有已登录的连接才发送跟单请求 + { + // 发送跟单数据封包 + QString sendData = "FollowBet|" + ui.tableWidget->item(i, 3)->text() +"|"+ order["ticket_id"]; + //qDebug() << "发送信息 -> 跟单成功 ->" << sendData; + emit m_clients[i]->signalSendData(sendData.toUtf8()); + } + } + } + } +} + +// 连接按钮 +void Connect::slotConnect() +{ + // 禁止编辑 + ui.tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); + // 禁用连接按钮 + ui.connectButton->setDisabled(true); + // 启用断开按钮 + ui.disconnectButton->setDisabled(false); + + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + QCheckBox* checkBox = reinterpret_cast(ui.tableWidget->cellWidget(row, 0)->layout()->itemAt(0)->widget()); + if (checkBox->isChecked()) + { + if (m_clients[row]) + { + // 错误重连 + connect(m_clients[row], QOverload::of(&QAbstractSocket::error), this, &Connect::handleError, Qt::QueuedConnection); + + + QHostAddress ip = QHostAddress(ui.tableWidget->item(row, 1)->text()); + qintptr port = ui.tableWidget->item(row, 2)->text().toInt(); + m_clients[row]->connectToHost(ip, port); + } + } + } +} + +// 断开按钮 +void Connect::slotDisconnect() +{ + + // 禁止操作 + ui.tableWidget->setEditTriggers(QAbstractItemView::AllEditTriggers); + ui.connectButton->setDisabled(false); + ui.disconnectButton->setDisabled(true); + + // 遍历 + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + QCheckBox* checkBox = reinterpret_cast(ui.tableWidget->cellWidget(row, 0)->layout()->itemAt(0)->widget()); + if (checkBox->isChecked()) + { + if (m_clients[row]) + { + // 错误重连 + disconnect(m_clients[row], QOverload::of(&QAbstractSocket::error), this, &Connect::handleError); + m_clients[row]->disconnectFromHost(); + } + } + } + +} + + + +/// +/// 更新读取次数 +/// +void Connect::updateReadTimes(int row, int times) +{ + if (row >= 0 && row < ui.tableWidget->rowCount()) { + int currentTimes = ui.tableWidget->item(row, 5)->text().toInt(); + ui.tableWidget->item(row, 5)->setText(QString::number(currentTimes + times)); + + // 保存到配置中 + QList> servers = g_config->servers(); + if (row < servers.count()) { + servers[row]["readTimes"] = ui.tableWidget->item(row, 5)->text(); + g_config->setServers(servers); + } + } +} + +/// +/// 更新读取数量 +/// +void Connect::updateReadCount(int row, int count) +{ + if (row >= 0 && row < ui.tableWidget->rowCount()) { + int currentCount = ui.tableWidget->item(row, 6)->text().toInt(); + ui.tableWidget->item(row, 6)->setText(QString::number(currentCount + count)); + + // 保存到配置中 + QList> servers = g_config->servers(); + if (row < servers.count()) { + servers[row]["dataCount"] = ui.tableWidget->item(row, 6)->text(); + g_config->setServers(servers); + } + } +} + + +/// +/// 窗口关闭事件 +/// +/// 事件 +void Connect::closeEvent(QCloseEvent* event) +{ + // 保存配置 + //qDebug() << "保存配置"; + QList> list; + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + QMap server; + QCheckBox* checkBox = reinterpret_cast(ui.tableWidget->cellWidget(row, 0)->layout()->itemAt(0)->widget()); + if (checkBox->isChecked()) + { + server["enable"] = "true"; + } + else + { + server["enable"] = "false"; + } + server["ip"] = ui.tableWidget->item(row, 1)->text(); + server["port"] = ui.tableWidget->item(row, 2)->text(); + server["connectPassword"] = ui.tableWidget->item(row, 3)->text(); + server["readTimes"] = ui.tableWidget->item(row, 5)->text(); + server["dataCount"] = ui.tableWidget->item(row, 6)->text(); + list.append(server); + } + // 保存服务器列表 + g_config->setServers(list); + // 保存客户端标志 + g_config->setClientSign(ui.clientSignEdit->text()); + // 保存一次读取数量 + g_config->setReadCount(ui.readNumberEdit->text().toInt()); + // 保存一次读取延迟 + g_config->setReadSleep(ui.readSleepEdit->text().toInt()); + // 保存自动连接状态 + g_config->setAutoConnect(ui.autoConnectCheckBox->isChecked()); + + //qDebug() << "配置保存完成,接受关闭事件"; + event->accept(); +} \ No newline at end of file diff --git a/CrownClient/Connect.h b/CrownClient/Connect.h new file mode 100644 index 0000000..9cc3678 --- /dev/null +++ b/CrownClient/Connect.h @@ -0,0 +1,98 @@ +#pragma once + +#include +#include +#include "TcpSocket.h" +#include "ui_Connect.h" + +/// +///通信协议 +/// +enum PROTOCOL +{ + Error, + Login, + LoginSuccess, + LoginFailed, + ReadOrders, + ReadUsers, + FollowBet, + Logout +}; + +class Connect : public QWidget +{ + Q_OBJECT + +public: + Connect(QWidget *parent = nullptr); + ~Connect(); +private: + // 在 Connect 类中添加一个枚举表示连接状态 + enum ServerState { + Disconnected, // 断开 + Connected, // 已连接但未登录 + LoggedIn // 已登录 + }; + // 客户端列表 + QList m_clients; + // 请求读取订单定时器 + QTimer* m_timer; + // TCP连接状态检查定时器 + QTimer* m_tcpCheckTimer; +signals: + // 连接状态改变信号 + void signalStateChange(int); + // 收到注单信号 + void signalUpdateOrders(QList>); + // 收到用户列表信号 + void signalUpdateUsers(QList>); + // 更新读取订单次数信号 + void signalReadOrdersTimes(); + // 更新读取订单数量信号 + void signalReadOrdersCount(int count); + +public slots: + // 槽函数 -> 连接 + void slotConnect(); + // 槽函数 -> 断开连接 + void slotDisconnect(); + // 槽函数 -> 已连接 + void slotOnConnected(); + // 槽函数 -> 已断开 + void slotOnDisconnected(); + // 槽函数 -> 重连 + void handleError(QAbstractSocket::SocketError socketError); + // 槽函数 -> 按日期接收 + void slotDateRecv(qintptr socketDecriptor, QByteArray data); + // 槽函数 -> 更新订单 + void slotUpdateOrders(); + + // 更新状态 + void updateState(); + // 同步连接状态 + void syncConnectionState(); + // 槽函数 -> 开始 + void slotStart(); + // 槽函数 -> 停止 + void slotStop(); + // 槽函数 -> 刷新会员列表 + void slotFlushAccount(); + + + // 槽函数 -> 发送跟单成功数据(防止重复派单) + void slotFollowBet(QMap order); + + +private: + // 窗口关闭事件 + void closeEvent(QCloseEvent* event); + // 解析协议类型 + PROTOCOL ProtocolType(QString data); +private: + // 添加这两个槽函数 + void updateReadCount(int row, int count); + void updateReadTimes(int row, int times); +private: + Ui::ConnectClass ui; +}; diff --git a/CrownClient/Connect.ui b/CrownClient/Connect.ui new file mode 100644 index 0000000..d65cead --- /dev/null +++ b/CrownClient/Connect.ui @@ -0,0 +1,190 @@ + + + ConnectClass + + + + 0 + 0 + 808 + 432 + + + + Connect + + + + + + + + + + + + + + + + + 客户标识: + + + + + + + + 16777215 + 16777215 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 每次读取: + + + + + + + + + + 条 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 读取延时: + + + + + + + + + + 秒 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + + + 自动连接[服务端] + + + + + + + 连 接 + + + true + + + + + + + false + + + 断 开 + + + true + + + + + + + + + + + + + + + + <html><head/><body><p><span style=" color:#3b8626;">填写不同(客户标识),各自读取完整注单,填写相同(客户标识)则共享同一份注单.</span></p></body></html> + + + + + + + <html><head/><body><p><span style=" color:#ff0800;">填写相同(客户标识),并且每次读取①条,则同一份注单,由多个客户端拆分读取.</span></p></body></html> + + + + + + + + + + + + + + diff --git a/CrownClient/Constant.h b/CrownClient/Constant.h new file mode 100644 index 0000000..c1189b9 --- /dev/null +++ b/CrownClient/Constant.h @@ -0,0 +1,69 @@ +#pragma once +#include +#include + + +static const long INIT_NUMBER = -1; + +//包数据结构 : [ 包头 + 长度(8字节) + 包类型(2字节) + 数据 + 包尾 ] +static const char* NET_PACKET_START = "PACKET_START"; +static const char* NET_PACKET_END = "PACKET_END"; +static const int NET_PACKET_TYPE_BYTES = 2; //包类型占几个字节 +static const int NET_PACKET_LENGTH_BYTES = 8; //包数据长度占几个字节 + +//包类型 +static const char* NET_PACKET_TYPE_SEND_FILE = "01"; //发送文件 +static const char* NET_PACKET_TYPE_SEND_TEXT = "02"; //发送文本 + +//用于存储接收到的数据包 +class SocketPacket +{ +public: + long length; //数据长度 + QByteArray data; //数据 + QByteArray dataType; //数据类型 + + SocketPacket() + { + length = INIT_NUMBER; + } + + void clear() + { + length = INIT_NUMBER; + data.clear(); + dataType.clear(); + } +}; + +struct NetSendFile +{ + QString m_filename; + QByteArray m_bytearray; + friend QDataStream& operator>>(QDataStream& in, NetSendFile& stru) + { + in >> stru.m_filename >> stru.m_bytearray; + return in; + } + friend QDataStream& operator<<(QDataStream& out, const NetSendFile& stru) + { + out << stru.m_filename << stru.m_bytearray; + return out; + } +}; + +class NetSendText +{ +public: + QString m_text; + friend QDataStream& operator>>(QDataStream& in, NetSendText& stru) + { + in >> stru.m_text; + return in; + } + friend QDataStream& operator<<(QDataStream& out, const NetSendText& stru) + { + out << stru.m_text; + return out; + } +}; diff --git a/CrownClient/CrownClient.cpp b/CrownClient/CrownClient.cpp new file mode 100644 index 0000000..2448088 --- /dev/null +++ b/CrownClient/CrownClient.cpp @@ -0,0 +1,2891 @@ +#include "CrownClient.h" +#include "Connect.h" +#include "User.h" +#include "Global.h" +#include +#include "WebEnginePage.h" +#include +#include +#include "Utils.h" +#include +#include +#include +#include "AppInstanceManager.h" +#include "PushMsg.h" +#include +#include +#include +CrownClient::CrownClient(QWidget *parent) + : QMainWindow(parent) +{ + + + + //// ... 在创建 QWebEngineView 之前添加这行代码 + //QNetworkProxyFactory::setUseSystemConfiguration(false); + + // 安装 UI + ui.setupUi(this); + // 设置窗口图标 + this->setWindowIcon(QIcon(":/images/Images/client.ico")); + // 设置窗口标题 + this->setWindowTitle(QString("金运来皇冠跟单软件(客户端) ") + QString(VERSION)); + + + +#ifdef _DEBUG + /////////////////////////////////////////////////// + // 调试窗口 + /////////////////////////////////////////////////// + QWidget* debug_window = new QWidget(nullptr); + QVBoxLayout* layout = new QVBoxLayout(debug_window); + + QWebEngineView* debug = new QWebEngineView(); + layout->addWidget(debug); + debug_window->setLayout(layout); + debug->load(QUrl("http://localhost:7777/")); \ + debug_window->show(); +#endif + + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // 防止多开 + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + connect(AppInstanceManager::instance(), &AppInstanceManager::raiseRequested, + this, [this]() { + showNormal(); // 双击托盘图标恢复窗口 + //show(); + raise(); + activateWindow(); + }); + + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // 托盘图标 + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + // 创建托盘图标 + trayIcon = new QSystemTrayIcon(this); + trayIcon->setIcon(QIcon(":/images/Images/client.ico")); + trayIcon->setToolTip("金运来皇冠跟单软件(客户端)"); + // 创建托盘菜单 + QMenu *trayMenu = new QMenu(this); + trayMenu->addAction("恢复", this, &CrownClient::showNormal); + trayMenu->addAction("退出", this, &CrownClient::close); + + trayIcon->setContextMenu(trayMenu); + trayIcon->show(); + + // 连接托盘图标点击事件 + connect(trayIcon, &QSystemTrayIcon::activated, this, &CrownClient::onTrayIconActivated); + + + ////////////////////////////////////////////////////////// + // 心跳定时器 + ////////////////////////////////////////////////////////// + m_heartbeatTimer = new QTimer(this); + connect(m_heartbeatTimer, &QTimer::timeout, this, &CrownClient::heartbeat); + m_heartbeatTimer->start(15000); // 15秒一次 + + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // 变量初始化 + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + // 初始化状态 + m_state = wait; + // 清空变量 + m_readOrderTimes = 0; + m_readOrderCount = 0; + m_successOrderCount = 0; + m_screenOrderCount = 0; + + m_bet_thread = nullptr; + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // 连接窗口 + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + Connect* window_connect = new Connect(); + // 载入窗口 + connect(ui.connectButton, &QPushButton::clicked, window_connect, &QWidget::show); + // 开始读取注单 + connect(this, &CrownClient::signalStart, window_connect, &Connect::slotStart); + // 停止读取注单 + connect(this, &CrownClient::signalStop, window_connect, &Connect::slotStop); + // 改变状态 + connect(window_connect, &Connect::signalStateChange, this, &CrownClient::slotChangeState); + + // 接收注单 + connect(window_connect, &Connect::signalUpdateOrders, this, &CrownClient::slotAcceptOrders); + + connect(window_connect, &Connect::signalReadOrdersTimes, this, &CrownClient::slotUpdateReadOrdersTimes); + connect(window_connect, &Connect::signalReadOrdersCount, this, &CrownClient::slotUpdateReadOrdersCount); + + + + + + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // 账户管理 + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + User* user = new User(); + // 窗口显示 + connect(ui.userManagerButton, &QPushButton::clicked, user, &QWidget::show); + // 连接添加用户信息信号 + connect(this, &CrownClient::signalAddUser, user, &User::slotAddUser); + // 连接设置用户信息信号 + connect(user, &User::signalSetUser, this, &CrownClient::slotSetUser); + // 开始按钮 + connect(ui.startButton, &QPushButton::clicked, this, [=]() { + QString username = ui.usernameEdit->text(); + QString password = ui.passwordEdit->text(); + emit signalAddUser(username, password); + }); + // 登录按钮 + connect(ui.loginButton, &QPushButton::clicked, this, [=]() { + QString username = ui.usernameEdit->text(); + QString password = ui.passwordEdit->text(); + emit signalAddUser(username, password); + }); + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // 通知窗口 + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + m_window_notice = new Notice(); + // 载入窗口 + connect(ui.button_notice, &QPushButton::clicked, m_window_notice, &QWidget::show); + //// 开始读取注单 + //connect(this, &CrownClient::signalStart, window_connect, &Connect::slotStart); + //// 停止读取注单 + //connect(this, &CrownClient::signalStop, window_connect, &Connect::slotStop); + //// 改变状态 + //connect(window_connect, &Connect::signalStateChange, this, &CrownClient::slotChangeState); + + //// 接收注单 + //connect(window_connect, &Connect::signalUpdateOrders, this, &CrownClient::slotAcceptOrders); + + //connect(window_connect, &Connect::signalReadOrdersTimes, this, &CrownClient::slotUpdateReadOrdersTimes); + //connect(window_connect, &Connect::signalReadOrdersCount, this, &CrownClient::slotUpdateReadOrdersCount); + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // 跟单设置 + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + m_window_setting = new Setting(); + connect(ui.settingButton, &QPushButton::clicked, m_window_setting, &Setting::show); + connect(ui.settingButton, &QPushButton::clicked, window_connect, &Connect::slotFlushAccount); + // 更新联盟和队伍 + connect(this, &CrownClient::signalUpdateLeagueAndTeam, m_window_setting, &Setting::slotUpdateLeagueAndTeam); + // 更新用户列表 + connect(window_connect, &Connect::signalUpdateUsers, m_window_setting, [this](QList> list) { + m_window_setting->slotUpdateUsers(list); + if (m_bet_thread) + { + + } + }); + // 皇冠时间按钮 + ui.crownTimeButton->setIconSize(QSize(48, 48)); + //ui.crownTimeButton->setFlat(true); + ui.crownTimeButton->setCursor(QCursor(Qt::PointingHandCursor)); + + connect(ui.crownTimeButton, &QPushButton::clicked, this, [&]() { + // 直接调用统一时间调整函数 + view_change_time(!g_config->crownTime()); + }); + + // 显示账号和到期时间 + ui.endtimeLabel->setText("

软件登录账号: " + g_verify->Username() + QString(" 软件到期时间: ") + g_verify->GetDueTime().toString("yyyy-MM-dd hh:MM:ss") + "

"); + + + + + // 重写Page屏蔽SSL证书错误 + WebEnginePage* page = new WebEnginePage(); + page->profile()->setHttpAcceptLanguage("zh-CN,zh;q=0.9"); + ui.webEngineView->setPage(page); + + QWebEngineSettings *settings = page->settings(); + + // 禁用favicon自动加载 + settings->setAttribute(QWebEngineSettings::AutoLoadIconsForPage, false); + // 禁用右键菜单 + ui.webEngineView->setContextMenuPolicy(Qt::NoContextMenu); + // 设置访问地址 + if (!ui.urlCombo->currentText().isEmpty()) + { + qDebug() << "主程序 -> 浏览默认网址:" << ui.urlCombo->currentText(); + ui.webEngineView->load(QUrl(ui.urlCombo->currentText())); + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // 读取配置 + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // ui.screenDateTimeCheckBox->setChecked(false); + ui.dateTimeEdit->setDateTime(g_config->formatDateTime(QDateTime::currentDateTime())); + ui.screenDateTimeCheckBox->setChecked(g_config->screenDateTimeEnable()); + if (g_config->crownTime()) + { + ui.crownTimeButton->setIcon(QIcon(":/images/Images/crownTime.png")); + ui.crownTimeButton->setText("皇冠时间"); + + QPalette palette; + palette.setColor(QPalette::ButtonText, QColor(Qt::red)); + ui.crownTimeButton->setPalette(palette); + + } + else + { + ui.crownTimeButton->setIcon(QIcon(":/images/Images/localTime.png")); + ui.crownTimeButton->setText("本地时间"); + QPalette palette; + palette.setColor(QPalette::ButtonText, QColor(QRgb(0x008000))); + ui.crownTimeButton->setPalette(palette); + } + // qDebug() << "URL List:" << g_config->client_url_list(); + // qDebug() << "Current URL:" << g_config->client_url(); + // qDebug() << g_config->client_url_list(); + ui.urlCombo->addItems(g_config->client_url_list()); + ui.urlCombo->setCurrentText(g_config->client_url()); + ui.usernameEdit->setText(g_config->username()); + ui.passwordEdit->setText(g_config->password()); + + //ui.dateTimeEdit->setDateTime(QDateTime::fromString(g_config->screenDateTime())); + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // 接收注单表格 - 改为QTreeView实现 + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + { + // 创建模型 + QStandardItemModel *orderModel = new QStandardItemModel(0, 11, this); + orderModel->setHorizontalHeaderLabels({ "单号/场次","下注时间","接收时间","会员/代理","项目","类型","联赛/队伍","下注","盘口","赔率","金额" }); + + // 设置TreeView + ui.order_tree_view->setModel(orderModel); + ui.order_tree_view->setEditTriggers(QAbstractItemView::NoEditTriggers); + ui.order_tree_view->setContextMenuPolicy(Qt::CustomContextMenu); + + // 设置列宽策略 + ui.order_tree_view->header()->setSectionsMovable(true); // 允许列移动 + ui.order_tree_view->header()->setSectionResizeMode(QHeaderView::Interactive); // 允许手动调整列宽 + ui.order_tree_view->header()->setMinimumSectionSize(50); // 设置最小宽度 + ui.order_tree_view->setWordWrap(true); // 设置文本自动换行和工具提示 + ui.order_tree_view->setSortingEnabled(true); // 启用排序 + + // 设置初始列宽(根据你的测试数据合理分配) + ui.order_tree_view->header()->resizeSection(0, 200); // 单号/场次 + ui.order_tree_view->header()->resizeSection(1, 150); // 下注时间 + ui.order_tree_view->header()->resizeSection(2, 150); // 接收时间 + ui.order_tree_view->header()->resizeSection(3, 120); // 会员/代理 + ui.order_tree_view->header()->resizeSection(4, 150); // 项目(足球滚球全场等可能较长) + ui.order_tree_view->header()->resizeSection(5, 100); // 类型 + ui.order_tree_view->header()->resizeSection(6, 250); // 联赛/队伍(需要较宽空间) + ui.order_tree_view->header()->resizeSection(7, 100); // 下注 + ui.order_tree_view->header()->resizeSection(8, 80); // 盘口 + ui.order_tree_view->header()->resizeSection(9, 150); // 赔率 + ui.order_tree_view->header()->resizeSection(10, 80); // 金额 + + // 创建右键菜单 + QMenu* orderMenu = new QMenu(ui.order_tree_view); + QMenu* orderGroupMenu = new QMenu("分组方式", orderMenu); + QAction* orderGroupByIdAction = new QAction("按订单号分组", orderMenu); + QAction* orderGroupByTimeAction = new QAction("按时间分组", orderMenu); + QAction* orderNoGroupAction = new QAction("无分组", orderMenu); + QAction* orderDeleteAction = new QAction("删除选中项", orderMenu); + QAction* orderClearAction = new QAction("清空所有", orderMenu); + + orderGroupMenu->addAction(orderGroupByIdAction); + orderGroupMenu->addAction(orderGroupByTimeAction); + orderGroupMenu->addAction(orderNoGroupAction); + orderMenu->addMenu(orderGroupMenu); + orderMenu->addSeparator(); + orderMenu->addAction(orderDeleteAction); + orderMenu->addAction(orderClearAction); + + // 连接信号槽 + connect(ui.order_tree_view, &QTreeView::customContextMenuRequested, this, [=](const QPoint &pos) { + orderMenu->popup(ui.order_tree_view->viewport()->mapToGlobal(pos)); + }); + connect(orderGroupByIdAction, &QAction::triggered, this, [=]() { groupTreeView(ui.order_tree_view, BY_ORDER_ID); }); + connect(orderGroupByTimeAction, &QAction::triggered, this, [=]() { groupTreeView(ui.order_tree_view, BY_TIME); }); + connect(orderNoGroupAction, &QAction::triggered, this, [=]() { groupTreeView(ui.order_tree_view, NO_GROUP); }); + connect(orderDeleteAction, &QAction::triggered, this, [=]() { deleteSelectedItems(ui.order_tree_view); }); + connect(orderClearAction, &QAction::triggered, this, [=]() { clearTreeView(ui.order_tree_view); }); + + // 启用排序 + ui.order_tree_view->setSortingEnabled(true); + + // 读取接收注单缓存 + QList> accept_orders = g_config->get_accept_orders(); + for (QMap accept_order : accept_orders) + { + view_add_accept_order(accept_order); + } + } + + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// 筛选注单表格 - 改为QTreeView +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + { + QStandardItemModel *screen_model = new QStandardItemModel(0, 11, this); + screen_model->setHorizontalHeaderLabels({ "单号/场次","下注时间","会员/代理","项目","类型","联赛/队伍","下注","盘口","赔率","金额","原因" }); + + ui.screen_tree_view->setModel(screen_model); + ui.screen_tree_view->setEditTriggers(QAbstractItemView::NoEditTriggers); + ui.screen_tree_view->setContextMenuPolicy(Qt::CustomContextMenu); + + // 设置列宽策略 + ui.screen_tree_view->header()->setSectionsMovable(true); // 允许列移动 + ui.screen_tree_view->header()->setSectionResizeMode(QHeaderView::Interactive); // 允许手动调整列宽 + ui.screen_tree_view->header()->setMinimumSectionSize(50); // 设置最小宽度 + ui.screen_tree_view->setWordWrap(true); // 设置文本自动换行和工具提示 + ui.screen_tree_view->setSortingEnabled(true); // 启用排序 + + // 设置初始列宽 + ui.screen_tree_view->header()->resizeSection(0, 200); // 单号/场次 + ui.screen_tree_view->header()->resizeSection(1, 150); // 下注时间 + ui.screen_tree_view->header()->resizeSection(2, 120); // 会员/代理 + ui.screen_tree_view->header()->resizeSection(3, 150); // 项目 + ui.screen_tree_view->header()->resizeSection(4, 100); // 类型 + ui.screen_tree_view->header()->resizeSection(5, 250); // 联赛/队伍 + ui.screen_tree_view->header()->resizeSection(6, 100); // 下注 + ui.screen_tree_view->header()->resizeSection(7, 80); // 盘口 + ui.screen_tree_view->header()->resizeSection(8, 150); // 赔率 + ui.screen_tree_view->header()->resizeSection(9, 80); // 金额 + ui.screen_tree_view->header()->resizeSection(10, 150); // 原因 + + // 创建右键菜单 + QMenu* screenMenu = new QMenu(ui.screen_tree_view); + QMenu* screenGroupMenu = new QMenu("分组方式", screenMenu); + QAction* screenGroupByIdAction = new QAction("按订单号分组", screenMenu); + QAction* screenGroupByTimeAction = new QAction("按时间分组", screenMenu); + QAction* screenNoGroupAction = new QAction("无分组", screenMenu); + QAction* screenDeleteAction = new QAction("删除选中项", screenMenu); + QAction* screenClearAction = new QAction("清空所有", screenMenu); + + screenGroupMenu->addAction(screenGroupByIdAction); + screenGroupMenu->addAction(screenGroupByTimeAction); + screenGroupMenu->addAction(screenNoGroupAction); + screenMenu->addMenu(screenGroupMenu); + screenMenu->addSeparator(); + screenMenu->addAction(screenDeleteAction); + screenMenu->addAction(screenClearAction); + + // 连接信号槽 + connect(ui.screen_tree_view, &QTreeView::customContextMenuRequested, this, [=](const QPoint &pos) { + screenMenu->popup(ui.screen_tree_view->viewport()->mapToGlobal(pos)); + }); + connect(screenGroupByIdAction, &QAction::triggered, this, [=]() { groupTreeView(ui.screen_tree_view, BY_ORDER_ID); }); + connect(screenGroupByTimeAction, &QAction::triggered, this, [=]() { groupTreeView(ui.screen_tree_view, BY_TIME); }); + connect(screenNoGroupAction, &QAction::triggered, this, [=]() { groupTreeView(ui.screen_tree_view, NO_GROUP); }); + connect(screenDeleteAction, &QAction::triggered, this, [=]() { deleteSelectedItems(ui.screen_tree_view); }); + connect(screenClearAction, &QAction::triggered, this, [=]() { clearTreeView(ui.screen_tree_view); }); + + // 启用排序 + ui.screen_tree_view->setSortingEnabled(true); + + // 读取筛选注单缓存 + QList> screen_orders = g_config->get_screen_orders(); + for (QMap screen_order : screen_orders) { + view_add_screen_order(screen_order); + } + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // 跟单成功表格 - 改为QTreeView + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + { + QStandardItemModel* success_model = new QStandardItemModel(0, 10, this); + success_model->setHorizontalHeaderLabels({ "单号/场次","跟单时间","会员/代理","项目","类型","联赛/队伍","下注","盘口","赔率","金额" }); + + ui.success_tree_view->setModel(success_model); + ui.success_tree_view->setEditTriggers(QAbstractItemView::NoEditTriggers); + ui.success_tree_view->setContextMenuPolicy(Qt::CustomContextMenu); + + // 设置列宽策略 + ui.success_tree_view->header()->setSectionsMovable(true); // 允许列移动 + ui.success_tree_view->header()->setSectionResizeMode(QHeaderView::Interactive); // 允许手动调整列宽 + ui.success_tree_view->header()->setMinimumSectionSize(50); // 设置最小宽度 + ui.success_tree_view->setWordWrap(true); // 设置文本自动换行和工具提示 + ui.success_tree_view->setSortingEnabled(true); // 启用排序 + + // 设置初始列宽 + ui.success_tree_view->header()->resizeSection(0, 200); // 单号/场次 + ui.success_tree_view->header()->resizeSection(1, 150); // 跟单时间 + ui.success_tree_view->header()->resizeSection(2, 120); // 会员/代理 + ui.success_tree_view->header()->resizeSection(3, 150); // 项目 + ui.success_tree_view->header()->resizeSection(4, 100); // 类型 + ui.success_tree_view->header()->resizeSection(5, 250); // 联赛/队伍 + ui.success_tree_view->header()->resizeSection(6, 100); // 下注 + ui.success_tree_view->header()->resizeSection(7, 80); // 盘口 + ui.success_tree_view->header()->resizeSection(8, 150); // 赔率 + ui.success_tree_view->header()->resizeSection(9, 80); // 金额 + + // 创建右键菜单 + QMenu* successMenu = new QMenu(ui.success_tree_view); + QMenu* successGroupMenu = new QMenu("分组方式", successMenu); + QAction* successGroupByIdAction = new QAction("按订单号分组", successMenu); + QAction* successGroupByTimeAction = new QAction("按时间分组", successMenu); + QAction* successNoGroupAction = new QAction("无分组", successMenu); + QAction* successDeleteAction = new QAction("删除选中项", successMenu); + QAction* successClearAction = new QAction("清空所有", successMenu); + + successGroupMenu->addAction(successGroupByIdAction); + successGroupMenu->addAction(successGroupByTimeAction); + successGroupMenu->addAction(successNoGroupAction); + successMenu->addMenu(successGroupMenu); + successMenu->addSeparator(); + successMenu->addAction(successDeleteAction); + successMenu->addAction(successClearAction); + + // 连接信号槽 + connect(ui.success_tree_view, &QTreeView::customContextMenuRequested, this, [=](const QPoint &pos) { + successMenu->popup(ui.success_tree_view->viewport()->mapToGlobal(pos)); + }); + connect(successGroupByIdAction, &QAction::triggered, this, [=]() { groupTreeView(ui.success_tree_view, BY_ORDER_ID); }); + connect(successGroupByTimeAction, &QAction::triggered, this, [=]() { groupTreeView(ui.success_tree_view, BY_TIME); }); + connect(successNoGroupAction, &QAction::triggered, this, [=]() { groupTreeView(ui.success_tree_view, NO_GROUP); }); + connect(successDeleteAction, &QAction::triggered, this, [=]() { deleteSelectedItems(ui.success_tree_view); }); + connect(successClearAction, &QAction::triggered, this, [=]() { clearTreeView(ui.success_tree_view); }); + + // 启用排序 + ui.success_tree_view->setSortingEnabled(true); + + // 读取成功注单缓存 + QList> success_orders = g_config->get_success_orders(); + for (QMap success_order : success_orders) { + view_add_success_order(success_order); + } + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // 跟单失败表格 - 改为QTreeView + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + { + QStandardItemModel * failed_model = new QStandardItemModel(0, 11, this); + failed_model->setHorizontalHeaderLabels({ "单号/场次","跟单时间","会员/代理","项目","类型","联赛/队伍","下注","盘口","赔率","金额","原因" }); + + ui.failed_tree_view->setModel(failed_model); + ui.failed_tree_view->setEditTriggers(QAbstractItemView::NoEditTriggers); + ui.failed_tree_view->setContextMenuPolicy(Qt::CustomContextMenu); + + // 设置列宽策略 + ui.failed_tree_view->header()->setSectionsMovable(true); // 允许列移动 + ui.failed_tree_view->header()->setSectionResizeMode(QHeaderView::Interactive); // 允许手动调整列宽 + ui.failed_tree_view->header()->setMinimumSectionSize(50); // 设置最小宽度 + ui.failed_tree_view->setWordWrap(true); // 设置文本自动换行和工具提示 + ui.failed_tree_view->setSortingEnabled(true); // 启用排序 + + // 设置初始列宽 + ui.failed_tree_view->header()->resizeSection(0, 200); // 单号/场次 + ui.failed_tree_view->header()->resizeSection(1, 150); // 跟单时间 + ui.failed_tree_view->header()->resizeSection(2, 120); // 会员/代理 + ui.failed_tree_view->header()->resizeSection(3, 150); // 项目 + ui.failed_tree_view->header()->resizeSection(4, 100); // 类型 + ui.failed_tree_view->header()->resizeSection(5, 250); // 联赛/队伍 + ui.failed_tree_view->header()->resizeSection(6, 100); // 下注 + ui.failed_tree_view->header()->resizeSection(7, 80); // 盘口 + ui.failed_tree_view->header()->resizeSection(8, 150); // 赔率 + ui.failed_tree_view->header()->resizeSection(9, 80); // 金额 + ui.failed_tree_view->header()->resizeSection(10, 150); // 原因 + + // 创建右键菜单 + QMenu* failedMenu = new QMenu(ui.failed_tree_view); + QMenu* failedGroupMenu = new QMenu("分组方式", failedMenu); + QAction* failedGroupByIdAction = new QAction("按订单号分组", failedMenu); + QAction* failedGroupByTimeAction = new QAction("按时间分组", failedMenu); + QAction* failedNoGroupAction = new QAction("无分组", failedMenu); + QAction* failedDeleteAction = new QAction("删除选中项", failedMenu); + QAction* failedClearAction = new QAction("清空所有", failedMenu); + + failedGroupMenu->addAction(failedGroupByIdAction); + failedGroupMenu->addAction(failedGroupByTimeAction); + failedGroupMenu->addAction(failedNoGroupAction); + failedMenu->addMenu(failedGroupMenu); + failedMenu->addSeparator(); + failedMenu->addAction(failedDeleteAction); + failedMenu->addAction(failedClearAction); + + // 连接信号槽 + connect(ui.failed_tree_view, &QTreeView::customContextMenuRequested, this, [=](const QPoint &pos) { + failedMenu->popup(ui.failed_tree_view->viewport()->mapToGlobal(pos)); + }); + connect(failedGroupByIdAction, &QAction::triggered, this, [=]() { groupTreeView(ui.failed_tree_view, BY_ORDER_ID); }); + connect(failedGroupByTimeAction, &QAction::triggered, this, [=]() { groupTreeView(ui.failed_tree_view, BY_TIME); }); + connect(failedNoGroupAction, &QAction::triggered, this, [=]() { groupTreeView(ui.failed_tree_view, NO_GROUP); }); + connect(failedDeleteAction, &QAction::triggered, this, [=]() { deleteSelectedItems(ui.failed_tree_view); }); + connect(failedClearAction, &QAction::triggered, this, [=]() { clearTreeView(ui.failed_tree_view); }); + + // 启用排序 + ui.failed_tree_view->setSortingEnabled(true); + + // 读取失败注单缓存 + QList> failedOrders = g_config->get_failed_orders(); + for (QMap failedOrder : failedOrders) { + view_add_failed_order(failedOrder); + } + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // 补单表格 - 改为QTreeView + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + { + QStandardItemModel* rebet_model = new QStandardItemModel(0, 11, this); + rebet_model->setHorizontalHeaderLabels({ "单号/场次","跟单时间","会员/代理","项目","类型","联赛/队伍","下注","盘口","赔率","金额","原因" }); + + ui.rebet_tree_view->setModel(rebet_model); + ui.rebet_tree_view->setEditTriggers(QAbstractItemView::NoEditTriggers); + ui.rebet_tree_view->setContextMenuPolicy(Qt::CustomContextMenu); + + // 设置列宽策略 + ui.rebet_tree_view->header()->setSectionsMovable(true); // 允许列移动 + ui.rebet_tree_view->header()->setSectionResizeMode(QHeaderView::Interactive); // 允许手动调整列宽 + ui.rebet_tree_view->header()->setMinimumSectionSize(50); // 设置最小宽度 + ui.rebet_tree_view->setWordWrap(true); // 设置文本自动换行和工具提示 + ui.rebet_tree_view->setSortingEnabled(true); // 启用排序 + + // 设置初始列宽 + ui.rebet_tree_view->header()->resizeSection(0, 200); // 单号/场次 + ui.rebet_tree_view->header()->resizeSection(1, 150); // 跟单时间 + ui.rebet_tree_view->header()->resizeSection(2, 120); // 会员/代理 + ui.rebet_tree_view->header()->resizeSection(3, 150); // 项目 + ui.rebet_tree_view->header()->resizeSection(4, 100); // 类型 + ui.rebet_tree_view->header()->resizeSection(5, 250); // 联赛/队伍 + ui.rebet_tree_view->header()->resizeSection(6, 100); // 下注 + ui.rebet_tree_view->header()->resizeSection(7, 80); // 盘口 + ui.rebet_tree_view->header()->resizeSection(8, 150); // 赔率 + ui.rebet_tree_view->header()->resizeSection(9, 80); // 金额 + ui.rebet_tree_view->header()->resizeSection(10, 150); // 原因 + + // 创建右键菜单 + QMenu* rebetMenu = new QMenu(ui.rebet_tree_view); + QMenu* rebetGroupMenu = new QMenu("分组方式", rebetMenu); + QAction* rebetGroupByIdAction = new QAction("按订单号分组", rebetMenu); + QAction* rebetGroupByTimeAction = new QAction("按时间分组", rebetMenu); + QAction* rebetNoGroupAction = new QAction("无分组", rebetMenu); + QAction* rebetDeleteAction = new QAction("删除选中项", rebetMenu); + QAction* rebetClearAction = new QAction("清空所有", rebetMenu); + + rebetGroupMenu->addAction(rebetGroupByIdAction); + rebetGroupMenu->addAction(rebetGroupByTimeAction); + rebetGroupMenu->addAction(rebetNoGroupAction); + rebetMenu->addMenu(rebetGroupMenu); + rebetMenu->addSeparator(); + rebetMenu->addAction(rebetDeleteAction); + rebetMenu->addAction(rebetClearAction); + + // 连接信号槽 + connect(ui.rebet_tree_view, &QTreeView::customContextMenuRequested, this, [=](const QPoint &pos) { + rebetMenu->popup(ui.rebet_tree_view->viewport()->mapToGlobal(pos)); + }); + connect(rebetGroupByIdAction, &QAction::triggered, this, [=]() { groupTreeView(ui.rebet_tree_view, BY_ORDER_ID); }); + connect(rebetGroupByTimeAction, &QAction::triggered, this, [=]() { groupTreeView(ui.rebet_tree_view, BY_TIME); }); + connect(rebetNoGroupAction, &QAction::triggered, this, [=]() { groupTreeView(ui.rebet_tree_view, NO_GROUP); }); + connect(rebetDeleteAction, &QAction::triggered, this, [=]() { deleteSelectedItems(ui.rebet_tree_view); }); + connect(rebetClearAction, &QAction::triggered, this, [=]() { clearTreeView(ui.rebet_tree_view); }); + + // 启用排序 + ui.rebet_tree_view->setSortingEnabled(true); + + // 读取补单记录缓存 + QList> rebet_orders = g_config->get_rebet_orders(); + for (QMap rebet_order : rebet_orders) { + view_add_rebet_order(rebet_order); + } + } + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // 日志树 + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + { + // 建立数据模型对象空间并指定父对象 + m_logModel = new QStandardItemModel(ui.log_tree_view); + // 绑定数据模型到树形视图上 + ui.log_tree_view->setModel(m_logModel); + // 设置水平表头列宽度根据内容变化 + ui.log_tree_view->header()->setSectionResizeMode(QHeaderView::ResizeToContents); + // 设置可排序 + ui.log_tree_view->setSortingEnabled(true); + // 添加列标题 + m_logModel->setHorizontalHeaderLabels({ "时间","类型","日志" }); + + // 创建一个QSortFilterProxyModel作为代理模型 + m_logProxyModel = new QSortFilterProxyModel(); + // 设置代理模型的源模型为我们创建的数据模型 + m_logProxyModel->setSourceModel(m_logModel); + // 将QTreeView的模型设置为代理模型 + ui.log_tree_view->setModel(m_logProxyModel); + + // 启用代理模型的排序功能 + m_logProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); + m_logProxyModel->setDynamicSortFilter(true); + + ui.log_tree_view->setEditTriggers(QAbstractItemView::NoEditTriggers); + connect(this, &CrownClient::log, this, &CrownClient::on_log); + + // 创建日志右键菜单 + QMenu* logMenu = new QMenu(ui.log_tree_view); + QMenu* logGroupMenu = new QMenu("分组方式", logMenu); + QAction* logGroupByTimeAction = new QAction("按时间分组", logMenu); + QAction* logGroupByTypeAction = new QAction("按类型分组", logMenu); + QAction* logNoGroupAction = new QAction("无分组", logMenu); + QAction* logDeleteAction = new QAction("删除选中项", logMenu); + QAction* logClearAction = new QAction("清空所有", logMenu); + + logGroupMenu->addAction(logGroupByTimeAction); + logGroupMenu->addAction(logGroupByTypeAction); + logGroupMenu->addAction(logNoGroupAction); + logMenu->addMenu(logGroupMenu); + logMenu->addSeparator(); + logMenu->addAction(logDeleteAction); + logMenu->addAction(logClearAction); + + // 连接信号槽 + connect(ui.log_tree_view, &QTreeView::customContextMenuRequested, this, [=](const QPoint &pos) { + logMenu->popup(ui.log_tree_view->viewport()->mapToGlobal(pos)); + }); + connect(logGroupByTimeAction, &QAction::triggered, this, [=]() { groupLogTreeView(BY_TIME); }); + connect(logGroupByTypeAction, &QAction::triggered, this, [=]() { groupLogTreeView(BY_LOG_TYPE); }); + connect(logNoGroupAction, &QAction::triggered, this, [=]() { groupLogTreeView(NO_GROUP); }); + connect(logDeleteAction, &QAction::triggered, this, [=]() { deleteSelectedItems(ui.log_tree_view); }); + connect(logClearAction, &QAction::triggered, this, [=]() { clearTreeView(ui.log_tree_view); }); + } + + + + + + // 开始按钮 + connect(ui.startButton, &QPushButton::clicked, this, &CrownClient::slotStart); + // 停止按钮 + connect(ui.stopButton, &QPushButton::clicked, this, &CrownClient::slotStop); + // 登录按钮 + connect(ui.loginButton, &QPushButton::clicked, this, &CrownClient::slotLogin); + + + + + //connect(this,&CrownClient::signalBetSuccess, m_conn); + + // 创建定时器获取必要参数 + m_paramerTimer = new QTimer(this); + connect(m_paramerTimer, &QTimer::timeout, this, &CrownClient::slotUpdateParamer); + + + //// 开启心跳线程 + //m_heartbeat_thread = new HeartbeatThread(); + //connect(m_heartbeat_thread, &HeartbeatThread::signal_due, this, [&]() { + // VMProtectBegin("HeartBeat"); + // QMessageBox::critical(nullptr, "错误", "授权已到期!"); + // QApplication::quit(); + // VMProtectEnd(); + //}); + //m_heartbeat_thread->start(); + + + + // 创建下注线程 + m_bet_thread = new BetThread(); + + + connect(m_bet_thread, &BetThread::signal_view_add_failed_order, this, &CrownClient::view_add_failed_order); + + connect(m_bet_thread, &BetThread::signal_view_add_rebet_order, this, &CrownClient::view_add_rebet_order); + connect(m_bet_thread, &BetThread::signal_view_add_screen_order, this, &CrownClient::view_add_screen_order); + connect(m_bet_thread, &BetThread::signal_view_add_success_order, this, &CrownClient::view_add_success_order); + connect(m_bet_thread, &BetThread::signal_view_alert_failed_order, this, &CrownClient::view_alert_failed_order); + connect(m_bet_thread, &BetThread::signal_view_remove_failed_order, this, &CrownClient::view_remove_failed_order); + + connect(m_bet_thread, &BetThread::account_disconnect, this, &CrownClient::on_disconnected); + + // 发送跟单信息给服务端(防止重复跟单) + // connect(this, &CrownClient::signalBetSuccess, window_connect, &Connect::slotFollowBet); + connect(m_bet_thread,&BetThread::signal_bet_oder,window_connect, &Connect::slotFollowBet); + connect(m_bet_thread, &BetThread::log, this, &CrownClient::log); + + emit log("日志","程序启动成功"); + +} + +CrownClient::~CrownClient() +{ + if (m_paramerTimer->isActive()) + { + m_paramerTimer->stop(); + } +} + +void CrownClient::closeEvent(QCloseEvent * event) +{ + + // 检查是否是自发事件(用户点击关闭按钮) + if (event->spontaneous()) { + // 用户点击窗口关闭按钮,最小化到托盘 + if (trayIcon->isVisible()) { + hide(); // 隐藏窗口 + event->ignore(); // 忽略关闭事件 + return; + } + } + // 在关闭窗口前确保所有网络请求被取消 + QWebEnginePage* page = ui.webEngineView->page(); + page->load(QUrl("")); + // 安全删除QWebEngineView和QWebEnginePage + //ui.webEngineView->deleteLater(); + page->deleteLater(); + + + // 保存配置 -> 过滤注单时间开关 + g_config->setScreenDateTimeEnable(ui.screenDateTimeCheckBox->isChecked()); + // 保存配置 -> 过滤注单时间 + g_config->setScreenDateTime(ui.dateTimeEdit->dateTime().toString()); + + g_config->set_client_url_list(ui.urlCombo->items()); + g_config->set_client_url(ui.urlCombo->currentText()); + g_config->setUsername(ui.usernameEdit->text()); + g_config->setPassword(ui.passwordEdit->text()); + if (m_heartbeatTimer->isActive()) + { + m_heartbeatTimer->stop(); + } + + + +} + + +/// +/// 平台账户掉线重连 +/// +void CrownClient::on_disconnected() +{ + // 判断当前正在工作状态 + if (m_state == work) + { + // 立即更新为重新登录状态 + m_state = relogin; + // 推送掉线消息 + push_disconnected(); + // 退出线程 + m_bet_thread->exit(); + // 清空参数 + m_paramers.clear(); + + m_start_time = QDateTime::currentDateTime().toMSecsSinceEpoch(); + emit log("掉线重连", "平台账户掉线重连"); + QTimer::singleShot(10 * 1000, [&]() { + + + // 访问网址 + ui.webEngineView->page()->load(QUrl("")); + ui.webEngineView->page()->load(ui.urlCombo->currentText()); + if (!m_paramerTimer->isActive()) + { + m_paramerTimer->start(3000); + } + + }); + + } + +} + +/// +/// 开始工作 +/// +void CrownClient::slotStart() +{ + // 保存配置 -> 过滤注单时间开关 + g_config->setScreenDateTimeEnable(ui.screenDateTimeCheckBox->isChecked()); + // 保存配置 -> 过滤注单时间 + g_config->setScreenDateTime(ui.dateTimeEdit->dateTime().toString()); + + // 更新网址 + m_paramers["url"] = ui.urlCombo->currentText(); + // qDebug() << "网址:" << m_paramers["url"]; + // 禁用连接按钮 + ui.connectButton->setDisabled(true); + // 禁用设置按钮 + ui.settingButton->setDisabled(true); + // 禁用开始按钮 + ui.startButton->setDisabled(true); + // 启用停止按钮 + ui.stopButton->setDisabled(false); + ui.screenDateTimeCheckBox->setDisabled(true); + ui.urlCombo->setDisabled(true); + ui.usernameEdit->setDisabled(true); + ui.passwordEdit->setDisabled(true); + + + m_start_time = QDateTime::currentDateTime().toMSecsSinceEpoch(); + + // 连接网页加载完成事件 + connect(ui.webEngineView->page(), &QWebEnginePage::loadFinished, this, &CrownClient::slotLoadFinished); + // 访问网址 + ui.webEngineView->page()->load(ui.urlCombo->currentText()); + if (!m_paramerTimer->isActive()) + { + m_paramerTimer->start(3000); + } + + + //if (!m_work_timer->isActive()) + //{ + // m_work_timer->start(1000); + //} + + emit signalStart(); +} + +void CrownClient::slotStop() +{ + ui.webEngineView->page()->load(QUrl("")); + // 启用连接按钮 + ui.connectButton->setDisabled(false); + // 启用设置按钮 + ui.settingButton->setDisabled(false); + // 禁用开始按钮 + ui.startButton->setDisabled(false); + // 启用停止按钮 + ui.stopButton->setDisabled(true); + + + ui.screenDateTimeCheckBox->setDisabled(false); + ui.urlCombo->setDisabled(false); + ui.usernameEdit->setDisabled(false); + ui.passwordEdit->setDisabled(false); + // 取消连接网页加载完成事件 + disconnect(ui.webEngineView->page(), &QWebEnginePage::loadFinished, this, &CrownClient::slotLoadFinished); + if (m_paramerTimer->isActive()) + { + m_paramerTimer->stop(); + } + + m_bet_thread->exit(); + //if (m_work_timer->isActive()) + //{ + // m_work_timer->stop(); + //} + m_state = wait; + m_paramers.clear(); + // 等到登录成功再切换 + ui.stateButton->setIcon(QIcon(":/images/Images/stop.png")); + emit signalStop(); +} + +/// +/// 网页加载完成事件 +/// +/// 是否加载完成 +void CrownClient::slotLoadFinished(bool isok) +{ + if (isok) + { + // this->slotLogin(); + } + +} + + + +/// +/// 槽函数 -> 登录 +/// +void CrownClient::slotLogin() +{ + // 延迟 500 毫秒防止未加载完成 + QTimer::singleShot(1500, [&]() { + + QString username = ui.usernameEdit->text().trimmed(); + QString password = ui.passwordEdit->text().trimmed(); + + QString jsCode = QString(R"( + (function() { + try { + function fireKeyEvent(element, evtType, keyChar) { + if (!element) return; + element.focus(); + var KeyboardEventInit = {key:keyChar, code:'', location:0, repeat:false, isComposing:false}; + var evtObj = new KeyboardEvent(evtType, KeyboardEventInit); + element.dispatchEvent(evtObj); + } + + function virtualText(el, str) { + if (!el) return; + for(var i = 0; i < str.length; i++){ + var cCode = str.charCodeAt(i); + fireKeyEvent(el,'keydown',cCode); + fireKeyEvent(el,'keypress',cCode); + fireKeyEvent(el,'keyup',cCode); + } + } + + // 检查元素是否存在 + var userObj = document.getElementById('usr'); + var pwdObj = document.getElementById('pwd'); + var loginBtn = document.getElementById('btn_login'); + + if (!userObj || !pwdObj || !loginBtn) { + console.log('登录元素未找到,等待重试'); + // 如果元素不存在,延迟200ms重试 + setTimeout(arguments.callee, 200); + return; + } + + userObj.click(); + var input_user = '%1'; + var input_user_event = new InputEvent('input', {bubbles: false, cancelable: false}); + userObj.value = input_user; + userObj.dispatchEvent(input_user_event); + virtualText(userObj, input_user); + + var input_pwd = '%2'; + var input_pwd_event = new InputEvent('input', {bubbles: false, cancelable: false}); + pwdObj.value = input_pwd; + pwdObj.dispatchEvent(input_pwd_event); + virtualText(pwdObj, input_pwd); + + // 添加一点延迟再点击登录按钮 + setTimeout(function() { + loginBtn.click(); + console.log('登录按钮已点击'); + }, 200); + + } catch(e) { + console.log('登录过程出错:', e.message); + } + })(); + )").arg(username).arg(password); + + ui.webEngineView->page()->runJavaScript(jsCode); + }); + +} + +///// +///// 槽函数 -> 登录 +///// +//void CrownClient::slotLogin() +//{ +// // 延迟 500 毫秒防止未加载完成 +// QTimer::singleShot(1500, [=]() { +// +// QString username = ui.usernameEdit->text().trimmed(); +// QString password = ui.passwordEdit->text().trimmed(); +// +// QString jsCode = QString(R"( +// function fireKeyEvent(element, evtType, keyChar) { +// element.focus(); +// var KeyboardEventInit = {key:keyChar, code:'', location:0, repeat:false, isComposing:false}; +// var evtObj = new KeyboardEvent(evtType, KeyboardEventInit); +// element.dispatchEvent(evtObj); +// } +// +// function virtualText(el,str){ +// for(var i = 0; ipage()->runJavaScript(jsCode); +// }); +// +//} +// + +void CrownClient::slotUpdateParamer() +{ + qint64 current_time = QDateTime::currentDateTime().toMSecsSinceEpoch(); + if (current_time - m_start_time > 30 * 1000) + { + // 清空参数 + m_state = wait; + m_paramers.clear(); + m_start_time = QDateTime::currentDateTime().toMSecsSinceEpoch(); + // 重新载入页面 + ui.webEngineView->page()->load(ui.urlCombo->currentText()); + + qDebug() << "登录超时重载"; + return; + + } + + // qDebug() << QString("定时器检测参数(%1)(%2):").arg(QDateTime::currentDateTime().toString()).arg(m_state) << m_paramers; + ui.webEngineView->page()->runJavaScript("if (document.getElementById('btn_login') && document.getElementById('usr') && document.getElementById('pwd')) 'ok';", [&](const QVariant& v) { + if (m_state == wait || m_state == relogin) + { + // 确保刚加载 设置为准备就绪状态 + if (m_paramers["btn_login"].isEmpty()) + { + m_paramers["btn_login"] = v.toString(); + if (!v.toString().isEmpty()) + { + m_state = readyLogin; + slotLogin(); + } + + } + + } + }); + + ui.webEngineView->page()->runJavaScript("if (document.getElementById('text_error')) document.getElementById('text_error').textContent;", [&](const QVariant& v) { + // qDebug() << "获取参数[text_error]: " << v.toString(); + m_paramers["text_error"] = v.toString(); + if (!v.toString().isEmpty() && m_state == readyLogin) + { + // qDebug() << "登录失败"; + m_paramers.clear(); + m_state = relogin; + // 重新执行登录 + slotLogin(); + } + + }); + + ui.webEngineView->page()->runJavaScript("if (langx) langx;", [&](const QVariant& v) { + // qDebug() << "获取参数[langx]: " << v.toString(); + m_paramers["langx"] = v.toString(); + }); + + ui.webEngineView->page()->runJavaScript("if (ver) ver;", [&](const QVariant& v) { + // qDebug() << "获取参数[ver]: " << v.toString(); + m_paramers["ver"] = v.toString(); + }); + + ui.webEngineView->page()->runJavaScript("if(document.URL) document.URL;", [=](const QVariant& v) { + // qDebug() << "获取参数[url]: " << v.toString(); + m_paramers["url"] = v.toString(); + }); + + // 更新cookie + ui.webEngineView->page()->runJavaScript("function GetCookie(){return document.cookie} GetCookie();", [=](const QVariant& v) { + m_paramers["cookies"] = v.toString(); + }); + + + ui.webEngineView->page()->runJavaScript("if (top.param) top.param;", [this](const QVariant& v) { + // qDebug() << "获取参数[param]: " << v.toString(); + if (!v.toString().isEmpty() && this->m_paramers["text_error"].isEmpty() && !this->m_paramers["ver"].isEmpty() && m_state != work) + { + push_reconnected(); + //if (m_state == relogin) + //{ + // push_reconnected(); + //} + m_state = work; + // 设置绿色信号灯 + slotChangeState(2); + + // 等到登录成功再切换 + ui.stateButton->setIcon(QIcon(":/images/Images/start.png")); + // qDebug() << "登录成功"; + if (this->m_paramers["url"] == "") + { + this->m_paramers["url"] = ui.urlCombo->currentText(); + } + //this->m_paramers["url"] = ui.urlCombo->currentText(); + this->m_paramers["param"] = v.toString(); + m_bet_thread->setParam(m_paramers["url"], m_paramers["ver"], m_paramers["param"], m_paramers["cookies"]); + m_bet_thread->start(); + + m_paramerTimer->stop(); + } + + + + }); + + + // alert_kick 踢人画面 + + //ui.webEngineView->findText("重新登入", QWebEnginePage::FindCaseSensitively, [&](bool result) { + // if (result) + // { + // qDebug() << "掉线"; + // } + //}); + + //ui.webEngineView->page()->runJavaScript("if (document.getElementById('#popup_title')) 'ok';", [&](const QVariant& v) { + // qDebug() << "获取参数[掉线]: " << v.toString(); + // if (!v.toString().isEmpty() && m_state == work) + // { + // qDebug() << "登录失败"; + // m_paramers.clear(); + // m_state = relogin; + // // 重新执行登录 + // slotLogin(); + // } + + //}); + // popup_content + if (m_state == work) + { + m_paramerTimer->stop(); + slotUpdateLeague(); + } +} + +void CrownClient::slotUpdateLeague() +{ + QNetworkAccessManager networkManager; + // 网络请求 + QNetworkRequest request; + request.setUrl(QUrl(QString(m_paramers["url"] + "transform.php?ver=" + m_paramers["ver"]))); + request.setRawHeader("Accept", "*/*"); + request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); + request.setRawHeader("Origin", m_paramers["url"].toUtf8()); + request.setRawHeader("Referer", m_paramers["url"].toUtf8()); + + // 获取当前时间戳 + QString timeStamp = QString::number(QDateTime::currentDateTime().addSecs(-43200).toTime_t()); + QString data = "p=get_list_tv&" + m_paramers["param"] + ">ype=ALL&date=ALL&device=phone&ts=" + timeStamp; + + + QNetworkReply* reply = networkManager.post(request, data.toUtf8()); + // 忽略SSL证书错误 + reply->ignoreSslErrors(); + // 事件循环 + QEventLoop eventLoop; + // 连接信号和槽 + connect(&networkManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit())); + // 开始循环 + eventLoop.exec(); + + // 错误处理 + if (reply->error() != QNetworkReply::NoError) + { + QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); + qDebug("服务器响应错误代码: %d Qt错误代码:%d\n", statusCode.toInt(), (int)reply->error()); + qDebug(qPrintable(reply->errorString())); + reply->deleteLater(); + return; + } + QByteArray result = reply->readAll(); + reply->deleteLater(); + QXmlStreamReader reader(result); + QList> list; + QMap game; + bool start = false; + while (!reader.atEnd()) + { + reader.readNext(); + + if (reader.name() == "game" && reader.isStartElement()) + { + start = true; + + } + if (start && reader.name() != "game") + { + QString name = reader.name().toString(); + game[name] = reader.readElementText(); + + } + if (reader.name() == "game" && reader.isEndElement()) + { + start = false; + list.append(game); + } + } + emit signalUpdateLeagueAndTeam(list); + +} + + + + + +void CrownClient::slotChangeState(int state) +{ + if (state == 0) + { + ui.stateButton_connect->setIcon(QIcon(":/images/Images/red.png")); + ui.stateButton_connect->setText("连接断开"); + QPalette palette; + palette.setColor(QPalette::ButtonText, QColor(Qt::red)); + ui.stateButton_connect->setPalette(palette); + } + else if (state == 1) + { + ui.stateButton_connect->setIcon(QIcon(":/images/Images/yellow.png")); + ui.stateButton_connect->setText("等待连接"); + QPalette palette; + palette.setColor(QPalette::ButtonText, QColor(0xFF8C00)); + ui.stateButton_connect->setPalette(palette); + } + else if (state == 2) + { + ui.stateButton_connect->setIcon(QIcon(":/images/Images/green.png")); + ui.stateButton_connect->setText("连接成功"); + QPalette palette; + palette.setColor(QPalette::ButtonText, QColor(0x008000)); + ui.stateButton_connect->setPalette(palette); + } +} + + + +/* + 接收注单 + list:注单信息 +*/ +void CrownClient::slotAcceptOrders(QList> list) +{ + // 播放接收注单声音 + if (g_config->acceptOrderSoundEnable()) + { + if (!g_config->acceptOrderSoundPath().isEmpty()) + { + QSound::play(g_config->acceptOrderSoundPath()); + } + else + { + QSound::play(":/sound/sound/accept.wav"); + } + } + + emit log("程序运行",QString("接收到 %1 条注单").arg(list.count())); + for (int i = 0; i < list.count(); i++) + { + QMap order = list[i]; + + // 提前处理数据格式 + // 接收时间(按当前配置取) + // 存储皇冠时间 + order["ACCEPT_DATETIME"] = QDateTime::currentDateTime().addSecs(-43200).toString("yyyy-MM-dd hh:mm:ss"); + // 接收注单入库 + g_config->add_accept_order(order); + // 添加接收注单视图 + + view_add_accept_order(order); + push_accept(order); + // 开始筛选注单 + } + + // 滚动到最后一行 + //ui.orderTableWidget->scrollToBottom(); +} + + + +/* + 设置账户信息 +*/ +void CrownClient::slotSetUser(QString username, QString password) +{ + if (ui.startButton->isEnabled()) + { + ui.usernameEdit->setText(username); + ui.passwordEdit->setText(password); + //ui.levelCombo->setCurrentText(level); + //ui.safeCodeEdit->setText(safeCode); + } +} + +/* + 更新读取次数 +*/ +void CrownClient::slotUpdateReadOrdersTimes() +{ + m_readOrderTimes++; + ui.readOrderTimes->setText("

读取次数: " + QString::number(m_readOrderTimes) + " 接收注单: " + QString::number(m_readOrderCount) + " 跟单成功: " + QString::number(m_successOrderCount) + " 过滤注单: " + QString::number(m_screenOrderCount)+ "

"); +} + +/* + 更新读取数量 +*/ +void CrownClient::slotUpdateReadOrdersCount(int count) +{ + m_readOrderCount += count; + ui.readOrderTimes->setText("

读取次数: " + QString::number(m_readOrderTimes) + " 接收注单: " + QString::number(m_readOrderCount) + " 跟单成功: " + QString::number(m_successOrderCount) + " 过滤注单: " + QString::number(m_screenOrderCount) + "

"); +} + + + +void CrownClient::on_log(QString type, QString log) +{ + // 1. 获取并调整当前时间(根据crownTime配置) + const bool useCrownTime = g_config->crownTime(); + const QDateTime currentTime = QDateTime::currentDateTime(); + const QDateTime displayTime = useCrownTime ? currentTime.addSecs(-43200) : currentTime; + + // 2. 格式化日期时间字符串 + const QString datetimeStr = displayTime.toString("yyyy-MM-dd hh:mm:ss"); + const QString dateStr = displayTime.toString("yyyy-MM-dd"); + + // 3. 创建日志条目项 + QList logItems = { + new QStandardItem(datetimeStr), + new QStandardItem(type), + new QStandardItem(log) + }; + logItems.first()->setData(-1, Qt::UserRole + 1); // 标记为子节点 + + // 4. 根据当前分组模式处理 + if (m_logGroupType == NO_GROUP) { + // 无分组模式,直接添加 + m_logModel->appendRow(logItems); + } + else { + // 查找或创建分组节点 + QString groupKey; + if (m_logGroupType == BY_TIME) { + groupKey = dateStr; + } + else if (m_logGroupType == BY_LOG_TYPE) { + groupKey = type; + } + + QStandardItem* groupItem = nullptr; + for (int i = 0; i < m_logModel->rowCount(); ++i) { + if (m_logModel->item(i)->text() == groupKey) { + groupItem = m_logModel->item(i); + break; + } + } + + if (groupItem) { + groupItem->appendRow(logItems); + } + else { + groupItem = new QStandardItem(groupKey); + groupItem->setData(1, Qt::UserRole + 1); // 标记为分组节点 + groupItem->setIcon(QIcon(":/icons/date.png")); + groupItem->appendRow(logItems); + m_logModel->appendRow(groupItem); + } + } + + // 自动滚动到底部 + ui.log_tree_view->scrollToBottom(); +} + +void CrownClient::view_add_accept_order(QMap order) +{ + QStandardItemModel *model = qobject_cast(ui.order_tree_view->model()); + if (!model) return; + + // 处理下注时间(皇冠时间提前12小时) + QString bet_dateTime = order["DATETIME"]; + if (!g_config->crownTime()) { + QDateTime finalDate1 = QDateTime::fromString(bet_dateTime, "yyyy-MM-dd HH:mm:ss"); + bet_dateTime = finalDate1.addSecs(43200).toString("yyyy-MM-dd HH:mm:ss"); + } + + // 提取日期用于分组 + QString dateStr = QDateTime::fromString(bet_dateTime, "yyyy-MM-dd HH:mm:ss") + .toString("yyyy-MM-dd"); + + // 创建行数据项 + QList rowItems; + + // Column 0: 单号/场次 + QStandardItem* item_tid = new QStandardItem(order["TID"]); + item_tid->setTextAlignment(Qt::AlignCenter); + item_tid->setData(-1, Qt::UserRole + 1); // 标记为子节点 + rowItems.append(item_tid); + + // Column 1: 下注时间 + QStandardItem* item_betDateTime = new QStandardItem(bet_dateTime); + item_betDateTime->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_betDateTime); + + // Column 2: 接收时间 + QString accept_dateTime = order["ACCEPT_DATETIME"]; + if (!g_config->crownTime()) { + QDateTime finalDate1 = QDateTime::fromString(accept_dateTime, "yyyy-MM-dd HH:mm:ss"); + accept_dateTime = finalDate1.addSecs(43200).toString("yyyy-MM-dd HH:mm:ss"); + } + QStandardItem* item_acceptTime = new QStandardItem(accept_dateTime); + item_acceptTime->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_acceptTime); + + // Column 3: 会员/代理 + QStandardItem* item_username = new QStandardItem(order["NAME0"]); + item_username->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_username); + + // Column 4: 项目 + QStandardItem* item_projectName = new QStandardItem(order["GT"] + order["SESSION"] + order["STAGE"]); + item_projectName->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_projectName); + + // Column 5: 类型 + + QStandardItem* item_type = new QStandardItem(Utils::get_market(order["WAGERS_TYPE"]) + Utils::format_wagers_type(order)); + item_type->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_type); + + // Column 6: 联赛/队伍 + QString league; + if (order["SCORE"] != "") + { + league = order["LEAGUE"] + "\n" + order["TEAM_H"] + " " + order["SCORE"] + " " + order["TEAM_C"]; + } + else + { + league = order["LEAGUE"] + "\n" + order["TEAM_H"] + " vs " + order["TEAM_C"]; + } + + QStandardItem* item_league = new QStandardItem(league); + item_league->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_league); + + // Column 7: 下注 + QStandardItem* item_team_bet = new QStandardItem(order["ORDER_TYPE"]); + item_team_bet->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_team_bet); + + // Column 8: 盘口 + QStandardItem* item_handicap = new QStandardItem(order["ORDER_CON"]); + item_handicap->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_handicap); + + // Column 9: 赔率 + QStandardItem* item_odds = new QStandardItem(order["IORATIO"]); + item_odds->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_odds); + + // Column 10: 金额 + QStandardItem* item_gold = new QStandardItem(Utils::instance().formatGold(order["GOLD"])); + item_gold->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_gold); + + // 根据当前分组模式处理 + if (m_orderGroupType == NO_GROUP) { + // 无分组模式,直接添加 + model->appendRow(rowItems); + } + else { + // 获取干净的分组键(移除可能存在的计数) + QString rawGroupKey; + if (m_orderGroupType == BY_TIME) { + rawGroupKey = dateStr; + } + else if (m_orderGroupType == BY_ORDER_ID) { + rawGroupKey = order["TID"]; // 取订单号前8位作为分组 + } + QString cleanGroupKey = rawGroupKey.split(" (").first().trimmed(); + + // 查找或创建分组节点(比较时也清理计数) + QStandardItem* groupItem = nullptr; + for (int i = 0; i < model->rowCount(); ++i) { + QString itemText = model->item(i)->text(); + if (itemText.split(" (").first().trimmed() == cleanGroupKey) { + groupItem = model->item(i); + break; + } + } + + if (groupItem) { + // 添加到现有分组 + groupItem->appendRow(rowItems); + // 统一更新分组标题格式为"键 (计数)" + groupItem->setText(QString("%1 (%2)").arg(cleanGroupKey).arg(groupItem->rowCount())); + } + else { + // 创建新分组(直接使用带计数的格式) + groupItem = new QStandardItem(QString("%1 (1)").arg(cleanGroupKey)); + groupItem->setData(1, Qt::UserRole + 1); // 标记为分组节点 + groupItem->setSelectable(false); + groupItem->setEditable(false); + groupItem->setIcon(QIcon(":/icons/date.png")); + groupItem->appendRow(rowItems); + model->appendRow(groupItem); + } + } + + // 自动滚动到底部 + ui.order_tree_view->scrollToBottom(); +} + +// 其他 view_add_* 函数也按照类似的模式修改,这里以 view_add_screen_order 为例 +void CrownClient::view_add_screen_order(QMap order) +{ + m_screenOrderCount++; + view_flush_counter(); + QStandardItemModel *model = qobject_cast(ui.screen_tree_view->model()); + if (!model) return; + + // 处理下注时间 + QString betTime = order["DATETIME"]; + if (!g_config->crownTime()) { + QDateTime finalDate = QDateTime::fromString(betTime, "yyyy-MM-dd HH:mm:ss"); + betTime = finalDate.addSecs(43200).toString("yyyy-MM-dd HH:mm:ss"); + } + + QString dateStr = QDateTime::fromString(betTime, "yyyy-MM-dd HH:mm:ss") + .toString("yyyy-MM-dd"); + + // 创建行数据项 + QList rowItems; + + // Column 0: 单号/场次 + QStandardItem* item_tid = new QStandardItem(order["TID"]); + item_tid->setTextAlignment(Qt::AlignCenter); + item_tid->setData(-1, Qt::UserRole + 1); + rowItems.append(item_tid); + + // Column 1: 下注时间 + QStandardItem* item_betTime = new QStandardItem(betTime); + item_betTime->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_betTime); + + // Column 2: 会员/代理 + QStandardItem* item_username = new QStandardItem(order["NAME0"]); + item_username->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_username); + + // Column 3: 项目 + QStandardItem* item_project = new QStandardItem(order["GT"] + order["SESSION"] + order["STAGE"]); + item_project->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_project); + + // Column 4: 类型 + QStandardItem* item_type = new QStandardItem(Utils::get_market(order["WAGERS_TYPE"]) + Utils::format_wagers_type(order)); + item_type->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_type); + + // Column 5: 联赛/队伍 + QString league; + if (order["SCORE"] != "") + { + league = order["LEAGUE"] + "\n" + order["TEAM_H"] + " " + order["SCORE"] + " " + order["TEAM_C"]; + } + else + { + league = order["LEAGUE"] + "\n" + order["TEAM_H"] + " vs " + order["TEAM_C"]; + } + + QStandardItem* item_league = new QStandardItem(league); + + //QStandardItem* item_league = new QStandardItem( + // order["LEAGUE"] + "\n" + order["TEAM_H"] + " vs " + order["TEAM_C"]); + item_league->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_league); + + // Column 6: 下注 + QStandardItem* item_teamBet = new QStandardItem(order["ORDER_TYPE"]); + item_teamBet->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_teamBet); + + // Column 7: 盘口 + QString handicap; + if (order["ORDER_CON_NEW"].isEmpty()) + { + if (order["ORDER_CON"] != "") + { + handicap = "(原)" + order["ORDER_CON"]; + } + } + else + { + handicap = "(原)" + order["ORDER_CON"] + "\n" + "(现)" + order["ORDER_CON_NEW"]; + } + QStandardItem* item_handicap = new QStandardItem(handicap); + item_handicap->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_handicap); + + // Column 8: 赔率 + // 筛选显示原始赔率/最新赔率 + // 补单显示原始赔率/最新赔率 + QString odds; + if (order["IORATIO_NEW"].isEmpty()) + { + odds = "(原)" + order["IORATIO"]; + } + else + { + odds = "(原)" + order["IORATIO"] + "\n" + "(现)" + order["IORATIO_NEW"]; + } + QStandardItem* item_odds = new QStandardItem(odds); + item_odds->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_odds); + + // Column 9: 金额 + QStandardItem* item_gold = new QStandardItem(order["GOLD"]); + item_gold->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_gold); + + // Column 10: 原因 + QStandardItem* item_reason = new QStandardItem(order["REASON"]); + item_reason->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_reason); + + // 根据当前分组模式处理 + if (m_screenGroupType == NO_GROUP) { + // 无分组模式,直接添加 + model->appendRow(rowItems); + } + else { + // 获取干净的分组键(移除可能存在的计数) + QString rawGroupKey; + if (m_screenGroupType == BY_TIME) { + rawGroupKey = dateStr; + } + else if (m_screenGroupType == BY_ORDER_ID) { + rawGroupKey = order["TID"]; // 使用完整订单号作为分组键 + } + QString cleanGroupKey = rawGroupKey.split(" (").first().trimmed(); + + // 查找或创建分组节点(比较时也清理计数) + QStandardItem* groupItem = nullptr; + for (int i = 0; i < model->rowCount(); ++i) { + QString itemText = model->item(i)->text(); + if (itemText.split(" (").first().trimmed() == cleanGroupKey) { + groupItem = model->item(i); + break; + } + } + + if (groupItem) { + // 添加到现有分组 + groupItem->appendRow(rowItems); + // 统一更新分组标题格式为"键 (计数)" + groupItem->setText(QString("%1 (%2)").arg(cleanGroupKey).arg(groupItem->rowCount())); + } + else { + // 创建新分组(直接使用带计数的格式) + groupItem = new QStandardItem(QString("%1 (1)").arg(cleanGroupKey)); + groupItem->setData(1, Qt::UserRole + 1); // 标记为分组节点 + groupItem->setSelectable(false); + groupItem->setEditable(false); + groupItem->setIcon(QIcon(":/icons/date.png")); + groupItem->appendRow(rowItems); + model->appendRow(groupItem); + } + } + + // 自动滚动到底部 + ui.screen_tree_view->scrollToBottom(); +} + +void CrownClient::view_add_success_order(QMap order) +{ + QStandardItemModel *model = qobject_cast(ui.success_tree_view->model()); + if (!model) return; + + // 跟单时间(本地当前时间,用于列表显示与分组) + //QString followTime = g_config->formatDateTime(QDateTime::currentDateTime()) + // .toString("yyyy-MM-dd HH:mm:ss"); + QString followTime = order["DATETIME"]; + if (!g_config->crownTime()) { + QDateTime finalDate = QDateTime::fromString(followTime, "yyyy-MM-dd HH:mm:ss"); + followTime = finalDate.addSecs(43200).toString("yyyy-MM-dd HH:mm:ss"); + } + QString dateStr = QDateTime::fromString(followTime, "yyyy-MM-dd HH:mm:ss") + .toString("yyyy-MM-dd"); + + // 清洗队名 + auto cleanTeam = [](QString s)->QString { + s.replace(QRegularExpression("", QRegularExpression::CaseInsensitiveOption), ""); + s.remove(' '); + return s.trimmed(); + }; + QString teamH = cleanTeam(order["TEAM_H"]); + QString teamC = cleanTeam(order["TEAM_C"]); + + // 盘口:原/新 + QString handicap; + if (order["ORDER_CON_NEW"].isEmpty()) + { + if (order["ORDER_CON"] != "") + { + handicap = "(原)" + order["ORDER_CON"]; + } + } + else + { + handicap = "(原)" + order["ORDER_CON"] + "\n" + "(现)" + order["ORDER_CON_NEW"]; + } + + // 赔率:原/新 + QString odds; + if (order["IORATIO_NEW"].isEmpty()) + { + odds = "(原)" + order["IORATIO"]; + } + else + { + odds = "(原)" + order["IORATIO"] + "\n" + "(现)" + order["IORATIO_NEW"]; + } + + // 创建行 + QList rowItems; + + // 0: 单号 + QStandardItem* item_tid = new QStandardItem(order["TID"]); + item_tid->setTextAlignment(Qt::AlignCenter); + item_tid->setData(-1, Qt::UserRole + 1); + rowItems.append(item_tid); + + // 1: 跟单时间 + QStandardItem* item_followTime = new QStandardItem(followTime); + item_followTime->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_followTime); + + // 2: 会员/代理 + QStandardItem* item_username = new QStandardItem(order["NAME0"]); + item_username->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_username); + + // 3: 项目(球种+会话+场次) + QStandardItem* item_project = new QStandardItem(order["GT"] + order["SESSION"] + order["STAGE"]); + item_project->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_project); + + // 4: 类型(统一用文案格式化) + QStandardItem* item_type = new QStandardItem(Utils::get_market(order["WAGERS_TYPE"]) + Utils::format_wagers_type(order)); + item_type->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_type); + + // 5: 联赛/队伍 + QString score; + if (order["SCORE_NEW"] != "") + { + score = order["LEAGUE"] + "\n" + teamH + " "+order["SCORE_NEW"]+" " + teamC ; + } + else + { + score = order["LEAGUE"] + "\n" + teamH + " vs " + teamC; + } + + QStandardItem* item_league = new QStandardItem(score); + item_league->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_league); + + // 6: 下注 + QStandardItem* item_teamBet = new QStandardItem(order["ORDER_TYPE"]); + item_teamBet->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_teamBet); + + // 7: 盘口 + QStandardItem* item_handicap = new QStandardItem(handicap); + item_handicap->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_handicap); + + // 8: 赔率 + QStandardItem* item_odds = new QStandardItem(odds); + item_odds->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_odds); + + // 9: 金额 + QStandardItem* item_gold = new QStandardItem(Utils::instance().formatGold(order["GOLD"])); + item_gold->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_gold); + + // 分组 + if (m_successGroupType == NO_GROUP) { + model->appendRow(rowItems); + } + else { + QString rawGroupKey; + if (m_successGroupType == BY_TIME) { + rawGroupKey = dateStr; + } + else if (m_successGroupType == BY_ORDER_ID) { + rawGroupKey = order["TID"].left(8); + } + QString cleanGroupKey = rawGroupKey.split(" (").first().trimmed(); + + QStandardItem* groupItem = nullptr; + for (int i = 0; i < model->rowCount(); ++i) { + QString txt = model->item(i)->text(); + if (txt.split(" (").first().trimmed() == cleanGroupKey) { + groupItem = model->item(i); + break; + } + } + + if (groupItem) { + groupItem->appendRow(rowItems); + groupItem->setText(QString("%1 (%2)").arg(cleanGroupKey).arg(groupItem->rowCount())); + } + else { + groupItem = new QStandardItem(QString("%1 (1)").arg(cleanGroupKey)); + groupItem->setData(1, Qt::UserRole + 1); + groupItem->setSelectable(false); + groupItem->setEditable(false); + groupItem->setIcon(QIcon(":/icons/success.png")); + groupItem->appendRow(rowItems); + model->appendRow(groupItem); + } + } + + // 计数与滚动 + m_successOrderCount++; + view_flush_counter(); + ui.success_tree_view->scrollToBottom(); +} + +void CrownClient::view_add_failed_order(QMap order) +{ + QStandardItemModel *model = qobject_cast(ui.failed_tree_view->model()); + if (!model) return; + + // 跟单时间 + QString followTime = order["DATETIME"]; + if (!g_config->crownTime()) { + QDateTime finalDate = QDateTime::fromString(followTime, "yyyy-MM-dd HH:mm:ss"); + followTime = finalDate.addSecs(43200).toString("yyyy-MM-dd HH:mm:ss"); + } + QString dateStr = QDateTime::fromString(followTime, "yyyy-MM-dd HH:mm:ss") + .toString("yyyy-MM-dd"); + + // 创建行数据项 + QList rowItems; + + // Column 0: 单号/场次 + QStandardItem* item_tid = new QStandardItem(order["TID"]); + item_tid->setTextAlignment(Qt::AlignCenter); + item_tid->setData(-1, Qt::UserRole + 1); // 标记为子节点 + rowItems.append(item_tid); + + // Column 1: 跟单时间 + QStandardItem* item_followTime = new QStandardItem(followTime); + item_followTime->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_followTime); + + // Column 2: 会员/代理 + QStandardItem* item_username = new QStandardItem(order["NAME0"]); + item_username->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_username); + + // Column 3: 项目 + QStandardItem* item_project = new QStandardItem(order["GT"] + order["SESSION"] + order["STAGE"]); + item_project->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_project); + + // Column 4: 类型 + QStandardItem* item_type = new QStandardItem(Utils::get_market(order["WAGERS_TYPE"]) + Utils::format_wagers_type(order)); + item_type->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_type); + + // Column 5: 联赛/队伍 + QString league; + if (order["SCORE"] != "") + { + league = order["LEAGUE"] + "\n" + order["TEAM_H"] + " " + order["SCORE"] + " " + order["TEAM_C"]; + } + else + { + league = order["LEAGUE"] + "\n" + order["TEAM_H"] + " vs " + order["TEAM_C"]; + } + + QStandardItem* item_league = new QStandardItem(league); + item_league->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_league); + + // Column 6: 下注 + QStandardItem* item_teamBet = new QStandardItem(order["ORDER_TYPE"]); + item_teamBet->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_teamBet); + + // Column 7: 盘口 + QString handicap; + if (order["ORDER_CON_NEW"].isEmpty()) + { + if (order["ORDER_CON"] != "") + { + handicap = "(原)" + order["ORDER_CON"]; + } + } + else + { + handicap = "(原)" + order["ORDER_CON"] + "\n" + "(现)" + order["ORDER_CON_NEW"]; + } + QStandardItem* item_handicap = new QStandardItem(handicap); + item_handicap->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_handicap); + + // Column 8: 赔率 + // 失败显示原始赔率/最新赔率 + // 补单显示原始赔率/最新赔率 + QString odds; + if (order["IORATIO_NEW"].isEmpty()) + { + odds = "(原)" + order["IORATIO"]; + } + else + { + odds = "(原)" + order["IORATIO"] + "\n" + "(现)" + order["IORATIO_NEW"]; + } + QStandardItem* item_odds = new QStandardItem(odds); + item_odds->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_odds); + + // Column 9: 金额 + QStandardItem* item_gold = new QStandardItem(Utils::instance().formatGold(order["GOLD"])); + item_gold->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_gold); + + // Column 10: 原因 + QStandardItem* item_reason = new QStandardItem(order["REASON"]); + item_reason->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_reason); + + + // 根据当前分组模式处理 + if (m_failedGroupType == NO_GROUP) { + // 无分组模式,直接添加 + model->appendRow(rowItems); + } + else { + // 获取干净的分组键(移除可能存在的计数) + QString rawGroupKey; + if (m_failedGroupType == BY_TIME) { + rawGroupKey = dateStr; + } + else if (m_failedGroupType == BY_ORDER_ID) { + rawGroupKey = order["TID"]; // 使用完整订单号作为分组键 + } + QString cleanGroupKey = rawGroupKey.split(" (").first().trimmed(); + + // 查找或创建分组节点(比较时也清理计数) + QStandardItem* groupItem = nullptr; + for (int i = 0; i < model->rowCount(); ++i) { + QString itemText = model->item(i)->text(); + if (itemText.split(" (").first().trimmed() == cleanGroupKey) { + groupItem = model->item(i); + break; + } + } + + if (groupItem) { + // 添加到现有分组 + groupItem->appendRow(rowItems); + // 统一更新分组标题格式为"键 (计数)" + groupItem->setText(QString("%1 (%2)").arg(cleanGroupKey).arg(groupItem->rowCount())); + } + else { + // 创建新分组(直接使用带计数的格式) + groupItem = new QStandardItem(QString("%1 (1)").arg(cleanGroupKey)); + groupItem->setData(1, Qt::UserRole + 1); // 标记为分组节点 + groupItem->setSelectable(false); + groupItem->setEditable(false); + groupItem->setIcon(QIcon(":/icons/failed.png")); + groupItem->appendRow(rowItems); + model->appendRow(groupItem); + } + } + + // 自动滚动到底部 + ui.failed_tree_view->scrollToBottom(); +} + +void CrownClient::view_alert_failed_order(QMap order) +{ + QStandardItemModel *model = qobject_cast(ui.failed_tree_view->model()); + if (!model) return; + + QString tid = order["TID"]; + + // 查找匹配的订单项(递归搜索所有层级) + QModelIndexList matches = model->match( + model->index(0, 0), + Qt::DisplayRole, + tid, + -1, + Qt::MatchExactly | Qt::MatchRecursive + ); + + if (matches.isEmpty()) { + // qDebug() << "未找到需要更新的失败订单:" << tid; + return; + } + + // 获取找到的第一行 + QModelIndex rowIndex = matches.first(); + QStandardItem* item = model->itemFromIndex(rowIndex); + if (!item) return; + + // 获取所在行和父项 + int row = rowIndex.row(); + QStandardItem* parentItem = item->parent(); + + // 更新原因列(第10列) + QStandardItem* reasonItem = nullptr; + if (parentItem) { + // 分组模式下的子项 + reasonItem = parentItem->child(row, 10); + } + else { + // 无分组模式 + reasonItem = model->item(row, 10); + } + + if (reasonItem) { + reasonItem->setText(order["REASON"]); + reasonItem->setTextAlignment(Qt::AlignCenter); + // qDebug() << "已更新失败订单原因:" << tid << order["REASON"]; + } +} + +void CrownClient::view_remove_failed_order(QMap order) +{ + QStandardItemModel *model = qobject_cast(ui.failed_tree_view->model()); + if (!model) return; + + QString tid = order["TID"]; + bool found = false; + + // 遍历所有项(包括分组) + for (int i = 0; i < model->rowCount(); ++i) { + QStandardItem* item = model->item(i); + + // 检查是否是分组项 + if (item->data(Qt::UserRole + 1).toInt() == 1) { + // 分组项,检查其子项 + for (int j = 0; j < item->rowCount(); ++j) { + QStandardItem* childItem = item->child(j, 0); + if (childItem && childItem->text() == tid) { + // 移除子项 + item->removeRow(j); + + // 更新分组标题计数 + QString cleanText = item->text().split(" (").first().trimmed(); + item->setText(QString("%1 (%2)").arg(cleanText).arg(item->rowCount())); + + // 如果分组为空则移除 + if (item->rowCount() == 0) { + model->removeRow(i); + } + + found = true; + break; + } + } + } + // 非分组项直接比较 + else if (item && item->text() == tid) { + model->removeRow(i); + found = true; + break; + } + + if (found) break; + } + + if (!found) { + // qDebug() << "未找到要移除的订单:" << tid; + } + else { + // qDebug() << "已移除失败订单:" << tid; + } +} + +void CrownClient::view_add_rebet_order(QMap order) +{ + QStandardItemModel *model = qobject_cast(ui.rebet_tree_view->model()); + if (!model) return; + + // 跟单时间 + QString followTime = order["DATETIME"]; + if (!g_config->crownTime()) { + QDateTime finalDate = QDateTime::fromString(followTime, "yyyy-MM-dd HH:mm:ss"); + followTime = finalDate.addSecs(43200).toString("yyyy-MM-dd HH:mm:ss"); + } + QString dateStr = QDateTime::fromString(followTime, "yyyy-MM-dd HH:mm:ss") + .toString("yyyy-MM-dd"); + + // 创建行数据项 + QList rowItems; + + // 提取纯净的订单号(移除可能存在的补单次数) + QString rawTid = order["TID"].split(" (").first().trimmed(); + + // Column 0: 单号/场次 + QStandardItem* item_tid = new QStandardItem(order["TID"]); + item_tid->setTextAlignment(Qt::AlignCenter); + item_tid->setData(-1, Qt::UserRole + 1); // 标记为子节点 + rowItems.append(item_tid); + + // Column 1: 跟单时间 + QStandardItem* item_followTime = new QStandardItem(followTime); + item_followTime->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_followTime); + + // Column 2: 会员/代理 + QStandardItem* item_username = new QStandardItem(order["NAME0"]); + item_username->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_username); + + // Column 3: 项目 + QStandardItem* item_project = new QStandardItem(order["GT"] + order["SESSION"] + order["STAGE"]); + item_project->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_project); + + // Column 4: 类型 + QStandardItem* item_type = new QStandardItem(Utils::get_market(order["WAGERS_TYPE"]) + Utils::format_wagers_type(order)); + item_type->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_type); + + // Column 5: 联赛/队伍 + QString league; + if (order["SCORE"] != "") + { + league = order["LEAGUE"] + "\n" + order["TEAM_H"] + " " + order["SCORE"] + " " + order["TEAM_C"]; + } + else + { + league = order["LEAGUE"] + "\n" + order["TEAM_H"] + " vs " + order["TEAM_C"]; + } + + QStandardItem* item_league = new QStandardItem(league); + item_league->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_league); + + // Column 6: 下注 + QStandardItem* item_teamBet = new QStandardItem(order["ORDER_TYPE"]); + item_teamBet->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_teamBet); + + // Column 7: 盘口 + QString handicap; + if (order["ORDER_CON_NEW"].isEmpty()) + { + if (order["ORDER_CON"] != "") + { + handicap = "(原)" + order["ORDER_CON"]; + } + + } + else + { + handicap = "(原)" + order["ORDER_CON"] + "\n" + "(现)" + order["ORDER_CON_NEW"]; + } + QStandardItem* item_handicap = new QStandardItem(handicap); + item_handicap->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_handicap); + + // Column 8: 赔率 + // 补单显示原始赔率/最新赔率 + QString odds; + if (order["IORATIO_NEW"].isEmpty()) + { + odds = "(原)" + order["IORATIO"]; + } + else + { + odds = "(原)" + order["IORATIO"] + "\n" + "(现)" + order["IORATIO_NEW"]; + } + QStandardItem* item_odds = new QStandardItem(odds); + item_odds->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_odds); + + // Column 9: 金额 + QStandardItem* item_gold = new QStandardItem(Utils::instance().formatGold(order["GOLD"])); + item_gold->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_gold); + + // Column 10: 原因 + QStandardItem* item_reason = new QStandardItem(order["REASON"]); + item_reason->setTextAlignment(Qt::AlignCenter); + rowItems.append(item_reason); + + // 根据当前分组模式处理 + if (m_rebetGroupType == NO_GROUP) { + // 无分组模式,直接添加 + model->appendRow(rowItems); + } + else { + // 获取干净的分组键(移除可能存在的计数) + QString rawGroupKey; + if (m_rebetGroupType == BY_TIME) { + rawGroupKey = dateStr; + } + else if (m_rebetGroupType == BY_ORDER_ID) { + rawGroupKey = rawTid; // 使用纯净的订单号作为分组键 + } + QString cleanGroupKey = rawGroupKey.split(" (").first().trimmed(); + + // 查找或创建分组节点(比较时也清理计数) + QStandardItem* groupItem = nullptr; + for (int i = 0; i < model->rowCount(); ++i) { + QString itemText = model->item(i)->text(); + if (itemText.split(" (").first().trimmed() == cleanGroupKey) { + groupItem = model->item(i); + break; + } + } + + if (groupItem) { + // 添加到现有分组 + groupItem->appendRow(rowItems); + // 统一更新分组标题格式为"键 (计数)" + groupItem->setText(QString("%1 (%2)").arg(cleanGroupKey).arg(groupItem->rowCount())); + } + else { + // 创建新分组(直接使用带计数的格式) + groupItem = new QStandardItem(QString("%1 (1)").arg(cleanGroupKey)); + groupItem->setData(1, Qt::UserRole + 1); // 标记为分组节点 + groupItem->setSelectable(false); + groupItem->setEditable(false); + groupItem->setIcon(QIcon(":/icons/rebet.png")); + groupItem->appendRow(rowItems); + model->appendRow(groupItem); + } + } + + // 自动滚动到底部 + ui.rebet_tree_view->scrollToBottom(); +} +void CrownClient::view_change_time(bool isCrownTime) +{ + // 1. 更新时间模式配置 + g_config->setCrownTime(isCrownTime); + + // 2. 计算时间偏移量(12小时 = 43200秒) + const int timeOffset = isCrownTime ? -43200 : 43200; + + // 3. 更新界面时间显示 + ui.dateTimeEdit->setDateTime(ui.dateTimeEdit->dateTime().addSecs(timeOffset)); + g_config->setScreenDateTime(ui.dateTimeEdit->dateTime().toString()); + + // 4. 更新按钮状态 + ui.crownTimeButton->setIcon(QIcon(isCrownTime + ? ":/images/Images/crownTime.png" + : ":/images/Images/localTime.png")); + ui.crownTimeButton->setText(isCrownTime ? "皇冠时间" : "本地时间"); + + QToolTip::showText(ui.crownTimeButton->mapToGlobal(ui.crownTimeButton->rect().bottomLeft()), + isCrownTime ? "当前设置为皇冠时间" : "当前设置为本地时间"); + + QPalette palette; + palette.setColor(QPalette::ButtonText, isCrownTime ? QColor(Qt::red) : QColor(QRgb(0x008000))); + ui.crownTimeButton->setPalette(palette); + + // 5. 处理所有视图 + const QVector allViews = { + ui.order_tree_view, + ui.screen_tree_view, + ui.success_tree_view, + ui.failed_tree_view, + ui.rebet_tree_view, + ui.log_tree_view + }; + + for (QTreeView* treeView : allViews) { + // 获取模型 + QAbstractItemModel* model = treeView->model(); + QStandardItemModel* standardModel = qobject_cast( + (treeView == ui.log_tree_view) ? + qobject_cast(model)->sourceModel() : + model + ); + if (!standardModel) continue; + + // 禁用视图刷新 + treeView->setUpdatesEnabled(false); + + // 确定需要调整的时间列索引集合 + QVector timeColumns; + if (treeView == ui.order_tree_view) { + // 下注时间(1列) + 接收时间(2列) + timeColumns = { 1, 2 }; + } + else if (treeView == ui.log_tree_view) { + // 日志视图时间在第0列 + timeColumns = { 0 }; + } + else { + // 其余视图时间统一在第1列 + timeColumns = { 1 }; + } + + // 处理所有行(包括分组行) + for (int row = 0; row < standardModel->rowCount(); ++row) { + QStandardItem* item = standardModel->item(row, 0); + if (!item) continue; + + // 处理分组标题时间(如"2025-06-16 (2)") + if (item->data(Qt::UserRole + 1).toInt() == 1 && item->text().contains(" (")) { + QStringList parts = item->text().split(" ("); + if (parts.size() >= 2) { + QString dateStr = parts[0].trimmed(); + QString countStr = parts[1].replace(")", "").trimmed(); + + QDate date = QDate::fromString(dateStr, "yyyy-MM-dd"); + if (date.isValid()) { + // 切换到皇冠时间 -> 日期减1天;切换到本地时间 -> 日期加1天 + date = isCrownTime ? date.addDays(-1) : date.addDays(1); + item->setText(QString("%1 (%2)") + .arg(date.toString("yyyy-MM-dd")) + .arg(countStr)); + } + } + } + + // 处理当前行的各时间列 + for (int timeColumn : timeColumns) { + QStandardItem* timeItem = standardModel->item(row, timeColumn); + if (timeItem && !timeItem->text().isEmpty()) { + QDateTime originalTime = QDateTime::fromString(timeItem->text(), "yyyy-MM-dd HH:mm:ss"); + if (originalTime.isValid()) { + timeItem->setText(originalTime.addSecs(timeOffset).toString("yyyy-MM-dd HH:mm:ss")); + } + } + } + + // 处理分组下的子项 + if (item->rowCount() > 0) { + for (int childRow = 0; childRow < item->rowCount(); ++childRow) { + for (int timeColumn : timeColumns) { + QStandardItem* childTimeItem = item->child(childRow, timeColumn); + if (childTimeItem && !childTimeItem->text().isEmpty()) { + QDateTime originalTime = QDateTime::fromString(childTimeItem->text(), "yyyy-MM-dd HH:mm:ss"); + if (originalTime.isValid()) { + childTimeItem->setText(originalTime.addSecs(timeOffset).toString("yyyy-MM-dd HH:mm:ss")); + } + } + } + } + } + } + + // 恢复视图刷新 + treeView->setUpdatesEnabled(true); + treeView->viewport()->update(); + + // 重新应用当前分组(确保分组标题更新) + if (treeView == ui.log_tree_view) { + groupLogTreeView(m_logGroupType); + } + } +} +// 添加更新计数器的函数 +void CrownClient::view_flush_counter() +{ + ui.readOrderTimes->setText(QString("

读取次数: %1" + " 接收注单: %2" + " 跟单成功: %3" + " 过滤注单: %4

") + .arg(m_readOrderTimes) + .arg(m_readOrderCount) + .arg(m_successOrderCount) + .arg(m_screenOrderCount)); +} + +void CrownClient::groupTreeView(QTreeView* treeView, GroupType groupType) +{ + if (treeView == ui.order_tree_view) { + m_orderGroupType = groupType; + } + else if (treeView == ui.screen_tree_view) { + m_screenGroupType = groupType; + } + else if (treeView == ui.success_tree_view) { + m_successGroupType = groupType; + } + else if (treeView == ui.failed_tree_view) { + m_failedGroupType = groupType; + } + else if (treeView == ui.rebet_tree_view) { + m_rebetGroupType = groupType; + } + + QStandardItemModel* model = qobject_cast(treeView->model()); + if (!model) return; + + // 1. 保存当前列宽 + QVector columnWidths; + for (int i = 0; i < model->columnCount(); ++i) { + columnWidths.append(treeView->columnWidth(i)); + } + + // 2. 保存当前数据 + QList> allData; + for (int row = 0; row < model->rowCount(); ++row) { + QStandardItem* item = model->item(row); + if (item->data(Qt::UserRole + 1).toInt() == 1) { + // 分组节点,遍历其子节点 + for (int childRow = 0; childRow < item->rowCount(); ++childRow) { + QMap rowData; + for (int col = 0; col < model->columnCount(); ++col) { + QStandardItem* childItem = item->child(childRow, col); + if (childItem) { + rowData[col] = childItem->text(); + } + } + allData.append(rowData); + } + } + else { + // 普通节点 + QMap rowData; + for (int col = 0; col < model->columnCount(); ++col) { + QStandardItem* childItem = model->item(row, col); + if (childItem) { + rowData[col] = childItem->text(); + } + } + allData.append(rowData); + } + } + + // 3. 清空模型并重新设置表头 + model->clear(); + if (treeView == ui.order_tree_view) { + model->setHorizontalHeaderLabels({ "单号/场次","下注时间","接收时间","会员/代理","项目","类型","联赛/队伍","下注","盘口","赔率","金额" }); + } + else if (treeView == ui.screen_tree_view) { + model->setHorizontalHeaderLabels({ "单号/场次","下注时间","会员/代理","项目","类型","联赛/队伍","下注","盘口","赔率","金额","原因" }); + } + else if (treeView == ui.success_tree_view) { + model->setHorizontalHeaderLabels({ "单号/场次","跟单时间","会员/代理","项目","类型","联赛/队伍","下注","盘口","赔率","金额" }); + } + else if (treeView == ui.failed_tree_view) { + model->setHorizontalHeaderLabels({ "单号/场次","跟单时间","会员/代理","项目","类型","联赛/队伍","下注","盘口","赔率","金额","原因" }); + } + else if (treeView == ui.rebet_tree_view) { + model->setHorizontalHeaderLabels({ "单号/场次","跟单时间","会员/代理","项目","类型","联赛/队伍","下注","盘口","赔率","金额","原因" }); + } + + // 4. 重新添加数据,按照新的分组方式 + if (groupType == NO_GROUP) { + // 无分组,直接添加所有行 + for (const auto& rowData : allData) { + QList rowItems; + for (int col = 0; col < model->columnCount(); ++col) { + QStandardItem* item = new QStandardItem(rowData[col]); + item->setTextAlignment(Qt::AlignCenter); + rowItems.append(item); + } + model->appendRow(rowItems); + } + } + else { + // 有分组,按分组键组织数据 + QMap>> groupedData; + + for (const auto& rowData : allData) { + QString groupKey; + if (groupType == BY_TIME) { + QString timeStr = rowData[1]; // 假设第1列是时间 + groupKey = timeStr.left(10); // 取日期部分 + } + else if (groupType == BY_ORDER_ID) { + groupKey = rowData[0].left(8); // 假设第0列是订单号,取前8位 + } + + // 清除可能存在的已有计数 + groupKey = groupKey.split(" (").first().trimmed(); + groupedData[groupKey].append(rowData); + } + + // 添加分组和子项 + for (auto it = groupedData.begin(); it != groupedData.end(); ++it) { + QString groupTitle = QString("%1 (%2)").arg(it.key()).arg(it.value().size()); + + QStandardItem* groupItem = new QStandardItem(groupTitle); + groupItem->setData(1, Qt::UserRole + 1); // 标记为分组节点 + groupItem->setSelectable(false); + groupItem->setEditable(false); + groupItem->setIcon(QIcon(":/icons/date.png")); + + for (const auto& rowData : it.value()) { + QList rowItems; + for (int col = 0; col < model->columnCount(); ++col) { + QStandardItem* item = new QStandardItem(rowData[col]); + item->setTextAlignment(Qt::AlignCenter); + rowItems.append(item); + } + groupItem->appendRow(rowItems); + } + + model->appendRow(groupItem); + } + } + + // 5. 恢复列宽 + for (int i = 0; i < columnWidths.size() && i < model->columnCount(); ++i) { + treeView->setColumnWidth(i, columnWidths[i]); + } + + // 6. 展开所有分组 + treeView->expandAll(); +} +void CrownClient::groupLogTreeView(GroupType groupType) +{ + m_logGroupType = groupType; + + if (!m_logModel) return; + + // 保存当前数据 + QList> allData; + for (int row = 0; row < m_logModel->rowCount(); ++row) { + QStandardItem* item = m_logModel->item(row); + if (item->data(Qt::UserRole + 1).toInt() == 1) { + // 分组节点,遍历其子节点 + for (int childRow = 0; childRow < item->rowCount(); ++childRow) { + QMap rowData; + for (int col = 0; col < m_logModel->columnCount(); ++col) { + QStandardItem* childItem = item->child(childRow, col); + if (childItem) { + rowData[col] = childItem->text(); + } + } + allData.append(rowData); + } + } + else { + // 普通节点 + QMap rowData; + for (int col = 0; col < m_logModel->columnCount(); ++col) { + QStandardItem* childItem = m_logModel->item(row, col); + if (childItem) { + rowData[col] = childItem->text(); + } + } + allData.append(rowData); + } + } + + // 清空模型并重新设置表头 + m_logModel->clear(); + m_logModel->setHorizontalHeaderLabels({ "时间","类型","日志" }); + + // 重新添加数据,按照新的分组方式 + if (groupType == NO_GROUP) { + // 无分组,直接添加所有行 + for (const auto& rowData : allData) { + QList rowItems; + for (int col = 0; col < m_logModel->columnCount(); ++col) { + QStandardItem* item = new QStandardItem(rowData[col]); + item->setTextAlignment(Qt::AlignCenter); + rowItems.append(item); + } + m_logModel->appendRow(rowItems); + } + } + else { + // 有分组,按分组键组织数据 + QMap>> groupedData; + + for (const auto& rowData : allData) { + QString groupKey; + if (groupType == BY_TIME) { + QString timeStr = rowData[0]; // 第0列是时间 + groupKey = timeStr.left(10); // 取日期部分 + } + else if (groupType == BY_LOG_TYPE) { + groupKey = rowData[1]; // 第1列是日志类型 + } + + // 清除可能存在的已有计数 + groupKey = groupKey.split(" (").first().trimmed(); + groupedData[groupKey].append(rowData); + } + + // 添加分组和子项 + for (auto it = groupedData.begin(); it != groupedData.end(); ++it) { + QString groupTitle = QString("%1 (%2)").arg(it.key()).arg(it.value().size()); + + QStandardItem* groupItem = new QStandardItem(groupTitle); + groupItem->setData(1, Qt::UserRole + 1); // 标记为分组节点 + groupItem->setSelectable(false); + groupItem->setEditable(false); + groupItem->setIcon(QIcon(":/icons/date.png")); + + for (const auto& rowData : it.value()) { + QList rowItems; + for (int col = 0; col < m_logModel->columnCount(); ++col) { + QStandardItem* item = new QStandardItem(rowData[col]); + item->setTextAlignment(Qt::AlignCenter); + rowItems.append(item); + } + groupItem->appendRow(rowItems); + } + + m_logModel->appendRow(groupItem); + } + } + + // 展开所有分组 + ui.log_tree_view->expandAll(); +} +// +void CrownClient::deleteSelectedItems(QTreeView* treeView) +{ + QStandardItemModel* model = qobject_cast(treeView->model()); + if (!model || !treeView->selectionModel()) { + // qDebug() << "模型或选择模型无效"; + return; + } + + // 获取所有选中的行(使用selectedRows确保获取整行) + QModelIndexList selected = treeView->selectionModel()->selectedRows(0); // 只需要第一列索引 + if (selected.isEmpty()) { + // qDebug() << "没有选中的行"; + return; + } + + // 收集要删除的订单号和对应模型索引 + QMap itemsToDelete; + for (const QModelIndex &index : selected) { + QStandardItem* item = model->itemFromIndex(index); + if (item) { + QString tid = item->data(Qt::UserRole + 2).toString(); + if (tid.isEmpty()) { + tid = item->text().split(" (").first().trimmed(); + } + itemsToDelete.insert(tid, index); + // qDebug() << "准备删除订单:" << tid << "行号:" << index.row(); + } + } + + // 根据视图类型调用对应的数据库删除函数 + bool dbSuccess = false; + QList tidList = itemsToDelete.keys(); + + if (treeView == ui.order_tree_view) { + dbSuccess = g_config->remove_accept_orders(tidList); + } + else if (treeView == ui.screen_tree_view) { + dbSuccess = g_config->remove_screen_orders(tidList); + } + else if (treeView == ui.success_tree_view) { + dbSuccess = g_config->remove_success_orders(tidList); + } + else if (treeView == ui.failed_tree_view) { + dbSuccess = g_config->remove_failed_orders(tidList); + } + else if (treeView == ui.rebet_tree_view) { + dbSuccess = g_config->remove_rebet_orders(tidList); + } + + if (!dbSuccess) { + QMessageBox::warning(this, "警告", "删除数据库记录失败!"); + return; + } + + // 从后往前删除模型项 + QList sortedIndexes = itemsToDelete.values(); + std::sort(sortedIndexes.begin(), sortedIndexes.end(), + [](const QModelIndex &a, const QModelIndex &b) { + return a.row() > b.row(); + }); + + // 禁用视图刷新以提高性能 + treeView->setUpdatesEnabled(false); + + for (const QModelIndex &index : sortedIndexes) { + QModelIndex parent = index.parent(); + if (parent.isValid()) { + // 分组模式 + QStandardItem* parentItem = model->itemFromIndex(parent); + if (parentItem) { + // qDebug() << "删除分组子项:" << index.row() << "父项:" << parent.row(); + parentItem->removeRow(index.row()); + + // 更新分组标题 + QString groupText = parentItem->text().split(" (").first().trimmed(); + parentItem->setText(QString("%1 (%2)").arg(groupText).arg(parentItem->rowCount())); + + // 空分组处理 + if (parentItem->rowCount() == 0) { + model->removeRow(parent.row()); + // qDebug() << "移除空分组:" << parent.row(); + } + } + } + else { + // 非分组模式 + // qDebug() << "删除独立行:" << index.row(); + model->removeRow(index.row()); + } + } + + // 重新启用视图刷新 + treeView->setUpdatesEnabled(true); + + // 只更新变化的部分,而不是重置整个视图 + treeView->viewport()->update(); + // qDebug() << "删除完成,当前模型行数:" << model->rowCount(); +} + +void CrownClient::clearTreeView(QTreeView* treeView) +{ + QStandardItemModel* model = qobject_cast(treeView->model()); + if (!model) return; + + // 根据视图类型清空对应数据库表 + bool dbSuccess = false; + if (treeView == ui.order_tree_view) { + dbSuccess = g_config->clear_accept_orders(); + } + else if (treeView == ui.screen_tree_view) { + dbSuccess = g_config->clear_screen_orders(); + } + else if (treeView == ui.success_tree_view) { + dbSuccess = g_config->clear_success_orders(); + } + else if (treeView == ui.failed_tree_view) { + dbSuccess = g_config->clear_failed_orders(); + } + else if (treeView == ui.rebet_tree_view) { + dbSuccess = g_config->clear_rebet_orders(); + } + else if (treeView == ui.log_tree_view) { + model->clear(); + model->setHorizontalHeaderLabels({ "时间","类型","日志" }); + treeView->reset(); + return; + } + + if (dbSuccess) { + model->clear(); + + // 重新设置表头 + if (treeView == ui.order_tree_view) { + model->setHorizontalHeaderLabels({ "单号/场次","下注时间","接收时间","会员/代理","项目","类型","联赛/队伍","下注","盘口","赔率","金额" }); + } + else if (treeView == ui.screen_tree_view) { + model->setHorizontalHeaderLabels({ "单号/场次","下注时间","会员/代理","项目","类型","联赛/队伍","下注","盘口","赔率","金额","原因" }); + } + else if (treeView == ui.success_tree_view) { + model->setHorizontalHeaderLabels({ "单号/场次","跟单时间","会员/代理","项目","类型","联赛/队伍","下注","盘口","赔率","金额" }); + } + else if (treeView == ui.failed_tree_view) { + model->setHorizontalHeaderLabels({ "单号/场次","跟单时间","会员/代理","项目","类型","联赛/队伍","下注","盘口","赔率","金额","原因" }); + } + else if (treeView == ui.rebet_tree_view) { + model->setHorizontalHeaderLabels({ "单号/场次","跟单时间","会员/代理","项目","类型","联赛/队伍","下注","盘口","赔率","金额","原因" }); + } + + treeView->reset(); + // qDebug() << "清空完成:" << treeView->objectName(); + } + else { + QMessageBox::warning(this, "警告", "清空数据库表失败!"); + } +} + + + +void CrownClient::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason) +{ + if (reason == QSystemTrayIcon::DoubleClick) { + showNormal(); // 双击托盘图标恢复窗口 + } +} + + +// 心跳检查槽函数 +void CrownClient::heartbeat() +{ + VMProtectBegin("Heartbeat_Check"); + + QString result; + bool heartbeatResult = g_verify->Heartbeat(result); + + if (!heartbeatResult) { + // 心跳失败,可以记录日志但不立即退出 + qDebug() << "心跳失败:" << result; + } + + // 检查授权到期时间 + if (g_verify->GetDueTime().msecsTo(QDateTime::currentDateTime()) >= 0) { + QMessageBox::critical(nullptr, "错误", "授权已到期!"); + QApplication::quit(); + } + + VMProtectEnd(); +} + + + +void CrownClient::push_disconnected() +{ + PushMsg *worker = new PushMsg(); + QThread *workerThread = new QThread(); + + worker->moveToThread(workerThread); + + // 连接信号槽 + connect(workerThread, &QThread::started, [worker]() { + //"-4826387471" + //worker->push("account_dissconnected", "-4826387471", QMap()); + worker->push("account_dissconnected", g_config->notice_account(), QMap()); + }); + + connect(worker, &PushMsg::resultReady, [](const QString &result) { + // qDebug() << "Result:" << result; + }); + + connect(worker, &PushMsg::resultReady, workerThread, &QThread::quit); + connect(workerThread, &QThread::finished, worker, &PushMsg::deleteLater); + connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater); + + workerThread->start(); +} + +void CrownClient::push_reconnected() +{ + PushMsg *worker = new PushMsg(); + QThread *workerThread = new QThread(); + + worker->moveToThread(workerThread); + + // 连接信号槽 + connect(workerThread, &QThread::started, [worker]() { + worker->push("account_reconnected", g_config->notice_account(), QMap()); + }); + + connect(worker, &PushMsg::resultReady, [](const QString &result) { + // qDebug() << "Result:" << result; + }); + + connect(worker, &PushMsg::resultReady, workerThread, &QThread::quit); + connect(workerThread, &QThread::finished, worker, &PushMsg::deleteLater); + connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater); + + workerThread->start(); +} + +void CrownClient::push_accept(QMap order) +{ + PushMsg *worker = new PushMsg(); + QThread *workerThread = new QThread(); + + worker->moveToThread(workerThread); + + // 连接信号槽 + connect(workerThread, &QThread::started, [worker, order]() { + worker->push("accept_order", g_config->notice_account(), order); + }); + + connect(worker, &PushMsg::resultReady, [](const QString &result) { + // qDebug() << "Result:" << result; + }); + + connect(worker, &PushMsg::resultReady, workerThread, &QThread::quit); + connect(workerThread, &QThread::finished, worker, &PushMsg::deleteLater); + connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater); + + workerThread->start(); +} diff --git a/CrownClient/CrownClient.h b/CrownClient/CrownClient.h new file mode 100644 index 0000000..6811611 --- /dev/null +++ b/CrownClient/CrownClient.h @@ -0,0 +1,171 @@ +#pragma once + +#include +#include "ui_CrownClient.h" +#include "Setting.h" +#include +#include +#include "BetThread.h" +#include "Notice.h" + +typedef enum _State { + wait, + loadLoginPage, + readyLogin, + login, + relogin, + work +}State; + +class CrownClient : public QMainWindow +{ + Q_OBJECT +public: + CrownClient(QWidget *parent = nullptr); + ~CrownClient(); +private: + void closeEvent(QCloseEvent* event); +public: + // 分组类型 + enum GroupType { + NO_GROUP, + BY_TIME, + BY_ORDER_ID, + BY_LOG_TYPE + }; + + + // 当前分组状态 + GroupType m_logGroupType = BY_TIME; // 日志默认按时间分组 + GroupType m_orderGroupType = BY_TIME; // 接收注单默认按时间分组 + GroupType m_screenGroupType = BY_TIME; // 筛选注单默认按时间分组 + GroupType m_successGroupType = BY_TIME; // 成功注单默认按时间分组 + GroupType m_failedGroupType = BY_TIME; // 失败注单默认按时间分组 + GroupType m_rebetGroupType = BY_TIME; // 补单默认按时间分组 + + // 分组函数 + void groupTreeView(QTreeView* treeView, GroupType groupType); + void groupLogTreeView(GroupType groupType); + + // 通用操作函数 + void deleteSelectedItems(QTreeView* treeView); + void clearTreeView(QTreeView* treeView); + + + +signals: + void log(QString type, QString log); + void signalLogin(); // 登录信号 + void signalStart(); // 开始信号 + void signalStop(); // 停止信号 + // 添加账号缓存 + void signalAddUser(QString username, QString password); + void signalBet(QMap); // 下单信号 + void signalUpdateLeagueAndTeam(QList>); // 更新联盟和队伍信号 + void signalBetSuccess(QMap); // 下单成功信号 + +private slots: + // 接收注单 -> 过滤注单 -> 获取注单游戏信息/可能需要轮询 -> 下单 -> 等待(根据情况判断) -> 成功/失败 + void slotChangeState(int state); + void slotAcceptOrders(QList> list); + void slotSetUser(QString username, QString password); + void slotStart(); + void slotStop(); + void slotLoadFinished(bool isok); + void slotLogin(); + void slotUpdateParamer(); + void slotUpdateLeague(); + + void slotUpdateReadOrdersTimes(); + void slotUpdateReadOrdersCount(int count); + + + + // 添加日志 + void on_log(QString type, QString log); + + + // 托盘点击 + void onTrayIconActivated(QSystemTrayIcon::ActivationReason reason); + +// 托盘 +private: + QSystemTrayIcon *trayIcon; + QTimer* m_heartbeatTimer; +public slots: + // 心跳 + void heartbeat(); + // 掉线重新登录 + void on_disconnected(); + + //QString getCleanGroupKey(const QString& rawKey); + //QString buildGroupTitle(const QString& cleanKey, int count); + // 视图 -> 添加接收注单 + void view_add_accept_order(QMap order); + // 视图 -> 添加筛选注单 + void view_add_screen_order(QMap order); + // 视图 -> 添加成功注单 + void view_add_success_order(QMap order); + // 视图 -> 添加失败注单 + void view_add_failed_order(QMap order); + // 视图 -> 修改失败注单 + void view_alert_failed_order(QMap order); + // 视图 -> 移除失败注单 + void view_remove_failed_order(QMap order); + // 视图 -> 添加补单记录 + void view_add_rebet_order(QMap order); + + // 刷新计数器显示 + void view_flush_counter(); + void view_change_time(bool isCrownTime); + + // 推送掉线信息 + void push_disconnected(); + // 推送连接信息 + void push_reconnected(); + // 推送接收注单 + void push_accept(QMap order); + +private: + QMenu *contextMenu; + QAction *groupByIdAction; + QAction *groupByTimeAction; + QAction *deleteAction; + QAction *clearAction; + QAction * noGroupAction; + +private: + Setting* m_window_setting; + Notice* m_window_notice; +private: + // 模型对象指针 + QStandardItemModel* m_logModel; + // 代理模型对象指针 + QSortFilterProxyModel* m_logProxyModel; + +private: + QMap m_paramers; + QTimer* m_paramerTimer; + State m_state; + // 用于记录盘口变化[初始化时清空] + QList> m_handicap; + QList> m_games; + // 订单[初始化时清空] + QList> m_orders; + // 补单原因[初始化时清空] + QMap m_rebetOrders; + + // 读取次数 + int m_readOrderTimes; + int m_readOrderCount; + int m_screenOrderCount; + int m_successOrderCount; + + BetThread* m_bet_thread; + + + qint64 m_start_time; + +private: + Ui::CrownClientClass ui; +}; diff --git a/CrownClient/CrownClient.qrc b/CrownClient/CrownClient.qrc new file mode 100644 index 0000000..e3eabe4 --- /dev/null +++ b/CrownClient/CrownClient.qrc @@ -0,0 +1,36 @@ + + + Images/user.png + Images/start.png + Images/stop.png + Images/client.ico + Images/crownTime.png + Images/localTime.png + Images/green.png + Images/red.png + Images/yellow.png + Resources/mail.png + + + Resources/visual_studio_dark.qss + + + sound/accept.wav + sound/disconnect.wav + sound/exit.wav + sound/failed.wav + sound/pushFailed.wav + sound/readOrder.wav + sound/relogin.wav + sound/screen.wav + sound/success.wav + sound/update.wav + + + Resources/icons/close.png + Resources/icons/restore.png + Resources/icons/down_arrow.png + Resources/icons/down_arrow_light.svg + Resources/icons/checkmark.png + + diff --git a/CrownClient/CrownClient.rc b/CrownClient/CrownClient.rc new file mode 100644 index 0000000..28c7ef4 --- /dev/null +++ b/CrownClient/CrownClient.rc @@ -0,0 +1,110 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// ÖÐÎÄ(¼òÌ壬Öйú) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS) +LANGUAGE LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED +#pragma code_page(936) + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_ICON1 ICON "Images\\client.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,0,6,8 + PRODUCTVERSION 1,0,6,8 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x40004L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "080404b0" + BEGIN + VALUE "CompanyName", "Crown" + VALUE "FileDescription", "CrownClient" + VALUE "FileVersion", "1.0.6.8" + VALUE "InternalName", "CrownClient.exe" + VALUE "LegalCopyright", "Copyright (C) 2025" + VALUE "OriginalFilename", "CrownClient.exe" + VALUE "ProductName", "TODO: " + VALUE "ProductVersion", "1.0.6.8" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x804, 1200 + END +END + +#endif // ÖÐÎÄ(¼òÌ壬Öйú) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/CrownClient/CrownClient.ui b/CrownClient/CrownClient.ui new file mode 100644 index 0000000..fffbdae --- /dev/null +++ b/CrownClient/CrownClient.ui @@ -0,0 +1,490 @@ + + + CrownClientClass + + + + 0 + 0 + 1368 + 1007 + + + + CrownClient + + + + + + + + + + + 过滤:下注时间 + + + + + + + + + + 之前注单 + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + #stateButton{border:none; padding: 0px;} + + + 连接断开 + + + + :/images/Images/red.png:/images/Images/red.png + + + Qt::ToolButtonTextBesideIcon + + + + + + + 连接服务 + + + + + + + 跟单设置 + + + + + + + 开 始 + + + + + + + #stateButton_2{border:none; padding: 0px;} + + + + + + + :/images/Images/stop.png:/images/Images/stop.png + + + + 64 + 64 + + + + true + + + + + + + false + + + 停 止 + + + + + + + PointingHandCursor + + + Qt::LeftToRight + + + #crownTimeButton{border:none; padding: 0px;} + + + 皇冠时间 + + + + :/images/Images/crownTime.png + + + + + 48 + 48 + + + + QToolButton::DelayedPopup + + + Qt::ToolButtonTextUnderIcon + + + false + + + + + + + #button_notice{border:none; padding: 0px;} + + + 信息推送 + + + + :/images/Resources/mail.png:/images/Resources/mail.png + + + + 48 + 48 + + + + Qt::ToolButtonTextUnderIcon + + + + + + + + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + 0 + + + + 皇冠会员 + + + + + + 6 + + + + + + 16777215 + 20 + + + + 网址: + + + + + + + + 250 + 0 + + + + true + + + + https://61.14.172.140/ + + + + + + + + + 16777215 + 20 + + + + 账号: + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 120 + 16777215 + + + + tuser2 + + + + + + + + 16777215 + 20 + + + + 密码: + + + + + + + + 0 + 0 + + + + + 120 + 16777215 + + + + Aa123456 + + + + + + + 登 录 + + + + + + + + + + + :/images/Images/user.png:/images/Images/user.png + + + + 40 + 40 + + + + true + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + true + + + + 0 + 600 + + + + + https://www.baidu.com/ + + + + + + + + + 接收注单 + + + + + + + + + + 筛选注单 + + + + + + + + + + 跟单成功 + + + + + + + + + + 跟单失败 + + + + + + + + + + 补单记录 + + + + + + + + + + 运行日志 + + + + + + + + + + + + + + + + QWebEngineView + QWidget +
QtWebEngineWidgets/QWebEngineView
+
+ + ComboBox + QComboBox +
combobox.h
+
+
+ + + + +
diff --git a/CrownClient/CrownClient.vcxproj b/CrownClient/CrownClient.vcxproj new file mode 100644 index 0000000..b2fe081 --- /dev/null +++ b/CrownClient/CrownClient.vcxproj @@ -0,0 +1,293 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {C339197A-FFBA-4AE7-81FA-325702162EC1} + QtVS_v304 + 10.0.17763.0 + 10.0 + 10.0.17763.0 + 10.0 + $(MSBuildProjectDirectory)\QtMsBuild + + + + Application + v141 + false + + + Application + v143 + + + Application + v141 + + + Application + v143 + + + + + + + core;xml;sql;network;gui;multimedia;widgets;webengine;webenginewidgets;webview + debug + true + true + 5.15.2_msvc2019_64 + + + 5.9.9_msvc2015 + core;xml;sql;network;gui;multimedia;widgets;webengine;webenginewidgets;webview + debug + true + + + 5.15.2_msvc2019_64 + core;xml;sql;network;gui;multimedia;widgets;webengine;webenginewidgets;webview + release + true + true + + + 5.12.12_msvc2017_64 + core;xml;sql;network;gui;multimedia;widgets;webengine;webenginewidgets;webview + release + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /utf-8 %(AdditionalOptions) + D:\开发工具\VMProtect\Include\C;%(AdditionalIncludeDirectories) + + + D:\开发工具\VMProtect\Lib\Windows;%(AdditionalLibraryDirectories) + + + + + /utf-8 %(AdditionalOptions) + + + + + /utf-8 %(AdditionalOptions) + D:\开发工具\VMProtect\Include\C;%(AdditionalIncludeDirectories) + + + D:\开发工具\VMProtect\Lib\Windows;%(AdditionalLibraryDirectories) + + + + + /utf-8 %(AdditionalOptions) + + + + + true + true + ProgramDatabase + Disabled + MultiThreadedDebugDLL + + + Windows + true + + + + + true + true + ProgramDatabase + Disabled + MultiThreadedDebugDLL + + + Windows + true + + + + + true + true + None + MaxSpeed + MultiThreadedDLL + + + Windows + false + + + + + true + true + None + MaxSpeed + MultiThreadedDLL + + + Windows + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/CrownClient/CrownClient.vcxproj.filters b/CrownClient/CrownClient.vcxproj.filters new file mode 100644 index 0000000..6224fec --- /dev/null +++ b/CrownClient/CrownClient.vcxproj.filters @@ -0,0 +1,379 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + qml;cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + qrc;rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + {6ff33be0-7973-4ee3-a600-239d14276a8b} + + + {8f10bb48-5a7f-40be-8a24-c643f7865939} + + + {5a24fc14-3744-4cef-a26b-a509a8bb0164} + + + {1e462d2e-253a-44ec-b387-f3fcdce0650b} + + + {1b3aa156-67c5-43ef-aaa9-e2240152cc26} + + + {ea16ec9e-6410-417d-92f1-7eb2ad9145f2} + + + {742b85ea-e9e5-4880-8790-de8c7aabae89} + + + {3532cadb-0cd6-4ad2-9828-cb84522c7730} + + + {5680a128-4b60-417d-83d1-beb5697bec78} + + + {6e842187-0177-4d08-8bb2-60d7f55183cf} + + + {e531d789-92fb-45f5-98ab-2cf97779c31d} + + + {d2914ecd-dcd1-40ab-ab1c-c4068905465f} + + + {0971c7b4-8e7e-4a6d-9a00-cff842a855e2} + + + {c26f804b-ddb3-48aa-b0fe-c9dd4c9e5d41} + + + {dd90d511-89a9-4d70-a8e8-2b10b83bedde} + + + {5419e85b-5c8f-4af4-914d-8a623bf63153} + + + {8f67554e-be9e-43cf-8987-3ca676373bee} + + + {95366ebe-5f33-4001-9b6d-8fb18afccada} + + + {a5419254-ff99-4b0a-a806-d71b9ba40f22} + + + {02a188eb-8517-470b-a97e-6c3b6470e4e5} + + + {65b219e3-a528-455a-939a-b33c3e24e4ab} + + + {98db2de1-5831-4d9e-a7fb-948211b629eb} + + + {3bafe2e9-16bf-4489-a7d1-e777d58fe480} + + + {126767a8-e6b5-46d7-8963-b340443cde15} + + + {8a54176d-8f83-48a0-bbe8-e1859744decc} + + + {08a904dc-29cf-4c2c-986b-abdd4851251c} + + + {f5646f0d-9e00-45ce-bea9-17f8de9842aa} + + + {833bb199-8abb-4fad-971e-4c4258d6f80d} + + + + + Resource Files + + + + + Source Files + + + Header Files\Form\Login + + + Header Files\Form\Client + + + Header Files\Form\Connect + + + Header Files\Form\Setting + + + Header Files\TCP + + + Header Files\CustomUI + + + Header Files\CustomUI + + + Header Files\CustomUI + + + Header Files + + + Header Files\Verify + + + Header Files\Config + + + Header Files\Form\FollowProject + + + Header Files\Form\Handicap + + + Header Files\Form\Odds + + + Header Files\Form\Amount + + + Header Files\CustomUI + + + Header Files\Utils + + + Header Files\Form\Sound + + + Header Files\Form\Sleep + + + Header Files\Form\Screen + + + Header Files\Form\Rebet + + + Header Files\Form\Match + + + Header Files\Form\Setting\FollowType + + + Header Files\Form\Setting\RatioAmount + + + Header Files\Form\Setting\FollowHandicap + + + Header Files\Form\User + + + Header Files\Platform + + + Header Files\AppInstanceManager + + + Header Files\Form\Notice + + + Header Files\PushMsg + + + + + Header Files\Form\Login + + + Header Files\Form\Client + + + Header Files\Form\Connect + + + Header Files\Form\Setting + + + Header Files\TCP + + + Header Files\CustomUI + + + Header Files\CustomUI + + + Header Files\Verify + + + Header Files\Config + + + Header Files\Form\FollowProject + + + Header Files\Form\Handicap + + + Header Files\Form\Odds + + + Header Files\Form\Amount + + + Header Files\CustomUI + + + Header Files\Form\Sound + + + Header Files\Form\Sleep + + + Header Files\Form\Screen + + + Header Files\Form\Rebet + + + Header Files\Form\Match + + + Header Files\Form\Setting\FollowType + + + Header Files\Form\Setting\RatioAmount + + + Header Files\Form\Setting\FollowHandicap + + + Header Files\Form\User + + + Header Files\AppInstanceManager + + + Header Files\Platform + + + Header Files\Form\Notice + + + Header Files\PushMsg + + + + + Header Files\Form\Login + + + Header Files\Form\Client + + + Header Files\Form\Connect + + + Header Files\Form\Setting + + + Header Files\Form\FollowProject + + + Header Files\Form\Handicap + + + Header Files\Form\Odds + + + Header Files\Form\Amount + + + Header Files\Form\Sound + + + Header Files\Form\Sleep + + + Header Files\Form\Screen + + + Header Files\Form\Rebet + + + Header Files\Form\Match + + + Header Files\Form\Setting\FollowType + + + Header Files\Form\Setting\RatioAmount + + + Header Files\Form\Setting\FollowHandicap + + + Header Files\Form\User + + + Header Files\Form\Notice + + + + + Header Files\CustomUI + + + Header Files + + + Header Files\Utils + + + Header Files + + + Header Files\TCP + + + Header Files + + + Header Files + + + Header Files\MessageHandle + + + + + Resource Files + + + + + Resource Files + + + Resource Files + + + \ No newline at end of file diff --git a/CrownClient/FollowHandicap.cpp b/CrownClient/FollowHandicap.cpp new file mode 100644 index 0000000..fc9c218 --- /dev/null +++ b/CrownClient/FollowHandicap.cpp @@ -0,0 +1,260 @@ +#include "FollowHandicap.h" + +FollowHandicap::FollowHandicap(QWidget *parent) + : QWidget(parent) +{ + ui.setupUi(this); + + // 设置窗口图标 + this->setWindowIcon(QIcon(":/images/Images/client.ico")); + // 设置窗口标题 + this->setWindowTitle("跟单盘口"); + // 设置为对话框窗口 + setWindowFlags(Qt::Dialog); + // 设置窗口仅有关闭按钮 + setWindowFlags(Qt::WindowCloseButtonHint); + // setFixedSize(1188, 711); +} + +FollowHandicap::~FollowHandicap() +{} + +QMap FollowHandicap::map() +{ + QMap map; + if (ui.hkCheckBox->isChecked()) + { + map["hkEnable"] = "true"; + if (ui.hkCombo->currentIndex() == 0) + { + map["hkChange"] = "H"; + map["hkType"] = "香港盘"; + } + if (ui.hkCombo->currentIndex() == 1) + { + map["hkChange"] = "M"; + map["hkType"] = "马来盘"; + } + if (ui.hkCombo->currentIndex() == 2) + { + map["hkChange"] = "I"; + map["hkType"] = "印尼盘"; + } + if (ui.hkCombo->currentIndex() == 3) + { + map["hkChange"] = "E"; + map["hkType"] = "欧洲盘"; + } + } + else + { + map["hkEnable"] = "false"; + map["hkType"] = "香港盘"; + } + + if (ui.masCheckBox->isChecked()) + { + map["masEnable"] = "true"; + if (ui.masCombo->currentIndex() == 0) + { + map["masChange"] = "H"; + map["masType"] = "香港盘"; + } + if (ui.masCombo->currentIndex() == 1) + { + map["masChange"] = "M"; + map["masType"] = "马来盘"; + } + if (ui.masCombo->currentIndex() == 2) + { + map["masChange"] = "I"; + map["masType"] = "印尼盘"; + } + if (ui.masCombo->currentIndex() == 3) + { + map["masChange"] = "E"; + map["masType"] = "欧洲盘"; + } + } + else + { + map["masEnable"] = "false"; + map["masType"] = "马来盘"; + } + + if (ui.idaCheckBox->isChecked()) + { + map["idaEnable"] = "true"; + if (ui.idaCombo->currentIndex() == 0) + { + map["idaChange"] = "H"; + map["idaType"] = "香港盘"; + } + if (ui.idaCombo->currentIndex() == 1) + { + map["idaChange"] = "M"; + map["idaType"] = "马来盘"; + } + if (ui.idaCombo->currentIndex() == 2) + { + map["idaChange"] = "I"; + map["idaType"] = "印尼盘"; + } + if (ui.idaCombo->currentIndex() == 3) + { + map["idaChange"] = "E"; + map["idaType"] = "欧洲盘"; + } + } + else + { + map["idaEnable"] = "false"; + map["idaType"] = "印尼盘"; + } + + if (ui.eurCheckBox->isChecked()) + { + map["eurEnable"] = "true"; + if (ui.eurCombo->currentIndex() == 0) + { + map["eurChange"] = "H"; + map["eurType"] = "香港盘"; + } + if (ui.eurCombo->currentIndex() == 1) + { + map["eurChange"] = "M"; + map["eurType"] = "马来盘"; + } + if (ui.eurCombo->currentIndex() == 2) + { + map["eurChange"] = "I"; + map["eurType"] = "印尼盘"; + } + if (ui.eurCombo->currentIndex() == 3) + { + map["eurChange"] = "E"; + map["eurType"] = "欧洲盘"; + } + } + else + { + map["eurEnable"] = "false"; + map["eurType"] = "欧洲盘"; + } + + + return map; +} + +void FollowHandicap::setMap(QMap map) +{ + if (map["hkEnable"] == "true") + { + ui.hkCheckBox->setChecked(true); + } + else + { + ui.hkCheckBox->setChecked(false); + } + + if (map["masEnable"] == "true") + { + ui.masCheckBox->setChecked(true); + } + else + { + ui.masCheckBox->setChecked(false); + } + + if (map["idaEnable"] == "true") + { + ui.idaCheckBox->setChecked(true); + } + else + { + ui.idaCheckBox->setChecked(false); + } + + if (map["eurEnable"] == "true") + { + ui.eurCheckBox->setChecked(true); + } + else + { + ui.eurCheckBox->setChecked(false); + } + + + if (map["hkChange"] == "H") + { + ui.hkCombo->setCurrentIndex(0); + } + if (map["hkChange"] == "M") + { + ui.hkCombo->setCurrentIndex(1); + } + if (map["hkChange"] == "I") + { + ui.hkCombo->setCurrentIndex(2); + } + if (map["hkChange"] == "E") + { + ui.hkCombo->setCurrentIndex(3); + } + + if (map["masChange"] == "H") + { + ui.masCombo->setCurrentIndex(0); + } + if (map["masChange"] == "M") + { + ui.masCombo->setCurrentIndex(1); + } + if (map["masChange"] == "I") + { + ui.masCombo->setCurrentIndex(2); + } + if (map["masChange"] == "E") + { + ui.masCombo->setCurrentIndex(3); + } + + if (map["idaChange"] == "H") + { + ui.idaCombo->setCurrentIndex(0); + } + if (map["idaChange"] == "M") + { + ui.idaCombo->setCurrentIndex(1); + } + if (map["idaChange"] == "I") + { + ui.idaCombo->setCurrentIndex(2); + } + if (map["idaChange"] == "E") + { + ui.idaCombo->setCurrentIndex(3); + } + + if (map["eurChange"] == "H") + { + ui.eurCombo->setCurrentIndex(0); + } + if (map["eurChange"] == "M") + { + ui.eurCombo->setCurrentIndex(1); + } + if (map["eurChange"] == "I") + { + ui.eurCombo->setCurrentIndex(2); + } + if (map["eurChange"] == "E") + { + ui.eurCombo->setCurrentIndex(3); + } +} + +void FollowHandicap::closeEvent(QCloseEvent * event) +{ + emit signalUpdateStatus(); +} diff --git a/CrownClient/FollowHandicap.h b/CrownClient/FollowHandicap.h new file mode 100644 index 0000000..8768f97 --- /dev/null +++ b/CrownClient/FollowHandicap.h @@ -0,0 +1,22 @@ +#pragma once + +#include +#include "ui_FollowHandicap.h" + +class FollowHandicap : public QWidget +{ + Q_OBJECT + +public: + FollowHandicap(QWidget *parent = nullptr); + ~FollowHandicap(); +signals: + void signalUpdateStatus(); +public: + QMap map(); + void setMap(QMap map); +private: + void closeEvent(QCloseEvent* event); +private: + Ui::FollowHandicapClass ui; +}; diff --git a/CrownClient/FollowHandicap.ui b/CrownClient/FollowHandicap.ui new file mode 100644 index 0000000..4638a4c --- /dev/null +++ b/CrownClient/FollowHandicap.ui @@ -0,0 +1,287 @@ + + + FollowHandicapClass + + + + 0 + 0 + 487 + 178 + + + + FollowHandicap + + + + + + + + + + + + + + + true + + + + + + + 原始盘口 + + + + + + + 香港盘 + + + + + + + 跟单盘口 + + + + + + + + 香港盘 + + + + + 马来盘 + + + + + 印尼盘 + + + + + 欧洲盘 + + + + + + + + + + + + + + + + + + + + true + + + + + + + 原始盘口 + + + + + + + 马来盘 + + + + + + + 跟单盘口 + + + + + + + 1 + + + + 香港盘 + + + + + 马来盘 + + + + + 印尼盘 + + + + + 欧洲盘 + + + + + + + + + + + + + + + + + + + + true + + + + + + + 原始盘口 + + + + + + + 印尼盘 + + + + + + + 跟单盘口 + + + + + + + 2 + + + + 香港盘 + + + + + 马来盘 + + + + + 印尼盘 + + + + + 欧洲盘 + + + + + + + + + + + + + + + + + + + + true + + + + + + + 原始盘口 + + + + + + + 欧洲盘 + + + + + + + 跟单盘口 + + + + + + + 3 + + + + 香港盘 + + + + + 马来盘 + + + + + 印尼盘 + + + + + 欧洲盘 + + + + + + + + + + + + + diff --git a/CrownClient/FollowProject.cpp b/CrownClient/FollowProject.cpp new file mode 100644 index 0000000..8d8c5d4 --- /dev/null +++ b/CrownClient/FollowProject.cpp @@ -0,0 +1,1547 @@ +#include "FollowProject.h" +#include +#include "CheckBoxHeaderView.h" +#include "Global.h" +#include "Utils.h" + + +FollowProject::FollowProject(QWidget *parent) + : QWidget(parent) +{ + ui.setupUi(this); + + // 设置窗口图标 + this->setWindowIcon(QIcon(":/images/Images/client.ico")); + // 设置窗口标题 + this->setWindowTitle("跟单项目"); + // 设置为对话框窗口 + setWindowFlags(Qt::Dialog); + // 设置窗口仅有关闭按钮 + setWindowFlags(Qt::WindowCloseButtonHint); + + + + + // 自定义表头 + //CheckBoxHeaderView* header = new CheckBoxHeaderView(0, Qt::Horizontal, ui.tableWidget); + //ui.tableWidget->setHorizontalHeader(header); + + // 设置表头标题 + ui.tableWidget->setColumnCount(15); + ui.tableWidget->setHorizontalHeaderLabels({ " ","读取项目","让球","受让","大","小","独赢主","独赢客","独赢和","单","双","主队大","主队小","客队大","客队小" }); + // 列宽自动分配 + ui.tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + ui.tableWidget->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); + // 行高随内容分配 + ui.tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch); + + // 读取配置 + QList> readProject = g_config->betProject(); + + // 创建行 + for (int row = 0; row < 9; row++) + { + ui.tableWidget->insertRow(row); + + // 第一列 - 行选择复选框 + QWidget* rowSelectWidget = new QWidget; + QHBoxLayout* rowSelectLayout = new QHBoxLayout; + QCheckBox* rowSelectCheckBox = new QCheckBox; + rowSelectLayout->addWidget(rowSelectCheckBox); + rowSelectLayout->setContentsMargins(0, 0, 0, 0); + rowSelectLayout->setAlignment(rowSelectCheckBox, Qt::AlignCenter); + rowSelectWidget->setLayout(rowSelectLayout); + ui.tableWidget->setCellWidget(row, 0, rowSelectWidget); + + // 连接行选择复选框信号 + connect(rowSelectCheckBox, &QCheckBox::stateChanged, this, [this, row](int state) { + // 只更新当前行的复选框状态 + for (int col = 2; col < ui.tableWidget->columnCount(); col++) + { + // 跳过特殊行不需要的列 + if ((row == 6 || row == 7 || row == 8) && col == 8) + continue; + + QWidget* cellWidget = ui.tableWidget->cellWidget(row, col); + if (cellWidget) + { + QCheckBox* checkBox = qobject_cast(cellWidget->children().at(1)); + if (checkBox) + { + checkBox->setChecked(state == Qt::Checked); + } + } + } + }); + + // 第二列 - 游戏类型 + QTableWidgetItem* itemGameType = new QTableWidgetItem(); + itemGameType->setText(g_gameTypes[row]); + ui.tableWidget->setItem(row, 1, itemGameType); + + // 其他列 - 类型复选框 + for (int col = 2; col < 15; col++) + { + // 跳过特殊行不需要的列 + if ((row == 6 || row == 7 || row == 8) && col == 8) + continue; + + // 创建复选框 + QWidget* typeWidget = new QWidget; + QHBoxLayout* typeLayout = new QHBoxLayout; + QCheckBox* typeCheckBox = new QCheckBox; + typeLayout->addWidget(typeCheckBox); + typeLayout->setContentsMargins(0, 0, 0, 0); + typeLayout->setAlignment(typeCheckBox, Qt::AlignCenter); + typeWidget->setLayout(typeLayout); + ui.tableWidget->setCellWidget(row, col, typeWidget); + + // 连接类型复选框信号 - 用于更新行选择状态 + connect(typeCheckBox, &QCheckBox::stateChanged, this, [this, row]() { + updateRowCheckState(row); + }); + } + } + + // 读取保存的配置 + loadConfiguration(); + + // 其他UI设置 + ui.betDaysEdit->setText(QString::number(g_config->betDays())); + ui.betDaysEdit->setValidator(new QIntValidator(0, 30, this)); + ui.betNormalOrderCheckBox->setChecked(g_config->betNormalOrder()); + ui.betPhoneOrderCheckBox->setChecked(g_config->betPhoneOrder()); +} + +// 更新行选择复选框状态 +void FollowProject::updateRowCheckState(int row) +{ + bool allChecked = true; + bool anyChecked = false; + + // 检查该行所有类型复选框 + for (int col = 2; col < ui.tableWidget->columnCount(); col++) + { + // 跳过特殊行不需要的列 + if ((row == 6 || row == 7 || row == 8) && col == 8) + continue; + + QWidget* cellWidget = ui.tableWidget->cellWidget(row, col); + if (cellWidget) + { + QCheckBox* checkBox = qobject_cast(cellWidget->children().at(1)); + if (checkBox) + { + if (!checkBox->isChecked()) + allChecked = false; + else + anyChecked = true; + } + } + } + + // 更新行选择复选框状态 + QWidget* rowSelectWidget = ui.tableWidget->cellWidget(row, 0); + if (rowSelectWidget) + { + QCheckBox* rowSelectCheckBox = qobject_cast(rowSelectWidget->children().at(1)); + if (rowSelectCheckBox) + { + // 阻止信号触发,避免循环调用 + rowSelectCheckBox->blockSignals(true); + + if (allChecked) + rowSelectCheckBox->setCheckState(Qt::Checked); + else if (anyChecked) + rowSelectCheckBox->setCheckState(Qt::PartiallyChecked); + else + rowSelectCheckBox->setCheckState(Qt::Unchecked); + + rowSelectCheckBox->blockSignals(false); + } + } +} + +// 加载配置 +void FollowProject::loadConfiguration() +{ + QList> readProject = g_config->betProject(); + + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + for (int col = 0; col < ui.tableWidget->columnCount(); col++) + { + // 跳过特殊行不需要的列 + if ((row == 6 || row == 7 || row == 8) && col == 8) + continue; + + QWidget* cellWidget = ui.tableWidget->cellWidget(row, col); + if (cellWidget) + { + QCheckBox* checkBox = qobject_cast(cellWidget->children().at(1)); + if (checkBox) + { + bool isChecked = false; // 默认 + for (const auto& project : readProject) + { + if (project["ROW"].toInt() == row && project["COLUMN"].toInt() == col) + { + isChecked = (project["ENABLE"] == "TRUE"); + break; + } + } + checkBox->setChecked(isChecked); + } + } + } + // 更新行选择状态 + updateRowCheckState(row); + } +} +FollowProject::~FollowProject() +{} + + + + +bool FollowProject::screen(QString GT, QString wtype) +{ + return false; +} + +void FollowProject::closeEvent(QCloseEvent* event) +{ + g_config->setBetDays(ui.betDaysEdit->text().toInt()); + g_config->setBetNormalOrder(ui.betNormalOrderCheckBox->isChecked()); + g_config->setBetPhoneOrder(ui.betPhoneOrderCheckBox->isChecked()); + + QList> readProject; + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + // 获取项目 + QString rowText = ui.tableWidget->item(row, 1)->text(); + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + QString columnText = ui.tableWidget->horizontalHeaderItem(column)->text(); + if ((row == 6 || row == 7 || row == 8) && column == 8) + { + continue; + } + + if (column != 1) + { + QCheckBox* checkBox = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(0)->widget()); + // qDebug() << "选中状态[" << row << "," << column << "]: " << checkBox->isChecked(); + //if (!checkBox->isChecked()) + //{ + // continue; + //} + QMap project; + project["ROW"] = QString::number(row); + project["COLUMN"] = QString::number(column); + project["ENABLE"] = checkBox->isChecked() ? "TRUE" : "FALSE"; + project["ORDER_TYPE"] = columnText; // 实际投注类型,如:让球/受让 + //-----------------------滚球---------------------------- + // 足球滚球全场让球 + if (row == 0 && column == 2) + { + + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "让球"; + readProject.append(project); + continue; + } + + // 足球滚球全场受让 + if (row == 0 && column == 3) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "让球"; + readProject.append(project); + continue; + } + + // 足球滚球全场得分大 + if (row == 0 && column == 4) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "大小"; + readProject.append(project); + continue; + } + + // 足球滚球全场得分小 + if (row == 0 && column == 5) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "大小"; + readProject.append(project); + continue; + } + + // 足球滚球全场独赢主 + if (row == 0 && column == 6) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 足球滚球全场独赢客 + if (row == 0 && column == 7) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 足球滚球全场独赢和 + if (row == 0 && column == 8) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 足球滚球全场单 + if (row == 0 && column == 9) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "单双"; + readProject.append(project); + continue; + } + + // 足球滚球全场双 + if (row == 0 && column == 10) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "单双"; + readProject.append(project); + continue; + } + + // 足球滚球全场主队大 + if (row == 0 && column == 11) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "主大小"; + readProject.append(project); + continue; + } + + // 足球滚球全场主队小 + if (row == 0 && column == 12) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "主大小"; + readProject.append(project); + continue; + } + + // 足球滚球全场客队大 + if (row == 0 && column == 13) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "客大小"; + readProject.append(project); + continue; + } + + // 足球滚球全场客队小 + if (row == 0 && column == 14) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "客大小"; + readProject.append(project); + continue; + } + + // 足球滚球上半场让球 + if (row == 1 && column == 2) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "让球"; + readProject.append(project); + continue; + } + + // 足球滚球上半场受让 + if (row == 1 && column == 3) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "让球"; + readProject.append(project); + continue; + } + + // 足球滚球上半场得分大 + if (row == 1 && column == 4) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "大小"; + readProject.append(project); + continue; + } + + // 足球滚球上半场得分小 + if (row == 1 && column == 5) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "大小"; + readProject.append(project); + continue; + } + + // 足球滚球上半场独赢主 + if (row == 1 && column == 6) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 足球滚球上半场独赢客 + if (row == 1 && column == 7) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 足球滚球上半场独赢和 + if (row == 1 && column == 8) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 足球滚球上半场单 + if (row == 1 && column == 9) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "单双"; + readProject.append(project); + continue; + } + + // 足球滚球上半场双 + if (row == 1 && column == 10) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "单双"; + readProject.append(project); + continue; + } + + // 足球滚球上半场主队大 + if (row == 1 && column == 11) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "主大小"; + readProject.append(project); + continue; + } + + // 足球滚球上半场主队小 + if (row == 1 && column == 12) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "主大小"; + readProject.append(project); + continue; + } + + // 足球滚球上半场客队大 + if (row == 1 && column == 13) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "客大小"; + readProject.append(project); + continue; + } + + // 足球滚球上半场客队小 + if (row == 1 && column == 14) + { + project["GT"] = "足球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "客大小"; + readProject.append(project); + continue; + } + + + //------------------------足球今日---------------- + // 足球今日全场让球 + if (row == 2 && column == 2) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "让球"; + readProject.append(project); + continue; + } + + // 足球今日全场受让 + if (row == 2 && column == 3) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "让球"; + readProject.append(project); + continue; + } + + // 足球今日全场得分大 + if (row == 2 && column == 4) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "大小"; + readProject.append(project); + continue; + } + + // 足球今日全场得分小 + if (row == 2 && column == 5) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "大小"; + readProject.append(project); + continue; + } + + // 足球今日全场独赢主 + if (row == 2 && column == 6) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 足球今日全场独赢客 + if (row == 2 && column == 7) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 足球今日全场独赢和 + if (row == 2 && column == 8) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 足球今日全场单 + if (row == 2 && column == 9) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "单双"; + readProject.append(project); + continue; + } + + // 足球今日全场双 + if (row == 2 && column == 10) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "单双"; + readProject.append(project); + continue; + } + + // 足球今日全场主队大 + if (row == 2 && column == 11) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "主大小"; + readProject.append(project); + continue; + } + + // 足球今日全场主队小 + if (row == 2 && column == 12) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "主大小"; + readProject.append(project); + continue; + } + + // 足球今日全场客队大 + if (row == 2 && column == 13) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "客大小"; + readProject.append(project); + continue; + } + + // 足球今日全场客队小 + if (row == 2 && column == 14) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "客大小"; + readProject.append(project); + continue; + } + + // 足球今日上半场让球 + if (row == 3 && column == 2) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "让球"; + readProject.append(project); + continue; + } + + // 足球今日上半场受让 + if (row == 3 && column == 3) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "让球"; + readProject.append(project); + continue; + } + + // 足球今日上半场得分大 + if (row == 3 && column == 4) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "大小"; + readProject.append(project); + continue; + } + + // 足球今日上半场得分小 + if (row == 3 && column == 5) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "大小"; + readProject.append(project); + continue; + } + + // 足球今日上半场独赢主 + if (row == 3 && column == 6) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 足球今日上半场独赢客 + if (row == 3 && column == 7) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 足球今日上半场独赢和 + if (row == 3 && column == 8) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + + // 足球今日上半场单 + if (row == 3 && column == 9) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "单双"; + readProject.append(project); + continue; + } + + // 足球今日上半场双 + if (row == 3 && column == 10) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "单双"; + readProject.append(project); + continue; + } + + // 足球今日上半场主队大 + if (row == 3 && column == 11) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "主大小"; + readProject.append(project); + continue; + } + + // 足球今日上半场主队小 + if (row == 3 && column == 12) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "主大小"; + readProject.append(project); + continue; + } + + // 足球今日上半场客队大 + if (row == 3 && column == 13) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "客大小"; + readProject.append(project); + continue; + } + + // 足球今日上半场客队小 + if (row == 3 && column == 14) + { + project["GT"] = "足球"; + project["SESSION"] = "今日"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "客大小"; + readProject.append(project); + continue; + } + + // ----------------足球早盘------------------- + // 足球早盘全场让球 + if (row == 4 && column == 2) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "让球"; + readProject.append(project); + continue; + } + + // 足球早盘全场受让 + if (row == 4 && column == 3) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "让球"; + readProject.append(project); + continue; + } + + // 足球早盘全场得分大 + if (row == 4 && column == 4) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "大小"; + readProject.append(project); + continue; + } + + // 足球早盘全场得分小 + if (row == 4 && column == 5) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "大小"; + readProject.append(project); + continue; + } + + // 足球早盘全场独赢主 + if (row == 4 && column == 6) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 足球早盘全场独赢客 + if (row == 4 && column == 7) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 足球早盘全场独赢和 + if (row == 4 && column == 8) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 足球早盘全场单 + if (row == 4 && column == 9) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "单双"; + readProject.append(project); + continue; + } + + // 足球早盘全场双 + if (row == 4 && column == 10) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "单双"; + readProject.append(project); + continue; + } + + // 足球早盘全场主队大 + if (row == 4 && column == 11) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "主大小"; + readProject.append(project); + continue; + } + + // 足球早盘全场主队小 + if (row == 4 && column == 12) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "主大小"; + readProject.append(project); + continue; + } + + // 足球早盘全场客队大 + if (row == 4 && column == 13) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "客大小"; + readProject.append(project); + continue; + } + + // 足球早盘全场客队小 + if (row == 4 && column == 14) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全场"; + project["WAGERS_TYPE"] = "客大小"; + readProject.append(project); + continue; + } + + // 足球早盘上半场让球 + if (row == 5 && column == 2) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "让球"; + readProject.append(project); + continue; + } + + // 足球早盘上半场受让 + if (row == 5 && column == 3) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "让球"; + readProject.append(project); + continue; + } + + // 足球早盘上半场得分大 + if (row == 5 && column == 4) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "大小"; + readProject.append(project); + continue; + } + + // 足球早盘上半场得分小 + if (row == 5 && column == 5) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "大小"; + readProject.append(project); + continue; + } + + // 足球早盘上半场独赢主 + if (row == 5 && column == 6) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 足球早盘上半场独赢客 + if (row == 5 && column == 7) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 足球早盘上半场独赢和 + if (row == 5 && column == 8) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 足球早盘上半场单 + if (row == 5 && column == 9) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "单双"; + readProject.append(project); + continue; + } + + // 足球早盘上半场双 + if (row == 5 && column == 10) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "单双"; + readProject.append(project); + continue; + } + + // 足球早盘上半场主队大 + if (row == 5 && column == 11) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "主大小"; + readProject.append(project); + continue; + } + + // 足球早盘上半场主队小 + if (row == 5 && column == 12) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "主大小"; + readProject.append(project); + continue; + } + + // 足球早盘上半场客队大 + if (row == 5 && column == 13) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "客大小"; + readProject.append(project); + continue; + } + + // 足球早盘上半场客队小 + if (row == 5 && column == 14) + { + project["GT"] = "足球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "上半场"; + project["WAGERS_TYPE"] = "客大小"; + readProject.append(project); + continue; + } + + //------------------篮球滚球------------------ + // 篮球滚球全场让球 + if (row == 6 && column == 2) + { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "让球"; + readProject.append(project); + continue; + } + + // 篮球滚球全场受让 + if (row == 6 && column == 3) + { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "让球"; + readProject.append(project); + continue; + } + + // 篮球滚球全场得分大 + if (row == 6 && column == 4) + { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "大小"; + readProject.append(project); + continue; + } + + // 篮球滚球全场得分小 + if (row == 6 && column == 5) + { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "大小"; + readProject.append(project); + continue; + } + + // 篮球滚球全场独赢主 + if (row == 6 && column == 6) + { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 篮球滚球全场独赢客 + if (row == 6 && column == 7) + { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 篮球滚球全场独赢和 + if (row == 6 && column == 8) + { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 篮球滚球全场单 + if (row == 6 && column == 9) + { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "单双"; + readProject.append(project); + continue; + } + + // 篮球滚球全场双 + if (row == 6 && column == 10) + { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "单双"; + readProject.append(project); + continue; + } + + // 篮球今日全场主队大 + if (row == 6 && column == 11) + { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "主大小"; + readProject.append(project); + continue; + } + + // 篮球滚球全场主队小 + if (row == 6 && column == 12) + { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "主大小"; + readProject.append(project); + continue; + } + + // 篮球滚球全场客队大 + if (row == 6 && column == 13) + { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "客大小"; + readProject.append(project); + continue; + } + + // 篮球滚球全场客队小 + if (row == 6 && column == 14) + { + project["GT"] = "篮球"; + project["SESSION"] = "滚球"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "客大小"; + readProject.append(project); + continue; + } + //------------------篮球今日------------------ + // 篮球今日全场让球 + if (row == 7 && column == 2) + { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "让球"; + readProject.append(project); + continue; + } + + // 篮球今日全场受让 + if (row == 7 && column == 3) + { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "让球"; + readProject.append(project); + continue; + } + + // 篮球今日全场得分大 + if (row == 7 && column == 4) + { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "大小"; + readProject.append(project); + continue; + } + + // 篮球今日全场得分小 + if (row == 7 && column == 5) + { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "大小"; + readProject.append(project); + continue; + } + + // 篮球今日全场独赢主 + if (row == 7 && column == 6) + { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 篮球今日全场独赢客 + if (row == 7 && column == 7) + { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 篮球今日全场独赢和 + if (row == 7 && column == 8) + { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 篮球今日全场单 + if (row == 7 && column == 9) + { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "单双"; + readProject.append(project); + continue; + } + + // 篮球今日全场双 + if (row == 7 && column == 10) + { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "单双"; + readProject.append(project); + continue; + } + + // 篮球今日全场主队大 + if (row == 7 && column == 11) + { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "主大小"; + readProject.append(project); + continue; + } + + // 篮球今日全场主队小 + if (row == 7 && column == 12) + { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "主大小"; + readProject.append(project); + continue; + } + + // 篮球今日全场客队大 + if (row == 7 && column == 13) + { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "客大小"; + readProject.append(project); + continue; + } + + // 篮球今日全场客队小 + if (row == 7 && column == 14) + { + project["GT"] = "篮球"; + project["SESSION"] = "今日"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "客大小"; + readProject.append(project); + continue; + } + + //------------------篮球早盘------------------ + // 篮球早盘全场让球 + if (row == 8 && column == 2) + { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "让球"; + readProject.append(project); + continue; + } + + // 篮球早盘全场受让 + if (row == 8 && column == 3) + { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "让球"; + readProject.append(project); + continue; + } + + // 篮球早盘全场得分大 + if (row == 8 && column == 4) + { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "大小"; + readProject.append(project); + continue; + } + + // 篮球早盘全场得分小 + if (row == 8 && column == 5) + { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "大小"; + readProject.append(project); + continue; + } + + // 篮球早盘全场独赢主 + if (row == 8 && column == 6) + { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 篮球早盘全场独赢客 + if (row == 8 && column == 7) + { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 篮球早盘全场独赢和 + if (row == 8 && column == 8) + { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "独赢"; + readProject.append(project); + continue; + } + + // 篮球早盘全场单 + if (row == 8 && column == 9) + { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "单双"; + readProject.append(project); + continue; + } + + // 篮球早盘全场双 + if (row == 8 && column == 10) + { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "单双"; + readProject.append(project); + continue; + } + + + // 篮球早盘全场主队大 + if (row == 8 && column == 11) + { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "主大小"; + readProject.append(project); + continue; + } + + // 篮球早盘全场主队小 + if (row == 8 && column == 12) + { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "主大小"; + readProject.append(project); + continue; + } + + // 篮球早盘全场客队大 + if (row == 8 && column == 13) + { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "客大小"; + readProject.append(project); + continue; + } + + // 篮球早盘全场客队小 + if (row == 8 && column == 14) + { + project["GT"] = "篮球"; + project["SESSION"] = "早盘"; + project["STAGE"] = "全部"; + project["WAGERS_TYPE"] = "客大小"; + readProject.append(project); + continue; + } + } + } + } + + QList>::iterator iter; + g_config->setBetProject(readProject); + + +} \ No newline at end of file diff --git a/CrownClient/FollowProject.h b/CrownClient/FollowProject.h new file mode 100644 index 0000000..db8ea29 --- /dev/null +++ b/CrownClient/FollowProject.h @@ -0,0 +1,23 @@ +#pragma once + +#include +#include "ui_FollowProject.h" + +class FollowProject : public QWidget +{ + Q_OBJECT + +public: + FollowProject(QWidget *parent = nullptr); + ~FollowProject(); + +private: + Ui::FollowProjectClass ui; +public: + bool screen(QString gtype, QString wtype); + void loadConfiguration(); + void updateRowCheckState(int row); +private: + // 重写窗口关闭事件 + void closeEvent(QCloseEvent* event); +}; diff --git a/CrownClient/FollowProject.ui b/CrownClient/FollowProject.ui new file mode 100644 index 0000000..e60090e --- /dev/null +++ b/CrownClient/FollowProject.ui @@ -0,0 +1,80 @@ + + + FollowProjectClass + + + + 0 + 0 + 1188 + 613 + + + + FollowProject + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 跟单:下注时间至今 + + + + + + + + 50 + 16777215 + + + + + + + + 天内注单! + + + + + + + 跟单普通注单 + + + + + + + 跟单手机注单 + + + + + + + + + + + diff --git a/CrownClient/FollowType.cpp b/CrownClient/FollowType.cpp new file mode 100644 index 0000000..7043c0e --- /dev/null +++ b/CrownClient/FollowType.cpp @@ -0,0 +1,206 @@ +#include "FollowType.h" +#include "Global.h" +#include "Utils.h" + +FollowType::FollowType(QWidget *parent) + : QWidget(parent) +{ + ui.setupUi(this); + // 设置窗口图标 + this->setWindowIcon(QIcon(":/images/Images/client.ico")); + // 设置窗口标题 + this->setWindowTitle("赛事盘口判断处理"); + // 设置为对话框窗口 + setWindowFlags(Qt::Dialog); + // 设置窗口仅有关闭按钮 + setWindowFlags(Qt::WindowCloseButtonHint); + + ui.tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + ui.tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch); + + for (int row = 0; row < 9; row++) + { + ui.tableWidget->insertRow(row); + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + if (column == 0) + { + ui.tableWidget->setItem(row, column, new QTableWidgetItem(g_gameTypes[row])); + } + else + { + ui.tableWidget->setItem(row, column, new QTableWidgetItem("正跟")); + } + ui.tableWidget->item(row, column)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + } + + } + + connect(ui.setButton, &QPushButton::clicked, this, [&]() { + // 单个 + if (ui.projectCheckBox->isChecked() && ui.typeCheckBox->isChecked()) + { + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + QString project = ui.tableWidget->item(row,0)->text(); + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + if (column == 0) + { + continue; + } + QString type = ui.tableWidget->horizontalHeaderItem(column)->text(); + if (project == ui.projectCombo->currentText() && type == ui.typeCombo->currentText()) + { + ui.tableWidget->item(row, column)->setText(ui.followTypeCombo->currentText()); + break; + } + } + } + } + // 整行 + if (ui.projectCheckBox->isChecked() && !ui.typeCheckBox->isChecked()) + { + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + QString project = ui.tableWidget->item(row, 0)->text(); + if (project == ui.projectCombo->currentText()) + { + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + if (column == 0) + { + continue; + } + ui.tableWidget->item(row, column)->setText(ui.followTypeCombo->currentText()); + } + } + } + } + // 整列 + if (!ui.projectCheckBox->isChecked() && ui.typeCheckBox->isChecked()) + { + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + QString type = ui.tableWidget->horizontalHeaderItem(column)->text(); + if (type == ui.typeCombo->currentText()) + { + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + if (column == 0) + { + continue; + } + ui.tableWidget->item(row, column)->setText(ui.followTypeCombo->currentText()); + } + } + } + + } + // 全部 + if (!ui.projectCheckBox->isChecked() && !ui.typeCheckBox->isChecked()) + { + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + if (column == 0) + { + continue; + } + ui.tableWidget->item(row, column)->setText(ui.followTypeCombo->currentText()); + } + } + } + }); + + +} + +FollowType::~FollowType() +{ + + +} + +QList> FollowType::list() +{ + QList> list; + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + QString project = ui.tableWidget->item(row, 0)->text(); + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + // 第一列跳过 + if (column == 0) + { + continue; + } + QString type = ui.tableWidget->horizontalHeaderItem(column)->text(); + QMap map = Utils::instance().type(project, type); + map["follow_row"] = QString::number(row); + map["follow_column"] = QString::number(column); + if (ui.tableWidget->item(row, column)->text() == "正跟") + { + map["follow_betType"] = "true"; + } + else + { + map["follow_betType"] = "false"; + } + list.append(map); + } + } + return list; +} + +void FollowType::setList(QList> list) +{ + for (int i = 0; i < list.count(); i++) + { + QMap follow = list[i]; + int column = follow["follow_column"].toInt(); + int row = follow["follow_row"].toInt(); + if (follow["follow_betType"] == "true") + { + ui.tableWidget->item(row, column)->setText("正跟"); + } + else + { + ui.tableWidget->item(row, column)->setText("反跟"); + } + } +} + +void FollowType::closeEvent(QCloseEvent * event) +{ + int positiveFollow = 0; + int negativeFollow = 0; + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + if (ui.tableWidget->item(row, column)->text() == "正跟") + { + positiveFollow++; + } + else + { + negativeFollow++; + } + } + } + if (positiveFollow == 0) + { + emit signalUpdateStatus(); + } + else if (negativeFollow == 0) + { + emit signalUpdateStatus(); + } + else + { + emit signalUpdateStatus(); + } + +} diff --git a/CrownClient/FollowType.h b/CrownClient/FollowType.h new file mode 100644 index 0000000..826b709 --- /dev/null +++ b/CrownClient/FollowType.h @@ -0,0 +1,22 @@ +#pragma once + +#include +#include "ui_FollowType.h" + +class FollowType : public QWidget +{ + Q_OBJECT + +public: + FollowType(QWidget *parent = nullptr); + ~FollowType(); +public: + QList> list(); + void setList(QList> list); +signals: + void signalUpdateStatus(); +private: + void closeEvent(QCloseEvent* event); +private: + Ui::FollowTypeClass ui; +}; diff --git a/CrownClient/FollowType.ui b/CrownClient/FollowType.ui new file mode 100644 index 0000000..ba3e81f --- /dev/null +++ b/CrownClient/FollowType.ui @@ -0,0 +1,290 @@ + + + FollowTypeClass + + + + 0 + 0 + 877 + 432 + + + + FollowType + + + + + + QAbstractItemView::NoEditTriggers + + + false + + + false + + + false + + + + 注单项目 + + + + + 让球 + + + + + 受让 + + + + + 大 + + + + + 小 + + + + + 独赢主 + + + + + 独赢客 + + + + + 独赢和 + + + + + 单 + + + + + 双 + + + + + 主队大 + + + + + 主队小 + + + + + 客队大 + + + + + 客队小 + + + + + + + + + + + + + + 注单项目: + + + + + + + + 足球滚球全场 + + + + + 足球滚球上半场 + + + + + 足球今日全场 + + + + + 足球今日上半场 + + + + + 足球早盘全场 + + + + + 足球早盘上半场 + + + + + 篮球滚球全部 + + + + + 篮球今日全部 + + + + + 篮球早盘全部 + + + + + + + + 注单类型: + + + + + + + + 让球 + + + + + 受让 + + + + + 大 + + + + + 小 + + + + + 独赢主 + + + + + 独赢客 + + + + + 独赢和 + + + + + 单 + + + + + 双 + + + + + 主队大 + + + + + 主队小 + + + + + 客队大 + + + + + 客队小 + + + + + + + + 设置方式 + + + + + + + 跟单方式: + + + + + + + + 正跟 + + + + + 反跟 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + diff --git a/CrownClient/Global.cpp b/CrownClient/Global.cpp new file mode 100644 index 0000000..b001807 --- /dev/null +++ b/CrownClient/Global.cpp @@ -0,0 +1,18 @@ +#include "Global.h" + +Verify* g_verify; +// Manager* g_manager; +Config* g_config; + +const char* g_gameTypes[] = { "足球滚球全场","足球滚球上半场","足球今日全场","足球今日上半场","足球早盘全场","足球早盘上半场","篮球滚球全部","篮球今日全部","篮球早盘全部" }; + +QString dateFormat(QString source) +{ + QList list = source.split("-"); + if (list.count() == 3) + { + return list[2] + "-" + list[1] + "-" + list[0]; + } + + return QString(); +} \ No newline at end of file diff --git a/CrownClient/Global.h b/CrownClient/Global.h new file mode 100644 index 0000000..c1803cb --- /dev/null +++ b/CrownClient/Global.h @@ -0,0 +1,16 @@ +#pragma once +#include "Verify.h" +//#include "Manager.h" +#include "Config.h" +#include "VersionUpdate.h" +#include "VMProtectSDK.h" +extern Verify* g_verify; +//extern Manager* g_manager; +extern Config* g_config; + +extern const char* g_gameTypes[]; + +#define VERSION (QString)(VersionUpdate::GetVersion()) + +extern QString dateFormat(QString source); + diff --git a/CrownClient/Handicap.cpp b/CrownClient/Handicap.cpp new file mode 100644 index 0000000..1e19813 --- /dev/null +++ b/CrownClient/Handicap.cpp @@ -0,0 +1,469 @@ +#include "Handicap.h" +#include +#include +#include "Global.h" +#include "Utils.h" + +Handicap::Handicap(QWidget *parent) + : QDialog(parent) +{ + ui.setupUi(this); + + // 设置窗口图标 + this->setWindowIcon(QIcon(":/images/Images/client.ico")); + // 设置窗口标题 + this->setWindowTitle("注单盘口判断处理"); + // 设置为对话框窗口 + setWindowFlags(Qt::Dialog); + // 设置窗口仅有关闭按钮 + setWindowFlags(Qt::WindowCloseButtonHint); + setFixedSize(883,552); + + + // 设置盘口判断方案样式 + ui.solutionComboBox->setItemData(0, QBrush(QColor(Qt::red)), Qt::ForegroundRole); + ui.solutionComboBox->setItemData(1, QBrush(QColor(Qt::darkGreen)), Qt::ForegroundRole); + ui.solutionComboBox->setItemData(2, QBrush(QColor(Qt::darkBlue)), Qt::ForegroundRole); + + ui.solutionComboBox->setItemData(3, QBrush(QColor(0xFF,0xAA,0x00)), Qt::ForegroundRole); + ui.solutionComboBox->setItemData(4, QBrush(QColor(0xAA,0x55,0xFF)), Qt::ForegroundRole); + ui.solutionComboBox->setItemData(5, QBrush(QColor(Qt::darkRed)), Qt::ForegroundRole); + ui.solutionComboBox->setItemData(6, QBrush(QColor(0xFF,0xAA,0xFF)), Qt::ForegroundRole); + + // 存在重载必须强制类型转换 + connect(ui.solutionComboBox, static_cast(&QComboBox::currentIndexChanged),this,&Handicap::slotSolutionChange); + + + + ui.projectCheckBox->setChecked(g_config->handicapProject()); + ui.typeCheckBox->setChecked(g_config->handicapType()); + ui.solutionComboBox->setCurrentText(g_config->handicapMethod()); + + if (ui.solutionComboBox->currentText() == "A") + { + ui.solutionComboBox->setStyleSheet("QComboBox{color:red;}"); + } + else if (ui.solutionComboBox->currentText() == "B") + { + ui.solutionComboBox->setStyleSheet("QComboBox{color:darkGreen;}"); + } + else if (ui.solutionComboBox->currentText() == "C") + { + ui.solutionComboBox->setStyleSheet("QComboBox{color:darkBlue;}"); + } + else if (ui.solutionComboBox->currentText() == "S") + { + ui.solutionComboBox->setStyleSheet("QComboBox{color:#ffaa00;}"); + } + else if (ui.solutionComboBox->currentText() == "X") + { + ui.solutionComboBox->setStyleSheet("QComboBox{color:#aa55ff;}"); + } + else if (ui.solutionComboBox->currentText() == "Y") + { + ui.solutionComboBox->setStyleSheet("QComboBox{color:darkRed;}"); + } + else if (ui.solutionComboBox->currentText() == "Z") + { + ui.solutionComboBox->setStyleSheet("QComboBox{color:#ffaaff;}"); + } + ui.tableWidget->setColumnCount(10); + ui.tableWidget->setHorizontalHeaderLabels({"注单项目", "让球","受让","大","小","主队大","主队小","客队大","客队小","补单" }); + ui.tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + ui.tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); + ui.tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch); + ui.tableWidget->horizontalHeader()->resizeSection(0, 50); + + + for (int i = 0; i < 9; i++) + { + ui.tableWidget->insertRow(i); + ui.tableWidget->setItem(i, 0, new QTableWidgetItem(g_gameTypes[i])); + ui.tableWidget->setItem(i, 1, new QTableWidgetItem("C")); + ui.tableWidget->item(i, 1)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + ui.tableWidget->item(i, 1)->setForeground(QBrush(QColor(Qt::darkBlue))); + ui.tableWidget->setItem(i, 2, new QTableWidgetItem("C")); + ui.tableWidget->item(i, 2)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + ui.tableWidget->item(i, 2)->setForeground(QBrush(QColor(Qt::darkBlue))); + ui.tableWidget->setItem(i, 3, new QTableWidgetItem("C")); + ui.tableWidget->item(i, 3)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + ui.tableWidget->item(i, 3)->setForeground(QBrush(QColor(Qt::darkBlue))); + ui.tableWidget->setItem(i, 4, new QTableWidgetItem("C")); + ui.tableWidget->item(i, 4)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + ui.tableWidget->item(i, 4)->setForeground(QBrush(QColor(Qt::darkBlue))); + ui.tableWidget->setItem(i, 5, new QTableWidgetItem("C")); + ui.tableWidget->item(i, 5)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + ui.tableWidget->item(i, 5)->setForeground(QBrush(QColor(Qt::darkBlue))); + ui.tableWidget->setItem(i, 6, new QTableWidgetItem("C")); + ui.tableWidget->item(i, 6)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + ui.tableWidget->item(i, 6)->setForeground(QBrush(QColor(Qt::darkBlue))); + ui.tableWidget->setItem(i, 7, new QTableWidgetItem("C")); + ui.tableWidget->item(i, 7)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + ui.tableWidget->item(i, 7)->setForeground(QBrush(QColor(Qt::darkBlue))); + ui.tableWidget->setItem(i, 8, new QTableWidgetItem("C")); + ui.tableWidget->item(i, 8)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + ui.tableWidget->item(i, 8)->setForeground(QBrush(QColor(Qt::darkBlue))); + + QWidget* widget = new QWidget; + QHBoxLayout* layout = new QHBoxLayout; + QCheckBox* box = new QCheckBox; + layout->addWidget(box); + layout->setContentsMargins(0, 0, 0, 0); + layout->setAlignment(box, Qt::AlignCenter); + widget->setLayout(layout); + ui.tableWidget->setCellWidget(i, 9, widget); + } + QList> handicap = g_config->handicap(); + for (int i = 0; i < handicap.count(); i++) + { + if (handicap[i]["COLUMN"] != "9") + { + ui.tableWidget->item(handicap[i]["ROW"].toInt(), handicap[i]["COLUMN"].toInt())->setText(handicap[i]["SOLUTION"]); + // 设置对应的颜色 + if (handicap[i]["SOLUTION"] == "A") + { + ui.tableWidget->item(handicap[i]["ROW"].toInt(), handicap[i]["COLUMN"].toInt())->setForeground(QBrush(QColor(Qt::red))); + } + else if (handicap[i]["SOLUTION"] == "B") + { + ui.tableWidget->item(handicap[i]["ROW"].toInt(), handicap[i]["COLUMN"].toInt())->setForeground(QBrush(QColor(Qt::darkGreen))); + } + else if (handicap[i]["SOLUTION"] == "C") + { + ui.tableWidget->item(handicap[i]["ROW"].toInt(), handicap[i]["COLUMN"].toInt())->setForeground(QBrush(QColor(Qt::darkBlue))); + } + else if (handicap[i]["SOLUTION"] == "S") + { + ui.tableWidget->item(handicap[i]["ROW"].toInt(), handicap[i]["COLUMN"].toInt())->setForeground(QBrush(QColor(0xFF, 0xAA, 0x00))); + } + else if (handicap[i]["SOLUTION"] == "X") + { + ui.tableWidget->item(handicap[i]["ROW"].toInt(), handicap[i]["COLUMN"].toInt())->setForeground(QBrush(QColor(0xAA, 0x55, 0xFF))); + } + else if (handicap[i]["SOLUTION"] == "Y") + { + ui.tableWidget->item(handicap[i]["ROW"].toInt(), handicap[i]["COLUMN"].toInt())->setForeground(QBrush(QColor(Qt::darkRed))); + } + else if (handicap[i]["SOLUTION"] == "Z") + { + ui.tableWidget->item(handicap[i]["ROW"].toInt(), handicap[i]["COLUMN"].toInt())->setForeground(QBrush(QColor(0xFF, 0xAA, 0xFF))); + } + } + else + { + QCheckBox* checkBox = reinterpret_cast(ui.tableWidget->cellWidget(handicap[i]["ROW"].toInt(), handicap[i]["COLUMN"].toInt())->layout()->itemAt(0)->widget()); + if (checkBox) + { + // 设置选中状态 + if (handicap[i]["REBET"] == "TRUE") + { + checkBox->setChecked(true); + } + else + { + checkBox->setChecked(false); + } + } + + + } + } + + connect(ui.setButton,&QPushButton::clicked,this,&Handicap::slotSetSolution); + +} + +Handicap::~Handicap() +{} + + + +void Handicap::slotSolutionChange(int index) +{ + switch (index) + { + case 0: + ui.solutionComboBox->setStyleSheet("QComboBox{color:red;}"); + break; + case 1: + ui.solutionComboBox->setStyleSheet("QComboBox{color:darkGreen;}"); + break; + case 2: + ui.solutionComboBox->setStyleSheet("QComboBox{color:darkBlue;}"); + break; + case 3: + ui.solutionComboBox->setStyleSheet("QComboBox{color:#ffaa00;}"); + break; + case 4: + ui.solutionComboBox->setStyleSheet("QComboBox{color:#aa55ff;}"); + break; + case 5: + ui.solutionComboBox->setStyleSheet("QComboBox{color:darkRed;}"); + break; + default: + ui.solutionComboBox->setStyleSheet("QComboBox{color:#ffaaff;}"); + break; + } + +} + +void Handicap::slotSetSolution() +{ + QString project = ui.projectComboBox->currentText(); + QString type = ui.typeComboBox->currentText(); + QString solution = ui.solutionComboBox->currentText(); + // 单个 + if (ui.projectCheckBox->isChecked() && ui.typeCheckBox->isChecked()) + { + int row = 0, column = 0; + for (row; row < ui.tableWidget->rowCount(); row++) + { + QString rowText = ui.tableWidget->item(row, 0)->text(); + if (rowText == project) + { + break; + } + } + for (column; column < ui.tableWidget->columnCount(); column++) + { + QString columnText = ui.tableWidget->horizontalHeaderItem(column)->text(); + if (columnText == type) + { + break; + } + } + ui.tableWidget->item(row,column)->setText(solution); + if (solution == "A") + { + ui.tableWidget->item(row,column)->setForeground(QBrush(QColor(Qt::red))); + } + else if (solution == "B") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(Qt::darkGreen))); + } + else if (solution == "C") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(Qt::darkBlue))); + } + else if (solution == "S") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(0xFF, 0xAA, 0x00))); + } + else if (solution == "X") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(0xAA, 0x55, 0xFF))); + } + else if (solution == "Y") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(Qt::darkRed))); + } + else if (solution == "Z") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(0xFF, 0xAA, 0xFF))); + } + } + else if (ui.projectCheckBox->isChecked() && !ui.typeCheckBox->isChecked()) + { + int row = 0, column = 0; + for (row; row < ui.tableWidget->rowCount(); row++) + { + QString rowText = ui.tableWidget->item(row, 0)->text(); + if (rowText == project) + { + break; + } + } + for (column; column < ui.tableWidget->columnCount(); column++) + { + // 第一列 最后一列跳过 + if (column == 0 || column == ui.tableWidget->columnCount() - 1) + { + continue; + } + ui.tableWidget->item(row, column)->setText(solution); + if (solution == "A") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(Qt::red))); + } + else if (solution == "B") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(Qt::darkGreen))); + } + else if (solution == "C") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(Qt::darkBlue))); + } + else if (solution == "S") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(0xFF, 0xAA, 0x00))); + } + else if (solution == "X") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(0xAA, 0x55, 0xFF))); + } + else if (solution == "Y") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(Qt::darkRed))); + } + else if (solution == "Z") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(0xFF, 0xAA, 0xFF))); + } + } + } + else if (!ui.projectCheckBox->isChecked() && ui.typeCheckBox->isChecked()) + { + int row = 0, column = 0; + for (column; column < ui.tableWidget->columnCount(); column++) + { + QString columnText = ui.tableWidget->horizontalHeaderItem(column)->text(); + if (columnText == type) + { + break; + } + } + for (row; row < ui.tableWidget->rowCount(); row++) + { + ui.tableWidget->item(row, column)->setText(solution); + if (solution == "A") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(Qt::red))); + } + else if (solution == "B") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(Qt::darkGreen))); + } + else if (solution == "C") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(Qt::darkBlue))); + } + else if (solution == "S") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(0xFF, 0xAA, 0x00))); + } + else if (solution == "X") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(0xAA, 0x55, 0xFF))); + } + else if (solution == "Y") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(Qt::darkRed))); + } + else if (solution == "Z") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(0xFF, 0xAA, 0xFF))); + } + } + } + else + { + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + // 第一列 最后一列跳过 + if (column == 0 || column == ui.tableWidget->columnCount() - 1) + { + continue; + } + ui.tableWidget->item(row, column)->setText(solution); + if (solution == "A") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(Qt::red))); + } + else if (solution == "B") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(Qt::darkGreen))); + } + else if (solution == "C") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(Qt::darkBlue))); + } + else if (solution == "S") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(0xFF, 0xAA, 0x00))); + } + else if (solution == "X") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(0xAA, 0x55, 0xFF))); + } + else if (solution == "Y") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(Qt::darkRed))); + } + else if (solution == "Z") + { + ui.tableWidget->item(row, column)->setForeground(QBrush(QColor(0xFF, 0xAA, 0xFF))); + } + } + } + + } + // 整列 +} + +void Handicap::closeEvent(QCloseEvent * event) +{ + QList> list; + + // 遍历所有行 + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + // 获取第一列标题(注单项目) + QString rowText = ui.tableWidget->item(row, 0)->text(); + // 获取补单选择状态 + QCheckBox* checkBox = reinterpret_cast(ui.tableWidget->cellWidget(row, ui.tableWidget->columnCount() - 1)->layout()->itemAt(0)->widget()); + bool rebet = checkBox->isChecked(); + // 遍历所有列 + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + // 第一列跳过 + if (column == 0) + { + continue; + } + // 获取列标题 + QString columnText = ui.tableWidget->horizontalHeaderItem(column)->text(); + + // 最后一列记录checkbox + if (column == ui.tableWidget->columnCount() - 1) + { + QMap map; + map["ROW"] = QString::number(row); + map["COLUMN"] = QString::number(column); + QCheckBox* checkBox = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(0)->widget()); + if (checkBox->isChecked()) + { + map["REBET"] = "TRUE"; + } + else + { + map["REBET"] = "FALSE"; + } + map["project"] = rowText; + list.append(map); + } + else + { + // 根据名称获取wtype rtype等参数 + QMap map = Utils::instance().type(rowText, columnText); + map["ROW"] = QString::number(row); + map["COLUMN"] = QString::number(column); + map["SOLUTION"] = ui.tableWidget->item(row, column)->text(); + if (rebet) + { + map["REBET"] = "TRUE"; + } + else + { + map["REBET"] = "FALSE"; + } + list.append(map); + } + + + } + } + + g_config->setHandicap(list); +} \ No newline at end of file diff --git a/CrownClient/Handicap.h b/CrownClient/Handicap.h new file mode 100644 index 0000000..45389f9 --- /dev/null +++ b/CrownClient/Handicap.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include "ui_Handicap.h" + +class Handicap : public QDialog +{ + Q_OBJECT + +public: + Handicap(QWidget *parent = nullptr); + ~Handicap(); + +private: + Ui::HandicapClass ui; + +private slots: + void slotSolutionChange(int index); + void slotSetSolution(); +private: + // 重写窗口关闭事件 + void closeEvent(QCloseEvent* event); + +}; diff --git a/CrownClient/Handicap.ui b/CrownClient/Handicap.ui new file mode 100644 index 0000000..9423f83 --- /dev/null +++ b/CrownClient/Handicap.ui @@ -0,0 +1,318 @@ + + + HandicapClass + + + + 0 + 0 + 902 + 715 + + + + Handicap + + + + + + + + + + + + + + + 注单项目: + + + + + + + + 足球滚球全场 + + + + + 足球滚球上半场 + + + + + 足球今日全场 + + + + + 足球今日上半场 + + + + + 足球早盘全场 + + + + + 足球早盘上半场 + + + + + 篮球滚球全部 + + + + + 篮球今日全部 + + + + + 篮球早盘全部 + + + + + + + + 注单类型: + + + + + + + + 让球 + + + + + 受让 + + + + + 大 + + + + + 小 + + + + + 主队大 + + + + + 主队小 + + + + + 客队大 + + + + + 客队小 + + + + + + + + 设置处理 + + + + + + + 盘口处理: + + + + + + + + 60 + 0 + + + + + 12 + 75 + true + + + + + A + + + + + B + + + + + C + + + + + S + + + + + X + + + + + Y + + + + + Z + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + + + <html><head/><body><p><span style=" font-weight:600; color:#f70004;">A:跟单任何盘口 </span>①原盘口 ②[让球|大](变小最近)盘口 [受让|小](变大最近)盘口 ③(变化最近)盘口</p></body></html> + + + + + + + <html><head/><body><p><span style=" font-weight:600; color:#00aa00;">B:盘口变化不跟 </span>只查找原盘口</p></body></html> + + + + + + + <html><head/><body><p><span style=" font-weight:600; color:#0000ff;">C:盘口变差不跟</span> ①原盘口 ②[让球|大](变小最近)盘口 [受让|小](变大最近)盘口</p></body></html> + + + + + + + + + + + + + + + + + + <html><head/><body><p><span style=" font-weight:600; color:#ffaa00;">S: </span><span style=" font-weight:600; color:#00aa00;">B③次 </span><span style=" font-weight:600; color:#ffaa00;">-&gt; </span><span style=" font-weight:600; color:#0000ff;">C</span></p></body></html> + + + + + + + + + + + + + + + + <html><head/><body><p><span style=" font-weight:600; color:#aa55ff;">X</span><span style=" font-weight:600;">: </span><span style=" font-weight:600; color:#00aa00;">B③次 </span><span style=" font-weight:600; color:#aa55ff;">-&gt; </span><span style=" font-weight:600; color:#ff0000;">A</span></p></body></html> + + + + + + + + + + + + + + + + <html><head/><body><p><span style=" font-weight:600; color:#aa5500;">Y: </span><span style=" font-weight:600; color:#0055ff;">C③次 </span><span style=" font-weight:600; color:#aa5500;">-&gt; </span><span style=" font-weight:600; color:#ff0000;">A</span></p></body></html> + + + + + + + + + + + + + + + + <html><head/><body><p><span style=" font-weight:600; color:#ffaaff;">Z: </span><span style=" font-weight:600; color:#00aa00;">B③次 </span><span style=" font-weight:600; color:#ffaaff;">-&gt; </span><span style=" font-weight:600; color:#0000ff;">C③次</span><span style=" font-weight:600; color:#ffaaff;"> -&gt; </span><span style=" font-weight:600; color:#ff0000;">A</span></p></body></html> + + + + + + + + + + + + + + diff --git a/CrownClient/Images/client.ico b/CrownClient/Images/client.ico new file mode 100644 index 0000000..191c2b4 Binary files /dev/null and b/CrownClient/Images/client.ico differ diff --git a/CrownClient/Images/crownTime.png b/CrownClient/Images/crownTime.png new file mode 100644 index 0000000..395f263 Binary files /dev/null and b/CrownClient/Images/crownTime.png differ diff --git a/CrownClient/Images/green.png b/CrownClient/Images/green.png new file mode 100644 index 0000000..5efc382 Binary files /dev/null and b/CrownClient/Images/green.png differ diff --git a/CrownClient/Images/localTime.png b/CrownClient/Images/localTime.png new file mode 100644 index 0000000..47b0051 Binary files /dev/null and b/CrownClient/Images/localTime.png differ diff --git a/CrownClient/Images/red.png b/CrownClient/Images/red.png new file mode 100644 index 0000000..9440058 Binary files /dev/null and b/CrownClient/Images/red.png differ diff --git a/CrownClient/Images/start.png b/CrownClient/Images/start.png new file mode 100644 index 0000000..ddd52c3 Binary files /dev/null and b/CrownClient/Images/start.png differ diff --git a/CrownClient/Images/stop.png b/CrownClient/Images/stop.png new file mode 100644 index 0000000..97bbd5a Binary files /dev/null and b/CrownClient/Images/stop.png differ diff --git a/CrownClient/Images/user.png b/CrownClient/Images/user.png new file mode 100644 index 0000000..52c6ad6 Binary files /dev/null and b/CrownClient/Images/user.png differ diff --git a/CrownClient/Images/yellow.png b/CrownClient/Images/yellow.png new file mode 100644 index 0000000..7758038 Binary files /dev/null and b/CrownClient/Images/yellow.png differ diff --git a/CrownClient/Login.cpp b/CrownClient/Login.cpp new file mode 100644 index 0000000..5af0981 --- /dev/null +++ b/CrownClient/Login.cpp @@ -0,0 +1,126 @@ +#include "Login.h" +#include "Global.h" +#include "CrownClient.h" +#include "AppInstanceManager.h" +Login::Login(QWidget* parent) + : QMainWindow(parent) +{ + ui.setupUi(this); + + + + // 在构造函数中添加: + connect(AppInstanceManager::instance(), &AppInstanceManager::raiseRequested, + this, [this]() { + show(); + raise(); + activateWindow(); + }); + + // 设置固定窗口大小 + this->setFixedSize(394, 158); + // Dialog窗口去除最小化最大化按钮 + setWindowFlags(Qt::Dialog); + setWindowFlags(Qt::WindowCloseButtonHint); + // 设置窗口标题 + this->setWindowTitle("金运来皇冠跟单软件(客户端)"); + // 设置窗口图标 + this->setWindowIcon(QIcon(":/images/Images/client.ico")); + // 隐藏自动登录倒计时 + ui.timeLabel->setHidden(true); + + // 连接登录按钮信号和槽 + connect(ui.LoginButton, &QPushButton::clicked, this, &Login::slotLogin); + + m_timer = new QTimer(); + + // 读取配置 + ui.usernameEdit->setText(g_config->verifyUsername()); + ui.passwordEdit->setText(g_config->verifyPassword()); + ui.autoLoginCheck->setChecked(g_config->autoLogin()); + + // 判断自动登录 + if (ui.autoLoginCheck->isChecked() && !ui.usernameEdit->text().isNull() && !ui.passwordEdit->text().isNull()) + { + ui.timeLabel->setHidden(false); + m_time = 5; + connect(m_timer, &QTimer::timeout, this, [&]() { + if (m_time > 0) + { + m_time--; + ui.timeLabel->setText("

" + QString::number(m_time) + "

"); + } + else + { + if (m_timer->isActive()) + { + emit ui.LoginButton->clicked(); + } + } + }); + // 启动定时器 + if (!m_timer->isActive()) + { + m_timer->start(1000); + } + } + + +} + +Login::~Login() +{} + + +void Login::slotLogin() +{ + VMProtectBegin("Login"); + // 停止定时器 + if (m_timer->isActive()) + { + m_timer->stop(); + } + + // 禁用登录按钮 + ui.LoginButton->setDisabled(true); + + // 获取账号密码 + QString username = ui.usernameEdit->text(); + QString password = ui.passwordEdit->text(); + + if (username.isEmpty() || password.isEmpty()) + { + QMessageBox::warning(this, "错误", "账号或密码为空"); + } + else + { + QString result; + + + if (g_verify->Login(username, password, result)) + { + // 断开所有信号连接(防止残留响应) + disconnect(AppInstanceManager::instance(), nullptr, this, nullptr); + CrownClient* client = new CrownClient(); + client->show(); + this->close(); + + + } + else + { + // 如果密码正确考虑OpenSSL库问题 + QMessageBox::warning(this, "登录失败", result); + } + } + // 激活登录按钮 + ui.LoginButton->setDisabled(false); + VMProtectEnd(); +} + +void Login::closeEvent(QCloseEvent* event) +{ + g_config->setVerifyUsername(ui.usernameEdit->text()); + g_config->setVerifyPassword(ui.passwordEdit->text()); + g_config->setAutoLogin(ui.autoLoginCheck->isChecked()); +} \ No newline at end of file diff --git a/CrownClient/Login.h b/CrownClient/Login.h new file mode 100644 index 0000000..2dfe43c --- /dev/null +++ b/CrownClient/Login.h @@ -0,0 +1,30 @@ +#pragma once + +#include +#include +#include +#include +#include "ui_Login.h" + + +class Login : public QMainWindow +{ + Q_OBJECT + +public: + Login(QWidget* parent = nullptr); + ~Login(); +private: + QTimer* m_timer; + int m_time; + + + +private: + void closeEvent(QCloseEvent* event); +private slots: + void slotLogin(); +private: + Ui::LoginClass ui; + +}; diff --git a/CrownClient/Login.ui b/CrownClient/Login.ui new file mode 100644 index 0000000..6180cbc --- /dev/null +++ b/CrownClient/Login.ui @@ -0,0 +1,108 @@ + + + LoginClass + + + + 0 + 0 + 394 + 158 + + + + Login + + + + + + + + 120 + 120 + + + + image: url(:/images/Images/client.ico); + + + + + + + + + + + + + + + + + + + + 账号: + + + + + + + + + + + + + + 密码: + + + + + + + + + + + + + + <html><head/><body><p><span style=" color:#ff0000;">5秒</span></p></body></html> + + + + + + + 自动登录 + + + + + + + 登录 + + + + + + + + + + + + + + + + + + + diff --git a/CrownClient/MessageHandle.h b/CrownClient/MessageHandle.h new file mode 100644 index 0000000..9694cf3 --- /dev/null +++ b/CrownClient/MessageHandle.h @@ -0,0 +1,69 @@ +#pragma once +#include +#include +#include +#include +#include +#include + +// 自定义日志处理器 +void message_handle(QtMsgType type, const QMessageLogContext& context, const QString& msg) +{ + // 获取时间戳 + QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz"); + + // 获取日志级别 + QString logLevel; + switch (type) { + case QtDebugMsg: + logLevel = "DEBUG"; + break; + case QtWarningMsg: + logLevel = "WARNING"; + break; + case QtCriticalMsg: + logLevel = "CRITICAL"; + break; + case QtFatalMsg: + logLevel = "FATAL"; + break; + } + + // 获取文件名、行号、函数名 + QString fileName = context.file; + int lineNumber = context.line; + QString functionName = context.function; + + // 格式化日志信息 + QString logMessage = QString("[%1] [%2] [%3:%4 - %5] %6") + .arg(timestamp) + .arg(logLevel) + .arg(fileName) + .arg(lineNumber) + .arg(functionName) + .arg(msg); + + // 方案1:在可执行文件同目录 + QString logPath = QCoreApplication::applicationDirPath() + "/application_client.log"; + + // 方案2:在用户文档目录 + // QString logPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/MyApp/application.log"; + + // 方案3:在临时目录 + // QString logPath = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + "/application.log"; + + // 方案4:在当前工作目录(VS 可能设置的工作目录) + // QString logPath = "application.log"; + + // 输出到文件 + QFile logFile(logPath); + if (logFile.open(QIODevice::Append | QIODevice::Text)) { + QTextStream out(&logFile); + out << logMessage << Qt::endl; // 使用 Qt::endl + logFile.close(); + } + + // 也可以将日志输出到控制台 + fprintf(stdout, "%s\n", logMessage.toLocal8Bit().constData()); + fflush(stdout); // 强制刷新标准输出 +} diff --git a/CrownClient/Notice.cpp b/CrownClient/Notice.cpp new file mode 100644 index 0000000..97f1ac6 --- /dev/null +++ b/CrownClient/Notice.cpp @@ -0,0 +1,39 @@ +#include "Notice.h" +#include "Global.h" +Notice::Notice(QWidget *parent) + : QWidget(parent) +{ + ui.setupUi(this); + + + // 设置固定窗口大小 + this->setFixedSize(394, 158); + // Dialog窗口去除最小化最大化按钮 + setWindowFlags(Qt::Dialog); + setWindowFlags(Qt::WindowCloseButtonHint); + // 设置窗口标题 + this->setWindowTitle("推送设置"); + // 设置窗口图标 + this->setWindowIcon(QIcon(":/images/Images/client.ico")); + + + ui.checkBox->setChecked(g_config->notice_status()); + ui.lineEdit->setText(g_config->notice_account()); + + connect(ui.push_button, &QPushButton::clicked, this, [&]() { + //qDebug() << "推送账户" << g_config->notice_account(); + g_verify->push_msg("test_push", "客户端", ui.lineEdit->text(), QMap()); + + }); + + +} + +Notice::~Notice() +{} + +void Notice::closeEvent(QCloseEvent * event) +{ + g_config->set_notice_status(ui.checkBox->isChecked()); + g_config->set_notice_account(ui.lineEdit->text()); +} diff --git a/CrownClient/Notice.h b/CrownClient/Notice.h new file mode 100644 index 0000000..a6854d8 --- /dev/null +++ b/CrownClient/Notice.h @@ -0,0 +1,17 @@ +#pragma once + +#include +#include "ui_Notice.h" + +class Notice : public QWidget +{ + Q_OBJECT + +public: + Notice(QWidget *parent = nullptr); + ~Notice(); +private: + Ui::NoticeClass ui; +public: + void closeEvent(QCloseEvent* event); +}; diff --git a/CrownClient/Notice.ui b/CrownClient/Notice.ui new file mode 100644 index 0000000..a7d3f8f --- /dev/null +++ b/CrownClient/Notice.ui @@ -0,0 +1,52 @@ + + + NoticeClass + + + + 0 + 0 + 376 + 153 + + + + Notice + + + + + + + + 启用通知 + + + + + + + + + + 测试通知 + + + + + + + + + 填写Telegram或邮箱账号即可 +支持私聊或群通知 +需先添加机器人 JYL88_bot 为好友或拉入群聊 + + + + + + + + + diff --git a/CrownClient/Odds.cpp b/CrownClient/Odds.cpp new file mode 100644 index 0000000..d1328dd --- /dev/null +++ b/CrownClient/Odds.cpp @@ -0,0 +1,320 @@ +#include "Odds.h" +#include +#include "Global.h" +#include "Utils.h" + +Odds::Odds(QWidget *parent) + : QWidget(parent) +{ + ui.setupUi(this); + + // 设置窗口图标 + this->setWindowIcon(QIcon(":/images/Images/client.ico")); + // 设置窗口标题 + this->setWindowTitle("注单赔率判断处理"); + + + + ui.tableWidget->setColumnCount(15); + ui.tableWidget->setHorizontalHeaderLabels({"注单项目","让球","受让","大","小","独赢主","独赢客","独赢和","单","双","主队大","主队小","客队大","客队小","补单" }); + + + ui.tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + ui.tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); + ui.tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch); + ui.tableWidget->horizontalHeader()->resizeSection(0, 50); + + + for (int i = 0; i < 9; i++) + { + ui.tableWidget->insertRow(i); + ui.tableWidget->setItem(i, 0, new QTableWidgetItem(g_gameTypes[i])); + + for (int j = 0; j < 15; j++) + { + if (j == 0) + { + continue; + } + + if (j == 14) + { + QWidget* widget = new QWidget; + QHBoxLayout* layout = new QHBoxLayout; + QCheckBox* box = new QCheckBox; + layout->addWidget(box); + layout->setContentsMargins(0, 0, 0, 0); + layout->setAlignment(box, Qt::AlignCenter); + widget->setLayout(layout); + ui.tableWidget->setCellWidget(i, j, widget); + } + else + { + QGridLayout* gridLayout = new QGridLayout(); + gridLayout->setContentsMargins(0, 0, 0, 0); + + QLabel* highLabel = new QLabel("0"); + QLabel* lowLabel = new QLabel("1"); + QLabel* upLabel = new QLabel("2"); + QLabel* downLabel = new QLabel("3"); + gridLayout->addWidget(highLabel, 0, 0, Qt::AlignCenter); + gridLayout->addWidget(upLabel, 0, 1, Qt::AlignCenter); + gridLayout->addWidget(lowLabel, 1, 0, Qt::AlignCenter); + gridLayout->addWidget(downLabel, 1, 1, Qt::AlignCenter); + + gridLayout->setAlignment(highLabel, Qt::AlignCenter); + gridLayout->setAlignment(upLabel, Qt::AlignCenter); + gridLayout->setAlignment(lowLabel, Qt::AlignCenter); + gridLayout->setAlignment(downLabel, Qt::AlignCenter); + + QWidget* widget = new QWidget(); + widget->setLayout(gridLayout); + ui.tableWidget->setCellWidget(i, j, widget); + + } + } + } + + QList> odds = g_config->odds(); + for (int i = 0; i < odds.count(); i++) + { + QMap map = odds[i]; + //qDebug() << map; + if (map["COLUMN"]!="14") + { + QLabel* high = reinterpret_cast(ui.tableWidget->cellWidget(map["ROW"].toInt(), map["COLUMN"].toInt())->layout()->itemAt(0)->widget()); + QLabel* up = reinterpret_cast(ui.tableWidget->cellWidget(map["ROW"].toInt(), map["COLUMN"].toInt())->layout()->itemAt(1)->widget()); + QLabel* low = reinterpret_cast(ui.tableWidget->cellWidget(map["ROW"].toInt(), map["COLUMN"].toInt())->layout()->itemAt(2)->widget()); + QLabel* down = reinterpret_cast(ui.tableWidget->cellWidget(map["ROW"].toInt(), map["COLUMN"].toInt())->layout()->itemAt(3)->widget()); + + high->setText(map["HIGH"]); + up->setText(map["UP"]); + low->setText(map["LOW"]); + down->setText(map["DOWN"]); + } + else + { + QCheckBox* checkBox = reinterpret_cast(ui.tableWidget->cellWidget(map["ROW"].toInt(), map["COLUMN"].toInt())->layout()->itemAt(0)->widget()); + if (map["REBET"] == "TRUE") + { + checkBox->setChecked(true); + } + else + { + checkBox->setChecked(false); + } + } + } + + // 读取配置 + ui.projectCheckBox->setChecked(g_config->oddsProject()); + ui.projectCombo->setCurrentIndex(g_config->oddsProjectIndex()); + ui.typeCheckBox->setChecked(g_config->oddsType()); + ui.typeCombo->setCurrentIndex(g_config->oddsTypeIndex()); + ui.highEdit->setText(QString::number(g_config->oddsHigh())); + ui.lowEdit->setText(QString::number(g_config->oddsLow())); + ui.upEdit->setText(QString::number(g_config->oddsUp())); + ui.downEdit->setText(QString::number(g_config->oddsDown())); + + connect(ui.setOddsButton, &QPushButton::clicked, this, &Odds::slotSetOdds); + +} + +Odds::~Odds() +{ + +} + + +void Odds::slotSetOdds() +{ + QString project = ui.projectCombo->currentText(); + QString type = ui.typeCombo->currentText(); + + // 单个 + if (ui.projectCheckBox->isChecked() && ui.typeCheckBox->isChecked()) + { + int row = 0, column = 0; + for (row; row < ui.tableWidget->rowCount(); row++) + { + QString rowText = ui.tableWidget->item(row, 0)->text(); + if (rowText == project) + { + break; + } + } + for (column; column < ui.tableWidget->columnCount(); column++) + { + QString columnText = ui.tableWidget->horizontalHeaderItem(column)->text(); + if (columnText == type) + { + break; + } + } + QLabel* high = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(0)->widget()); + QLabel* up = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(1)->widget()); + QLabel* low = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(2)->widget()); + QLabel* down = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(3)->widget()); + + high->setText(ui.highEdit->text()); + up->setText(ui.upEdit->text()); + low->setText(ui.lowEdit->text()); + down->setText(ui.downEdit->text()); + + + } + else if (ui.projectCheckBox->isChecked() && !ui.typeCheckBox->isChecked()) + { + int row = 0, column = 0; + for (row; row < ui.tableWidget->rowCount(); row++) + { + QString rowText = ui.tableWidget->item(row, 0)->text(); + if (rowText == project) + { + break; + } + } + for (column; column < ui.tableWidget->columnCount(); column++) + { + // 第一列 最后一列跳过 + if (column == 0 || column == ui.tableWidget->columnCount() - 1) + { + continue; + } + QLabel* high = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(0)->widget()); + QLabel* up = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(1)->widget()); + QLabel* low = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(2)->widget()); + QLabel* down = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(3)->widget()); + high->setText(ui.highEdit->text()); + up->setText(ui.upEdit->text()); + low->setText(ui.lowEdit->text()); + down->setText(ui.downEdit->text()); + } + } + else if (!ui.projectCheckBox->isChecked() && ui.typeCheckBox->isChecked()) + { + int row = 0, column = 0; + for (column; column < ui.tableWidget->columnCount(); column++) + { + QString columnText = ui.tableWidget->horizontalHeaderItem(column)->text(); + if (columnText == type) + { + break; + } + } + for (row; row < ui.tableWidget->rowCount(); row++) + { + QLabel* high = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(0)->widget()); + QLabel* up = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(1)->widget()); + QLabel* low = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(2)->widget()); + QLabel* down = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(3)->widget()); + high->setText(ui.highEdit->text()); + up->setText(ui.upEdit->text()); + low->setText(ui.lowEdit->text()); + down->setText(ui.downEdit->text()); + } + } + else + { + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + // 第一列 最后一列跳过 + if (column == 0 || column == ui.tableWidget->columnCount() - 1) + { + continue; + } + QLabel* high = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(0)->widget()); + QLabel* up = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(1)->widget()); + QLabel* low = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(2)->widget()); + QLabel* down = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(3)->widget()); + high->setText(ui.highEdit->text()); + up->setText(ui.upEdit->text()); + low->setText(ui.lowEdit->text()); + down->setText(ui.downEdit->text()); + } + } + + } +} + +void Odds::closeEvent(QCloseEvent * event) +{ + QList> list; + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + QString rowText = ui.tableWidget->item(row, 0)->text(); + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + if (column == 0) + { + continue; + } + QString columnText = ui.tableWidget->horizontalHeaderItem(column)->text(); + + // 判断是否勾选补单 + QCheckBox* rebet_checkbox = reinterpret_cast(ui.tableWidget->cellWidget(row, ui.tableWidget->columnCount() - 1)->layout()->itemAt(0)->widget()); + bool rebet = rebet_checkbox->isChecked(); + if (column == ui.tableWidget->columnCount() - 1) + { + QMap map; + map["ROW"] = QString::number(row); + map["COLUMN"] = QString::number(column); + QCheckBox* checkBox = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(0)->widget()); + if (checkBox->isChecked()) + { + map["REBET"] = "TRUE"; + } + else + { + map["REBET"] = "FALSE"; + } + map["project"] = rowText; + list.append(map); + } + else + { + QMap map = Utils::instance().type(rowText, columnText); + map["ROW"] = QString::number(row); + map["COLUMN"] = QString::number(column); + + QLabel* high = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(0)->widget()); + QLabel* up = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(1)->widget()); + QLabel* low = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(2)->widget()); + QLabel* down = reinterpret_cast(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(3)->widget()); + + map["HIGH"] = high->text(); + map["UP"] = up->text(); + map["LOW"] = low->text(); + map["DOWN"] = down->text(); + map["project"] = rowText; + + if (rebet) + { + map["REBET"] = "TRUE"; + } + else + { + map["REBET"] = "FALSE"; + } + //map["type"] = columnText; + list.append(map); + } + } + } + + g_config->setOdds(list); + + g_config->setOddsProject(ui.projectCheckBox->isChecked()); + g_config->setOddsProjectIndex(ui.projectCombo->currentIndex()); + g_config->setOddsType(ui.typeCheckBox->isChecked()); + g_config->setOddsTypeIndex(ui.typeCombo->currentIndex()); + + g_config->setOddsHigh(ui.highEdit->text().toInt()); + g_config->setOddsLow(ui.lowEdit->text().toInt()); + g_config->setOddsUp(ui.upEdit->text().toInt()); + g_config->setOddsDown(ui.downEdit->text().toInt()); + +} + diff --git a/CrownClient/Odds.h b/CrownClient/Odds.h new file mode 100644 index 0000000..9b27d26 --- /dev/null +++ b/CrownClient/Odds.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include "ui_Odds.h" + +class Odds : public QWidget +{ + Q_OBJECT + +public: + Odds(QWidget *parent = nullptr); + ~Odds(); +private slots: + void slotSetOdds(); +private: + void closeEvent(QCloseEvent* event); +private: + Ui::OddsClass ui; +}; diff --git a/CrownClient/Odds.ui b/CrownClient/Odds.ui new file mode 100644 index 0000000..d1ffb9d --- /dev/null +++ b/CrownClient/Odds.ui @@ -0,0 +1,534 @@ + + + OddsClass + + + + 0 + 0 + 1282 + 539 + + + + Odds + + + + + + + + + + + + + 0 + 0 + + + + + 1677215 + 16777215 + + + + + + + + 原盘口: + + + + + + + + 1677215 + 16777215 + + + + + + + + 模拟结果: + + + + + + + 现盘口: + + + + + + + 现赔率: + + + + + + + + 1677215 + 16777215 + + + + + 香港盘 + + + + + + + + 原赔率: + + + + + + + + 0 + 0 + + + + + 90 + 0 + + + + + 16777215 + 16777215 + + + + + 让球 + + + + + 受让 + + + + + 大 + + + + + 小 + + + + + 独赢主 + + + + + 独赢客 + + + + + 独赢和 + + + + + 单 + + + + + 双 + + + + + 主队大 + + + + + 主队小 + + + + + 客队大 + + + + + 客队小 + + + + + + + + 模拟测试 + + + + + + + + + + 注单项目: + + + + + + + + 0 + 0 + + + + + 135 + 0 + + + + + 16777215 + 16777215 + + + + + 足球滚球全场 + + + + + 足球滚球上半场 + + + + + 足球今日全场 + + + + + 足球今日上半场 + + + + + 足球早盘全场 + + + + + 足球早盘上半场 + + + + + 篮球滚球全部 + + + + + 篮球今日全部 + + + + + 篮球早盘全部 + + + + + + + + + 0 + 0 + + + + + 1677215 + 16777215 + + + + + 香港盘 + + + + + + + + 注单类型: + + + + + + + + + + + + + + + + 注单项目: + + + + + + + + 足球滚球全场 + + + + + 足球滚球上半场 + + + + + 足球今日全场 + + + + + 足球今日上半场 + + + + + 足球早盘全场 + + + + + 足球早盘上半场 + + + + + 篮球滚球全部 + + + + + 篮球今日全部 + + + + + 篮球早盘全部 + + + + + + + + 注单类型: + + + + + + + + 让球 + + + + + 受让 + + + + + 大 + + + + + 小 + + + + + 独赢主 + + + + + 独赢客 + + + + + 独赢和 + + + + + 单 + + + + + 双 + + + + + 主队大 + + + + + 主队小 + + + + + 客队大 + + + + + 客队小 + + + + + + + + 设置赔率 + + + + + + + 大于不跟: + + + + + + + + + + 小于不跟: + + + + + + + + + + 上涨不跟: + + + + + + + + + + 下跌不跟: + + + + + + + + + + + + + + + + + + + + + + <html><head/><body><p><span style=" color:#ff0000;">赔率表填写非0值,启用判断功能!</span><span style=" color:#009400;">自动换算成香港赔率再进行判断.</span></p></body></html> + + + + + + + <html><head/><body><p><span style=" color:#0000ff;">[上涨不跟]或[下跌不跟],如果填写负数,则进行反义判断!</span></p></body></html> + + + + + + + <html><head/><body><p><span style=" color:#aa00ff;">例如:[上涨不跟]填写(-0.1),则只有赔率上涨(0.1)才跟.</span></p></body></html> + + + + + + + 详细情况:请先填写上面的赔率表,再进行模拟测试! + + + + + + + + + + + + diff --git a/CrownClient/Project.cpp b/CrownClient/Project.cpp new file mode 100644 index 0000000..630ddf0 --- /dev/null +++ b/CrownClient/Project.cpp @@ -0,0 +1,156 @@ +#include "Project.h" +#include "Global.h" + +Project::Project(QWidget *parent) + : QWidget(parent) +{ + ui.setupUi(this); + + // 设置窗口图标 + this->setWindowIcon(QIcon(":/images/Images/client.ico")); + // 设置窗口标题 + this->setWindowTitle("赛事盘口判断处理"); + // 设置为对话框窗口 + setWindowFlags(Qt::Dialog); + // 设置窗口仅有关闭按钮 + setWindowFlags(Qt::WindowCloseButtonHint); + + // 盘口计算方式 + switch (g_config->session_calc_type()) + { + case 0: + { + ui.handicapCalcTypeRadio1->setChecked(true); + break; + } + case 1: + { + ui.handicapCalcTypeRadio2->setChecked(true); + break; + } + case 2: + { + ui.handicapCalcTypeRadio3->setChecked(true); + break; + } + case 3: + { + ui.handicapCalcTypeRadio4->setChecked(true); + break; + } + } + + // 对头单不跟 + ui.gameOppositeCheckBox->setChecked(g_config->gameOppositeEnable()); + ui.handicapOppositeCheckBox->setChecked(g_config->handicapOppositeEnable()); + + // 场次项目计算方式 + switch (g_config->ptype_calc_type()) + { + case 0: + { + ui.sessionCalcTypeRadio1->setChecked(true); + break; + } + case 1: + { + ui.sessionCalcTypeRadio2->setChecked(true); + break; + } + } + + // 注单类型计算方式 + switch (g_config->gameCalcType()) + { + + case 0: + { + ui.gameCalcTypeRadio1->setChecked(true); + break; + } + case 1: + { + ui.gameCalcTypeRadio2->setChecked(true); + break; + } + case 2: + { + ui.gameCalcTypeRadio3->setChecked(true); + break; + } + } + + ui.gameFollowTimesMaxCheckBox->setChecked(g_config->gameFollowTimesMaxEnable()); + ui.gameFollowTimesMaxEdit->setText(QString::number(g_config->gameFollowTimesMax())); + + ui.gameFollowAmountMaxCheckBox->setChecked(g_config->gameFollowAmountMaxEnable()); + ui.gameFollowAmountMaxEdit->setText(QString::number(g_config->gameFollowAmountMax())); + + ui.handicapFollowTimesMaxCheckBox->setChecked(g_config->handicapFollowTimesMaxEnable()); + ui.handicapFollowTimesMaxEdit->setText(QString::number(g_config->handicapFollowTimesMax())); + ui.handicapFollowAmountMaxCheckBox->setChecked(g_config->handicapFollowAmountMaxEnable()); + ui.handicapFollowAmountMaxEdit->setText(QString::number(g_config->handicapFollowAmountMax())); +} + +Project::~Project() +{ + + +} + +void Project::closeEvent(QCloseEvent* event) +{ + if (ui.handicapCalcTypeRadio1->isChecked()) + { + g_config->set_session_calc_type(0); + } + else if(ui.handicapCalcTypeRadio2->isChecked()) + { + g_config->set_session_calc_type(1); + } + else if (ui.handicapCalcTypeRadio3->isChecked()) + { + g_config->set_session_calc_type(2); + } + else if (ui.handicapCalcTypeRadio4->isChecked()) + { + g_config->set_session_calc_type(3); + } + g_config->setGameOppositeEnable(ui.gameOppositeCheckBox->isChecked()); + g_config->setHandicapOppositeEnable(ui.handicapOppositeCheckBox->isChecked()); + + if (ui.sessionCalcTypeRadio1->isChecked()) + { + g_config->set_ptype_calc_type(0); + } + else if(ui.sessionCalcTypeRadio2->isChecked()) + { + g_config->set_ptype_calc_type(1); + } + + if (ui.gameCalcTypeRadio1->isChecked()) + { + //qDebug() << "保存0"; + g_config->setGameCalcType(0); + } + else if (ui.gameCalcTypeRadio2->isChecked()) + { + //qDebug() << "保存1"; + g_config->setGameCalcType(1); + } + else if (ui.gameCalcTypeRadio3->isChecked()) + { + //qDebug() << "保存2"; + g_config->setGameCalcType(2); + } + g_config->setGameFollowTimesMaxEnable(ui.gameFollowTimesMaxCheckBox->isChecked()); + g_config->setGameFollowTimesMax(ui.gameFollowTimesMaxEdit->text().toInt()); + g_config->setHandicapFollowTimesMaxEnable(ui.handicapFollowTimesMaxCheckBox->isChecked()); + g_config->setHandicapFollowTimesMax(ui.handicapFollowTimesMaxEdit->text().toInt()); + + g_config->setGameFollowAmountMaxEnable(ui.gameFollowAmountMaxCheckBox->isChecked()); + g_config->setGameFollowAmountMax(ui.gameFollowAmountMaxEdit->text().toFloat()); + g_config->setHandicapFollowAmountMaxEnable(ui.handicapFollowAmountMaxCheckBox->isChecked()); + g_config->setHandicapFollowAmountMax(ui.handicapFollowAmountMaxEdit->text().toFloat()); + +} diff --git a/CrownClient/Project.h b/CrownClient/Project.h new file mode 100644 index 0000000..5707c23 --- /dev/null +++ b/CrownClient/Project.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include "ui_Project.h" + +class Project : public QWidget +{ + Q_OBJECT + +public: + Project(QWidget *parent = nullptr); + ~Project(); + +private: + Ui::ProjectClass ui; + +private: + void closeEvent(QCloseEvent* event); +}; diff --git a/CrownClient/Project.ui b/CrownClient/Project.ui new file mode 100644 index 0000000..73f2c24 --- /dev/null +++ b/CrownClient/Project.ui @@ -0,0 +1,513 @@ + + + ProjectClass + + + + 0 + 0 + 472 + 811 + + + + Project + + + + + + + + + + + + + + + + + + + + + <html><head/><body><p><span style=" color:#ff0000;">[早盘]</span>与<span style=" color:#ff0000;">[今日]</span>与<span style=" color:#ff0000;">[滚球]</span>:分别计算</p></body></html> + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + + + + + <html><head/><body><p><span style=" color:#55aa00;">[早盘]</span>和<span style=" color:#55aa00;">[今日]</span>与<span style=" color:#ff0000;">[滚球]</span>:分开计算</p></body></html> + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + + + + + <html><head/><body><p><span style=" color:#ff0000;">[早盘]</span>与<span style=" color:#55aa00;">[今日]</span>和<span style=" color:#55aa00;">[滚球]</span>:分开计算</p></body></html> + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + true + + + + + + + <html><head/><body><p><span style=" color:#55aa00;">[早盘]</span>和<span style=" color:#55aa00;">[今日]</span>和<span style=" color:#55aa00;">[滚球]</span>:统一计算</p></body></html> + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + + + + + [同赛事]对头单不跟 + + + + + + + [同赛事盘口]对头单不跟 + + + + + + + <html><head/><body><p><span style=" color:#b3a7af;">所有场次项目:分别计算</span></p><p><span style=" color:#b3a7af;">勾选[同赛事盘口]判断方式,适用[让球|大小]!</span></p><p><span style=" color:#b3a7af;">此外[独赢|单双],自动使用[同赛事]判断方式!</span></p></body></html> + + + + + + + + + + + + + + + + 7 + + + + + + + + + + + + false + + + + + + + <html><head/><body><p><span style=" color:#ff0000;">所有场次项目</span>:分别计算</p></body></html> + + + + + + + + + + + + + + true + + + + + + + <html><head/><body><p><span style=" color:#55aa00;">所有场次项目</span>:统一计算</p></body></html> + + + + + + + + + + + <html><head/><body><p><span style=" color:#ff0000;">[全场|上半场|下半场|分节]</span></p><p><span style=" color:#ff0000;">[加时|角球|罚牌|晋级]</span></p><p><span style=" color:#ff0000;">[冠军|点球|....|....]</span></p></body></html> + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + + + + + + + + + + + + + + <html><head/><body><p><span style=" color:#ff0000;">所有注单类型</span>:分别计算</p></body></html> + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + + + + + <html><head/><body><p><span style=" color:#ff0000;">[</span><span style=" color:#55aa00;">让球</span><span style=" color:#ff0000;">|</span><span style=" color:#55aa00;">大小</span><span style=" color:#ff0000;">|</span><span style=" color:#55aa00;">独赢</span><span style=" color:#ff0000;">|</span><span style=" color:#55aa00;">单双</span><span style=" color:#ff0000;">|</span><span style=" color:#55aa00;">主大小</span><span style=" color:#ff0000;">|</span><span style=" color:#55aa00;">客大小</span><span style=" color:#ff0000;">]</span>:分开计算</p></body></html> + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + true + + + + + + + <html><head/><body><p><span style=" color:#55aa00;">所有注单类型</span>:统一计算</p></body></html> + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + <hr> + + + + + + + + + [同赛事]最多跟单次数: + + + + + + + 100 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + [同赛事]最多跟单金额: + + + + + + + 100000 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + [同赛事盘口]最多跟单次数: + + + + + + + 10 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + [同赛事盘口]最多跟单金额: + + + + + + + 10000 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + <html><head/><body><p><span style=" color:#b3a7af;">勾选[同赛事盘口]判断方式,适用[让球|大小]!</span></p><p><span style=" color:#b3a7af;">此外[独赢|单双],需要勾选[同赛事]判断方式!</span></p></body></html> + + + + + + + + + + + + diff --git a/CrownClient/PushMsg.cpp b/CrownClient/PushMsg.cpp new file mode 100644 index 0000000..90e1d22 --- /dev/null +++ b/CrownClient/PushMsg.cpp @@ -0,0 +1,11 @@ +#include "PushMsg.h" +#include "Global.h" + +void PushMsg::push(QString type, QString account, QMap order) +{ + if (g_config->notice_status() && account != "") + { + g_verify->push_msg(type, "客户端", account, order); + } + emit resultReady("推送请求结束"); +} \ No newline at end of file diff --git a/CrownClient/PushMsg.h b/CrownClient/PushMsg.h new file mode 100644 index 0000000..830eab0 --- /dev/null +++ b/CrownClient/PushMsg.h @@ -0,0 +1,15 @@ +#pragma once +#include + + + +class PushMsg : public QObject { + Q_OBJECT +public: + explicit PushMsg(QObject* parent = nullptr) :QObject(parent) {}; +signals: + void resultReady(const QString &result); + void log(QString log); +public slots: + void push(QString type, QString account, QMap order); +}; \ No newline at end of file diff --git a/CrownClient/RCa09272 b/CrownClient/RCa09272 new file mode 100644 index 0000000..85a571e Binary files /dev/null and b/CrownClient/RCa09272 differ diff --git a/CrownClient/RatioAmount.cpp b/CrownClient/RatioAmount.cpp new file mode 100644 index 0000000..b656852 --- /dev/null +++ b/CrownClient/RatioAmount.cpp @@ -0,0 +1,276 @@ +#include "RatioAmount.h" +#include "Global.h" +#include "Utils.h" +RatioAmount::RatioAmount(QWidget *parent) + : QWidget(parent) +{ + ui.setupUi(this); + // 设置窗口图标 + this->setWindowIcon(QIcon(":/images/Images/client.ico")); + // 设置窗口标题 + this->setWindowTitle("赔率金额判断处理"); + // 设置为对话框窗口 + setWindowFlags(Qt::Dialog); + // 设置窗口仅有关闭按钮 + setWindowFlags(Qt::WindowCloseButtonHint); + + + ui.tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + ui.tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch); + + for (int row = 0; row < 9; row++) + { + ui.tableWidget->insertRow(row); + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + if (column == 0) + { + ui.tableWidget->setItem(row, column, new QTableWidgetItem(g_gameTypes[row])); + } + else + { + ui.tableWidget->setItem(row, column, new QTableWidgetItem("1")); + ui.tableWidget->item(row, column)->setBackgroundColor(QColor(Qt::green)); + } + ui.tableWidget->item(row, column)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + + } + + } + + + + connect(ui.setButton, &QPushButton::clicked, this, [&]() { + // 单个 + if (ui.projectCheckBox->isChecked() && ui.typeCheckBox->isChecked()) + { + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + QString project = ui.tableWidget->item(row, 0)->text(); + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + if (column == 0) + { + continue; + } + QString type = ui.tableWidget->horizontalHeaderItem(column)->text(); + if (project == ui.projectCombo->currentText() && type == ui.typeCombo->currentText()) + { + // 缩放比率 + if (ui.scaleRadio->isChecked()) + { + ui.tableWidget->item(row, column)->setText(ui.scaleEdit->text()); + ui.tableWidget->item(row, column)->setBackgroundColor(QColor(Qt::green)); + } + // 固定金额 + if (ui.fiexedRadio->isChecked()) + { + ui.tableWidget->item(row, column)->setText(ui.fixedEdit->text()); + ui.tableWidget->item(row, column)->setBackgroundColor(QColor(Qt::red)); + } + + break; + } + } + } + } + // 整行 + if (ui.projectCheckBox->isChecked() && !ui.typeCheckBox->isChecked()) + { + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + QString project = ui.tableWidget->item(row, 0)->text(); + if (project == ui.projectCombo->currentText()) + { + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + if (column == 0) + { + continue; + } + // 缩放比率 + if (ui.scaleRadio->isChecked()) + { + ui.tableWidget->item(row, column)->setText(ui.scaleEdit->text()); + ui.tableWidget->item(row, column)->setBackgroundColor(QColor(Qt::green)); + } + // 固定金额 + if (ui.fiexedRadio->isChecked()) + { + ui.tableWidget->item(row, column)->setText(ui.fixedEdit->text()); + ui.tableWidget->item(row, column)->setBackgroundColor(QColor(Qt::red)); + } + } + } + } + } + // 整列 + if (!ui.projectCheckBox->isChecked() && ui.typeCheckBox->isChecked()) + { + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + QString type = ui.tableWidget->horizontalHeaderItem(column)->text(); + if (type == ui.typeCombo->currentText()) + { + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + if (column == 0) + { + continue; + } + // 缩放比率 + if (ui.scaleRadio->isChecked()) + { + ui.tableWidget->item(row, column)->setText(ui.scaleEdit->text()); + ui.tableWidget->item(row, column)->setBackgroundColor(QColor(Qt::green)); + } + // 固定金额 + if (ui.fiexedRadio->isChecked()) + { + ui.tableWidget->item(row, column)->setText(ui.fixedEdit->text()); + ui.tableWidget->item(row, column)->setBackgroundColor(QColor(Qt::red)); + } + } + } + } + + } + // 全部 + if (!ui.projectCheckBox->isChecked() && !ui.typeCheckBox->isChecked()) + { + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + if (column == 0) + { + continue; + } + // 缩放比率 + if (ui.scaleRadio->isChecked()) + { + ui.tableWidget->item(row, column)->setText(ui.scaleEdit->text()); + ui.tableWidget->item(row, column)->setBackgroundColor(QColor(Qt::green)); + } + // 固定金额 + if (ui.fiexedRadio->isChecked()) + { + ui.tableWidget->item(row, column)->setText(ui.fixedEdit->text()); + ui.tableWidget->item(row, column)->setBackgroundColor(QColor(Qt::red)); + } + } + } + } + }); + +} + +RatioAmount::~RatioAmount() +{ + + +} + +QList> RatioAmount::list() +{ + QList> list; + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + QString project = ui.tableWidget->item(row,0)->text(); + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + // 第一列跳过 + if (column == 0) + { + continue; + } + QString type = ui.tableWidget->horizontalHeaderItem(column)->text(); + QMap map = Utils::instance().type(project, type); + map["row"] = QString::number(row); + map["column"] = QString::number(column); + + if (ui.tableWidget->item(row, column)->backgroundColor() == QColor(Qt::green)) + { + // 缩放比率 + map["type"] = "scale"; + } + else + { + // 固定金额 + map["type"] = "fixed"; + } + map["value"] = ui.tableWidget->item(row,column)->text(); + list.append(map); + } + } + return list; +} + +void RatioAmount::setList(QList> list) +{ + for (int i = 0; i < list.count(); i++) + { + QMap follow = list[i]; + int column = follow["column"].toInt(); + int row = follow["row"].toInt(); + QString value = follow["value"]; + + if (follow["type"] == "scale") + { + if (value.isEmpty()) + { + ui.tableWidget->item(row, column)->setText("1"); + } + else + { + ui.tableWidget->item(row, column)->setText(value); + } + ui.tableWidget->item(row, column)->setBackgroundColor(QColor(Qt::green)); + } + else + { + if (value.isEmpty()) + { + ui.tableWidget->item(row, column)->setText("50"); + } + else + { + ui.tableWidget->item(row, column)->setText(value); + } + ui.tableWidget->item(row, column)->setBackgroundColor(QColor(Qt::red)); + } + } +} + +void RatioAmount::closeEvent(QCloseEvent * event) +{ + int positiveFollow = 0; + int negativeFollow = 0; + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + for (int column = 0; column < ui.tableWidget->columnCount();column++) + { + if (ui.tableWidget->item(row, column)->text() == "正跟") + { + positiveFollow++; + } + else + { + negativeFollow++; + } + } + } + if (positiveFollow == 0) + { + emit signalUpdateStatus(); + } + else if (negativeFollow == 0) + { + emit signalUpdateStatus(); + } + else + { + emit signalUpdateStatus(); + } + +} diff --git a/CrownClient/RatioAmount.h b/CrownClient/RatioAmount.h new file mode 100644 index 0000000..d87fe1d --- /dev/null +++ b/CrownClient/RatioAmount.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include "ui_RatioAmount.h" + +class RatioAmount : public QWidget +{ + Q_OBJECT + +public: + RatioAmount(QWidget *parent = nullptr); + ~RatioAmount(); +public: + QList> list(); + void setList(QList> list); +signals: + void signalUpdateStatus(); +private: + void closeEvent(QCloseEvent* event); + +private: + Ui::RatioAmountClass ui; + +}; diff --git a/CrownClient/RatioAmount.ui b/CrownClient/RatioAmount.ui new file mode 100644 index 0000000..b669279 --- /dev/null +++ b/CrownClient/RatioAmount.ui @@ -0,0 +1,287 @@ + + + RatioAmountClass + + + + 0 + 0 + 1146 + 565 + + + + RatioAmount + + + + + + QAbstractItemView::NoEditTriggers + + + false + + + false + + + false + + + + 注单项目 + + + + + 让球 + + + + + 受让 + + + + + 大 + + + + + 小 + + + + + 独赢主 + + + + + 独赢客 + + + + + 独赢和 + + + + + 单 + + + + + 双 + + + + + 主队大 + + + + + 主队小 + + + + + 客队大 + + + + + 客队小 + + + + + + + + + + + + + + 注单项目: + + + + + + + + 足球滚球全场 + + + + + 足球滚球上半场 + + + + + 足球今日全场 + + + + + 足球今日上半场 + + + + + 足球早盘全场 + + + + + 足球早盘上半场 + + + + + 篮球滚球全部 + + + + + 篮球今日全部 + + + + + 篮球早盘全部 + + + + + + + + 注单类型: + + + + + + + + 让球 + + + + + 受让 + + + + + 大 + + + + + 小 + + + + + 独赢主 + + + + + 独赢客 + + + + + 独赢和 + + + + + 单 + + + + + 双 + + + + + 主队大 + + + + + 主队小 + + + + + 客队大 + + + + + 客队小 + + + + + + + + 设置比率 + + + + + + + 缩放比率: + + + true + + + + + + + 1 + + + + + + + 固定金额: + + + + + + + 50 + + + + + + + + + + + + diff --git a/CrownClient/Rebet.cpp b/CrownClient/Rebet.cpp new file mode 100644 index 0000000..608a908 --- /dev/null +++ b/CrownClient/Rebet.cpp @@ -0,0 +1,86 @@ +#include "Rebet.h" +#include "Global.h" + +Rebet::Rebet(QWidget *parent) + : QWidget(parent) +{ + ui.setupUi(this); + + // 设置窗口图标 + this->setWindowIcon(QIcon(":/images/Images/client.ico")); + // 设置窗口标题 + this->setWindowTitle("补单筛选判断处理(关键字)"); + // 设置为对话框窗口 + setWindowFlags(Qt::Dialog); + // 设置窗口仅有关闭按钮 + setWindowFlags(Qt::WindowCloseButtonHint); + + for (int row = 0; row < 10; row++) + { + ui.tableWidget->insertRow(row); + + QWidget* widget_enable = new QWidget; + QHBoxLayout* layout_enale = new QHBoxLayout; + QCheckBox* chekcBox = new QCheckBox; + layout_enale->addWidget(chekcBox); + layout_enale->setContentsMargins(0, 0, 0, 0); + layout_enale->setAlignment(chekcBox, Qt::AlignCenter); + widget_enable->setLayout(layout_enale); + ui.tableWidget->setCellWidget(row, 0, widget_enable); + ui.tableWidget->setItem(row, 1, new QTableWidgetItem("")); + ui.tableWidget->setItem(row, 2, new QTableWidgetItem("")); + ui.tableWidget->item(row, 1)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + ui.tableWidget->item(row, 2)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + } + + ui.rebetScreenCheckBox->setChecked(g_config->rebetScreenEnable()); + QList> list = g_config->rebetScreen(); + for (int row = 0; row < list.count(); row++) + { + QMap screen = list[row]; + QCheckBox* checkBox = reinterpret_cast(ui.tableWidget->cellWidget(row, 0)->layout()->itemAt(0)->widget()); + if (screen["ENABLE"] == "TRUE") + { + checkBox->setChecked(true); + } + else + { + checkBox->setChecked(false); + } + ui.tableWidget->item(row,1)->setText(screen["REASON"]); + ui.tableWidget->item(row,2)->setText(screen["TIMES"]); + } +} + +Rebet::~Rebet() +{ + +} + +void Rebet::closeEvent(QCloseEvent * event) +{ + QList> list; + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + QMap screen; + QCheckBox* checkBox = reinterpret_cast(ui.tableWidget->cellWidget(row, 0)->layout()->itemAt(0)->widget()); + if (checkBox->isChecked()) + { + screen["ENABLE"] = "TRUE"; + } + else + { + screen["ENABLE"] = "FALSE"; + } + screen["REASON"] = ui.tableWidget->item(row, 1)->text(); + screen["TIMES"] = ui.tableWidget->item(row, 2)->text(); + list.append(screen); + } + + // 保存补单原因列表 + g_config->setRebetScreen(list); + + + // 保存补单筛选开关 + g_config->setRebetScreenEnable(ui.rebetScreenCheckBox->isChecked()); +} diff --git a/CrownClient/Rebet.h b/CrownClient/Rebet.h new file mode 100644 index 0000000..c660cfa --- /dev/null +++ b/CrownClient/Rebet.h @@ -0,0 +1,17 @@ +#pragma once + +#include +#include "ui_Rebet.h" + +class Rebet : public QWidget +{ + Q_OBJECT + +public: + Rebet(QWidget *parent = nullptr); + ~Rebet(); +private: + void closeEvent(QCloseEvent* event); +private: + Ui::RebetClass ui; +}; diff --git a/CrownClient/Rebet.ui b/CrownClient/Rebet.ui new file mode 100644 index 0000000..719d21c --- /dev/null +++ b/CrownClient/Rebet.ui @@ -0,0 +1,78 @@ + + + RebetClass + + + + 0 + 0 + 426 + 522 + + + + Rebet + + + + + + + 启用 + + + + + 失败原因 + + + + + 累计次数 + + + + + + + + + + + + + + + + 启用筛选: + + + + + + + (失败原因)达到累积次数(判断处理) + + + + + + + + + 放弃注单 + + + true + + + + + + + + + + + + diff --git a/CrownClient/Resources/check.svg b/CrownClient/Resources/check.svg new file mode 100644 index 0000000..1c20989 --- /dev/null +++ b/CrownClient/Resources/check.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/CrownClient/Resources/checkmark.png b/CrownClient/Resources/checkmark.png new file mode 100644 index 0000000..1545ba7 Binary files /dev/null and b/CrownClient/Resources/checkmark.png differ diff --git a/CrownClient/Resources/chevron-down.svg b/CrownClient/Resources/chevron-down.svg new file mode 100644 index 0000000..278c6a3 --- /dev/null +++ b/CrownClient/Resources/chevron-down.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/CrownClient/Resources/crownTime.png b/CrownClient/Resources/crownTime.png new file mode 100644 index 0000000..395f263 Binary files /dev/null and b/CrownClient/Resources/crownTime.png differ diff --git a/CrownClient/Resources/down_arrow.png b/CrownClient/Resources/down_arrow.png new file mode 100644 index 0000000..b51a01f Binary files /dev/null and b/CrownClient/Resources/down_arrow.png differ diff --git a/CrownClient/Resources/icons/checkmark.png b/CrownClient/Resources/icons/checkmark.png new file mode 100644 index 0000000..1545ba7 Binary files /dev/null and b/CrownClient/Resources/icons/checkmark.png differ diff --git a/CrownClient/Resources/icons/close.png b/CrownClient/Resources/icons/close.png new file mode 100644 index 0000000..ba32052 Binary files /dev/null and b/CrownClient/Resources/icons/close.png differ diff --git a/CrownClient/Resources/icons/down_arrow.png b/CrownClient/Resources/icons/down_arrow.png new file mode 100644 index 0000000..b51a01f Binary files /dev/null and b/CrownClient/Resources/icons/down_arrow.png differ diff --git a/CrownClient/Resources/icons/down_arrow_light.svg b/CrownClient/Resources/icons/down_arrow_light.svg new file mode 100644 index 0000000..95dc821 --- /dev/null +++ b/CrownClient/Resources/icons/down_arrow_light.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/CrownClient/Resources/icons/icons/close.png b/CrownClient/Resources/icons/icons/close.png new file mode 100644 index 0000000..ba32052 Binary files /dev/null and b/CrownClient/Resources/icons/icons/close.png differ diff --git a/CrownClient/Resources/icons/icons/down_arrow.png b/CrownClient/Resources/icons/icons/down_arrow.png new file mode 100644 index 0000000..b51a01f Binary files /dev/null and b/CrownClient/Resources/icons/icons/down_arrow.png differ diff --git a/CrownClient/Resources/icons/icons/down_arrow_light.svg b/CrownClient/Resources/icons/icons/down_arrow_light.svg new file mode 100644 index 0000000..95dc821 --- /dev/null +++ b/CrownClient/Resources/icons/icons/down_arrow_light.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/CrownClient/Resources/icons/icons/restore.png b/CrownClient/Resources/icons/icons/restore.png new file mode 100644 index 0000000..e1cfbf7 Binary files /dev/null and b/CrownClient/Resources/icons/icons/restore.png differ diff --git a/CrownClient/Resources/icons/restore.png b/CrownClient/Resources/icons/restore.png new file mode 100644 index 0000000..e1cfbf7 Binary files /dev/null and b/CrownClient/Resources/icons/restore.png differ diff --git a/CrownClient/Resources/localTime.png b/CrownClient/Resources/localTime.png new file mode 100644 index 0000000..47b0051 Binary files /dev/null and b/CrownClient/Resources/localTime.png differ diff --git a/CrownClient/Resources/mail.png b/CrownClient/Resources/mail.png new file mode 100644 index 0000000..bd41033 Binary files /dev/null and b/CrownClient/Resources/mail.png differ diff --git a/CrownClient/Resources/server.ico b/CrownClient/Resources/server.ico new file mode 100644 index 0000000..2f6ae8c Binary files /dev/null and b/CrownClient/Resources/server.ico differ diff --git a/CrownClient/Resources/start.png b/CrownClient/Resources/start.png new file mode 100644 index 0000000..ddd52c3 Binary files /dev/null and b/CrownClient/Resources/start.png differ diff --git a/CrownClient/Resources/stop.png b/CrownClient/Resources/stop.png new file mode 100644 index 0000000..97bbd5a Binary files /dev/null and b/CrownClient/Resources/stop.png differ diff --git a/CrownClient/Resources/user.png b/CrownClient/Resources/user.png new file mode 100644 index 0000000..52c6ad6 Binary files /dev/null and b/CrownClient/Resources/user.png differ diff --git a/CrownClient/Resources/visual_studio_dark.qss b/CrownClient/Resources/visual_studio_dark.qss new file mode 100644 index 0000000..a7e022d --- /dev/null +++ b/CrownClient/Resources/visual_studio_dark.qss @@ -0,0 +1,616 @@ +/* VS暗黑/Atom风格 QSS样式表 - 优化中文显示版 */ +QMainWindow, QDialog, QWidget { + background-color: #1e1e1e; + color: #d4d4d4; + font-family: "Microsoft YaHei UI", "Segoe UI", "PingFang SC", sans-serif; + font-size: 13px; + border: none; +} + +/* 菜单栏 */ +QMenuBar { + background-color: #2d2d30; + color: #cccccc; + border-bottom: 1px solid #3e3e42; + font-size: 13px; +} + +QMenuBar::item { + background: transparent; + padding: 5px 10px; +} + +QMenuBar::item:selected { + background: #3e3e42; +} + +QMenuBar::item:pressed { + background: #007acc; +} + +/* 菜单 */ +QMenu { + background-color: #2d2d30; + color: #cccccc; + border: 1px solid #3e3e42; + font-size: 13px; +} + +QMenu::item { + padding: 6px 25px 6px 20px; +} + +QMenu::item:selected { + background-color: #3e3e42; + color: #ffffff; +} + +QMenu::item:disabled { + color: #656565; +} + +QMenu::separator { + height: 1px; + background-color: #3e3e42; + margin: 5px 0px; +} + +/* 工具栏 */ +QToolBar { + background-color: #2d2d30; + border: none; + spacing: 5px; + padding: 3px; +} + +QToolBar::handle { + background-color: #3e3e42; + width: 10px; +} + +/* 状态栏 */ +QStatusBar { + background-color: #007acc; + color: #ffffff; + font-size: 12px; +} + +QStatusBar::item { + border: none; +} + +/* 按钮 */ +QPushButton { + background-color: #0e639c; + color: #ffffff; + border: none; + border-radius: 3px; + padding: 6px 16px; + min-width: 60px; + font-size: 13px; +} + +QPushButton:hover { + background-color: #1177bb; +} + +QPushButton:pressed { + background-color: #0c5a8c; +} + +QPushButton:disabled { + background-color: #3e3e42; + color: #7a7a7a; +} + +QPushButton:focus { + outline: 0; +} +QPushButton:pressed { + outline: 0; +} + +/* === 专为图标按钮:stateButton / userManagerButton 的统一样式(支持QPushButton与QToolButton) === */ +QPushButton#stateButton, +QToolButton#stateButton, +QPushButton#userManagerButton { + background: transparent; + border: none; + padding: 0px; + margin: 0px; + min-width: 0px; + border-radius: 6px; +} + +/* 悬浮与按下为蓝色系半透明,保持与全局蓝色主色一致 */ +QPushButton#stateButton:hover, +QToolButton#stateButton:hover, +QPushButton#userManagerButton:hover { + background-color: rgba(0, 122, 204, 0.18); +} +QPushButton#stateButton:pressed, +QToolButton#stateButton:pressed, +QPushButton#userManagerButton:pressed { + background-color: rgba(0, 122, 204, 0.30); +} + +/* 明确图标尺寸(与UI设置一致,可按需调整) */ +QPushButton#stateButton, +QToolButton#stateButton { + qproperty-iconSize: 64px 64px; +} +QPushButton#userManagerButton { + qproperty-iconSize: 40px 40px; +} + +/* 工具栏按钮 */ +QToolButton { + background-color: transparent; + border: 1px solid transparent; + border-radius: 3px; + padding: 3px; +} + +QToolButton:hover { + background-color: #3e3e42; + border: 1px solid #3e3e42; +} + +QToolButton:pressed { + background-color: #007acc; +} + +QToolButton:checked { + background-color: #007acc; +} + +/* 复选框 */ +QCheckBox { + color: #d4d4d4; + spacing: 8px; + font-size: 13px; +} + +QCheckBox::indicator { + width: 16px; + height: 16px; +} + +QCheckBox::indicator:unchecked { + border: 1px solid #3e3e42; + background-color: #252526; +} + +QCheckBox::indicator:checked { + border: 1px solid #007acc; + background-color: #007acc; + image: url(:/Resources/icons/checkmark.png); +} + +QCheckBox::indicator:disabled { + border: 1px solid #3e3e42; + background-color: #2d2d30; +} + +/* 单选框 */ +QRadioButton { + color: #d4d4d4; + spacing: 8px; + font-size: 13px; +} + +QRadioButton::indicator { + width: 16px; + height: 16px; + border-radius: 8px; +} + +QRadioButton::indicator:unchecked { + border: 1px solid #3e3e42; + background-color: #252526; +} + +QRadioButton::indicator:checked { + border: 1px solid #007acc; + background-color: #007acc; +} + +QRadioButton::indicator:disabled { + border: 1px solid #3e3e42; + background-color: #2d2d30; +} + +/* 组合框 */ +QComboBox { + background-color: #252526; + color: #d4d4d4; + border: 1px solid #3e3e42; + border-radius: 3px; + padding: 5px 10px; + min-width: 75px; + font-size: 13px; +} + +QComboBox:hover { + border: 1px solid #007acc; +} + +QComboBox:editable { + background: #1e1e1e; +} + +QComboBox::drop-down { + subcontrol-origin: padding; + subcontrol-position: top right; + width: 22px; + border-left: 1px solid #3e3e42; +} + +QComboBox::down-arrow { + image: url(:/Resources/icons/down_arrow_light.svg); + width: 14px; + height: 14px; + right: 4px; + subcontrol-origin: padding; + subcontrol-position: center right; +} + +QComboBox QAbstractItemView { + background-color: #252526; + color: #d4d4d4; + selection-background-color: #007acc; + selection-color: #ffffff; + border: 1px solid #3e3e42; + outline: 0; + font-size: 13px; +} + +/* 自定义ComboBoxItem样式 - 修复删除按钮问题 */ +ComboBoxItem { + background-color: transparent; + border: none; + outline: 0; + min-height: 25px; + max-height: 25px; +} + +ComboBoxItem QLabel { + color: #d4d4d4; + background-color: transparent; + border: none; + font-size: 13px; + padding-left: 5px; +} + +ComboBoxItem QPushButton { + background: transparent; + border: none; + outline: 0; + min-width: 20px; + max-width: 20px; + min-height: 20px; + max-height: 20px; + border-radius: 10px; + margin: 0px 2px; + padding: 0px; +} + +ComboBoxItem QPushButton:hover { + background-color: rgba(200, 200, 200, 50); + border-radius: 10px; +} + +ComboBoxItem QPushButton:pressed { + background-color: rgba(0, 122, 204, 100); + border-radius: 10px; +} + +ComboBoxItem QPushButton:focus { + outline: 0; +} + +/* 确保QListWidget中的ComboBoxItem正确显示 */ +QListWidget::item { + background-color: transparent; + border: none; + outline: 0; + padding: 0px; + margin: 0px; +} + +QListWidget::item:hover { + background-color: #2a2d2e; +} + +QListWidget::item:selected { + background-color: #094771; +} + +/* 滚动条 */ +QScrollBar { + background: transparent; + outline: 0; + border: none; +} +QScrollBar:focus { + outline: 0; +} +QScrollBar::add-page, QScrollBar::sub-page { + background: transparent; +} +QScrollBar:vertical { + background: transparent; + width: 12px; + margin: 0px; +} + +QScrollBar::handle:vertical { + background: #424245; + min-height: 20px; + border-radius: 6px; + margin: 2px; +} + +QScrollBar::handle:vertical:hover { + background: #4c4c4f; +} + +QScrollBar::handle:vertical:pressed { + background: #007acc; +} + +QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { + height: 0px; +} + +QScrollBar:horizontal { + background: transparent; + height: 12px; + margin: 0px; +} + +QScrollBar::handle:horizontal { + background: #424245; + min-width: 20px; + border-radius: 6px; + margin: 2px; +} + +QScrollBar::handle:horizontal:hover { + background: #4c4c4f; +} + +QScrollBar::handle:horizontal:pressed { + background: #007acc; +} + +QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal { + width: 0px; +} + +/* 滑块 */ +QSlider::groove:horizontal { + background: #3e3e42; + height: 4px; + border-radius: 2px; +} + +QSlider::handle:horizontal { + background: #007acc; + border: none; + height: 12px; + width: 12px; + border-radius: 6px; + margin: -4px 0; +} + +QSlider::handle:horizontal:hover { + background: #1c97ea; +} + +QSlider::groove:vertical { + background: #3e3e42; + width: 4px; + border-radius: 2px; +} + +QSlider::handle:vertical { + background: #007acc; + border: none; + width: 12px; + height: 12px; + border-radius: 6px; + margin: 0 -4px; +} + +QSlider::handle:vertical:hover { + background: #1c97ea; +} + +/* 进度条 */ +QProgressBar { + background-color: #3e3e42; + color: #d4d4d4; + border: none; + border-radius: 3px; + text-align: center; + font-size: 13px; +} + +QProgressBar::chunk { + background-color: #007acc; + border-radius: 3px; +} + +/* 分页控件 */ +QTabWidget::pane { + background-color: #1e1e1e; + border: 1px solid #3e3e42; +} + +QTabBar::tab { + background-color: #2d2d30; + color: #cccccc; + padding: 8px 15px; + border: none; + border-bottom: 2px solid transparent; + font-size: 13px; +} + +QTabBar::tab:selected { + background-color: #1e1e1e; + color: #ffffff; + border-bottom: 2px solid #007acc; +} + +QTabBar::tab:hover:!selected { + background-color: #3e3e42; +} + +QTabBar::close-button { + image: url(:/Resources/icons/close.png); + subcontrol-position: right; +} + +QTabBar::close-button:hover { + background-color: #e81123; +} + +/* 分组框 */ +QGroupBox { + font-weight: bold; + border: 1px solid #3e3e42; + border-radius: 3px; + margin-top: 1ex; + padding-top: 10px; + font-size: 13px; +} + +QGroupBox::title { + subcontrol-origin: margin; + subcontrol-position: top center; + padding: 0 5px; +} + +/* 文本框 */ +QLineEdit, QTextEdit, QPlainTextEdit { + background-color: #252526; + color: #d4d4d4; + border: 1px solid #3e3e42; + border-radius: 3px; + padding: 5px; + selection-background-color: #007acc; + selection-color: #ffffff; + font-size: 13px; +} + +QLineEdit:focus, QTextEdit:focus, QPlainTextEdit:focus { + border: 1px solid #007acc; +} + +/* 列表视图 */ +QListView, QTreeView, QTableView { + background-color: #252526; + color: #d4d4d4; + border: 1px solid #3e3e42; + border-radius: 3px; + outline: 0; + selection-background-color: #007acc; + selection-color: #ffffff; + alternate-background-color: #2d2d30; + font-size: 13px; +} + +QHeaderView::section { + background-color: #2d2d30; + color: #cccccc; + padding: 5px; + border: none; + border-right: 1px solid #3e3e42; + font-size: 13px; +} + +QHeaderView::section:last { + border-right: none; +} + +QHeaderView::section:checked { + background-color: #007acc; + color: #ffffff; +} + +/* 分割线 */ +QSplitter::handle { + background-color: #2d2d30; +} + +QSplitter::handle:hover { + background-color: #007acc; +} + +QSplitter::handle:horizontal { + width: 5px; +} + +QSplitter::handle:vertical { + height: 5px; +} + +/* 停靠窗口 */ +QDockWidget { + background-color: #2d2d30; + color: #cccccc; + border: 1px solid #3e3e42; + titlebar-close-icon: url(:/Resources/icons/close.png); + titlebar-normal-icon: url(:/Resources/icons/restore.png); + font-size: 13px; +} + +QDockWidget::title { + background-color: #2d2d30; + padding: 5px; + text-align: center; +} + +QDockWidget::close-button, QDockWidget::float-button { + background-color: transparent; + border: none; + padding: 0px; + icon-size: 12px; +} + +QDockWidget::close-button:hover, QDockWidget::float-button:hover { + background-color: #3e3e42; +} + +/* 工具提示 */ +QToolTip { + background-color: #007acc; + color: #ffffff; + border: 1px solid #007acc; + border-radius: 3px; + padding: 5px; + font-size: 13px; + font-family: "Microsoft YaHei UI", "Segoe UI", "PingFang SC", sans-serif; +} + +/* 表格表头(更高优先级,覆盖默认白色的行号列头与角按钮) */ +QTableView QHeaderView::section { + background-color: #2d2d30; + color: #cccccc; + border: none; + border-right: 1px solid #3e3e42; + border-bottom: 1px solid #3e3e42; +} +QTableView QHeaderView::section:horizontal { + background-color: #2d2d30; + color: #cccccc; +} +QTableView QHeaderView::section:vertical { + background-color: #2d2d30; + color: #cccccc; +} +QTableView QTableCornerButton::section { + background-color: #2d2d30; + border: 1px solid #3e3e42; +} \ No newline at end of file diff --git a/CrownClient/Resources/x.svg b/CrownClient/Resources/x.svg new file mode 100644 index 0000000..7d5875c --- /dev/null +++ b/CrownClient/Resources/x.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/CrownClient/Screen.cpp b/CrownClient/Screen.cpp new file mode 100644 index 0000000..eb537e5 --- /dev/null +++ b/CrownClient/Screen.cpp @@ -0,0 +1,225 @@ +#include "Screen.h" +#include +#include "Global.h" +Screen::Screen(QWidget *parent) + : QWidget(parent) +{ + ui.setupUi(this); + + // 设置窗口图标 + this->setWindowIcon(QIcon(":/images/Images/client.ico")); + // 设置窗口标题 + this->setWindowTitle("赛事筛选判断处理"); + // 设置为对话框窗口 + setWindowFlags(Qt::Dialog); + // 设置窗口仅有关闭按钮 + setWindowFlags(Qt::WindowCloseButtonHint); + + + //ui.acceptCheckBox->setDisabled(true); + ui.acceptCheckBox->setCheckState(Qt::CheckState::Checked); + ui.acceptCheckBox->setAttribute(Qt::WA_TransparentForMouseEvents, true); + //ui.unAcceptCheckBox->setDisabled(true); + ui.unAcceptCheckBox->setCheckState(Qt::CheckState::PartiallyChecked); + ui.unAcceptCheckBox->setAttribute(Qt::WA_TransparentForMouseEvents, true); + //ui.followSuperCheckBox->setDisabled(true); + ui.followSuperCheckBox->setCheckState(Qt::CheckState::Unchecked); + ui.followSuperCheckBox->setAttribute(Qt::WA_TransparentForMouseEvents, true); + + ui.treeWidget->setColumnCount(1); + ui.treeWidget->setHeaderLabels({ "赛事" }); + ui.treeWidget->header()->resizeSection(0, 280); + //ui.treeWidget->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); + + + + + ui.tableWidget->setColumnCount(2); + ui.tableWidget->setHorizontalHeaderLabels({ "赛事","操作" }); + ui.tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + ui.tableWidget->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); + + + connect(ui.treeWidget, &QTreeWidget::itemChanged, this, &Screen::slotItemCheckChanged); + + connect(ui.readConfigButton, &QPushButton::clicked, this, [&]() + { + + QList screenList = g_config->screenGameList(); + QList acceptList = g_config->acceptGameList(); + QTreeWidgetItemIterator iter(ui.treeWidget); + while (*iter) + { + QTreeWidgetItem* item = *iter; + for (int i = 0; i < screenList.count(); i++) + { + QString user = screenList[i]; + + if (user == (*iter)->text(0)) + { + item->setCheckState(0, Qt::PartiallyChecked); + } + } + + for (int i = 0; i < acceptList.count(); i++) + { + QString user = acceptList[i]; + + if (user == (*iter)->text(0)) + { + item->setCheckState(0, Qt::Checked); + } + } + + iter++; + } + + }); + + + connect(ui.saveConfigButton, &QPushButton::clicked, this, [&]() { + + + QList screenList; + QList acceptList; + for (int i = 0; i < ui.tableWidget->rowCount(); i++) + { + QString user; + + user = ui.tableWidget->item(i, 0)->text(); + //user["level"] = ui.tableWidget->item(i, 1)->text(); + //user["option"] = ui.tableWidget->item(i, 2)->text(); + if (ui.tableWidget->item(i, 1)->text() == "接收") + { + acceptList.append(user); + } + else if (ui.tableWidget->item(i, 1)->text() == "屏蔽") + { + screenList.append(user); + } + + } + g_config->setAcceptGameList(acceptList); + g_config->setScreenGameList(screenList); + }); + +} + +Screen::~Screen() +{ +} + + + +void Screen::slotItemCheckChanged(QTreeWidgetItem* item, int column) +{ + // 跟随上级 + if (item->checkState(0) == Qt::CheckState::Unchecked) + { + item->setForeground(0, QBrush(QColor(0, 0, 0))); + QList tableItem = ui.tableWidget->findItems(item->text(0), Qt::MatchExactly); + if (tableItem.count() == 1) + { + ui.tableWidget->removeRow(tableItem[0]->row()); + } + } + // 屏蔽 + else if (item->checkState(0) == Qt::CheckState::PartiallyChecked) + { + item->setForeground(0, QBrush(QColor(255, 0, 0))); + + + // 精准匹配 + QList tableItem = ui.tableWidget->findItems(item->text(0), Qt::MatchExactly); + if (tableItem.count() == 1) + { + ui.tableWidget->setItem(tableItem[0]->row(), 1, new QTableWidgetItem("屏蔽")); + } + else + { + int index = ui.tableWidget->rowCount(); + ui.tableWidget->insertRow(index); + ui.tableWidget->setItem(index, 0, new QTableWidgetItem(item->text(0))); + ui.tableWidget->setItem(index, 1, new QTableWidgetItem("屏蔽")); + } + } + // 接收 + else if (item->checkState(0) == Qt::CheckState::Checked) + { + item->setForeground(0, QBrush(QColor(0, 255, 0))); + + QList tableItem = ui.tableWidget->findItems(item->text(0), Qt::MatchExactly); + if (tableItem.count() == 1) + { + ui.tableWidget->setItem(tableItem[0]->row(), 1, new QTableWidgetItem("接收")); + } + else + { + int index = ui.tableWidget->rowCount(); + ui.tableWidget->insertRow(index); + ui.tableWidget->setItem(index, 0, new QTableWidgetItem(item->text(0))); + ui.tableWidget->setItem(index, 1, new QTableWidgetItem("接收")); + } + + } + +} + + +void Screen::slotUpdateLeagueAndTeam(QList> list) +{ + // 查找所有联盟选项 + QList allLeagueItemArray = ui.treeWidget->findItems("所有联盟", Qt::MatchExactly, 0); + QTreeWidgetItem* allLeagueItem = nullptr; + if (allLeagueItemArray.count() <= 0) + { + allLeagueItem = new QTreeWidgetItem(ui.treeWidget); + allLeagueItem->setText(0, "所有联盟"); + } + else + { + allLeagueItem = allLeagueItemArray[0]; + } + allLeagueItem->setFlags(Qt::ItemIsUserTristate | allLeagueItem->flags()); + allLeagueItem->setCheckState(0, Qt::CheckState::Checked); + + for (int i = 0; i < list.count(); i++) + { + QMap game = list[i]; + + QList leagueItemArray = ui.treeWidget->findItems(game["league"].trimmed(), Qt::MatchRecursive, 0); + QTreeWidgetItem* leagueItem = nullptr; + if (leagueItemArray.count() < 1) + { + leagueItem = new QTreeWidgetItem(allLeagueItem); + leagueItem->setText(0, game["league"].trimmed()); + } + else + { + + leagueItem = leagueItemArray[0]; + } + leagueItem->setFlags(Qt::ItemIsUserTristate | leagueItem->flags()); + leagueItem->setCheckState(0, Qt::CheckState::Unchecked); + + QList teamHItemArray = ui.treeWidget->findItems(game["team_h"].trimmed(), Qt::MatchRecursive, 0); + if (teamHItemArray.count() < 1) + { + QTreeWidgetItem* teamHItem = new QTreeWidgetItem(leagueItem); + teamHItem->setText(0, game["team_h"].trimmed()); + teamHItem->setFlags(Qt::ItemIsUserTristate | teamHItem->flags()); + teamHItem->setCheckState(0, Qt::CheckState::Unchecked); + } + + + QList teamCItemArray = ui.treeWidget->findItems(game["team_c"].trimmed(), Qt::MatchRecursive, 0); + if (teamCItemArray.count() < 1) + { + QTreeWidgetItem* teamCItem = new QTreeWidgetItem(leagueItem); + teamCItem->setText(0, game["team_c"].trimmed()); + teamCItem->setFlags(Qt::ItemIsUserTristate | teamCItem->flags()); + teamCItem->setCheckState(0, Qt::CheckState::Unchecked); + } + + } +} \ No newline at end of file diff --git a/CrownClient/Screen.h b/CrownClient/Screen.h new file mode 100644 index 0000000..6ac58ef --- /dev/null +++ b/CrownClient/Screen.h @@ -0,0 +1,18 @@ +#pragma once + +#include +#include "ui_Screen.h" + +class Screen : public QWidget +{ + Q_OBJECT + +public: + Screen(QWidget *parent = nullptr); + ~Screen(); +public slots: + void slotItemCheckChanged(QTreeWidgetItem* item, int column); + void slotUpdateLeagueAndTeam(QList> list); +private: + Ui::ScreenClass ui; +}; diff --git a/CrownClient/Screen.ui b/CrownClient/Screen.ui new file mode 100644 index 0000000..f2b8256 --- /dev/null +++ b/CrownClient/Screen.ui @@ -0,0 +1,117 @@ + + + ScreenClass + + + + 0 + 0 + 579 + 398 + + + + Screen + + + + + + + + + 1 + + + + + + + + + + + + + + + + + QCheckBox { +color: rgb(255, 0, 0); +padding: 0px 0px 0px 0px; +} + + + 屏蔽 + + + false + + + true + + + + + + + 跟随联盟 + + + true + + + true + + + + + + + false + + + QCheckBox { +color: rgb(0, 255, 0); +padding: 0px 0px 0px 0px; +} + + + 接收 + + + false + + + 300 + + + true + + + + + + + 读取配置 + + + + + + + 保存配置 + + + + + + + + + + + + + diff --git a/CrownClient/Setting.cpp b/CrownClient/Setting.cpp new file mode 100644 index 0000000..9b0317d --- /dev/null +++ b/CrownClient/Setting.cpp @@ -0,0 +1,540 @@ +#include "Setting.h" +#include "Global.h" +#include "Utils.h" +#include "CrownClient.h" +Setting::Setting(QWidget *parent) + : QWidget(parent) +{ + ui.setupUi(this); + // 设置窗口图标 + this->setWindowIcon(QIcon(":/images/Images/client.ico")); + // 设置窗口标题 + this->setWindowTitle("跟单设置"); + // 设置为对话框窗口 + setWindowFlags(Qt::Dialog); + // 设置窗口仅有关闭按钮 + setWindowFlags(Qt::WindowCloseButtonHint); + setFixedSize(1188, 711); + + // 跟单项目窗口 + window_followProject = new FollowProject(); + connect(ui.followProjectButton, &QPushButton::clicked, window_followProject, &QWidget::show); + + // 注单盘口窗口 + window_handicap = new Handicap(); + connect(ui.handicapButton, &QPushButton::clicked, window_handicap, &QWidget::show); + + // 注单赔率窗口 + window_odds = new Odds(); + connect(ui.oddsButton, &QPushButton::clicked, window_odds, &QWidget::show); + + // 注单金额窗口 + window_amount = new Amount(); + connect(ui.amountButton, &QPushButton::clicked, window_amount, &QWidget::show); + + // 赛事盘口窗口 + window_screen = new Screen(); + connect(ui.screenButton, &QPushButton::clicked, window_screen, &QWidget::show); + connect(this, &Setting::signalUpdateLeagueAndTeam, window_screen, &Screen::slotUpdateLeagueAndTeam); + + // 赛事盘口窗口 + window_project = new Project(); + connect(ui.projectButton, &QPushButton::clicked, window_project, &QWidget::show); + + // 补单筛选窗口 + window_rebet = new Rebet(); + connect(ui.rebetButton, &QPushButton::clicked, window_rebet, &QWidget::show); + + window_sleep = new class Sleep(); + connect(ui.sleepButton, &QPushButton::clicked, window_sleep, &QWidget::show); + // 跟单声音窗口 + window_sound = new Sound(); + connect(ui.soundButton, &QPushButton::clicked, window_sound, &QWidget::show); + + + // 初始化表格 + ui.tableWidget->setColumnCount(8); + ui.tableWidget->setHorizontalHeaderLabels({ "启用","注单账号","账号类型","跟单方式","跟单盘口","计算方式","缩放比率","固定金额" }); + + ui.tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + ui.tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch); + ui.tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); + ui.tableWidget->horizontalHeader()->resizeSection(0, 50); + + connect(ui.tableWidget, &QTableWidget::cellClicked, this, &Setting::slotCellClicked); + + // 读取配置 + QList followType = g_config->followType(); + if (followType.contains("normal")) + { + ui.followNormalCheckBox->setChecked(true); + } + else + { + ui.followNormalCheckBox->setChecked(false); + } + + if (followType.contains("addTime")) + { + ui.followAddTimeCheckBox->setChecked(true); + } + else + { + ui.followAddTimeCheckBox->setChecked(false); + } + + if (followType.contains("corner")) + { + ui.cornerCheckBox->setChecked(true); + } + else + { + ui.cornerCheckBox->setChecked(false); + } + + if (followType.contains("free")) + { + ui.freeCheckBox->setChecked(true); + } + else + { + ui.freeCheckBox->setChecked(false); + } + + if (followType.contains("promotion")) + { + ui.promotionCheckBox->setChecked(true); + } + else + { + ui.promotionCheckBox->setChecked(false); + } + + if (followType.contains("champion")) + { + ui.championCheckBox->setChecked(true); + } + else + { + ui.championCheckBox->setChecked(false); + } + + if (followType.contains("point")) + { + ui.pointCheckBox->setChecked(true); + } + else + { + ui.pointCheckBox->setChecked(false); + } + ui.lackHandicapCombo->setCurrentIndex(g_config->lackType()); + ui.followDeviceCombo->setCurrentIndex(g_config->followDeviceType()); + ui.rebetMaxEdit->setText(QString::number(g_config->rebetMaxTimes())); + ui.rebetSleepTimesEdit->setText(QString::number(g_config->rebetSleepTimes())); + ui.rebetSleepEdit->setText(QString::number(g_config->rebetSleep())); + ui.sessionAutoChangeCheckBox->setChecked(g_config->sessionAutoChangeEnable()); + ui.ignoreScoreChangedCheckBox->setChecked(g_config->ignoreScoreChangedEnable()); + ui.followFixedScoreCheckBox->setChecked(g_config->followFixedScoreEnable()); + ui.fixedScoreMasterEdit->setText(QString::number(g_config->fixedScoreMaster())); + ui.fixedScoreVisitorEdit->setText(QString::number(g_config->fixedScoreVisitor())); + + // 用户/代理独立规则设置 + for (int i = 0; i < 10; i++) + { + int index = ui.tableWidget->rowCount(); + ui.tableWidget->insertRow(index); + + QWidget* widget_enable = new QWidget; + QHBoxLayout* layout_enale = new QHBoxLayout; + QCheckBox* chekcBox = new QCheckBox; + layout_enale->addWidget(chekcBox); + layout_enale->setContentsMargins(0, 0, 0, 0); + layout_enale->setAlignment(chekcBox, Qt::AlignCenter); + widget_enable->setLayout(layout_enale); + ui.tableWidget->setCellWidget(index, 0, widget_enable); + + + QComboBox* userNameCombo = new QComboBox; + if (i == 0) + { + userNameCombo->addItem("其他会员"); + userNameCombo->setDisabled(true); + } + + ui.tableWidget->setCellWidget(index, 1, userNameCombo); + + + + QComboBox* userTypeCombo = new QComboBox; + userTypeCombo->addItem("会员"); + userTypeCombo->addItem("代理"); + if (i == 0) + { + userTypeCombo->setDisabled(true); + } + ui.tableWidget->setCellWidget(index, 2, userTypeCombo); + + connect(userTypeCombo, static_cast(&QComboBox::activated), this,&Setting::slotAlertUsersCombo); + + // 跟单方式 + QTableWidgetItem* follow = new QTableWidgetItem("正跟"); + ui.tableWidget->setItem(index, 3, follow); + FollowType* followType = new FollowType(); + m_followTypeList.append(followType); + connect(followType, &FollowType::signalUpdateStatus, this, &Setting::slotUpdateFollowType); + + ui.tableWidget->setItem(index, 4, new QTableWidgetItem("原始盘口")); + FollowHandicap* handicap = new FollowHandicap(); + connect(handicap, &FollowHandicap::signalUpdateStatus, this, &Setting::slotUpdateHandicap); + m_followHandicapList.append(handicap); + + + QComboBox* ratioAmountCombo = new QComboBox; + ratioAmountCombo->addItem("缩放比率"); + ratioAmountCombo->addItem("固定金额"); + ratioAmountCombo->addItem("项目设置"); + + ui.tableWidget->setCellWidget(index, 5, ratioAmountCombo); + + RatioAmount* ratioAmount = new RatioAmount(); + m_ratioAmountList.append(ratioAmount); + connect(ratioAmountCombo, static_cast(&QComboBox::activated), this, [&](const QString& text) { + if (text == "项目设置") + { + m_ratioAmountList[m_ratioAmountList.count() - 1]->show(); + } + }); + + ui.tableWidget->setItem(index, 6, new QTableWidgetItem("1")); + ui.tableWidget->setItem(index, 7, new QTableWidgetItem("50")); + } + + + // 读取配置 + QList> list = g_config->setting(); + + for (int row = 0; row < list.count(); row++) + { + QMap map = list[row]; + + if (map["enable"] == "true") + { + reinterpret_cast(ui.tableWidget->cellWidget(row, 0)->layout()->itemAt(0)->widget())->setChecked(true); + } + + // 直接获取的是Combo,转换后再取数据封装保存 + QComboBox* comboUsername = reinterpret_cast(ui.tableWidget->cellWidget(row, 1)); + if (map["username"] != "") + { + comboUsername->addItem(map["username"]); + comboUsername->setCurrentText(map["username"]); + } + + // 类型 + QComboBox* comboType = reinterpret_cast(ui.tableWidget->cellWidget(row, 2)); + if (map["type"] != "") + { + //comboType->addItem(map["type"]); + comboType->setCurrentText(map["type"]); + } + + + QMap handicap; + handicap["hkEnable"] = map["hkEnable"]; + handicap["hkChange"] = map["hkChange"]; + handicap["masEnable"] = map["masEnable"]; + handicap["masChange"] = map["masChange"]; + handicap["idaEnable"] = map["idaEnable"]; + handicap["idaChange"] = map["idaChange"]; + handicap["eurEnable"] = map["eurEnable"]; + handicap["eurChange"] = map["eurChange"]; + m_followHandicapList[row]->setMap(handicap); + + QList> followType = g_config->toMapList(map["followType"]); + m_followTypeList[row]->setList(followType); + + reinterpret_cast(ui.tableWidget->cellWidget(row, 5))->setCurrentText(map["calcType"]); + m_ratioAmountList[row]->setList(g_config->toMapList(map["calcType_custom"])); + ui.tableWidget->item(row, 6)->setText(map["calcType_scale"]); + ui.tableWidget->item(row, 7)->setText(map["calcType_fixed"]); + } + + slotUpdateHandicap(); + slotUpdateFollowType(); + slotUpdateRatioAmount(); + + + +} + +Setting::~Setting() +{} + +void Setting::slotCellClicked(int row, int column) +{ + QString type = ui.tableWidget->horizontalHeaderItem(column)->text(); + if (type == "跟单方式") + { + m_followTypeList[row]->show(); + } + else if (type == "跟单盘口") + { + m_followHandicapList[row]->show(); + } +} + +void Setting::slotUpdateFollowType() +{ + for (int row = 0; row < m_followTypeList.count(); row++) + { + FollowType* followType = m_followTypeList[row]; + QList> list = followType->list(); + int positiveFollow = 0; + int negativeFollow = 0; + for (int i = 0; i < list.count(); i++) + { + QMap map = list[i]; + if (map["follow_betType"] == "true") + { + positiveFollow++; + } + else + { + negativeFollow++; + } + } + if (positiveFollow == 0) + { + ui.tableWidget->item(row, 3)->setText("反跟"); + } + else if (negativeFollow == 0) + { + ui.tableWidget->item(row, 3)->setText("正跟"); + } + else + { + ui.tableWidget->item(row, 3)->setText("项目设置"); + } + } +} + +void Setting::slotComboChecked(const QString & text) +{ +} + +void Setting::slotUpdateRatioAmount() +{ + + //for (int row = 0; row < m_ratioAmountList.count(); row++) + //{ + // RatioAmount* ratioAmount = m_ratioAmountList[row]; + // QList> list = ratioAmount->list(); + // int scale = 0; + // int fixed = 0; + // for (int i = 0; i < list.count(); i++) + // { + // QMap map = list[i]; + // if (map["type"] == "scale") + // { + // scale++; + // } + // else + // { + // fixed++; + // } + // } + // if (scale == 0) + // { + // QComboBox* combo = reinterpret_cast(ui.tableWidget->cellWidget(row, 5)); + // combo->setCurrentText("固定金额"); + // } + // else if (fixed == 0) + // { + // QComboBox* combo = reinterpret_cast(ui.tableWidget->cellWidget(row, 5)); + // combo->setCurrentText("缩放比率"); + // } + // else + // { + // QComboBox* combo = reinterpret_cast(ui.tableWidget->cellWidget(row, 5)); + // combo->setCurrentText("项目设置"); + // } + //} +} + +void Setting::slotUpdateHandicap() +{ + for (int row = 0; row < m_followHandicapList.count(); row++) + { + QMap map = m_followHandicapList[row]->map(); + if ((map["hkEnable"] == "true" && map["hkChange"] != "H") || + (map["masEnable"] == "true" && map["masChange"] != "M") || + (map["idaEnable"] == "true" && map["idaChange"] != "I") || + (map["eurEnable"] == "true" && map["eurChange"] != "E")) + { + ui.tableWidget->item(row, 4)->setText("项目设置"); + } + else + { + ui.tableWidget->item(row, 4)->setText("原始盘口"); + } + } +} + +void Setting::slotUpdateUsers(QList> list) +{ + + m_users = list; + //qDebug() << "[收到用户列表下拉框][slotUpdateUsers]:" << m_users; + slotAlertUsersCombo(); +} + +void Setting::slotAlertUsersCombo() +{ + //qDebug() << "[修改用户列表下拉框][slotAlertUsersCombo]:" << m_users; + for (int row = 1; row < ui.tableWidget->rowCount(); row++) + { + QComboBox* comboType = reinterpret_cast(ui.tableWidget->cellWidget(row, 2)); + // qDebug() << "row:" << row << "|" << comboType << "|" << sender(); + // 找到发送者 + if (comboType != sender()) + { + continue; + } + QComboBox* combo = reinterpret_cast(ui.tableWidget->cellWidget(row, 1)); + + // + QString originalText = combo->currentText(); + combo->clear(); + + QString type = reinterpret_cast(ui.tableWidget->cellWidget(row, 2))->currentText(); + + if (type == "会员") + { + // 遍历列表 + for (int i = 0; i < m_users.count(); i++) + { + // 会员加入 + // 判断内容为空 且 未加入 + if (m_users[i]["level"] == "user") + { + //if(combo->find()) + if (combo->findText(m_users[i]["username"]) == -1) + { + combo->addItem(m_users[i]["username"]); + if (m_users[i]["username"] == originalText) + { + combo->setCurrentText(originalText); + } + } + + } + } + } + else + { + // 遍历列表 + for (int i = 0; i < m_users.count(); i++) + { + // 代理加入 + if (m_users[i]["level"] != "user") + { + if (combo->findText(m_users[i]["username"]) == -1) + { + combo->addItem(m_users[i]["username"]); + if (m_users[i]["username"] == originalText) + { + combo->setCurrentText(originalText); + } + } + + } + } + } + + + } +} + +void Setting::slotUpdateLeagueAndTeam(QList> list) +{ + emit signalUpdateLeagueAndTeam(list); +} + + +void Setting::closeEvent(QCloseEvent* event) +{ + QList> list; + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + // 先获取跟单盘口 + QMap map = m_followHandicapList[row]->map(); + // 启用 + if (reinterpret_cast(ui.tableWidget->cellWidget(row, 0)->layout()->itemAt(0)->widget())->isChecked()) + { + map["enable"] = "true"; + } + else + { + map["enable"] = "false"; + } + // 帐号 + // 直接获取的是Combo,转换后再取数据封装保存 + QComboBox* comboUsername = reinterpret_cast(ui.tableWidget->cellWidget(row, 1)); + map["username"] = comboUsername->currentText(); + // 类型 + QComboBox* comboType = reinterpret_cast(ui.tableWidget->cellWidget(row, 2)); + map["type"] = comboType->currentText(); + + // 跟单方式 + map["followType"] = g_config->toJson(m_followTypeList[row]->list()); + // 计算方式 + map["calcType"] = reinterpret_cast(ui.tableWidget->cellWidget(row, 5))->currentText(); + map["calcType_custom"] = g_config->toJson(m_ratioAmountList[row]->list()); + map["calcType_scale"] = ui.tableWidget->item(row, 6)->text(); + map["calcType_fixed"] = ui.tableWidget->item(row, 7)->text(); + list.append(map); + } + g_config->setSetting(list); + + QList followType; + if (ui.followNormalCheckBox->isChecked()) + { + followType.append("normal"); + } + if (ui.followAddTimeCheckBox->isChecked()) + { + followType.append("addTime"); + } + if (ui.cornerCheckBox->isChecked()) + { + followType.append("corner"); + } + if (ui.freeCheckBox->isChecked()) + { + followType.append("free"); + } + if (ui.promotionCheckBox->isChecked()) + { + followType.append("promotion"); + } + if (ui.championCheckBox->isChecked()) + { + followType.append("champion"); + } + if (ui.pointCheckBox->isChecked()) + { + followType.append("point"); + } + g_config->setFollowType(followType); + + g_config->setLackType(ui.lackHandicapCombo->currentIndex()); + g_config->setFollowDeviceType(ui.followDeviceCombo->currentIndex()); + g_config->setReBetMaxTimes(ui.rebetMaxEdit->text().toInt()); + g_config->setRebetSleepTimes(ui.rebetSleepTimesEdit->text().toInt()); + g_config->setRebetSleep(ui.rebetSleepEdit->text().toInt()); + g_config->setSessionAutoChangeEnable(ui.sessionAutoChangeCheckBox->isChecked()); + g_config->setIgnoreScoreChangedEnable(ui.ignoreScoreChangedCheckBox->isChecked()); + g_config->setFollowFixedScoreEnable(ui.followFixedScoreCheckBox->isChecked()); + g_config->setFixedScoreMaster(ui.fixedScoreMasterEdit->text().toInt()); + g_config->setFixedScoreVisitor(ui.fixedScoreVisitorEdit->text().toInt()); +} \ No newline at end of file diff --git a/CrownClient/Setting.h b/CrownClient/Setting.h new file mode 100644 index 0000000..21cb30d --- /dev/null +++ b/CrownClient/Setting.h @@ -0,0 +1,61 @@ +#pragma once + +#include +#include "ui_Setting.h" + +#include "FollowProject.h" +#include "Handicap.h" +#include "Odds.h" +#include "Amount.h" +#include "Project.h" +#include "CheckBoxHeaderView.h" +#include "Sleep.h" +#include "Screen.h" +#include "Sound.h" +#include "Rebet.h" + +#include "FollowType.h" +#include "RatioAmount.h" +#include "FollowHandicap.h" + +class Setting : public QWidget +{ + Q_OBJECT + +public: + Setting(QWidget *parent = nullptr); + ~Setting(); +signals: + void signalUpdateLeagueAndTeam(QList> list); +public slots: + void slotUpdateLeagueAndTeam(QList> list); + void slotCellClicked(int row, int column); + void slotUpdateFollowType(); + void slotComboChecked(const QString& text); + void slotUpdateRatioAmount(); + void slotUpdateHandicap(); + void slotUpdateUsers(QList>); + void slotAlertUsersCombo(); +private: + FollowProject* window_followProject; + Handicap* window_handicap; + Odds* window_odds; + Amount* window_amount; + Screen* window_screen; + Project* window_project; + Rebet* window_rebet; + class Sleep* window_sleep; + Sound* window_sound; +private: + QList m_followTypeList; + QList m_ratioAmountList; + QList m_followHandicapList; + QList> m_users; + +private: + void closeEvent(QCloseEvent* event); + + +private: + Ui::SettingClass ui; +}; diff --git a/CrownClient/Setting.ui b/CrownClient/Setting.ui new file mode 100644 index 0000000..3e16488 --- /dev/null +++ b/CrownClient/Setting.ui @@ -0,0 +1,485 @@ + + + SettingClass + + + + 0 + 0 + 1047 + 692 + + + + Setting + + + + + + + + 跟单项目 + + + + + + + 注单盘口 + + + + + + + 注单赔率 + + + + + + + 注单金额 + + + + + + + 赛事盘口 + + + + + + + 赛事筛选 + + + + + + + 补单筛选 + + + + + + + 跟单延时 + + + + + + + 跟单声音 + + + + + + + + + + + + + + + + + + 账号设置: + + + + + + + false + + + 启用会员账号提示列表 + + + true + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 注单账号匹配顺序:①会员账号 ②登3代理 ③登2代理 ④其他会员 + + + + + + + + + + + + + + + + + + 跟单类型: + + + + + + + 普通 + + + true + + + + + + + 加时 + + + true + + + + + + + 角球 + + + true + + + + + + + 罚球 + + + true + + + + + + + 晋级 + + + true + + + + + + + 冠军 + + + true + + + + + + + 点球 + + + true + + + + + + + + + + + + + + + + 跟单会员缺少注单所需[盘口类型]: + + + + + + + + 使用[香港盘类型]进行跟单 + + + + + [过滤注单]等会员重新设置 + + + + + + + + + + + + + + + + + + + + + 跟单设置: + + + + + + + + 普通跟单(自动) + + + + + 手机跟单 + + + + + + + + + + + + + + + + + 最多补单次数: + + + + + + + + 50 + 16777215 + + + + 100 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 达到补单次数: + + + + + + + + 50 + 16777215 + + + + 30 + + + + + + + 延时秒数: + + + + + + + + 50 + 16777215 + + + + 10 + + + + + + + + + + + + + + + + + + 赛事设置: + + + + + + + (早盘)变(今日)变(滚球)自动切换 + + + true + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 比分变化不跟 + + + true + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 只跟固定比分 + + + + + + + + 0 + 0 + + + + + 30 + 16777215 + + + + 0 + + + + + + + : + + + + + + + + 30 + 16777215 + + + + 0 + + + + + + + + + + + + diff --git a/CrownClient/Sleep.cpp b/CrownClient/Sleep.cpp new file mode 100644 index 0000000..d6feb93 --- /dev/null +++ b/CrownClient/Sleep.cpp @@ -0,0 +1,146 @@ +#include "Sleep.h" +#include "Global.h" +Sleep::Sleep(QWidget *parent) + : QWidget(parent) +{ + ui.setupUi(this); + + // 设置窗口图标 + this->setWindowIcon(QIcon(":/images/Images/client.ico")); + // 设置窗口标题 + this->setWindowTitle("跟单延时判断处理"); + // 设置为对话框窗口 + setWindowFlags(Qt::Dialog); + // 设置窗口仅有关闭按钮 + setWindowFlags(Qt::WindowCloseButtonHint); + setFixedSize(752,561); + + + ui.tableWidget->setColumnCount(7); + ui.tableWidget->setHorizontalHeaderLabels({ "注单项目", "跟单之前\n最小延时","跟单之前\n最大延时","跟单成功\n最小延时","跟单成功\n最大延时","跟单失败\n最小延时","跟单失败\n最大延时"}); + ui.tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + ui.tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); + ui.tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch); + ui.tableWidget->horizontalHeader()->resizeSection(0, 50); + + for (int i = 0; i < 9; i++) + { + ui.tableWidget->insertRow(i); + ui.tableWidget->setItem(i, 0, new QTableWidgetItem(g_gameTypes[i])); + ui.tableWidget->setItem(i, 1, new QTableWidgetItem("0")); + ui.tableWidget->item(i, 1)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + ui.tableWidget->setItem(i, 2, new QTableWidgetItem("0")); + ui.tableWidget->item(i, 2)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + ui.tableWidget->setItem(i, 3, new QTableWidgetItem("0")); + ui.tableWidget->item(i, 3)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + ui.tableWidget->setItem(i, 4, new QTableWidgetItem("0")); + ui.tableWidget->item(i, 4)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + ui.tableWidget->setItem(i, 5, new QTableWidgetItem("0")); + ui.tableWidget->item(i, 5)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + ui.tableWidget->setItem(i, 6, new QTableWidgetItem("0")); + ui.tableWidget->item(i, 6)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + } + + QList> list = g_config->sleep(); + for (int i = 0; i < list.count(); i++) + { + QMap map = list[i]; + ui.tableWidget->item(map["row"].toInt(), map["column"].toInt())->setText(map["sleep"]); + } + + ui.betBeforeSleepMin->setText(QString::number(g_config->betBeforeSleepMin())); + ui.betBeforeSleepMax->setText(QString::number(g_config->betBeforeSleepMax())); + + ui.betSuccessSleepMin->setText(QString::number(g_config->betSuccessSleepMin())); + ui.betSuccessSleepMax->setText(QString::number(g_config->betSuccessSleepMax())); + + ui.betFailedSleepMin->setText(QString::number(g_config->betFailedSleepMin())); + ui.betFailedSleepMax->setText(QString::number(g_config->betFailedSleepMax())); + + ui.betBeforeCalcCombo->setCurrentIndex(g_config->betBeforeCalcIndex()); + + ui.projectCheckBox->setChecked(g_config->sleepProjectEnable()); + ui.projectCombo->setCurrentIndex(g_config->sleepProjectIndex()); + + connect(ui.setButton, &QPushButton::clicked, this, [&]() { + + if (ui.projectCheckBox->isChecked()) + { + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + if (ui.tableWidget->item(row, 0)->text() == ui.projectCombo->currentText()) + { + ui.tableWidget->item(row, 1)->setText(ui.betBeforeSleepMin->text()); + ui.tableWidget->item(row, 2)->setText(ui.betBeforeSleepMax->text()); + ui.tableWidget->item(row, 3)->setText(ui.betSuccessSleepMin->text()); + ui.tableWidget->item(row, 4)->setText(ui.betSuccessSleepMax->text()); + ui.tableWidget->item(row, 5)->setText(ui.betFailedSleepMin->text()); + ui.tableWidget->item(row, 6)->setText(ui.betFailedSleepMax->text()); + } + } + } + else + { + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + ui.tableWidget->item(row, 1)->setText(ui.betBeforeSleepMin->text()); + ui.tableWidget->item(row, 2)->setText(ui.betBeforeSleepMax->text()); + ui.tableWidget->item(row, 3)->setText(ui.betSuccessSleepMin->text()); + ui.tableWidget->item(row, 4)->setText(ui.betSuccessSleepMax->text()); + ui.tableWidget->item(row, 5)->setText(ui.betFailedSleepMin->text()); + ui.tableWidget->item(row, 6)->setText(ui.betFailedSleepMax->text()); + } + } + + + + }); + + +} + +Sleep::~Sleep() +{ + +} + +void Sleep::closeEvent(QCloseEvent * event) +{ + QList> list; + for (int row = 0; row < ui.tableWidget->rowCount(); row++) + { + QString rowText = ui.tableWidget->item(row, 0)->text(); + for (int column = 0; column < ui.tableWidget->columnCount(); column++) + { + if (column == 0) + { + continue; + } + + QMap map; + map["project"] = rowText; + map["row"] = QString::number(row); + map["column"] = QString::number(column); + map["type"] = QString::number(column); + map["sleep"] = ui.tableWidget->item(row, column)->text(); + + list.append(map); + } + } + + g_config->setSleep(list); + + g_config->setBetBeforeSleepMin(ui.betBeforeSleepMin->text().toInt()); + g_config->setBetBeforeSleepMax(ui.betBeforeSleepMax->text().toInt()); + + g_config->setBetSuccessSleepMin(ui.betSuccessSleepMin->text().toInt()); + g_config->setBetSuccessSleepMax(ui.betSuccessSleepMax->text().toInt()); + + g_config->setBetFailedSleepMin(ui.betFailedSleepMin->text().toInt()); + g_config->setBetFailedSleepMax(ui.betFailedSleepMax->text().toInt()); + + g_config->setBetBeforeCalcIndex(ui.betBeforeCalcCombo->currentIndex()); + + g_config->setSleepProjectEnable(ui.projectCheckBox->isChecked()); + g_config->setSleepProjectIndex(ui.projectCombo->currentIndex()); +} diff --git a/CrownClient/Sleep.h b/CrownClient/Sleep.h new file mode 100644 index 0000000..d03d1c6 --- /dev/null +++ b/CrownClient/Sleep.h @@ -0,0 +1,17 @@ +#pragma once + +#include +#include "ui_Sleep.h" + +class Sleep : public QWidget +{ + Q_OBJECT + +public: + Sleep(QWidget *parent = nullptr); + ~Sleep(); +private: + void closeEvent(QCloseEvent* event); +private: + Ui::SleepClass ui; +}; diff --git a/CrownClient/Sleep.ui b/CrownClient/Sleep.ui new file mode 100644 index 0000000..bf52784 --- /dev/null +++ b/CrownClient/Sleep.ui @@ -0,0 +1,280 @@ + + + SleepClass + + + + 0 + 0 + 744 + 651 + + + + Sleep + + + + + + + + + + + + + + + + + 跟单之前最小延时 + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 跟单成功最小延时 + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 跟单失败最小延时 + + + + + + + + + + + + + + 跟单之前最大延时 + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 跟单成功最大延时 + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 跟单失败最大延时 + + + + + + + + + + + + + + 跟单之前开始计算 + + + + + + + + 下注时间 + + + + + 读取时间 + + + + + 接收时间 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 注单项目: + + + + + + + + 足球滚球全场 + + + + + 足球滚球上半场 + + + + + 足球今日全场 + + + + + 足球今日上半场 + + + + + 足球早盘全场 + + + + + 足球早盘上半场 + + + + + 篮球滚球全部 + + + + + 篮球今日全部 + + + + + 篮球早盘全部 + + + + + + + + 设置延时 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + <html><head/><body><p align="center"><span style=" color:#13911c;">如果(最小值|最大值)不一致,则延时两数之间随机值.</span></p></body></html> + + + + + + + + + + + + diff --git a/CrownClient/Sound.cpp b/CrownClient/Sound.cpp new file mode 100644 index 0000000..539cfbb --- /dev/null +++ b/CrownClient/Sound.cpp @@ -0,0 +1,238 @@ +#include "Sound.h" +#include +#include "Global.h" +#include +Sound::Sound(QWidget *parent) + : QWidget(parent) +{ + ui.setupUi(this); + + this->setWindowTitle("跟单声音判断处理"); + // 设置窗口图标 + this->setWindowIcon(QIcon(":/images/Images/client.ico")); + // 设置窗口样式 + setWindowFlags(Qt::Dialog); + setWindowFlags(Qt::WindowCloseButtonHint); + this->setFixedSize(475, 450); + + + // 读取配置 + ui.acceptCheckBox->setChecked(g_config->acceptOrderSoundEnable()); + ui.acceptEdit->setText(g_config->acceptOrderSoundPath()); + + ui.screenCheckBox->setChecked(g_config->screenOrderSoundEnable()); + ui.screenEdit->setText(g_config->screenOrderSoundPath()); + + ui.followSuccessCheckBox->setChecked(g_config->followOrderSuccessSoundEnable()); + ui.followSuccessEdit->setText(g_config->followOrderSuccessSoundPath()); + + + ui.followFailedCheckBox->setChecked(g_config->followOrderFailedSoundEnable()); + ui.followFailedEdit->setText(g_config->followOrderFailedSoundPath()); + + ui.disconnectCheckBox->setChecked(g_config->disconnectSoundEnable()); + ui.disconnectEdit->setText(g_config->disconnectSoundPath()); + + ui.pushFailedCheckBox->setChecked(g_config->pushFailedSoundEnable()); + ui.pushFailedEdit->setText(g_config->pushFailedSoundPath()); + + ui.exitCheckBox->setChecked(g_config->exitSoundEnable()); + ui.exitEdit->setText(g_config->exitSoundPath()); + + ui.reloginCheckBox->setChecked(g_config->reloginSoundEnable()); + ui.reloginEdit->setText(g_config->reloginSoundPath()); + + ui.updataCheckBox->setChecked(g_config->softUpdateSoundEnable()); + ui.updataEdit->setText(g_config->softUpdateSoundPath()); + + connect(ui.acceptBrowseButton, &QPushButton::clicked, this, [&]() { + QString fileName = QFileDialog::getOpenFileName(this, "浏览", QDir::currentPath(), "mp3(*mp3);;wav(*.wav)"); + g_config->setAcceptOrderSoundPath(fileName); + ui.acceptEdit->setText(fileName); + }); + + connect(ui.screenBrowseButton, &QPushButton::clicked, this, [&]() { + QString fileName = QFileDialog::getOpenFileName(this, "浏览", QDir::currentPath(), "mp3(*mp3);;wav(*.wav)"); + g_config->setScreenOrderSoundPath(fileName); + ui.screenEdit->setText(fileName); + }); + + connect(ui.followSuccessBrowseButton, &QPushButton::clicked, this, [&]() { + QString fileName = QFileDialog::getOpenFileName(this, "浏览", QDir::currentPath(), "mp3(*mp3);;wav(*.wav)"); + g_config->setFollowOrderSuccessSoundPath(fileName); + ui.followSuccessEdit->setText(fileName); + }); + + connect(ui.followFailedBrowseButton, &QPushButton::clicked, this, [&]() { + QString fileName = QFileDialog::getOpenFileName(this, "浏览", QDir::currentPath(), "mp3(*mp3);;wav(*.wav)"); + g_config->setFollowOrderFailedSoundPath(fileName); + ui.followFailedEdit->setText(fileName); + }); + + connect(ui.disconnectBrowseButton, &QPushButton::clicked, this, [&]() { + QString fileName = QFileDialog::getOpenFileName(this, "浏览", QDir::currentPath(), "mp3(*mp3);;wav(*.wav)"); + g_config->setDisconnectSoundPath(fileName); + ui.disconnectEdit->setText(fileName); + }); + + connect(ui.pushFailedBrowseButton, &QPushButton::clicked, this, [&]() { + QString fileName = QFileDialog::getOpenFileName(this, "浏览", QDir::currentPath(), "mp3(*mp3);;wav(*.wav)"); + g_config->setPushFailedSoundPath(fileName); + ui.pushFailedEdit->setText(fileName); + }); + + connect(ui.exitBrowseButton, &QPushButton::clicked, this, [&]() { + QString fileName = QFileDialog::getOpenFileName(this,"浏览", QDir::currentPath(), "mp3(*mp3);;wav(*.wav)"); + g_config->setExitSoundPath(fileName); + ui.exitEdit->setText(fileName); + }); + + connect(ui.reloginBrowseButton, &QPushButton::clicked, this, [&]() { + QString fileName = QFileDialog::getOpenFileName(this, "浏览", QDir::currentPath(), "mp3(*mp3);;wav(*.wav)"); + g_config->setReloginSoundPath(fileName); + ui.reloginEdit->setText(fileName); + }); + + connect(ui.updataBrowseButton, &QPushButton::clicked, this, [&]() { + QString fileName = QFileDialog::getOpenFileName(this, "浏览", QDir::currentPath(), "mp3(*mp3);;wav(*.wav)"); + g_config->setSoftUpdateSoundPath(fileName); + ui.updataEdit->setText(fileName); + }); + + connect(ui.acceptPlayButton, &QPushButton::clicked, this, [&]() { + QString path = ui.acceptEdit->text(); + if (path.isEmpty()) + { + QSound::play(":/sound/sound/accept.wav"); + } + else + { + QSound::play(path); + } + }); + + connect(ui.screenPlayButton, &QPushButton::clicked, this, [&]() { + QString path = ui.screenEdit->text(); + if (path.isEmpty()) + { + QSound::play(":/sound/sound/screen.wav"); + } + else + { + QSound::play(path); + } + }); + + connect(ui.followSuccessPlayButton, &QPushButton::clicked, this, [&]() { + QString path = ui.followSuccessEdit->text(); + if (path.isEmpty()) + { + QSound::play(":/sound/sound/success.wav"); + } + else + { + QSound::play(path); + } + }); + + connect(ui.followFailedPlayButton, &QPushButton::clicked, this, [&]() { + QString path = ui.followFailedEdit->text(); + if (path.isEmpty()) + { + QSound::play(":/sound/sound/failed.wav"); + } + else + { + QSound::play(path); + } + }); + + connect(ui.disconnectPlayButton, &QPushButton::clicked, this, [&]() { + QString path = ui.disconnectEdit->text(); + if (path.isEmpty()) + { + QSound::play(":/sound/sound/disconnect.wav"); + } + else + { + QSound::play(path); + } + }); + + connect(ui.pushFailedPlayButton, &QPushButton::clicked, this, [&]() { + QString path = ui.pushFailedEdit->text(); + if (path.isEmpty()) + { + QSound::play(":/sound/sound/pushFailed.wav"); + } + else + { + QSound::play(path); + } + }); + + connect(ui.exitPlayButton, &QPushButton::clicked, this, [&]() { + QString path = ui.exitEdit->text(); + if (path.isEmpty()) + { + QSound::play(":/sound/sound/exit.wav"); + } + else + { + QSound::play(path); + } + }); + + connect(ui.reloginPlayButton, &QPushButton::clicked, this, [&]() { + QString path = ui.reloginEdit->text(); + if (path.isEmpty()) + { + QSound::play(":/sound/sound/relogin.wav"); + } + else + { + QSound::play(path); + } + }); + + connect(ui.updataPlayButton, &QPushButton::clicked, this, [&]() { + QString path = ui.updataEdit->text(); + if (path.isEmpty()) + { + QSound::play(":/sound/sound/update.wav"); + } + else + { + QSound::play(path); + } + }); + +} + +Sound::~Sound() +{} + + +void Sound::closeEvent(QCloseEvent* event) +{ + g_config->setAcceptOrderSoundEnable(ui.acceptCheckBox->isChecked()); + g_config->setScreenOrderSoundEnable(ui.screenCheckBox->isChecked()); + g_config->setFollowOrderSuccessSoundEnable(ui.followSuccessCheckBox->isChecked()); + g_config->setFollowOrderFailedSoundEnable(ui.followFailedCheckBox->isChecked()); + g_config->setDisconnectSoundEnable(ui.disconnectCheckBox->isChecked()); + g_config->setPushFailedSoundEnable(ui.pushFailedCheckBox->isChecked()); + g_config->setExitSoundEnable(ui.exitCheckBox->isChecked()); + g_config->setReloginSoundEnable(ui.reloginCheckBox->isChecked()); + g_config->setSoftUpdateSoundEnable(ui.updataCheckBox->isChecked()); + + + g_config->setAcceptOrderSoundPath(ui.acceptEdit->text()); + g_config->setScreenOrderSoundPath(ui.screenEdit->text()); + g_config->setFollowOrderSuccessSoundPath(ui.followSuccessEdit->text()); + g_config->setFollowOrderFailedSoundPath(ui.followFailedEdit->text()); + g_config->setDisconnectSoundPath(ui.disconnectEdit->text()); + g_config->setPushFailedSoundPath(ui.pushFailedEdit->text()); + g_config->setExitSoundPath(ui.exitEdit->text()); + g_config->setReloginSoundPath(ui.reloginEdit->text()); + g_config->setSoftUpdateSoundPath(ui.updataEdit->text()); +} \ No newline at end of file diff --git a/CrownClient/Sound.h b/CrownClient/Sound.h new file mode 100644 index 0000000..9710a66 --- /dev/null +++ b/CrownClient/Sound.h @@ -0,0 +1,17 @@ +#pragma once + +#include +#include "ui_Sound.h" + +class Sound : public QWidget +{ + Q_OBJECT + +public: + Sound(QWidget *parent = nullptr); + ~Sound(); +private: + void closeEvent(QCloseEvent* event); +private: + Ui::SoundClass ui; +}; diff --git a/CrownClient/Sound.ui b/CrownClient/Sound.ui new file mode 100644 index 0000000..f243ae7 --- /dev/null +++ b/CrownClient/Sound.ui @@ -0,0 +1,287 @@ + + + SoundClass + + + + 0 + 0 + 513 + 524 + + + + Sound + + + + + + 声音设置 + + + + + + + + 接收注单: + + + + + + + + + + 浏览 + + + + + + + 播放 + + + + + + + + + + + 过滤注单: + + + + + + + + + + + + + + 浏览 + + + + + + + 播放 + + + + + + + + + + + 跟单成功: + + + + + + + + + + 浏览 + + + + + + + 播放 + + + + + + + + + + + 跟单失败: + + + + + + + + + + 浏览 + + + + + + + 播放 + + + + + + + + + + + 连接断开: + + + + + + + + + + 浏览 + + + + + + + 播放 + + + + + + + + + + + 推送失败: + + + + + + + + + + 浏览 + + + + + + + 播放 + + + + + + + + + + + 强制退出: + + + + + + + + + + 浏览 + + + + + + + 播放 + + + + + + + + + + + 重新登录: + + + + + + + + + + 浏览 + + + + + + + 播放 + + + + + + + + + + + 软件升级: + + + + + + + + + + 浏览 + + + + + + + 播放 + + + + + + + + + + + + + + diff --git a/CrownClient/StyleLoader.h b/CrownClient/StyleLoader.h new file mode 100644 index 0000000..acbb267 --- /dev/null +++ b/CrownClient/StyleLoader.h @@ -0,0 +1,21 @@ +// StyleLoader.h +#pragma once +#include +#include +#include + +class StyleLoader { +public: + // 修改StyleLoader.cpp中的loadStyle方法 + static QString StyleLoader::loadStyleFromResource() { + QFile file(":/style/Resources/visual_studio_dark.qss"); + if (!file.open(QIODevice::ReadOnly)) { + return QString(); + } + + QTextStream stream(&file); + QString style = stream.readAll(); + file.close(); + return style; + } +}; \ No newline at end of file diff --git a/CrownClient/TcpSocket.cpp b/CrownClient/TcpSocket.cpp new file mode 100644 index 0000000..b17e7c8 --- /dev/null +++ b/CrownClient/TcpSocket.cpp @@ -0,0 +1,219 @@ +#include "TcpSocket.h" + +TcpSocket::TcpSocket(QObject* parent) : QTcpSocket(parent) +{ + m_heartbeatTimer = new QTimer(); + // 接收数据 + connect(this, &TcpSocket::readyRead, this, &TcpSocket::slotDataRecv, Qt::QueuedConnection); + // 发送数据 + connect(this, &TcpSocket::signalSendData, this, &TcpSocket::slotSendData, Qt::QueuedConnection); + + connect(m_heartbeatTimer, &QTimer::timeout, this, &TcpSocket::slotHeartBeat); + connect(this, &TcpSocket::disconnected, this, [&]() { + //qDebug() << "停止心跳-------------------"; + m_heartbeatTimer->stop(); + }); + + m_heartbeatDateTime = QDateTime::currentDateTime(); + m_heartbeatTimer->start(3000); +} + +TcpSocket::~TcpSocket() +{ + //qDebug() << "TcpSocket 析构开始"; + + // 先断开所有信号,防止回调时访问已释放的对象 + this->disconnect(); + + // 停止心跳定时器 + if (m_heartbeatTimer) { + m_heartbeatTimer->stop(); + m_heartbeatTimer->deleteLater(); + m_heartbeatTimer = nullptr; + } + + // 如果还在连接状态,优雅断开 + if (this->state() == QAbstractSocket::ConnectedState) { + //qDebug() << "TcpSocket 析构时断开连接"; + this->disconnectFromHost(); + // 等待连接断开 + if (this->waitForDisconnected(1000)) { + //qDebug() << "TcpSocket 连接已优雅断开"; + } else { + //qDebug() << "TcpSocket 连接断开超时,强制断开"; + this->abort(); + } + } + + //qDebug() << "TcpSocket 析构完成"; +} + +/// +/// 封包发送 +/// +/// 数据 +/// 数据长度 +void TcpSocket::slotSendData(QByteArray data) +{ + if (data.isEmpty()) + { + //qDebug() << "Socket:send data is empty"; + return; + } + if (this->state() != QTcpSocket::ConnectedState) + { + //qDebug() << "Socket:state error:" << this->state(); + return; + } + QByteArray dataType = NET_PACKET_TYPE_SEND_TEXT; + // [包类型 + 数据 + 包尾] + QByteArray packet = dataType + data + NET_PACKET_END; + // 长度占8字节,前面补零,如"00065536" + int size = packet.size(); + QByteArray length = QByteArray().setNum(size); + length = QByteArray(NET_PACKET_LENGTH_BYTES, '0') + length; + length = length.right(NET_PACKET_LENGTH_BYTES); + // 插入 [包头 + 数据长度] + packet.insert(0, NET_PACKET_START + length); + this->write(packet); + this->flush(); +} + +/// +/// 解包 +/// +/// 数据 +/// 数据长度 +bool TcpSocket::parsePacket(SocketPacket *packet) +{ + int pIndexStart = packet->data.indexOf(NET_PACKET_START); + if (pIndexStart < 0) + { + return false; + } + + packet->data = packet->data.mid(pIndexStart); //截取从包头index_start到末尾的数据 + SocketPacket tmpPacket; + tmpPacket.data = packet->data; + + tmpPacket.data.remove(0, QByteArray(NET_PACKET_START).size());//删除包头 + + //解析包长度 + if (tmpPacket.data.count() < NET_PACKET_LENGTH_BYTES) + { + return false; + } + bool isOk; + tmpPacket.length = tmpPacket.data.mid(0, NET_PACKET_LENGTH_BYTES).toLong(&isOk); + if (isOk == false) + { + packet->data.remove(0, QByteArray(NET_PACKET_START).size());//删除包头 + if (packet->data.indexOf(NET_PACKET_START) >= 0) + { + return true;//有可能出现粘包的情况,继续解析后面数据 + } + else + { + return false; + } + } + + //数据到达包长度 + tmpPacket.data.remove(0, NET_PACKET_LENGTH_BYTES);//删除数据长度 + if (tmpPacket.length > tmpPacket.data.count()) + { + return false; + } + + //包尾是否匹配 + tmpPacket.data.resize(tmpPacket.length);//删除多余数据 + if (tmpPacket.data.endsWith(NET_PACKET_END) == false) + { + packet->data.remove(0, QByteArray(NET_PACKET_START).size());//删除包头 + if (packet->data.indexOf(NET_PACKET_START) >= 0) + { + return true;//有可能出现粘包的情况,继续解析后面数据 + } + else + { + return false; + } + } + + tmpPacket.data.resize(tmpPacket.length - + QByteArray(NET_PACKET_END).count()); //删除包尾 + + //解析出数据类型 + if (tmpPacket.data.count() < NET_PACKET_TYPE_BYTES) + { + return false; + } + QByteArray dataType = tmpPacket.data.left(NET_PACKET_TYPE_BYTES); + tmpPacket.dataType = dataType; + + tmpPacket.data.remove(0, NET_PACKET_TYPE_BYTES);//删除数据类型 + + //删除当前包数据 + packet->data.remove(0, + QByteArray(NET_PACKET_START).size() + + NET_PACKET_LENGTH_BYTES + + tmpPacket.length); + + //发送数据包消息 + if (tmpPacket.data == QString("@HEARTBEAT@").toUtf8()) + { + //qDebug() << "更新心跳"; + m_heartbeatDateTime = QDateTime::currentDateTime(); + if (!m_heartbeatTimer->isActive() && this->state() == QTcpSocket::ConnectedState) + { + m_heartbeatTimer->start(3000); + } + } + else + { + emit signalDataRecv(this->socketDescriptor(), tmpPacket.data); + } + + //dealDataPacket(tmpPacket); + + return true; +} + + + +void TcpSocket::slotDataRecv() +{ + m_dataPacket.data += this->readAll(); + + // 循环解析包数据,m_dataPacket.data 中可能不只一包数据 + bool isOk = false; + do { + isOk = parsePacket(&m_dataPacket); + } while (isOk); +} + + +void TcpSocket::slotHeartBeat() +{ + // 15秒超时 + if (this->m_heartbeatDateTime.msecsTo(QDateTime::currentDateTime()) > 15000) + { + //qDebug() << "心跳超时掉线:" << this->state(); + if (this->state() == QTcpSocket::ConnectedState) + { + + emit this->error(QAbstractSocket::SocketTimeoutError); + + } + m_heartbeatTimer->stop(); + } + else + { + //qDebug() << "发送心跳"; + QByteArray data = QString("@HEARTBEAT@").toUtf8(); + // 发送心跳 + emit signalSendData(data); + } +} + + diff --git a/CrownClient/TcpSocket.h b/CrownClient/TcpSocket.h new file mode 100644 index 0000000..cbb8805 --- /dev/null +++ b/CrownClient/TcpSocket.h @@ -0,0 +1,32 @@ +#pragma once +#include +#include +#include +#include +#include "Constant.h" + + +class TcpSocket : public QTcpSocket +{ + Q_OBJECT +public: + TcpSocket(QObject* parent = Q_NULLPTR); + ~TcpSocket(); +public: + SocketPacket m_dataPacket; + // 心跳定时器 + QTimer* m_heartbeatTimer; + // 心跳时间 + QDateTime m_heartbeatDateTime; +private: + bool parsePacket(SocketPacket *packet); +signals: + void signalDataRecv(qintptr socketDescriptor, QByteArray data); + void signalDisConnected(qintptr socketDescriptor); + void signalSendData(QByteArray data); + +public slots: + void slotDataRecv(); + void slotSendData(QByteArray data); + void slotHeartBeat(); +}; diff --git a/CrownClient/User.cpp b/CrownClient/User.cpp new file mode 100644 index 0000000..6fe01d4 --- /dev/null +++ b/CrownClient/User.cpp @@ -0,0 +1,123 @@ +#include "User.h" +#include +#include +#include "Global.h" +User::User(QWidget *parent) + : QWidget(parent) +{ + ui.setupUi(this); + + this->setWindowTitle("账户管理"); + // 设置窗口图标 + this->setWindowIcon(QIcon(":/images/Images/client.ico")); + setWindowFlags(Qt::Dialog); + setWindowFlags(Qt::WindowCloseButtonHint); + this->setFixedSize(400, 500); + + // 读取配置 + m_users = g_config->usersList(); + for (int i = 0; i < m_users.count(); i++) + { + QMap user = m_users[i]; + // 添加视图 + int index = ui.tableWidget->rowCount(); + ui.tableWidget->insertRow(index); + ui.tableWidget->setItem(index, 0, new QTableWidgetItem(user["username"])); + ui.tableWidget->setItem(index, 1, new QTableWidgetItem(user["password"])); + } + + // 设置禁止编辑 + ui.tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); + // 设置选择行为为整行选中 + ui.tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); + // 设置表头拉伸方式 + ui.tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + // 设置自定义上下文菜单方案 + ui.tableWidget->setContextMenuPolicy(Qt::CustomContextMenu); + + // 创建自定义菜单 + m_menu = new QMenu(ui.tableWidget); + m_actionDelete = new QAction("删除", this); + m_menu->addAction(m_actionDelete); + // 连接自定义菜单请求与槽 + connect(ui.tableWidget, &QTableWidget::customContextMenuRequested, this, [=](QPoint point) { + m_menu->exec(QCursor::pos()); + }); + // 连接动作触发请求与槽 + connect(m_actionDelete, &QAction::triggered, this,&User::slotDelete); + // 设置双击事件 + connect(ui.tableWidget, &QTableWidget::itemDoubleClicked, this, [=]() { + int row = ui.tableWidget->currentRow(); + QString username = ui.tableWidget->item(row, 0)->text(); + QString password = ui.tableWidget->item(row, 1)->text(); + emit signalSetUser(username, password); + }); + +} + +User::~User() +{ + + +} + + + +void User::slotDelete(bool ok) +{ + int row = ui.tableWidget->currentRow(); + QString username = ui.tableWidget->item(row, 0)->text(); + QString password = ui.tableWidget->item(row, 1)->text(); + // 删除视图 + ui.tableWidget->removeRow(row); + + // 删除配置 + for (int i = 0; i < m_users.count();i++) + { + QMap user = m_users[i]; + if (user["username"] == username && user["password"] == password) + { + m_users.removeAt(i); + break; + } + } + g_config->setUsersList(m_users); +} + + +void User::slotAddUser(QString username, QString password) +{ + bool found = false; + QList>::iterator iter; + for (iter = m_users.begin(); iter != m_users.end(); iter++) + { + QMap user = *iter; + if (user["username"] == username && user["password"] == password) + { + found = true; + break; + } + } + // 避免重复添加 + if (found) + { + return; + } + + if (username.isEmpty() || password.isEmpty()) + { + return; + } + // 添加视图 + int index = ui.tableWidget->rowCount(); + ui.tableWidget->insertRow(index); + ui.tableWidget->setItem(index, 0, new QTableWidgetItem(username)); + ui.tableWidget->setItem(index, 1, new QTableWidgetItem(password)); + + // 保存配置 + QMap user; + user["username"] = username; + user["password"] = password; + m_users.append(user); + g_config->setUsersList(m_users); +} \ No newline at end of file diff --git a/CrownClient/User.h b/CrownClient/User.h new file mode 100644 index 0000000..0854c8e --- /dev/null +++ b/CrownClient/User.h @@ -0,0 +1,32 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include "ui_User.h" + +class User : public QWidget +{ + Q_OBJECT + +public: + User(QWidget *parent = nullptr); + ~User(); + +private: + Ui::UserClass ui; + +signals: + void signalSetUser(QString username, QString password); +public slots: + void slotAddUser(QString username, QString password); + void slotDelete(bool); +private: + QMenu* m_menu; + QAction* m_actionDelete; + QList> m_users; +}; diff --git a/CrownClient/User.ui b/CrownClient/User.ui new file mode 100644 index 0000000..9e390ca --- /dev/null +++ b/CrownClient/User.ui @@ -0,0 +1,36 @@ + + + UserClass + + + + 0 + 0 + 367 + 376 + + + + User + + + + + + + 账号 + + + + + 密码 + + + + + + + + + + diff --git a/CrownClient/Utils.cpp b/CrownClient/Utils.cpp new file mode 100644 index 0000000..f2ce6e6 --- /dev/null +++ b/CrownClient/Utils.cpp @@ -0,0 +1,1703 @@ +#include "Utils.h" + + +#include +Utils::Utils() +{ +} + +Utils::~Utils() +{ +} + +Utils& Utils::instance() +{ + static Utils m_instance; + return m_instance; +} + +QString Utils::findSuffix(const QString& str1, const QString& str2) { + if (!str1.startsWith(str2)) { + // 如果str2不是str1的前缀,可以返回一个空字符串或抛出异常 + // 这里选择返回一个空字符串作为示例 + return QString(); + } + + // 找到str2在str1中的结束位置(即最后一个字符的索引加1) + int endIndex = str2.length(); + + // 使用mid()方法从str2之后开始提取子字符串 + // 注意:mid()方法的第一个参数是起始索引(包含),第二个参数是长度(可选) + // 这里我们省略第二个参数,表示从endIndex开始提取到str1的末尾 + return str1.mid(endIndex); +} +QString Utils::convertToBase(const QString& input) { + // 假设输入字符串的格式是 "前缀_数字" + // 使用'_'作为分隔符来分割字符串 + QStringList parts = input.split('_'); + + // 检查是否成功分割出至少两部分 + if (parts.size() > 0) { + // 返回第一部分,即前缀 + return parts.first(); + } + else { + // 如果没有'_'或者输入为空,则直接返回原字符串 + return input; + } +} + +QMap Utils::toClient(QMap order) +{ + QMap newOrder = order; + // 让球 + if (newOrder["rtype"] == "REH" || newOrder["rtype"] == "RH") + { + newOrder["wtype"] = "R"; + newOrder["rtype"] = "RH"; + newOrder["chose_team"] = "H"; + } + // 受让 + if (newOrder["rtype"] == "REC" || newOrder["rtype"] == "RC") + { + newOrder["wtype"] = "R"; + newOrder["rtype"] = "RC"; + newOrder["chose_team"] = "C"; + } + // 大 + if (newOrder["rtype"] == "ROUC" || newOrder["rtype"] == "OUC") + { + newOrder["wtype"] = "OU"; + newOrder["rtype"] = "OUC"; + newOrder["chose_team"] = "C"; + } + // 小 + if (newOrder["rtype"] == "ROUH" || newOrder["rtype"] == "OUH") + { + newOrder["wtype"] = "OU"; + newOrder["rtype"] = "OUH"; + newOrder["chose_team"] = "H"; + } + // 独赢主 + if (newOrder["rtype"] == "RMH" || newOrder["rtype"] == "MH") + { + newOrder["wtype"] = "M"; + newOrder["rtype"] = "MH"; + newOrder["chose_team"] = "H"; + } + // 独赢客 + if (newOrder["rtype"] == "RMC" || newOrder["rtype"] == "MC") + { + newOrder["wtype"] = "M"; + newOrder["rtype"] = "MC"; + newOrder["chose_team"] = "C"; + } + // 独赢和 + if (newOrder["rtype"] == "RMN" || newOrder["rtype"] == "MN") + { + newOrder["wtype"] = "M"; + newOrder["rtype"] = "MN"; + newOrder["chose_team"] = "N"; + } + // 单 + if (newOrder["rtype"] == "REOO" || newOrder["rtype"] == "EOO") + { + newOrder["wtype"] = "T"; + newOrder["rtype"] = "ODD"; + newOrder["chose_team"] = "ODD"; + } + // 双 + if (newOrder["rtype"] == "REOE" || newOrder["rtype"] == "EOE") + { + newOrder["wtype"] = "T"; + newOrder["rtype"] = "EVEN"; + newOrder["chose_team"] = "EVEN"; + } + // 主队大 + if (newOrder["rtype"] == "ROUHO" || newOrder["rtype"] == "OUHO") + { + newOrder["rtype"] = "OUHO"; + newOrder["chose_team"] = "O"; + } + // 主队小 + if (newOrder["rtype"] == "ROUHU" || newOrder["rtype"] == "OUHU") + { + newOrder["rtype"] = "OUHU"; + newOrder["chose_team"] = "U"; + } + // 客队大 + if (newOrder["rtype"] == "ROUCO" || newOrder["rtype"] == "OUCO") + { + newOrder["rtype"] = "OUCO"; + newOrder["chose_team"] = "O"; + } + // 客队小 + if (newOrder["rtype"] == "ROUCU" || newOrder["rtype"] == "OUCU") + { + newOrder["rtype"] = "OUCU"; + newOrder["chose_team"] = "U"; + } + return newOrder; +} + +/// +/// 转换为今日 +/// +/// 早盘订单信息 +/// 今日订单信息 +QMap Utils::toToday(QMap order) +{ + QMap newOrder = order; + + // session转换为早盘 + newOrder["session"] = "FT"; + + // 根据原始订单信息设置正确的项目名称 + QString gtype = order.value("gtype", "FT"); + QString name = order.value("name", ""); + + // 判断是全场还是上半场 + if (name.contains("上半场")) { + newOrder["project"] = (gtype == "FT" ? "足球今日上半场" : "篮球今日上半场"); + } + else { + newOrder["project"] = (gtype == "FT" ? "足球今日全场" : "篮球今日全场"); + } + // rtype早盘->今日无需转换? + return newOrder; +} + +QMap Utils::toLive(QMap order) +{ + QMap newOrder = order; + newOrder["session"] = "RB"; + + // 根据原始订单信息设置正确的项目名称 + QString gtype = order.value("gtype", "FT"); + QString name = order.value("name", ""); + + // 判断是全场还是上半场 + if (name.contains("上半场")) { + newOrder["project"] = (gtype == "FT" ? "足球滚球上半场" : "篮球滚球上半场"); + } + else { + newOrder["project"] = (gtype == "FT" ? "足球滚球全场" : "篮球滚球全场"); + } + + // 今日转滚球的投注类型转换(需要将今日格式转换为滚球格式) + QString rtype = order.value("rtype", ""); + + if (rtype == "RH") { + newOrder["rtype"] = "REH"; + } + else if (rtype == "RC") { + newOrder["rtype"] = "REC"; + } + else if (rtype == "OUC") { + newOrder["rtype"] = "ROUC"; + } + else if (rtype == "OUH") { + newOrder["rtype"] = "ROUH"; + } + else if (rtype == "MH") { + newOrder["rtype"] = "RMH"; + } + else if (rtype == "MC") { + newOrder["rtype"] = "RMC"; + } + else if (rtype == "MN") { + newOrder["rtype"] = "RMN"; + } + else if (rtype == "EOO") { + newOrder["rtype"] = "REOO"; + } + else if (rtype == "EOE") { + newOrder["rtype"] = "REOE"; + } + else if (rtype == "OUHO") { + newOrder["rtype"] = "ROUHO"; + } + else if (rtype == "OUHU") { + newOrder["rtype"] = "ROUHU"; + } + else if (rtype == "OUCO") { + newOrder["rtype"] = "ROUCO"; + } + else if (rtype == "OUCU") { + newOrder["rtype"] = "ROUCU"; + } + // 上半场转换 + else if (rtype == "HRH") { + newOrder["rtype"] = "HREH"; + } + else if (rtype == "HRC") { + newOrder["rtype"] = "HREC"; + } + else if (rtype == "HOUC") { + newOrder["rtype"] = "HROUC"; + } + else if (rtype == "HOUH") { + newOrder["rtype"] = "HROUH"; + } + else if (rtype == "HMH") { + newOrder["rtype"] = "HRMH"; + } + else if (rtype == "HMC") { + newOrder["rtype"] = "HRMC"; + } + else if (rtype == "HMN") { + newOrder["rtype"] = "HRMN"; + } + else if (rtype == "HEOO") { + newOrder["rtype"] = "HREOO"; + } + else if (rtype == "HEOE") { + newOrder["rtype"] = "HREOE"; + } + else if (rtype == "HOUHO") { + newOrder["rtype"] = "HROUHO"; + } + else if (rtype == "HOUHU") { + newOrder["rtype"] = "HROUHU"; + } + else if (rtype == "HOUCO") { + newOrder["rtype"] = "HROUCO"; + } + else if (rtype == "HOUCU") { + newOrder["rtype"] = "HROUCU"; + } + + return newOrder; +} + +QMap Utils::toContra(QMap order) +{ + QMap newOrder = order; + QString rtype = order["rtype"]; + if (order["ORDER_TYPE"] == order["TEAM_H"]) + { + newOrder["ORDER_TYPE"] = order["TEAM_C"]; + } + else if (order["ORDER_TYPE"] == order["TEAM_C"]) + { + newOrder["ORDER_TYPE"] = order["TEAM_H"]; + } + else if (order["ORDER_TYPE"] == "大") + { + newOrder["ORDER_TYPE"] = "小"; + } + else if (order["ORDER_TYPE"] == "小") + { + newOrder["ORDER_TYPE"] = "大"; + } + else if (order["ORDER_TYPE"] == "独赢主") + { + newOrder["ORDER_TYPE"] = "独赢客"; + } + else if (order["ORDER_TYPE"] == "独赢客") + { + newOrder["ORDER_TYPE"] = "独赢主"; + } + else if (order["ORDER_TYPE"] == "单") + { + newOrder["ORDER_TYPE"] = "双"; + } + else if (order["ORDER_TYPE"] == "双") + { + newOrder["ORDER_TYPE"] = "单"; + } + // 和局不做处理 + + + // 先按 rtype 翻转,同时写入中文 type + // 滚球 全场 让球 + if (rtype == "REH") {newOrder["rtype"] = "REC"; } + else if (rtype == "REC") { newOrder["rtype"] = "REH"; } + // 滚球 全场 大小 + else if (rtype == "ROUC") { newOrder["rtype"] = "ROUH"; } + else if (rtype == "ROUH") { newOrder["rtype"] = "ROUC"; } + // 滚球 全场 独赢 + else if (rtype == "RMH") {newOrder["rtype"] = "RMC"; } + else if (rtype == "RMC") { newOrder["rtype"] = "RMH"; } + else if (rtype == "RMN") { newOrder["rtype"] = "RMN"; /* 和局不切队 */ } + // 滚球 全场 单双 + else if (rtype == "REOO") { newOrder["rtype"] = "REOE"; } + else if (rtype == "REOE") { newOrder["rtype"] = "REOO"; } + // 滚球 主/客 队大小 + else if (rtype == "ROUHO") { newOrder["rtype"] = "ROUHU"; } + else if (rtype == "ROUHU") { newOrder["rtype"] = "ROUHO"; } + else if (rtype == "ROUCO") { newOrder["rtype"] = "ROUCU"; } + else if (rtype == "ROUCU") { newOrder["rtype"] = "ROUCO"; } + + // 滚球 上半场 让球/大小/独赢/单双/球队大小 + else if (rtype == "HREH") { newOrder["rtype"] = "HREC";} + else if (rtype == "HREC") { newOrder["rtype"] = "HREH"; } + else if (rtype == "HROUC") { newOrder["rtype"] = "HROUH"; } + else if (rtype == "HROUH") { newOrder["rtype"] = "HROUC"; } + else if (rtype == "HRMH") { newOrder["rtype"] = "HRMC"; } + else if (rtype == "HRMC") { newOrder["rtype"] = "HRMH"; } + else if (rtype == "HRMN") { newOrder["rtype"] = "HRMN"; /* 和局不切队 */ } + else if (rtype == "HREOO") { newOrder["rtype"] = "HREOE"; } + else if (rtype == "HREOE") { newOrder["rtype"] = "HREOO"; } + else if (rtype == "HROUHO") { newOrder["rtype"] = "HROUHU"; } + else if (rtype == "HROUHU") { newOrder["rtype"] = "HROUHO"; } + else if (rtype == "HROUCO") { newOrder["rtype"] = "HROUCU"; } + else if (rtype == "HROUCU") { newOrder["rtype"] = "HROUCO"; } + + // 今日/早盘 全场 让球/大小/独赢/单双/球队大小 + else if (rtype == "RH") { newOrder["rtype"] = "RC"; } + else if (rtype == "RC") { newOrder["rtype"] = "RH"; } + else if (rtype == "OUC") { newOrder["rtype"] = "OUH"; } + else if (rtype == "OUH") { newOrder["rtype"] = "OUC"; } + else if (rtype == "MH") { newOrder["rtype"] = "MC"; } + else if (rtype == "MC") { newOrder["rtype"] = "MH"; } + else if (rtype == "MN") { newOrder["rtype"] = "MN"; /* 和局不切队 */ } + else if (rtype == "EOO") { newOrder["rtype"] = "EOE"; } + else if (rtype == "EOE") { newOrder["rtype"] = "EOO"; } + else if (rtype == "OUHO") { newOrder["rtype"] = "OUHU"; } + else if (rtype == "OUHU") { newOrder["rtype"] = "OUHO"; } + else if (rtype == "OUCO") { newOrder["rtype"] = "OUCU"; } + else if (rtype == "OUCU") {newOrder["rtype"] = "OUCO"; } + + // 今日/早盘 上半场 + else if (rtype == "HRH") { newOrder["rtype"] = "HRC"; } + else if (rtype == "HRC") { newOrder["rtype"] = "HRH"; } + else if (rtype == "HOUC") { newOrder["rtype"] = "HOUH"; } + else if (rtype == "HOUH") { newOrder["rtype"] = "HOUC"; } + else if (rtype == "HMH") { newOrder["rtype"] = "HMC"; } + else if (rtype == "HMC") { newOrder["rtype"] = "HMH";} + else if (rtype == "HMN") { newOrder["rtype"] = "HMN"; /* 和局不切队 */ } + else if (rtype == "HEOO") { newOrder["rtype"] = "HEOE"; } + else if (rtype == "HEOE") { newOrder["rtype"] = "HEOO"; } + else if (rtype == "HOUHO") { newOrder["rtype"] = "HOUHU"; } + else if (rtype == "HOUHU") { newOrder["rtype"] = "HOUHO"; } + else if (rtype == "HOUCO") { newOrder["rtype"] = "HOUCU"; } + else if (rtype == "HOUCU") { newOrder["rtype"] = "HOUCO"; } + return newOrder; +} +QMap Utils::type(QString projcet, QString ORDER_TYPE) +{ + QMap map; + map["projcet"] = projcet; + map["ORDER_TYPE"] = ORDER_TYPE; + if (projcet == "足球滚球全场") + { + map["GT"] = "足球"; + map["SESSION"] = "滚球"; + map["STAGE"] = "全场"; + if (ORDER_TYPE == "让球") + { + map["wtype"] = "RE"; + map["rtype"] = "REH"; + } + else if (ORDER_TYPE == "受让") + { + map["wtype"] = "RE"; + map["rtype"] = "REC"; + } + else if (ORDER_TYPE == "大") + { + map["wtype"] = "ROU"; + map["rtype"] = "ROUC"; + } + else if (ORDER_TYPE == "小") + { + map["wtype"] = "ROU"; + map["rtype"] = "ROUH"; + } + else if (ORDER_TYPE == "独赢主") + { + map["wtype"] = "RM"; + map["rtype"] = "RMH"; + } + else if (ORDER_TYPE == "独赢客") + { + map["wtype"] = "RM"; + map["rtype"] = "RMC"; + } + else if (ORDER_TYPE == "独赢和") + { + map["wtype"] = "RM"; + map["rtype"] = "RMN"; + } + else if (ORDER_TYPE == "单") + { + map["wtype"] = "REO"; + map["rtype"] = "REOO"; + } + else if (ORDER_TYPE == "双") + { + map["wtype"] = "REO"; + map["rtype"] = "REOE"; + } + else if (ORDER_TYPE == "主队大") + { + map["wtype"] = "ROUH"; + map["rtype"] = "ROUHO"; + } + else if (ORDER_TYPE == "主队小") + { + map["wtype"] = "ROUH"; + map["rtype"] = "ROUHU"; + } + else if (ORDER_TYPE == "客队大") + { + map["wtype"] = "ROUC"; + map["rtype"] = "ROUCO"; + } + else if (ORDER_TYPE == "客队小") + { + map["wtype"] = "ROUC"; + map["rtype"] = "ROUCU"; + } + } + else if (projcet == "足球滚球上半场") + { + map["GT"] = "足球"; + map["SESSION"] = "滚球"; + map["STAGE"] = "上半场"; + if (ORDER_TYPE == "让球") + { + map["wtype"] = "HRE"; + map["rtype"] = "HREH"; + } + else if (ORDER_TYPE == "受让") + { + map["wtype"] = "HRE"; + map["rtype"] = "HREC"; + } + else if (ORDER_TYPE == "大") + { + map["wtype"] = "HROU"; + map["rtype"] = "HROUC"; + } + else if (ORDER_TYPE == "小") + { + map["wtype"] = "HROU"; + map["rtype"] = "HROUH"; + } + else if (ORDER_TYPE == "独赢主") + { + map["wtype"] = "HRM"; + map["rtype"] = "HRMH"; + } + else if (ORDER_TYPE == "独赢客") + { + map["wtype"] = "HRM"; + map["rtype"] = "HRMC"; + } + else if (ORDER_TYPE == "独赢和") + { + map["wtype"] = "HRM"; + map["rtype"] = "HRMN"; + } + else if (ORDER_TYPE == "单") + { + map["wtype"] = "HREO"; + map["rtype"] = "HREOO"; + } + else if (ORDER_TYPE == "双") + { + map["wtype"] = "HREO"; + map["rtype"] = "HREOE"; + } + else if (ORDER_TYPE == "主队大") + { + map["wtype"] = "HROUH"; + map["rtype"] = "HROUHO"; + } + else if (ORDER_TYPE == "主队小") + { + map["wtype"] = "HROUH"; + map["rtype"] = "HROUHU"; + } + else if (ORDER_TYPE == "客队大") + { + map["wtype"] = "HROUC"; + map["rtype"] = "HROUCO"; + } + else if (ORDER_TYPE == "客队小") + { + map["wtype"] = "HROUC"; + map["rtype"] = "HROUCU"; + } + } + else if (projcet == "足球今日全场") + { + map["GT"] = "足球"; + map["SESSION"] = "今日"; + map["STAGE"] = "全场"; + if (ORDER_TYPE == "让球") + { + map["wtype"] = "R"; + map["rtype"] = "RH"; + } + else if (ORDER_TYPE == "受让") + { + map["wtype"] = "R"; + map["rtype"] = "RC"; + } + else if (ORDER_TYPE == "大") + { + map["rtype"] = "OUC"; + } + else if (ORDER_TYPE == "小") + { + map["rtype"] = "OUH"; + } + else if (ORDER_TYPE == "独赢主") + { + map["rtype"] = "MH"; + } + else if (ORDER_TYPE == "独赢客") + { + map["rtype"] = "MC"; + } + else if (ORDER_TYPE == "独赢和") + { + map["rtype"] = "MN"; + } + else if (ORDER_TYPE == "单") + { + map["rtype"] = "EOO"; + } + else if (ORDER_TYPE == "双") + { + map["rtype"] = "EOE"; + } + else if (ORDER_TYPE == "主队大") + { + map["rtype"] = "OUHO"; + } + else if (ORDER_TYPE == "主队小") + { + map["rtype"] = "OUHU"; + } + else if (ORDER_TYPE == "客队大") + { + map["rtype"] = "OUCO"; + } + else if (ORDER_TYPE == "客队小") + { + map["rtype"] = "OUCU"; + } + } + else if (projcet == "足球今日上半场") + { + map["GT"] = "足球"; + map["SESSION"] = "今日"; + map["STAGE"] = "上半场"; + if (ORDER_TYPE == "让球") + { + map["rtype"] = "HRH"; + } + else if (ORDER_TYPE == "受让") + { + map["rtype"] = "HRC"; + } + else if (ORDER_TYPE == "大") + { + map["rtype"] = "HOUC"; + } + else if (ORDER_TYPE == "小") + { + map["rtype"] = "HOUH"; + } + else if (ORDER_TYPE == "独赢主") + { + map["rtype"] = "HMH"; + } + else if (ORDER_TYPE == "独赢客") + { + map["rtype"] = "HMC"; + } + else if (ORDER_TYPE == "独赢和") + { + map["rtype"] = "HMN"; + } + else if (ORDER_TYPE == "单") + { + map["rtype"] = "HEOO"; + } + else if (ORDER_TYPE == "双") + { + map["rtype"] = "HEOE"; + } + else if (ORDER_TYPE == "主队大") + { + map["rtype"] = "HOUHO"; + } + else if (ORDER_TYPE == "主队小") + { + map["rtype"] = "HOUHU"; + } + else if (ORDER_TYPE == "客队大") + { + map["rtype"] = "HOUCO"; + } + else if (ORDER_TYPE == "客队小") + { + map["rtype"] = "HOUCU"; + } + } + else if (projcet == "足球早盘全场") + { + map["GT"] = "足球"; + map["SESSION"] = "早盘"; + map["STAGE"] = "全场"; + if (ORDER_TYPE == "让球") + { + map["rtype"] = "RH"; + } + else if (ORDER_TYPE == "受让") + { + map["rtype"] = "RC"; + } + else if (ORDER_TYPE == "大") + { + map["rtype"] = "OUC"; + } + else if (ORDER_TYPE == "小") + { + map["rtype"] = "OUH"; + } + else if (ORDER_TYPE == "独赢主") + { + map["rtype"] = "MH"; + } + else if (ORDER_TYPE == "独赢客") + { + map["rtype"] = "MC"; + } + else if (ORDER_TYPE == "独赢和") + { + map["rtype"] = "MN"; + } + else if (ORDER_TYPE == "单") + { + map["rtype"] = "EOO"; + } + else if (ORDER_TYPE == "双") + { + map["rtype"] = "EOE"; + } + else if (ORDER_TYPE == "主队大") + { + map["rtype"] = "OUHO"; + } + else if (ORDER_TYPE == "主队小") + { + map["rtype"] = "OUHU"; + } + else if (ORDER_TYPE == "客队大") + { + map["rtype"] = "OUCO"; + } + else if (ORDER_TYPE == "客队小") + { + map["rtype"] = "OUCU"; + } + } + else if (projcet == "足球早盘上半场") + { + map["GT"] = "足球"; + map["SESSION"] = "早盘"; + map["STAGE"] = "上半场"; + if (ORDER_TYPE == "让球") + { + map["rtype"] = "HRH"; + } + else if (ORDER_TYPE == "受让") + { + map["rtype"] = "HRC"; + } + else if (ORDER_TYPE == "大") + { + map["rtype"] = "HOUC"; + } + else if (ORDER_TYPE == "小") + { + map["rtype"] = "HOUH"; + } + else if (ORDER_TYPE == "独赢主") + { + map["rtype"] = "HMH"; + } + else if (ORDER_TYPE == "独赢客") + { + map["rtype"] = "HMC"; + } + else if (ORDER_TYPE == "独赢和") + { + map["rtype"] = "HMN"; + } + else if (ORDER_TYPE == "单") + { + map["rtype"] = "HEOO"; + } + else if (ORDER_TYPE == "双") + { + map["rtype"] = "HEOE"; + } + else if (ORDER_TYPE == "主队大") + { + map["rtype"] = "HOUHO"; + } + else if (ORDER_TYPE == "主队小") + { + map["rtype"] = "HOUHU"; + } + else if (ORDER_TYPE == "客队大") + { + map["rtype"] = "HOUCO"; + } + else if (ORDER_TYPE == "客队小") + { + map["rtype"] = "HOUCU"; + } + } + else if (projcet == "篮球滚球全部") + { + map["GT"] = "篮球"; + map["SESSION"] = "滚球"; + map["STAGE"] = "全部"; + if (ORDER_TYPE == "让球") + { + map["rtype"] = "REH"; + } + else if (ORDER_TYPE == "受让") + { + map["rtype"] = "REC"; + } + else if (ORDER_TYPE == "大") + { + map["rtype"] = "ROUC"; + } + else if (ORDER_TYPE == "小") + { + map["rtype"] = "ROUH"; + } + else if (ORDER_TYPE == "独赢主") + { + map["rtype"] = "RMH"; + } + else if (ORDER_TYPE == "独赢客") + { + map["rtype"] = "RMC"; + } + else if (ORDER_TYPE == "独赢和") + { + map["rtype"] = "RMN"; + } + else if (ORDER_TYPE == "单") + { + map["rtype"] = "REOO"; + } + else if (ORDER_TYPE == "双") + { + map["rtype"] = "REOE"; + } + else if (ORDER_TYPE == "主队大") + { + map["rtype"] = "ROUHO"; + } + else if (ORDER_TYPE == "主队小") + { + map["rtype"] = "ROUHU"; + } + else if (ORDER_TYPE == "客队大") + { + map["rtype"] = "ROUCO"; + } + else if (ORDER_TYPE == "客队小") + { + map["rtype"] = "ROUCU"; + } + } + else if (projcet == "篮球今日全部") + { + map["GT"] = "篮球"; + map["SESSION"] = "今日"; + map["STAGE"] = "全部"; + if (ORDER_TYPE == "让球") + { + map["rtype"] = "RH"; + } + else if (ORDER_TYPE == "受让") + { + map["rtype"] = "RC"; + } + else if (ORDER_TYPE == "大") + { + map["rtype"] = "OUC"; + } + else if (ORDER_TYPE == "小") + { + map["rtype"] = "OUH"; + } + else if (ORDER_TYPE == "独赢主") + { + map["rtype"] = "MH"; + } + else if (ORDER_TYPE == "独赢客") + { + map["rtype"] = "MC"; + } + else if (ORDER_TYPE == "独赢和") + { + map["rtype"] = "MN"; + } + else if (ORDER_TYPE == "单") + { + map["rtype"] = "EOO"; + } + else if (ORDER_TYPE == "双") + { + map["rtype"] = "EOE"; + } + else if (ORDER_TYPE == "主队大") + { + map["rtype"] = "OUHO"; + } + else if (ORDER_TYPE == "主队小") + { + map["rtype"] = "OUHU"; + } + else if (ORDER_TYPE == "客队大") + { + map["rtype"] = "OUCO"; + } + else if (ORDER_TYPE == "客队小") + { + map["rtype"] = "OUCU"; + } + } + else if (projcet == "篮球早盘全部") + { + map["GT"] = "篮球"; + map["SESSION"] = "早盘"; + map["STAGE"] = "全部"; + if (ORDER_TYPE == "让球") + { + map["rtype"] = "RH"; + } + else if (ORDER_TYPE == "受让") + { + map["rtype"] = "RC"; + } + else if (ORDER_TYPE == "大") + { + map["rtype"] = "OUC"; + } + else if (ORDER_TYPE == "小") + { + map["rtype"] = "OUH"; + } + else if (ORDER_TYPE == "独赢主") + { + map["rtype"] = "MH"; + } + else if (ORDER_TYPE == "独赢客") + { + map["rtype"] = "MC"; + } + else if (ORDER_TYPE == "独赢和") + { + map["rtype"] = "MN"; + } + else if (ORDER_TYPE == "单") + { + map["rtype"] = "EOO"; + } + else if (ORDER_TYPE == "双") + { + map["rtype"] = "EOE"; + } + else if (ORDER_TYPE == "主队大") + { + map["rtype"] = "OUHO"; + } + else if (ORDER_TYPE == "主队小") + { + map["rtype"] = "OUHU"; + } + else if (ORDER_TYPE == "客队大") + { + map["rtype"] = "OUCO"; + } + else if (ORDER_TYPE == "客队小") + { + map["rtype"] = "OUCU"; + } + } + return map; +} + + + + +QString Utils::get_wagers_wtype_name(QString wtype) +{ + // 滚球 RE 让球 ROU大小 RM独赢 HRE 让球上半 HROU 大小上半 HRM 独赢上半 RG下个进球 RTS双方球队进球 + // 滚球全场 REO单双 + + if (wtype == "R" || wtype == "RE" || wtype == "HR" || wtype == "HRE") + { + return "让球"; + } + if (wtype == "OU" || wtype == "ROU" || wtype == "HOU" || wtype == "HROU") + { + return "大小"; + } + if (wtype == "M" || wtype == "RM" || wtype == "HM" || wtype == "HRM") + { + return "独赢"; + } + if (wtype == "G" || wtype == "RG" || wtype == "HG" || wtype == "HRG") + { + return "下个进球"; + } + if (wtype == "TS" || wtype == "RTS" || wtype == "HTS" || wtype == "HRTS") + { + return "双方球队进球"; + } + if (wtype == "EO" || wtype == "REO" || wtype == "HEO" || wtype == "HREO") // RT 滚球单双 EO 早盘单双 + { + return "单双"; // ODD / EVEN ? + } + if (wtype == "OUH" || wtype == "ROUH" || wtype == "HOUH" || wtype == "HROUH") + { + return "队伍1进球"; + } + if (wtype == "OUC" || wtype == "ROUC" || wtype == "HOUC" || wtype == "HROUC") + { + return "队伍2进球"; + } + if (wtype == "SH" || wtype == "RSH" || wtype == "HSH" || wtype == "HRSH") + { + return "下个点球"; + } + + return ""; + // R 让球 + // OU 大小 + // M 独赢 + // HR 让球上半场 + // HOU 大小上半场 + // HM 独赢上半场 + + // TS 双方进球 TSY 是/ TSN 否 + // EO 单双 +} + + +/// +/// 通过错误代码获取错误信息 +/// +/// 错误代码 +/// 错误信息 +QString Utils::error(QString errorCode) +{ + static QMap errorMap; + if (!errorMap.isEmpty()) + { + if (errorMap[errorCode].isEmpty() || errorMap[errorCode]=="") + { + return "未知错误代码"; + } + return errorMap[errorCode]; + } + errorMap["0X001"] = "由于网站流量较高,请重新再试。谢谢"; + errorMap["0X002"] = "由于网站流量较高,请重新再试。谢谢"; + errorMap["0X003"] = "系统正在忙碌中,请稍后再试。"; + errorMap["0X004"] = "系统正在忙碌中,请稍后再试。"; + errorMap["0X005"] = "系统正在忙碌中,请稍后再试。"; + errorMap["0X006"] = "系统最佳化中,请稍后。"; + errorMap["0X007"] = "系统正在忙碌中,请稍后再试。"; + errorMap["0X008"] = "系统正在忙碌中,请稍后再试。"; + errorMap["1X000"] = "此选项不再开放投注。请从交易单中移除。"; + errorMap["1X001"] = "此选项目前不开放投注。"; + errorMap["1X002"] = "已超过停止交易时间,无法进行交易。"; + errorMap["1X003"] = "本场次已转至走地盘口,请至走地交易。"; + errorMap["1X004"] = "最小投注金额为"; + errorMap["1X005"] = "让球数,赔率或比分已更新。"; + errorMap["1X006"] = "让球数,赔率或比分已更新。"; + errorMap["1X007"] = "输入比数后 1 分钟内,无法进行交易!!"; + errorMap["1X008"] = "交易金额不可大于股东单场总信用额度。请联络您的直属上线以解决这个问题。"; + errorMap["1X009"] = "暂时停止交易"; + errorMap["1X010"] = "暂时停止交易"; + errorMap["1X011"] = "此选项不再开放投注。请从交易单中移除。"; + errorMap["1X012"] = "您的总投注金额已超过您的余额,请重新编辑投注金额。"; + errorMap["1X013"] = "赔率错误,请重新交易。"; + errorMap["1X014"] = "登入失败,请重新尝试。"; + errorMap["1X015"] = "让球数,赔率或比分已更新。"; + errorMap["1X016"] = "让球数,赔率或比分已更新。"; + errorMap["1X017"] = "已超过某场次之过关注单限额"; + errorMap["1X018"] = "最高投注额设在 "; + errorMap["1X019"] = "同组合可赢金额不得超过人民币 "; + errorMap["1X020"] = "单注最高可赢金额: 人民币 "; + errorMap["1X021"] = "让过赛事重覆"; + errorMap["1X022"] = "最小投注金额为"; + errorMap["1X023"] = "本场有下注金额最高是 "; + errorMap["1X024"] = "下注失败,请重新交易。"; + errorMap["1X025"] = "球头错误。"; + errorMap["1X026"] = "所选赛程跨天。"; + errorMap["1X027"] = "过关串数错误"; + errorMap["1X029"] = "您没有足够的昨日余额进行昨日赛事的投注"; + errorMap["1X030"] = "本场有下注金额最高是 "; + errorMap["1X031"] = "最高投注额设在 "; + errorMap["1X032"] = "综合过关选项不足"; + errorMap["1X034"] = "被标注的选项无法串综合过关。"; + errorMap["1X035"] = errorMap["1X016"]; + errorMap["1X036"] = "本场有下注金额最高是 "; + errorMap["1X037"] = "额度最佳化中,请稍后再试。"; + errorMap["1X038"] = errorMap["0X008"]; + errorMap["score_changed"] = "让球数,赔率或比分已更新。"; + errorMap["order_failed"] = "投注失败"; + errorMap["connectFail"] = "系统目前无法回应,请稍后再试。"; + errorMap["1more_failed"] = "至少一张注单投注失败。"; + errorMap["1more_place_failed"] = "至少一张注单无法投注。"; + errorMap["1more_pending"] = "至少一张注单目前正在处理中。"; + errorMap["1more_rejected"] = "至少一张注单被拒收。"; + errorMap["bet_success"] = "您已成功投注。"; + errorMap["bet_pending"] = "您的注单正在处理中,请稍候。"; + errorMap["bet_rejected"] = "您的注单已被拒收。"; + errorMap["1more_rejected_toast"] = "您有至少一张注单已被拒绝。请到“交易状况”查看详情"; + errorMap["bet_try_again"] = "由于网站流量较高,请重新再试。谢谢"; + errorMap["max"] = "为上限"; + errorMap["error_mem_max"] = "本场累积下注共:"; + errorMap["error_mem_max1"] = ",总下注金额已超过单场限额。"; + errorMap["error7D"] = "过关选项的日期间距不可超过7天。"; + errorMap["errorLogin"] = "现在我们的系统面临技术问题。请稍后再尝试登入。对于这样的不便我们深感抱歉,我们也正在全力的解决该问题。谢谢您的耐心等待。"; + errorMap["betError000"] = "交易失败,请重新交易。"; + errorMap["betError9487"] = "交易失败,请重新交易."; + errorMap["betError878787"] = "网路不稳,请至交易状况确认注单是否成功。"; + errorMap["totalBet_close"] = "目前无法同时下注单注和过关的模式。"; + errorMap["betError016"] = "交易单处理中,请稍后...."; + errorMap["betError021"] = "不接受"; + errorMap["betError022"] = "串过关投注。"; + errorMap["str_over_sc"] = "交易金额已超过单场最高限额。"; + errorMap["user_stop"] = "您的帐户已被停用,请联系您的上线开启你的帐号。"; + errorMap["user_forbid"] = "您的帐号已被禁止登入,请联系您的上线开启你的帐号!"; + errorMap["4pwd_input"] = "输入密码"; + errorMap["4pwd_confirmed"] = "确认密码"; + errorMap["4pwd_title"] = "移除四位数密码"; + errorMap["4pwd_btn"] = "确认"; + errorMap["4pwd_removed"] = "您已经成功移除四位数密码登入"; + errorMap["4pwd_removedAlready"] = "您已经移除四位数密码登入"; + errorMap["4pwd_login_fail"] = "密码错误,请重新输入"; + errorMap["4pwd_fail_twice"] = "您已经连续两次输入错误密码,请使用您的帐号密码登入。"; + errorMap["4pwd_doubleCheck_fail"] = "两次输入的四位数密码必须一致"; + errorMap["4pwd_block"] = "密码错误次数过多,请联系您的上线寻求协助。"; + errorMap["4pwd_db_fail"] = "基于安全考量,此设备/浏览器的四位数密码登入已被禁用。请使用您的帐号密码登入。"; + errorMap["4pwd_chg_pwd"] = "基于安全考量,在更改帐号密码后,四位数密码登入已被删除。请使用您的帐号密码登入。"; + errorMap["4pwd_fistcome"] = "设定您的简易密码以便快速登入。"; + errorMap["4pwd_onepassd"] = "重新输入你的简易密码来登入或是"; + errorMap["indexsubmit"] = "提交"; + errorMap["changepwd_oldpassword"] = "请输入现用密码。"; + errorMap["changepwd_password"] = "请输入新密码。"; + errorMap["changepwd_REpassword"] = "请输入确认密码。"; + errorMap["changepwd_oldpassworderror"] = "您输入的密码不正确,请重试。"; + errorMap["changepwd_passworderror"] = "您的新密码必须和现用密码不一样。"; + errorMap["changepwd_REpassworderror"] = "密码确认错误,请重新输入。"; + errorMap["changepwd_error"] = "1.您的新密码必须由 6-12个字母和数字 (A-Z 或 0-9)组成。\n2.您的新密码不能和现用密码相同"; + errorMap["changepwd_passwordcomplete"] = "你的密码已成功修改完成。"; + errorMap["changepwd_stop"] = "停止修改密码?"; + errorMap["rule_error_1"] = "您的新密码必须由 6-12个字母和数字 (A-Z 或 0-9)组成。"; + errorMap["rule_error_2"] = "您输入的密码不符合要求:\n1. 您的新密码必须由6 - 12个字母和数字(A - Z 或 0 - 9)组成。\n2. 您的新密码不能和现用密码相同"; + errorMap["rule_error_3"] = "密码过于简易会导致安全性的问题,请尝试使用其他密码组合。"; + errorMap["rule_error_4"] = "安全代码过于简易会导致安全性的问题,请尝试使用其他安全代码组合。"; + errorMap["rule_error_5"] = "您的密码必须根据以下规则:\n1. 至少要有两个大或小写英文字母和数字(0 - 9)组合,字数最少6至12个。\n2. 三个不同的字母数字。\n3. 不准许有空格。"; + errorMap["changeemail_page"] = "要注册密码恢复?"; + errorMap["login_internalerror"] = "网路过慢,请重新登入!"; + errorMap["login_usr"] = "请输入登录帐号 ?"; + errorMap["login_pwd"] = "请输入密码 ? "; + errorMap["login_error"] = "您输入的帐号或密码不正确。 请重新登入。"; + errorMap["login_lock"] = "请几分钟后再试一次。"; + errorMap["mail_disable"] = "此功能暂时已被禁用,请联系您的上线。"; + errorMap["mail_cancel"] = "取消注册?"; + errorMap["mail_delete"] = "删除密码恢复用的电子信箱?"; + errorMap["mail_error"] = "连线异常,请联系您的线上。"; + errorMap["mail_error1"] = "请输入有效电子邮件。"; + errorMap["mail_pop"] = "认证码已经送到您的电子信箱"; + errorMap["mail_lock"] = "您输入的验证码不正确, 请再尝试输入。"; + errorMap["mail_complete"] = "已成功注册。"; + errorMap["mail_gmail"] = "此功能不再支援Gmail。请用其他供应商的电子邮件。"; + errorMap["chgid_complete"] = "你的帐号已成功创建"; + errorMap["chgid_error"] = "请输入登录帐号。"; + errorMap["chgid_error_duplicate"] = "此登录帐号已有人使用。"; + errorMap["chgid_error_rule"] = "您输入的登录帐号不符合要求:\n1.您的登入帐号必须由2个英文大小写字母(A-Z或a-z)和数字(0-9)组合,输入限制6-12字元\n2.您的登入帐号不准许有空格。"; + errorMap["chgid_error_passwd"] = "登录帐号请勿和帐号密码相同。"; + errorMap["right_msg"] = "显示帐户金额"; + errorMap["todat_wagers_magtitle"] = "系统公告"; + errorMap["alldateno"] = "目前没有任何赛事。"; + errorMap["dateno"] = "您选择的日期没有任何赛事。"; + errorMap["pls_enter_email"] = "请输入有效的电子邮件。"; + errorMap["pls_enter_usertag"] = "请输入 帐号 或 登录帐号。"; + errorMap["verify_sent_ok"] = "验证码已经送到您的电子信箱"; + errorMap["verify_cancel"] = "取消密码恢复用电子信箱?"; + errorMap["pls_enter_passwords"] = "请输入密码。"; + errorMap["pls_enter_pwd_chk"] = "请输入确认密码。"; + errorMap["pwd_chk_error"] = "密码确认错误,请重新输入。"; + errorMap["pwd_rule_error"] = "您的新密码必须由 6-12个字母和数字 (A-Z 或 0-9)组成."; + errorMap["pwd_rule_error2"] = "您的密码必须由根据以下规则:\n1. 至少要有两个大或小写英文字母和数字(0 - 9)组合, 字数最少6至12个。\n2. 三个不同的字母数字。\n3. 不准许有空格。"; + errorMap["pwd_rule_error3"] = "密码过于简易会导致安全性的问题,请尝试使用其他密码组合。"; + errorMap["pwd_rule_error4"] = "安全代码过于简易会导致安全性的问题,请尝试使用其他安全代码组合。"; + errorMap["pwd_rule_error5"] = "您的密码必须根据以下规则:\n1. 至少要有两个大或小写英文字母和数字(0-9)组合,字数最少6至12个。\n2. 三个不同的字母数字。\n3. 不准许有空格。"; + errorMap["history_pop"] = "日期区间错误。请输入正确的日期区间。"; + return errorMap[errorCode]; +} + +QString Utils::formatGold(QString gold) +{ + double doubleGold = gold.toDouble(); + return QString::number(doubleGold,'f',2); +} + + + + + + +#include +#include +#include +#include + + +// 解析盘口数值(支持单一值和复合值) +// 参数: +// marketStr - 输入的盘口字符串,可以是单一值(如"1.5")或范围值(如"1.5/2") +// lowValue - 输出参数,解析得到的下限值 +// highValue - 输出参数,解析得到的上限值 +// 返回值: +// bool - 解析成功返回true,失败返回false +bool parseMarketValue(const std::string& marketStr, double& lowValue, double& highValue) { + std::string cleanStr = marketStr; + + // 移除字符串中的所有空格,便于后续处理 + cleanStr.erase(std::remove(cleanStr.begin(), cleanStr.end(), ' '), cleanStr.end()); + + // 查找分隔符 '/',用于判断是否为范围值 + size_t slashPos = cleanStr.find('/'); + + // 如果没有找到分隔符,说明是单一数值 + if (slashPos == std::string::npos) { + try { + // 将整个字符串转换为double类型 + lowValue = std::stod(cleanStr); + highValue = lowValue; // 单一值时,上下限值相同 + return true; + } + catch (...) { + // 转换失败,返回false + return false; + } + } + + // 处理范围值(包含'/'分隔符的情况) + try { + // 提取'/'前的部分作为下限值字符串 + std::string lowStr = cleanStr.substr(0, slashPos); + // 提取'/'后的部分作为上限值字符串 + std::string highStr = cleanStr.substr(slashPos + 1); + + // 将字符串转换为double数值 + lowValue = std::stod(lowStr); + highValue = std::stod(highStr); + + // 验证下限值不大于上限值,确保范围有效 + return lowValue <= highValue; + } + catch (...) { + // 转换过程中出现异常,返回false + return false; + } +} + +// 让球/受让盘口判断函数(修正版) +// 对于让球方:数值升高(负值变小或正值变大)表示让球优势增加,更难赢 +// 对于让球方:数值降低(负值变大或正值变小)表示让球优势减小,更容易赢 +// 对于受让方:数值升高(正值变大)表示受让优势增加,更容易赢 +// 对于受让方:数值降低(正值变小)表示受让优势减小,更难赢 +// 让球/受让盘口判断函数(修正版) +// 让球/受让盘口判断函数(修正版) +// 让球/受让盘口判断函数(修正版) +MarketChange Utils::checkHandicapChange(const std::string& marketType, + const std::string& oldMarket, + const std::string& newMarket) { + double oldLow, oldHigh, newLow, newHigh; + + if (!parseMarketValue(oldMarket, oldLow, oldHigh) || !parseMarketValue(newMarket, newLow, newHigh)) { + return MARKET_INVALID; + } + + const double tolerance = 0.01; + + // 检查是否为复合盘口(上下限不同) + bool oldIsCompound = (std::abs(oldHigh - oldLow) > tolerance); + bool newIsCompound = (std::abs(newHigh - newLow) > tolerance); + + if (marketType == "让球") { + // 特殊处理:复合盘口变单一盘口 + if (oldIsCompound && !newIsCompound) { + // 从复合盘口变为单一盘口,需要判断是变好还是变差 + // 关键是比较新单一值与旧上限值的关系 + if (std::abs(newLow - oldHigh) < tolerance) { + // 新单一值等于旧上限值:变差(门槛提高) + return MARKET_WORSENED; + } + else if (std::abs(newLow - oldLow) < tolerance) { + // 新单一值等于旧下限值:变好(门槛降低) + return MARKET_IMPROVED; + } + // 让球方:数值变大(更容易赢) + else if (newLow > oldLow + tolerance) { + return MARKET_IMPROVED; // 更容易赢 + } + else { + return MARKET_WORSENED; // 更难赢 + } + } + // 单一盘口变复合盘口 + else if (!oldIsCompound && newIsCompound) { + // 从单一盘口变为复合盘口,需要判断是变好还是变差 + // 关键是比较旧单一值与新下限值的关系 + if (std::abs(newLow - oldLow) < tolerance) { + // 新下限值等于旧单一值:变差(门槛提高) + return MARKET_WORSENED; + } + else if (std::abs(newHigh - oldLow) < tolerance) { + // 新上限值等于旧单一值:变好(门槛降低) + return MARKET_IMPROVED; + } + // 让球方:数值变大(更容易赢) + else if (newLow > oldLow + tolerance) { + return MARKET_IMPROVED; // 更容易赢 + } + else { + return MARKET_WORSENED; // 更难赢 + } + } + // 都是复合盘口 + else if (oldIsCompound && newIsCompound) { + // 比较下限值 + if (std::abs(newLow - oldLow) < tolerance) { + return MARKET_UNCHANGED; + } + // 让球方:数值变大(更容易赢) + if (newLow > oldLow + tolerance) { + return MARKET_IMPROVED; // 更容易赢 + } + else { + return MARKET_WORSENED; // 更难赢 + } + } + // 都是单一盘口 + else { + if (std::abs(newLow - oldLow) < tolerance) { + return MARKET_UNCHANGED; + } + // 让球方:数值变大(更容易赢) + if (newLow > oldLow + tolerance) { + return MARKET_IMPROVED; // 更容易赢 + } + else { + return MARKET_WORSENED; // 更难赢 + } + } + } + else if (marketType == "受让") { + // 受让方:数值变大(更容易赢),数值变小(更难赢) + + // 特殊处理:复合盘口变单一盘口 + if (oldIsCompound && !newIsCompound) { + // 从复合盘口变为单一盘口,比较新单一值与旧上限值 + if (std::abs(newLow - oldHigh) < tolerance) { + // 新单一值等于旧上限值:变好(门槛降低) + return MARKET_IMPROVED; + } + // 受让方:数值变大(更容易赢) + else if (newLow > oldHigh + tolerance) { + return MARKET_IMPROVED; // 更容易赢 + } + else { + return MARKET_WORSENED; // 更难赢 + } + } + // 单一盘口变复合盘口 + else if (!oldIsCompound && newIsCompound) { + // 从单一盘口变为复合盘口,比较旧单一值与新上限值 + if (std::abs(newHigh - oldLow) < tolerance) { + // 新上限值等于旧单一值:变好(门槛降低) + return MARKET_IMPROVED; + } + // 受让方:数值变大(更容易赢) + else if (newHigh > oldLow + tolerance) { + return MARKET_IMPROVED; // 更容易赢 + } + else { + return MARKET_WORSENED; // 更难赢 + } + } + // 都是复合盘口 + else if (oldIsCompound && newIsCompound) { + // 比较上限值(受让方主要看上盘) + if (std::abs(newHigh - oldHigh) < tolerance) { + return MARKET_UNCHANGED; + } + // 受让方:数值变大(更容易赢) + if (newHigh > oldHigh + tolerance) { + return MARKET_IMPROVED; // 更容易赢 + } + else { + return MARKET_WORSENED; // 更难赢 + } + } + // 都是单一盘口 + else { + if (std::abs(newLow - oldLow) < tolerance) { + return MARKET_UNCHANGED; + } + // 受让方:数值变大(更容易赢) + if (newLow > oldLow + tolerance) { + return MARKET_IMPROVED; // 更容易赢 + } + else { + return MARKET_WORSENED; // 更难赢 + } + } + } + else { + return MARKET_INVALID; + } + + return MARKET_UNCHANGED; +} +// 大小球盘口判断函数(保持不变,逻辑正确) +// 对于大球盘:数值降低更容易赢(门槛降低) +// 对于小球盘:数值升高更容易赢(门槛提高) +MarketChange Utils::checkOverUnderChange(const std::string& marketType, + const std::string& oldMarket, + const std::string& newMarket) { + double oldLow, oldHigh, newLow, newHigh; + + if (!parseMarketValue(oldMarket, oldLow, oldHigh) || !parseMarketValue(newMarket, newLow, newHigh)) { + return MARKET_INVALID; + } + + const double tolerance = 0.01; + double oldAvg = (oldLow + oldHigh) / 2.0; + double newAvg = (newLow + newHigh) / 2.0; + + if (std::abs(newAvg - oldAvg) < tolerance) { + return MARKET_UNCHANGED; + } + + if (marketType == "大" || marketType == "over" || marketType == "OVER") { + // 大球盘:数值降低更容易赢(门槛降低) + if (newAvg < oldAvg - tolerance) { + return MARKET_IMPROVED; // 更容易赢 + } + else if (newAvg > oldAvg + tolerance) { + return MARKET_WORSENED; // 更难赢 + } + } + else if (marketType == "小" || marketType == "under" || marketType == "UNDER") { + // 小球盘:数值升高更容易赢(门槛提高) + if (newAvg > oldAvg + tolerance) { + return MARKET_IMPROVED; // 更容易赢 + } + else if (newAvg < oldAvg - tolerance) { + return MARKET_WORSENED; // 更难赢 + } + } + else { + return MARKET_INVALID; + } + + return MARKET_UNCHANGED; +} +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#include +#endif + +int Utils::get_number_of_application_name() { + std::string filepath; + + // 获取可执行文件完整路径 +#ifdef _WIN32 + char buffer[MAX_PATH]; + GetModuleFileNameA(nullptr, buffer, MAX_PATH); + filepath = buffer; +#else + char buffer[PATH_MAX]; + ssize_t len = readlink("/proc/self/exe", buffer, sizeof(buffer) - 1); + if (len != -1) { + buffer[len] = '\0'; + filepath = buffer; + } +#endif + + // 从完整路径中提取文件名 + std::string filename; + size_t lastSlash = filepath.find_last_of("/\\"); + if (lastSlash != std::string::npos) { + filename = filepath.substr(lastSlash + 1); + } + else { + filename = filepath; + } + + // 提取文件名中的数字 + std::string numberStr; + bool foundDigit = false; + + for (char c : filename) { + if (std::isdigit(c)) { + numberStr += c; + foundDigit = true; + } + else if (foundDigit) { + // 遇到非数字字符且已经找到过数字,停止提取 + break; + } + } + + // 如果找到数字,转换为整数 + if (!numberStr.empty()) { + try { + // 数字范围超过5,返回默认值1 + if (std::stoi(numberStr) < 1 || std::stoi(numberStr) > 5) + { + return 1; //返回默认值1 + } + return std::stoi(numberStr); + } + catch (const std::exception&) { + return 1; // 转换失败,返回默认值1 + } + } + + return 1; // 未找到数字,返回默认值1 +} + + + + + + + +// +//QString Utils::switchConRtype(QString rtype, QString isOutside, QString gtype) { +// rtype = rtype.toLowerCase(); +// var _gtype = gtype ? gtype : top.choice_gtype; +// var hash = new Object; +// if (isOutside == "Y" || _gtype != "ft") { +// hash["ouc"] = "ratio_ouo"; +// hash["ouh"] = "ratio_ouu"; +// hash["houc"] = "ratio_houo"; +// hash["houh"] = "ratio_houu"; +// hash["rh"] = "ratio_r"; +// hash["rc"] = "ratio_r"; +// hash["prh"] = "ratio_r"; +// hash["prc"] = "ratio_r"; +// hash["pouc"] = "ratio_ouo"; +// hash["pouh"] = "ratio_ouu"; +// hash["hrh"] = "ratio_hr"; +// hash["hrc"] = "ratio_hr"; +// hash["hprh"] = "ratio_hr"; +// hash["hprc"] = "ratio_hr"; +// hash["hpouc"] = "ratio_houo"; +// hash["hpouh"] = "ratio_houu" +// } +// else { +// hash["ouc"] = "ratio_o"; +// hash["ouh"] = "ratio_u"; +// hash["houc"] = "ratio_ho"; +// hash["houh"] = "ratio_hu"; +// hash["rh"] = "ratio"; +// hash["rc"] = "ratio"; +// hash["prh"] = "ratio"; +// hash["prc"] = "ratio"; +// hash["pouc"] = "ratio_o"; +// hash["pouh"] = "ratio_u"; +// hash["hrh"] = "hratio"; +// hash["hrc"] = "hratio"; +// hash["hprh"] = "hratio"; +// hash["hprc"] = "hratio"; +// hash["hpouc"] = "ratio_ho"; +// hash["hpouh"] = "ratio_hu" +// } +// hash["rouc"] = "ratio_rouo"; +// hash["rouh"] = "ratio_rouu"; +// hash["hrouc"] = "ratio_hrouo"; +// hash["hrouh"] = "ratio_hrouu"; +// hash["reh"] = "ratio_re"; +// hash["rec"] = "ratio_re"; +// hash["hreh"] = "ratio_hre"; +// hash["hrec"] = "ratio_hre"; +// hash["arh"] = "ratio_ar"; +// hash["arc"] = "ratio_ar"; +// hash["brh"] = "ratio_br"; +// hash["brc"] = "ratio_br"; +// hash["crh"] = "ratio_cr"; +// hash["crc"] = "ratio_cr"; +// hash["drh"] = "ratio_dr"; +// hash["drc"] = "ratio_dr"; +// hash["erh"] = "ratio_er"; +// hash["erc"] = "ratio_er"; +// hash["frh"] = "ratio_fr"; +// hash["frc"] = "ratio_fr"; +// hash["aouo"] = "ratio_aouo"; +// hash["aouu"] = "ratio_aouu"; +// hash["bouo"] = "ratio_bouo"; +// hash["bouu"] = "ratio_bouu"; +// hash["couo"] = "ratio_couo"; +// hash["couu"] = "ratio_couu"; +// hash["douo"] = "ratio_douo"; +// hash["douu"] = "ratio_douu"; +// hash["eouo"] = "ratio_eouo"; +// hash["eouu"] = "ratio_eouu"; +// hash["fouo"] = "ratio_fouo"; +// hash["fouu"] = "ratio_fouu"; +// hash["parh"] = "ratio_ar"; +// hash["parc"] = "ratio_ar"; +// hash["pbrh"] = "ratio_br"; +// hash["pbrc"] = "ratio_br"; +// hash["pcrh"] = "ratio_cr"; +// hash["pcrc"] = "ratio_cr"; +// hash["pdrh"] = "ratio_dr"; +// hash["pdrc"] = "ratio_dr"; +// hash["perh"] = "ratio_er"; +// hash["perc"] = "ratio_er"; +// hash["pfrh"] = "ratio_fr"; +// hash["pfrc"] = "ratio_fr"; +// hash["paouo"] = "ratio_aouo"; +// hash["paouu"] = "ratio_aouu"; +// hash["pbouo"] = "ratio_bouo"; +// hash["pbouu"] = "ratio_bouu"; +// hash["pcouo"] = "ratio_couo"; +// hash["pcouu"] = "ratio_couu"; +// hash["pdouo"] = "ratio_douo"; +// hash["pdouu"] = "ratio_douu"; +// hash["peouo"] = "ratio_eouo"; +// hash["peouu"] = "ratio_eouu"; +// hash["pfouo"] = "ratio_fouo"; +// hash["pfouu"] = "ratio_fouu"; +// hash["rouho"] = "ratio_rouho"; +// hash["rouhu"] = "ratio_rouhu"; +// hash["rouco"] = "ratio_rouco"; +// hash["roucu"] = "ratio_roucu"; +// hash["hruho"] = "ratio_hruho"; +// hash["hruhu"] = "ratio_hruhu"; +// hash["hruco"] = "ratio_hruco"; +// hash["hrucu"] = "ratio_hrucu"; +// hash["ouho"] = "ratio_ouho"; +// hash["ouhu"] = "ratio_ouhu"; +// hash["ouco"] = "ratio_ouco"; +// hash["oucu"] = "ratio_oucu"; +// hash["houho"] = "ratio_houho"; +// hash["houhu"] = "ratio_houhu"; +// hash["houco"] = "ratio_houco"; +// hash["houcu"] = "ratio_houcu"; +// hash["w3h"] = "ratio_w3h"; +// hash["w3c"] = "ratio_w3c"; +// hash["w3n"] = "ratio_w3n"; +// hash["areh"] = "ratio_are"; +// hash["arec"] = "ratio_are"; +// hash["breh"] = "ratio_bre"; +// hash["brec"] = "ratio_bre"; +// hash["creh"] = "ratio_cre"; +// hash["crec"] = "ratio_cre"; +// hash["dreh"] = "ratio_dre"; +// hash["drec"] = "ratio_dre"; +// hash["ereh"] = "ratio_ere"; +// hash["erec"] = "ratio_ere"; +// hash["freh"] = "ratio_fre"; +// hash["frec"] = "ratio_fre"; +// hash["arouo"] = "ratio_arouo"; +// hash["arouu"] = "ratio_arouu"; +// hash["brouo"] = "ratio_brouo"; +// hash["brouu"] = "ratio_brouu"; +// hash["crouo"] = "ratio_crouo"; +// hash["crouu"] = "ratio_crouu"; +// hash["drouo"] = "ratio_drouo"; +// hash["drouu"] = "ratio_drouu"; +// hash["erouo"] = "ratio_erouo"; +// hash["erouu"] = "ratio_erouu"; +// hash["frouo"] = "ratio_frouo"; +// hash["frouu"] = "ratio_frouu"; +// hash["pouho"] = "ratio_ouho"; +// hash["pouhu"] = "ratio_ouhu"; +// hash["pouco"] = "ratio_ouco"; +// hash["poucu"] = "ratio_oucu"; +// hash["hpouho"] = "ratio_houho"; +// hash["hpouhu"] = "ratio_houhu"; +// hash["hpouco"] = "ratio_houco"; +// hash["hpoucu"] = "ratio_houcu"; +// hash["taruo"] = "ratio_taruo"; +// hash["taruu"] = "ratio_taruu"; +// hash["tbruo"] = "ratio_tbruo"; +// hash["tbruu"] = "ratio_tbruu"; +// hash["tdruo"] = "ratio_tdruo"; +// hash["tdruu"] = "ratio_tdruu"; +// hash["teruo"] = "ratio_teruo"; +// hash["teruu"] = "ratio_teruu"; +// hash["prouc"] = "ratio_rouo"; +// hash["prouh"] = "ratio_rouu"; +// hash["hprouc"] = "ratio_hrouo"; +// hash["hprouh"] = "ratio_hrouu"; +// hash["preh"] = "ratio_re"; +// hash["prec"] = "ratio_re"; +// hash["hpreh"] = "ratio_hre"; +// hash["hprec"] = "ratio_hre"; +// hash["pareh"] = "ratio_are"; +// hash["parec"] = "ratio_are"; +// hash["pbreh"] = "ratio_bre"; +// hash["pbrec"] = "ratio_bre"; +// hash["pcreh"] = "ratio_cre"; +// hash["pcrec"] = "ratio_cre"; +// hash["pdreh"] = "ratio_dre"; +// hash["pdrec"] = "ratio_dre"; +// hash["pereh"] = "ratio_ere"; +// hash["perec"] = "ratio_ere"; +// hash["pfreh"] = "ratio_fre"; +// hash["pfrec"] = "ratio_fre"; +// hash["parouo"] = "ratio_arouo"; +// hash["parouu"] = "ratio_arouu"; +// hash["pbrouo"] = "ratio_brouo"; +// hash["pbrouu"] = "ratio_brouu"; +// hash["pcrouo"] = "ratio_crouo"; +// hash["pcrouu"] = "ratio_crouu"; +// hash["pdrouo"] = "ratio_drouo"; +// hash["pdrouu"] = "ratio_pdrouu"; +// hash["perouo"] = "ratio_erouo"; +// hash["perouu"] = "ratio_erouu"; +// hash["pfrouo"] = "ratio_frouo"; +// hash["pfrouu"] = "ratio_frouu"; +// hash["prouho"] = "ratio_rouho"; +// hash["prouhu"] = "ratio_rouhu"; +// hash["prouco"] = "ratio_rouco"; +// hash["proucu"] = "ratio_roucu"; +// hash["hpruho"] = "ratio_hruho"; +// hash["hpruhu"] = "ratio_hruhu"; +// hash["hpruco"] = "ratio_hruco"; +// hash["hprucu"] = "ratio_hrucu"; +// hash["ptaruo"] = "ratio_taruo"; +// hash["ptaruu"] = "ratio_taruu"; +// hash["ptbruo"] = "ratio_tbruo"; +// hash["ptbruu"] = "ratio_tbruu"; +// hash["ptdruo"] = "ratio_tdruo"; +// hash["ptdruu"] = "ratio_tdr uu"; +// hash["pteruo"] = "ratio_teruo"; +// hash["pteruu"] = "ratio_teruu"; +// return hash[rtype] != null ? hash[rtype] : rtype +//} +//; \ No newline at end of file diff --git a/CrownClient/Utils.h b/CrownClient/Utils.h new file mode 100644 index 0000000..028a83a --- /dev/null +++ b/CrownClient/Utils.h @@ -0,0 +1,1968 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +typedef enum _ProjectType{ + Early, + Today, + RollBall +}ProjectType; + +typedef enum _MarketChange { + MARKET_IMPROVED, // 变好(对投注者更有利) + MARKET_WORSENED, // 变差(对投注者更不利) + MARKET_UNCHANGED, // 没变 + MARKET_INVALID // 无效输入 +}MarketChange; + + +class Utils { +private: + Utils(); + ~Utils(); + +public: + static Utils& instance(); +public: + // 取选择队伍 + QString findSuffix(const QString& str1, const QString& str2); + // ABC_0 去除后缀 + QString convertToBase(const QString& input); + // 转换为客户端 + QMap toClient(QMap); + // 转换为今日 + QMap toToday(QMap); + // 转换为滚球 + QMap toLive(QMap); + // 转换为反跟 + QMap toContra(QMap); + // 获取类型代号 + QMap type(QString projcet, QString type); + // 获取错误信息 + QString error(QString errorCode); + + + QString formatGold(QString gold); + + + + + + // 反向映射 rtype:从标准格式转回原始格式 + static QString reverse_map_rtype(const QString &rtypeIn) { + QString r = rtypeIn.trimmed().toUpper(); + + // 反向映射表:标准 → 原始 + static const QMap reverseHash = { + // 标准 → 简写(优先返回简写) + {"EOO", "ODD"}, + {"EOE", "EVEN"}, + {"HEOO", "HODD"}, + {"HEOE", "HEVEN"}, + {"REOO", "RODD"}, + {"REOE", "REVEN"}, + {"HREOO","HRODD"}, + {"HREOE","HREVEN"} + }; + + return reverseHash.contains(r) ? reverseHash.value(r) : r; + } + + // 反向映射 wtype:从标准格式转回原始格式 + static QString reverse_map_wtype(const QString &wtypeIn) { + QString w = wtypeIn.trimmed().toUpper(); + // 反向映射表:标准 → 原始 + static const QMap reverseHash = { + {"EO", "T"}, + {"REO", "RT"}, + {"HEO", "HT"}, + {"HREO", "HRT"} + }; + + // 如果是单双类型,进行反向映射 + if (reverseHash.contains(w)) { + return reverseHash.value(w); + } + + // 非单双类型,保持原样 + return w; + } + + QString get_chose_team(QString rtype) { + // 让球 + if (rtype == "REH" || rtype == "RH" || rtype == "HREH" || rtype == "HRH") + { + return "H"; + } + // 受让 + if (rtype == "REC" || rtype == "RC" || rtype == "HREC" || rtype == "HRC") + { + return "C"; + } + // 大 + if (rtype == "ROUC" || rtype == "OUC" || rtype == "HROUC" || rtype == "HOUC") + { + return "C"; + } + // 小 + if (rtype == "ROUH" || rtype == "OUH" || rtype == "HROUH" || rtype == "HOUH") + { + return "H"; + } + // 独赢主 + if (rtype == "RMH" || rtype == "MH" || rtype == "HRMH" || rtype == "HMH") + { + return "H"; + } + // 独赢客 + if (rtype == "RMC" || rtype == "MC" || rtype == "HRMC" || rtype == "HMC") + { + return "C"; + } + // 独赢和 + if (rtype == "RMN" || rtype == "MN" || rtype == "HRMN" || rtype == "HMN") + { + return "N"; + } + //// 单 + //if (rtype == "REOO" || rtype == "EOO" || rtype == "HREOO" || rtype == "HEOO") + //{ + // return rtype; + //} + //// 双 + //if (rtype == "REOE" || rtype == "EOE" || rtype == "HREOE" || rtype == "HEOE") + //{ + // return rtype; + //} + // 改 + //// 单 + //if (rtype == "RODD" || rtype == "ODD" || rtype == "HRODD" || rtype == "HODD") + //{ + // return "单"; + //} + //// 双 + //if (rtype == "REVEN" || rtype == "EVEN" || rtype == "HREVEN" || rtype == "HEVEN") + //{ + // return "双"; + //} + + // 主队大 + if (rtype == "ROUHO" || rtype == "OUHO" || rtype == "HROUHO" || rtype == "HOUHO") + { + return "O"; + } + // 主队小 + if (rtype == "ROUHU" || rtype == "OUHU" || rtype == "HROUHU" || rtype == "HOUHU") + { + return "U"; + } + // 客队大 + if (rtype == "ROUCO" || rtype == "OUCO" || rtype == "HROUCO" || rtype == "HOUCO") + { + return "O"; + } + // 客队小 + if (rtype == "ROUCU" || rtype == "OUCU" || rtype == "HROUCU" || rtype == "HOUCU") + { + return "U"; + } + return rtype; + } + + // 检查是否为滚球 + static bool is_roll_ball(const QString wtype) { + static const QStringList wtypeRB = { + "RE", "ROU", "HRE", "HROU", "RM", "HRM", "ARE", "BRE", "CRE", "DRE", "ERE", "FRE", + "AROU", "BROU", "CROU", "DROU", "EROU", "FROU", "ARM", "BRM", "CRM", "DRM", "ERM", "FRM", + "ROUH", "ROUC", "HRUH", "HRUC", "RPD", "RPD3", "RPD5", "RPD7", "HRPD", "RDT", "RT", "HRT", + "REO", "HREO", "RF", "RHG", "RMG", "ARG", "BRG", "CRG", "DRG", "ERG", "FRG", "GRG", "HRG", + "IRG", "JRG", "RWM", "RDC", "RCS", "RWN", "RTS", "RWB", "RWE", "RSB", "RT1G", "RT3G" + }; + return wtypeRB.contains(wtype.toUpper()); + } + + // 获取游戏类型 + QString get_wagers_wtype_name(QString wtype); + + + MarketChange checkOverUnderChange(const std::string& marketType, + const std::string& oldMarket, + const std::string& newMarket); + + MarketChange checkHandicapChange(const std::string& marketType, + const std::string& oldMarket, + const std::string& newMarket); + + + int get_number_of_application_name(); + + + + + // + static QString gtype_map(const QString >ype) { + QString w = gtype.trimmed().toUpper(); + + // 游戏类型映射表:代码 -> 中文名称 + static const QMap gtypeToChinese = { + {"FT", "足球"}, // Football + {"BK", "篮球"}, // Basketball + {"ES", "电竞"}, // E-Sports + {"BS", "棒球"}, // Baseball + {"BM", "羽毛球"}, // Badminton + {"OP", "其他"}, // Other + {"SK", "斯诺克"}, // Snooker + {"TT", "乒乓球"}, // Table Tennis + {"TN", "网球"}, // Tennis + {"VB", "排球"} // Volleyball + }; + + // 中文名称映射表:中文名称 -> 代码 + static const QMap chineseToGtype = { + {"足球", "FT"}, // Football + {"篮球 / 美式足球", "BK"}, // Basketball + {"篮球", "BK"}, // Basketball + {"电竞", "ES"}, // E-Sports + {"棒球", "BS"}, // Baseball + {"羽毛球", "BM"}, // Badminton + {"其他", "OP"}, // Other + {"斯诺克", "SK"}, // Snooker + {"乒乓球", "TT"}, // Table Tennis + {"网球", "TN"}, // Tennis + {"排球", "VB"} // Volleyball + }; + + // 检查是否为游戏类型代码 + if (gtypeToChinese.contains(w)) { + return gtypeToChinese.value(w); + } + + // 检查是否为中文游戏类型名称 + if (chineseToGtype.contains(w)) { + return chineseToGtype.value(w); + } + + // 如果都不匹配,保持原样 + return w; + } + + static QString showtype_map(const QString &showtype) { + QString w = showtype.trimmed().toLower(); + + // 显示类型映射表:代码 -> 中文名称 + static const QMap showtypeToChinese = { + {"live", "滚球"}, // Live - 正在进行中的比赛 + {"today", "今日"}, // Today - 今天进行的比赛 + {"early", "早盘"}, // Early - 未来进行的比赛 + {"mygame", "我的游戏"}, // My Game - 用户收藏的比赛 + {"parlay", "串关"}, // Parlay - 组合投注 + {"hot", "热门"}, // Hot - 热门比赛 + {"soon", "即将开始"} // Soon - 即将开始的比赛 + }; + + // 中文名称映射表:中文名称 -> 代码 + static const QMap chineseToShowtype = { + {"滚球", "live"}, // Live + {"今日", "today"}, // Today + {"早盘", "early"}, // Early + {"我的游戏", "mygame"}, // My Game + {"串关", "parlay"}, // Parlay + {"热门", "hot"}, // Hot + {"即将开始", "soon"} // Soon + }; + + // 检查是否为显示类型代码 + if (showtypeToChinese.contains(w)) { + return showtypeToChinese.value(w); + } + + // 检查是否为中文显示类型名称 + if (chineseToShowtype.contains(w)) { + return chineseToShowtype.value(w); + } + + // 如果都不匹配,保持原样 + return w; + } + + static QString format_wagers_type(QMap& order) + { + QString wt = order.value("WAGERS_TYPE"); + QString teamH = order.value("TEAM_H"); + QString teamC = order.value("TEAM_C"); + + auto reHas = [](const QString& s, const QString& pat)->bool { + QRegularExpression re(pat, QRegularExpression::CaseInsensitiveOption); + return re.isValid() ? re.match(s).hasMatch() : s.contains(pat, Qt::CaseInsensitive); + }; + + wt.replace(QRegularExpression("\\s*/\\s*"), "/"); + + auto cleanTeam = [](QString s)->QString { + s.replace(QRegularExpression("", QRegularExpression::CaseInsensitiveOption), ""); + s.remove(' '); + return s.trimmed(); + }; + teamH = cleanTeam(teamH); + teamC = cleanTeam(teamC); + + // 让分/让球 + if (reHas(wt, "(让球|让分)")) return "让球"; + + // 大/小(含大小分、球队总分) + if (reHas(wt, "(大/小|大小|大小分)")) { + const bool refHome = (!teamH.isEmpty() && wt.contains(teamH, Qt::CaseInsensitive)) || reHas(wt, "主队"); + const bool refAway = (!teamC.isEmpty() && wt.contains(teamC, Qt::CaseInsensitive)) || reHas(wt, "客队"); + if (refHome) return "主大小"; + if (refAway) return "客大小"; + return "大小"; + } + + // 独赢/胜负 + if (reHas(wt, "(独赢|胜负|money\\s*line|moneyline)")) return "独赢"; + + // 单双 + if (reHas(wt, "(单/双|单双)")) return "单双"; + + // 双方进球 + if (reHas(wt, "(双方球队进球|Both\\s*Teams\\s*To\\s*Score|BTTS)")) return "双方进球"; + + // 下个进球 / 首个进球 / 最后进球 + if (reHas(wt, "(下个进球|下一个进球|Next\\s*Goal)")) return "下个进球"; + if (reHas(wt, "(首个进球|第一球|First\\s*Goal|First\\s*Team\\s*To\\s*Score)")) return "首个进球"; + if (reHas(wt, "(最后进球|最后一球|Last\\s*Goal)")) return "最后进球"; + + // 角球/罚牌/晋级/冠军/点球/加时 + if (reHas(wt, "角球")) return "角球"; + if (reHas(wt, "(罚牌|红牌|黄牌|卡牌|cards?)")) return "罚牌"; + if (reHas(wt, "(晋级|To\\s*Qualify|Qualify)")) return "晋级"; + if (reHas(wt, "(冠军|Outright|Futures)")) return "冠军"; + if (reHas(wt, "(点球大战|点球|PK\\b|Penalty)")) return "点球"; + if (reHas(wt, "(加时|OT\\b|ET\\b|Over\\s*Time|Extra\\s*Time)")) return "加时"; + + return wt; + } + + static QString format_order_type(QMap& order) + { + QString wt = order.value("WAGERS_TYPE"); + QString otype = order.value("ORDER_TYPE"); + QString teamH = order.value("TEAM_H"); + QString teamC = order.value("TEAM_C"); + + auto reHas = [](const QString& s, const QString& pat)->bool { + QRegularExpression re(pat, QRegularExpression::CaseInsensitiveOption); + return re.isValid() ? re.match(s).hasMatch() : s.contains(pat, Qt::CaseInsensitive); + }; + + wt.replace(QRegularExpression("\\s*/\\s*"), "/"); + + // 让分/让球 + if (reHas(wt, "(让球|让分)")) { + return (otype == teamH) ? "让球" : "受让"; + } + + //// 大/小(含大小分、球队总分) + //if (reHas(wt, "(大/小|大小|大小分)")) { + // const bool refHome = (!teamH.isEmpty() && wt.contains(teamH, Qt::CaseInsensitive)) || reHas(wt, "主队"); + // const bool refAway = (!teamC.isEmpty() && wt.contains(teamC, Qt::CaseInsensitive)) || reHas(wt, "客队"); + // if (refHome) return "主大小"; + // if (refAway) return "客大小"; + // return "大小"; + //} + + + // 大/小(含大小分、球队总分) + if (reHas(wt, "(大/小|大小|大小分)")) { + const bool refHome = (!teamH.isEmpty() && wt.contains(teamH, Qt::CaseInsensitive)) || reHas(wt, "主队"); + const bool refAway = (!teamC.isEmpty() && wt.contains(teamC, Qt::CaseInsensitive)) || reHas(wt, "客队"); + + if (reHas(otype, "大")) { + if (refHome) return "主队大"; + if (refAway) return "客队大"; + return "大"; // 全场大 + } + if (reHas(otype, "小")) { + if (refHome) return "主队小"; + if (refAway) return "客队小"; + return "小"; // 全场小 + } + return otype; // 保持原样 + } + + //// 球队大小分(主队大/小、客队大/小) + //// 必须优先匹配队伍大小 + //if (reHas(wt, "(主队大/小|主队大小|主队大小分)")) { + // if (reHas(otype, "大")) return "主队大"; + // if (reHas(otype, "小")) return "主队小"; + // return otype; + //} + //if (reHas(wt, "(客队大/小|客队大小|客队大小分)")) { + // if (reHas(otype, "大")) return "客队大"; + // if (reHas(otype, "小")) return "客队小"; + // return otype; + //} + + //// 大小/大小分(全场) + //if (reHas(wt, "(大/小|大小|大小分)")) { + // return otype; // 大 / 小 + //} + + + + // 独赢/胜负 + if (reHas(wt, "(独赢|胜负|money\\s*line|moneyline)")) { + if (otype == teamH) return "独赢主"; + if (otype == teamC) return "独赢客"; + return "独赢和"; + } + + // 单双 + if (reHas(wt, "(单/双|单双)")) return otype; // 单 / 双 + + // 双方进球:是/否 + if (reHas(wt, "(双方球队进球|Both\\s*Teams\\s*To\\s*Score|BTTS)")) { + if (reHas(otype, "(是|YES)")) return "双方进球-是"; + if (reHas(otype, "(否|NO)")) return "双方进球-否"; + return otype; + } + + // 下个进球 / 首个进球 / 最后进球:主/客/无进球 + if (reHas(wt, "(下个进球|下一个进球|Next\\s*Goal)")) { + if (otype == teamH) return "下个进球-主队"; + if (otype == teamC) return "下个进球-客队"; + if (reHas(otype, "(无进球|No\\s*Goal)")) return "下个进球-无进球"; + return otype; + } + if (reHas(wt, "(首个进球|第一球|First\\s*Goal|First\\s*Team\\s*To\\s*Score)")) { + if (otype == teamH) return "首个进球-主队"; + if (otype == teamC) return "首个进球-客队"; + if (reHas(otype, "(无进球|No\\s*Goal)")) return "首个进球-无进球"; + return otype; + } + if (reHas(wt, "(最后进球|最后一球|Last\\s*Goal)")) { + if (otype == teamH) return "最后进球-主队"; + if (otype == teamC) return "最后进球-客队"; + if (reHas(otype, "(无进球|No\\s*Goal)")) return "最后进球-无进球"; + return otype; + } + + // 其他玩法保持原样(角球/罚牌/晋级/冠军/点球/加时等) + return otype; + } + // 场次格式化 + QString format_stage(QMap& order) + { + if (order["WARGES_TYPE"].contains("全场")) + { + return "全场"; + } + if (order["WARGES_TYPE"].contains("上半场")) + { + return "上半场"; + } + if (order["WARGES_TYPE"].contains("下半场")) + { + return "下半场"; + } + if (order["WARGES_TYPE"].contains("第一节")) + { + return "第一节"; + } + if (order["WARGES_TYPE"].contains("第二节")) + { + return "第二节"; + } + if (order["WARGES_TYPE"].contains("第三节")) + { + return "第三节"; + } + if (order["WARGES_TYPE"].contains("第四节")) + { + return "第四节"; + } + if (order["WARGES_TYPE"].contains("加时")) + { + return "加时"; + } + if (order["WARGES_TYPE"].contains("角球")) + { + return "角球"; + } + if (order["WARGES_TYPE"].contains("罚牌")) + { + return "罚牌"; + } + if (order["WARGES_TYPE"].contains("晋级")) + { + return "晋级"; + } + if (order["WARGES_TYPE"].contains("冠军")) + { + return "冠军"; + } + if (order["WARGES_TYPE"].contains("点球")) + { + return "点球"; + } + return ""; + } + + + + // 赛段/时段判断:返回 "全场" / "上半场" / "下半场" / "分节" + // - 覆盖关键字:全场/上半场/下半场/半场/第一节/第x节/第x局/第x盘/Q1~Q4/第一盘等 + static QString get_stage_tag(const QString& wt) + { + QString w = wt; + + auto reHas = [](const QString& s, const QString& pat)->bool { + QRegularExpression re(pat, QRegularExpression::CaseInsensitiveOption); + return re.isValid() ? re.match(s).hasMatch() : s.contains(pat, Qt::CaseInsensitive); + }; + + // 明确全场 + if (reHas(w, "(全场|FT\\b|Full\\s*Time)")) return "全场"; + + // 半场(优先识别上下半) + if (reHas(w, "(上半场|上半)")) return "上半场"; + if (reHas(w, "(下半场|下半)")) return "下半场"; + if (reHas(w, "(半场|HT\\b|1H\\b|2H\\b)")) return "上半场"; // 未指明上下,按 HTML 常见处理归为“半场”→"上半场" + + // 分节(Q1~Q4、第一节/第二节/…;或者 局/盘) + if (reHas(w, "(Q[1-4]\\b|第\\s*一\\s*节|第\\s*二\\s*节|第\\s*三\\s*节|第\\s*四\\s*节|第\\s*\\d+\\s*节|第\\s*\\d+\\s*局|第\\s*\\d+\\s*盘)")) + return "分节"; + + // 网球/乒乓/斯诺克等常见“盘/局”也视作分节 + if (reHas(w, "(第一盘|第二盘|第三盘|第一局|第二局|第三局)")) + return "分节"; + + // 默认当全场处理 + return "全场"; + } + + // 玩法子类标签:命中则放入返回列表(可能多标签并存) + // 覆盖:加时/角球/罚牌/晋级/点球/冠军(可扩展) + // - 加时:加时/加时赛/含加时/OT/ET + // - 角球:角球/角球数/角球大小/角球让球 + // - 罚牌:罚牌/红牌/黄牌/牌数/卡牌 + // - 晋级:晋级/To Qualify/Qualify + // - 点球:点球/点球大战/PK/Penalty + // - 冠军:冠军/优胜/Outright/Futures/联赛赢家/赛季冠军 + static QStringList get_market_tags(const QString& wt) + { + QStringList tags; + auto reHas = [](const QString& s, const QString& pat)->bool { + QRegularExpression re(pat, QRegularExpression::CaseInsensitiveOption); + return re.isValid() ? re.match(s).hasMatch() : s.contains(pat, Qt::CaseInsensitive); + }; + if (reHas(wt, "(加时|加时赛|含加时|OT\\b|ET\\b|Over\\s*Time|Extra\\s*Time)")) + tags << "加时"; + + if (reHas(wt, "(角球|角球数|角球大小|角球让球|Corner)")) + tags << "角球"; + + if (reHas(wt, "(罚牌|红牌|黄牌|牌数|卡牌|Cards?)")) + tags << "罚牌"; + + if (reHas(wt, "(晋级|To\\s*Qualify|Qualify)")) + tags << "晋级"; + + if (reHas(wt, "(点球大战|点球|罚点球|PK\\b|Penalty|Pen\\.?\\b)")) + tags << "点球"; + + if (reHas(wt, "(冠军|优胜|联赛赢家|赛季冠军|联赛冠军|夺冠|Outright|Futures)")) + tags << "冠军"; + + // 需要更多类型时,继续追加: + // if (reHas(wt, "(界外球|任意球|球门球|Goal\\s*Kicks|Throw\\s*In)")) tags << "边球类"; + // if (reHas(wt, "(射正|射门|Shots\\s*On|Shots)")) tags << "射门"; + + return tags; + } + + static QString get_market(const QString& wt) + { + auto reHas = [](const QString& s, const QString& pat)->bool { + QRegularExpression re(pat, QRegularExpression::CaseInsensitiveOption); + return re.isValid() ? re.match(s).hasMatch() : s.contains(pat, Qt::CaseInsensitive); + }; + if (reHas(wt, "(加时|加时赛|含加时|OT\\b|ET\\b|Over\\s*Time|Extra\\s*Time)")) + { + return "(加时)"; + } + + if (reHas(wt, "(角球|角球数|角球大小|角球让球|Corner)")) + { + return "(角球)"; + } + + if (reHas(wt, "(罚牌|红牌|黄牌|牌数|卡牌|Cards?)")) + { + return "(罚牌)"; + } + + + if (reHas(wt, "(晋级|To\\s*Qualify|Qualify)")) + { + return "(晋级)"; + } + + if (reHas(wt, "(点球大战|点球|罚点球|PK\\b|Penalty|Pen\\.?\\b)")) + { + return "(点球)"; + } + + if (reHas(wt, "(冠军|优胜|联赛赢家|赛季冠军|联赛冠军|夺冠|Outright|Futures)")) + { + return "(冠军)"; + } + + // 需要更多类型时,继续追加: + // if (reHas(wt, "(界外球|任意球|球门球|Goal\\s*Kicks|Throw\\s*In)")) tags << "边球类"; + // if (reHas(wt, "(射正|射门|Shots\\s*On|Shots)")) tags << "射门"; + + return ""; + } + + + static QString get_wtype_code(QMap& order) + { + QString wt = order.value("WAGERS_TYPE"); + QString session = order.value("SESSION"); + QString teamH = order.value("TEAM_H"); + QString teamC = order.value("TEAM_C"); + + auto reHas = [](const QString& s, const QString& pat)->bool { + QRegularExpression re(pat, QRegularExpression::CaseInsensitiveOption); + return re.isValid() ? re.match(s).hasMatch() : s.contains(pat, Qt::CaseInsensitive); + }; + + bool isRB = reHas(wt, "滚球"); + bool isHalf = reHas(wt, "(上半场|半场)"); + + // 是否为“球队总分大小”(主/客队) + bool isHomeTotal = (!teamH.isEmpty() && wt.contains(teamH, Qt::CaseInsensitive)) || reHas(wt, "主队"); + bool isAwayTotal = (!teamC.isEmpty() && wt.contains(teamC, Qt::CaseInsensitive)) || reHas(wt, "客队"); + + // 1) 基础盘口类型 → base + // R 让球; OU 大小; OUH/OUC 主/客队总分大小; M 独赢; EO 单双 + // 可选扩展:G 下个进球;TS 双方球队进球 + QString base; + if (reHas(wt, "让球")) { + base = "R"; + } + else if (reHas(wt, "大\\s*/\\s*小|大小|大 / 小")) { + if (isHomeTotal) base = "OUH"; // 主队总分大小 + else if (isAwayTotal) base = "OUC"; // 客队总分大小 + else base = "OU"; // 全场大小 + } + else if (reHas(wt, "独赢")) { + base = "M"; + } + else if (reHas(wt, "单\\s*/\\s*双|单双|单 / 双")) { + base = "EO"; + } + else if (reHas(wt, "下个进球")) { + base = "G"; + } + else if (reHas(wt, "双方球队进球")) { + base = "TS"; + } + else { + return QString(); + } + + // 2) 滚球替换(与 html 一致) + auto applyRb = [&](const QString& b)->QString { + if (!isRB) return b; + if (b == "R") return "RE"; + if (b == "OU") return "ROU"; + if (b == "OUH") return "ROUH"; + if (b == "OUC") return "ROUC"; + if (b == "M") return "RM"; + if (b == "EO") return "REO"; + if (b == "G") return "RG"; + if (b == "TS") return "RTS"; + return b; + }; + + // 3) 半场前缀(与 html 一致,半场在最前加 H) + auto applyHalf = [&](const QString& p)->QString { + if (!isHalf) return p; + if (p == "R") return "HR"; + if (p == "RE") return "HRE"; + if (p == "OU") return "HOU"; + if (p == "ROU") return "HROU"; + if (p == "OUH") return "HOUH"; + if (p == "ROUH") return "HROUH"; + if (p == "OUC") return "HOUC"; + if (p == "ROUC") return "HROUC"; + if (p == "M") return "HM"; + if (p == "RM") return "HRM"; + if (p == "EO") return "HEO"; + if (p == "REO") return "HREO"; + if (p == "G") return "HG"; + if (p == "RG") return "HRG"; + if (p == "TS") return "HTS"; + if (p == "RTS") return "HRTS"; + return p; + }; + + QString wtype = applyRb(base); + if (!order["GT"].contains("篮球")) + { + //qDebug() << "半场替换?"; + wtype = applyHalf(wtype); + } + + return wtype; + } + + // 获取游戏列表用 + static QString get_rtype_code_for_request(const QMap& order) + { + QString session = order.value("SESSION"); + QString show = order.value("showtype"); + QString gtRaw = order.value("GT"); + QString wt = order.value("WAGERS_TYPE"); + + auto norm = [](QString s)->QString { + s.replace(QRegularExpression("\\s+"), " ").trimmed(); + s.replace(QRegularExpression("\\s*/\\s*"), "/"); + return s; + }; + wt = norm(wt); + + auto has = [](const QString& s, const QString& pat)->bool { + QRegularExpression re(pat, QRegularExpression::CaseInsensitiveOption); + return re.match(s).hasMatch(); + }; + + QString gtype = Utils::gtype_map(gtRaw).toLower(); // ft/bk/... + + // 1) 滚球优先 + const bool isRB = (session == "滚球") || (show == "live") || has(wt, "滚球"); + if (isRB) { + if (gtype == "ft" && has(wt, "(角球|corner)")) return "rrnou"; + return "rb"; + } + + // 2) 专题类(今日/早盘) + if (has(wt, "(冠军|Outright|Futures)")) return "outr"; + if (gtype == "ft" && has(wt, "(角球|corner)")) return "rnou"; + if (has(wt, "(单双|单/双)")) return "eo"; + if (has(wt, "(波胆|正确比分)")) return "pd"; + if (has(wt, "(双方球队进球|Both\\s*Teams\\s*To\\s*Score|BTTS)")) return "ts"; + if (has(wt, "(下个进球|下一个进球|首个进球|第一球|最后进球|Next\\s*Goal|First\\s*Goal|Last\\s*Goal)")) return "g"; + if (has(wt, "(点球大战|点球|Penalty|PK\\b)")) return "pen"; + if (has(wt, "(加时|OT\\b|ET\\b|Over\\s*Time|Extra\\s*Time)")) return "ot"; + if (has(wt, "(晋级|To\\s*Qualify|Qualify)")) return "q"; + + // 3) 主盘集合(让球/让分 或 大小/大小分 或 独赢/胜负)→ moua + if (has(wt, "(让球|让分)") || has(wt, "(大小分|大/小|大小)") || has(wt, "(独赢|胜负|money\\s*line|moneyline)")) + return "moua"; + + // 4) 兜底:未知归总入口 + return "moua"; + } + + static QString get_rtype_code(QMap& order) + { + const QString wt = order.value("WAGERS_TYPE"); + const QString session = order.value("SESSION"); + const QString teamH = order.value("TEAM_H"); + const QString teamC = order.value("TEAM_C"); + const QString otype = order.value("ORDER_TYPE"); + + auto reHas = [](const QString& s, const QString& pat)->bool { + QRegularExpression re(pat, QRegularExpression::CaseInsensitiveOption); + return re.isValid() ? re.match(s).hasMatch() : s.contains(pat, Qt::CaseInsensitive); + }; + + const bool isRB = reHas(wt, "滚球"); + const bool isHalf = reHas(wt, "(上半场|半场)"); + + // 1) 基础盘别(按 html 的关键字正则) + auto baseOf = [&]() -> QString { + if (reHas(wt, "让球")) return "R"; + if (reHas(wt, "大\\s*/\\s*小|大小|大 / 小")) return "OU"; + if (reHas(wt, "独赢")) return "M"; + if (reHas(wt, "单\\s*/\\s*双|单双|单 / 双")) return "EO"; + return ""; + }; + + // 2) 滚球替换 + auto addRb = [&](const QString& b)->QString { + if (!isRB) return b; + if (b == "R") return "RE"; + if (b == "OU") return "ROU"; + if (b == "M") return "RM"; + if (b == "EO") return "REO"; + return b; + }; + + // 3) 半场前缀 + auto addHalf = [&](const QString& p)->QString { + if (!isHalf) return p; + if (p == "R") return "HR"; + if (p == "RE") return "HRE"; + if (p == "OU") return "HOU"; + if (p == "ROU") return "HROU"; + if (p == "M") return "HM"; + if (p == "RM") return "HRM"; + if (p == "EO") return "HEO"; + if (p == "REO") return "HREO"; + return p; + }; + + // 4) 后缀(侧别/结果),严格按 html 语义 + auto suffix = [&](const QString& p)->QString { + // 让球:主 H / 客 C + if (p == "R" || p == "RE" || p == "HR" || p == "HRE") { + return (otype == teamH) ? "H" : "C"; + } + // 大小:全场 C=大 / H=小;若指向主/客队总分,用 HO/HU/CO/CU + if (p == "OU" || p == "ROU" || p == "HOU" || p == "HROU") { + const bool refHome = (!teamH.isEmpty() && wt.contains(teamH, Qt::CaseInsensitive)) || reHas(wt, "主队"); + const bool refAway = (!teamC.isEmpty() && wt.contains(teamC, Qt::CaseInsensitive)) || reHas(wt, "客队"); + const bool isBig = reHas(otype, "大"); + + if (refHome) return isBig ? "HO" : "HU"; + if (refAway) return isBig ? "CO" : "CU"; + return isBig ? "C" : "H"; + } + // 独赢:主 H / 客 C / 和 N + if (p == "M" || p == "RM" || p == "HM" || p == "HRM") { + if (otype == teamH) return "H"; + if (otype == teamC) return "C"; + return "N"; + } + // 单双:单 O / 双 E + if (p == "EO" || p == "REO" || p == "HEO" || p == "HREO") { + return reHas(otype, "单") ? "O" : "E"; + } + return ""; + }; + + QString b = baseOf(); // R / OU / M / EO + if (b.isEmpty()) return QString(); + + b = addRb(b); // → RE/ROU/RM/REO + if (!order["GT"].contains("篮球")) + { + b = addHalf(b); // → HRE/HROU/HRM/HREO(若半场) + } + + const QString suf = suffix(b); // H/C/N/O/E/HO/HU/CO/CU + + if (suf.isEmpty()) return QString(); + return b + suf; + } + + // 基于开赛时间 G_TIME 判定会话:滚球/今日/早盘(按“皇冠时间=本地 -12h”) + // 支持 "yyyy-MM-dd HH:mm:ss" 与 "MM-dd-yyyy HH:mm:ss" + static QString get_session_by_gtime(const QMap& order) + { + QString gtime = order.value("G_TIME"); + QDateTime gdt = QDateTime::fromString(gtime, "yyyy-MM-dd HH:mm:ss"); + if (!gdt.isValid()) + gdt = QDateTime::fromString(gtime, "MM-dd-yyyy HH:mm:ss"); + if (!gdt.isValid()) + return QString(); + + // 皇冠当前时间 + QDateTime crownNow = QDateTime::currentDateTime().addSecs(-12 * 3600); + QDate crownToday = crownNow.date(); + + // 已开赛 → 滚球 + if (crownNow >= gdt) + return "滚球"; + + // 未开赛:同日 → 今日;未来日期 → 早盘 + if (gdt.date() == crownToday) + return "今日"; + if (gdt.date() > crownToday) + return "早盘"; + + // 理论到不了这里,兜底按今日 + return "今日"; + } + + + + + + + + + // 根据开赛时间自动切换会话类型:早盘->今日->滚球 + static QString get_auto_session(const QMap& order) + { + QString gtime = order.value("G_TIME"); + if (gtime.isEmpty()) { + return "早盘"; // 默认早盘 + } + + // 解析开赛时间 + QDateTime gameTime = QDateTime::fromString(gtime, "yyyy-MM-dd HH:mm:ss"); + if (!gameTime.isValid()) { + gameTime = QDateTime::fromString(gtime, "MM-dd-yyyy HH:mm:ss"); + } + if (!gameTime.isValid()) { + return "早盘"; // 解析失败,默认早盘 + } + + // 皇冠当前时间(本地-12小时) + QDateTime crownNow = QDateTime::currentDateTime().addSecs(-12 * 3600); + QDate crownToday = crownNow.date(); + QDate gameDate = gameTime.date(); + + // 判断会话类型 + if (gameDate > crownToday) { + return "早盘"; // 未来日期 -> 早盘 + } + else if (gameDate == crownToday) { + // 同一天,判断是否已开赛 + if (crownNow >= gameTime) { + return "滚球"; // 已开赛 -> 滚球 + } + else { + return "今日"; // 未开赛 -> 今日 + } + } + else { + return "滚球"; // 过去日期 -> 滚球 + } + } + + // 根据会话类型自动获取对应的 wtype 和 rtype + static QMap get_auto_wtype_rtype(QMap& order) + { + QMap result; + + // 自动切换会话 + QString session = get_auto_session(order); + result["SESSION"] = session; + // 如果变成滚球,在 WAGERS_TYPE 前边加上 "(滚球)" + if (session == "滚球") { + QString wagersType = order.value("WAGERS_TYPE"); + if (!wagersType.startsWith("(滚球)")) { + order["WAGERS_TYPE"] = "(滚球) " + wagersType; + } + } + // 根据会话类型获取 wtype + QString wtype = get_wtype_code(order); + result["wtype"] = wtype; + + // 根据会话类型获取 rtype + QString rtype = get_rtype_code(order); + result["rtype"] = rtype; + + // 根据会话类型设置 showtype + QString showtype; + if (session == "滚球") { + showtype = "live"; + } + else if (session == "今日") { + showtype = "today"; + } + else { + showtype = "early"; + } + result["showtype"] = showtype; + + return result; + } + + // 完整的自动切换函数,包含所有必要字段 + static QMap auto_switch_session(QMap order) + { + // 获取自动切换的结果 + QMap autoResult = get_auto_wtype_rtype(order); + + // 更新订单数据 + order["SESSION"] = autoResult["SESSION"]; + order["showtype"] = autoResult["showtype"]; + order["wtype"] = autoResult["wtype"]; + order["rtype"] = autoResult["rtype"]; + + // 根据会话类型设置其他相关字段 + QString session = autoResult["SESSION"]; + QString wtype = autoResult["wtype"]; + + // 设置 STAGE(全场/上半场) + QString stage = "全场"; + if (wtype.contains("H", Qt::CaseInsensitive) && + (wtype.startsWith("H") || wtype.contains("HRE") || wtype.contains("HOU"))) { + stage = "上半场"; + } + order["STAGE"] = stage; + + // 设置 G_TIME(如果为空) + if (order["G_TIME"].isEmpty()) { + order["G_TIME"] = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"); + } + + return order; + } + + // 使用示例 + void example_usage() + { + QMap order; + order["GT"] = "足球"; + order["WAGERS_TYPE"] = "让球"; + order["ORDER_TYPE"] = "让球"; + order["TEAM_H"] = "主队"; + order["TEAM_C"] = "客队"; + order["G_TIME"] = "2025-09-23 21:00:00"; // 开赛时间 + + // 自动切换会话 + QMap result = auto_switch_session(order); + + qDebug() << "自动切换结果:"; + qDebug() << " SESSION:" << result["SESSION"]; + qDebug() << " showtype:" << result["showtype"]; + qDebug() << " wtype:" << result["wtype"]; + qDebug() << " rtype:" << result["rtype"]; + qDebug() << " STAGE:" << result["STAGE"]; + } + + + static QString getCountFieldName(const QString& orderType) + { + // 让球/受让 + if (orderType == "让球" || orderType == "受让") { + return "R_COUNT"; + } + + // 大小(全场) + if (orderType == "大" || orderType == "小") { + return "OU_COUNT"; + } + + // 独赢 + if (orderType == "独赢主" || orderType == "独赢客" || orderType == "独赢和") { + return "M_COUNT"; + } + + // 单双 + if (orderType == "单" || orderType == "双") { + return "EO_COUNT"; + } + + // 角球相关 + if (orderType.contains("角球")) { + if (orderType.contains("让球")) { + return "RN_COUNT"; // 角球让球 + } + else if (orderType.contains("大") || orderType.contains("小")) { + return "CN_COUNT"; // 角球大小 + } + else if (orderType.contains("独赢")) { + return "MN_COUNT"; // 角球独赢 + } + else if (orderType.contains("单") || orderType.contains("双")) { + return "EON_COUNT"; // 角球单双 + } + else { + return "CN_COUNT"; // 默认角球盘 + } + } + + // 波胆(正确比分) + if (orderType.contains("波胆") || orderType.contains("正确比分")) { + return "PD_COUNT"; + } + + // 总进球 + if (orderType.contains("总进球") || orderType.contains("进球数")) { + return "TQ_COUNT"; + } + + // 加时相关 + if (orderType.contains("加时")) { + if (orderType.contains("让球")) { + return "RET_COUNT"; // 加时让球 + } + else if (orderType.contains("大") || orderType.contains("小")) { + return "OUET_COUNT"; // 加时大小 + } + else if (orderType.contains("独赢")) { + return "MET_COUNT"; // 加时独赢 + } + else { + return "ET_COUNT"; // 默认加时盘 + } + } + + // 点球相关 + if (orderType.contains("点球")) { + if (orderType.contains("让球")) { + return "RPK_COUNT"; // 点球让球 + } + else if (orderType.contains("大") || orderType.contains("小")) { + return "OUPK_COUNT"; // 点球大小 + } + else if (orderType.contains("独赢")) { + return "MPK_COUNT"; // 点球独赢 + } + else { + return "PK_COUNT"; // 默认点球盘 + } + } + + // 特殊功能 + if (orderType.contains("特殊") || orderType.contains("特殊功能")) { + return "SFS_COUNT"; + } + + // 其他特殊玩法 + if (orderType.contains("双方进球")) { + return "TS_COUNT"; + } + + if (orderType.contains("下个进球") || orderType.contains("首个进球") || orderType.contains("最后进球")) { + return "G_COUNT"; + } + + if (orderType.contains("主队大") || orderType.contains("主队小")) { + return "OUH_COUNT"; + } + + if (orderType.contains("客队大") || orderType.contains("客队小")) { + return "OUC_COUNT"; + } + + if (orderType.contains("罚牌") || orderType.contains("卡牌")) { + return "CARD_COUNT"; + } + + if (orderType.contains("晋级") || orderType.contains("资格")) { + return "QUALIFY_COUNT"; + } + + if (orderType.contains("冠军")) { + return "CHAMPION_COUNT"; + } + + // 上半场相关 + if (orderType.contains("上半场")) { + if (orderType.contains("让球")) { + return "HR_COUNT"; + } + else if (orderType.contains("大") || orderType.contains("小")) { + return "HOU_COUNT"; + } + else if (orderType.contains("独赢")) { + return "HM_COUNT"; + } + else if (orderType.contains("单") || orderType.contains("双")) { + return "HEO_COUNT"; + } + else { + return "H_COUNT"; // 默认上半场 + } + } + + // 下半场相关 + if (orderType.contains("下半场")) { + if (orderType.contains("让球")) { + return "SR_COUNT"; + } + else if (orderType.contains("大") || orderType.contains("小")) { + return "SOU_COUNT"; + } + else if (orderType.contains("独赢")) { + return "SM_COUNT"; + } + else if (orderType.contains("单") || orderType.contains("双")) { + return "SEO_COUNT"; + } + else { + return "S_COUNT"; // 默认下半场 + } + } + + // 滚球相关 + if (orderType.contains("滚球")) { + if (orderType.contains("让球")) { + return "RE_COUNT"; + } + else if (orderType.contains("大") || orderType.contains("小")) { + return "ROU_COUNT"; + } + else if (orderType.contains("独赢")) { + return "RM_COUNT"; + } + else if (orderType.contains("单") || orderType.contains("双")) { + return "REO_COUNT"; + } + else { + return "R_COUNT"; // 默认滚球 + } + } + + qDebug() << "[警告] 未知的盘口类型:" << orderType; + return ""; + } + + static QString getModelForOrderType(const QString& orderType) + { + // 让球/受让 + if (orderType == "让球" || orderType == "受让") { + return "R"; + } + + // 大小 + else if (orderType == "大" || orderType == "小") { + return "OU"; + } + + // 独赢 + else if (orderType == "独赢主" || orderType == "独赢客" || orderType == "独赢和") { + return "M"; + } + + // 单双 + else if (orderType == "单" || orderType == "双") { + return "EO"; + } + + // 角球相关 + else if (orderType.contains("角球")) { + if (orderType.contains("让球")) { + return "RN"; // 角球让球 + } + else if (orderType.contains("大") || orderType.contains("小")) { + return "CN"; // 角球大小 + } + else if (orderType.contains("独赢")) { + return "CM"; // 角球独赢 + } + else if (orderType.contains("单") || orderType.contains("双")) { + return "CEO"; // 角球单双 + } + else { + return "CN"; // 默认角球盘 + } + } + + // 波胆 + else if (orderType.contains("波胆") || orderType.contains("正确比分")) { + return "PD"; + } + + // 总进球 + else if (orderType.contains("总进球") || orderType.contains("进球数")) { + return "TQ"; + } + + // 加时 + else if (orderType.contains("加时")) { + if (orderType.contains("让球")) return "RET"; + else if (orderType.contains("大小")) return "OUET"; + else if (orderType.contains("独赢")) return "MET"; + else if (orderType.contains("单双")) return "EOET"; + else return "ET"; + } + + // 点球 + else if (orderType.contains("点球")) { + if (orderType.contains("让球")) return "RPK"; + else if (orderType.contains("大小")) return "OUPK"; + else if (orderType.contains("独赢")) return "MPK"; + else if (orderType.contains("单双")) return "EOPK"; + else return "PK"; + } + + // 球队大小 + else if (orderType == "主队大" || orderType == "主队小" || + orderType == "客队大" || orderType == "客队小") { + return "OU"; // 球队大小归类到OU + } + + // 双方进球 + else if (orderType.contains("双方进球") || orderType.contains("双方球队进球")) { + return "TS"; + } + + // 下个进球/首个进球/最后进球 + else if (orderType.contains("下个进球") || orderType.contains("首个进球") || + orderType.contains("最后进球") || orderType.contains("进球")) { + return "RG"; + } + + // 罚牌相关 + else if (orderType.contains("罚牌") || orderType.contains("红牌") || + orderType.contains("黄牌") || orderType.contains("卡牌")) { + return "CARD"; + } + + // 晋级相关 + else if (orderType.contains("晋级") || orderType.contains("资格")) { + return "QUALIFY"; + } + + // 冠军相关 + else if (orderType.contains("冠军") || orderType.contains("夺冠")) { + return "CHAMPION"; + } + + // 特殊玩法 + else if (orderType.contains("特殊") || orderType.contains("其他")) { + return "SFS"; + } + + // 上半场相关 + else if (orderType.contains("上半场")) { + if (orderType.contains("让球")) return "HR"; + else if (orderType.contains("大小")) return "HOU"; + else if (orderType.contains("独赢")) return "HM"; + else if (orderType.contains("单双")) return "HEO"; + else if (orderType.contains("角球")) { + if (orderType.contains("让球")) return "HRN"; + else if (orderType.contains("大小")) return "HCN"; + else if (orderType.contains("独赢")) return "HCM"; + else return "HCN"; + } + else return "H"; // 通用上半场 + } + + // 下半场相关 + else if (orderType.contains("下半场")) { + if (orderType.contains("让球")) return "R2"; + else if (orderType.contains("大小")) return "OU2"; + else if (orderType.contains("独赢")) return "M2"; + else if (orderType.contains("单双")) return "EO2"; + else if (orderType.contains("角球")) { + if (orderType.contains("让球")) return "RN2"; + else if (orderType.contains("大小")) return "CN2"; + else if (orderType.contains("独赢")) return "CM2"; + else return "CN2"; + } + else return "2H"; // 通用下半场 + } + + // 滚球相关 + else if (orderType.contains("滚球")) { + if (orderType.contains("让球")) return "RE"; + else if (orderType.contains("大小")) return "ROU"; + else if (orderType.contains("独赢")) return "RM"; + else if (orderType.contains("单双")) return "REO"; + else if (orderType.contains("角球")) { + if (orderType.contains("让球")) return "RRN"; + else if (orderType.contains("大小")) return "RCN"; + else if (orderType.contains("独赢")) return "RCM"; + else return "RCN"; + } + else return "RB"; // 通用滚球 + } + + // 分节相关(篮球等) + else if (orderType.contains("第一节") || orderType.contains("第二节") || + orderType.contains("第三节") || orderType.contains("第四节") || + orderType.contains("Q1") || orderType.contains("Q2") || + orderType.contains("Q3") || orderType.contains("Q4")) { + if (orderType.contains("让球")) return "Q1R"; // 第一节让球 + else if (orderType.contains("大小")) return "Q1OU"; // 第一节大小 + else if (orderType.contains("独赢")) return "Q1M"; // 第一节独赢 + else if (orderType.contains("单双")) return "Q1EO"; // 第一节单双 + else return "Q1"; // 通用第一节 + } + + // 默认情况 + else { + qDebug() << "[警告] 未知的盘口类型:" << orderType; + return ""; // 返回空字符串表示不支持 + } + } + + + static QString get_rtypename(QMap order) + { + if (order["GT"].contains("篮球")) + { + if (order["SESSION"] == "早盘") + { + return "篮球早盘全部"; + } + if (order["SESSION"] == "今日") + { + return "篮球今日全部"; + } + if (order["SESSION"] == "滚球") + { + return "篮球滚球全部"; + } + } + + if (order["GT"] == "足球") + { + return order["GT"] + order["SESSION"] + order["STAGE"]; + } + return ""; + } + // 繁体转简体 + static QString traditionalToSimplified(const QString& traditional) { + if (traditional.isEmpty()) { + return traditional; + } + + // 将 QString 转换为 wchar_t 数组 + int length = traditional.length(); + wchar_t* inputBuffer = new wchar_t[length + 1]; + traditional.toWCharArray(inputBuffer); + inputBuffer[length] = L'\0'; + + wchar_t* outputBuffer = new wchar_t[length + 1]; + + // 使用 LCMapString 进行简繁转换 + int result = LCMapStringW( + LOCALE_SYSTEM_DEFAULT, // 系统区域设置 + LCMAP_SIMPLIFIED_CHINESE, // 简体中文映射 + inputBuffer, // 输入字符串 + length, // 输入长度 + outputBuffer, // 输出缓冲区 + length // 输出缓冲区大小 + ); + + QString simplified; + if (result > 0) { + outputBuffer[result] = L'\0'; + simplified = QString::fromWCharArray(outputBuffer, result); + } + else { + // 如果转换失败,返回原字符串 + simplified = traditional; + } + + delete[] inputBuffer; + delete[] outputBuffer; + return simplified; + } + + // 标准化URL:保留主机名(包括子域名),移除路径和参数 + static QString normalizeUrl(const QString& url, const QString& defaultUrl = "") + { + // 为空则返回默认值 + if (url.isEmpty()) { + return defaultUrl; + } + + // 去除空格 + QString trimmedUrl = url.trimmed(); + QUrl qurl(trimmedUrl); + + // 如果URL无效或缺少协议,尝试添加https:// + if (!qurl.isValid() || qurl.scheme().isEmpty()) { + qurl = QUrl("https://" + trimmedUrl); + } + + // 如果仍然无效,返回默认值 + if (!qurl.isValid() || qurl.host().isEmpty()) { + return defaultUrl; + } + + // 获取主机名(保留www等子域名) + QString host = qurl.host(); + + // 构建标准化URL + QString scheme = (qurl.scheme() == "http") ? "http" : "https"; + return scheme + "://" + host + "/"; + } + + + + /* + * 函数:switchConRtype + * 目的: + * 将前端内部使用的 rtype(玩法/赔率短码)映射为数据对象中实际使用的 ratio 字段名。 + * 对应前端文件 `game_more_page.txt` 中的 JavaScript 实现:_self.switchConRtype。 + * + * 使用场景: + * JSON/XML 解析时用到 -- 前端在读取比率时会先调用该映射得到类似 "ratio_ouo" 的键再去取值。 + * + * 参数: + * - rtype: 要转换的玩法短码(例如 "ouc", "ouh", "rouc", "reh" 等),函数内部会转换为小写处理。 + * - isOutside: 字符串标志(前端用 "Y" 表示外部),当 isOutside == "Y" 或 gtype != "ft" 时使用外部映射分支。 + * - gtype: 比赛类别(如 "ft" 表示足球),用于区分 ft 与非-ft 的差异映射。 + * + * 返回值: + * 返回映射后的字段名(通常为小写的 "ratio_xxx"),若映射表中不存在该 rtype,则返回原始 rtype(小写)。 + * + * 注意: + * - 前端在最终使用时通常会把结果再做 .toUpperCase(),C++ 返回小写以便与前端行为一致(调用处按需转换)。 + * - 建议将长映射表做成 static const(只初始化一次),避免每次调用都构造映射表。 + * - 映射表内容严格来自前端实现,若后端命名变化请同步更新该表以保证解析一致性。 + * + * 返回示例: + * switchConRtype("ouc", "Y", "ft") -> "ratio_ouo" + * switchConRtype("ouc", "N", "ft") -> "ratio_o" + * switchConRtype("rouh", "N", "ft") -> "ratio_rouu" + * switchConRtype("unknown", "N", "ft") -> "unknown" (未匹配时返回原值) + */ + static QString switchConRtype(QString rtype, const QString &isOutside, const QString >ype) + { + // 统一使用小写处理,和前端 JS 的 rtype.toLowerCase() 行为一致 + rtype = rtype.toLower(); + + // 规范 gtype:若调用时传空字符串,则视为 "ft"(与前端默认行为保持一致) + QString _gtype = gtype.isEmpty() ? "ft" : gtype.toLower(); + + // 注意:为了代码可读性这里直接构造 QHash。 + // 为了性能可以把下面整个表做成 static const QHash 并只初始化一次。 + QHash hash; + + // ---------- 根据 isOutside 或 gtype 选择 ft / 非-ft 的初始映射 ---------- + // 前端逻辑:若 isOutside == "Y" 或 gtype != "ft",使用“外部/非 ft”的映射分支 + if (isOutside == "Y" || _gtype !="ft") { + // 外部/非-ft 分支(部分短码指向 ratio_ouo/ratio_ouu 等) + hash.insert("ouc", "ratio_ouo"); + hash.insert("ouh", "ratio_ouu"); + hash.insert("houc", "ratio_houo"); + hash.insert("houh", "ratio_houu"); + hash.insert("rh", "ratio_r"); + hash.insert("rc", "ratio_r"); + hash.insert("prh", "ratio_r"); + hash.insert("prc", "ratio_r"); + hash.insert("pouc", "ratio_ouo"); + hash.insert("pouh", "ratio_ouu"); + hash.insert("hrh", "ratio_hr"); + hash.insert("hrc", "ratio_hr"); + hash.insert("hprh", "ratio_hr"); + hash.insert("hprc", "ratio_hr"); + hash.insert("hpouc", "ratio_houo"); + hash.insert("hpouh", "ratio_houu"); + } + else { + // ft 内部分支(某些短码映射为 ratio_o/ratio_u/hratio 等) + hash.insert("ouc", "ratio_o"); + hash.insert("ouh", "ratio_u"); + hash.insert("houc", "ratio_ho"); + hash.insert("houh", "ratio_hu"); + hash.insert("rh", "ratio"); + hash.insert("rc", "ratio"); + hash.insert("prh", "ratio"); + hash.insert("prc", "ratio"); + hash.insert("pouc", "ratio_o"); + hash.insert("pouh", "ratio_u"); + hash.insert("hrh", "hratio"); + hash.insert("hrc", "hratio"); + hash.insert("hprh", "hratio"); + hash.insert("hprc", "hratio"); + hash.insert("hpouc", "ratio_ho"); + hash.insert("hpouh", "ratio_hu"); + } + + // ---------- 通用映射表 ------------ + // 以下映射项来自前端 `game_more_page.txt` 中的完整表(已逐项移植) + // 如果后端新增/改名,需要在此同步更新。 + hash.insert("rouc", "ratio_rouo"); + hash.insert("rouh", "ratio_rouu"); + hash.insert("hrouc", "ratio_hrouo"); + hash.insert("hrouh", "ratio_hrouu"); + hash.insert("reh", "ratio_re"); + hash.insert("rec", "ratio_re"); + hash.insert("hreh", "ratio_hre"); + hash.insert("hrec", "ratio_hre"); + hash.insert("arh", "ratio_ar"); + hash.insert("arc", "ratio_ar"); + hash.insert("brh", "ratio_br"); + hash.insert("brc", "ratio_br"); + hash.insert("crh", "ratio_cr"); + hash.insert("crc", "ratio_cr"); + hash.insert("drh", "ratio_dr"); + hash.insert("drc", "ratio_dr"); + hash.insert("erh", "ratio_er"); + hash.insert("erc", "ratio_er"); + hash.insert("frh", "ratio_fr"); + hash.insert("frc", "ratio_fr"); + + hash.insert("aouo", "ratio_aouo"); + hash.insert("aouu", "ratio_aouu"); + hash.insert("bouo", "ratio_bouo"); + hash.insert("bouu", "ratio_bouu"); + hash.insert("couo", "ratio_couo"); + hash.insert("couu", "ratio_couu"); + hash.insert("douo", "ratio_douo"); + hash.insert("douu", "ratio_douu"); + hash.insert("eouo", "ratio_eouo"); + hash.insert("eouu", "ratio_eouu"); + hash.insert("fouo", "ratio_fouo"); + hash.insert("fouu", "ratio_fouu"); + + hash.insert("parh", "ratio_ar"); + hash.insert("parc", "ratio_ar"); + hash.insert("pbrh", "ratio_br"); + hash.insert("pbrc", "ratio_br"); + hash.insert("pcrh", "ratio_cr"); + hash.insert("pcrc", "ratio_cr"); + hash.insert("pdrh", "ratio_dr"); + hash.insert("pdrc", "ratio_dr"); + hash.insert("perh", "ratio_er"); + hash.insert("perc", "ratio_er"); + hash.insert("pfrh", "ratio_fr"); + hash.insert("pfrc", "ratio_fr"); + + hash.insert("paouo", "ratio_aouo"); + hash.insert("paouu", "ratio_aouu"); + hash.insert("pbouo", "ratio_bouo"); + hash.insert("pbouu", "ratio_bouu"); + hash.insert("pcouo", "ratio_couo"); + hash.insert("pcouu", "ratio_couu"); + hash.insert("pdouo", "ratio_douo"); + hash.insert("pdouu", "ratio_douu"); + hash.insert("peouo", "ratio_eouo"); + hash.insert("peouu", "ratio_eouu"); + hash.insert("pfouo", "ratio_fouo"); + hash.insert("pfouu", "ratio_fouu"); + + hash.insert("rouho", "ratio_rouho"); + hash.insert("rouhu", "ratio_rouhu"); + hash.insert("rouco", "ratio_rouco"); + hash.insert("roucu", "ratio_roucu"); + hash.insert("hruho", "ratio_hruho"); + hash.insert("hruhu", "ratio_hruhu"); + hash.insert("hruco", "ratio_hruco"); + hash.insert("hrucu", "ratio_hrucu"); + + hash.insert("ouho", "ratio_ouho"); + hash.insert("ouhu", "ratio_ouhu"); + hash.insert("ouco", "ratio_ouco"); + hash.insert("oucu", "ratio_oucu"); + hash.insert("houho", "ratio_houho"); + hash.insert("houhu", "ratio_houhu"); + hash.insert("houco", "ratio_houco"); + hash.insert("houcu", "ratio_houcu"); + + hash.insert("w3h", "ratio_w3h"); + hash.insert("w3c", "ratio_w3c"); + hash.insert("w3n", "ratio_w3n"); + + hash.insert("areh", "ratio_are"); + hash.insert("arec", "ratio_are"); + hash.insert("breh", "ratio_bre"); + hash.insert("brec", "ratio_bre"); + hash.insert("creh", "ratio_cre"); + hash.insert("crec", "ratio_cre"); + hash.insert("dreh", "ratio_dre"); + hash.insert("drec", "ratio_dre"); + hash.insert("ereh", "ratio_ere"); + hash.insert("erec", "ratio_ere"); + hash.insert("freh", "ratio_fre"); + hash.insert("frec", "ratio_fre"); + + hash.insert("arouo", "ratio_arouo"); + hash.insert("arouu", "ratio_arouu"); + hash.insert("brouo", "ratio_brouo"); + hash.insert("brouu", "ratio_brouu"); + hash.insert("crouo", "ratio_crouo"); + hash.insert("crouu", "ratio_crouu"); + hash.insert("drouo", "ratio_drouo"); + hash.insert("drouu", "ratio_drouu"); + hash.insert("erouo", "ratio_erouo"); + hash.insert("erouu", "ratio_erouu"); + hash.insert("frouo", "ratio_frouo"); + hash.insert("frouu", "ratio_frouu"); + + hash.insert("pouho", "ratio_ouho"); + hash.insert("pouhu", "ratio_ouhu"); + hash.insert("pouco", "ratio_ouco"); + hash.insert("poucu", "ratio_oucu"); + hash.insert("hpouho", "ratio_houho"); + hash.insert("hpouhu", "ratio_houhu"); + hash.insert("hpouco", "ratio_houco"); + hash.insert("hpoucu", "ratio_houcu"); + + hash.insert("taruo", "ratio_taruo"); + hash.insert("taruu", "ratio_taruu"); + hash.insert("tbruo", "ratio_tbruo"); + hash.insert("tbruu", "ratio_tbruu"); + hash.insert("tdruo", "ratio_tdruo"); + hash.insert("tdruu", "ratio_tdruu"); + hash.insert("teruo", "ratio_teruo"); + hash.insert("teruu", "ratio_teruu"); + + hash.insert("prouc", "ratio_rouo"); + hash.insert("prouh", "ratio_rouu"); + hash.insert("hprouc", "ratio_hrouo"); + hash.insert("hprouh", "ratio_hrouu"); + + hash.insert("preh", "ratio_re"); + hash.insert("prec", "ratio_re"); + hash.insert("hpreh", "ratio_hre"); + hash.insert("hprec", "ratio_hre"); + + hash.insert("pareh", "ratio_are"); + hash.insert("parec", "ratio_are"); + hash.insert("pbreh", "ratio_bre"); + hash.insert("pbrec", "ratio_bre"); + hash.insert("pcreh", "ratio_cre"); + hash.insert("pcrec", "ratio_cre"); + hash.insert("pdreh", "ratio_dre"); + hash.insert("pdrec", "ratio_dre"); + hash.insert("pereh", "ratio_ere"); + hash.insert("perec", "ratio_ere"); + hash.insert("pfreh", "ratio_fre"); + hash.insert("pfrec", "ratio_fre"); + + hash.insert("parouo", "ratio_arouo"); + hash.insert("parouu", "ratio_arouu"); + hash.insert("pbrouo", "ratio_brouo"); + hash.insert("pbrouu", "ratio_brouu"); + hash.insert("pcrouo", "ratio_crouo"); + hash.insert("pcrouu", "ratio_crouu"); + hash.insert("pdrouo", "ratio_drouo"); + hash.insert("pdrouu", "ratio_drouu"); + + hash.insert("perouo", "ratio_erouo"); + hash.insert("perouu", "ratio_erouu"); + hash.insert("pfrouo", "ratio_frouo"); + hash.insert("pfrouu", "ratio_frouu"); + + hash.insert("prouho", "ratio_rouho"); + hash.insert("prouhu", "ratio_rouhu"); + hash.insert("prouco", "ratio_rouco"); + hash.insert("proucu", "ratio_roucu"); + + hash.insert("hpruho", "ratio_hruho"); + hash.insert("hpruhu", "ratio_hruhu"); + hash.insert("hpruco", "ratio_hruco"); + hash.insert("hprucu", "ratio_hrucu"); + + hash.insert("ptaruo", "ratio_taruo"); + hash.insert("ptaruu", "ratio_taruu"); + hash.insert("ptbruo", "ratio_tbruo"); + hash.insert("ptbruu", "ratio_tbruu"); + hash.insert("ptdruo", "ratio_tdruo"); + hash.insert("ptdruu", "ratio_tdruu"); + + hash.insert("pteruo", "ratio_teruo"); + hash.insert("pteruu", "ratio_teruu"); + + // 若 hash 中存在对应的映射,返回映射值;否则返回原始 rtype(小写) + return hash.value(rtype, rtype); + } + + + static QString rtypeToRATIO(const QString &rtype, const QString >ype) + { + QString rtypeLower = rtype.toLower(); + QString _gtype = gtype.isEmpty() ? "ft" : gtype.toLower(); + + QMap hash; + + if (_gtype != "ft") { + hash["ouc"] = "ratio_ouo"; + hash["ouh"] = "ratio_ouu"; + hash["houc"] = "ratio_houo"; + hash["houh"] = "ratio_houu"; + hash["rh"] = "ratio_r"; + hash["rc"] = "ratio_r"; + hash["prh"] = "ratio_r"; + hash["prc"] = "ratio_r"; + hash["pouc"] = "ratio_ouo"; + hash["pouh"] = "ratio_ouu"; + hash["hrh"] = "ratio_hr"; + hash["hrc"] = "ratio_hr"; + hash["hprh"] = "ratio_hr"; + hash["hprc"] = "ratio_hr"; + hash["hpouc"] = "ratio_houo"; + hash["hpouh"] = "ratio_houu"; + } + else { + hash["ouc"] = "ratio_o"; + hash["ouh"] = "ratio_u"; + hash["houc"] = "ratio_ho"; + hash["houh"] = "ratio_hu"; + hash["rh"] = "ratio"; + hash["rc"] = "ratio"; + hash["prh"] = "ratio"; + hash["prc"] = "ratio"; + hash["pouc"] = "ratio_o"; + hash["pouh"] = "ratio_u"; + hash["hrh"] = "hratio"; + hash["hrc"] = "hratio"; + hash["hprh"] = "hratio"; + hash["hprc"] = "hratio"; + hash["hpouc"] = "ratio_ho"; + hash["hpouh"] = "ratio_hu"; + } + + hash["rouc"] = "ratio_rouo"; + hash["rouh"] = "ratio_rouu"; + hash["hrouc"] = "ratio_hrouo"; + hash["hrouh"] = "ratio_hrouu"; + hash["reh"] = "ratio_re"; + hash["rec"] = "ratio_re"; + hash["hreh"] = "ratio_hre"; + hash["hrec"] = "ratio_hre"; + hash["arh"] = "ratio_ar"; + hash["arc"] = "ratio_ar"; + hash["brh"] = "ratio_br"; + hash["brc"] = "ratio_br"; + hash["crh"] = "ratio_cr"; + hash["crc"] = "ratio_cr"; + hash["drh"] = "ratio_dr"; + hash["drc"] = "ratio_dr"; + hash["erh"] = "ratio_er"; + hash["erc"] = "ratio_er"; + hash["frh"] = "ratio_fr"; + hash["frc"] = "ratio_fr"; + hash["aouo"] = "ratio_aouo"; + hash["aouu"] = "ratio_aouu"; + hash["bouo"] = "ratio_bouo"; + hash["bouu"] = "ratio_bouu"; + hash["couo"] = "ratio_couo"; + hash["couu"] = "ratio_couu"; + hash["douo"] = "ratio_douo"; + hash["douu"] = "ratio_douu"; + hash["eouo"] = "ratio_eouo"; + hash["eouu"] = "ratio_eouu"; + hash["fouo"] = "ratio_fouo"; + hash["fouu"] = "ratio_fouu"; + hash["parh"] = "ratio_ar"; + hash["parc"] = "ratio_ar"; + hash["pbrh"] = "ratio_br"; + hash["pbrc"] = "ratio_br"; + hash["pcrh"] = "ratio_cr"; + hash["pcrc"] = "ratio_cr"; + hash["pdrh"] = "ratio_dr"; + hash["pdrc"] = "ratio_dr"; + hash["perh"] = "ratio_er"; + hash["perc"] = "ratio_er"; + hash["pfrh"] = "ratio_fr"; + hash["pfrc"] = "ratio_fr"; + hash["paouo"] = "ratio_aouo"; + hash["paouu"] = "ratio_aouu"; + hash["pbouo"] = "ratio_bouo"; + hash["pbouu"] = "ratio_bouu"; + hash["pcouo"] = "ratio_couo"; + hash["pcouu"] = "ratio_couu"; + hash["pdouo"] = "ratio_douo"; + hash["pdouu"] = "ratio_douu"; + hash["peouo"] = "ratio_eouo"; + hash["peouu"] = "ratio_eouu"; + hash["pfouo"] = "ratio_fouo"; + hash["pfouu"] = "ratio_fouu"; + hash["rouho"] = "ratio_rouho"; + hash["rouhu"] = "ratio_rouhu"; + hash["rouco"] = "ratio_rouco"; + hash["roucu"] = "ratio_roucu"; + hash["hruho"] = "ratio_hruho"; + hash["hruhu"] = "ratio_hruhu"; + hash["hruco"] = "ratio_hruco"; + hash["hrucu"] = "ratio_hrucu"; + hash["ouho"] = "ratio_ouho"; + hash["ouhu"] = "ratio_ouhu"; + hash["ouco"] = "ratio_ouco"; + hash["oucu"] = "ratio_oucu"; + hash["houho"] = "ratio_houho"; + hash["houhu"] = "ratio_houhu"; + hash["houco"] = "ratio_houco"; + hash["houcu"] = "ratio_houcu"; + hash["w3h"] = "ratio_w3h"; + hash["w3c"] = "ratio_w3c"; + hash["w3n"] = "ratio_w3n"; + hash["areh"] = "ratio_are"; + hash["arec"] = "ratio_are"; + hash["breh"] = "ratio_bre"; + hash["brec"] = "ratio_bre"; + hash["creh"] = "ratio_cre"; + hash["crec"] = "ratio_cre"; + hash["dreh"] = "ratio_dre"; + hash["drec"] = "ratio_dre"; + hash["ereh"] = "ratio_ere"; + hash["erec"] = "ratio_ere"; + hash["freh"] = "ratio_fre"; + hash["frec"] = "ratio_fre"; + hash["arouo"] = "ratio_arouo"; + hash["arouu"] = "ratio_arouu"; + hash["brouo"] = "ratio_brouo"; + hash["brouu"] = "ratio_brouu"; + hash["crouo"] = "ratio_crouo"; + hash["crouu"] = "ratio_crouu"; + hash["drouo"] = "ratio_drouo"; + hash["drouu"] = "ratio_drouu"; + hash["erouo"] = "ratio_erouo"; + hash["erouu"] = "ratio_erouu"; + hash["frouo"] = "ratio_frouo"; + hash["frouu"] = "ratio_frouu"; + hash["pouho"] = "ratio_ouho"; + hash["pouhu"] = "ratio_ouhu"; + hash["pouco"] = "ratio_ouco"; + hash["poucu"] = "ratio_oucu"; + hash["hpouho"] = "ratio_houho"; + hash["hpouhu"] = "ratio_houhu"; + hash["hpouco"] = "ratio_houco"; + hash["hpoucu"] = "ratio_houcu"; + hash["taruo"] = "ratio_taruo"; + hash["taruu"] = "ratio_taruu"; + hash["tbruo"] = "ratio_tbruo"; + hash["tbruu"] = "ratio_tbruu"; + hash["tdruo"] = "ratio_tdruo"; + hash["tdruu"] = "ratio_tdruu"; + hash["teruo"] = "ratio_teruo"; + hash["teruu"] = "ratio_teruu"; + hash["prouc"] = "ratio_rouo"; + hash["prouh"] = "ratio_rouu"; + hash["hprouc"] = "ratio_hrouo"; + hash["hprouh"] = "ratio_hrouu"; + hash["preh"] = "ratio_re"; + hash["prec"] = "ratio_re"; + hash["hpreh"] = "ratio_hre"; + hash["hprec"] = "ratio_hre"; + hash["pareh"] = "ratio_are"; + hash["parec"] = "ratio_are"; + hash["pbreh"] = "ratio_bre"; + hash["pbrec"] = "ratio_bre"; + hash["pcreh"] = "ratio_cre"; + hash["pcrec"] = "ratio_cre"; + hash["pdreh"] = "ratio_dre"; + hash["pdrec"] = "ratio_dre"; + hash["pereh"] = "ratio_ere"; + hash["perec"] = "ratio_ere"; + hash["pfreh"] = "ratio_fre"; + hash["pfrec"] = "ratio_fre"; + hash["parouo"] = "ratio_arouo"; + hash["parouu"] = "ratio_arouu"; + hash["pbrouo"] = "ratio_brouo"; + hash["pbrouu"] = "ratio_brouu"; + hash["pcrouo"] = "ratio_crouo"; + hash["pcrouu"] = "ratio_crouu"; + hash["pdrouo"] = "ratio_drouo"; + hash["pdrouu"] = "ratio_drouu"; + hash["perouo"] = "ratio_erouo"; + hash["perouu"] = "ratio_erouu"; + hash["pfrouo"] = "ratio_frouo"; + hash["pfrouu"] = "ratio_frouu"; + hash["prouho"] = "ratio_rouho"; + hash["prouhu"] = "ratio_rouhu"; + hash["prouco"] = "ratio_rouco"; + hash["proucu"] = "ratio_roucu"; + hash["hpruho"] = "ratio_hruho"; + hash["hpruhu"] = "ratio_hruhu"; + hash["hpruco"] = "ratio_hruco"; + hash["hprucu"] = "ratio_hrucu"; + hash["ptaruo"] = "ratio_taruo"; + hash["ptaruu"] = "ratio_taruu"; + hash["ptbruo"] = "ratio_tbruo"; + hash["ptbruu"] = "ratio_tbruu"; + hash["ptdruo"] = "ratio_tdruo"; + hash["ptdruu"] = "ratio_tdruu"; + + if (hash.contains(rtypeLower)) { + return hash[rtypeLower].toUpper(); + } + + return QString(); + } + + +}; \ No newline at end of file diff --git a/CrownClient/Verify.cpp b/CrownClient/Verify.cpp new file mode 100644 index 0000000..3fbabeb --- /dev/null +++ b/CrownClient/Verify.cpp @@ -0,0 +1,609 @@ +#include "Verify.h" +#include "Global.h" + + +/// +/// 构造函数 +/// +/// +/// +/// +/// +Verify::Verify(QString Url, QString AppId, QString CommKey, QString Verison) +{ + VMProtectBegin("Verify_Init"); + + // 获取随机Key + this->m_randomeKey = this->GetRandom(32); + + m_appId = this->ParamEncrypt(AppId); + m_commKey = this->ParamEncrypt(CommKey); + m_webApi = this->ParamEncrypt(Url + "/api_new.php?"); + m_machineCode = this->GetCPUID(); + m_version = Verison; + + //qDebug() << "验证网址:" << Url; + //qDebug() << "软件ID:" << AppId; + //qDebug() << "通信密钥:" << CommKey; + //qDebug() << "软件版本:" << Verison; + //qDebug() << "机器码:" << this->GetCPUID(); + VMProtectEnd(); +} + +Verify::~Verify() +{ + +} + + +// 获取计算机的CPU的ID +QString Verify::GetCPUID() +{ + QString strCpuId = ""; + unsigned int dwBuf[4] = { 0 }; + unsigned long long ret = 0; + + __cpuid((int*)(void*)dwBuf, 1); + + ret = dwBuf[3]; + ret = ret << 32; + + QString str0 = QString::number(dwBuf[3], 16).toUpper(); + QString str0_1 = str0.rightJustified(8, '0'); + QString str1 = QString::number(dwBuf[0], 16).toUpper(); + QString str1_1 = str1.rightJustified(8, '0'); + strCpuId = str0_1 + str1_1; + + return strCpuId; +} + +// 取随机文本 +QString Verify::GetRandom(int Length) +{ + srand(QDateTime::currentMSecsSinceEpoch()); + QString String; + const char ch[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + int index = 0; + for (int i = 0; i < Length; ++i) + { + index = rand() % strlen(ch); + String += ch[index]; + } + return String; +} + +// 取随机数 +int Verify::GetRandom(int Min, int Max) +{ + srand(QTime(0, 0, 0).secsTo(QTime::currentTime())); + int Random = rand(); + int Number = Random % (Max - Min + 1) + Min; + return Number; +} + +// 计算CRC32 +unsigned int Verify::Crc32(const void* Buffer, unsigned short Length) +{ + + int i, j; + unsigned int CRC32; + + CRC32 = 0xFFFFFFFF; + for (i = 0; i < Length; i++) + { + for (j = 0; j < 8; j++) + { + if (CRC32 & 1) { + CRC32 = (CRC32 >> 1) ^ 0xEDB88320; + } + else + { + CRC32 = (CRC32 >> 1); + } + if (((unsigned char*)Buffer)[i] & (1 << j)) + { + CRC32 ^= 0xEDB88320; + } + } + } + CRC32 = ~CRC32; + return (CRC32); +} + +// RC4加密 +QByteArray Verify::RC4(QByteArray Data, QString Key) +{ + QByteArray m, k, result; + m.resize(256); + k.resize(256); + result.resize(Data.length()); + if (Data.length() < 1) + { + return ""; + } + for (int i = 0; i < 256; i++) + { + m[i] = i; + } + + if (Key.length() > 0) + { + int j = 0; + for (int i = 0; i < 256; i++) + { + k[i] = Key.toUtf8()[j]; + j++; + if (j > Key.length() - 1) + { + j = 0; + } + } + j = 0; + for (int i = 0; i < 256; i++) + { + j = (j + m[i] + k[i]) & 255; + char temp = m[i]; + m[i] = m[j]; + m[j] = temp; + } + } + int i = 0, j = 0; + for (int x = 0; x < Data.length(); x++) + { + i = (i + 1) & 255; + j = (j + m[i]) & 255; + + char temp = m[i]; + m[i] = m[j]; + m[j] = temp; + result[x] = Data[x] ^ m[(m[i] + m[j]) & 255]; + } + //qDebug() << "RC4:" << result.toHex(); + return result; +} + +// 获取MD5 +QString Verify::Md5(QByteArray Data) +{ + QCryptographicHash hash(QCryptographicHash::Md5); + hash.addData(Data); + QString md5 = hash.result().toHex(); + return md5; +} + +QString Verify::ParamEncrypt(QString Param) +{ + VMProtectBegin("Verify_Enc"); + if (Param.isEmpty()) + { + return ""; + } + // 转为字节数组 + QByteArray paramByteArray = Param.toUtf8(); + // 根据字节数组指针计算CRC32 + unsigned int ParamCrc32 = this->Crc32(paramByteArray.data(), Param.size()); + // 参数 + CRC32 + paramByteArray.append(((char*)&ParamCrc32)[0]); + paramByteArray.append(((char*)&ParamCrc32)[1]); + paramByteArray.append(((char*)&ParamCrc32)[2]); + paramByteArray.append(((char*)&ParamCrc32)[3]); + + int Key = this->GetRandom(1, 65535); + QByteArray keyByteArray; + keyByteArray.append(((char*)&Key)[0]); + keyByteArray.append(((char*)&Key)[1]); + keyByteArray.append(((char*)&Key)[2]); + keyByteArray.append(((char*)&Key)[3]); + + int passwordCRC32 = this->Crc32(m_randomeKey.toUtf8().data(), m_randomeKey.size()); + keyByteArray.append(((char*)&passwordCRC32)[0]); + keyByteArray.append(((char*)&passwordCRC32)[1]); + keyByteArray.append(((char*)&passwordCRC32)[2]); + keyByteArray.append(((char*)&passwordCRC32)[3]); + + // MD5加密 + QCryptographicHash hash(QCryptographicHash::Md5); + hash.addData(keyByteArray); + // 转换为十六进制字符串 + QString md5 = hash.result().toHex(); + int offset = 0; + for (int i = 0; i < paramByteArray.length(); i++) + { + // 防止数组越界 + if (offset > md5.length() - 1) + { + offset = 0; + } + + int location = md5.mid(offset, 1).toInt(nullptr, 16) + 4; + offset++; + if (location > paramByteArray.length() - 1) + { + continue; + } + char TempA = paramByteArray[paramByteArray.size() - 1 - i]; + char TempB = paramByteArray[location]; + paramByteArray[paramByteArray.size() - 1 - i] = TempB; + paramByteArray[location] = TempA; + } + paramByteArray += ((char*)&offset)[0]; + paramByteArray += ((char*)&offset)[1]; + paramByteArray += ((char*)&Key)[0]; + paramByteArray += ((char*)&Key)[1]; + paramByteArray += ((char*)&Key)[2]; + + // XOR + for (unsigned int i = 0; i < paramByteArray.length(); i++) + { + paramByteArray[i] = paramByteArray[i] ^ ((char*)&Key)[3]; + } + paramByteArray.append(((char*)&Key)[3]); + + return paramByteArray.toHex(); + VMProtectEnd(); + +} + +QString Verify::ParamDecrypt(QString Param) +{ + VMProtectBegin("Verify_Dec"); + if (Param.isEmpty()) + { + return ""; + } + QByteArray paramByteArray = QByteArray::fromHex(Param.toUtf8()); + char xorKey = paramByteArray[paramByteArray.size() - 1]; + + QByteArray UnHashData = NULL; + for (unsigned int i = 0; i < paramByteArray.size() - 1; i++) + { + UnHashData += paramByteArray[i] ^ xorKey; + } + QByteArray md5ByteArray; + + // 根据字节数组指针计算CRC32 + int passwordCrc32 = this->Crc32(m_randomeKey.toUtf8().data(), m_randomeKey.size()); + // 参数 + CRC32 + md5ByteArray.append(UnHashData[UnHashData.size() - 3]); + md5ByteArray.append(UnHashData[UnHashData.size() - 2]); + md5ByteArray.append(UnHashData[UnHashData.size() - 1]); + //qDebug() << "RValue:" << md5ByteArray.toHex(); + md5ByteArray.append(xorKey); + md5ByteArray.append(((char*)&passwordCrc32)[0]); + md5ByteArray.append(((char*)&passwordCrc32)[1]); + md5ByteArray.append(((char*)&passwordCrc32)[2]); + md5ByteArray.append(((char*)&passwordCrc32)[3]); + + QCryptographicHash hash(QCryptographicHash::Md5); + hash.addData(md5ByteArray); + // 转换为十六进制字符串 + QString md5 = hash.result().toHex(); + short last; + ((char*)&last)[0] = UnHashData[UnHashData.length() - 5]; + ((char*)&last)[1] = UnHashData[UnHashData.length() - 4]; + + UnHashData = UnHashData.mid(0, UnHashData.length() - 5); + + int offset = 0; + int _last = last; + bool error = false; + for (int i = 0; i < UnHashData.length(); i++) + { + if (UnHashData.length() < _last - 1) + { + break; + } + if (offset > md5.size() - 1) + { + offset = 0; + } + if (last - offset - 1 < 0) + { + last = md5.size(); + offset = 0; + } + int location = md5.mid(last - offset - 1, 1).toInt(nullptr, 16) + 4; + offset = offset + 1; + if (location > UnHashData.size() - 1) + { + continue; + } + char TempA = UnHashData[i]; + char TempB = UnHashData[location]; + UnHashData[i] = TempB; + UnHashData[location] = TempA; + } + + int crc32; + ((char*)&crc32)[0] = UnHashData[UnHashData.length() - 4]; + ((char*)&crc32)[1] = UnHashData[UnHashData.length() - 3]; + ((char*)&crc32)[2] = UnHashData[UnHashData.length() - 2]; + ((char*)&crc32)[3] = UnHashData[UnHashData.length() - 1]; + UnHashData = UnHashData.mid(0, UnHashData.length() - 4); + if (crc32 != this->Crc32(UnHashData.data(), UnHashData.length())) + { + return ""; + } + + return UnHashData; + VMProtectEnd(); +} + + +QString ByteArrayToHexString(QByteArray data) { + QString ret(data.toHex().toUpper()); + int len = ret.length() / 2; + //qDebug() << len; + for (int i = 1; i < len; i++) + { + //qDebug() << i; + ret.insert(2 * i + i - 1, " "); + } + + return ret; +} + +// 发送网络请求 +bool Verify::Send(QString Option, QString Data, QString& Result,bool async) +{ + VMProtectBegin("Verify_Send"); + QNetworkAccessManager networkAccessManager; + // 获取当前时间戳 + QDateTime timeDate = QDateTime::currentDateTime(); + QString timestamp = QString::number(timeDate.toSecsSinceEpoch()); + //qDebug() << "解密:" << ParamDecrypt(m_commKey); + // 获取签名 + + // 转为十六进制文本 + QString PostData; + PostData.append(RC4(Data.toUtf8(), ParamDecrypt(m_commKey)).toHex()); + + //qDebug() << "RC4的结果:" << PostData; + QByteArray PostByte = PostData.toUtf8(); + //qDebug() << "RC4结果:" << PostByte.toHex(); + QByteArray SignData = PostByte + timestamp.toUtf8() + ParamDecrypt(m_commKey).toUtf8(); + // 转换为十六进制字符串 + + QString md5 = this->Md5(SignData); + // a98d0872e603bc63f04767a14617df64 + //qDebug() << "md5:" << md5; + QUrl strUrl = ParamDecrypt(m_webApi) + "&mod=" + Option + "&appId=" + this->ParamDecrypt(m_appId) + "&sign=" + md5 + "×tamp=" + timestamp; + //qDebug() << "访问地址:" << strUrl; + // 网络请求 + QNetworkRequest request; + // 设置请求地址 + request.setUrl(strUrl); + // 设置请求头 + // request.setRawHeader("Content-Type", "charset='utf-8'"); + request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");// "charset='utf-8'" + //request.setRawHeader("Content-Type", "application/json"); + // 网络应答 + + QNetworkReply* reply = networkAccessManager.post(request, PostData.toUtf8()); + QByteArray responseData; + + if (!async) + { + // 事件循环 + QEventLoop eventLoop; + // 连接信号和槽 + connect(&networkAccessManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit())); + // 开始循环 + eventLoop.exec(); + } + + + //错误处理 + if (reply->error() != QNetworkReply::NoError) + { + qDebug() << "Request protobufHttp handle errors here"; + QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); + // statusCodeV是HTTP服务器的相应码,reply->error()是Qt定义的错误码,可以参考QT的文档 + qDebug("request protobufHttp found error ....code: %d %d\n", statusCodeV.toInt(), (int)reply->error()); + qDebug(qPrintable(reply->errorString())); + reply->deleteLater(); + return ""; + } + + //RC4(QByteArray::fromHex(数据.toUtf8()), ParamDecrypt(m_commKey)); + //QString strReply = reply->readAll(); + QString result = reply->readAll();//RC4(QByteArray::fromHex(reply->readAll()),ParamDecrypt(m_commKey)); + //qDebug() << "访问结果:" << result.toStdString().c_str(); + reply->deleteLater(); + + QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); + if (jsonDocument.isNull()) + { + qDebug() << "String NULL";; + } + QJsonObject jsonObject = jsonDocument.object(); + QString jsonCode = jsonObject["code"].toVariant().toString();//QString::number(jsonObject["code"].toInt()); + QString jsonMsg = jsonObject["msg"].toVariant().toString(); + QString jsonData = jsonObject["data"].toVariant().toString(); + QString jsonSign = jsonObject["sign"].toVariant().toString(); + QString jsonTampstamp = jsonObject["timestamp"].toVariant().toString(); + + Result = RC4(QByteArray::fromHex(jsonData.toUtf8()), ParamDecrypt(m_commKey)); + if (!jsonSign.isEmpty()) + { + QString verifySign = this->Md5(jsonCode.toUtf8() + jsonMsg.toUtf8() + jsonData.toUtf8()); + if (verifySign != jsonSign) + { + Result = "数据校验失败"; + return false; + } + } + //qDebug() << "解密结果" << jsonObject["msg"].toVariant().toString();; + + if (jsonCode == "1") + { + return true; + } + + Result = jsonObject["msg"].toVariant().toString(); + return false; + VMProtectEnd(); +} + + +bool Verify::Login(QString Username, QString Password, QString& result) +{ + VMProtectBegin("Verify_Login"); + QJsonObject JsonObject; + JsonObject.insert("username", Username); + JsonObject.insert("password", Password); + JsonObject.insert("hardwareCode", m_machineCode); + QJsonDocument jsonDoc = QJsonDocument(JsonObject); + QString post_data = jsonDoc.toJson(QJsonDocument::Compact); + //qDebug() << "参数:" << post_data.toStdString().c_str(); + if (!Send("login", post_data, result)) + { + //qDebug() << "登录失败:" << result.toStdString().c_str(); + //result = "登录失败"; + return false; + } + //qDebug() << "登录成功:" << result.toStdString().c_str(); + QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); + if (jsonDocument.isNull()) + { + //qDebug() << "String NULL";; + //result = "登录失败"; + return false; + } + QJsonObject jsonObject = jsonDocument.object(); + QString jsonTime = jsonObject["expireTime"].toVariant().toString(); + m_dueTime = QDateTime::fromString(jsonTime, "yyyy-MM-dd hh:mm:ss"); + m_username = Username; + m_password = Password; + return true; + VMProtectEnd(); +} + +bool Verify::Heartbeat(QString& result) +{ + VMProtectBegin("Verify_Heartbeat"); + QJsonObject JsonObject; + JsonObject.insert("username", m_username); + JsonObject.insert("password", m_password); + JsonObject.insert("hardwareCode", m_machineCode); + QJsonDocument jsonDoc = QJsonDocument(JsonObject); + QString post_data = jsonDoc.toJson(QJsonDocument::Compact); + //qDebug() << "参数:" << post_data.toStdString().c_str(); + if (!Send("heartbeat", post_data, result)) + { + //qDebug() << "登录失败:" << result.toStdString().c_str(); + return false; + } + //qDebug() << "登录成功:" << result.toStdString().c_str(); + QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); + if (jsonDocument.isNull()) + { + //qDebug() << "String NULL";; + return false; + } + QJsonObject jsonObject = jsonDocument.object(); + QString jsonTime = jsonObject["expireTime"].toVariant().toString(); + m_dueTime = QDateTime::fromString(jsonTime, "yyyy-MM-dd hh:mm:ss"); + + return true; + VMProtectEnd(); +} + +bool Verify::checkUpdate() +{ + VMProtectBegin("Verify_Check"); + QString result; + QJsonObject JsonObject; + JsonObject.insert("username", m_username); + JsonObject.insert("password", m_password); + JsonObject.insert("hardwareCode", m_machineCode); + QJsonDocument jsonDoc = QJsonDocument(JsonObject); + QString post_data = jsonDoc.toJson(QJsonDocument::Compact); + //qDebug() << "参数:" << post_data.toStdString().c_str(); + if (!Send("version", post_data, result)) + { + //qDebug() << "获取版本失败:" << result.toStdString().c_str(); + return false; + } + //qDebug() << "获取版本成功:" << result.toStdString().c_str(); + QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); + if (jsonDocument.isNull()) + { + //qDebug() << "String NULL";; + return false; + } + QJsonObject jsonObject = jsonDocument.object(); + QString version = jsonObject["version"].toVariant().toString(); + //qDebug() << "最新版本:" << version; + if (m_version == version) + { + //qDebug() << "验证结果: 真"; + } + else + { + //qDebug() << "验证结果: 假"; + } + + return version == m_version; + VMProtectEnd(); +} + +QString Verify::Username() +{ + return m_username; +} + +QDateTime Verify::GetDueTime() +{ + return m_dueTime; +} + +bool Verify::push_msg(QString type, QString app, QString account, QMap order) +{ + VMProtectBegin("Verify_Push"); + QString result; + QJsonObject JsonObject; + JsonObject.insert("username", m_username); + JsonObject.insert("password", m_password); + JsonObject.insert("account", m_machineCode); + JsonObject.insert("type", type); + JsonObject.insert("app", app); + JsonObject.insert("account", account); + + // 修复:直接将 QMap 转换为 QJsonObject + QJsonObject orderJson; + for (auto it = order.begin(); it != order.end(); ++it) { + orderJson.insert(it.key(), it.value()); + } + JsonObject.insert("order", orderJson); + + QJsonDocument jsonDoc = QJsonDocument(JsonObject); + QString post_data = jsonDoc.toJson(QJsonDocument::Compact); + //qDebug() << "参数:" << post_data.toStdString().c_str(); + if (!Send("push", post_data, result, false)) + { + //qDebug() << "推送消息失败:" << result.toStdString().c_str(); + return false; + } + //qDebug() << "推送成功:" << result.toStdString().c_str(); + QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); + if (jsonDocument.isNull()) + { + //qDebug() << "String NULL";; + return false; + } + QJsonObject jsonObject = jsonDocument.object(); + QString version = jsonObject["version"].toVariant().toString(); + //qDebug() << "最新版本:" << version; + if (m_version == version) + { + //qDebug() << "验证结果: 真"; + } + else + { + //qDebug() << "验证结果: 假"; + } + + return false; + VMProtectEnd(); +} diff --git a/CrownClient/Verify.h b/CrownClient/Verify.h new file mode 100644 index 0000000..8579790 --- /dev/null +++ b/CrownClient/Verify.h @@ -0,0 +1,68 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +class Verify :public QObject +{ + Q_OBJECT + +public: + Verify(QString Url, QString AppKey, QString CommKey, QString Verison); + ~Verify(); +private: + // 获取机器码 + QString GetCPUID(); + int GetRandom(int Min, int Max); + QString GetRandom(int Length); + unsigned int Crc32(const void* Buffer, unsigned short Length); + QString Md5(QByteArray Data); + QByteArray RC4(QByteArray Data, QString Key); +private: + QString ParamEncrypt(QString Param); + QString ParamDecrypt(QString Param); + bool Send(QString Option, QString Data, QString& Result, bool async = false); +public: + // 登录 + bool Login(QString Username, QString Password, QString& result); + // 心跳 + bool Heartbeat(QString& result); + // 检查更新 + bool checkUpdate(); + // 软件登录账号 + QString Username(); + QDateTime GetDueTime(); +public slots: + // 推送消息 + bool push_msg(QString type, QString app, QString account, QMap order); + +private: + // 随机密码字符串 非十六进制 + QString m_randomeKey; + // 应用密钥 + QString m_appId; + // 通信密钥 + QString m_commKey; + // 网络接口 + QString m_webApi; + // 机器码 + QString m_machineCode; + // 版本 + QString m_version; + // 账号 + QString m_username; + // 密码 + QString m_password; + + +private: + // 到期时间 + QDateTime m_dueTime; + + +}; \ No newline at end of file diff --git a/CrownClient/VersionUpdate.h b/CrownClient/VersionUpdate.h new file mode 100644 index 0000000..a80ae63 --- /dev/null +++ b/CrownClient/VersionUpdate.h @@ -0,0 +1,53 @@ +#pragma comment(lib, "version.lib") + +#include +#include +#include + +class VersionUpdate +{ +public: + static QString VersionUpdate::GetVersion() + { + int nMaxPathName = 4096; // Max length of file name/path + TCHAR* pBuffer; + UINT nItemLength; + void* pData, * lpBuffer; + QString sVersion; + DWORD dwInfoSize, dwHandle; + VS_FIXEDFILEINFO* pFileInfo; + + // Get the file path and name + pBuffer = new TCHAR[nMaxPathName]; + GetModuleFileName(NULL, pBuffer, nMaxPathName - 1); + + // Get File Version Info size + dwInfoSize = GetFileVersionInfoSize(pBuffer, &dwHandle); + if (dwInfoSize > 0) + { + pData = new TCHAR[dwInfoSize]; + if (GetFileVersionInfo(pBuffer, dwHandle, dwInfoSize, pData)) + if (VerQueryValue(pData, _T("\\"), &lpBuffer, &nItemLength)) + { + pFileInfo = (VS_FIXEDFILEINFO*)lpBuffer; + sVersion = QString("%1.%2.%3.%4") + .arg(pFileInfo->dwProductVersionMS >> 16) + .arg(pFileInfo->dwProductVersionMS & 0xFFFF) + .arg(pFileInfo->dwProductVersionLS >> 16) + .arg(pFileInfo->dwProductVersionLS & 0xFFFF); + // Calculate the product version as a number, you can delete the next statement if you don't need it. + DWORD dwProductVersion = (pFileInfo->dwProductVersionMS >> 16) * 1000 + + (pFileInfo->dwProductVersionMS & 0xFFFF) * 100 + + (pFileInfo->dwProductVersionLS >> 16) * 10 + + (pFileInfo->dwProductVersionLS & 0xFFFF) * 1; + + } + // Delete the data buffer + delete[] pData; + } + // Get rid of the allocated string buffer + delete[] pBuffer; + return sVersion; + } +private: +}; diff --git a/CrownClient/WebEnginePage.cpp b/CrownClient/WebEnginePage.cpp new file mode 100644 index 0000000..c1efa7c --- /dev/null +++ b/CrownClient/WebEnginePage.cpp @@ -0,0 +1,11 @@ +#include "WebEnginePage.h" + +WebEnginePage::WebEnginePage() +{ + +} + +bool WebEnginePage::certificateError(const QWebEngineCertificateError &certificateError) +{ + return true; +} diff --git a/CrownClient/WebEnginePage.h b/CrownClient/WebEnginePage.h new file mode 100644 index 0000000..36fc94c --- /dev/null +++ b/CrownClient/WebEnginePage.h @@ -0,0 +1,12 @@ +#pragma once + +#include + +class WebEnginePage : public QWebEnginePage +{ +public: + WebEnginePage(); + + virtual bool certificateError(const QWebEngineCertificateError &certificateError); +}; + diff --git a/CrownClient/js/iframeState.txt b/CrownClient/js/iframeState.txt new file mode 100644 index 0000000..5d90007 --- /dev/null +++ b/CrownClient/js/iframeState.txt @@ -0,0 +1,36 @@ +function GetFrameState(frm) +{ + var framedoc = frm.document || frm.contentWindow.document; + var ret = false; + if (framedoc.readyState == 'complete') + { + ret = true; + var frms = frm.frames; + if (frms && frms.length > 0) + { + for (var i = 1; i < frms.length; i++) + { + if (frms[i].document.URL == 'about:blank') + { + return false; + } + if (frms[i].attachEvent) + { + frms[i].attachEvent("onload", function () + { + return false; + }); + } + else + { + frms[i].onload = function () + { + return false; + }; + } + } + } + } + return ret; +}; +GetFrameState(); \ No newline at end of file diff --git a/CrownClient/main.cpp b/CrownClient/main.cpp new file mode 100644 index 0000000..7687438 --- /dev/null +++ b/CrownClient/main.cpp @@ -0,0 +1,98 @@ +#include "CrownClient.h" +#include +#include "Global.h" +#include "Login.h" +#include +#include +#include "AppInstanceManager.h" + +#include "Utils.h" +#pragma comment(lib,"D:\\开发工具\\VMProtect\\Lib\\Windows\\VMProtectSDK64.lib") + +#include "StyleLoader.h" + +#include "MessageHandle.h" + + + + +int main(int argc, char *argv[]) +{ + + // 禁用GPU加速(如果黑屏) + qputenv("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu"); + // 启用软件渲染 + qputenv("QT_QUICK_BACKEND", "software"); + qputenv("QT_XCB_FORCE_SOFTWARE_OPENGL", "1"); + // 设置DPI兼容 + if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) + { + QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); + } + + // 检测SSL兼容 + if (!QSslSocket::supportsSsl()) + { + QMessageBox::warning(nullptr, "警告", "OpenSSL组件异常"); + return 0; + } + + // 防止多开 + if (AppInstanceManager::isAlreadyRunning()) { + return 0; + } + + // 关闭浏览器安全警告 + char ARG_DISABLE_WEB_SECURITY[] = "--disable-web-security"; + int newArgc = argc + 1 + 1; + char** newArgv = new char*[newArgc]; + for (int i = 0; i < argc; i++) { + newArgv[i] = argv[i]; + } + newArgv[argc] = ARG_DISABLE_WEB_SECURITY; + newArgv[argc + 1] = nullptr; + + + + QApplication app(newArgc, newArgv); + + + qInstallMessageHandler(message_handle); + + + // 加载QSS样式 + QString style = StyleLoader::loadStyleFromResource(); + if (!style.isEmpty()) { + app.setStyleSheet(style); + } + + // 设置调试端口临时环境变量 + qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "7777"); + + // 设置字体 + QFont font("黑体", 11); + app.setFont(font); + + // 初始化配置类 + g_config = new Config(); + + // 初始化验证类 + g_verify = new Verify("https://gendan.xyz", "72", "NAO87ZGQXTXR1HLFHGL3NSLXD", VERSION); + + + // 检测更新 + if (g_verify->checkUpdate()) + { + Login w; + w.show(); + + return app.exec(); + } + else + { + QProcess::execute(QCoreApplication::applicationDirPath() + "/Update.exe"); + QApplication::quit(); + } + + return 0; +} diff --git a/CrownClient/main.ico b/CrownClient/main.ico new file mode 100644 index 0000000..ab36572 Binary files /dev/null and b/CrownClient/main.ico differ diff --git a/CrownClient/main.qrc b/CrownClient/main.qrc new file mode 100644 index 0000000..04830f4 --- /dev/null +++ b/CrownClient/main.qrc @@ -0,0 +1,13 @@ + + + image/btn_close.png + image/btn_ok.png + image/fontawesome-webfont.ttf + image/msg_error.png + image/msg_info.png + image/msg_question.png + image/qt_zh_CN.qm + main.ico + image/widgets.qm + + diff --git a/CrownClient/resource.h b/CrownClient/resource.h new file mode 100644 index 0000000..318da04 --- /dev/null +++ b/CrownClient/resource.h @@ -0,0 +1,17 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ Éú³ɵİüº¬Îļþ¡£ +// ¹© CrownClient.rc ʹÓà +// +#define IDI_ICON1 101 +#define IDI_ICON2 102 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 103 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/CrownClient/sound/accept.mp3 b/CrownClient/sound/accept.mp3 new file mode 100644 index 0000000..8064dd3 Binary files /dev/null and b/CrownClient/sound/accept.mp3 differ diff --git a/CrownClient/sound/accept.wav b/CrownClient/sound/accept.wav new file mode 100644 index 0000000..f583ffe Binary files /dev/null and b/CrownClient/sound/accept.wav differ diff --git a/CrownClient/sound/disconnect.mp3 b/CrownClient/sound/disconnect.mp3 new file mode 100644 index 0000000..c68c3b0 Binary files /dev/null and b/CrownClient/sound/disconnect.mp3 differ diff --git a/CrownClient/sound/disconnect.wav b/CrownClient/sound/disconnect.wav new file mode 100644 index 0000000..33028f5 Binary files /dev/null and b/CrownClient/sound/disconnect.wav differ diff --git a/CrownClient/sound/exit.mp3 b/CrownClient/sound/exit.mp3 new file mode 100644 index 0000000..1a120d5 Binary files /dev/null and b/CrownClient/sound/exit.mp3 differ diff --git a/CrownClient/sound/exit.wav b/CrownClient/sound/exit.wav new file mode 100644 index 0000000..4293339 Binary files /dev/null and b/CrownClient/sound/exit.wav differ diff --git a/CrownClient/sound/failed.mp3 b/CrownClient/sound/failed.mp3 new file mode 100644 index 0000000..78ca739 Binary files /dev/null and b/CrownClient/sound/failed.mp3 differ diff --git a/CrownClient/sound/failed.wav b/CrownClient/sound/failed.wav new file mode 100644 index 0000000..88b12f2 Binary files /dev/null and b/CrownClient/sound/failed.wav differ diff --git a/CrownClient/sound/pushFailed.mp3 b/CrownClient/sound/pushFailed.mp3 new file mode 100644 index 0000000..e2ac75a Binary files /dev/null and b/CrownClient/sound/pushFailed.mp3 differ diff --git a/CrownClient/sound/pushFailed.wav b/CrownClient/sound/pushFailed.wav new file mode 100644 index 0000000..d8cc1e0 Binary files /dev/null and b/CrownClient/sound/pushFailed.wav differ diff --git a/CrownClient/sound/readOrder.mp3 b/CrownClient/sound/readOrder.mp3 new file mode 100644 index 0000000..d9c0113 Binary files /dev/null and b/CrownClient/sound/readOrder.mp3 differ diff --git a/CrownClient/sound/readOrder.wav b/CrownClient/sound/readOrder.wav new file mode 100644 index 0000000..51c8d8f Binary files /dev/null and b/CrownClient/sound/readOrder.wav differ diff --git a/CrownClient/sound/relogin.mp3 b/CrownClient/sound/relogin.mp3 new file mode 100644 index 0000000..c0c8834 Binary files /dev/null and b/CrownClient/sound/relogin.mp3 differ diff --git a/CrownClient/sound/relogin.wav b/CrownClient/sound/relogin.wav new file mode 100644 index 0000000..3965462 Binary files /dev/null and b/CrownClient/sound/relogin.wav differ diff --git a/CrownClient/sound/screen.mp3 b/CrownClient/sound/screen.mp3 new file mode 100644 index 0000000..d94617a Binary files /dev/null and b/CrownClient/sound/screen.mp3 differ diff --git a/CrownClient/sound/screen.wav b/CrownClient/sound/screen.wav new file mode 100644 index 0000000..7238117 Binary files /dev/null and b/CrownClient/sound/screen.wav differ diff --git a/CrownClient/sound/success.mp3 b/CrownClient/sound/success.mp3 new file mode 100644 index 0000000..5d9e4d5 Binary files /dev/null and b/CrownClient/sound/success.mp3 differ diff --git a/CrownClient/sound/success.wav b/CrownClient/sound/success.wav new file mode 100644 index 0000000..f5f16ca Binary files /dev/null and b/CrownClient/sound/success.wav differ diff --git a/CrownClient/sound/update.mp3 b/CrownClient/sound/update.mp3 new file mode 100644 index 0000000..9c9d050 Binary files /dev/null and b/CrownClient/sound/update.mp3 differ diff --git a/CrownClient/sound/update.wav b/CrownClient/sound/update.wav new file mode 100644 index 0000000..1db16fb Binary files /dev/null and b/CrownClient/sound/update.wav differ diff --git a/CrownClient/sound/手动跟单.mp3 b/CrownClient/sound/手动跟单.mp3 new file mode 100644 index 0000000..28fa985 Binary files /dev/null and b/CrownClient/sound/手动跟单.mp3 differ diff --git a/CrownClient/sound/手动跟单.wav b/CrownClient/sound/手动跟单.wav new file mode 100644 index 0000000..ffef8fe Binary files /dev/null and b/CrownClient/sound/手动跟单.wav differ diff --git a/CrownServer/AppInstanceManager.cpp b/CrownServer/AppInstanceManager.cpp new file mode 100644 index 0000000..ee15253 --- /dev/null +++ b/CrownServer/AppInstanceManager.cpp @@ -0,0 +1,43 @@ +#include "AppInstanceManager.h" +#include "Global.h" +#include "Utils.h" +static int number = Utils::instance().get_number_of_application_name(); +AppInstanceManager* AppInstanceManager::instance() { + static AppInstanceManager manager; + return &manager; +} + +AppInstanceManager::AppInstanceManager(QObject *parent) : QObject(parent) { + m_server = new QLocalServer(this); + if (m_server->listen("crown_server_instance" + QString::number(number))) { + connect(m_server, &QLocalServer::newConnection, [this]() { + QLocalSocket *socket = m_server->nextPendingConnection(); + connect(socket, &QLocalSocket::readyRead, [socket, this]() { + if (socket->readAll() == "ACTIVATE") { + emit raiseRequested(); // 触发激活信号 + } + socket->deleteLater(); + }); + }); + } +} + +void AppInstanceManager::notifyActivate() { + QLocalSocket socket; + socket.connectToServer("crown_server_instance" + QString::number(number)); + if (socket.waitForConnected(300)) { + socket.write("ACTIVATE"); + socket.waitForBytesWritten(); + } +} + +bool AppInstanceManager::isAlreadyRunning() { + QLocalSocket socket; + socket.connectToServer("crown_server_instance" + QString::number(number)); // 固定名称,不要用版本号 + if (socket.waitForConnected(500)) { + socket.write("ACTIVATE"); // 发送激活指令 + socket.waitForBytesWritten(); + return true; // 已存在实例 + } + return false; // 无其他实例 +} \ No newline at end of file diff --git a/CrownServer/AppInstanceManager.h b/CrownServer/AppInstanceManager.h new file mode 100644 index 0000000..5e790bb --- /dev/null +++ b/CrownServer/AppInstanceManager.h @@ -0,0 +1,18 @@ +#pragma once +#include +#include + +class AppInstanceManager : public QObject { + Q_OBJECT +public: + static AppInstanceManager* instance(); + void notifyActivate(); // 向其他实例发送激活信号 + static bool isAlreadyRunning(); + +signals: + void raiseRequested(); // 触发窗口激活 + +private: + explicit AppInstanceManager(QObject *parent = nullptr); + QLocalServer *m_server; +}; \ No newline at end of file diff --git a/CrownServer/CheckBoxHeaderView.cpp b/CrownServer/CheckBoxHeaderView.cpp new file mode 100644 index 0000000..ed6425a --- /dev/null +++ b/CrownServer/CheckBoxHeaderView.cpp @@ -0,0 +1,74 @@ +#include "CheckBoxHeaderView.h" + +CheckBoxHeaderView::CheckBoxHeaderView(int checkColumnIndex, Qt::Orientation orientation, QWidget* parent) + :QHeaderView(orientation, parent) +{ + m_checkColIdx = checkColumnIndex; + m_isChecked = false; +} + +void CheckBoxHeaderView::setCheckStaus(bool isChecked) +{ + m_isChecked = isChecked; + this->updateSection(m_checkColIdx); +} + +bool CheckBoxHeaderView::getCheckStaus() +{ + return m_isChecked; +} + +/// +/// 绘制区域事件 +/// +/// 画笔 +/// 区域 +/// 索引 +void CheckBoxHeaderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const +{ + // 保存当前状态 + painter->save(); + // 绘制区域 + QHeaderView::paintSection(painter, rect, logicalIndex); + // 恢复状态 + painter->restore(); + + // 判断是否为所选行列 + if (logicalIndex == m_checkColIdx) + { + QStyleOptionButton option; + int width = 10; + + option.rect = QRect((rect.right() - rect.left()) / 2 - width / 2 + rect.left() - 1, (rect.bottom() - rect.top()) / 2 - width / 2 + rect.top() - 1, width, width); + + if (m_isChecked) + { + option.state = QStyle::State_Enabled | QStyle::State_On; + } + else + { + option.state = QStyle::State_Enabled | QStyle::State_Off; + } + + this->style()->drawControl(QStyle::CE_CheckBox, &option, painter); + } + +} + +/// +/// 鼠标按下事件 +/// +/// 事件 +void CheckBoxHeaderView::mousePressEvent(QMouseEvent* event) +{ + if (visualIndexAt(event->pos().x()) == m_checkColIdx) + { + if (m_isChecked) + m_isChecked = false; + else + m_isChecked = true; + this->updateSection(m_checkColIdx); + emit checkStausChange(m_isChecked); + } + QHeaderView::mousePressEvent(event); +} \ No newline at end of file diff --git a/CrownServer/CheckBoxHeaderView.h b/CrownServer/CheckBoxHeaderView.h new file mode 100644 index 0000000..38efd77 --- /dev/null +++ b/CrownServer/CheckBoxHeaderView.h @@ -0,0 +1,27 @@ +#pragma once +#include +#include +#include +#include + +// 参考 https://blog.csdn.net/wj584652425/article/details/125034684 + + +class CheckBoxHeaderView : public QHeaderView +{ + Q_OBJECT +public: + CheckBoxHeaderView(int checkColumnIndex, Qt::Orientation orientation, QWidget* parent = 0); + void setCheckStaus(bool isChecked); + bool getCheckStaus(); +signals: + void checkStausChange(bool); + +protected: + void paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const; + void mousePressEvent(QMouseEvent* event); + +private: + bool m_isChecked; + int m_checkColIdx; +}; \ No newline at end of file diff --git a/CrownServer/ComboBox.cpp b/CrownServer/ComboBox.cpp new file mode 100644 index 0000000..b13ecf7 --- /dev/null +++ b/CrownServer/ComboBox.cpp @@ -0,0 +1,243 @@ +#include "ComboBox.h" +#include +#include + +/// +/// 构造函数 +/// +/// 父类 +ComboBox::ComboBox(QWidget* parent) : QComboBox(parent) +, m_count(0) // 修复:初始化 m_count +{ + // 初始化列表容器 + listWidget = new QListWidget(this); // 修复:设置父对象 + // 设置模型 + this->setModel(listWidget->model()); + // 设置视图 + this->setView(listWidget); + // 清空 + this->clear(); + // 设置可编辑 + this->setEditable(true); + // 设置禁止重复 + this->setDuplicatesEnabled(false); + // 设置插入策略 + this->setInsertPolicy(QComboBox::NoInsert); +} + +/// +/// 添加项目 +/// +/// 文本 +void ComboBox::addItem(const QString& text) +{ + // 检查空内容 + if (text.trimmed().isEmpty()) { + // qDebug() << __FILE__ << __LINE__ << "Cannot add empty text!"; + // this->setToolTip("输入内容不能为空!"); + return; + } + + // 检查重复项(遍历现有项) + for (int i = 0; i < listWidget->count(); i++) { + QListWidgetItem* existingItem = listWidget->item(i); + ComboBoxItem* itemWidget = static_cast(listWidget->itemWidget(existingItem)); + if (itemWidget && text == itemWidget->getLabelText()) { + // qDebug() << "Item already exists:" << text; + // this->setToolTip("内容已存在!"); + return; + } + } + + // 修复:使用动态宽度计算 + int textWidth = fontMetrics().horizontalAdvance(text); + int buttonWidth = 30; // 按钮宽度 + int minWidth = textWidth + buttonWidth + 20; + + // 调整最小宽度 + if (this->minimumWidth() < minWidth) { + this->setMinimumWidth(minWidth); + } + + // 组合框项目 + ComboBoxItem* item = new ComboBoxItem(); + // 设置文本 + item->setLabelText(text); + + // 移除属性 + connect(item, &ComboBoxItem::signalRemoveProperty, this, &ComboBox::slotRemoveProperty); + // 显示点击条目 + connect(item, &ComboBoxItem::signalShowClicked, this, &ComboBox::slotCurrentText); + + // 条目 + QListWidgetItem* list_item = new QListWidgetItem(listWidget); + list_item->setSizeHint(QSize(minWidth, 25)); // 修复:设置合适的大小 + + item->setProperty("count", QString::number(m_count++)); + listWidget->setItemWidget(list_item, item); + + if (this->currentText().isEmpty()) + { + this->setCurrentText(text); + } +} + +/// +/// 添加列表 +/// +/// 列表 +void ComboBox::addItems(const QList& list) +{ + foreach(QString item, list) + { + addItem(item); + } +} + +/* 删除选择的文本,注意此处删除的是listwidget而不是combobox,combobox是一个空的内容 */ +void ComboBox::slotRemoveItem(const QString text) +{ + // qDebug() << "SlotRemoveItem/text = " << text; + for (int i = 0; i < listWidget->count(); i++) + { + QListWidgetItem* item = listWidget->item(i); + ComboBoxItem* clickitem = static_cast(listWidget->itemWidget(item)); + if (!clickitem) continue; + + QString labelText = clickitem->getLabelText(); + if (text == labelText) + { + listWidget->takeItem(i); + delete item; + + // 如果当前显示的文本是被删除的文本,清空显示 + if (this->currentText() == text) { + this->setCurrentText(""); + } + + // 刷新显示 + if (listWidget->count() > 0) + { + this->showPopup(); + } + else + { + this->hidePopup(); + } + break; + } + } +} + +/* 删除选择的属性对应的item,因为文本可能重复,但是设置的属性是唯一的,注意此处删除的是listwidget而不是combobox,combobox是一个空的内容 */ +void ComboBox::slotRemoveProperty(const QString PropertyStr) +{ + // qDebug() << "SlotRemoveProperty/text = " << PropertyStr; + int list_count = listWidget->count(); + for (int i = 0; i < list_count; i++) { + QListWidgetItem* item = listWidget->item(i); + ComboBoxItem* clickitem = static_cast(listWidget->itemWidget(item)); + if (!clickitem) continue; + + QString LabelText = clickitem->property("count").toString(); + if (PropertyStr == LabelText) { + QString itemText = clickitem->getLabelText(); + listWidget->takeItem(i); + delete item; + + // 如果当前显示的文本是被删除的文本,清空显示 + if (this->currentText() == itemText) { + this->setCurrentText(""); + } + + // 刷新显示 + if (listWidget->count() > 0) + { + this->showPopup(); + } + else + { + this->hidePopup(); + } + break; + } + } +} + +/* 设置当前combobox的显示文本 */ +void ComboBox::slotCurrentText(const QString text) +{ + this->setCurrentText(text); + hidePopup(); +} + +/// +/// 键盘释放事件 +/// +/// 事件 +void ComboBox::keyReleaseEvent(QKeyEvent* event) +{ + // 判断是否按下回车 + if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) + { + // 获取当前文本 + QString text = this->currentText(); + if (text.trimmed().isEmpty()) + { + return; + } + + // 清空编辑框文本但不关闭下拉框 + this->setEditText(""); + + // 判断是否过滤重复 + if (this->duplicatesEnabled() == false) + { + // 遍历QListWidget + for (int i = 0; i < listWidget->count(); i++) + { + QListWidgetItem* item = listWidget->item(i); + ComboBoxItem* itemWidget = static_cast(listWidget->itemWidget(item)); + if (!itemWidget) continue; + + QString labelText = itemWidget->getLabelText(); + if (text == labelText) + { + return; + } + } + } + this->addItem(text); + } + else + { + QComboBox::keyReleaseEvent(event); + } +} + +QString ComboBox::item(int index) +{ + if (index < 0 || index >= listWidget->count()) { + return QString(); + } + + QListWidgetItem* item = listWidget->item(index); + ComboBoxItem* itemWidget = static_cast(listWidget->itemWidget(item)); + if (!itemWidget) return QString(); + + return itemWidget->getLabelText(); +} + +QList ComboBox::items() +{ + QList list; + for (int i = 0; i < listWidget->count(); i++) + { + QListWidgetItem* item = listWidget->item(i); + ComboBoxItem* itemWidget = static_cast(listWidget->itemWidget(item)); + if (!itemWidget) continue; + + list.append(itemWidget->getLabelText()); + } + return list; +} \ No newline at end of file diff --git a/CrownServer/ComboBox.h b/CrownServer/ComboBox.h new file mode 100644 index 0000000..5380044 --- /dev/null +++ b/CrownServer/ComboBox.h @@ -0,0 +1,27 @@ +#pragma once +#include +#include +#include +#include +#include "ComboBoxItem.h" + +class ComboBox : public QComboBox +{ + Q_OBJECT +public: + explicit ComboBox(QWidget* parent = nullptr); + void addItem(const QString& text); + void addItems(const QList& list); + QString item(int index); + QList items(); +public slots: + void slotRemoveItem(const QString text); + void slotRemoveProperty(const QString PropertyStr); + void slotCurrentText(const QString text); +protected: + void keyReleaseEvent(QKeyEvent* event); +private: + QListWidget* listWidget; + int m_count; +}; + diff --git a/CrownServer/ComboBoxItem.cpp b/CrownServer/ComboBoxItem.cpp new file mode 100644 index 0000000..80bd1de --- /dev/null +++ b/CrownServer/ComboBoxItem.cpp @@ -0,0 +1,106 @@ +#include "ComboBoxItem.h" + +/// +/// 构造函数 +/// +/// 父类 +ComboBoxItem::ComboBoxItem(QWidget* parent) : QWidget(parent) +, m_mousePress(false) +, painter(nullptr) +{ + m_label = new QLabel(this); + m_button = new QPushButton(this); + + // 修复:正确创建和绘制叉号图标 + QPixmap pixmap(16, 16); + pixmap.fill(Qt::transparent); + + QPainter painter(&pixmap); + painter.setRenderHint(QPainter::Antialiasing, true); + QPen pen(Qt::black); + pen.setWidth(2); + painter.setPen(pen); + + // 绘制叉号 + painter.drawLine(4, 4, 12, 12); + painter.drawLine(12, 4, 4, 12); + painter.end(); + + // 设置按钮图片 + m_button->setIcon(QIcon(pixmap)); + m_button->setIconSize(QSize(12, 12)); + m_button->setFixedSize(20, 20); + // 设置风格 + m_button->setStyleSheet("QPushButton { border: none; background: transparent; }" + "QPushButton:hover { background: rgba(200, 200, 200, 100); border-radius: 3px; }"); + + // 点击事件 + connect(m_button, &QPushButton::clicked, [this] { + // 删除选项 + emit signalRemoveClicked(m_label->text()); + // 删除属性 + emit signalRemoveProperty(property("count").toString()); + }); + + // 水平布局 + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(5, 2, 5, 2); + layout->setSpacing(5); + + // 标签 + layout->addWidget(m_label); + // 弹簧 + layout->addStretch(); + // 按钮 + layout->addWidget(m_button); + + setLayout(layout); + setFixedHeight(25); // 修复:固定高度 +} + +/// +/// 设置项目文本 +/// +/// 文本 +void ComboBoxItem::setLabelText(QString text) +{ + m_label->setText(text); +} + +/// +/// 获取当前项目文本 +/// +/// 文本 +QString ComboBoxItem::getLabelText() +{ + return m_label->text(); +} + +/// +/// 鼠标按下事件 +/// +/// 事件 +void ComboBoxItem::mousePressEvent(QMouseEvent* event) +{ + if (event->button() == Qt::LeftButton) + { + m_mousePress = true; + } + QWidget::mousePressEvent(event); // 修复:调用父类事件 +} + +/// +/// 鼠标释放事件 +/// +/// 事件 +void ComboBoxItem::mouseReleaseEvent(QMouseEvent* event) +{ + if (m_mousePress && rect().contains(event->pos())) + { + // 发送信号 + qDebug() << "按下:" << m_label->text(); + emit signalShowClicked(m_label->text()); + } + m_mousePress = false; + QWidget::mouseReleaseEvent(event); // 修复:调用父类事件 +} \ No newline at end of file diff --git a/CrownServer/ComboBoxItem.h b/CrownServer/ComboBoxItem.h new file mode 100644 index 0000000..29edfea --- /dev/null +++ b/CrownServer/ComboBoxItem.h @@ -0,0 +1,31 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include + +class ComboBoxItem : public QWidget +{ + Q_OBJECT +public: + explicit ComboBoxItem(QWidget* parent = nullptr); + void setLabelText(QString text); + QString getLabelText(); +signals: + void signalRemoveClicked(const QString& text); + void signalRemoveProperty(const QString& text); + void signalShowClicked(const QString& text); +protected: + void mousePressEvent(QMouseEvent* event); + void mouseReleaseEvent(QMouseEvent* event); +private: + bool m_mousePress; + QPushButton* m_button; + QLabel* m_label; + QPixmap* m_pixmap; + QPainter* painter; + +}; diff --git a/CrownServer/Config.cpp b/CrownServer/Config.cpp new file mode 100644 index 0000000..2cfcdae --- /dev/null +++ b/CrownServer/Config.cpp @@ -0,0 +1,1388 @@ +#include "Config.h" + +#include "Global.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Utils.h" + +extern QString dateFormat(QString source); + + +Config::Config() +{ + int number = Utils::instance().get_number_of_application_name(); + + // 确保目录存在 + QString dataDir = QDir::homePath() + "/AppData/Roaming" + "/crown/"; + QDir dir(dataDir); + if (!dir.exists()) { + dir.mkpath("."); // 递归创建目录 + } + QString setting_path = QDir::homePath() + "/AppData/Roaming" + QString("/crown/settings%1.ini").arg(number); + QString db_path = QDir::homePath() + "/AppData/Roaming" + QString("/crown/server%1.db").arg(number); + m_settings = new QSettings(setting_path, QSettings::IniFormat); + + + //qDebug() << db_path; + // 添加数据库驱动并打开 + m_db = QSqlDatabase::addDatabase("QSQLITE"); + m_db.setDatabaseName(db_path); + if (!m_db.open()) { + qDebug() << "配置类 -> 数据库打开失败"; + return; + } + + auto execSql = [&](const char* sql) { + QSqlQuery q(m_db); + if (!q.exec(sql)) { + qDebug() << "SQL 执行失败:" << q.lastError().text() << "\n" << sql; + return false; + } + return true; + }; + + // 检查某表是否存在某列 + auto hasColumn = [&](const QString& table, const QString& column) -> bool { + QSqlQuery q(m_db); + q.prepare(QStringLiteral("PRAGMA table_info(%1)").arg(table)); + if (!q.exec()) return false; + while (q.next()) { + if (q.value(1).toString().compare(column, Qt::CaseInsensitive) == 0) return true; + } + return false; + }; + + // 1) note + execSql(R"( +CREATE TABLE IF NOT EXISTS note( + id INTEGER PRIMARY KEY AUTOINCREMENT, + sign TEXT, + TID INTEGER +); +)"); + + // 2) follow + execSql(R"( +CREATE TABLE IF NOT EXISTS follow( + id INTEGER PRIMARY KEY AUTOINCREMENT, + TID INTEGER +); +)"); + + // 3) orders(包含 SESSION、STAGE、G_TIME) + execSql(R"( +CREATE TABLE IF NOT EXISTS orders( + TID INTEGER PRIMARY KEY, /* 单号 */ + DATETIME TEXT, /* 下注时间 */ + READ_DATETIME TEXT, /* 读取时间 */ + NAME0 TEXT, /* 会员/代理 */ + GT TEXT, /* 球种:足球/篮球 */ + WAGERS_TYPE TEXT, /* 投注类型:如让球 */ + LEAGUE TEXT, /* 联赛 */ + TEAM_H TEXT, /* 主队 */ + TEAM_C TEXT, /* 客队 */ + ORDER_TYPE TEXT, /* 下注队伍 */ + ORDER_CON TEXT, /* 下注盘口 */ + SCORE TEXT, /* 比分 */ + IORATIO REAL, /* 赔率 */ + GOLD REAL, /* 金额 */ + SRV_IP TEXT, /* 下单来源:手机/电脑 */ + SESSION TEXT, /* 会话: 滚球/今日/早盘 */ + STAGE TEXT, /* 场次: 全场/上半场/全部 */ + G_TIME TEXT, /* 比赛时间 yyyy-MM-dd HH:mm:ss */ + NUM_H TEXT, /* 主队ID */ + NUM_C TEXT /* 客队ID */ + ODDF_TYPE TEXT /* 下注盘口:香港盘 欧洲盘 */ + BET_TYPE TEXT /* 投注方向:H C*/ +); +)"); + + // 兼容旧表:缺哪个列就补哪个列 + { + QSqlQuery q(m_db); + if (!hasColumn("orders", "SESSION")) execSql("ALTER TABLE orders ADD COLUMN SESSION TEXT"); + if (!hasColumn("orders", "STAGE")) execSql("ALTER TABLE orders ADD COLUMN STAGE TEXT"); + if (!hasColumn("orders", "G_TIME")) execSql("ALTER TABLE orders ADD COLUMN G_TIME TEXT"); + if (!hasColumn("orders", "NUM_H")) execSql("ALTER TABLE orders ADD COLUMN NUM_H TEXT"); + if (!hasColumn("orders", "NUM_C")) execSql("ALTER TABLE orders ADD COLUMN NUM_C TEXT"); + if (!hasColumn("orders", "SRV_IP")) execSql("ALTER TABLE orders ADD COLUMN SRV_IP TEXT"); + if (!hasColumn("orders", "ODDF_TYPE")) execSql("ALTER TABLE orders ADD COLUMN ODDF_TYPE TEXT"); + if (!hasColumn("orders", "BET_TYPE")) execSql("ALTER TABLE orders ADD COLUMN BET_TYPE TEXT"); + } + + // 4) log + execSql(R"( +CREATE TABLE IF NOT EXISTS log( + id INTEGER PRIMARY KEY AUTOINCREMENT, + date TEXT, + datetime TEXT, + type TEXT, + log TEXT +); +)"); +} + + +Config::~Config() +{ + m_db.close(); +} + + + +QString Config::toJson(QList> list) +{ + QList>::iterator iter; + QJsonArray jsonArray; + for (iter = list.begin(); iter != list.end(); iter++) + { + QMap map = *iter; + QJsonObject dataJson; + for (int i = 0; i < map.keys().count(); i++) + { + dataJson.insert(map.keys()[i], map.value(map.keys()[i])); + } + + jsonArray.append(dataJson); + } + return QString(QJsonDocument(jsonArray).toJson()); +} +QString Config::toJson(QList list) +{ + QList::iterator iter; + QJsonArray jsonArray; + for (iter = list.begin(); iter != list.end(); iter++) + { + QString string = *iter; + jsonArray.append(string); + } + return QString(QJsonDocument(jsonArray).toJson()); +} + +QList> Config::toMapList(QString data) +{ + QList> list; + QJsonArray jsonArray = QJsonDocument::fromJson(data.toStdString().c_str()).array(); + for (int i = 0; i < jsonArray.count(); i++) + { + QMap map; + map.clear(); + for (int j = 0; j < jsonArray[i].toObject().keys().count(); j++) + { + QString key = jsonArray[i].toObject().keys().at(j); + map[key] = jsonArray[i].toObject()[key].toString(); + } + // qDebug() << map; + list.append(map); + } + + return list; +} + +QList Config::toStringList(QString data) +{ + QList list; + + QJsonArray jsonArray = QJsonDocument::fromJson(data.toStdString().c_str()).array(); + + for (int i = 0; i < jsonArray.count(); i++) + { + list.append(jsonArray[i].toString()); + } + + return list; +} + + +QString Config::verifyUsername() +{ + m_mutex.lock(); + QString username = m_settings->value("Server/VerifyUsername").toString(); + m_mutex.unlock(); + return username; +} + +void Config::setVerifyUsername(QString username) +{ + m_mutex.lock(); + m_settings->setValue("Server/VerifyUsername", QVariant::fromValue(username)); + m_mutex.unlock(); +} + +QString Config::verifyPassword() +{ + m_mutex.lock(); + QString password = m_settings->value("Server/VerifyPassword").toString(); + m_mutex.unlock(); + return password; +} + +void Config::setVerifyPassword(QString password) +{ + m_mutex.lock(); + m_settings->setValue("Server/VerifyPassword", QVariant::fromValue(password)); + m_mutex.unlock(); +} + +bool Config::autoLogin() +{ + m_mutex.lock(); + bool autoLogin = m_settings->value("Server/AutoLogin").toBool(); + m_mutex.unlock(); + return autoLogin; +} + +void Config::setAutoLogin(bool autoLogin) +{ + m_mutex.lock(); + m_settings->setValue("Server/AutoLogin", QVariant::fromValue(autoLogin)); + m_mutex.unlock(); +} + +bool Config::crownTime() +{ + m_mutex.lock(); + bool crownTime = m_settings->value("Server/CrownTime").toBool(); + m_mutex.unlock(); + return crownTime; +} + +void Config::setCrownTime(bool crownTime) +{ + m_mutex.lock(); + m_settings->setValue("Server/CrownTime", QVariant::fromValue(crownTime)); + m_mutex.unlock(); +} + + +int Config::readDays() +{ + m_mutex.lock(); + int days = m_settings->value("Server/ReadDays", 1).toInt(); + m_mutex.unlock(); + return days; +} + +void Config::setReadDays(int days) +{ + m_mutex.lock(); + m_settings->setValue("Server/ReadDays", days); + m_mutex.unlock(); +} + +bool Config::readNormalOrder() +{ + m_mutex.lock(); + bool enable = m_settings->value("Server/ReadNormalOrder", true).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setReadNormalOrder(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Server/ReadNormalOrder", enable); + m_mutex.unlock(); +} + +bool Config::readPhoneOrder() +{ + m_mutex.lock(); + bool enable = m_settings->value("Server/ReadPhoneOrder", true).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setReadPhoneOrder(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Server/ReadPhoneOrder", enable); + m_mutex.unlock(); +} + +QList> Config::screen_list() +{ + m_mutex.lock(); + QList> list = toMapList(m_settings->value("Server/ScreenList").toString()); + m_mutex.unlock(); + return list; +} + +void Config::set_screen_list(QList> list) +{ + m_mutex.lock(); + m_settings->setValue("Server/ScreenList", toJson(list)); + m_mutex.unlock(); +} + + + +QList Config::acceptUserList() +{ + m_mutex.lock(); + QList list = toStringList(m_settings->value("Server/AcceptUserList").toString()); + m_mutex.unlock(); + return list; +} + +QList Config::screenUserList() +{ + m_mutex.lock(); + QList list = toStringList(m_settings->value("Server/ScreenUserList").toString()); + m_mutex.unlock(); + return list; +} + +void Config::setAcceptUserList(QList list) +{ + m_mutex.lock(); + m_settings->setValue("Server/AcceptUserList", toJson(list)); + m_mutex.unlock(); +} + +void Config::setScreenUserList(QList list) +{ + m_mutex.lock(); + m_settings->setValue("Server/ScreenUserList", toJson(list)); + m_mutex.unlock(); +} + +QList> Config::screenUsernameList() +{ + m_mutex.lock(); + QList> list = toMapList(m_settings->value("Server/ScreenUsernameList").toString()); + m_mutex.unlock(); + return list; +} + +void Config::setScreenUsernameList(QList> list) +{ + m_mutex.lock(); + m_settings->setValue("Server/ScreenUsernameList", toJson(list)); + m_mutex.unlock(); +} + +bool Config::screenEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Server/ScreenEnable", false).toBool(); + m_mutex.unlock(); + return enable; +} + +void Config::setScreenEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Server/ScreenEnable", enable); + m_mutex.unlock(); +} + +int Config::screenMode() +{ + m_mutex.lock(); + int mode = m_settings->value("Server/ScreenMode", 0).toInt(); + m_mutex.unlock(); + return mode; +} + +void Config::setScreenMode(int mode) +{ + m_mutex.lock(); + m_settings->setValue("Server/ScreenMode", mode); + m_mutex.unlock(); +} + + + +/// +/// 获取代理网址列表 +/// +/// 列表 +QList Config::agentUrlList() +{ + m_mutex.lock(); + QList list = toStringList(m_settings->value("Server/AgentUrlList").toString()); + + if (list.isEmpty()) + { + list.append("https://ag.hga050.com"); + list.append("https://ag.hga030.com"); + list.append("https://123.108.119.60"); + list.append("https://ag.mos011.com/"); + list.append("https://hga035.com/"); + + } + m_mutex.unlock(); + return list; +} + +/// +/// 设置代理网址列表 +/// +/// 列表 +void Config::setAgentUrlList(QList list) +{ + m_mutex.lock(); + m_settings->setValue("Server/AgentUrlList", toJson(list)); + m_mutex.unlock(); +} + +/// +/// 获取用户网址列表 +/// +/// 列表 +QList Config::userUrlList() +{ + m_mutex.lock(); + QList list = toStringList(m_settings->value("Server/UserUrlList").toString()); + m_mutex.unlock(); + return list; +} + +/// +/// 设置用户网址列表 +/// +/// 列表 +void Config::setUserUrlList(QList list) +{ + //auto client_setting = new QSettings(QCoreApplication::applicationDirPath() + "/settings.ini", QSettings::IniFormat); + m_mutex.lock(); + m_settings->setValue("Server/UserUrlList", toJson(list)); + m_mutex.unlock(); +} + + +QString Config::ip() +{ + m_mutex.lock(); + QString ip = m_settings->value("Server/Ip", "127.0.0.1").toString(); + m_mutex.unlock(); + return ip; +} + +void Config::setIp(QString ip) +{ + m_mutex.lock(); + m_settings->setValue("Server/Ip", QVariant::fromValue(ip)); + m_mutex.unlock(); +} + +QList Config::ipList() +{ + m_mutex.lock(); + QList list = toStringList(m_settings->value("Server/IpList").toString()); + m_mutex.unlock(); + return list; +} + +void Config::setIpList(QList list) +{ + m_mutex.lock(); + m_settings->setValue("Server/IpList", toJson(list)); + m_mutex.unlock(); +} + +QString Config::port() +{ + // 需要注意 + m_mutex.lock(); + + int number = Utils::instance().get_number_of_application_name(); + QString port_default; + port_default = QString("%1%2%3%4%5").arg(number).arg(number).arg(number).arg(number).arg(number); + QString port = m_settings->value("Server/Port", port_default).toString(); + m_mutex.unlock(); + return port; +} + +void Config::setPort(QString port) +{ + m_mutex.lock(); + m_settings->setValue("Server/Port", QVariant::fromValue(port)); + m_mutex.unlock(); +} + +QList Config::portList() +{ + m_mutex.lock(); + QList list = toStringList(m_settings->value("Server/PortList").toString()); + + if (list.isEmpty()) + { + list.append("11111"); + list.append("22222"); + list.append("33333"); + list.append("44444"); + list.append("55555"); + } + m_mutex.unlock(); + return list; +} + +void Config::setPortList(QList list) +{ + m_mutex.lock(); + m_settings->setValue("Server/PortList", toJson(list)); + m_mutex.unlock(); +} + +QString Config::connectPassword() +{ + m_mutex.lock(); + QString password = m_settings->value("Server/ConnectPassword", "88888").toString(); + m_mutex.unlock(); + return password; +} + +void Config::setConnectPassword(QString password) +{ + m_mutex.lock(); + m_settings->setValue("Server/ConnectPassword", password); + m_mutex.unlock(); +} + +QString Config::agentUrl() +{ + m_mutex.lock(); + QString url = m_settings->value("Server/AgentUrl", "https://ag.hga050.com").toString(); + m_mutex.unlock(); + return url; +} + +void Config::setAgentUrl(QString url) +{ + m_mutex.lock(); + m_settings->setValue("Server/AgentUrl", url); + m_mutex.unlock(); +} + +QString Config::username() +{ + m_mutex.lock(); + QString username = m_settings->value("Server/Username").toString(); + m_mutex.unlock(); + return username; +} + +void Config::setUsername(QString username) +{ + m_mutex.lock(); + m_settings->setValue("Server/Username", username); + m_mutex.unlock(); +} + + +QString Config::password() +{ + m_mutex.lock(); + QString password = m_settings->value("Server/Password").toString(); + m_mutex.unlock(); + return password; +} + +void Config::setPassword(QString password) +{ + m_mutex.lock(); + m_settings->setValue("Server/Password", password); + m_mutex.unlock(); +} + + +QString Config::level() +{ + m_mutex.lock(); + QString level = m_settings->value("Server/Level").toString(); + m_mutex.unlock(); + return level; +} + +void Config::setLevel(QString level) +{ + m_mutex.lock(); + m_settings->setValue("Server/Level", level); + m_mutex.unlock(); +} + +QString Config::safeCode() +{ + m_mutex.lock(); + QString safeCode = m_settings->value("Server/SafeCode").toString(); + m_mutex.unlock(); + return safeCode; +} + +void Config::setSafeCode(QString safeCode) +{ + m_mutex.lock(); + m_settings->setValue("Server/SafeCode", QVariant::fromValue(safeCode)); + m_mutex.unlock(); +} + + +/// +/// 获取报表列表读取频率最小值 +/// +/// 频率 +int Config::readReportListInterValMin() +{ + m_mutex.lock(); + int interval = m_settings->value("Server/ReadReportListIntervalMin", 1).toInt(); + m_mutex.unlock(); + return interval; +} + +/// +/// 获取报表列表读取频率最大值 +/// +/// 频率 +int Config::readReportListInterValMax() +{ + m_mutex.lock(); + int interval = m_settings->value("Server/ReadReportListIntervalMax", 3).toInt(); + m_mutex.unlock(); + return interval; +} + +/// +/// 获取报表读取频率 +/// +/// 频率 +int Config::readReportListInterVal() +{ + m_mutex.lock(); + + int min = m_settings->value("Server/ReadReportListIntervalMin", 1).toInt(); + int max = m_settings->value("Server/ReadReportListIntervalMax", 3).toInt(); + min = min > 0 ? min : 1; + max = max > 0 ? max : 60; + srand(QTime(0, 0, 0).secsTo(QTime::currentTime())); + int interval = rand() % (max - min + 1) + min; + m_mutex.unlock(); + return interval; +} + +/// +/// 设置读取报表频率最小值 +/// +/// 频率 +void Config::setReadReportListIntervalMin(int msec) +{ + m_mutex.lock(); + m_settings->setValue("Server/ReadReportListIntervalMin", msec); + m_mutex.unlock(); +} + +/// +/// 设置读取报表列表频率最大值 +/// +/// 频率 +void Config::setReadReportListIntervalMax(int msec) +{ + m_mutex.lock(); + m_settings->setValue("Server/ReadReportListIntervalMax", msec); + m_mutex.unlock(); +} + +/// +/// 获取用户列表读取频率最小值 +/// +/// 频率 +int Config::readUserListInterValMin() +{ + m_mutex.lock(); + int interval = m_settings->value("Server/ReadUserListIntervalMin", 3).toInt(); + m_mutex.unlock(); + return interval; +} + +/// +/// 获取用户列表读取频率最大值 +/// +/// 频率 +int Config::readUserListInterValMax() +{ + m_mutex.lock(); + int interval = m_settings->value("Server/ReadUserListIntervalMax", 4).toInt(); + m_mutex.unlock(); + return interval; +} + +/// +/// 获取用户列表读取频率 +/// +/// 频率 +int Config::readUserListInterVal() +{ + m_mutex.lock(); + + int min = m_settings->value("Server/ReadUserListIntervalMin").toInt(); + int max = m_settings->value("Server/ReadUserListIntervalMax").toInt(); + min = min > 0 ? min : 1; + max = max > 0 ? max : 60; + srand(QTime(0, 0, 0).secsTo(QTime::currentTime())); + int interval = rand() % (max - min + 1) + min; + m_mutex.unlock(); + return interval; +} + +/// +/// 设置读取用户列表频率最小值 +/// +/// 频率 +void Config::setReadUserListIntervalMin(int msec) +{ + m_mutex.lock(); + m_settings->setValue("Server/ReadUserListIntervalMin", msec); + m_mutex.unlock(); +} + +/// +/// 设置读取用户列表频率最大值 +/// +/// 频率 +void Config::setReadUserListIntervalMax(int msec) +{ + m_mutex.lock(); + m_settings->setValue("Server/ReadUserListIntervalMax", msec); + m_mutex.unlock(); +} + +/// +/// 获取注单列表读取频率最小值 +/// +/// 频率 +int Config::readOrderListInterValMin() +{ + m_mutex.lock(); + int interval = m_settings->value("Server/ReadOrderListIntervalMin", 10).toInt(); + m_mutex.unlock(); + return interval; +} + +/// +/// 获取注单列表读取频率最大值 +/// +/// 频率 +int Config::readOrderListInterValMax() +{ + m_mutex.lock(); + int interval = m_settings->value("Server/ReadOrderListIntervalMax", 12).toInt(); + m_mutex.unlock(); + return interval; +} + +/// +/// 获取注单列表读取频率 +/// +/// 频率 +int Config::readOrderListInterVal() +{ + m_mutex.lock(); + int min = m_settings->value("Server/ReadOrderListIntervalMin").toInt(); + int max = m_settings->value("Server/ReadOrderListIntervalMax").toInt(); + min = min > 0 ? min : 1; + max = max > 0 ? max : 60; + srand(QTime(0, 0, 0).secsTo(QTime::currentTime())); + int interval = rand() % (max - min + 1) + min; + m_mutex.unlock(); + return interval; +} + +/// +/// 设置读取注单列表频率最小值 +/// +/// 频率 +void Config::setReadOrderListIntervalMin(int msec) +{ + m_mutex.lock(); + m_settings->setValue("Server/ReadOrderListIntervalMin", msec); + m_mutex.unlock(); +} + +/// +/// 设置读取注单列表频率最大值 +/// +/// 频率 +void Config::setReadOrderListIntervalMax(int msec) +{ + m_mutex.lock(); + m_settings->setValue("Server/ReadOrderListIntervalMax", msec); + m_mutex.unlock(); +} + + + +/// +/// 掉线延时最小值 +/// +/// 延时 +int Config::disconnectedSleepMin() +{ + m_mutex.lock(); + int value = m_settings->value("Server/DisconnectedSleepMin", 10).toInt(); + m_mutex.unlock(); + return value; +} + +/// +/// 掉线延时最大值 +/// +/// 延时 +int Config::disconnectedSleepMax() +{ + m_mutex.lock(); + int value = m_settings->value("Server/DisconnectedSleepMax", 60).toInt(); + m_mutex.unlock(); + return value; +} + +/// +/// 掉线延时 +/// +/// 延时 +int Config::disconnectedSleep() +{ + m_mutex.lock(); + int min = m_settings->value("Server/DisconnectedSleepMin").toInt(); + int max = m_settings->value("Server/DisconnectedSleepMax").toInt(); + min = min > 0 ? min : 1; + max = max > 0 ? max : 60; + srand(QTime(0, 0, 0).secsTo(QTime::currentTime())); + int value = rand() % (max - min + 1) + min; + m_mutex.unlock(); + return value; +} + +/// +/// 设置掉线延时最小值 +/// +/// 延时 +void Config::setDisconnectedSleepMin(int value) +{ + m_mutex.lock(); + m_settings->setValue("Server/DisconnectedSleepMin", value); + m_mutex.unlock(); +} + +/// +/// 设置掉线延时最大值 +/// +/// 延时 +void Config::setDisconnectedSleepMax(int value) +{ + m_mutex.lock(); + m_settings->setValue("Server/DisconnectedSleepMax", value); + m_mutex.unlock(); +} + + +/// +/// 登录失败延时最小值 +/// +/// 延时 +int Config::failedSleepMin() +{ + m_mutex.lock(); + int value = m_settings->value("Server/FailedSleepMin", 10).toInt(); + m_mutex.unlock(); + return value; +} + +/// +/// 登录失败延时最大值 +/// +/// 延时 +int Config::failedSleepMax() +{ + m_mutex.lock(); + int value = m_settings->value("Server/FailedSleepMax", 60).toInt(); + m_mutex.unlock(); + return value; +} + +/// +/// 登录失败延时 +/// +/// 延时 +int Config::failedSleep() +{ + m_mutex.lock(); + int min = m_settings->value("Server/FailedSleepMin").toInt(); + int max = m_settings->value("Server/FailedSleepMax").toInt(); + min = min > 0 ? min : 1; + max = max > 0 ? max : 60; + srand(QTime(0, 0, 0).secsTo(QTime::currentTime())); + int value = rand() % (max - min + 1) + min; + m_mutex.unlock(); + return value; +} + +/// +/// 设置登录失败延时最小值 +/// +/// 延时 +void Config::setFailedSleepMin(int value) +{ + m_mutex.lock(); + m_settings->setValue("Server/FailedSleepMin", value); + m_mutex.unlock(); +} + +/// +/// 设置登录失败延时最大值 +/// +/// 延时 +void Config::setFailedSleepMax(int value) +{ + m_mutex.lock(); + m_settings->setValue("Server/FailedSleepMax", value); + m_mutex.unlock(); +} + +int Config::failedReconnectTimes() +{ + m_mutex.lock(); + int value = m_settings->value("Server/FailedReconnectTimes", 5).toInt(); + m_mutex.unlock(); + return value; +} + +void Config::setFailedReconnectTimes(int value) +{ + m_mutex.lock(); + m_settings->setValue("Server/FailedReconnectTimes", value); + m_mutex.unlock(); +} + + +bool Config::updateOrderSoundEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Server/UpdateOrderSoundEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +QString Config::updateOrderSoundPath() +{ + m_mutex.lock(); + QString path = m_settings->value("Server/UpdateOrderSoundPath").toString(); + m_mutex.unlock(); + return path; +} + +void Config::setUpdateOrderSoundEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Server/UpdateOrderSoundEnable", enable); + m_mutex.unlock(); +} + +void Config::setUpdateOrderSoundPath(QString path) +{ + m_mutex.lock(); + m_settings->setValue("Server/UpdateOrderSoundPath", path); + m_mutex.unlock(); +} + + + + +bool Config::pushFailedSoundEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Server/PushFailedSoundEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +QString Config::pushFailedSoundPath() +{ + m_mutex.lock(); + QString path = m_settings->value("Server/PushFailedSoundPath").toString(); + m_mutex.unlock(); + return path; +} + +void Config::setPushFailedSoundEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Server/PushFailedSoundEnable", enable); + m_mutex.unlock(); +} + +void Config::setPushFailedSoundPath(QString path) +{ + m_mutex.lock(); + m_settings->setValue("Server/PushFailedSoundPath", path); + m_mutex.unlock(); +} + + + + + +bool Config::exitSoundEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Server/ExitSoundEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +QString Config::exitSoundPath() +{ + m_mutex.lock(); + QString path = m_settings->value("Server/ExitSoundPath").toString(); + m_mutex.unlock(); + return path; +} + +void Config::setExitSoundEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Server/ExitSoundEnable", enable); + m_mutex.unlock(); +} + +void Config::setExitSoundPath(QString path) +{ + m_mutex.lock(); + m_settings->setValue("Server/ExitSoundPath", path); + m_mutex.unlock(); +} + +bool Config::reloginSoundEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Server/ReloginSoundEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +QString Config::reloginSoundPath() +{ + m_mutex.lock(); + QString path = m_settings->value("Server/ReloginSoundPath").toString(); + m_mutex.unlock(); + return path; +} + +void Config::setReloginSoundEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Server/ReloginSoundEnable", enable); + m_mutex.unlock(); +} + +void Config::setReloginSoundPath(QString path) +{ + m_mutex.lock(); + m_settings->setValue("Server/ReloginSoundPath", path); + m_mutex.unlock(); +} + +bool Config::softUpdateSoundEnable() +{ + m_mutex.lock(); + bool enable = m_settings->value("Server/SoftUpdateSoundEnable", true).toBool(); + m_mutex.unlock(); + return enable; +} + +QString Config::softUpdateSoundPath() +{ + m_mutex.lock(); + QString path = m_settings->value("Server/SoftUpdateSoundPath").toString(); + m_mutex.unlock(); + return path; +} + +void Config::setSoftUpdateSoundEnable(bool enable) +{ + m_mutex.lock(); + m_settings->setValue("Server/SoftUpdateSoundEnable", enable); + m_mutex.unlock(); +} + +void Config::setSoftUpdateSoundPath(QString path) +{ + m_mutex.lock(); + m_settings->setValue("Server/SoftUpdateSoundPath", path); + m_mutex.unlock(); +} + + +QList> Config::usersList() +{ + m_mutex.lock(); + QList> list = toMapList(m_settings->value("Server/UsersList").toString()); + m_mutex.unlock(); + return list; +} + +void Config::setUsersList(QList> list) +{ + m_mutex.lock(); + m_settings->setValue("Server/UsersList", toJson(list)); + m_mutex.unlock(); +} + + + + + + + + +bool Config::notice_status() +{ + m_mutex.lock(); + bool status = m_settings->value("Server/NoticeStatus", false).toBool(); + m_mutex.unlock(); + return status; +} + +void Config::set_notice_status(bool status) +{ + m_mutex.lock(); + m_settings->setValue("Server/NoticeStatus", QVariant::fromValue(status)); + m_mutex.unlock(); +} + +QString Config::notice_account() +{ + m_mutex.lock(); + QString account = m_settings->value("Server/NoticeAccount").toString(); + m_mutex.unlock(); + return account; +} + +void Config::set_notice_account(QString account) +{ + m_mutex.lock(); + m_settings->setValue("Server/NoticeAccount", QVariant::fromValue(account)); + m_mutex.unlock(); +} + + + + + +bool Config::hasOrder(QString TID) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + query.prepare("SELECT 1 FROM orders WHERE TID = ? LIMIT 1"); + query.addBindValue(TID); + if (!query.exec()) return false; + return query.next(); +} + + + + + + + +bool Config::addOrder(QMap order) +{ + // 下注时间:优先使用返回里的 DATETIME;没有则用 DATE + TIME 组装 + QString betTime = order.value("DATETIME"); + if (betTime.isEmpty()) { + betTime = dateFormat(order.value("DATE")) + " " + order.value("TIME"); + } + + // 读取时间:皇冠时间(本地 -12h) + QString read_time = QDateTime::currentDateTime().addSecs(-43200).toString("yyyy-MM-dd HH:mm:ss"); + + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + query.prepare( + "INSERT INTO orders(" + "TID, DATETIME, READ_DATETIME, NAME0, GT, WAGERS_TYPE, LEAGUE, " + "TEAM_H, TEAM_C, ORDER_TYPE, ORDER_CON, SCORE, IORATIO, GOLD, SRV_IP, " + "SESSION, STAGE, G_TIME, NUM_H, NUM_C,ODDF_TYPE,BET_TYPE" + ") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)" + ); + + query.addBindValue(order.value("TID")); + query.addBindValue(betTime); + query.addBindValue(read_time); + query.addBindValue(order.value("NAME0")); + query.addBindValue(order.value("GT")); + query.addBindValue(order.value("WAGERS_TYPE")); + query.addBindValue(order.value("LEAGUE")); + query.addBindValue(order.value("TEAM_H")); + query.addBindValue(order.value("TEAM_C")); + query.addBindValue(order.value("ORDER_TYPE")); + query.addBindValue(order.value("ORDER_CON")); + query.addBindValue(order.value("SCORE")); + query.addBindValue(order.value("IORATIO")); + query.addBindValue(order.value("GOLD")); + query.addBindValue(order.value("SRV_IP")); + query.addBindValue(order.value("SESSION")); + query.addBindValue(order.value("STAGE")); + query.addBindValue(order.value("G_TIME")); // 如需统一格式,可先转成 yyyy-MM-dd HH:mm:ss + query.addBindValue(order.value("NUM_H")); + query.addBindValue(order.value("NUM_C")); + query.addBindValue(order.value("ODDF_TYPE")); + query.addBindValue(order.value("BET_TYPE")); + + bool ok = query.exec(); + if (!ok) { + qDebug() << "sql(insert orders) ok:" << ok + << " tid:" << order.value("TID") + << " err:" << query.lastError().text(); + } + else { + // qDebug() << "sql(insert orders) ok:" << ok << " tid:" << order.value("TID"); + } + return ok; +} +void Config::addFollowOrder(QString TID) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + query.prepare("INSERT INTO follow(TID) VALUES(?)"); + query.addBindValue(TID); + query.exec(); +} + +// 列位序: +// 0 TID, 1 DATETIME, 2 READ_DATETIME, 3 NAME0, 4 GT, 5 WAGERS_TYPE, 6 LEAGUE, +// 7 TEAM_H, 8 TEAM_C, 9 ORDER_TYPE, 10 ORDER_CON, 11 SCORE, 12 IORATIO, 13 GOLD, +// 14 SRV_IP, 15 SESSION, 16 STAGE, 17 G_TIME, 18 NUM_H, 19 NUM_C +QString Config::readOrder(QString sign, QString startTime, int count) +{ + QMutexLocker locker(&m_mutex); + QList> list; + + QSqlQuery query(m_db); + query.setForwardOnly(true); + + // 动态SQL:startTime 为空则不加时间条件 + QString sql = + "SELECT * FROM orders " + "WHERE (orders.TID NOT IN (SELECT TID FROM note WHERE note.sign = :sign) " + " AND orders.TID NOT IN (SELECT TID FROM follow) "; + if (!startTime.trimmed().isEmpty()) { + sql += " AND orders.DATETIME > :dt "; + } + sql += ") ORDER BY TID ASC LIMIT :limit"; + + if (!query.prepare(sql)) { + qDebug() << "[数据库] readOrder 预处理失败:" << query.lastError(); + return toJson(list); + } + + query.bindValue(":sign", sign); + if (!startTime.trimmed().isEmpty()) { + query.bindValue(":dt", startTime.trimmed()); // 期望格式: "yyyy-MM-dd HH:mm:ss" + } + query.bindValue(":limit", count); + + if (!query.exec()) { + qDebug() << "[数据库] readOrder 执行失败:" << query.lastError(); + return toJson(list); + } + + while (query.next()) { + QMap map; + map["TID"] = query.value(0).toString(); + map["DATETIME"] = query.value(1).toString(); + map["READ_DATETIME"] = query.value(2).toString(); + map["NAME0"] = query.value(3).toString(); + map["GT"] = query.value(4).toString(); + map["WAGERS_TYPE"] = query.value(5).toString(); + map["LEAGUE"] = query.value(6).toString(); + map["TEAM_H"] = query.value(7).toString(); + map["TEAM_C"] = query.value(8).toString(); + map["ORDER_TYPE"] = query.value(9).toString(); + map["ORDER_CON"] = query.value(10).toString(); + map["SCORE"] = query.value(11).toString(); + map["IORATIO"] = QString::number(query.value(12).toDouble()); + map["GOLD"] = QString::number(query.value(13).toDouble()); + map["SRV_IP"] = query.value(14).toString(); + map["SESSION"] = query.value(15).toString(); + map["STAGE"] = query.value(16).toString(); + map["G_TIME"] = query.value(17).toString(); + map["NUM_H"] = query.value(18).toString(); + map["NUM_C"] = query.value(19).toString(); + map["ODDF_TYPE"] = query.value(20).toString(); + map["BET_TYPE"] = query.value(21).toString(); + + list.append(map); + + QSqlQuery insert(m_db); + insert.prepare("INSERT INTO note(sign, TID) VALUES(:sign, :tid)"); + insert.bindValue(":sign", sign); + insert.bindValue(":tid", map["TID"]); + insert.exec(); + } + + return toJson(list); +} +QList> Config::readAllOrder() +{ + QMutexLocker locker(&m_mutex); + QList> list; + + QSqlQuery query(m_db); + query.setForwardOnly(true); + query.exec("SELECT * FROM orders"); + + while (query.next()) { + QMap map; + map["TID"] = query.value(0).toString(); + map["DATETIME"] = query.value(1).toDateTime().toString("yyyy-MM-dd HH:mm:ss"); + map["READ_DATETIME"] = query.value(2).toDateTime().toString("yyyy-MM-dd HH:mm:ss"); + map["NAME0"] = query.value(3).toString(); + map["GT"] = query.value(4).toString(); + map["WAGERS_TYPE"] = query.value(5).toString(); + map["LEAGUE"] = query.value(6).toString(); + map["TEAM_H"] = query.value(7).toString(); + map["TEAM_C"] = query.value(8).toString(); + map["ORDER_TYPE"] = query.value(9).toString(); + map["ORDER_CON"] = query.value(10).toString(); + map["SCORE"] = query.value(11).toString(); + map["IORATIO"] = QString::number(query.value(12).toDouble()); + map["GOLD"] = QString::number(query.value(13).toDouble()); + map["SRV_IP"] = query.value(14).toString(); + map["SESSION"] = query.value(15).toString(); + map["STAGE"] = query.value(16).toString(); + map["G_TIME"] = query.value(17).toString(); + map["NUM_H"] = query.value(18).toString(); + map["NUM_C"] = query.value(19).toString(); + map["ODDF_TYPE"] = query.value(20).toString(); + map["BET_TYPE"] = query.value(21).toString(); + list.append(map); + } + return list; +} + +bool Config::delete_order(QString TID) +{ + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + query.prepare("DELETE FROM orders WHERE TID = ?"); + query.addBindValue(TID); + return query.exec(); +} +bool Config::delete_order_by_date(QString date) +{ + // date 传入格式:yyyy-MM-dd + QMutexLocker locker(&m_mutex); + QSqlQuery query(m_db); + query.prepare("DELETE FROM orders WHERE DATE(DATETIME) = ?"); + query.addBindValue(date); + return query.exec(); +} diff --git a/CrownServer/Config.h b/CrownServer/Config.h new file mode 100644 index 0000000..35fda6d --- /dev/null +++ b/CrownServer/Config.h @@ -0,0 +1,184 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +class Config : public QObject +{ + Q_OBJECT +public: + Config(); + ~Config(); + +private: + QMutex m_mutex; + QSettings* m_settings; +public: + QString toJson(QList> data); + QString toJson(QList data); + QList> toMapList(QString data); + QList toStringList(QString data); + +public: + QString verifyUsername(); + void setVerifyUsername(QString username); + QString verifyPassword(); + void setVerifyPassword(QString password); + bool autoLogin(); + void setAutoLogin(bool autoLogin); +public: + bool crownTime(); + void setCrownTime(bool crownTime); +public: + int readDays(); + void setReadDays(int days); + bool readNormalOrder(); + void setReadNormalOrder(bool enable); + bool readPhoneOrder(); + void setReadPhoneOrder(bool enable); +public: + // new + QList> screen_list(); + void set_screen_list(QList> list); + + + + QList acceptUserList(); + QList screenUserList(); + void setAcceptUserList(QList list); + void setScreenUserList(QList list); + + + + QList> screenUsernameList(); + void setScreenUsernameList(QList> list); + bool screenEnable(); + void setScreenEnable(bool enable); + int screenMode(); + void setScreenMode(int mode); +public: + QString ip(); + void setIp(QString ip); + QList ipList(); + void setIpList(QList list); + QString port(); + void setPort(QString port); + QList portList(); + void setPortList(QList list); + QString connectPassword(); + void setConnectPassword(QString password); + QString agentUrl(); + void setAgentUrl(QString url); + QList agentUrlList(); + QList userUrlList(); + void setAgentUrlList(QList list); + void setUserUrlList(QList list); + QString username(); + void setUsername(QString username); + QString password(); + void setPassword(QString password); + QString level(); + void setLevel(QString level); + QString safeCode(); + void setSafeCode(QString safeCode); +public: + + int readReportListInterValMin(); + int readReportListInterValMax(); + int readReportListInterVal(); + void setReadReportListIntervalMin(int msec); + void setReadReportListIntervalMax(int msec); + + int readUserListInterValMin(); + int readUserListInterValMax(); + int readUserListInterVal(); + void setReadUserListIntervalMin(int msec); + void setReadUserListIntervalMax(int msec); + + int readOrderListInterValMin(); + int readOrderListInterValMax(); + int readOrderListInterVal(); + void setReadOrderListIntervalMin(int msec); + void setReadOrderListIntervalMax(int msec); + + // 掉线重连延时 + int disconnectedSleepMin(); + int disconnectedSleepMax(); + int disconnectedSleep(); + void setDisconnectedSleepMin(int value); + void setDisconnectedSleepMax(int value); + + // 失败重连延时 + int failedSleepMin(); + int failedSleepMax(); + int failedSleep(); + void setFailedSleepMin(int value); + void setFailedSleepMax(int value); + + + // 失败重连次数 + int failedReconnectTimes(); + void setFailedReconnectTimes(int value); + + + bool updateOrderSoundEnable(); + QString updateOrderSoundPath(); + void setUpdateOrderSoundEnable(bool value); + void setUpdateOrderSoundPath(QString path); + + bool pushFailedSoundEnable(); + QString pushFailedSoundPath(); + void setPushFailedSoundEnable(bool value); + void setPushFailedSoundPath(QString path); + + bool exitSoundEnable(); + QString exitSoundPath(); + void setExitSoundEnable(bool value); + void setExitSoundPath(QString path); + + bool reloginSoundEnable(); + QString reloginSoundPath(); + void setReloginSoundEnable(bool value); + void setReloginSoundPath(QString path); + + bool softUpdateSoundEnable(); + QString softUpdateSoundPath(); + void setSoftUpdateSoundEnable(bool value); + void setSoftUpdateSoundPath(QString path); +public: + // 通知状态 + bool notice_status(); + // 设置通知状态 + void set_notice_status(bool status); + // 通知账户 + QString notice_account(); + // 设置通知账户 + void set_notice_account(QString account); + +public: + QList> usersList(); + void setUsersList(QList>); + //订单数据库 +private: + QSqlDatabase m_db; +public: + bool hasOrder(QString TID); + bool addOrder(QMap order); + void addFollowOrder(QString TID); + QString readOrder(QString sign, QString startTime, int count); + QList> readAllOrder(); + bool delete_order(QString TID); + bool delete_order_by_date(QString date); +public: + void database_insertLog(QString datetime, QString type, QString log); + //QList> database_readLogList(); + //void database_deleteLogs(); + +}; \ No newline at end of file diff --git a/CrownServer/Constant.h b/CrownServer/Constant.h new file mode 100644 index 0000000..c1189b9 --- /dev/null +++ b/CrownServer/Constant.h @@ -0,0 +1,69 @@ +#pragma once +#include +#include + + +static const long INIT_NUMBER = -1; + +//包数据结构 : [ 包头 + 长度(8字节) + 包类型(2字节) + 数据 + 包尾 ] +static const char* NET_PACKET_START = "PACKET_START"; +static const char* NET_PACKET_END = "PACKET_END"; +static const int NET_PACKET_TYPE_BYTES = 2; //包类型占几个字节 +static const int NET_PACKET_LENGTH_BYTES = 8; //包数据长度占几个字节 + +//包类型 +static const char* NET_PACKET_TYPE_SEND_FILE = "01"; //发送文件 +static const char* NET_PACKET_TYPE_SEND_TEXT = "02"; //发送文本 + +//用于存储接收到的数据包 +class SocketPacket +{ +public: + long length; //数据长度 + QByteArray data; //数据 + QByteArray dataType; //数据类型 + + SocketPacket() + { + length = INIT_NUMBER; + } + + void clear() + { + length = INIT_NUMBER; + data.clear(); + dataType.clear(); + } +}; + +struct NetSendFile +{ + QString m_filename; + QByteArray m_bytearray; + friend QDataStream& operator>>(QDataStream& in, NetSendFile& stru) + { + in >> stru.m_filename >> stru.m_bytearray; + return in; + } + friend QDataStream& operator<<(QDataStream& out, const NetSendFile& stru) + { + out << stru.m_filename << stru.m_bytearray; + return out; + } +}; + +class NetSendText +{ +public: + QString m_text; + friend QDataStream& operator>>(QDataStream& in, NetSendText& stru) + { + in >> stru.m_text; + return in; + } + friend QDataStream& operator<<(QDataStream& out, const NetSendText& stru) + { + out << stru.m_text; + return out; + } +}; diff --git a/CrownServer/Crown.vcxproj b/CrownServer/Crown.vcxproj new file mode 100644 index 0000000..84a6092 --- /dev/null +++ b/CrownServer/Crown.vcxproj @@ -0,0 +1,275 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {67E7A149-F86D-481B-AF61-E98BA438B8C4} + QtVS_v304 + 10.0.19041.0 + 10.0 + 10.0.19041.0 + 10.0 + $(MSBuildProjectDirectory)\QtMsBuild + CrownServer + + + + Application + v142 + + + Application + v143 + + + Application + v142 + + + Application + v143 + + + + + + + core;sql;network;gui;multimedia;widgets;concurrent;webengine;webenginewidgets;webview + debug + true + false + 5.15.2_msvc2019_64 + + + core;sql;network;gui;multimedia;widgets;webengine;webenginewidgets;webview + debug + true + false + 5.12.2_msvc2017 + + + 5.15.2_msvc2019_64 + core;sql;network;gui;multimedia;widgets;concurrent;webengine;webenginewidgets;networkauth + release + true + + + 5.9.9_msvc2015 + core;sql;network;gui;multimedia;widgets;webengine;webenginewidgets + release + true + + + + + + + + + + + + + + + + + + + + + + + + + $(IncludePath) + $(LibraryPath) + + + $(IncludePath) + $(LibraryPath) + + + + + + /utf-8 + D:\reverse\vmprotect33\Include\C;%(AdditionalIncludeDirectories) + + + D:\reverse\vmprotect33\Lib\Windows;%(AdditionalLibraryDirectories) + + + + + /utf-8 + + + + + + /utf-8 %(AdditionalOptions) + MultiThreadedDLL + D:\reverse\vmprotect33\Include\C;%(AdditionalIncludeDirectories) + + + D:\reverse\vmprotect33\Lib\Windows;%(AdditionalLibraryDirectories) + + + + + + /utf-8 %(AdditionalOptions) + + + + + true + true + ProgramDatabase + Disabled + + + Windows + true + + + + + true + true + ProgramDatabase + Disabled + MultiThreadedDebugDLL + + + Windows + true + + + + + true + true + None + MaxSpeed + + + Windows + false + + + + + true + true + None + MaxSpeed + MultiThreadedDLL + + + Windows + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/CrownServer/Crown.vcxproj.filters b/CrownServer/Crown.vcxproj.filters new file mode 100644 index 0000000..6407195 --- /dev/null +++ b/CrownServer/Crown.vcxproj.filters @@ -0,0 +1,298 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + qml;cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + qrc;rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + {639EADAA-A684-42e4-A9AD-28FC9BCB8F7C} + ts + + + {4e39d59b-7d11-4fbc-8fe1-c702a63bd82e} + + + {55a31899-39fc-40a6-bb48-17d62276741e} + + + {08300ac7-793a-414b-a129-6d6042208546} + + + {0c3de194-56a7-402c-86f0-c0deaf6a8559} + + + {a68d20ab-31d2-48c3-adf4-d73061744f94} + + + {617af581-f427-437f-9450-dcf7cd4f007a} + + + {52ac7f1f-fdcd-4a95-bcd3-53b0805355b9} + + + {35da1c43-7969-4e3d-92fe-26df7e1d62c8} + + + {2ca90531-e83c-4b28-99f1-e4385b0c0a68} + + + {96e48344-70f6-44c8-b09e-3e0ce751debd} + + + {a7ed3041-9d8b-4474-8003-3045c170a5af} + + + {2fa7faac-6feb-4e2d-aa65-7fae9491b467} + + + {673239c3-f7d0-43f7-bd3d-47ff9492611a} + + + {490be768-aa3d-4165-9d7b-c0265d44361b} + + + {8effe380-58f9-462b-81df-596d5455e1a5} + + + {57c67bf8-33a7-4b61-8f04-f2a3167ee03a} + + + {5df2509a-1838-4708-a573-584a501d6975} + + + {bd108902-c702-4063-a236-ceadc68ee955} + + + {f9f295ff-3b8d-4d0b-8c55-0ee2e528ac08} + + + {4b6ab513-ce4f-4e7e-a602-dd5dabdf64b9} + + + {11fe7662-f96b-4e75-83ce-140ff77da5bb} + + + + + Header Files\Form\Setting + + + Header Files\Form\Screen + + + Header Files\Form\Server + + + Header Files\Form\User + + + Header Files\TCP + + + Header Files\Platform + + + Header Files\Platform + + + Header Files\CustomUI\StandardModel + + + Header Files\AppInstanceManager + + + Header Files\Platform + + + Header Files\CustomUI\TreeView + + + Header Files\CustomUI\TreeView + + + Header Files\Form\Notice + + + Header Files\PushMsg + + + + + Source Files + + + Header Files\Verify + + + Source Files + + + Header Files\CustomUI\CheckBoxHeaderView + + + Header Files\CustomUI\ComboBox + + + Header Files\CustomUI\ComboBox + + + Header Files\Config + + + Header Files\TCP + + + Header Files\TCP + + + Header Files\Form\Login + + + Header Files\Form\Server + + + Header Files\Form\Setting + + + Header Files\Form\Screen + + + Header Files\CustomUI\WebEnginePage + + + Header Files\Form\User + + + Header Files\TCP + + + Header Files\Utils + + + Header Files\Platform + + + Header Files\Platform + + + Header Files\CustomUI\StandardModel + + + Header Files\AppInstanceManager + + + Header Files\Platform + + + Header Files\CustomUI\TreeView + + + Header Files\CustomUI\TreeView + + + Header Files\Form\Notice + + + Header Files\PushMsg + + + + + Header Files\Verify + + + Header Files\CustomUI\CheckBoxHeaderView + + + Header Files\CustomUI\ComboBox + + + Header Files\CustomUI\ComboBox + + + Header Files\Config + + + Header Files\TCP + + + Header Files\TCP + + + Header Files\Form\Login + + + + + Header Files + + + Header Files + + + Header Files\CustomUI\WebEnginePage + + + Header Files\TCP + + + Source Files + + + Header Files\Utils + + + Header Files + + + Header Files\MessageHandle + + + + + Header Files\Form\Login + + + Header Files\Form\Server + + + Header Files\Form\Setting + + + Header Files\Form\Screen + + + Header Files\Form\User + + + Header Files\Form\Notice + + + + + Resource Files + + + + + Resource Files + + + + + Resource Files + + + Resource Files + + + \ No newline at end of file diff --git a/CrownServer/CrownServer.cpp b/CrownServer/CrownServer.cpp new file mode 100644 index 0000000..0591566 --- /dev/null +++ b/CrownServer/CrownServer.cpp @@ -0,0 +1,2071 @@ +#include "CrownServer.h" +#include "Global.h" +#include +#include "Screen.h" +#include "Setting.h" +#include "ComboBox.h" +#include "WebEnginePage.h" +#include "User.h" +#include +#include +#include +#include +#include "Utils.h" + +#include +#include +#include +#include "AppInstanceManager.h" + +#include +#include "PushMsg.h" + + +CrownServer::CrownServer(QWidget* parent) + : QMainWindow(parent) +{ + +#ifdef _DEBUG + ///////////////////////////////////////////////////// + // 调试窗口 + ///////////////////////////////////////////////////// + //QWidget* debug_window = new QWidget(nullptr); + //QVBoxLayout* layout = new QVBoxLayout(debug_window); + + //QWebEngineView* debug = new QWebEngineView(); + //layout->addWidget(debug); + //debug_window->setLayout(layout); + //debug->load(QUrl("http://localhost:7777/")); \ + // debug_window->show(); +#endif + + + + ui.setupUi(this); + + + ///////////////////////////////////////////////////// + // 应用接口管理(防止多开) + ///////////////////////////////////////////////////// + connect(AppInstanceManager::instance(), &AppInstanceManager::raiseRequested, + this, [this]() { + showNormal(); // 双击托盘图标恢复窗口 + //show(); + raise(); + activateWindow(); + }); + + ///////////////////////////////////////////////////// + // 托盘设置 + ///////////////////////////////////////////////////// + m_tray_icon = new QSystemTrayIcon(this); + m_tray_icon->setIcon(QIcon(":/CrownServer/Resources/server.ico")); + m_tray_icon->setToolTip("金运来皇冠跟单软件(服务端)"); + // 创建托盘菜单 + QMenu *trayMenu = new QMenu(this); + trayMenu->addAction("恢复", this, &CrownServer::showNormal); + trayMenu->addAction("退出", this, &CrownServer::close); // 改为调用quit()而不是close() + m_tray_icon->setContextMenu(trayMenu); + m_tray_icon->show(); + // 连接托盘图标点击事件 + connect(m_tray_icon, &QSystemTrayIcon::activated, this, &CrownServer::tray_activated); + + + ////////////////////////////////////////////////////// + // 心跳定时器 + ////////////////////////////////////////////////////// + m_heartbeatTimer = new QTimer(this); + connect(m_heartbeatTimer, &QTimer::timeout, this, &CrownServer::heartbeat); + m_heartbeatTimer->start(15000); // 15秒一次 + + + + ///////////////////////////////////////////////////// + // 窗口设置 + ///////////////////////////////////////////////////// + setWindowIcon(QIcon(":/CrownServer/Resources/server.ico")); + setWindowTitle(QString("金运来皇冠跟单软件(服务端) ") + QString(VERSION)); + // 创建子窗口 + m_screen_window = new Screen(); + connect(m_screen_window, &Screen::signal_extract_user_list,this, &CrownServer::extract_accounts); + connect(this, &CrownServer::extract_account_finish, m_screen_window, &Screen::slotUpdateUserList); + m_config = new Setting(); + m_user = new User(); + m_notice_window = new Notice(); + connect(ui.button_notice, &QPushButton::clicked, m_notice_window, &QWidget::show); + // connect(CrownServer::button_notice, QPushB); + + ui.urlCombo->addItems(g_config->agentUrlList()); + ui.urlCombo->setCurrentText(g_config->agentUrl()); + + ui.portCombo->addItems(g_config->portList()); + ui.comPasswordEdit->setText(g_config->connectPassword()); + ui.usernameEdit->setText(g_config->username()); + ui.passwordEdit->setText(g_config->password()); + ui.levelCombo->setCurrentText(g_config->level()); + + + ui.portCombo->setCurrentText(g_config->port()); + ui.safeCodeEdit->setText(g_config->safeCode()); + + + m_login_timer = new QTimer(this); + connect(m_login_timer, &QTimer::timeout, this, &CrownServer::read_web_parameter_login); + + // 开始按钮 + connect(ui.startButton, &QPushButton::clicked, this, &CrownServer::start_task); + // 停止按钮 + connect(ui.stopButton, &QPushButton::clicked, this, &CrownServer::stop_task); + // 登录按钮 + //connect(ui.loginButton, &QPushButton::clicked, this, &CrownServer::login_account); + // 登录按钮 + connect(ui.loginButton, &QPushButton::clicked, this, [=]() { + QString username = ui.usernameEdit->text(); + QString password = ui.passwordEdit->text(); + QString level = ui.levelCombo->currentText(); + QString safeCode = ui.safeCodeEdit->text(); + emit add_account_record(username, password, level, safeCode); + ui.webEngineView->page()->load(ui.urlCombo->currentText()); + if (m_login_timer && !m_login_timer->isActive()) + { + m_login_timer->start(3000); + + } + + + }); + connect(ui.screenButton, &QPushButton::clicked, m_screen_window, &QWidget::show); + connect(ui.configButton, &QPushButton::clicked, m_config, &QWidget::show); + connect(ui.userManagerButton, &QPushButton::clicked, m_user, &QWidget::show); + connect(this, &CrownServer::add_account_record, m_user, &User::slotAddUser); + // 快捷设置账户 + connect(m_user, &User::signalSetUser, this, &CrownServer::set_account); + connect(ui.startButton, &QPushButton::clicked, this, [=]() { + QString username = ui.usernameEdit->text(); + QString password = ui.passwordEdit->text(); + QString level = ui.levelCombo->currentText(); + QString safeCode = ui.safeCodeEdit->text(); + emit add_account_record(username, password, level, safeCode); + }); + + ///////////////////////////////////////////////////// + // 到期时间设置 + ///////////////////////////////////////////////////// + ui.endtimeLabel->setText( + QString("

软件登录账号: %1 软件到期时间: %2

") + .arg(g_verify->Username()) + .arg(g_verify->GetDueTime().toString("yyyy-MM-dd hh:mm:ss")) + ); + + ///////////////////////////////////////////////////// + // 时区切换 + ///////////////////////////////////////////////////// + if (g_config->crownTime()) + { + ui.crownTimeButton->setIcon(QIcon(":/CrownServer/Resources/crownTime.png")); + ui.crownTimeButton->setText("皇冠时间"); + QPalette palette; + palette.setColor(QPalette::ButtonText, QColor(Qt::red)); + ui.crownTimeButton->setPalette(palette); + } + else + { + ui.crownTimeButton->setIcon(QIcon(":/CrownServer/Resources/LocalTime.png")); + ui.crownTimeButton->setText("本地时间"); + QPalette palette; + palette.setColor(QPalette::ButtonText, QColor(QRgb(0x008000))); + ui.crownTimeButton->setPalette(palette); + } + connect(ui.crownTimeButton, &QPushButton::clicked, this, [=]() { + // 切换时间设置 + bool isCrownTime = !g_config->crownTime(); + g_config->setCrownTime(isCrownTime); + + // 更新按钮UI + if (isCrownTime) { + ui.crownTimeButton->setIcon(QIcon(":/CrownServer/Resources/crownTime.png")); + ui.crownTimeButton->setText("皇冠时间"); + QToolTip::showText(ui.crownTimeButton->mapToGlobal(ui.crownTimeButton->rect().bottomLeft()), + "当前设置为皇冠时间"); + + QPalette palette; + palette.setColor(QPalette::ButtonText, QColor(Qt::red)); + ui.crownTimeButton->setPalette(palette); + } + else { + ui.crownTimeButton->setIcon(QIcon(":/CrownServer/Resources/LocalTime.png")); + ui.crownTimeButton->setText("本地时间"); + QToolTip::showText(ui.crownTimeButton->mapToGlobal(ui.crownTimeButton->rect().bottomLeft()), + "当前设置为本地时间"); + + QPalette palette; + palette.setColor(QPalette::ButtonText, QColor(QRgb(0x008000))); + ui.crownTimeButton->setPalette(palette); + } + + // 更新订单树视图中的时间显示 + view_time_zone_change(isCrownTime); + }); + + // 在创建 WebEngineView 之前设置 + // QWebEngineProfile::defaultProfile()->setHttpAcceptLanguage("zh-CN,zh;q=0.9"); + + ///////////////////////////////////////////////////// + // 浏览器设置 + ///////////////////////////////////////////////////// + // 重写Page屏蔽SSL证书错误 + WebEnginePage* page = new WebEnginePage(ui.webEngineView); + page->profile()->setHttpAcceptLanguage("zh-CN,zh;q=0.9"); + ui.webEngineView->setPage(page); + // 禁用浏览器右键菜单 + ui.webEngineView->setContextMenuPolicy(Qt::NoContextMenu); + // 设置访问地址 + if (!ui.urlCombo->currentText().isEmpty()) + { + // qDebug() << "设置默认网址:" << ui.urlCombo->currentText(); + ui.webEngineView->load(QUrl(ui.urlCombo->currentText())); + } + + connect(ui.webEngineView, &QWebEngineView::loadFinished, this, [&](bool ok) { + + // 网页访问失败 + if (!ok) + { + qDebug() << "Page load finished:" << (ok ? "Success" : "Failed") << " " << ui.webEngineView->page()->url(); + } + }); + + + ///////////////////////////////////////////////////// + // 树形表格设置 + ///////////////////////////////////////////////////// + + // 创建订单数据模型 + m_orderModel = new QStandardItemModel(ui.order_tree_view); + // 绑定订单数据模型到视图 + ui.order_tree_view->setModel(m_orderModel); + // 设置水平表头列宽度根据内容变化 + ui.order_tree_view->header()->setSectionResizeMode(QHeaderView::ResizeToContents); + // 设置可排序 + ui.order_tree_view->setSortingEnabled(true); + // 添加订单列标题 + m_orderModel->setHorizontalHeaderLabels({ "单号/场次","下注时间","读取时间","会员/代理","项目","类型","联赛/队伍","下注","盘口","赔率","金额" }); + // 创建一个QSortFilterProxyModel作为代理模型 + m_orderProxyModel = new QSortFilterProxyModel(); + // 设置代理模型的源模型为我们创建的数据模型 + m_orderProxyModel->setSourceModel(m_orderModel); + // 将QTreeView的模型设置为代理模型 + ui.order_tree_view->setModel(m_orderProxyModel); + // 启用代理模型的排序功能 + m_orderProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); + m_orderProxyModel->setDynamicSortFilter(true); + //ui.order_tree_view->setSelectionMode(QAbstractItemView::MultiSelection); + ui.order_tree_view->setEditTriggers(QAbstractItemView::NoEditTriggers); + + + // 建立数据模型对象空间并指定父对象 + m_logModel = new QStandardItemModel(ui.log_tree_view); + // 绑定数据模型到树形视图上 + ui.log_tree_view->setModel(m_logModel); + // 设置水平表头列宽度根据内容变化 + ui.log_tree_view->header()->setSectionResizeMode(QHeaderView::ResizeToContents); + // 设置可排序 + ui.log_tree_view->setSortingEnabled(true); + // 添加列标题 + m_logModel->setHorizontalHeaderLabels({ "时间","类型","日志" }); + // 创建一个QSortFilterProxyModel作为代理模型 + m_logProxyModel = new QSortFilterProxyModel(); + // 设置代理模型的源模型为我们创建的数据模型 + m_logProxyModel->setSourceModel(m_logModel); + // 将QTreeView的模型设置为代理模型 + ui.log_tree_view->setModel(m_logProxyModel); + // 启用代理模型的排序功能 + m_logProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); + m_logProxyModel->setDynamicSortFilter(true); + //ui.log_tree_view->setSelectionMode(QAbstractItemView::MultiSelection); + ui.log_tree_view->setEditTriggers(QAbstractItemView::NoEditTriggers); + + + + + ///////////////////////////////////////////////////// + // 参数获取 + ///////////////////////////////////////////////////// + m_paramerTimer = new QTimer(this); + connect(m_paramerTimer, &QTimer::timeout, this, &CrownServer::read_web_parameter); + // 初始化变量 + m_state = wait; + + + + + + //connect(m_order_thread, &OrderThread::account_disconnect, this, &CrownServer::on_disconnected); + + + + + // 读取数据库注单 + QList> history_order_list = g_config->readAllOrder(); + for (int i = 0; i < history_order_list.count(); i++) + { + view_add_order(history_order_list[i]); + + } + + // 初始化变量 + m_read_count = 0; + m_read_times = 0; + m_failed_reconnect_times = 0; + + + ///////////////////////////////////////////////////// + // 右键菜单 + ///////////////////////////////////////////////////// + + //打开右键菜单属性 + ui.order_tree_view->setContextMenuPolicy(Qt::CustomContextMenu); + + //右键菜单 + m_order_tree_menu = new QMenu(ui.order_tree_view); + QAction* delete_order = m_order_tree_menu->addAction("删除所选注单"); + QAction* clear_order = m_order_tree_menu->addAction("清空"); + + connect(ui.order_tree_view, &QTreeView::customContextMenuRequested, this, [&](const QPoint& pos) { + QModelIndex curIndex = ui.order_tree_view->indexAt(pos); + QModelIndex index = curIndex.sibling(curIndex.row(), 0); + if (curIndex.isValid()) + { + QMenu menu; + menu.addAction("删除", [&]() { + if (index.parent() == ui.order_tree_view->rootIndex()) + { + //qDebug() << "一级节点"; + QStandardItem *item = m_orderModel->item(index.row()); + for (int i = 0; i < item->rowCount(); i++) + { + QStandardItem *sub_item = item->child(i); + QString TID = sub_item->text(); + //qDebug() << sub_item->text(); + g_config->delete_order(TID); + } + m_orderModel->removeRow(item->row()); + } + else + { + //qDebug() << "子节点"; + QModelIndex parentIndex = curIndex.parent(); + QStandardItem *parentItem = m_orderModel->item(parentIndex.row(), 0); + + // 先删除子节点数据 + QStandardItem *childItem = parentItem->child(curIndex.row()); + QString TID = childItem->text(); + g_config->delete_order(TID); + + // 删除子节点 + parentItem->removeRow(curIndex.row()); + + // 检查父节点是否还有子节点 + if (parentItem->rowCount() == 0) { + // 如果没有子节点了,删除父节点 + m_orderModel->removeRow(parentIndex.row()); + } + } + }); + + menu.addSeparator(); + menu.addAction("清空", this, [&]() { + // 先删除数据库中所有订单 + QAbstractItemModel* model = ui.order_tree_view->model(); + + // 遍历所有一级节点 + for (int i = 0; i < model->rowCount(); ++i) { + QModelIndex parentIndex = model->index(i, 0); + // 遍历所有子节点 + for (int j = 0; j < model->rowCount(parentIndex); ++j) { + QModelIndex childIndex = model->index(j, 0, parentIndex); + QString TID = childIndex.data().toString(); + g_config->delete_order(TID); + } + } + + // 清空模型数据 + model->removeRows(0, model->rowCount()); + }); + + menu.exec(QCursor::pos()); + } + }); + + + + + + view_add_log("程序执行", "初始化完成"); + + + + + +} + +CrownServer::~CrownServer() +{ + // 停止并释放 TCP 服务器 + if (m_tcp_server) { + //qDebug() << "释放 TCP 服务器"; + m_tcp_server->disconnect(); + m_tcp_server->close(); + delete m_tcp_server; + m_tcp_server = nullptr; + } + + // 停止并等待线程结束 + //if (m_order_thread) { + // qDebug() << "停止订单线程"; + // m_order_thread->exit(); + // m_order_thread->wait(); // 等待线程结束 + // delete m_order_thread; + // m_order_thread = nullptr; + //} + + if (m_report_thread) { + //qDebug() << "停止订单线程"; + m_report_thread->exit(); + m_report_thread->wait(); // 等待线程结束 + delete m_report_thread; + m_report_thread = nullptr; + } + + if (m_user_thread) { + //qDebug() << "停止用户线程"; + m_user_thread->exit(); + m_user_thread->wait(); // 等待线程结束 + delete m_user_thread; + m_user_thread = nullptr; + } + + if (m_url_thread) { + //qDebug() << "停止URL线程"; + m_url_thread->exit(); + m_url_thread->wait(); // 等待线程结束 + delete m_url_thread; + m_url_thread = nullptr; + } + + + // 停止定时器 + if (m_paramerTimer) { + //qDebug() << "停止参数定时器"; + m_paramerTimer->stop(); + delete m_paramerTimer; + m_paramerTimer = nullptr; + } + + // 释放子窗口 + if (m_screen_window) { + //qDebug() << "释放筛选窗口"; + delete m_screen_window; + m_screen_window = nullptr; + } + + + + //qDebug() << "CrownServer 析构完成"; +} + +void CrownServer::view_connect_state_change(int state) +{ + if (state == -1) + { + ui.stateButton->setIcon(QIcon(":/images/Images/red.png")); + } + else if (state == 0) + { + ui.stateButton->setIcon(QIcon(":/images/Images/yellow.png")); + } + else if (state == 1) + { + ui.stateButton->setIcon(QIcon(":/images/Images/green.png")); + } + +} + +// 托盘点击事件 +void CrownServer::tray_activated(QSystemTrayIcon::ActivationReason reason) +{ + if (reason == QSystemTrayIcon::DoubleClick) { + showNormal(); // 双击托盘图标恢复窗口 + } +} + +void CrownServer::start_task() +{ + // 清空参数 + m_state = wait; + m_failed_reconnect_times = 0; + m_start_time = QDateTime::currentDateTime().toMSecsSinceEpoch(); + m_parameters.clear(); + // 检查必要参数 + if (ui.urlCombo->currentText().isEmpty()) + { + QMessageBox::critical(nullptr, "错误", "请填写网址"); + return; + } + + if (ui.usernameEdit->text().isEmpty() || ui.passwordEdit->text().isEmpty()) + { + QMessageBox::critical(nullptr, "错误", "请填写账号和密码"); + return; + + } + + // 创建TCP服务端 + m_tcp_server = new TcpServer(this); + qintptr port = ui.portCombo->currentText().toInt(); + if (!m_tcp_server->listen(QHostAddress::Any, port)) + { + QMessageBox::critical(this, "错误", "服务启动失败,请检查端口是否占用!"); + m_tcp_server->deleteLater(); + m_tcp_server = nullptr; + return; + } + connect(m_tcp_server, &TcpServer::signalDataRecv, this, &CrownServer::tcp_server_recv_data, Qt::QueuedConnection); + connect(this, &CrownServer::send_data, m_tcp_server, &TcpServer::slotSendData, Qt::QueuedConnection); + + // 修改标题 + setWindowTitle( + QString("金运来皇冠跟单软件(服务端) %1 - 服务端口:%2 服务密码:%3") + .arg(VERSION) + .arg(ui.portCombo->currentText()) + .arg(ui.comPasswordEdit->text()) + ); + + + ///////////////////////////////////////////////////// + // 工作线程(平台接口) + ///////////////////////////////////////////////////// + + + //m_user_thread = new UserThread(); + m_url_thread = new UrlThread(); + connect(m_url_thread, &UrlThread::signalUpdateAgentUrlList, this, &CrownServer::update_agent_url); + connect(m_url_thread, &UrlThread::signalUpdateUserUrlList, this, &CrownServer::update_client_url); + + // 创建工作线程 + m_report_thread = new ReportThread(); + connect(m_report_thread, &ReportThread::read, this, &CrownServer::view_update_read_times); + connect(m_report_thread, &ReportThread::update_orders, this, &CrownServer::read_orders); + // 掉线重连 + connect(m_report_thread, &ReportThread::account_disconnect, this, &CrownServer::disconnected); + //m_order_thread = new OrderThread(); + //connect(m_order_thread, &OrderThread::read, this, &CrownServer::view_update_read_times); + //connect(m_order_thread, &OrderThread::update_orders, this, &CrownServer::read_orders); + // 掉线重连 + //connect(m_order_thread, &OrderThread::account_disconnect, this, &CrownServer::disconnected); + + // 访问网址 + ui.webEngineView->page()->load(ui.urlCombo->currentText()); + if (!m_paramerTimer->isActive()) + { + m_paramerTimer->start(3000); + } + + // 按钮控制 + ui.startButton->setDisabled(true); + ui.screenButton->setDisabled(true); + ui.configButton->setDisabled(true); + ui.urlCombo->setDisabled(true); + ui.userManagerButton->setDisabled(true); + ui.stopButton->setDisabled(false); + ui.portCombo->setDisabled(true); + ui.comPasswordEdit->setDisabled(true); + ui.usernameEdit->setDisabled(true); + ui.passwordEdit->setDisabled(true); + ui.levelCombo->setDisabled(true); + ui.safeCodeEdit->setDisabled(true); + ui.loginButton->setDisabled(true); + +} + + +void CrownServer::handleNewConnection() { + QLocalSocket *socket = m_localServer->nextPendingConnection(); + if (socket && socket->waitForReadyRead(500)) { + QString command = QString::fromUtf8(socket->readAll()); + if (command == "activate_window") { + showNormal(); // 双击托盘图标恢复窗口 + } + } + socket->deleteLater(); +} + + +/// +/// 停止按钮槽函数 +/// +/// +/// 停止按钮槽函数 +/// +void CrownServer::stop_task() +{ + //qDebug() << "CrownServer 停止服务开始"; + + // 首先设置停止状态,防止新的操作开始 + m_state = wait; + // m_start_time = QDateTime::currentDateTime().toMSecsSinceEpoch(); + // 停止参数获取时钟 + if (m_paramerTimer && m_paramerTimer->isActive()) + { + //qDebug() << "停止参数定时器"; + m_paramerTimer->stop(); + } + + // 停止服务 - TCP 服务器 + if (m_tcp_server) + { + //qDebug() << "停止 TCP 服务器"; + + // 先断开所有信号连接 + disconnect(this, &CrownServer::send_data, m_tcp_server, &TcpServer::slotSendData); + disconnect(m_tcp_server, &TcpServer::signalDataRecv, this, &CrownServer::tcp_server_recv_data); + + // 断开 TCP 服务器自身的所有连接 + m_tcp_server->disconnect(); + + // 关闭服务器并停止接受新连接 + m_tcp_server->close(); + + // 延迟删除,避免在事件处理中访问 + QTimer::singleShot(100, m_tcp_server, [this]() { + if (m_tcp_server) { + m_tcp_server->deleteLater(); + m_tcp_server = nullptr; + //qDebug() << "TCP 服务器已删除"; + } + }); + } + + // 定义线程停止函数模板 + auto stopThread = [this](QThread* thread, const QString& threadName) -> QThread* { + if (thread && thread->isRunning()) { + //qDebug() << "停止" << threadName; + + // 调用线程的停止方法 + if (auto orderThread = dynamic_cast(thread)) { + orderThread->stopImmediately(); + } + else if (auto userThread = dynamic_cast(thread)) { + userThread->stopImmediately(); + } + else if (auto urlThread = dynamic_cast(thread)) { + urlThread->stopImmediately(); + } + else { + thread->requestInterruption(); + thread->quit(); + } + + // 非阻塞等待线程退出 + QElapsedTimer timer; + timer.start(); + + while (thread->isRunning() && timer.elapsed() < 2000) { + QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents, 50); + QThread::msleep(10); + + // 如果超过1秒还在运行,尝试更积极的中断 + if (timer.elapsed() > 1000) { + thread->quit(); + } + } + + if (thread->isRunning()) { + //qWarning() << threadName << "超时,强制终止"; + //thread->terminate(); + //if (!thread->wait(500)) { + // qCritical() << threadName << "无法终止"; + //} + } + + thread->deleteLater(); + //qDebug() << threadName << "已停止"; + return nullptr; + } + return thread; + }; + + // 停止订单线程并断开信号连接 + //if (m_order_thread) { + // disconnect(m_order_thread, &OrderThread::read, this, &CrownServer::view_update_read_times); + // disconnect(m_order_thread, &OrderThread::update_orders, this, &CrownServer::read_orders); + // disconnect(m_order_thread, &OrderThread::account_disconnect, this, &CrownServer::disconnected); + // m_order_thread = static_cast(stopThread(m_order_thread, "订单线程")); + //} + if (m_report_thread) { + disconnect(m_report_thread, &ReportThread::read, this, &CrownServer::view_update_read_times); + disconnect(m_report_thread, &ReportThread::update_orders, this, &CrownServer::read_orders); + disconnect(m_report_thread, &ReportThread::account_disconnect, this, &CrownServer::disconnected); + m_report_thread = static_cast(stopThread(m_report_thread, "订单线程")); + } + + // 停止用户线程 + //if (m_user_thread) { + // m_user_thread = static_cast(stopThread(m_user_thread, "用户线程")); + //} + + // 停止 URL 线程并断开信号连接 + if (m_url_thread) { + disconnect(m_url_thread, &UrlThread::signalUpdateAgentUrlList, this, &CrownServer::update_agent_url); + disconnect(m_url_thread, &UrlThread::signalUpdateUserUrlList, this, &CrownServer::update_client_url); + m_url_thread = static_cast(stopThread(m_url_thread, "URL 线程")); + } + + // 清空数据 + m_parameters.clear(); + m_client_list.clear(); + + // 更新UI状态 + ui.stateButton->setIcon(QIcon(":/CrownServer/Resources/stop.png")); + + // 启用相关按钮 + ui.screenButton->setDisabled(false); + ui.configButton->setDisabled(false); + ui.urlCombo->setDisabled(false); + ui.userManagerButton->setDisabled(false); + ui.startButton->setDisabled(false); + ui.stopButton->setDisabled(true); + ui.portCombo->setDisabled(false); + ui.comPasswordEdit->setDisabled(false); + ui.usernameEdit->setDisabled(false); + ui.passwordEdit->setDisabled(false); + ui.levelCombo->setDisabled(false); + ui.safeCodeEdit->setDisabled(false); + ui.loginButton->setDisabled(false); + + this->setWindowTitle(QString("金运来皇冠跟单软件(服务端) ") + QString(VERSION)); + + //qDebug() << "CrownServer 停止服务完成"; + + // 强制进行一次垃圾回收 + QCoreApplication::processEvents(); +} + + +void CrownServer::tcp_server_recv_data(qintptr socketDecriptor, QByteArray data) +{ + //qDebug() << "服务端数据到达:" << data; + if (data.isEmpty()) + { + //qDebug() << "TCP 服务端接收数据为空"; + return; + } + QString data_string = QString::fromUtf8(data); + PROTOCOL protocol = ProtocolType(data_string); + QStringList list = data_string.split("|"); + + // 发送订单列表 + if (protocol == ReadOrders) + { + if (list.count() == 5) + { + //qDebug() << "封包->读取订单:" << list.count(); + QString sign = list[2]; + if (sign.isEmpty()) + { + return; + } + QString dateTimeString = list[3]; + //if (dateTimeString.isEmpty()) + //{ + // return; + //} + QString countString = list[4]; + if (countString.isEmpty()) + { + return; + } + int count = countString.toInt(); + //qDebug() << "数据读取开始"; + QString json = g_config->readOrder(sign, dateTimeString, count); + //qDebug() << "数据读取完毕"; + //qDebug() << "订单:" << json; + emit send_data(socketDecriptor, QString("ReadOrders|" + json).toUtf8()); + //qDebug() << "信号发送完毕"; + } + } + + // 发送用户列表 + if (protocol == ReadUsers) + { + //qDebug() << "客户端消息 -> 读取用户列表"; + emit send_data(socketDecriptor, QString("ReadUsers|" + g_config->toJson(m_accounts)).toUtf8()); + } + + // 跟单注单 + if (protocol == FollowBet) + { + //qDebug() << "获取跟单注单 -> " << data_string; + if (list.count() == 3) + { + // 入库跟单订单号 + g_config->addFollowOrder(list[2]); + } + } +} + +void CrownServer::view_update_read_times() +{ + m_read_times++; + ui.readOrderTimes->setText( + QString("

读取次数: %1 注单数量: %2

") + .arg(m_read_times) + .arg(m_read_count) + ); +} + +void CrownServer::view_add_log(QString type, QString log) +{ + //// 获取格式化时间 + //QDateTime dateTime = QDateTime::currentDateTime(); + //QString dateFromat = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"); + //// 插入日志 + //QTreeWidgetItem* item = new QTreeWidgetItem(ui.logTreeWidget); + //item->setFlags(Qt::ItemIsUserTristate | item->flags()); + //// item->setCheckState(0, Qt::CheckState::Unchecked); + //item->setText(0, dateFromat); + //item->setText(1, type); + //item->setText(2, log); + + // 新的索引正好等于当前数量即当前最大索引+1 + int index = m_logModel->rowCount(); + + + // 日期时间 + QString datetime; + // 日期 + QString date; + if (g_config->crownTime()) + { + datetime = QDateTime::currentDateTime().addSecs(-43200).toString("yyyy-MM-dd hh:mm:ss"); + date = QDateTime::currentDateTime().addSecs(-43200).toString("yyyy-MM-dd"); + } + else + { + datetime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"); + date = QDateTime::currentDateTime().toString("yyyy-MM-dd"); + } + + + QList standardItemList; + standardItemList.append(new QStandardItem(datetime)); + standardItemList.append(new QStandardItem(type)); + standardItemList.append(new QStandardItem(log)); + standardItemList[0]->setData(-1, Qt::UserRole + 1); // 设置父节点行, 当值为-1时则当前为顶级节点 + + // 查找日期 + QModelIndex curIndex = Utils::instance().findItem(m_logModel, date); + if (-1 == curIndex.row() || -1 == curIndex.column() || -1 != curIndex.data(Qt::UserRole + 1).toInt()) + { + // 添加顶级节点 + int index = m_logModel->rowCount(); + QStandardItem* topNode; + topNode = new QStandardItem(date); + topNode->setData(-1, Qt::UserRole + 1); + topNode->appendRow(standardItemList); + m_logModel->appendRow(topNode); + } + else + { + m_logModel->item(curIndex.row())->appendRow(standardItemList); + } + + //! 设置Qt::UserRole + n: 用户自定义值 + //! 当n值不同时, 相当于不同的键值, 同理不同键则可设置不同值 + //! 此处设置data是为了获取顶级节点值, 通过该值判断和做出对应的操作 + + //standardItemList[0]->setData(date, Qt::UserRole + 2); // 设置父节点行, 当值为-1时则当前为顶级节点 + + //m_logModel->appendRow(standardItemList); + +} + + +void CrownServer::read_orders(QList> list) +{ + //view_add_log("调试日志",QString("读取到 %1 条注单").arg(list.count())); + QList>::iterator order_iter; + for (order_iter = list.begin(); order_iter != list.end(); order_iter++) + { + QMap order = *order_iter; + if (order["RESULT_WL"] == "投注失败") + { + view_add_log("注单筛选", "投注失败"); + continue; + } + + // 读取普通注单 + if (!g_config->readNormalOrder() && order["SRV_IP"] == "") + { + emit view_add_log("注单筛选", "读取普通注单未启用"); + continue; + } + // 读取手机注单 + if (!g_config->readPhoneOrder() && order["SRV_IP"] == "手机") + { + emit view_add_log("注单筛选", "读取手机注单未启用"); + continue; + } + + // 读取下注时间多少天内注单(这里直接用皇冠时间) + if (g_config->readDays() != 0) + { + QString betTime = dateFormat(order["DATE"]) + " " + order["TIME"]; + QDateTime formatBetTime = QDateTime::fromString(betTime, "yyyy-MM-dd hh:mm:ss"); + //qDebug() << "下单时间:" << formatBetTime; + //qDebug() << "当前时间:" << QDateTime::currentDateTime().addSecs(-43200); + //qDebug() << "间隔时间:" << formatBetTime.secsTo(QDateTime::currentDateTime().addSecs(-43200)); + if (g_config->readDays() * 86400 < formatBetTime.secsTo(QDateTime::currentDateTime().addSecs(-43200))) + { + // emit view_add_log("注单筛选", "超出下注时间天数限制"); + continue; + } + } + + if (g_config->hasOrder(order["TID"])) + { + //emit log("注单筛选"); + //qDebug() << "订单过滤:订单已存在:" + order["TID"]; + continue; + } + // + + //if (screenUser(order["NAME0"])) + //{ + // qDebug() << "订单过滤:不读取该用户"; + // continue; + //} + + // 此处映射解决单双问题 + QString map_rtype = Utils::instance().map_rtype(order["rtype"]); + QString map_wtype = Utils::instance().map_wtype(order["wtype"]); + order["rtype"] = map_rtype; + order["wtype"] = map_wtype; + QString rtypeName; + + + //if (m_screen_window->check(order["gtype"], order["session"], order["rtype"], rtypeName)) + //{ + // // qDebug() << "问题:" << order; + // emit view_add_log("注单筛选", QString("订单号 %1: 匹配项目失败").arg(order["tid"])); + // continue; + //} + // 角球/罚球等判断 + if (!order["ptype"].isEmpty()) + { + order["rtypeName"] = rtypeName + "\n" + order["ptype"].mid(1, 2); + } + + //// 普通注单/手机注单判断 + //if (order["SRV_IP"] == "手机") + //{ + // order["rtypeName"] = rtypeName + "\n手机注单"; + //} + //else + //{ + // order["rtypeName"] = rtypeName; + //} + + //order["WAGERS_TYPE"] = Utils::instance().get_wagers_wtype_name(order["wtype"]); + + // 注单入库 + g_config->addOrder(order); + + view_add_order(order); + push_order(order); + + // 更新读取注单数量 + m_read_count++; + ui.readOrderTimes->setText( + QString("

读取次数: %1 注单数量: %2

") + .arg(m_read_times) + .arg(m_read_count) + ); + + // 播放读取注单声音 + if (g_config->updateOrderSoundEnable()) + { + if (!g_config->updateOrderSoundPath().isEmpty()) + { + QSound::play(g_config->updateOrderSoundPath()); + } + else + { + QSound::play(":/sound/sound/readOrder.wav"); + } + } + + } + + //// 会员/代理 + //if (m_manager) + //{ + // QString up_username = m_manager->up_username(order["NAME0"]); + // QTableWidgetItem* userItem = new QTableWidgetItem(order["NAME0"] + (up_username.isEmpty() ? "" : "/" + up_username)); + // userItem->setTextAlignment(Qt::AlignCenter); + // ui.orderTableWidget->setItem(index, 3, userItem); + //} + + + //// 滚动到最后一行 + //ui.orderTableWidget->scrollToBottom(); +} + +void CrownServer::view_add_order(QMap order) +{ + + + + + + + + + + + + + + + // 异步推送消息 - 使用lambda确保在独立线程中执行 + //QFuture future = QtConcurrent::run([order]() { + // g_verify->push_msg("read_order", "服务端", "-4826387471", order); + ////}); + //QThreadPool::globalInstance()->setMaxThreadCount(50); + + //QtConcurrent::run([&]() { + + // g_verify->push_msg("read_order", "服务端", "-4826387471", order); + // qDebug() << "后台线程中执行任务:" << QThread::currentThread(); + //}); + + //QFuture future = QtConcurrent::run(g_verify, &Verify::push_msg, QString("read_order"), QString("服务端"), QString("-4826387471"), order); + + + //push_msg("read_order","服务端","-4826387471",order); + // 下单时间(优先用 DATETIME,没有则用 DATE+TIME) + QString bet_time = order.value("DATETIME"); + if (bet_time.isEmpty()) { + bet_time = dateFormat(order.value("DATE")) + " " + order.value("TIME"); + } + QDateTime betDt = QDateTime::fromString(bet_time, "yyyy-MM-dd HH:mm:ss"); + if (betDt.isValid() && !g_config->crownTime()) { + betDt = betDt.addSecs(43200); // 皇冠 -> 本地展示 +12h + } + if (betDt.isValid()) { + bet_time = betDt.toString("yyyy-MM-dd HH:mm:ss"); + } + const QString betDateStr = betDt.isValid() + ? betDt.date().toString("yyyy-MM-dd") + : dateFormat(order.value("DATE")); // 兜底 + + // 读取时间(READ_DATETIME) + QString read_time = order.value("READ_DATETIME"); + QDateTime readDt = QDateTime::fromString(read_time, "yyyy-MM-dd HH:mm:ss"); + if (readDt.isValid()) { + if (!g_config->crownTime()) readDt = readDt.addSecs(43200); + read_time = readDt.toString("yyyy-MM-dd HH:mm:ss"); + } + else { + read_time = bet_time; // 兜底:用下注时间 + } + + // 处理联赛+对阵文本(去掉
等) + QString league = order.value("LEAGUE"); + QString teamH = order.value("TEAM_H"); + QString teamC = order.value("TEAM_C"); + QRegularExpression brRe(R"()", QRegularExpression::CaseInsensitiveOption); + teamH.replace(brRe, QString()); + teamC.replace(brRe, QString()); + teamH.remove(QLatin1Char(' ')); + teamC.remove(QLatin1Char(' ')); + QString team = teamH + " vs " + teamC; + + // 组装行 + QList rowItems; + rowItems.append(new QStandardItem(order.value("TID"))); // 单号 + rowItems.append(new QStandardItem(bet_time)); // 下注时间 + rowItems.append(new QStandardItem(read_time)); // 读取时间 + rowItems.append(new QStandardItem(order.value("NAME0"))); // 会员 + if (order.value("GT") == "篮球 / 美式足球") + { + rowItems.append(new QStandardItem("篮球" + order.value("SESSION") + order.value("STAGE"))); // 球种 + } + else + { + rowItems.append(new QStandardItem(order.value("GT") + order.value("SESSION") + order.value("STAGE"))); // 球种 + } + order["WAGERS_TYPE"] = Utils::format_wagers_type(order); + + //if (order.value("WAGERS_TYPE").contains(order.value("TEAM_H")) && order.value("WAGERS_TYPE").contains("大 / 小")) + //{ + // order["WAGERS_TYPE"] = "主大小"; + //} + //else if(order.value("WAGERS_TYPE").contains(order.value("TEAM_C")) && order.value("WAGERS_TYPE").contains("大 / 小")) + //{ + // order["WAGERS_TYPE"] = "客大小"; + //} + //else if (order.value("WAGERS_TYPE").contains("大 / 小")) + //{ + // order["WAGERS_TYPE"] = "大小"; + //} + + + if (order.value("SRV_IP") == "手机") + { + rowItems.append(new QStandardItem(order.value("WAGERS_TYPE") +"\n"+ order.value("SRV_IP"))); // 投注类型 + } + else + { + rowItems.append(new QStandardItem(order.value("WAGERS_TYPE"))); // 投注类型 + } + + if (!order.value("TEAM_H").isEmpty() && !order.value("TEAM_C").isEmpty()) + { + rowItems.append(new QStandardItem(league + "\n" + team)); // 联赛+对阵 + } + else + { + rowItems.append(new QStandardItem(league)); // 联赛(冠军) + } + rowItems.append(new QStandardItem(order.value("ORDER_TYPE"))); // 下注队伍 + rowItems.append(new QStandardItem(order.value("ORDER_CON"))); // 盘口 + rowItems.append(new QStandardItem(order.value("IORATIO"))); // 赔率 + rowItems.append(new QStandardItem(order.value("GOLD"))); // 金额 + rowItems[0]->setData(-1, Qt::UserRole + 1); // 顶级标记 + + // 查找是否已有该日期分组(格式:yyyy-MM-dd(n)) + QStandardItem* targetTop = nullptr; + int targetRow = -1; + for (int i = 0; i < m_orderModel->rowCount(); ++i) { + QStandardItem* top = m_orderModel->item(i); + if (!top) continue; + const QString txt = top->text(); + if (txt.startsWith(betDateStr)) { + targetTop = top; + targetRow = i; + break; + } + } + + if (!targetTop) { + // 新建分组,数量 = 1 + QString title = betDateStr + "(1)"; + QStandardItem* topNode = new QStandardItem(title); + topNode->setData(-1, Qt::UserRole + 1); + topNode->appendRow(rowItems); + m_orderModel->appendRow(topNode); + } + else { + // 追加并更新数量 + targetTop->appendRow(rowItems); + // 提取并自增括号内的数量 + int count = 0; + { + QRegularExpression re(R"(\((\d+)\)$)"); + QRegularExpressionMatch m = re.match(targetTop->text()); + if (m.hasMatch()) count = m.captured(1).toInt(); + } + ++count; + targetTop->setText(QString("%1(%2)").arg(betDateStr).arg(count)); + } +} + +// 掉线重连 +void CrownServer::disconnected() +{ + if (m_state == work) + { + push_disconnected(); + // 定义线程停止函数模板 + auto stopThread = [this](QThread* thread, const QString& threadName) -> QThread* { + if (thread && thread->isRunning()) { + //qDebug() << "停止" << threadName; + + // 调用线程的停止方法 + if (auto orderThread = dynamic_cast(thread)) { + orderThread->stopImmediately(); + } + //else if (auto userThread = dynamic_cast(thread)) { + // userThread->stopImmediately(); + //} + else if (auto urlThread = dynamic_cast(thread)) { + urlThread->stopImmediately(); + } + else { + thread->requestInterruption(); + thread->quit(); + } + + // 非阻塞等待线程退出 + QElapsedTimer timer; + timer.start(); + + while (thread->isRunning() && timer.elapsed() < 2000) { + QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents, 50); + QThread::msleep(10); + + // 如果超过1秒还在运行,尝试更积极的中断 + if (timer.elapsed() > 1000) { + thread->quit(); + } + } + + if (thread->isRunning()) { + //qWarning() << threadName << "超时,强制终止"; + thread->terminate(); + if (!thread->wait(500)) { + //qCritical() << threadName << "无法终止"; + } + } + + thread->deleteLater(); + //qDebug() << threadName << "已停止"; + return nullptr; + } + return thread; + }; + + // 停止订单线程并断开信号连接 + //if (m_order_thread) { + // disconnect(m_order_thread, &OrderThread::read, this, &CrownServer::view_update_read_times); + // disconnect(m_order_thread, &OrderThread::update_orders, this, &CrownServer::read_orders); + // disconnect(m_order_thread, &OrderThread::account_disconnect, this, &CrownServer::disconnected); + // m_order_thread = static_cast(stopThread(m_order_thread, "订单线程")); + //} + + if (m_report_thread) { + disconnect(m_report_thread, &ReportThread::read, this, &CrownServer::view_update_read_times); + disconnect(m_report_thread, &ReportThread::update_orders, this, &CrownServer::read_orders); + disconnect(m_report_thread, &ReportThread::account_disconnect, this, &CrownServer::disconnected); + m_report_thread = static_cast(stopThread(m_report_thread, "订单线程")); + } + + //// 停止用户线程 + //if (m_user_thread) { + // m_user_thread = static_cast(stopThread(m_user_thread, "用户线程")); + //} + + // 停止 URL 线程并断开信号连接 + if (m_url_thread) { + disconnect(m_url_thread, &UrlThread::signalUpdateAgentUrlList, this, &CrownServer::update_agent_url); + disconnect(m_url_thread, &UrlThread::signalUpdateUserUrlList, this, &CrownServer::update_client_url); + m_url_thread = static_cast(stopThread(m_url_thread, "URL 线程")); + } + + // 清空数据 + m_parameters.clear(); + // 重新登录状态 + m_state = relogin; + m_start_time = QDateTime::currentDateTime().toMSecsSinceEpoch(); + + + emit view_add_log("掉线重连", "平台账户掉线重连"); + // 注意这里需要重新创建线程 + //m_user_thread = new UserThread(); + m_url_thread = new UrlThread(); + connect(m_url_thread, &UrlThread::signalUpdateAgentUrlList, this, &CrownServer::update_agent_url); + connect(m_url_thread, &UrlThread::signalUpdateUserUrlList, this, &CrownServer::update_client_url); + + // 创建工作线程 + //m_order_thread = new OrderThread(); + //connect(m_order_thread, &OrderThread::read, this, &CrownServer::view_update_read_times); + //connect(m_order_thread, &OrderThread::update_orders, this, &CrownServer::read_orders); + //// 掉线重连 + //connect(m_order_thread, &OrderThread::account_disconnect, this, &CrownServer::disconnected); + + m_report_thread = new ReportThread(); + connect(m_report_thread, &ReportThread::read, this, &CrownServer::view_update_read_times); + connect(m_report_thread, &ReportThread::update_orders, this, &CrownServer::read_orders); + // 掉线重连 + connect(m_report_thread, &ReportThread::account_disconnect, this, &CrownServer::disconnected); + + QTimer::singleShot(g_config->disconnectedSleep() * 1000, [&]() { + + + // 访问网址 + ui.webEngineView->page()->load(QUrl("")); + ui.webEngineView->page()->load(ui.urlCombo->currentText()); + if (!m_paramerTimer->isActive()) + { + m_paramerTimer->start(3000); + } + + }); + + } + +} + +/// +/// 快捷设置用户 +/// +void CrownServer::set_account(QString username, QString password, QString level, QString safeCode) +{ + if (ui.startButton->isEnabled()) + { + ui.usernameEdit->setText(username); + ui.passwordEdit->setText(password); + ui.levelCombo->setCurrentText(level); + ui.safeCodeEdit->setText(safeCode); + } +} + + + +/// +/// 登录 +/// +void CrownServer::login_account() +{ + // 等待三秒防止获取不到dom对象 + QTimer::singleShot(1500, [=] { + + QString loginType = ui.levelCombo->currentText().trimmed(); + if (loginType == "1") + { + loginType = "btn_A"; + } + else if (loginType == "2") + { + loginType = "btn_B"; + } + else + { + loginType = "btn_C"; + } + QString username = ui.usernameEdit->text().trimmed(); + QString password = ui.passwordEdit->text().trimmed(); + QString safeCode = ui.safeCodeEdit->text().trimmed(); + + QString jsCode; + + jsCode += "function fireKeyEvent(element, evtType, keyChar) {"; + jsCode += " element.focus();"; + jsCode += " var KeyboardEventInit = {key:keyChar, code:'', location:0, repeat:false, isComposing:false};"; + jsCode += " var evtObj = new KeyboardEvent(evtType, KeyboardEventInit);"; + jsCode += " element.dispatchEvent(evtObj);"; + jsCode += "}"; + + jsCode += "function virtualText(el,str){"; + jsCode += " for(var i = 0; ipage()->runJavaScript(jsCode); + }); + +} + +// 提取 +void CrownServer::extract_accounts() +{ + // 一次性获取所有需要的参数 + QString javascriptCode = R"( + (function() { + return { + langx: typeof langx !== 'undefined' ? langx : '', + ver: typeof ver !== 'undefined' ? ver : '', + url: document.URL ? document.URL : '', + username: typeof username !== 'undefined' ? username : '', + login_layer: typeof login_layer !== 'undefined' ? login_layer : '', + blackbox: typeof blackbox !== 'undefined' ? blackbox : '', + layer_id: typeof top.layer_id !== 'undefined' ? top.layer_id : '', + pay_type: typeof pay_type !== 'undefined' ? pay_type : '', + cookies: document.cookie, + uid: typeof uid !== 'undefined' ? uid : '' + }; + })() + )"; + + // 执行JavaScript并在lambda中处理结果 + ui.webEngineView->page()->runJavaScript(javascriptCode, + [this](const QVariant& result) { + // 检查结果有效性 + if (!result.isValid() || result.isNull()) { + //qWarning() << "JavaScript执行失败或返回空结果"; + emit extract_account_finish(QList>()); + return; + } + + // 转换为Map格式 + QVariantMap dataMap = result.toMap(); + if (dataMap.isEmpty()) { + //qWarning() << "返回的数据不是有效的对象"; + emit extract_account_finish(QList>()); + return; + } + + // 提取参数并调试输出 + QMap params; + for (auto it = dataMap.begin(); it != dataMap.end(); ++it) { + QString key = it.key(); + QString value = it.value().toString(); + //qDebug() << "获取参数[" << key << "]: " << value; + params[key] = value; + } + + // 验证必要参数 + if (params["url"].isEmpty() || params["ver"].isEmpty() || params["uid"].isEmpty() || params["pay_type"].isEmpty()) { + //qWarning() << "错误:缺少必要的参数(url、ver或uid或pay_type)"; + emit extract_account_finish(QList>()); + return; + } + + try { + // 调用用户获取方法 + UserThread::UserListResult result = UserThread::getAllUsersStatic( + params["url"], // url + params["ver"], // ver + params["uid"], // uid + params["login_layer"],// login_layer + params["layer_id"], // layer_id + params["langx"], // langx + params["cookies"], // cookies + params["username"], // current_username + params["pay_type"], + 10000 // timeoutMs + ); + + // 发送完成信号 + //qDebug() << result.accountList; + emit extract_account_finish(result.accountList); + + // 缓存账户 + m_accounts = result.accountList; + + } + catch (const std::exception& e) { + //qCritical() << "处理用户数据时发生异常:" << e.what(); + emit extract_account_finish(QList>()); + } + } + ); +} +/// +/// 读取网页参数 +/// +void CrownServer::read_web_parameter() +{ + qint64 current_time = QDateTime::currentDateTime().toMSecsSinceEpoch(); + if (current_time - m_start_time > 30 * 1000) + { + if (m_failed_reconnect_times < g_config->failedReconnectTimes()) + { + + QTimer::singleShot(g_config->failedSleep() * 1000, [&]() { + if (m_failed_reconnect_times < g_config->failedReconnectTimes()) + { + m_failed_reconnect_times++; + // 清空参数 + m_state = wait; + m_parameters.clear(); + m_start_time = QDateTime::currentDateTime().toMSecsSinceEpoch(); + // 重新载入页面 + ui.webEngineView->page()->load(ui.urlCombo->currentText()); + //qDebug() << "登录超时重载"; + //qDebug() << "次数:" << m_failed_reconnect_times << "最大:" << g_config->failedReconnectTimes(); + } + //m_paramerTimer->stop(); + + //m_paramerTimer->start(); + }); + + //m_paramerTimer->stop(); + + + } + else + { + + //m_paramerTimer->stop(); + //push_disconnected(); + + emit ui.stopButton->clicked(); + //stop_task(); + } + + return; + + } + // 判断登录按钮出现后开始执行登录操作 + ui.webEngineView->page()->runJavaScript("if (document.getElementById('loginBtn')) 'ok';", [&](const QVariant& v) + { + // 判断是等待工作状态或者重新登录状态 + if (m_state == wait || m_state == relogin) + { + // 确保没有脏数据 + if (m_parameters["loginBtn"].isEmpty()) + { + // 确保登录按钮已经加载 + m_parameters["loginBtn"] = v.toString(); + if (!v.toString().isEmpty()) + { + // 修改状态为准备登录 + m_state = readyLogin; + // 延迟1秒后执行登录Javascript + QTimer::singleShot(1000, [this]() { + login_account(); + }); + + } + + } + } + }); + + // 登录失败则清空参数修改状态重新登录 + ui.webEngineView->page()->runJavaScript("if (document.getElementById('hr_info1TXT')) document.getElementById('hr_info1TXT').textContent;", [&](const QVariant& v) { + //qDebug() << "获取参数[hr_info1TXT]: " << v.toString(); + m_parameters["hr_info1TXT"] = v.toString(); + if (!v.toString().isEmpty() && m_state == readyLogin) + { + //qDebug() << "登录失败"; + // 登录失败延迟 + + m_parameters.clear(); + m_state = relogin; + login_account(); + } + + }); + + ui.webEngineView->page()->runJavaScript("if (langx) langx;", [&](const QVariant& v) { + //qDebug() << "获取参数[langx]: " << v.toString(); + m_parameters["langx"] = v.toString(); + }); + + ui.webEngineView->page()->runJavaScript("if (ver) ver;", [&](const QVariant& v) { + //qDebug() << "获取参数[ver]: " << v.toString(); + m_parameters["ver"] = v.toString(); + }); + + ui.webEngineView->page()->runJavaScript("if(window.location.origin) document.URL;", [=](const QVariant& v) { + //qDebug() << "获取参数[url]: " << v.toString(); + m_parameters["url"] = v.toString(); + }); + + ui.webEngineView->page()->runJavaScript("if (username) username;", [=](const QVariant& v) { + //qDebug() << "获取参数[username]: " << v.toString(); + m_parameters["username"] = v.toString(); + }); + + + ui.webEngineView->page()->runJavaScript("if(login_layer) login_layer;", [=](const QVariant& v) { + //qDebug() << "获取参数[login_layer]: " << v.toString(); + m_parameters["login_layer"] = v.toString(); + }); + + // 更新blackbox加密参数 + ui.webEngineView->page()->runJavaScript("if(blackbox) blackbox;", [=](const QVariant& v) { + //qDebug() << "获取参数[blackbox]: " << v.toString(); + m_parameters["blackbox"] = v.toString(); + }); + + + // 更新up_id参数 + ui.webEngineView->page()->runJavaScript("top.layer_id;", [=](const QVariant& v) { + // qDebug() << "获取参数[layer_id]: " << v.toString(); + m_parameters["layer_id"] = v.toString(); + }); + + // 更新cookie + ui.webEngineView->page()->runJavaScript("function GetCookie(){return document.cookie} GetCookie();", [=](const QVariant& v) { + m_parameters["cookies"] = v.toString(); + }); + + ui.webEngineView->page()->runJavaScript("if (uid) uid;", [&](const QVariant& v) { + //qDebug() << "获取参数[uid]: " << v.toString(); + if (!v.toString().isEmpty() && m_parameters["hr_info1TXT"].isEmpty() && !m_parameters["username"].isEmpty() && !m_parameters["layer_id"].isEmpty() && m_state != work) + { + push_reconnected(); + //if (m_state == relogin) + //{ + // push_reconnected(); + //} + m_state = work; + //qDebug() << "登录成功"; + + // 等到登录成功再切换 + ui.stateButton->setIcon(QIcon(":/CrownServer/Resources/start.png")); + m_parameters["uid"] = v.toString(); + + // 更新用户列表 + //m_user_thread->setParam(m_parameters["url"], m_parameters["ver"], m_parameters["uid"], m_parameters["login_layer"], m_parameters["layer_id"], m_parameters["langx"], ui.usernameEdit->text(), m_parameters["cookies"]); + //m_user_thread->start(); + + // 更新订单 + //m_order_thread->setParam(m_parameters["url"], m_parameters["ver"], m_parameters["uid"], m_parameters["login_layer"], m_parameters["layer_id"], m_parameters["langx"], ui.usernameEdit->text(),m_parameters["cookies"]); + //m_order_thread->start(); + QString current_agent_type = ui.levelCombo->currentText().trimmed(); + if (current_agent_type == "1") + { + current_agent_type = "co"; + } + else if (current_agent_type == "2") + { + current_agent_type = "su"; + } + else + { + current_agent_type = "ag"; + } + + m_report_thread->setParam(m_parameters["url"], m_parameters["ver"], m_parameters["uid"], m_parameters["login_layer"], m_parameters["layer_id"], m_parameters["langx"], ui.usernameEdit->text(), m_parameters["cookies"], current_agent_type,m_accounts); + m_report_thread->start(); + + // 更新网址 + m_url_thread->setParam(m_parameters["url"], m_parameters["ver"], m_parameters["uid"], m_parameters["login_layer"], m_parameters["layer_id"], m_parameters["langx"], ui.usernameEdit->text(), m_parameters["cookies"]); + m_url_thread->start(); + + m_paramerTimer->stop(); + } + + + + }); +} + + +/// +/// 读取网页参数(仅登录) +/// +void CrownServer::read_web_parameter_login() +{ + // 判断登录按钮出现后开始执行登录操作 + ui.webEngineView->page()->runJavaScript("if (document.getElementById('loginBtn')) 'ok';", [&](const QVariant& v) + { + // 判断是等待工作状态或者重新登录状态 + if (m_state == wait || m_state == relogin) + { + // 确保没有脏数据 + if (m_parameters["loginBtn"].isEmpty()) + { + // 确保登录按钮已经加载 + m_parameters["loginBtn"] = v.toString(); + if (!v.toString().isEmpty()) + { + // 修改状态为准备登录 + m_state = readyLogin; + // 延迟1秒后执行登录Javascript + QTimer::singleShot(1000, [this]() { + login_account(); + }); + + + } + + } + } + }); + + + ui.webEngineView->page()->runJavaScript("if (langx) langx;", [&](const QVariant& v) { + //qDebug() << "获取参数[langx]: " << v.toString(); + m_parameters["langx"] = v.toString(); + }); + + ui.webEngineView->page()->runJavaScript("if (ver) ver;", [&](const QVariant& v) { + //qDebug() << "获取参数[ver]: " << v.toString(); + m_parameters["ver"] = v.toString(); + }); + + ui.webEngineView->page()->runJavaScript("if(document.URL) document.URL;", [=](const QVariant& v) { + //qDebug() << "获取参数[url]: " << v.toString(); + m_parameters["url"] = v.toString(); + }); + + ui.webEngineView->page()->runJavaScript("if (username) username;", [=](const QVariant& v) { + //qDebug() << "获取参数[username]: " << v.toString(); + m_parameters["username"] = v.toString(); + }); + + + ui.webEngineView->page()->runJavaScript("if(login_layer) login_layer;", [=](const QVariant& v) { + //qDebug() << "获取参数[login_layer]: " << v.toString(); + m_parameters["login_layer"] = v.toString(); + }); + + // 更新blackbox加密参数 + ui.webEngineView->page()->runJavaScript("if(blackbox) blackbox;", [=](const QVariant& v) { + //qDebug() << "获取参数[blackbox]: " << v.toString(); + m_parameters["blackbox"] = v.toString(); + }); + + + // 更新up_id参数 + ui.webEngineView->page()->runJavaScript("top.layer_id;", [=](const QVariant& v) { + // qDebug() << "获取参数[layer_id]: " << v.toString(); + m_parameters["layer_id"] = v.toString(); + }); + + // 更新cookie + ui.webEngineView->page()->runJavaScript("function GetCookie(){return document.cookie} GetCookie();", [=](const QVariant& v) { + m_parameters["cookies"] = v.toString(); + }); + + ui.webEngineView->page()->runJavaScript("if (uid) uid;", [&](const QVariant& v) { + //qDebug() << "获取参数[uid]: " << v.toString(); + if (!v.toString().isEmpty() && m_parameters["hr_info1TXT"].isEmpty() && !m_parameters["username"].isEmpty() && !m_parameters["layer_id"].isEmpty() && m_state != work) + { + // 这里不修改状态 + m_state = wait; + //qDebug() << "登录成功"; + m_parameters.clear(); + m_login_timer->stop(); + } + + + + }); +} + + + + + + + + +/// +/// 窗口关闭事件 +/// +/// 事件 +void CrownServer::closeEvent(QCloseEvent* event) +{ + //qDebug() << "CrownServer 窗口关闭事件"; + + // 检查是否是自发事件(用户点击关闭按钮) + if (event->spontaneous()) { + // 用户点击窗口关闭按钮,最小化到托盘 + if (m_tray_icon->isVisible()) { + hide(); // 隐藏窗口 + event->ignore(); // 忽略关闭事件 + return; + } + } + + // 先停止服务,释放资源 + if (m_state != wait) { + //qDebug() << "窗口关闭时停止服务"; + stop_task(); // 调用停止逻辑,释放所有资源 + } + if (ui.webEngineView) { + //qDebug() << "开始清理WebEngine资源..."; + + // 先停止所有加载 + ui.webEngineView->stop(); + ui.webEngineView->page()->triggerAction(QWebEnginePage::Stop); + + // 断开所有连接 + ui.webEngineView->disconnect(); + ui.webEngineView->page()->disconnect(); + + // 显式删除页面 + QWebEnginePage* page = ui.webEngineView->page(); + if (page) { + // 先设置页面为nullptr,避免双重删除 + ui.webEngineView->setPage(nullptr); + + // 使用deleteLater确保在事件循环中删除 + page->deleteLater(); + QCoreApplication::processEvents(); + } + + // 删除视图 + ui.webEngineView->deleteLater(); + ui.webEngineView = nullptr; + + //qDebug() << "WebEngine资源清理完成"; + } + + // 保存配置 + //qDebug() << "保存配置"; + g_config->setAgentUrlList(ui.urlCombo->items()); + g_config->setAgentUrl(ui.urlCombo->currentText()); + g_config->setConnectPassword(ui.comPasswordEdit->text()); + g_config->setUsername(ui.usernameEdit->text()); + g_config->setPassword(ui.passwordEdit->text()); + g_config->setLevel(ui.levelCombo->currentText()); + g_config->setPort(ui.portCombo->currentText()); + g_config->setSafeCode(ui.safeCodeEdit->text()); + + // qDebug() << "配置保存完成,接受关闭事件"; + event->accept(); // 接受关闭事件 + +} + +PROTOCOL CrownServer::ProtocolType(QString data) +{ + QStringList list = data.split("|"); + if (list.count() >= 2) + { + QString protocol = list[0]; + QString password = list[1]; + // 校验连接密码 + if (password != g_config->connectPassword()) + { + return Error; + } + + if (protocol == "ReadOrders") + { + return ReadOrders; + } + else if (protocol == "ReadUsers") + { + return ReadUsers; + } + else if (protocol == "FollowBet") + { + return FollowBet; + } + + } + return Error; +} + + + + + + + + +// 添加这个成员函数到你的类中 +void CrownServer::view_time_zone_change(bool isCrownTime) +{ + // 先更新所有时间项,并记录新的日期分组 + QMap>> newGroups; + + for (int i = 0; i < m_orderModel->rowCount(); ++i) { + QStandardItem* dateItem = m_orderModel->item(i); + + for (int j = 0; j < dateItem->rowCount(); ++j) { + QStandardItem* betTimeItem = dateItem->child(j, 1); + QStandardItem* readTimeItem = dateItem->child(j, 2); + + QDateTime betTime = QDateTime::fromString(betTimeItem->text(), "yyyy-MM-dd HH:mm:ss"); + QDateTime readTime = QDateTime::fromString(readTimeItem->text(), "yyyy-MM-dd HH:mm:ss"); + + // 转换时间 + int offset = isCrownTime ? -12 * 3600 : 12 * 3600; + betTime = betTime.addSecs(offset); + readTime = readTime.addSecs(offset); + + // 更新显示 + betTimeItem->setText(betTime.toString("yyyy-MM-dd HH:mm:ss")); + readTimeItem->setText(readTime.toString("yyyy-MM-dd HH:mm:ss")); + + // 记录新的分组信息 + QString newDateStr = betTime.date().toString("yyyy-MM-dd"); + newGroups[newDateStr].append(qMakePair(dateItem, j)); + } + } + + // 现在更新分组标题 + for (int i = 0; i < m_orderModel->rowCount(); ++i) { + QStandardItem* dateItem = m_orderModel->item(i); + QString dateText = dateItem->text(); + + if (dateText.startsWith("下注时间:")) { + // 找到这个分组中第一个项目的新日期 + if (dateItem->rowCount() > 0) { + QStandardItem* firstBetTimeItem = dateItem->child(0, 1); + QDateTime firstBetTime = QDateTime::fromString(firstBetTimeItem->text(), "yyyy-MM-dd HH:mm:ss"); + QString newDateStr = firstBetTime.date().toString("yyyy-MM-dd"); + dateItem->setText("下注时间:" + newDateStr); + } + } + } + + m_orderProxyModel->invalidate(); +} +/// +/// 更新代理网址列表 +/// +/// 列表 +void CrownServer::update_agent_url(QList list) +{ + for (int i = 0; i < list.count(); i++) + { + QString url = list.at(i); + bool found = false; + for (int j = 0; j < ui.urlCombo->count(); j++) + { + QString item = ui.urlCombo->item(j); + if (item.contains(url, Qt::CaseInsensitive)) + { + found = true; + break; + } + if (url.contains(item, Qt::CaseInsensitive)) + { + found = true; + break; + } + } + if (!found) + { + ui.urlCombo->addItem(url); + } + } +} + + +/// +/// 更新客户网址列表 +/// +/// 列表 +void CrownServer::update_client_url(QList list) +{ + auto client_url_list = g_config->userUrlList(); + for (auto url : list) + { + if (!client_url_list.contains(url)) + { + client_url_list.append(url); + } + } + g_config->setUserUrlList(client_url_list); + +} + + + +// 心跳检查槽函数 +void CrownServer::heartbeat() +{ + VMProtectBegin("Heartbeat_Check"); + + QString result; + QFuture future = QtConcurrent::run(g_verify, &Verify::Heartbeat, result); + //bool heartbeatResult = g_verify->Heartbeat(result); + bool heartbeatResult = future.result(); + if (!heartbeatResult) { + // 心跳失败,可以记录日志但不立即退出 + qDebug() << "心跳失败:" << result; + } + + // 检查授权到期时间 + if (g_verify->GetDueTime().msecsTo(QDateTime::currentDateTime()) >= 0) { + QMessageBox::critical(nullptr, "错误", "授权已到期!"); + QApplication::quit(); + } + + VMProtectEnd(); +} + +void CrownServer::push_disconnected() +{ + // 清空 + m_failed_reconnect_times = 0; + + PushMsg *worker = new PushMsg(); + QThread *workerThread = new QThread(); + + worker->moveToThread(workerThread); + + // 连接信号槽 + connect(workerThread, &QThread::started, [worker]() { + //"-4826387471" + //worker->push("account_dissconnected", "-4826387471", QMap()); + worker->push("account_dissconnected", g_config->notice_account(), QMap()); + }); + + connect(worker, &PushMsg::resultReady, [](const QString &result) { + //qDebug() << "Result:" << result; + }); + + connect(worker, &PushMsg::resultReady, workerThread, &QThread::quit); + connect(workerThread, &QThread::finished, worker, &PushMsg::deleteLater); + connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater); + + workerThread->start(); +} + +void CrownServer::push_reconnected() +{ + PushMsg *worker = new PushMsg(); + QThread *workerThread = new QThread(); + + worker->moveToThread(workerThread); + + // 连接信号槽 + connect(workerThread, &QThread::started, [worker]() { + worker->push("account_reconnected", g_config->notice_account(), QMap()); + }); + + connect(worker, &PushMsg::resultReady, [](const QString &result) { + //qDebug() << "Result:" << result; + }); + + connect(worker, &PushMsg::resultReady, workerThread, &QThread::quit); + connect(workerThread, &QThread::finished, worker, &PushMsg::deleteLater); + connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater); + + workerThread->start(); +} + + +void CrownServer::push_order(QMap order) +{ + + PushMsg *worker = new PushMsg(); + QThread *workerThread = new QThread(); + + worker->moveToThread(workerThread); + + // 连接信号槽 + connect(workerThread, &QThread::started, [worker, order]() { + worker->push("read_order", g_config->notice_account(), order); + }); + + connect(worker, &PushMsg::resultReady, [](const QString &result) { + //qDebug() << "Result:" << result; + }); + + connect(worker, &PushMsg::resultReady, workerThread, &QThread::quit); + connect(workerThread, &QThread::finished, worker, &PushMsg::deleteLater); + connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater); + + workerThread->start(); + +} \ No newline at end of file diff --git a/CrownServer/CrownServer.h b/CrownServer/CrownServer.h new file mode 100644 index 0000000..dc02fee --- /dev/null +++ b/CrownServer/CrownServer.h @@ -0,0 +1,193 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "TcpServer.h" +#include +#include "ui_CrownServer.h" +#include "UserThread.h" +#include "ReportThread.h" +#include "UrlThread.h" +#include "Screen.h" +#include "Notice.h" +#include "Setting.h" +#include "User.h" +#include +#include +#include + + +typedef enum _State { + wait, + loadLoginPage, + readyLogin, + login, + relogin, + work +}State; + +enum PROTOCOL +{ + Error, + Login, + LoginSuccess, + LoginFailed, + ReadOrders, + ReadUsers, + FollowBet, + Logout +}; + +class CrownServer : public QMainWindow +{ + Q_OBJECT +public: + CrownServer(QWidget* parent = nullptr); + ~CrownServer(); +private: + void closeEvent(QCloseEvent* event); +private: + TcpServer* m_tcp_server; + QList m_client_list; +private: + PROTOCOL ProtocolType(QString data); +private: + // 当前状态 + State m_state; + // 参数列表 + QMap m_parameters; + // 获取参数定时器(工作) + QTimer* m_paramerTimer; + // 获取参数定时器(仅登录) + QTimer* m_login_timer; + + // 用户列表 + QList> m_accounts; + +private: + // 订单列表主菜单 + QMenu* m_orderTableMenu; + // 订单列表删除操作选项 + QAction* m_orderTableDeleteAction; + + + +signals: + // 添加账号记录 + void add_account_record(QString username, QString password, QString level, QString safeCode); + // 发送数据 + void send_data(qintptr socketDescriptor, QByteArray data); + // 提取账号 + void extract_account_finish(QList> list); + // 推送消息 + void push_msg(QString type, QString app, QString account, QMap order); +public slots: + // 状态改变 + void view_connect_state_change(int state); + // 时区切换 + void view_time_zone_change(bool isCrownTime); + // 更新读取次数 + void view_update_read_times(); + + // TCP服务端数据到达 + void tcp_server_recv_data(qintptr, QByteArray); + // 开始工作 + void start_task(); + // 停止工作 + void stop_task(); + // 登录平台账户 + void login_account(); + // 提取账户 + void extract_accounts(); + // 读取网页参数 + void read_web_parameter(); + // 读取网页参数(仅登录) + void read_web_parameter_login(); + // 读取平台注单 + void read_orders(QList> list); + // 掉线重连 + void disconnected(); + // 更新代理网址 + void update_agent_url(QList); + // 更新客户网址 + void update_client_url(QList); + + + // 快捷设置平台账户 + void set_account(QString username, QString password, QString level, QString safeCode); + // 添加订单显示 + void view_add_order(QMap order); + // 添加日志 + void view_add_log(QString type, QString log); + // 托盘点击 + void tray_activated(QSystemTrayIcon::ActivationReason reason); + // 心跳 + void heartbeat(); + + // 推送掉线信息 + void push_disconnected(); + // 推送连接信息 + void push_reconnected(); + // 推送读取信息 + void push_order(QMap order); + +public: + + QLocalServer *m_localServer; // 本地服务器; + void handleNewConnection(); + + + +private: + // 托盘 + QSystemTrayIcon *m_tray_icon; + // 模型对象指针 + QStandardItemModel* m_orderModel; + // 代理模型对象指针 + QSortFilterProxyModel* m_orderProxyModel; + // 模型对象指针 + QStandardItemModel* m_logModel; + // 代理模型对象指针 + QSortFilterProxyModel* m_logProxyModel; + + QMenu* m_order_tree_menu; + + Screen* m_screen_window; + + Notice* m_notice_window; + + Setting* m_config; + User* m_user; + + + UserThread* m_user_thread; + ReportThread* m_report_thread; + // OrderThread* m_order_thread; + UrlThread* m_url_thread; + + int m_read_times; + int m_read_count; + + + QTimer* m_heartbeatTimer; + + // 登录开始时间 + qint64 m_start_time; + + int m_failed_reconnect_times; + +private: + Ui::CrownServerClass ui; +}; diff --git a/CrownServer/CrownServer.h.backup b/CrownServer/CrownServer.h.backup new file mode 100644 index 0000000..61fe23c Binary files /dev/null and b/CrownServer/CrownServer.h.backup differ diff --git a/CrownServer/CrownServer.qrc b/CrownServer/CrownServer.qrc new file mode 100644 index 0000000..d95fbf3 --- /dev/null +++ b/CrownServer/CrownServer.qrc @@ -0,0 +1,26 @@ + + + Resources/user.png + Resources/server.ico + Resources/LocalTime.png + Resources/crownTime.png + Resources/start.png + Resources/stop.png + Resources/visual_studio_dark.qss + Resources/mail.png + + + sound/exit.wav + sound/pushFailed.wav + sound/readOrder.wav + sound/relogin.wav + sound/update.wav + + + Resources/icons/checkmark.png + Resources/icons/close.png + Resources/icons/down_arrow.png + Resources/icons/down_arrow_light.svg + Resources/icons/restore.png + + diff --git a/CrownServer/CrownServer.rc b/CrownServer/CrownServer.rc new file mode 100644 index 0000000..7e2810f Binary files /dev/null and b/CrownServer/CrownServer.rc differ diff --git a/CrownServer/CrownServer.ui b/CrownServer/CrownServer.ui new file mode 100644 index 0000000..f754d3f --- /dev/null +++ b/CrownServer/CrownServer.ui @@ -0,0 +1,567 @@ + + + CrownServerClass + + + + 0 + 0 + 1317 + 945 + + + + CrownServer + + + + + + + + + + + 端口: + + + + + + + true + + + + + + + + + + + 密码: + + + + + + + + 0 + 0 + + + + 88888 + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 18 + 20 + + + + + + + + + + 注单筛选 + + + + + + + 设 置 + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 18 + 20 + + + + + + + + 开 始 + + + + + + + true + + + + 50 + 50 + + + + #stateButton{border:none; padding: 0px;} + + + + + + + :/CrownServer/Resources/stop.png:/CrownServer/Resources/stop.png + + + + 64 + 64 + + + + true + + + + + + + false + + + 停 止 + + + + + + + PointingHandCursor + + + #crownTimeButton{border:none; padding: 0px;} + + + 皇冠时间 + + + + :/CrownServer/Resources/LocalTime.png:/CrownServer/Resources/LocalTime.png + + + + 50 + 50 + + + + Qt::ToolButtonTextUnderIcon + + + + + + + #button_notice{border:none; padding: 0px;} + + + 信息推送 + + + + :/CrownServer/Resources/mail.png:/CrownServer/Resources/mail.png + + + + 50 + 50 + + + + Qt::ToolButtonTextUnderIcon + + + + + + + Qt::Horizontal + + + + 78 + 20 + + + + + + + + + + + + + + + + + + + Qt::Horizontal + + + + 38 + 17 + + + + + + + + + + + + + + + Qt::Horizontal + + + + 278 + 17 + + + + + + + + + + 0 + + + + 皇冠代理 + + + + + + + 0 + 600 + + + + + https://www.baidu.com/ + + + + + + + + 6 + + + QLayout::SetDefaultConstraint + + + + + + 16777215 + 20 + + + + 网址: + + + + + + + + 0 + 0 + + + + + 250 + 0 + + + + true + + + + + + + + 16777215 + 20 + + + + 账号: + + + + + + + + 0 + 0 + + + + + 120 + 16777215 + + + + + 0 + 0 + + + + + 0 + 0 + + + + Twxm6699 + + + + + + + + 16777215 + 20 + + + + 密码: + + + + + + + + 0 + 0 + + + + + 120 + 16777215 + + + + Az123456 + + + + + + + + 16777215 + 20 + + + + 级别: + + + + + + + + 50 + 0 + + + + + 3 + + + + + 2 + + + + + 1 + + + + + + + + + 16777215 + 20 + + + + 安全码: + + + + + + + + 0 + 0 + + + + + 90 + 16777215 + + + + + + + + 登 录 + + + + + + + PointingHandCursor + + + + + + + :/CrownServer/Resources/user.png:/CrownServer/Resources/user.png + + + + 30 + 30 + + + + true + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + 读取注单 + + + + + + + + + + 运行日志 + + + + + + + + + + + + + + + + QWebEngineView + QWidget +
QtWebEngineWidgets/QWebEngineView
+
+ + ComboBox + QComboBox +
combobox.h
+
+ + TreeView + QTreeView +
treeview.h
+
+
+ + + + +
diff --git a/CrownServer/CrownServer.ui.backup b/CrownServer/CrownServer.ui.backup new file mode 100644 index 0000000..b492fc0 --- /dev/null +++ b/CrownServer/CrownServer.ui.backup @@ -0,0 +1,581 @@ + + + CrownServerClass + + + + 0 + 0 + 1317 + 945 + + + + CrownServer + + + + + + + + + + + IP: + + + + + + + true + + + + 127.0.0.1 + + + + + + + + + + + + 端口: + + + + + + + true + + + + + + + + + + + 密码: + + + + + + + + 0 + 0 + + + + 88888 + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 18 + 20 + + + + + + + + + + 读取项目 + + + + + + + 注单筛选 + + + + + + + 设 置 + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 18 + 20 + + + + + + + + 开 始 + + + + + + + + 50 + 50 + + + + #stateButton{border:none; padding: 0px;} + + + + + + + :/CrownServer/Resources/stop.png:/CrownServer/Resources/stop.png + + + + 64 + 64 + + + + true + + + + + + + + + + :/CrownServer/Resources/stop.png + + + + + + + false + + + 停 止 + + + + + + + PointingHandCursor + + + #crownTimeButton{border:none; padding: 0px;} + + + 皇冠时间 + + + + :/CrownServer/Resources/LocalTime.png:/CrownServer/Resources/LocalTime.png + + + + 50 + 50 + + + + Qt::ToolButtonTextUnderIcon + + + + + + + Qt::Horizontal + + + + 78 + 20 + + + + + + + + + + + + + + + + + + + Qt::Horizontal + + + + 38 + 17 + + + + + + + + + + + + + + + Qt::Horizontal + + + + 278 + 17 + + + + + + + + + + 0 + + + + 皇冠代理 + + + + + + 6 + + + QLayout::SetDefaultConstraint + + + + + + 16777215 + 20 + + + + 网址: + + + + + + + + 0 + 0 + + + + + 250 + 0 + + + + true + + + + + + + + 16777215 + 20 + + + + 账号: + + + + + + + + 0 + 0 + + + + + 120 + 16777215 + + + + + 0 + 0 + + + + + 0 + 0 + + + + Twxm6699 + + + + + + + + 16777215 + 20 + + + + 密码: + + + + + + + + 0 + 0 + + + + + 120 + 16777215 + + + + Az123456 + + + + + + + + 16777215 + 20 + + + + 级别: + + + + + + + + 50 + 0 + + + + + 3 + + + + + 2 + + + + + 1 + + + + + + + + + 16777215 + 20 + + + + 安全码: + + + + + + + + 0 + 0 + + + + + 90 + 16777215 + + + + + + + + 登 录 + + + + + + + PointingHandCursor + + + + + + + :/CrownServer/Resources/user.png:/CrownServer/Resources/user.png + + + + 40 + 40 + + + + true + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + 0 + 600 + + + + + https://www.baidu.com/ + + + + + + + + + 读取注单 + + + + + + + + + + 运行日志 + + + + + + + + + + + + + + + + QWebEngineView + QWidget +
QtWebEngineWidgets/QWebEngineView
+
+ + ComboBox + QComboBox +
combobox.h
+
+ + TreeView + QTreeView +
treeview.h
+
+
+ + + + +
diff --git a/CrownServer/CustomTitleBar.cpp b/CrownServer/CustomTitleBar.cpp new file mode 100644 index 0000000..7c79917 --- /dev/null +++ b/CrownServer/CustomTitleBar.cpp @@ -0,0 +1,228 @@ +#include "CustomTitleBar.h" +#include +#include +#include +#include +#include +#include +#include +#include + +CustomTitleBar::CustomTitleBar(QWidget* parent) + : QWidget(parent) + , m_dragging(false) + , m_titleLabel(nullptr) + , m_iconLabel(nullptr) + , m_minimizeButton(nullptr) + , m_maximizeButton(nullptr) + , m_closeButton(nullptr) + , m_parentWindow(parent) +{ + setupUI(); + setFixedHeight(32); + setAttribute(Qt::WA_TranslucentBackground, true); +} + +void CustomTitleBar::setupUI() +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(8, 0, 0, 0); + layout->setSpacing(8); + + // 图标 + m_iconLabel = new QLabel(this); + m_iconLabel->setFixedSize(16, 16); + m_iconLabel->setScaledContents(true); + layout->addWidget(m_iconLabel); + + // 标题 + m_titleLabel = new QLabel(this); + m_titleLabel->setStyleSheet("color: #d4d4d4; font-size: 12px; font-weight: 500;"); + layout->addWidget(m_titleLabel); + + // 添加弹性空间 + layout->addStretch(); + + // 最小化按钮 + m_minimizeButton = new QPushButton("−", this); + m_minimizeButton->setFixedSize(32, 32); + m_minimizeButton->setStyleSheet( + "QPushButton {" + " background: transparent;" + " border: none;" + " color: #d4d4d4;" + " font-size: 14px;" + " font-weight: bold;" + "}" + "QPushButton:hover {" + " background-color: #3e3e42;" + "}" + "QPushButton:pressed {" + " background-color: #007acc;" + "}" + ); + connect(m_minimizeButton, &QPushButton::clicked, this, &CustomTitleBar::minimizeWindow); + layout->addWidget(m_minimizeButton); + + // 最大化/还原按钮 + m_maximizeButton = new QPushButton("", this); + m_maximizeButton->setFixedSize(32, 32); + m_maximizeButton->setStyleSheet( + "QPushButton {" + " background: transparent;" + " border: none;" + " color: #d4d4d4;" + " font-size: 12px;" + " font-weight: bold;" + "}" + "QPushButton:hover {" + " background-color: #3e3e42;" + "}" + "QPushButton:pressed {" + " background-color: #007acc;" + "}" + ); + connect(m_maximizeButton, &QPushButton::clicked, this, &CustomTitleBar::maximizeWindow); + layout->addWidget(m_maximizeButton); + + // 关闭按钮 + m_closeButton = new QPushButton("", this); + m_closeButton->setFixedSize(32, 32); + m_closeButton->setStyleSheet( + "QPushButton {" + " background: transparent;" + " border: none;" + " color: #d4d4d4;" + " font-size: 16px;" + " font-weight: bold;" + "}" + "QPushButton:hover {" + " background-color: #e81123;" + " color: white;" + "}" + "QPushButton:pressed {" + " background-color: #c50e1f;" + " color: white;" + "}" + ); + connect(m_closeButton, &QPushButton::clicked, this, &CustomTitleBar::closeWindow); + layout->addWidget(m_closeButton); + + updateMaximizeButton(); +} + +void CustomTitleBar::setTitle(const QString& title) +{ + if (m_titleLabel) { + m_titleLabel->setText(title); + } +} + +void CustomTitleBar::setWindowIcon(const QIcon& icon) +{ + if (m_iconLabel) { + m_iconLabel->setPixmap(icon.pixmap(16, 16)); + } +} + +void CustomTitleBar::paintEvent(QPaintEvent* event) +{ + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing); + + // 绘制深色渐变背景 + QLinearGradient gradient(0, 0, 0, height()); + gradient.setColorAt(0, QColor(37, 37, 38)); + gradient.setColorAt(1, QColor(30, 30, 30)); + + painter.fillRect(rect(), gradient); + + // 绘制底部边框 + painter.setPen(QColor(60, 60, 60)); + painter.drawLine(0, height() - 1, width(), height() - 1); +} + +void CustomTitleBar::mousePressEvent(QMouseEvent* event) +{ + if (event->button() == Qt::LeftButton) { + m_dragging = true; + m_dragPosition = event->globalPos() - m_parentWindow->frameGeometry().topLeft(); + event->accept(); + } +} + +void CustomTitleBar::mouseMoveEvent(QMouseEvent* event) +{ + if (m_dragging && (event->buttons() & Qt::LeftButton)) { + m_parentWindow->move(event->globalPos() - m_dragPosition); + event->accept(); + } +} + +void CustomTitleBar::mouseReleaseEvent(QMouseEvent* event) +{ + if (event->button() == Qt::LeftButton) { + m_dragging = false; + event->accept(); + } +} + +void CustomTitleBar::mouseDoubleClickEvent(QMouseEvent* event) +{ + if (event->button() == Qt::LeftButton) { + maximizeWindow(); + event->accept(); + } +} + +bool CustomTitleBar::eventFilter(QObject* obj, QEvent* event) +{ + if (event->type() == QEvent::WindowStateChange) { + updateMaximizeButton(); + } + return QWidget::eventFilter(obj, event); +} + +void CustomTitleBar::minimizeWindow() +{ + if (m_parentWindow) { + m_parentWindow->showMinimized(); + } +} + +void CustomTitleBar::maximizeWindow() +{ + if (m_parentWindow) { + if (m_parentWindow->isMaximized()) { + m_parentWindow->showNormal(); + } else { + m_parentWindow->showMaximized(); + } + updateMaximizeButton(); + } +} + +void CustomTitleBar::closeWindow() +{ + if (m_parentWindow) { + m_parentWindow->close(); + } +} + +void CustomTitleBar::updateMaximizeButton() +{ + if (m_maximizeButton && m_parentWindow) { + if (m_parentWindow->isMaximized()) { + m_maximizeButton->setText("❐"); + } else { + m_maximizeButton->setText(""); + } + } +} + +bool CustomTitleBar::isMaximized() const +{ + return m_parentWindow ? m_parentWindow->isMaximized() : false; +} + +#include "CustomTitleBar.moc" diff --git a/CrownServer/CustomTitleBar.h b/CrownServer/CustomTitleBar.h new file mode 100644 index 0000000..51abed6 --- /dev/null +++ b/CrownServer/CustomTitleBar.h @@ -0,0 +1,47 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class CustomTitleBar : public QWidget +{ + Q_OBJECT + +public: + explicit CustomTitleBar(QWidget* parent = nullptr); + void setTitle(const QString& title); + void setWindowIcon(const QIcon& icon); + +protected: + void paintEvent(QPaintEvent* event) override; + void mousePressEvent(QMouseEvent* event) override; + void mouseMoveEvent(QMouseEvent* event) override; + void mouseReleaseEvent(QMouseEvent* event) override; + void mouseDoubleClickEvent(QMouseEvent* event) override; + bool eventFilter(QObject* obj, QEvent* event) override; + +private slots: + void minimizeWindow(); + void maximizeWindow(); + void closeWindow(); + +private: + void setupUI(); + void updateMaximizeButton(); + bool isMaximized() const; + QPoint m_dragPosition; + bool m_dragging; + + QLabel* m_titleLabel; + QLabel* m_iconLabel; + QPushButton* m_minimizeButton; + QPushButton* m_maximizeButton; + QPushButton* m_closeButton; + QWidget* m_parentWindow; +}; diff --git a/CrownServer/Global.cpp b/CrownServer/Global.cpp new file mode 100644 index 0000000..adfc82f --- /dev/null +++ b/CrownServer/Global.cpp @@ -0,0 +1,15 @@ +#include "Global.h" + +Verify* g_verify; +Config* g_config; + +QString dateFormat(QString source) +{ + QList list = source.split("-"); + if (list.count() == 3) + { + return list[2] + "-" + list[0] + "-" + list[1]; + } + + return QString(); +} \ No newline at end of file diff --git a/CrownServer/Global.h b/CrownServer/Global.h new file mode 100644 index 0000000..6363571 --- /dev/null +++ b/CrownServer/Global.h @@ -0,0 +1,13 @@ +#pragma once +#include "Verify.h" +#include "Config.h" +#include "VersionUpdate.h" + +#include "VMProtectSDK.h" +extern Verify* g_verify; +extern Config* g_config; + +#define VERSION (QString)(VersionUpdate::GetVersion()) + + +extern QString dateFormat(QString source); \ No newline at end of file diff --git a/CrownServer/Login.cpp b/CrownServer/Login.cpp new file mode 100644 index 0000000..101927b --- /dev/null +++ b/CrownServer/Login.cpp @@ -0,0 +1,123 @@ +#include "Login.h" +#include "Global.h" +#include "CrownServer.h" +#include "AppInstanceManager.h" + +Login::Login(QWidget* parent) + : QMainWindow(parent) +{ + ui.setupUi(this); + + ///////////////////////////////////////////////////// + // 应用接口管理(防止多开) + ///////////////////////////////////////////////////// + connect(AppInstanceManager::instance(), &AppInstanceManager::raiseRequested, + this, [this]() { + show(); + raise(); + activateWindow(); + }); + + ///////////////////////////////////////////////////// + // 窗口设置 + ///////////////////////////////////////////////////// + this->setFixedSize(394, 158); + setWindowFlags(Qt::Dialog); + setWindowFlags(Qt::WindowCloseButtonHint); + this->setWindowIcon(QIcon(":/CrownServer/Resources/server.ico")); + this->setWindowTitle("金运来皇冠跟单软件(服务端)"); + ui.timeLabel->setHidden(true); + + ui.usernameEdit->setText(g_config->verifyUsername()); + ui.passwordEdit->setText(g_config->verifyPassword()); + ui.autoLoginCheck->setChecked(g_config->autoLogin()); + connect(ui.LoginButton, &QPushButton::clicked, this, &Login::slotLogin); + + + + ///////////////////////////////////////////////////// + // 自动登录 + ///////////////////////////////////////////////////// + m_timer = new QTimer(); + if (ui.autoLoginCheck->isChecked() && !ui.usernameEdit->text().isNull() && !ui.passwordEdit->text().isNull()) + { + ui.timeLabel->setHidden(false); + m_time = 5; + connect(m_timer, &QTimer::timeout, this, [&]() { + if (m_time > 0) + { + m_time--; + ui.timeLabel->setText("

" + QString::number(m_time) + "

"); + } + else + { + if (m_timer->isActive()) + { + emit ui.LoginButton->clicked(); + } + } + }); + + if (!m_timer->isActive()) + { + m_timer->start(1000); + } + } + + +} + +Login::~Login() +{} + + +void Login::slotLogin() +{ + VMProtectBegin("Login_Btn"); + // 停止定时器 + if (m_timer->isActive()) + { + m_timer->stop(); + } + + // 禁用登录按钮 + ui.LoginButton->setDisabled(true); + + // 获取账号密码 + QString username = ui.usernameEdit->text(); + QString password = ui.passwordEdit->text(); + + if (username.isEmpty() || password.isEmpty()) + { + QMessageBox::warning(this, "错误", "账号或密码为空"); + } + else + { + QString result; + + + if (g_verify->Login(username, password, result)) + { + // 断开所有信号连接(防止残留响应) + disconnect(AppInstanceManager::instance(), nullptr, this, nullptr); + CrownServer* server = new CrownServer(); + server->show(); + this->close(); + } + else + { + // 如果密码正确考虑OpenSSL库问题 + QMessageBox::warning(this, "登录失败", result); + } + } + // 激活登录按钮 + ui.LoginButton->setDisabled(false); + VMProtectEnd(); +} + +void Login::closeEvent(QCloseEvent* event) +{ + g_config->setVerifyUsername(ui.usernameEdit->text()); + g_config->setVerifyPassword(ui.passwordEdit->text()); + g_config->setAutoLogin(ui.autoLoginCheck->isChecked()); +} \ No newline at end of file diff --git a/CrownServer/Login.h b/CrownServer/Login.h new file mode 100644 index 0000000..695c8fe --- /dev/null +++ b/CrownServer/Login.h @@ -0,0 +1,27 @@ +#pragma once + +#include +#include +#include +#include +#include "ui_Login.h" + +class Login : public QMainWindow +{ + Q_OBJECT + +public: + Login(QWidget* parent = nullptr); + ~Login(); +private: + QTimer* m_timer; + int m_time; + +private: + void closeEvent(QCloseEvent* event); +private slots: + void slotLogin(); +private: + Ui::LoginClass ui; + +}; diff --git a/CrownServer/Login.ui b/CrownServer/Login.ui new file mode 100644 index 0000000..596b093 --- /dev/null +++ b/CrownServer/Login.ui @@ -0,0 +1,108 @@ + + + LoginClass + + + + 0 + 0 + 394 + 158 + + + + Login + + + + + + + + 120 + 120 + + + + image: url(:/CrownServer/Resources/server.ico); + + + + + + + + + + + + + + + + + + + + 账号: + + + + + + + + + + + + + + 密码: + + + + + + + + + + + + + + <html><head/><body><p><span style=" color:#ff0000;">5秒</span></p></body></html> + + + + + + + 自动登录 + + + + + + + 登录 + + + + + + + + + + + + + + + + + + + diff --git a/CrownServer/MessageHandle.h b/CrownServer/MessageHandle.h new file mode 100644 index 0000000..8ead30d --- /dev/null +++ b/CrownServer/MessageHandle.h @@ -0,0 +1,68 @@ +#pragma once +#include +#include +#include +#include +#include +#include + +// 自定义日志处理器 +void message_handle(QtMsgType type, const QMessageLogContext& context, const QString& msg) +{ + // 获取时间戳 + QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz"); + + // 获取日志级别 + QString logLevel; + switch (type) { + case QtDebugMsg: + logLevel = "DEBUG"; + break; + case QtWarningMsg: + logLevel = "WARNING"; + break; + case QtCriticalMsg: + logLevel = "CRITICAL"; + break; + case QtFatalMsg: + logLevel = "FATAL"; + break; + } + + // 获取文件名、行号、函数名 + QString fileName = context.file; + int lineNumber = context.line; + QString functionName = context.function; + + // 格式化日志信息 + QString logMessage = QString("[%1] [%2] [%3:%4 - %5] %6") + .arg(timestamp) + .arg(logLevel) + .arg(fileName) + .arg(lineNumber) + .arg(functionName) + .arg(msg); + + // 方案1:在可执行文件同目录 + QString logPath = QCoreApplication::applicationDirPath() + "/application_server.log"; + + // 方案2:在用户文档目录 + // QString logPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/MyApp/application.log"; + + // 方案3:在临时目录 + // QString logPath = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + "/application.log"; + + // 方案4:在当前工作目录(VS 可能设置的工作目录) + // QString logPath = "application.log"; + + // 输出到文件 + QFile logFile(logPath); + if (logFile.open(QIODevice::Append | QIODevice::Text)) { + QTextStream out(&logFile); + out << logMessage << Qt::endl; // 使用 Qt::endl + logFile.close(); + } + + // 也可以将日志输出到控制台 + //qDebug() << logMessage; +} diff --git a/CrownServer/Notice.cpp b/CrownServer/Notice.cpp new file mode 100644 index 0000000..3fff155 --- /dev/null +++ b/CrownServer/Notice.cpp @@ -0,0 +1,37 @@ +#include "Notice.h" +#include "Global.h" +Notice::Notice(QWidget *parent) + : QWidget(parent) +{ + ui.setupUi(this); + + // 设置固定窗口大小 + this->setFixedSize(394, 158); + // Dialog窗口去除最小化最大化按钮 + setWindowFlags(Qt::Dialog); + setWindowFlags(Qt::WindowCloseButtonHint); + // 设置窗口标题 + this->setWindowTitle("推送设置"); + // 设置窗口图标 + this->setWindowIcon(QIcon(":/CrownServer/Resources/server.ico")); + + + ui.checkBox->setChecked(g_config->notice_status()); + ui.lineEdit->setText(g_config->notice_account()); + connect(ui.test_button, &QPushButton::clicked, this, [&]() { + + g_verify->push_msg("test_push","服务端", ui.lineEdit->text(),QMap()); + + }); + + +} + +Notice::~Notice() +{} + +void Notice::closeEvent(QCloseEvent * event) +{ + g_config->set_notice_status(ui.checkBox->isChecked()); + g_config->set_notice_account(ui.lineEdit->text()); +} diff --git a/CrownServer/Notice.h b/CrownServer/Notice.h new file mode 100644 index 0000000..2d8b3de --- /dev/null +++ b/CrownServer/Notice.h @@ -0,0 +1,17 @@ +#pragma once + +#include +#include "ui_Notice.h" + +class Notice : public QWidget +{ + Q_OBJECT + +public: + Notice(QWidget *parent = nullptr); + ~Notice(); +private: + void closeEvent(QCloseEvent* event); +private: + Ui::NoticeClass ui; +}; diff --git a/CrownServer/Notice.ui b/CrownServer/Notice.ui new file mode 100644 index 0000000..80ccdea --- /dev/null +++ b/CrownServer/Notice.ui @@ -0,0 +1,52 @@ + + + NoticeClass + + + + 0 + 0 + 376 + 153 + + + + Notice + + + + + + + + 启用通知 + + + + + + + + + + 测试通知 + + + + + + + + + 填写Telegram或邮箱账号即可 +支持私聊或群通知 +需先添加机器人 JYL88_bot 为好友或拉入群聊 + + + + + + + + + diff --git a/CrownServer/PushMsg.cpp b/CrownServer/PushMsg.cpp new file mode 100644 index 0000000..c386ec5 --- /dev/null +++ b/CrownServer/PushMsg.cpp @@ -0,0 +1,20 @@ +#include "PushMsg.h" +#include "Global.h" + +void PushMsg::push(QString type,QString account, QMap order) +{ + if (g_config->notice_status() && account != "") + { + g_verify->push_msg(type, "服务端", account, order); + } + else + { + if (type == "read_order") + { + g_verify->push_msg(type, "服务端", account, order); + } + } + + + emit resultReady("推送请求结束"); +} \ No newline at end of file diff --git a/CrownServer/PushMsg.h b/CrownServer/PushMsg.h new file mode 100644 index 0000000..830eab0 --- /dev/null +++ b/CrownServer/PushMsg.h @@ -0,0 +1,15 @@ +#pragma once +#include + + + +class PushMsg : public QObject { + Q_OBJECT +public: + explicit PushMsg(QObject* parent = nullptr) :QObject(parent) {}; +signals: + void resultReady(const QString &result); + void log(QString log); +public slots: + void push(QString type, QString account, QMap order); +}; \ No newline at end of file diff --git a/CrownServer/QSQLITE b/CrownServer/QSQLITE new file mode 100644 index 0000000..e69de29 diff --git a/CrownServer/ReportThread.cpp b/CrownServer/ReportThread.cpp new file mode 100644 index 0000000..4eedaa2 --- /dev/null +++ b/CrownServer/ReportThread.cpp @@ -0,0 +1,918 @@ +#include "ReportThread.h" +#include "Global.h" +#include "Utils.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "PushMsg.h" + +ReportThread::ReportThread() + : m_wakeUpRequested(false) + , m_isPaused(false) +{ + // 注册自定义类型 + qRegisterMetaType>>("QList>"); +} + +ReportThread::~ReportThread() +{ + stopImmediately(); + if (this->isRunning()) { + this->wait(1000); + } +} +void ReportThread::stopImmediately() +{ + { + // 创建互斥锁保护器,锁定互斥锁,确保线程安全地访问共享变量 + QMutexLocker lock(&m_mutex); + + // 设置唤醒请求标志为true,表示外部请求立即停止线程 + m_wakeUpRequested = true; + + // 设置暂停状态为false,确保线程不会被卡在暂停等待中 + m_isPaused = false; + } // 此处QMutexLocker超出作用域,自动释放互斥锁 + + // 唤醒所有正在条件变量上等待的线程 + // 这会中断interruptibleSleep()中的等待,让线程立即继续执行 + m_waitCondition.wakeAll(); + + // 请求线程中断,设置Qt线程的中断标志 + // 这会让isInterruptionRequested()返回true,线程run()方法中的循环会检测到这个标志并退出 + this->requestInterruption(); +} + +void ReportThread::interruptibleSleep(int milliseconds) +{ + if (milliseconds <= 0 || this->isInterruptionRequested()) return; + + QMutexLocker lock(&m_mutex); + if (m_wakeUpRequested) return; + + m_waitCondition.wait(&m_mutex, milliseconds); +} + +QByteArray ReportThread::interruptibleNetworkRequest(QNetworkAccessManager& manager, QNetworkRequest& request, const QByteArray& data, int timeoutMs) +{ + if (this->isInterruptionRequested() || m_wakeUpRequested) { + return QByteArray(); + } + + QNetworkReply* reply = manager.post(request, data); + reply->ignoreSslErrors(); + + QEventLoop eventLoop; + QTimer timeoutTimer; + timeoutTimer.setSingleShot(true); + + connect(&manager, &QNetworkAccessManager::finished, &eventLoop, &QEventLoop::quit); + connect(&timeoutTimer, &QTimer::timeout, &eventLoop, &QEventLoop::quit); + connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit); + + // 中断检查定时器 + QTimer interruptTimer; + interruptTimer.setInterval(100); + connect(&interruptTimer, &QTimer::timeout, [&]() { + if (this->isInterruptionRequested() || m_wakeUpRequested) { + reply->abort(); + eventLoop.quit(); + } + }); + + timeoutTimer.start(timeoutMs); + interruptTimer.start(); + eventLoop.exec(); + + interruptTimer.stop(); + timeoutTimer.stop(); + + QByteArray result; + if (!this->isInterruptionRequested() && !m_wakeUpRequested && reply->error() == QNetworkReply::NoError) { + result = reply->readAll(); + } + + reply->deleteLater(); + //qDebug() << "网络请求返回: " << result; + return result; +} + +bool ReportThread::screen_user(QString NAME0) +{ + auto policy_list = g_config->screen_list(); + for (auto policy : policy_list) + { + if (policy["username"] == NAME0) + { + if (policy["policy"] == "false") + { + return false; + } + break; + } + } + // 默认跟单 + return true; + //// 判断是否启用筛选功能 + //if (!g_config->screenEnable()) + //{ + // return true; + //} + + //// 匹配模式 + //if (g_config->screenMode() == 0) + //{ + // QList> list = g_config->screenUsernameList(); + // if (list.count() > 0) + // { + // for (int i = 0; i < list.count(); i++) + // { + // QMap rowData = list[i]; + // if (rowData.contains("row")) + // { + // int row = rowData["row"].toInt(); + // bool enable = rowData["enable"] == "true" ? true : false; + // QString username = rowData["username"]; + // if (enable) + // { + // if (username == NAME0) + // { + // // 匹配模式则跟 + // return true; + // } + // } + // } + + // } + // } + // return false; + //} + //else + //{ + // QList> list = g_config->screenUsernameList(); + // if (list.count() > 0) + // { + // for (int i = 0; i < list.count(); i++) + // { + // QMap rowData = list[i]; + // if (rowData.contains("row")) + // { + // int row = rowData["row"].toInt(); + // bool enable = rowData["enable"] == "true" ? true : false; + // QString username = rowData["username"]; + // if (enable) + // { + // if (username == NAME0) + // { + // // 匹配模式则跟 + // return false; + // } + // } + // } + + // } + // } + // return true; + //} +} + + + + +void ReportThread::run() +{ + while (!this->isInterruptionRequested() && !m_wakeUpRequested) { + { + QMutexLocker lock(&m_mutex); + if (m_wakeUpRequested) break; + + // 检查暂停状态 + while (m_isPaused && !m_wakeUpRequested && !this->isInterruptionRequested()) { + m_waitCondition.wait(&m_mutex, 100); + } + if (m_wakeUpRequested) break; + } + + //qDebug() << "线程执行: 读取注单"; + emit read(); + + // 开始时间点 + auto start = std::chrono::steady_clock::now(); + + QString date_start = QDateTime::currentDateTime().addSecs(-43200).toString("yyyy-MM-dd"); + QString date_end = QDateTime::currentDateTime().addSecs(-43200).addMonths(12).toString("yyyy-MM-dd"); + + // co -> su -> ag + + // 筛选策略 + auto policy_list = g_config->screen_list(); + + + + + + + if (m_current_agent_type == "co") + { + // 自身默认读取 + auto co_list = get_report_co(date_start, date_end); + for (auto co : co_list) + { + if (!screen_user(co["NAME0"])) + { + continue; + } + auto su_list = get_report_su(co["ACTION0"], date_start, date_end); + for (auto su : su_list) + { + if (!screen_user(su["NAME0"])) + { + continue; + } + auto ag_list = get_report_ag(su["ACTION0"], date_start, date_end); + for (auto ag : ag_list) + { + if (!screen_user(ag["NAME0"])) + { + continue; + } + auto mem_list = get_report_mem(ag["ACTION0"], date_start, date_end); + + for (auto mem : mem_list) + { + if (!screen_user(mem["NAME0"])) + { + continue; + } + auto order_list = get_report_list_bet(mem["ACTION0"], date_start, date_end); + emit update_orders(order_list); + } + + } + } + } + + } + + else if (m_current_agent_type == "su") + { + auto su_list = get_report_su("",date_start, date_end); + for (auto su : su_list) + { + if (!screen_user(su["NAME0"])) + { + continue; + } + auto ag_list = get_report_ag(su["ACTION0"], date_start, date_end); + for (auto ag : ag_list) + { + if (!screen_user(ag["NAME0"])) + { + continue; + } + auto mem_list = get_report_mem(ag["ACTION0"], date_start, date_end); + + for (auto mem : mem_list) + { + if (!screen_user(mem["NAME0"])) + { + continue; + } + auto order_list = get_report_list_bet(mem["ACTION0"], date_start, date_end); + emit update_orders(order_list); + } + + } + } + } + else if (m_current_agent_type == "ag") + { + auto ag_list = get_report_ag("",date_start, date_end); + for (auto ag : ag_list) + { + if (!screen_user(ag["NAME0"])) + { + continue; + } + auto mem_list = get_report_mem(ag["ACTION0"], date_start, date_end); + + for (auto mem : mem_list) + { + if (!screen_user(mem["NAME0"])) + { + continue; + } + auto order_list = get_report_list_bet(mem["ACTION0"], date_start, date_end); + emit update_orders(order_list); + } + + } + } + + + // auto current_agent_type = g_config-> + // ag + + + // 结束时间点 + auto end = std::chrono::steady_clock::now(); + // 计算持续时间 + std::chrono::duration elapsed_seconds = end - start; + //qDebug() << "time:" << elapsed_seconds.count(); + + + interruptibleSleep(g_config->readReportListInterVal() * 1000); + } + + //qDebug() << "OrderThread 安全退出"; +} + +void ReportThread::pause() +{ + QMutexLocker lock(&m_mutex); + m_isPaused = true; +} + +void ReportThread::resume() +{ + QMutexLocker lock(&m_mutex); + m_isPaused = false; + m_waitCondition.wakeAll(); +} + +QList> ReportThread::get_report_co(QString date_start, QString date_end) +{ +GET_LEAGUE_WAGER: + + if (this->isInterruptionRequested() || m_wakeUpRequested) { + return QList>(); + } + + QNetworkAccessManager networkManager; + QNetworkRequest request; + request.setUrl(QUrl(QString(m_url + "transform.php?ver=" + m_ver))); + + request.setRawHeader("Accept", "*/*"); + request.setRawHeader("Cookie", m_cookies.toUtf8()); + request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); + request.setRawHeader("Origin", m_url.toUtf8()); + request.setRawHeader("Referer", m_url.toUtf8()); + request.setRawHeader("Host", QUrl(m_url).host().toUtf8()); + + QString data = QString("login_layer=%1&uid=%2&langx=%3&ver=%4&p=get_report_co&report_kind=A&result_type=N&date_start=%5&date_end=%6>ype=&wtype=").arg(m_login_layer).arg(m_uid) + .arg(m_langx).arg(m_ver).arg(date_start).arg(date_end); + + QByteArray result = interruptibleNetworkRequest(networkManager, request, data.toUtf8()); + if (result.isEmpty() || this->isInterruptionRequested() || m_wakeUpRequested) { + return QList>(); + } + + QJsonDocument document = QJsonDocument::fromJson(result); + if (document.isNull()) { + return QList>(); + } + + QJsonObject jsonObject = document.object(); + if (jsonObject["status"].toString() == "error") { + // 系统忙碌中,请稍候再查询 + if (jsonObject["code"].toString() == "m_rep") { + //qDebug() << "获取代理忙碌"; + // 可中断的重试等待 + interruptibleSleep(3000); + if (!this->isInterruptionRequested() && !m_wakeUpRequested) { + goto GET_LEAGUE_WAGER; + } + } + else if (jsonObject["code"].toString() == "4X014") { + // qDebug() << "账户掉线"; + emit account_disconnect(); + } + qDebug() << "[get_report_co]其他错误:" << result; + return QList>(); + } + + //qDebug() << result; + + // 获取 data.array.row0 数组 + QJsonObject dataObj = jsonObject["data"].toObject(); + QJsonObject arrayObj = dataObj["array"].toObject(); + QJsonArray row0Array = arrayObj["row0"].toArray(); + + if (row0Array.isEmpty()) { + return QList>(); + } + + QList> list; + for (int i = 0; i < row0Array.count(); i++) { + if (this->isInterruptionRequested() || m_wakeUpRequested) break; + + QJsonObject row0Json = row0Array.at(i).toObject(); + QMap map; + + // 只提取需要的字段 + map.insert("ACTION0", row0Json["ACTION0"].toString()); + map.insert("NAME0", row0Json["NAME0"].toString()); + map.insert("AID0", row0Json["AID0"].toString()); + map.insert("SID0", row0Json["SID0"].toString()); + + list.append(map); + } + + return list; +} +QList> ReportThread::get_report_su(QString ACTION0, QString date_start, QString date_end) +{ +GET_LEAGUE_WAGER: + + if (this->isInterruptionRequested() || m_wakeUpRequested) { + return QList>(); + } + + QNetworkAccessManager networkManager; + QNetworkRequest request; + request.setUrl(QUrl(QString(m_url + "transform.php?ver=" + m_ver))); + + request.setRawHeader("Accept", "*/*"); + request.setRawHeader("Cookie", m_cookies.toUtf8()); + request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); + request.setRawHeader("Origin", m_url.toUtf8()); + request.setRawHeader("Referer", m_url.toUtf8()); + request.setRawHeader("Host", QUrl(m_url).host().toUtf8()); + + QString data; + if (ACTION0 == "") + { + data = QString("login_layer=%1&uid=%2&langx=%3&ver=%4&p=get_report_su&report_kind=A&result_type=N&date_start=%5&date_end=%6>ype=&wtype=").arg(m_login_layer).arg(m_uid) + .arg(m_langx).arg(m_ver).arg(date_start).arg(date_end); + } + else + { + data = QString("login_layer=%1&uid=%2&langx=%3&ver=%4&p=get_report_su&%5&report_kind=A&result_type=N&date_start=%6&date_end=%7>ype=&wtype=").arg(m_login_layer).arg(m_uid) + .arg(m_langx).arg(m_ver).arg(ACTION0).arg(date_start).arg(date_end); + } + + QByteArray result = interruptibleNetworkRequest(networkManager, request, data.toUtf8()); + if (result.isEmpty() || this->isInterruptionRequested() || m_wakeUpRequested) { + return QList>(); + } + + QJsonDocument document = QJsonDocument::fromJson(result); + if (document.isNull()) { + return QList>(); + } + + QJsonObject jsonObject = document.object(); + if (jsonObject["status"].toString() == "error") { + // 系统忙碌中,请稍候再查询 + if (jsonObject["code"].toString() == "m_rep") { + //qDebug() << "获取代理忙碌"; + // 可中断的重试等待 + interruptibleSleep(3000); + if (!this->isInterruptionRequested() && !m_wakeUpRequested) { + goto GET_LEAGUE_WAGER; + } + } + else if (jsonObject["code"].toString() == "4X014") { + emit account_disconnect(); + } + qDebug() << "[get_report_su]其他错误:" << result; + return QList>(); + } + + //qDebug() << result; + + // 获取 data.array.row0 数组 + QJsonObject dataObj = jsonObject["data"].toObject(); + QJsonObject arrayObj = dataObj["array"].toObject(); + QJsonArray row0Array = arrayObj["row0"].toArray(); + + if (row0Array.isEmpty()) { + return QList>(); + } + + QList> list; + for (int i = 0; i < row0Array.count(); i++) { + if (this->isInterruptionRequested() || m_wakeUpRequested) break; + + QJsonObject row0Json = row0Array.at(i).toObject(); + QMap map; + + // 只提取需要的字段 + map.insert("ACTION0", row0Json["ACTION0"].toString()); + map.insert("NAME0", row0Json["NAME0"].toString()); + map.insert("AID0", row0Json["AID0"].toString()); + map.insert("SID0", row0Json["SID0"].toString()); + + list.append(map); + } + + return list; +} + +QList> ReportThread::get_report_ag(QString ACTION0, QString date_start, QString date_end) +{ +GET_LEAGUE_WAGER: + + if (this->isInterruptionRequested() || m_wakeUpRequested) { + return QList>(); + } + + QNetworkAccessManager networkManager; + QNetworkRequest request; + request.setUrl(QUrl(QString(m_url + "transform.php?ver=" + m_ver))); + + request.setRawHeader("Accept", "*/*"); + request.setRawHeader("Cookie", m_cookies.toUtf8()); + request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); + request.setRawHeader("Origin", m_url.toUtf8()); + request.setRawHeader("Referer", m_url.toUtf8()); + request.setRawHeader("Host", QUrl(m_url).host().toUtf8()); + + QString data; + if (ACTION0 == "") + { + data = QString("login_layer=%1&uid=%2&langx=%3&ver=%4&p=get_report_ag&report_kind=A&result_type=N&date_start=%5&date_end=%6>ype=&wtype=").arg(m_login_layer).arg(m_uid) + .arg(m_langx).arg(m_ver).arg(date_start).arg(date_end); + } + else + { + data = QString("login_layer=%1&uid=%2&langx=%3&ver=%4&p=get_report_ag&%5&report_kind=A&result_type=N&date_start=%6&date_end=%7>ype=&wtype=").arg(m_login_layer).arg(m_uid) + .arg(m_langx).arg(m_ver).arg(ACTION0).arg(date_start).arg(date_end); + } + + + QByteArray result = interruptibleNetworkRequest(networkManager, request, data.toUtf8()); + if (result.isEmpty() || this->isInterruptionRequested() || m_wakeUpRequested) { + return QList>(); + } + + QJsonDocument document = QJsonDocument::fromJson(result); + if (document.isNull()) { + return QList>(); + } + + QJsonObject jsonObject = document.object(); + if (jsonObject["status"].toString() == "error") { + // 系统忙碌中,请稍候再查询 + if (jsonObject["code"].toString() == "m_rep") { + //qDebug() << "获取代理忙碌"; + // 可中断的重试等待 + interruptibleSleep(3000); + if (!this->isInterruptionRequested() && !m_wakeUpRequested) { + goto GET_LEAGUE_WAGER; + } + } + // 强行处理 + //emit account_disconnect(); + else if (jsonObject["code"].toString() == "4X014") { + emit account_disconnect(); + } + qDebug() << "[get_report_ag]其他错误:" << result; + return QList>(); + } + + //qDebug() << result; + + // 获取 data.array.row0 数组 + QJsonObject dataObj = jsonObject["data"].toObject(); + QJsonObject arrayObj = dataObj["array"].toObject(); + QJsonArray row0Array = arrayObj["row0"].toArray(); + + if (row0Array.isEmpty()) { + return QList>(); + } + + QList> list; + for (int i = 0; i < row0Array.count(); i++) { + if (this->isInterruptionRequested() || m_wakeUpRequested) break; + + QJsonObject row0Json = row0Array.at(i).toObject(); + QMap map; + + // 只提取需要的字段 + map.insert("ACTION0", row0Json["ACTION0"].toString()); + map.insert("NAME0", row0Json["NAME0"].toString()); + map.insert("AID0", row0Json["AID0"].toString()); + map.insert("SID0", row0Json["SID0"].toString()); + + list.append(map); + } + + return list; +} + +QList> ReportThread::get_report_mem(QString ACTION0, QString date_start, QString date_end) +{ + if (this->isInterruptionRequested() || m_wakeUpRequested) { + return QList>(); + } + +REQUERY_ALLBET_WAGER: + QNetworkAccessManager networkManager; + QNetworkRequest request; + request.setUrl(QUrl(QString(m_url + "transform.php?ver=" + m_ver))); + request.setRawHeader("Accept", "*/*"); + request.setRawHeader("Cookie", m_cookies.toUtf8()); + request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); + request.setRawHeader("Origin", m_url.toUtf8()); + request.setRawHeader("Referer", m_url.toUtf8()); + request.setRawHeader("Host", QUrl(m_url).host().toUtf8()); + + QString data = QString("login_layer=%1&uid=%2&langx=%3&ver=%4&p=get_report_mem&%5&report_kind=A&result_type=N&date_start=%6&date_end=%7>ype=&wtype=") + .arg(m_login_layer).arg(m_uid).arg(m_langx).arg(m_ver).arg(ACTION0).arg(date_start).arg(date_end); + + QByteArray result = interruptibleNetworkRequest(networkManager, request, data.toUtf8()); + if (result.isEmpty() || this->isInterruptionRequested() || m_wakeUpRequested) { + return QList>(); + } + + QJsonDocument document = QJsonDocument::fromJson(result); + if (document.isNull()) { + return QList>(); + } + + QJsonObject jsonObject = document.object(); + if (jsonObject["status"].toString() == "error") { + // 系统忙碌中,请稍候再查询 + if (jsonObject["code"].toString() == "m_rep") { + //qDebug() << "获取用户忙碌"; + // 可中断的重试等待 + interruptibleSleep(3000); + if (!this->isInterruptionRequested() && !m_wakeUpRequested) { + goto REQUERY_ALLBET_WAGER; + } + } + //emit account_disconnect(); + else if (jsonObject["code"].toString() == "4X014") { + //qDebug() << "[网络返回失败] get_report_mem"; + //qDebug() << jsonObject; + emit account_disconnect(); + } + qDebug() << "[get_report_mem]其他错误:" << result; + return QList>(); + } + + //qDebug() << result; + + // 获取 data.array.row0 数组 + QJsonObject dataObj = jsonObject["data"].toObject(); + QJsonObject arrayObj = dataObj["array"].toObject(); + QJsonArray row0Array = arrayObj["row0"].toArray(); + + if (row0Array.isEmpty()) { + return QList>(); + } + + QList> list; + for (int i = 0; i < row0Array.count(); i++) { + if (this->isInterruptionRequested() || m_wakeUpRequested) break; + + QJsonObject row0Json = row0Array.at(i).toObject(); + QMap map; + + // 只提取需要的字段 + map.insert("NAME0", row0Json["NAME0"].toString()); + map.insert("ID0", row0Json["ID0"].toString()); + map.insert("ACTION0", row0Json["ACTION0"].toString()); + + list.append(map); + } + + return list; +} + + +//DATETIME: 下单时间(yyyy - MM - dd HH : mm:ss) +// DATE : 下单日期(MM - dd - YYYY) +// TIME : 下单时间(HH:mm:ss) +// WAGERS_ID / TID : 注单号(同值) +// SRV_IP : 下单来源标识(为空或用于区分手机 / 客户端) +// NAME0 : 会员账号 +// ALIAS0 : 会员别名 +// M_TYPE : 盘口时段 / 标识(如 D,多见于盘口分类内部标记) +// WAGERS_TYPE : 投注玩法名称(如 让球、独赢) +// G_TIME : 比赛开赛时间(MM - dd - YYYY HH : mm:ss) +// GT : 球种(如 足球、篮球) +// DIS_GT : 前端显示开关(如 hide_item) +// LEAGUE : 联赛名称 +// TEAM_H / TEAM_C : 主队 / 客队名称 +// NUM_H / NUM_C : 主队 / 客队内部编号 +// IORATIO : 赔率 +// CON : 盘口线(如 0、0 / 0.5) +// ORDER_TYPE : 实际下注对象(如 主队名 / 客队名 / 大小方向等) +// ORDER_CON : 下注的具体盘口(可能含让球数 / 大小球数等) +// GOLD : 投注金额 +// ODDF_TYPE : 盘别(如 香港盘、欧洲盘,可能为空) +// SCORE : 比分(进行中或结算时可能出现,未结为空) +// DIF_SCORE : 分差(部分玩法使用,常为空) +// RESULT_WL : 结果文案(如 注单平局 / 取消 等) +// RESULT_WL_CLASS : 结果样式class(前端用) +// RESULT_DATA : 结果明细数据(未结通常为 null) +// SETTLED : 结算标志(Y 已结,N 未结) +// WIN_GOLD : 派彩金额(未结通常为 0.0) +// WIN_GOLD_CLASS : 派彩样式class(前端用) +// ARESULT / CRESULT / SRESULT : 结果 / 派彩相关的内部字段(常为空或0) +// COMWINLOSS : 组合输赢信息(串关 / 复合时可能用,通常为空) +// BALL_ACT : 球类动作 / 事件标志(常为空) +// STRONG : 强队标记(Y / N,用于让球方) +// BET_TYPE : 投注方向(如 H 主队、C 客队等) +// IN_RADIO : 滚球注单标记 / 内部位(常为0) +// LIST_PMSG : 行内提示显示控制(none为不显示) +// LIST_NUM0 : 序号或前端列表用计数 +// FS_DIS : 冠军 / 特殊盘显示标识(常为空) +// TNAME : 前端展示用 HTML 片段(联赛 / 对阵 / 盘口 / 赔率的组合) +// TNAME_P / test / CANCEL_MSG / DELAY_REASON / CANCEL_APN / CANCEL_DIS / IS_P : 一组前端控制 / 取消原因 / 展示开关,业务为空居多 + +QList> ReportThread::get_report_list_bet(QString ACTION0, QString date_start, QString date_end) +{ + if (this->isInterruptionRequested() || m_wakeUpRequested) { + return QList>(); + } + +REQUERY_WAGERS_LIST: + QNetworkAccessManager networkManager; + QNetworkRequest request; + request.setUrl(QUrl(QString(m_url + "transform.php?ver=" + m_ver))); + request.setRawHeader("Accept", "*/*"); + request.setRawHeader("Cookie", m_cookies.toUtf8()); + request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); + request.setRawHeader("Origin", m_url.toUtf8()); + request.setRawHeader("Referer", m_url.toUtf8()); + request.setRawHeader("Host", QUrl(m_url).host().toUtf8()); + + QString data = QString("login_layer=%1&uid=%2&langx=%3&ver=%4&p=get_report_list_bet&%5&report_kind=A&result_type=N&date_start=%6&date_end=%7>ype=&wtype=") + .arg(m_login_layer).arg(m_uid).arg(m_langx).arg(m_ver).arg(ACTION0).arg(date_start).arg(date_end); + + //qDebug() << "get_report_list_bet:" << data; + + QByteArray result = interruptibleNetworkRequest(networkManager, request, data.toUtf8()); + if (result.isEmpty() || this->isInterruptionRequested() || m_wakeUpRequested) { + return QList>(); + } + + QJsonDocument document = QJsonDocument::fromJson(result); + if (document.isNull()) { + return QList>(); + } + + QJsonObject jsonObject = document.object(); + if (jsonObject["status"].toString() == "error") { + if (jsonObject["code"].toString() == "m_rep") { + //qDebug() << "获取报表忙碌"; + interruptibleSleep(3000); + if (!this->isInterruptionRequested() && !m_wakeUpRequested) { + goto REQUERY_WAGERS_LIST; + } + } + else if (jsonObject["code"].toString() == "4X014") { + //qDebug() << "[网络返回失败] get_report_list_bet"; + //qDebug() << jsonObject; + emit account_disconnect(); + } + + qDebug() << "[get_report_list_bet]其他错误:" << result; + //emit account_disconnect(); + return QList>(); + } + + //qDebug() << result; + + QJsonObject dataObj = jsonObject["data"].toObject(); + QJsonObject arrayObj = dataObj["array"].toObject(); + QJsonArray row0Array = arrayObj["row0"].toArray(); + + if (row0Array.isEmpty()) { + return QList>(); + } + + // 皇冠“今天”的日期(本地时间 - 12 小时) + const QDate crownToday = QDateTime::currentDateTime().addSecs(-12 * 3600).date(); + + auto classifySession = [&](const QString& wagersType, const QString& gtimeStr) -> QString { + if (wagersType.contains("滚球")) + return "滚球"; + QDateTime gdt = QDateTime::fromString(gtimeStr, "MM-dd-yyyy HH:mm:ss"); + if (!gdt.isValid()) return QString(); + const QDate d = gdt.date(); + if (d == crownToday) return"今日"; + if (d > crownToday) return"早盘"; + return QString(); // 早于今天可按需返回“历史” + }; + + auto classifyStage = [&](const QString& wagersType) -> QString { + if (wagersType.contains("上半场") || wagersType.contains("半场")) + { + return "上半场"; + } + if (wagersType.contains("第一节") ) + { + return "第一节"; + } + if (wagersType.contains("第二节")) + { + return "第二节"; + } + if (wagersType.contains("第三节")) + { + return "第三节"; + } + if (wagersType.contains("第四节")) + { + return "第四节"; + } + + return "全场"; + }; + + QList> list; + for (int i = 0; i < row0Array.count(); i++) { + if (this->isInterruptionRequested() || m_wakeUpRequested) break; + + QJsonObject orderJson = row0Array.at(i).toObject(); + QMap map; + + for (const QString& key : orderJson.keys()) { + map.insert(key, orderJson.value(key).toVariant().toString()); + } + + // 规范比分 + QString score = map.value("SCORE"); + if (score.isEmpty()) { + map["SCORE"] = ""; + } + else if (score.contains(':')) { + map["SCORE"] = score; + } + else if (score.startsWith('(') && score.endsWith(')') && score.contains('-')) { + score = score.mid(1, score.length() - 2).remove(' ').replace('-', ':'); + map["SCORE"] = score; + } + else { + map["SCORE"] = ""; + } + + // SESSION 与 STAGE + const QString wagersType = map.value("WAGERS_TYPE"); + const QString gtimeStr = map.value("G_TIME"); // 源格式: MM-dd-yyyy HH:mm:ss + const QString session = classifySession(wagersType, gtimeStr); + const QString stage = classifyStage(wagersType); + + map["SESSION"] = session; + map["STAGE"] = stage; + + // 直接改成皇冠时间 + map["READ_DATETIME"] = QDateTime::currentDateTime().addSecs(-43200).toString("yyyy-MM-dd HH:mm:ss"); + + map["GOLD"] = map["GOLD"].remove(","); + //push_order(map); + list.append(map); + } + + return list; +} + +void ReportThread::setParam(QString url, QString ver, QString uid, QString login_layer, QString layer_id, QString langx, QString current_username, QString cookies, QString current_agent_type, QList> accounts) +{ + QMutexLocker lock(&m_mutex); + m_url = Utils::normalizeUrl(url); + m_ver = ver; + m_uid = uid; + m_login_layer = login_layer; + m_layer_id = layer_id; + m_langx = langx; + m_current_username = current_username; + m_cookies = cookies; + m_current_agent_type = current_agent_type; + m_accounts = accounts; +} + + + +void ReportThread::clearParam() +{ + // 写数据不加锁 + // QMutexLocker lock(&m_mutex); + m_url = ""; + m_ver = ""; + m_uid = ""; + m_login_layer = ""; + m_layer_id = ""; + m_langx = ""; + m_current_username = ""; + m_cookies = ""; +} diff --git a/CrownServer/ReportThread.h b/CrownServer/ReportThread.h new file mode 100644 index 0000000..64af1d2 --- /dev/null +++ b/CrownServer/ReportThread.h @@ -0,0 +1,72 @@ +#ifndef REPORTTHREAD_H +#define REPORTTHREAD_H + +#include +#include +#include +#include +#include +#include +#include + +class ReportThread : public QThread +{ + Q_OBJECT +public: + ReportThread(); + ~ReportThread(); + + void run() override; + void pause(); + void resume(); + void stopImmediately(); + // 获取报表代理(登1) + QList> get_report_co(QString session, QString gtype); + // 获取报表代理(登2) + QList> get_report_su(QString ACTION0, QString session, QString gtype); + // 获取报表代理(登3) + QList> get_report_ag(QString ACTION0, QString session, QString gtype); + // 获取报表成员 + QList> get_report_mem(QString ACTION0, QString date_start, QString date_end); + // 获取报表 + QList> get_report_list_bet(QString ACTION0, QString date_start, QString date_end); + + + void setParam(QString url, QString ver, QString uid, QString login_layer, QString layer_id, QString langx, QString current_username, QString cookies, QString agent_type, QList> accounts); + void clearParam(); + +signals: + void update_orders(QList> orderArray); + void read(); + void account_disconnect(); +private: + // 用户列表 + QList> m_accounts; +private: + // 可中断的休眠函数 + void interruptibleSleep(int milliseconds); + // 可中断的网络请求 + QByteArray interruptibleNetworkRequest(QNetworkAccessManager& manager, QNetworkRequest& request, const QByteArray& data, int timeoutMs = 10000); + + QMutex m_mutex; + QWaitCondition m_waitCondition; + bool m_wakeUpRequested = false; + bool m_isPaused = false; + + QString m_url; + QString m_ver; + QString m_uid; + QString m_login_layer; + QString m_layer_id; + QString m_langx; + QString m_current_username; + QString m_cookies; + QString m_current_agent_type; + +private: + bool screen_user(QString NAME0); + + +}; + +#endif // REPORTTHREAD_H \ No newline at end of file diff --git a/CrownServer/Resources/check.svg b/CrownServer/Resources/check.svg new file mode 100644 index 0000000..1c20989 --- /dev/null +++ b/CrownServer/Resources/check.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/CrownServer/Resources/checkmark.png b/CrownServer/Resources/checkmark.png new file mode 100644 index 0000000..1545ba7 Binary files /dev/null and b/CrownServer/Resources/checkmark.png differ diff --git a/CrownServer/Resources/chevron-down.svg b/CrownServer/Resources/chevron-down.svg new file mode 100644 index 0000000..278c6a3 --- /dev/null +++ b/CrownServer/Resources/chevron-down.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/CrownServer/Resources/crownTime.png b/CrownServer/Resources/crownTime.png new file mode 100644 index 0000000..395f263 Binary files /dev/null and b/CrownServer/Resources/crownTime.png differ diff --git a/CrownServer/Resources/icons/checkmark.png b/CrownServer/Resources/icons/checkmark.png new file mode 100644 index 0000000..1545ba7 Binary files /dev/null and b/CrownServer/Resources/icons/checkmark.png differ diff --git a/CrownServer/Resources/icons/close.png b/CrownServer/Resources/icons/close.png new file mode 100644 index 0000000..ba32052 Binary files /dev/null and b/CrownServer/Resources/icons/close.png differ diff --git a/CrownServer/Resources/icons/down_arrow.png b/CrownServer/Resources/icons/down_arrow.png new file mode 100644 index 0000000..b51a01f Binary files /dev/null and b/CrownServer/Resources/icons/down_arrow.png differ diff --git a/CrownServer/Resources/icons/down_arrow_light.svg b/CrownServer/Resources/icons/down_arrow_light.svg new file mode 100644 index 0000000..95dc821 --- /dev/null +++ b/CrownServer/Resources/icons/down_arrow_light.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/CrownServer/Resources/icons/restore.png b/CrownServer/Resources/icons/restore.png new file mode 100644 index 0000000..e1cfbf7 Binary files /dev/null and b/CrownServer/Resources/icons/restore.png differ diff --git a/CrownServer/Resources/localTime.png b/CrownServer/Resources/localTime.png new file mode 100644 index 0000000..47b0051 Binary files /dev/null and b/CrownServer/Resources/localTime.png differ diff --git a/CrownServer/Resources/mail.png b/CrownServer/Resources/mail.png new file mode 100644 index 0000000..bd41033 Binary files /dev/null and b/CrownServer/Resources/mail.png differ diff --git a/CrownServer/Resources/server.ico b/CrownServer/Resources/server.ico new file mode 100644 index 0000000..2f6ae8c Binary files /dev/null and b/CrownServer/Resources/server.ico differ diff --git a/CrownServer/Resources/start.png b/CrownServer/Resources/start.png new file mode 100644 index 0000000..ddd52c3 Binary files /dev/null and b/CrownServer/Resources/start.png differ diff --git a/CrownServer/Resources/stop.png b/CrownServer/Resources/stop.png new file mode 100644 index 0000000..97bbd5a Binary files /dev/null and b/CrownServer/Resources/stop.png differ diff --git a/CrownServer/Resources/user - 副本.png b/CrownServer/Resources/user - 副本.png new file mode 100644 index 0000000..ef6bf97 Binary files /dev/null and b/CrownServer/Resources/user - 副本.png differ diff --git a/CrownServer/Resources/user.png b/CrownServer/Resources/user.png new file mode 100644 index 0000000..52c6ad6 Binary files /dev/null and b/CrownServer/Resources/user.png differ diff --git a/CrownServer/Resources/visual_studio_dark.qss b/CrownServer/Resources/visual_studio_dark.qss new file mode 100644 index 0000000..a7e022d --- /dev/null +++ b/CrownServer/Resources/visual_studio_dark.qss @@ -0,0 +1,616 @@ +/* VS暗黑/Atom风格 QSS样式表 - 优化中文显示版 */ +QMainWindow, QDialog, QWidget { + background-color: #1e1e1e; + color: #d4d4d4; + font-family: "Microsoft YaHei UI", "Segoe UI", "PingFang SC", sans-serif; + font-size: 13px; + border: none; +} + +/* 菜单栏 */ +QMenuBar { + background-color: #2d2d30; + color: #cccccc; + border-bottom: 1px solid #3e3e42; + font-size: 13px; +} + +QMenuBar::item { + background: transparent; + padding: 5px 10px; +} + +QMenuBar::item:selected { + background: #3e3e42; +} + +QMenuBar::item:pressed { + background: #007acc; +} + +/* 菜单 */ +QMenu { + background-color: #2d2d30; + color: #cccccc; + border: 1px solid #3e3e42; + font-size: 13px; +} + +QMenu::item { + padding: 6px 25px 6px 20px; +} + +QMenu::item:selected { + background-color: #3e3e42; + color: #ffffff; +} + +QMenu::item:disabled { + color: #656565; +} + +QMenu::separator { + height: 1px; + background-color: #3e3e42; + margin: 5px 0px; +} + +/* 工具栏 */ +QToolBar { + background-color: #2d2d30; + border: none; + spacing: 5px; + padding: 3px; +} + +QToolBar::handle { + background-color: #3e3e42; + width: 10px; +} + +/* 状态栏 */ +QStatusBar { + background-color: #007acc; + color: #ffffff; + font-size: 12px; +} + +QStatusBar::item { + border: none; +} + +/* 按钮 */ +QPushButton { + background-color: #0e639c; + color: #ffffff; + border: none; + border-radius: 3px; + padding: 6px 16px; + min-width: 60px; + font-size: 13px; +} + +QPushButton:hover { + background-color: #1177bb; +} + +QPushButton:pressed { + background-color: #0c5a8c; +} + +QPushButton:disabled { + background-color: #3e3e42; + color: #7a7a7a; +} + +QPushButton:focus { + outline: 0; +} +QPushButton:pressed { + outline: 0; +} + +/* === 专为图标按钮:stateButton / userManagerButton 的统一样式(支持QPushButton与QToolButton) === */ +QPushButton#stateButton, +QToolButton#stateButton, +QPushButton#userManagerButton { + background: transparent; + border: none; + padding: 0px; + margin: 0px; + min-width: 0px; + border-radius: 6px; +} + +/* 悬浮与按下为蓝色系半透明,保持与全局蓝色主色一致 */ +QPushButton#stateButton:hover, +QToolButton#stateButton:hover, +QPushButton#userManagerButton:hover { + background-color: rgba(0, 122, 204, 0.18); +} +QPushButton#stateButton:pressed, +QToolButton#stateButton:pressed, +QPushButton#userManagerButton:pressed { + background-color: rgba(0, 122, 204, 0.30); +} + +/* 明确图标尺寸(与UI设置一致,可按需调整) */ +QPushButton#stateButton, +QToolButton#stateButton { + qproperty-iconSize: 64px 64px; +} +QPushButton#userManagerButton { + qproperty-iconSize: 40px 40px; +} + +/* 工具栏按钮 */ +QToolButton { + background-color: transparent; + border: 1px solid transparent; + border-radius: 3px; + padding: 3px; +} + +QToolButton:hover { + background-color: #3e3e42; + border: 1px solid #3e3e42; +} + +QToolButton:pressed { + background-color: #007acc; +} + +QToolButton:checked { + background-color: #007acc; +} + +/* 复选框 */ +QCheckBox { + color: #d4d4d4; + spacing: 8px; + font-size: 13px; +} + +QCheckBox::indicator { + width: 16px; + height: 16px; +} + +QCheckBox::indicator:unchecked { + border: 1px solid #3e3e42; + background-color: #252526; +} + +QCheckBox::indicator:checked { + border: 1px solid #007acc; + background-color: #007acc; + image: url(:/Resources/icons/checkmark.png); +} + +QCheckBox::indicator:disabled { + border: 1px solid #3e3e42; + background-color: #2d2d30; +} + +/* 单选框 */ +QRadioButton { + color: #d4d4d4; + spacing: 8px; + font-size: 13px; +} + +QRadioButton::indicator { + width: 16px; + height: 16px; + border-radius: 8px; +} + +QRadioButton::indicator:unchecked { + border: 1px solid #3e3e42; + background-color: #252526; +} + +QRadioButton::indicator:checked { + border: 1px solid #007acc; + background-color: #007acc; +} + +QRadioButton::indicator:disabled { + border: 1px solid #3e3e42; + background-color: #2d2d30; +} + +/* 组合框 */ +QComboBox { + background-color: #252526; + color: #d4d4d4; + border: 1px solid #3e3e42; + border-radius: 3px; + padding: 5px 10px; + min-width: 75px; + font-size: 13px; +} + +QComboBox:hover { + border: 1px solid #007acc; +} + +QComboBox:editable { + background: #1e1e1e; +} + +QComboBox::drop-down { + subcontrol-origin: padding; + subcontrol-position: top right; + width: 22px; + border-left: 1px solid #3e3e42; +} + +QComboBox::down-arrow { + image: url(:/Resources/icons/down_arrow_light.svg); + width: 14px; + height: 14px; + right: 4px; + subcontrol-origin: padding; + subcontrol-position: center right; +} + +QComboBox QAbstractItemView { + background-color: #252526; + color: #d4d4d4; + selection-background-color: #007acc; + selection-color: #ffffff; + border: 1px solid #3e3e42; + outline: 0; + font-size: 13px; +} + +/* 自定义ComboBoxItem样式 - 修复删除按钮问题 */ +ComboBoxItem { + background-color: transparent; + border: none; + outline: 0; + min-height: 25px; + max-height: 25px; +} + +ComboBoxItem QLabel { + color: #d4d4d4; + background-color: transparent; + border: none; + font-size: 13px; + padding-left: 5px; +} + +ComboBoxItem QPushButton { + background: transparent; + border: none; + outline: 0; + min-width: 20px; + max-width: 20px; + min-height: 20px; + max-height: 20px; + border-radius: 10px; + margin: 0px 2px; + padding: 0px; +} + +ComboBoxItem QPushButton:hover { + background-color: rgba(200, 200, 200, 50); + border-radius: 10px; +} + +ComboBoxItem QPushButton:pressed { + background-color: rgba(0, 122, 204, 100); + border-radius: 10px; +} + +ComboBoxItem QPushButton:focus { + outline: 0; +} + +/* 确保QListWidget中的ComboBoxItem正确显示 */ +QListWidget::item { + background-color: transparent; + border: none; + outline: 0; + padding: 0px; + margin: 0px; +} + +QListWidget::item:hover { + background-color: #2a2d2e; +} + +QListWidget::item:selected { + background-color: #094771; +} + +/* 滚动条 */ +QScrollBar { + background: transparent; + outline: 0; + border: none; +} +QScrollBar:focus { + outline: 0; +} +QScrollBar::add-page, QScrollBar::sub-page { + background: transparent; +} +QScrollBar:vertical { + background: transparent; + width: 12px; + margin: 0px; +} + +QScrollBar::handle:vertical { + background: #424245; + min-height: 20px; + border-radius: 6px; + margin: 2px; +} + +QScrollBar::handle:vertical:hover { + background: #4c4c4f; +} + +QScrollBar::handle:vertical:pressed { + background: #007acc; +} + +QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { + height: 0px; +} + +QScrollBar:horizontal { + background: transparent; + height: 12px; + margin: 0px; +} + +QScrollBar::handle:horizontal { + background: #424245; + min-width: 20px; + border-radius: 6px; + margin: 2px; +} + +QScrollBar::handle:horizontal:hover { + background: #4c4c4f; +} + +QScrollBar::handle:horizontal:pressed { + background: #007acc; +} + +QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal { + width: 0px; +} + +/* 滑块 */ +QSlider::groove:horizontal { + background: #3e3e42; + height: 4px; + border-radius: 2px; +} + +QSlider::handle:horizontal { + background: #007acc; + border: none; + height: 12px; + width: 12px; + border-radius: 6px; + margin: -4px 0; +} + +QSlider::handle:horizontal:hover { + background: #1c97ea; +} + +QSlider::groove:vertical { + background: #3e3e42; + width: 4px; + border-radius: 2px; +} + +QSlider::handle:vertical { + background: #007acc; + border: none; + width: 12px; + height: 12px; + border-radius: 6px; + margin: 0 -4px; +} + +QSlider::handle:vertical:hover { + background: #1c97ea; +} + +/* 进度条 */ +QProgressBar { + background-color: #3e3e42; + color: #d4d4d4; + border: none; + border-radius: 3px; + text-align: center; + font-size: 13px; +} + +QProgressBar::chunk { + background-color: #007acc; + border-radius: 3px; +} + +/* 分页控件 */ +QTabWidget::pane { + background-color: #1e1e1e; + border: 1px solid #3e3e42; +} + +QTabBar::tab { + background-color: #2d2d30; + color: #cccccc; + padding: 8px 15px; + border: none; + border-bottom: 2px solid transparent; + font-size: 13px; +} + +QTabBar::tab:selected { + background-color: #1e1e1e; + color: #ffffff; + border-bottom: 2px solid #007acc; +} + +QTabBar::tab:hover:!selected { + background-color: #3e3e42; +} + +QTabBar::close-button { + image: url(:/Resources/icons/close.png); + subcontrol-position: right; +} + +QTabBar::close-button:hover { + background-color: #e81123; +} + +/* 分组框 */ +QGroupBox { + font-weight: bold; + border: 1px solid #3e3e42; + border-radius: 3px; + margin-top: 1ex; + padding-top: 10px; + font-size: 13px; +} + +QGroupBox::title { + subcontrol-origin: margin; + subcontrol-position: top center; + padding: 0 5px; +} + +/* 文本框 */ +QLineEdit, QTextEdit, QPlainTextEdit { + background-color: #252526; + color: #d4d4d4; + border: 1px solid #3e3e42; + border-radius: 3px; + padding: 5px; + selection-background-color: #007acc; + selection-color: #ffffff; + font-size: 13px; +} + +QLineEdit:focus, QTextEdit:focus, QPlainTextEdit:focus { + border: 1px solid #007acc; +} + +/* 列表视图 */ +QListView, QTreeView, QTableView { + background-color: #252526; + color: #d4d4d4; + border: 1px solid #3e3e42; + border-radius: 3px; + outline: 0; + selection-background-color: #007acc; + selection-color: #ffffff; + alternate-background-color: #2d2d30; + font-size: 13px; +} + +QHeaderView::section { + background-color: #2d2d30; + color: #cccccc; + padding: 5px; + border: none; + border-right: 1px solid #3e3e42; + font-size: 13px; +} + +QHeaderView::section:last { + border-right: none; +} + +QHeaderView::section:checked { + background-color: #007acc; + color: #ffffff; +} + +/* 分割线 */ +QSplitter::handle { + background-color: #2d2d30; +} + +QSplitter::handle:hover { + background-color: #007acc; +} + +QSplitter::handle:horizontal { + width: 5px; +} + +QSplitter::handle:vertical { + height: 5px; +} + +/* 停靠窗口 */ +QDockWidget { + background-color: #2d2d30; + color: #cccccc; + border: 1px solid #3e3e42; + titlebar-close-icon: url(:/Resources/icons/close.png); + titlebar-normal-icon: url(:/Resources/icons/restore.png); + font-size: 13px; +} + +QDockWidget::title { + background-color: #2d2d30; + padding: 5px; + text-align: center; +} + +QDockWidget::close-button, QDockWidget::float-button { + background-color: transparent; + border: none; + padding: 0px; + icon-size: 12px; +} + +QDockWidget::close-button:hover, QDockWidget::float-button:hover { + background-color: #3e3e42; +} + +/* 工具提示 */ +QToolTip { + background-color: #007acc; + color: #ffffff; + border: 1px solid #007acc; + border-radius: 3px; + padding: 5px; + font-size: 13px; + font-family: "Microsoft YaHei UI", "Segoe UI", "PingFang SC", sans-serif; +} + +/* 表格表头(更高优先级,覆盖默认白色的行号列头与角按钮) */ +QTableView QHeaderView::section { + background-color: #2d2d30; + color: #cccccc; + border: none; + border-right: 1px solid #3e3e42; + border-bottom: 1px solid #3e3e42; +} +QTableView QHeaderView::section:horizontal { + background-color: #2d2d30; + color: #cccccc; +} +QTableView QHeaderView::section:vertical { + background-color: #2d2d30; + color: #cccccc; +} +QTableView QTableCornerButton::section { + background-color: #2d2d30; + border: 1px solid #3e3e42; +} \ No newline at end of file diff --git a/CrownServer/Resources/x.svg b/CrownServer/Resources/x.svg new file mode 100644 index 0000000..7d5875c --- /dev/null +++ b/CrownServer/Resources/x.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/CrownServer/Screen.cpp b/CrownServer/Screen.cpp new file mode 100644 index 0000000..d3cbb4c --- /dev/null +++ b/CrownServer/Screen.cpp @@ -0,0 +1,386 @@ +#include "Screen.h" +#include +#include +Screen::Screen(QWidget* parent) + : QWidget(parent) +{ + ui.setupUi(this); + + // 窗口标题 + this->setWindowTitle("筛选会员帐号注单"); + // 窗口图标 + this->setWindowIcon(QIcon(":/CrownServer/Resources/server.ico")); + // 无边框窗口 + setWindowFlags(Qt::Dialog); + // 仅有关闭按钮 + setWindowFlags(Qt::WindowCloseButtonHint); + // 固定窗口大小 + this->setFixedSize(470, 500); + //this->setFixedSize(700, 447); + + + + + ui.treeWidget->setColumnCount(2); + ui.treeWidget->setHeaderLabels({ "账号","等级"}); + ui.treeWidget->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); + ui.treeWidget->header()->resizeSection(0, 280); + ui.treeWidget->header()->resizeSection(1, 50); + //ui.treeWidget->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); + + + + //ui.tableWidget->setColumnCount(3); + //ui.tableWidget->setHorizontalHeaderLabels({ "账号","等级","操作" }); + //ui.tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + //ui.tableWidget->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); + //ui.tableWidget->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents); + + //ui.acceptCheckBox->setDisabled(true); + ui.acceptCheckBox->setCheckState(Qt::CheckState::Checked); + ui.acceptCheckBox->setAttribute(Qt::WA_TransparentForMouseEvents, true); + //ui.unAcceptCheckBox->setDisabled(true); + ui.unAcceptCheckBox->setCheckState(Qt::CheckState::Unchecked); + ui.unAcceptCheckBox->setAttribute(Qt::WA_TransparentForMouseEvents, true); + //ui.followSuperCheckBox->setDisabled(true); + + + connect(ui.treeWidget, &QTreeWidget::itemChanged, this, &Screen::slotItemCheckChanged); + // connect(m_manager, &Manager::signalUpdateUserList, this, &Screen::slotUpdateUserList); + + //connect(ui.readConfigButton, &QPushButton::clicked, this, [&]() + //{ + + // QList screenList = g_config->screenUserList(); + // QList acceptList = g_config->acceptUserList(); + // QTreeWidgetItemIterator iter(ui.treeWidget); + // while (*iter) + // { + // QTreeWidgetItem* item = *iter; + // for (int i = 0; i < screenList.count(); i++) + // { + // QString user = screenList[i]; + + // if (user == (*iter)->text(0)) + // { + // item->setCheckState(0, Qt::PartiallyChecked); + // } + // } + + // for (int i = 0; i < acceptList.count(); i++) + // { + // QString user = acceptList[i]; + + // if (user == (*iter)->text(0)) + // { + // item->setCheckState(0, Qt::Checked); + // } + // } + + // iter++; + // } + + //}); + + + //connect(ui.saveConfigButton, &QPushButton::clicked, this, [&]() { + + + // QList screenList; + // QList acceptList; + // //for (int i = 0; i < ui.tableWidget->rowCount(); i++) + // //{ + // // QString user; + + // // user = ui.tableWidget->item(i, 0)->text(); + // // //user["level"] = ui.tableWidget->item(i, 1)->text(); + // // //user["option"] = ui.tableWidget->item(i, 2)->text(); + // // if (ui.tableWidget->item(i, 2)->text() == "接收") + // // { + // // acceptList.append(user); + // // } + // // else if (ui.tableWidget->item(i, 2)->text() == "屏蔽") + // // { + // // screenList.append(user); + // // } + + // //} + // g_config->setAcceptUserList(acceptList); + // g_config->setScreenUserList(screenList); + //}); + +} + +Screen::~Screen() +{ + +} + + + +void Screen::slotItemCheckChanged(QTreeWidgetItem* item, int column) +{ + ui.treeWidget->blockSignals(true); + + Qt::CheckState state = item->checkState(0); + QColor color = (state == Qt::Unchecked) ? QColor(255, 0, 0) : QColor(0, 255, 0); + + // 设置当前项的颜色 + item->setForeground(0, QBrush(color)); + item->setForeground(1, QBrush(color)); + + // 逻辑1:如果子节点被选中,所有父节点必须选中 + if (state == Qt::Checked) { + QTreeWidgetItem* parent = item->parent(); + while (parent != nullptr) { + parent->setCheckState(0, Qt::Checked); + parent->setForeground(0, QBrush(QColor(0, 255, 0))); + parent->setForeground(1, QBrush(QColor(0, 255, 0))); + parent = parent->parent(); + } + } + + // 逻辑2:如果父节点取消选中,所有子节点取消选中 + if (state == Qt::Unchecked && item->childCount() > 0) { + QList childrenToProcess; + for (int i = 0; i < item->childCount(); ++i) { + childrenToProcess.append(item->child(i)); + } + + while (!childrenToProcess.isEmpty()) { + QTreeWidgetItem* child = childrenToProcess.takeFirst(); + child->setCheckState(0, Qt::Unchecked); + child->setForeground(0, QBrush(QColor(255, 0, 0))); + child->setForeground(1, QBrush(QColor(255, 0, 0))); + + for (int i = 0; i < child->childCount(); ++i) { + childrenToProcess.append(child->child(i)); + } + } + } + + ui.treeWidget->blockSignals(false); +} + +void Screen::slotUpdateUserList(QList> list) +{ + // 启用按钮 + ui.button_extract->setEnabled(true); + //qDebug() << "更新用户列表:" << list; + // 新增用户加入列表 + for (int i = 0; i < list.count(); i++) + { + bool found = false; + QMap user = list[i]; + for (int j = 0; j < m_screenList.count(); j++) + { + QMap screenUser = m_screenList[j]; + if (user["username"] == screenUser["username"]) + { + found = true; + break; + } + } + if (!found) + { + // 加入列表 + m_screenList.append(user); + } + } + + // 删除用户去除列表 + for (int i = 0; i < m_screenList.count(); ++i) + { + bool found = false; + QMap screenUser = m_screenList[i]; + for (int j = 0; j < list.count(); j++) + { + QMap user = list[j]; + if (user["username"] == screenUser["username"]) + { + found = true; + break; + } + } + if (!found) + { + //QList tableItem = ui.tableWidget->findItems(screenUser["username"], Qt::MatchExactly); + //if (tableItem.count() == 1) + //{ + // ui.tableWidget->removeRow(tableItem[0]->row()); + //} + m_screenList.removeAt(i); + i--; + } + } + + for (auto iter = m_screenList.begin(); iter != m_screenList.end(); iter++) + { + + QMap user = *iter; + + // 已经加入列表的不再处理 + + QTreeWidgetItemIterator treeIter(ui.treeWidget); + + bool treeFound = false; + while (*treeIter) + { + if ((*treeIter)->text(0) == user["username"]) + { + treeFound = true; + break; + } + treeIter++; + } + if (treeFound) + { + continue; + } + + + if (user["up_username"].isEmpty()) + { + QTreeWidgetItem* item = new QTreeWidgetItem(ui.treeWidget); + // item2->setFlags(item2->flags() & ~Qt::ItemIsUserCheckable); + // item->setFlags(Qt::ItemIsUserTristate | item->flags()); + // 禁止点击 + item->setFlags(item->flags() & ~Qt::ItemIsUserCheckable); + item->setCheckState(0, Qt::CheckState::Checked); + // 设置默认颜色(选中状态为绿色) + item->setForeground(0, QBrush(QColor(0, 255, 0))); + item->setForeground(1, QBrush(QColor(0, 255, 0))); + item->setText(0, user["username"]); + if (user["level"] == "co") + { + item->setText(1, "管理"); + } + else if (user["level"] == "su") + { + item->setText(1, "总代理"); + } + else if (user["level"] == "ag") + { + item->setText(1, "代理商"); + } + else if (user["level"] == "user") + { + item->setText(1, "会员"); + } + continue; + } + + QTreeWidgetItemIterator itemIter(ui.treeWidget); + while (*itemIter) + { + QTreeWidgetItem* parentItem = *itemIter; + if (parentItem->text(0) == user["up_username"]) + { + auto item = new QTreeWidgetItem(parentItem); + // 不启用三态 + // item->setFlags(Qt::ItemIsUserTristate | item->flags()); + item->setCheckState(0, Qt::CheckState::Checked); + // 设置默认颜色(选中状态为绿色) + item->setForeground(0, QBrush(QColor(0, 255, 0))); + item->setForeground(1, QBrush(QColor(0, 255, 0))); + item->setText(0, user["username"]); + if (user["level"] == "co") + { + item->setText(1, "管理"); + } + else if (user["level"] == "su") + { + item->setText(1, "总代理"); + } + else if (user["level"] == "ag") + { + item->setText(1, "代理商"); + } + else if (user["level"] == "user") + { + item->setText(1, "会员"); + } + } + itemIter++; + } + } + + + // 匹配策略 + + auto policy_list = g_config->screen_list(); + + QTreeWidgetItemIterator iter(ui.treeWidget); + while (*iter) + { + QTreeWidgetItem* item = *iter; + for (auto policy : policy_list) + { + if (policy["username"] == (*iter)->text(0)) + { + if (policy["policy"] == "false") + { + item->setCheckState(0, Qt::Unchecked); + + // 设置屏蔽状态颜色(红色) + item->setForeground(0, QBrush(QColor(255, 0, 0))); + item->setForeground(1, QBrush(QColor(255, 0, 0))); + + } + else if(policy["policy"] == "true") + { + item->setCheckState(0, Qt::Checked); + + // 设置接收状态颜色(绿色) + item->setForeground(0, QBrush(QColor(0, 255, 0))); + item->setForeground(1, QBrush(QColor(0, 255, 0))); + + } + } + } + iter++; + } + + + +} + + + +void Screen::on_button_extract_clicked() +{ + // 禁用按钮 + ui.button_extract->setEnabled(false); + + + emit signal_extract_user_list(); + +} + + + +void Screen::closeEvent(QCloseEvent* event) +{ + auto policy_list = g_config->screen_list(); + + QList> list; + QTreeWidgetItemIterator iter(ui.treeWidget); + while (*iter) + { + QTreeWidgetItem* item = *iter; + QMap map; + map["username"] = item->text(0); + if (item->checkState(0) == Qt::Unchecked) + { + map["policy"] = "false"; + } + else if (item->checkState(0) == Qt::Checked) + { + map["policy"] = "true"; + } + list.append(map); + iter++; + } + g_config->set_screen_list(list); + +} diff --git a/CrownServer/Screen.h b/CrownServer/Screen.h new file mode 100644 index 0000000..a3561d1 --- /dev/null +++ b/CrownServer/Screen.h @@ -0,0 +1,43 @@ +#pragma once + +#include +#include +#include +#include "Global.h" +#include "ui_Screen.h" +#include +#include "UserThread.h" +#include +class Screen : public QWidget +{ + Q_OBJECT + +public: + Screen(QWidget* parent = nullptr); + ~Screen(); +public: + QList> m_screenList; +signals: + + // 提取会员信号 + void signal_extract_user_list(); +public slots: + + // 提取会员按钮 + void on_button_extract_clicked(); + void slotItemCheckChanged(QTreeWidgetItem* item, int column); + void slotUpdateUserList(QList> list); + +//public slots: +// void on_get_user_list(QList); + +// void on_screen_checkbox_stateChanged(int state); +// void on_match_radio_clicked(); +// void on_filter_radio_clicked(); +// void on_clear_button_clicked(); +private: + // 重写窗口关闭事件 + void closeEvent(QCloseEvent* event); +private: + Ui::ScreenClass ui; +}; diff --git a/CrownServer/Screen.ui b/CrownServer/Screen.ui new file mode 100644 index 0000000..6a97915 --- /dev/null +++ b/CrownServer/Screen.ui @@ -0,0 +1,90 @@ + + + ScreenClass + + + + 0 + 0 + 413 + 314 + + + + Screen + + + + + + + 1 + + + + + + + + + + false + + + QCheckBox { +color: rgb(0, 255, 0); +padding: 0px 0px 0px 0px; +} + + + 接收 + + + false + + + 300 + + + true + + + + + + + QCheckBox { +color: rgb(255, 0, 0); +padding: 0px 0px 0px 0px; +} + + + 屏蔽 + + + false + + + true + + + + + + + + + + + 提取会员 + + + + + + + + + + + diff --git a/CrownServer/Setting.cpp b/CrownServer/Setting.cpp new file mode 100644 index 0000000..e2e9bbf --- /dev/null +++ b/CrownServer/Setting.cpp @@ -0,0 +1,191 @@ +#include "Setting.h" +#include + +Setting::Setting(QWidget *parent) + : QWidget(parent) +{ + ui.setupUi(this); + + + // this->setWindowFlags(Qt::Window); + this->setWindowTitle("设置"); + // 设置窗口图标 + this->setWindowIcon(QIcon(":/CrownServer/Resources/server.ico")); + setWindowFlags(Qt::Dialog); + setWindowFlags(Qt::WindowCloseButtonHint); + // 设置模态显示属性 + this->setAttribute(Qt::WA_ShowModal, true); + this->setFixedSize(600,500); + + + // 限制输入范围 + ui.readUserListIntervalMinEdit->setValidator(new QIntValidator(0, 60000, this)); + ui.readUserListIntervalMaxEdit->setValidator(new QIntValidator(0, 60000, this)); + ui.readOrderListIntervalMinEdit->setValidator(new QIntValidator(0, 60000, this)); + ui.readOrderListIntervalMaxEdit->setValidator(new QIntValidator(0, 60000, this)); + + + + connect(ui.updateOrderSoundBrowse, &QPushButton::clicked, this, [&]() { + QString fileName = QFileDialog::getOpenFileName(this, "浏览", QDir::currentPath(),"mp3(*mp3);;wav(*.wav)"); + g_config->setUpdateOrderSoundPath(fileName); + ui.updateOrderSoundEdit->setText(fileName); + }); + + connect(ui.pushFailedBrower, &QPushButton::clicked, this, [&]() { + QString fileName = QFileDialog::getOpenFileName(this, "浏览", QDir::currentPath(), "mp3(*mp3);;wav(*.wav)"); + g_config->setPushFailedSoundPath(fileName); + ui.pushFailedEdit->setText(fileName); + }); + + connect(ui.exitBrower, &QPushButton::clicked, this, [&]() { + QString fileName = QFileDialog::getOpenFileName(this, "浏览", QDir::currentPath(), "mp3(*mp3);;wav(*.wav)"); + g_config->setExitSoundPath(fileName); + ui.exitEdit->setText(fileName); + }); + + connect(ui.reloginBrower, &QPushButton::clicked, this, [&]() { + QString fileName = QFileDialog::getOpenFileName(this, "浏览", QDir::currentPath(), "mp3(*mp3);;wav(*.wav)"); + g_config->setReloginSoundPath(fileName); + ui.reloginEdit->setText(fileName); + }); + + connect(ui.softUpdateBrower, &QPushButton::clicked, this, [&]() { + QString fileName = QFileDialog::getOpenFileName(this,"浏览", QDir::currentPath(),"mp3(*mp3);;wav(*.wav)"); + g_config->setSoftUpdateSoundPath(fileName); + ui.softUpdateEdit->setText(fileName); + }); + + connect(ui.updateOrderSoundPlay, &QPushButton::clicked, this, [&]() { + if (ui.updateOrderSoundEdit->text().isEmpty()) + { + QSound::play(":/sound/sound/readOrder.wav"); + } + else + { + QSound::play(ui.updateOrderSoundEdit->text()); + } + + }); + + connect(ui.pushFailedPlay, &QPushButton::clicked, this, [&]() { + if (ui.pushFailedEdit->text().isEmpty()) + { + QSound::play(":/sound/sound/pushFailed.wav"); + } + else + { + QSound::play(ui.pushFailedEdit->text()); + } + + }); + + connect(ui.exitPlay, &QPushButton::clicked, this, [&]() { + if (ui.exitEdit->text().isEmpty()) + { + QSound::play(":/sound/sound/exit.wav"); + } + else + { + QSound::play(ui.exitEdit->text()); + } + + }); + + connect(ui.reloginPlay, &QPushButton::clicked, this, [&]() { + if (ui.reloginEdit->text().isEmpty()) + { + QSound::play(":/sound/sound/relogin.wav"); + } + else + { + QSound::play(ui.reloginEdit->text()); + } + + }); + + connect(ui.softUpdatePlay, &QPushButton::clicked, this, [&]() { + if (ui.softUpdateEdit->text().isEmpty()) + { + QSound::play(":/sound/sound/update.wav"); + } + else + { + QSound::play(ui.softUpdateEdit->text()); + } + + }); + + + + // 读取配置 + ui.readReportListIntervalMinEdit->setText(QString::number(g_config->readReportListInterValMin())); + ui.readReportListIntervalMaxEdit->setText(QString::number(g_config->readReportListInterValMax())); + ui.readUserListIntervalMinEdit->setText(QString::number(g_config->readUserListInterValMin())); + ui.readUserListIntervalMaxEdit->setText(QString::number(g_config->readUserListInterValMax())); + ui.readOrderListIntervalMinEdit->setText(QString::number(g_config->readOrderListInterValMin())); + ui.readOrderListIntervalMaxEdit->setText(QString::number(g_config->readOrderListInterValMax())); + + ui.disconnectSleepMinEdit->setText(QString::number(g_config->disconnectedSleepMin())); + ui.disconnectSleepMaxEdit->setText(QString::number(g_config->disconnectedSleepMax())); + ui.failedSleepMinEdit->setText(QString::number(g_config->failedSleepMin())); + ui.failedSleepMaxEdit->setText(QString::number(g_config->failedSleepMax())); + + ui.failedReconnectTimesEdit->setText(QString::number(g_config->failedReconnectTimes())); + + ui.updateOrderSoundCheckBox->setChecked(g_config->updateOrderSoundEnable()); + ui.pushFailedCheckBox->setChecked(g_config->pushFailedSoundEnable()); + ui.exitCheckBox->setChecked(g_config->exitSoundEnable()); + ui.reloginCheckBox->setChecked(g_config->reloginSoundEnable()); + ui.softUpdateCheckBox->setChecked(g_config->softUpdateSoundEnable()); + + ui.updateOrderSoundEdit->setText(g_config->updateOrderSoundPath()); + ui.pushFailedEdit->setText(g_config->pushFailedSoundPath()); + ui.exitEdit->setText(g_config->exitSoundPath()); + ui.reloginEdit->setText(g_config->reloginSoundPath()); + ui.softUpdateEdit->setText(g_config->softUpdateSoundPath()); +} + +Setting::~Setting() +{ + + +} + + +void Setting::closeEvent(QCloseEvent* event) +{ + qDebug() << "服务端 - > 设置窗口 -> 保存配置"; + + g_config->setReadReportListIntervalMin(ui.readReportListIntervalMinEdit->text().toInt()); + g_config->setReadReportListIntervalMax(ui.readReportListIntervalMaxEdit->text().toInt()); + + g_config->setReadUserListIntervalMin(ui.readUserListIntervalMinEdit->text().toInt()); + g_config->setReadUserListIntervalMax(ui.readUserListIntervalMaxEdit->text().toInt()); + + g_config->setReadOrderListIntervalMin(ui.readOrderListIntervalMinEdit->text().toInt()); + g_config->setReadOrderListIntervalMax(ui.readOrderListIntervalMaxEdit->text().toInt()); + + + g_config->setDisconnectedSleepMin(ui.disconnectSleepMinEdit->text().toInt()); + g_config->setDisconnectedSleepMax(ui.disconnectSleepMaxEdit->text().toInt()); + g_config->setFailedSleepMin(ui.failedSleepMinEdit->text().toInt()); + g_config->setFailedSleepMax(ui.failedSleepMaxEdit->text().toInt()); + + g_config->setFailedReconnectTimes(ui.failedReconnectTimesEdit->text().toInt()); + + + + + g_config->setUpdateOrderSoundEnable(ui.updateOrderSoundCheckBox->isChecked()); + g_config->setPushFailedSoundEnable(ui.pushFailedCheckBox->isChecked()); + g_config->setExitSoundEnable(ui.exitCheckBox->isChecked()); + g_config->setReloginSoundEnable(ui.reloginCheckBox->isChecked()); + g_config->setSoftUpdateSoundEnable(ui.softUpdateCheckBox->isChecked()); + + g_config->setUpdateOrderSoundPath(ui.updateOrderSoundEdit->text()); + g_config->setPushFailedSoundPath(ui.pushFailedEdit->text()); + g_config->setExitSoundPath(ui.exitEdit->text()); + g_config->setReloginSoundPath(ui.reloginEdit->text()); + g_config->setSoftUpdateSoundPath(ui.softUpdateEdit->text()); +} \ No newline at end of file diff --git a/CrownServer/Setting.h b/CrownServer/Setting.h new file mode 100644 index 0000000..0f9d9f6 --- /dev/null +++ b/CrownServer/Setting.h @@ -0,0 +1,23 @@ +#pragma once + +#include +#include "ui_Setting.h" + +#include +#include +#include +#include "Global.h" +class Setting : public QWidget +{ + Q_OBJECT + +public: + Setting(QWidget *parent = nullptr); + ~Setting(); +private: + void closeEvent(QCloseEvent* event); + +private: + Ui::SettingClass ui; +}; + \ No newline at end of file diff --git a/CrownServer/Setting.ui b/CrownServer/Setting.ui new file mode 100644 index 0000000..61edd34 --- /dev/null +++ b/CrownServer/Setting.ui @@ -0,0 +1,493 @@ + + + SettingClass + + + + 0 + 0 + 454 + 506 + + + + Setting + + + + + + 读取频率 + + + + + + + + 读取报表频率: + + + + + + + 最小 + + + + + + + + + + 秒 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 最大 + + + + + + + + + + 秒 + + + + + + + + + + + 读取列表频率: + + + + + + + 最小 + + + + + + + + + + 秒 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 最大 + + + + + + + + + + 秒 + + + + + + + + + + + 读取注单频率: + + + + + + + 最小 + + + + + + + + + + 秒 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 最大 + + + + + + + + + + 秒 + + + + + + + + + <html><head/><body><p><span style=" color:#00aa00;">如果[最小值]与[最大值]不一致,则频率为两者之间的随机值.</span></p></body></html> + + + + + + + + + + 延时 + + + + + + + + 掉线重连延时: 最小 + + + + + + + + + + 秒 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 最大 + + + + + + + + + + 秒 + + + + + + + + + + + 失败重连延时: 最小 + + + + + + + + + + 秒 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 最大 + + + + + + + + + + 秒 + + + + + + + + + + + 失败重连次数: 最大 + + + + + + + + + + 次 + + + + + + + + + + + + 声音 + + + + + + + + 读取注单: + + + + + + + + + + 浏览 + + + + + + + 播放 + + + + + + + + + + + 推送失败: + + + + + + + + + + 浏览 + + + + + + + 播放 + + + + + + + + + + + 强制退出: + + + + + + + + + + 浏览 + + + + + + + 播放 + + + + + + + + + + + 重新登录: + + + + + + + + + + 浏览 + + + + + + + 播放 + + + + + + + + + + + 软件升级: + + + + + + + + + + 浏览 + + + + + + + 播放 + + + + + + + + + + + + + + diff --git a/CrownServer/StandardModel.cpp b/CrownServer/StandardModel.cpp new file mode 100644 index 0000000..e69de29 diff --git a/CrownServer/StandardModel.h b/CrownServer/StandardModel.h new file mode 100644 index 0000000..a9c35fe --- /dev/null +++ b/CrownServer/StandardModel.h @@ -0,0 +1,10 @@ +#pragma once +#include + +class StandardModel :public QAbstractItemModel +{ + Q_OBJECT +public: + StandardModel(); + ~StandardModel(); +}; \ No newline at end of file diff --git a/CrownServer/StyleLoader.h b/CrownServer/StyleLoader.h new file mode 100644 index 0000000..1e91352 --- /dev/null +++ b/CrownServer/StyleLoader.h @@ -0,0 +1,21 @@ +// StyleLoader.h +#pragma once +#include +#include +#include + +class StyleLoader { +public: + // 修改StyleLoader.cpp中的loadStyle方法 + static QString StyleLoader::loadStyleFromResource() { + QFile file(":/CrownServer/Resources/visual_studio_dark.qss"); + if (!file.open(QIODevice::ReadOnly)) { + return QString(); + } + + QTextStream stream(&file); + QString style = stream.readAll(); + file.close(); + return style; + } +}; \ No newline at end of file diff --git a/CrownServer/StyledItemDelegate.cpp b/CrownServer/StyledItemDelegate.cpp new file mode 100644 index 0000000..d6f2e9d --- /dev/null +++ b/CrownServer/StyledItemDelegate.cpp @@ -0,0 +1,129 @@ +#include "StyledItemDelegate.h" + +StyledItemDelegate::StyledItemDelegate(QAbstractItemView* parent) + : m_view(parent) + , m_isCheckable(false) +{ + +} + +StyledItemDelegate::~StyledItemDelegate() +{ + +} + +void StyledItemDelegate::setCheckable() +{ + m_isCheckable = true; +} + +bool StyledItemDelegate::isCheckable() const +{ + return m_isCheckable; +} + +// 截取源码,部分修改 +void StyledItemDelegate::initStyleOption(QStyleOptionViewItem* option, const QModelIndex& index) const +{ + QVariant value = index.data(Qt::FontRole); + if (value.isValid() && !value.isNull()) { + option->font = qvariant_cast(value).resolve(option->font); + option->fontMetrics = QFontMetrics(option->font); + } + + value = index.data(Qt::TextAlignmentRole); + if (value.isValid() && !value.isNull()) + option->displayAlignment = Qt::Alignment(value.toInt()); + + value = index.data(Qt::ForegroundRole); + if (value.canConvert()) + option->palette.setBrush(QPalette::Text, qvariant_cast(value)); + + option->index = index; + if (isCheckable()) { + option->features |= QStyleOptionViewItem::HasCheckIndicator; + // 选中状态替换为复选框 + if (m_view->selectionModel()->isSelected(index)) { + option->checkState = Qt::Checked; + } + else { + // 非选中状态需要判断是否不完全选中 + option->checkState = isPartially(index) ? Qt::PartiallyChecked : Qt::Unchecked; + } + } + else { + // 原复选框 + value = index.data(Qt::CheckStateRole); + if (value.isValid() && !value.isNull()) { + option->features |= QStyleOptionViewItem::HasCheckIndicator; + option->checkState = static_cast(value.toInt()); + } + } + + value = index.data(Qt::DecorationRole); + if (value.isValid() && !value.isNull()) { + option->features |= QStyleOptionViewItem::HasDecoration; + switch (value.type()) { + case QVariant::Icon: { + option->icon = qvariant_cast(value); + QIcon::Mode mode; + if (!(option->state & QStyle::State_Enabled)) + mode = QIcon::Disabled; + else if (option->state & QStyle::State_Selected) + mode = QIcon::Selected; + else + mode = QIcon::Normal; + QIcon::State state = option->state & QStyle::State_Open ? QIcon::On : QIcon::Off; + QSize actualSize = option->icon.actualSize(option->decorationSize, mode, state); + // For highdpi icons actualSize might be larger than decorationSize, which we don't want. Clamp it to decorationSize. + option->decorationSize = QSize(qMin(option->decorationSize.width(), actualSize.width()), + qMin(option->decorationSize.height(), actualSize.height())); + break; + } + case QVariant::Color: { + QPixmap pixmap(option->decorationSize); + pixmap.fill(qvariant_cast(value)); + option->icon = QIcon(pixmap); + break; + } + case QVariant::Image: { + QImage image = qvariant_cast(value); + option->icon = QIcon(QPixmap::fromImage(image)); + option->decorationSize = image.size() / image.devicePixelRatio(); + break; + } + case QVariant::Pixmap: { + QPixmap pixmap = qvariant_cast(value); + option->icon = QIcon(pixmap); + option->decorationSize = pixmap.size() / pixmap.devicePixelRatio(); + break; + } + default: + break; + } + } + + value = index.data(Qt::DisplayRole); + if (value.isValid() && !value.isNull()) { + option->features |= QStyleOptionViewItem::HasDisplay; + option->text = displayText(value, option->locale); + } + + option->backgroundBrush = qvariant_cast(index.data(Qt::BackgroundRole)); + + // disable style animations for checkboxes etc. within itemviews (QTBUG-30146) + option->styleObject = 0; +} + +bool StyledItemDelegate::isPartially(const QModelIndex& index) const +{ + if (m_view->model()->rowCount(index)) { + QModelIndexList indexList = m_view->model()->match(index.sibling(0, 0), Qt::DisplayRole, "*", -1, Qt::MatchWildcard | Qt::MatchRecursive); + foreach(QModelIndex childIndex, indexList) { + if (m_view->selectionModel()->isSelected(childIndex)) { + return true; + } + } + } + return false; +} diff --git a/CrownServer/StyledItemDelegate.h b/CrownServer/StyledItemDelegate.h new file mode 100644 index 0000000..93be2c6 --- /dev/null +++ b/CrownServer/StyledItemDelegate.h @@ -0,0 +1,25 @@ +#pragma once +#include +#include +class StyledItemDelegate : public QStyledItemDelegate +{ + Q_OBJECT + +public: + StyledItemDelegate(QAbstractItemView* parent); + virtual ~StyledItemDelegate(); + + void setCheckable();// 选中状态增加复选框 + bool isCheckable() const; + +protected: + virtual void initStyleOption(QStyleOptionViewItem* option, const QModelIndex& index) const; + +private: + bool isPartially(const QModelIndex& index) const; + +private: + QAbstractItemView* m_view; + bool m_isCheckable; +}; + diff --git a/CrownServer/TcpServer.cpp b/CrownServer/TcpServer.cpp new file mode 100644 index 0000000..da38392 --- /dev/null +++ b/CrownServer/TcpServer.cpp @@ -0,0 +1,93 @@ +// cpp +#include "TCPServer.h" +#include + +TcpServer::TcpServer(QObject* parent, int port) : QTcpServer(parent) +{ + +} + +TcpServer::~TcpServer() +{ + // qDebug() << "TcpServer 析构开始"; + + // 停止所有客户端线程 + QList::iterator iter; + for (iter = m_clients.begin(); iter != m_clients.end(); iter++) + { + TcpThread* thread = *iter; + if (thread) { + //qDebug() << "停止客户端线程:" << thread; + thread->quit(); + thread->wait(); // 等待线程结束 + thread->deleteLater(); + } + } + m_clients.clear(); + + // qDebug() << "TcpServer 析构完成"; +} + +void TcpServer::slotSendData(qintptr socketDescriptor, QByteArray data) +{ + emit signalSendData(socketDescriptor, data);// 转发发送数据信号 +} + +void TcpServer::slotDisconnected(qintptr socketDescriptor) +{ + //qDebug() << "TcpServer 客户端断开连接:" << socketDescriptor; + + QList::iterator iter; + for (iter = m_clients.begin(); iter != m_clients.end(); ) + { + TcpThread* thread = *iter; + if (thread == sender()) + { + //qDebug() << "停止并释放断开连接的线程:" << thread; + thread->quit(); + thread->wait(); // 等待线程结束 + thread->disconnect(); // 断开所有信号 + iter = m_clients.erase(iter); + thread->deleteLater(); + // 不要再用 thread 指针 + } else { + ++iter; + } + } +} + + + +void TcpServer::slotDataRecv(qintptr socketDescriptor, QByteArray data) +{ + //qDebug() << "[Server]收到数据:" << data; + // 发送更新服务端界面信号 + emit signalDataRecv(socketDescriptor, data); +} + + + +/// +/// 连接到达 +/// +/// Socket描述符 +void TcpServer::incomingConnection(qintptr socketDescriptor) +{ + // 创建新的Socket + TcpThread* thread = new TcpThread(socketDescriptor); + m_clients.append(thread); + //qDebug() << "客户端(" << socketDescriptor << "):连接"; + + // 接收数据 + connect(thread, &TcpThread::signalDataRecv, this, &TcpServer::slotDataRecv, Qt::QueuedConnection); + // 发送数据 + connect(this, &TcpServer::signalSendData, thread, &TcpThread::slotSendData, Qt::QueuedConnection); + // 断开连接 + connect(thread, &TcpThread::signalDisconnected, this, &TcpServer::slotDisconnected); + connect(thread, &TcpThread::signalDisconnected, thread, &TcpThread::deleteLater); + // 退出后释放资源 + connect(thread, &TcpThread::finished, thread, &TcpThread::deleteLater); + thread->start(); + +} + diff --git a/CrownServer/TcpServer.h b/CrownServer/TcpServer.h new file mode 100644 index 0000000..d904d5e --- /dev/null +++ b/CrownServer/TcpServer.h @@ -0,0 +1,29 @@ +#pragma once + +#include +#include +#include "TcpThread.h" + +class TcpServer : public QTcpServer +{ + Q_OBJECT +public: + TcpServer(QObject* parent = nullptr, int port = 3366); + ~TcpServer(); +private: + QList m_clients; +signals: + void signalSendData(qintptr socketDescriptor, QByteArray data); + void signalDataRecv(qintptr socketDescriptor, QByteArray data); + void signal_disconnected(qintptr socketDescriptor); // Added new signal +public slots: + void slotDataRecv(qintptr socketDescriptor, QByteArray data); + void slotSendData(qintptr socketDescriptor, QByteArray data); + void slotDisconnected(qintptr socketDescriptor); +protected: + // 用来连接客户端,这个函数需要注意,在QT 5后面的版本参数部分类型要改为 **qintptr** 否则会出现连接上了,但是没有执行函数的情况 + virtual void incomingConnection(qintptr socketDescriptor); + +}; + + diff --git a/CrownServer/TcpSocket.cpp b/CrownServer/TcpSocket.cpp new file mode 100644 index 0000000..ba067b8 --- /dev/null +++ b/CrownServer/TcpSocket.cpp @@ -0,0 +1,197 @@ +#include "TcpSocket.h" + +TcpSocket::TcpSocket(QObject* parent) : QTcpSocket(parent) +{ + m_heartbeatTimer = new QTimer(); + // 接收数据 + connect(this, &TcpSocket::readyRead, this, &TcpSocket::slotDataRecv, Qt::QueuedConnection); + // 发送数据 + connect(this, &TcpSocket::signalSendData, this, &TcpSocket::slotSendData, Qt::QueuedConnection); + + connect(m_heartbeatTimer, &QTimer::timeout, this, &TcpSocket::slotHeartBeat); + connect(this, &TcpSocket::disconnected, this, [&]() { + //qDebug() << "停止心跳-------------------"; + m_heartbeatTimer->stop(); + }); + + m_heartbeatDateTime = QDateTime::currentDateTime(); + m_heartbeatTimer->start(3000); +} + +TcpSocket::~TcpSocket() +{ + //qDebug() << "Socket 析构"; + m_heartbeatTimer->stop(); + m_heartbeatTimer->deleteLater(); +} + +/// +/// 封包发送 +/// +/// 数据 +/// 数据长度 +void TcpSocket::slotSendData(QByteArray data) +{ + if (data.isEmpty()) + { + //qDebug() << "Socket:send data is empty"; + return; + } + if (this->state() != QTcpSocket::ConnectedState) + { + //qDebug() << "Socket:state error:" << this->state(); + return; + } + QByteArray dataType = NET_PACKET_TYPE_SEND_TEXT; + // [包类型 + 数据 + 包尾] + QByteArray packet = dataType + data + NET_PACKET_END; + // 长度占8字节,前面补零,如"00065536" + int size = packet.size(); + QByteArray length = QByteArray().setNum(size); + length = QByteArray(NET_PACKET_LENGTH_BYTES, '0') + length; + length = length.right(NET_PACKET_LENGTH_BYTES); + // 插入 [包头 + 数据长度] + packet.insert(0, NET_PACKET_START + length); + this->write(packet); + this->flush(); +} + +/// +/// 解包 +/// +/// 数据 +/// 数据长度 +bool TcpSocket::parsePacket(SocketPacket *packet) +{ + int pIndexStart = packet->data.indexOf(NET_PACKET_START); + if (pIndexStart < 0) + { + return false; + } + + packet->data = packet->data.mid(pIndexStart); //截取从包头index_start到末尾的数据 + SocketPacket tmpPacket; + tmpPacket.data = packet->data; + + tmpPacket.data.remove(0, QByteArray(NET_PACKET_START).size());//删除包头 + + //解析包长度 + if (tmpPacket.data.count() < NET_PACKET_LENGTH_BYTES) + { + return false; + } + bool isOk; + tmpPacket.length = tmpPacket.data.mid(0, NET_PACKET_LENGTH_BYTES).toLong(&isOk); + if (isOk == false) + { + packet->data.remove(0, QByteArray(NET_PACKET_START).size());//删除包头 + if (packet->data.indexOf(NET_PACKET_START) >= 0) + { + return true;//有可能出现粘包的情况,继续解析后面数据 + } + else + { + return false; + } + } + + //数据到达包长度 + tmpPacket.data.remove(0, NET_PACKET_LENGTH_BYTES);//删除数据长度 + if (tmpPacket.length > tmpPacket.data.count()) + { + return false; + } + + //包尾是否匹配 + tmpPacket.data.resize(tmpPacket.length);//删除多余数据 + if (tmpPacket.data.endsWith(NET_PACKET_END) == false) + { + packet->data.remove(0, QByteArray(NET_PACKET_START).size());//删除包头 + if (packet->data.indexOf(NET_PACKET_START) >= 0) + { + return true;//有可能出现粘包的情况,继续解析后面数据 + } + else + { + return false; + } + } + + tmpPacket.data.resize(tmpPacket.length - + QByteArray(NET_PACKET_END).count()); //删除包尾 + + //解析出数据类型 + if (tmpPacket.data.count() < NET_PACKET_TYPE_BYTES) + { + return false; + } + QByteArray dataType = tmpPacket.data.left(NET_PACKET_TYPE_BYTES); + tmpPacket.dataType = dataType; + + tmpPacket.data.remove(0, NET_PACKET_TYPE_BYTES);//删除数据类型 + + //删除当前包数据 + packet->data.remove(0, + QByteArray(NET_PACKET_START).size() + + NET_PACKET_LENGTH_BYTES + + tmpPacket.length); + + //发送数据包消息 + if (tmpPacket.data == QString("@HEARTBEAT@").toUtf8()) + { + //qDebug() << "更新心跳"; + m_heartbeatDateTime = QDateTime::currentDateTime(); + if (!m_heartbeatTimer->isActive() && this->state() == QTcpSocket::ConnectedState) + { + m_heartbeatTimer->start(3000); + } + } + else + { + emit signalDataRecv(this->socketDescriptor(), tmpPacket.data); + } + + //dealDataPacket(tmpPacket); + + return true; +} + + + +void TcpSocket::slotDataRecv() +{ + m_dataPacket.data += this->readAll(); + + // 循环解析包数据,m_dataPacket.data 中可能不只一包数据 + bool isOk = false; + do { + isOk = parsePacket(&m_dataPacket); + } while (isOk); +} + + +void TcpSocket::slotHeartBeat() +{ + // 15秒超时 + if (this->m_heartbeatDateTime.msecsTo(QDateTime::currentDateTime()) > 15000) + { + //qDebug() << "心跳超时掉线:" << this->state(); + if (this->state() == QTcpSocket::ConnectedState) + { + + emit this->error(QAbstractSocket::SocketTimeoutError); + + } + m_heartbeatTimer->stop(); + } + else + { + //qDebug() << "发送心跳"; + QByteArray data = QString("@HEARTBEAT@").toUtf8(); + // 发送心跳 + emit signalSendData(data); + } + //m_mutex.unlock(); +} + + diff --git a/CrownServer/TcpSocket.h b/CrownServer/TcpSocket.h new file mode 100644 index 0000000..cbb8805 --- /dev/null +++ b/CrownServer/TcpSocket.h @@ -0,0 +1,32 @@ +#pragma once +#include +#include +#include +#include +#include "Constant.h" + + +class TcpSocket : public QTcpSocket +{ + Q_OBJECT +public: + TcpSocket(QObject* parent = Q_NULLPTR); + ~TcpSocket(); +public: + SocketPacket m_dataPacket; + // 心跳定时器 + QTimer* m_heartbeatTimer; + // 心跳时间 + QDateTime m_heartbeatDateTime; +private: + bool parsePacket(SocketPacket *packet); +signals: + void signalDataRecv(qintptr socketDescriptor, QByteArray data); + void signalDisConnected(qintptr socketDescriptor); + void signalSendData(QByteArray data); + +public slots: + void slotDataRecv(); + void slotSendData(QByteArray data); + void slotHeartBeat(); +}; diff --git a/CrownServer/TcpThread.cpp b/CrownServer/TcpThread.cpp new file mode 100644 index 0000000..a015a59 --- /dev/null +++ b/CrownServer/TcpThread.cpp @@ -0,0 +1,120 @@ +#include "TcpThread.h" + +TcpThread::TcpThread(qintptr socketDecriptor, QObject* parent) : QThread(parent) +{ + m_ip = NULL; + m_port = 0; + m_socketDescriptor = socketDecriptor; + m_socket = nullptr; +} +TcpThread::TcpThread(QHostAddress ip, quint16 port, QObject* parent) : QThread(parent) +{ + + m_ip = ip; + m_port = port; + m_socketDescriptor = 0; + m_socket = nullptr; +} +TcpThread::~TcpThread() +{ + //qDebug() << "[线程] -> 析构开始"; + + if (m_socket) { + //qDebug() << "[线程] -> 释放socket"; + m_socket->disconnect(); // 断开所有信号 + m_socket->abort(); // 强制断开连接 + m_socket->deleteLater(); // 延迟删除 + m_socket = nullptr; + } + + //qDebug() << "[线程] -> 析构完成"; +} + +void TcpThread::run() +{ + if (!m_socket) + { + m_socket = new TcpSocket(); + } + if (m_socketDescriptor) + { + //qDebug() << "客户端设置:" << m_socketDescriptor; + if (!m_socket->setSocketDescriptor(m_socketDescriptor)) + { + qDebug() << "设置失败"; + return; + } + } + + // 数据到达 + connect(m_socket, &TcpSocket::signalDataRecv, this, &TcpThread::slotDataRecv, Qt::QueuedConnection); + + // 连接建立 + connect(m_socket, &TcpSocket::connected, this, &TcpThread::slotConnected, Qt::QueuedConnection); + // 连接断开 + connect(m_socket, &TcpSocket::disconnected, this, &TcpThread::slotDisconnected, Qt::QueuedConnection); + + // 数据发送 + connect(this, &TcpThread::signalSendData, m_socket, &TcpSocket::slotSendData, Qt::QueuedConnection); + + + if (!m_ip.isNull() && m_port) + { + //qDebug() << "连接"; + m_socket->connectToHost(m_ip, m_port); + m_socket->waitForConnected(1000); + } + + this->exec(); + + // 线程退出时安全释放socket + if (m_socket) { + // qDebug() << "[线程] -> 退出时释放socket"; + m_socket->abort(); + m_socket->disconnect(); + m_socket->deleteLater(); + m_socket = nullptr; + } + + //qDebug() << "线程退出"; +} + +void TcpThread::slotSendData(qintptr socketDescriptor, QByteArray data) +{ + //qDebug() << "[线程] -> 发送数据"; + if (socketDescriptor != this->m_socketDescriptor) + { + return; + } + if (data.isEmpty()) + { + //qDebug() << "数据发送:数据为空"; + return; + } + emit this->signalSendData(data); +} + +void TcpThread::slotDataRecv(qintptr socketDescriptor, QByteArray data) +{ + //qDebug() << "[线程] -> 接收数据"; + if (data.isEmpty()) + { + //qDebug() << "数据接收:数据为空"; + return; + } + emit this->signalDataRecv(socketDescriptor, data); +} + +void TcpThread::slotConnected() +{ + //qDebug() << "[线程] -> 连接:" << m_socket->socketDescriptor(); + m_socketDescriptor = m_socket->socketDescriptor(); + emit signalConnected(m_socketDescriptor); +} + +void TcpThread::slotDisconnected() +{ + //qDebug() << "[线程] -> 断开:" << m_socketDescriptor; + emit signalDisconnected(m_socketDescriptor); +} + diff --git a/CrownServer/TcpThread.h b/CrownServer/TcpThread.h new file mode 100644 index 0000000..70b2286 --- /dev/null +++ b/CrownServer/TcpThread.h @@ -0,0 +1,37 @@ +#pragma once +#include "TcpSocket.h" +#include +#include +#include +#include +#include +//每一个新的客户端连接,都会由QTcpServer通过重写的incomingConnection()自动分配一个新的线程。 +//线程只接受了一个QTcpServer提供的socketDescriptor。 +//QTcpSocket类的setSocketDescriptor()函数接收这个socketDescriptor,并利用它完成与客户端的连接。 +class TcpThread : public QThread +{ + Q_OBJECT +public: + TcpThread(qintptr socketDecriptor, QObject* parent = Q_NULLPTR); + TcpThread(QHostAddress ip, quint16 port, QObject* parent = Q_NULLPTR); + ~TcpThread(); +public: + // 重写QThread虚函数 run() + void run(); +private: + QHostAddress m_ip; + quint16 m_port; +private: + TcpSocket * m_socket; + qintptr m_socketDescriptor; +signals: + void signalSendData(QByteArray data); + void signalDataRecv(qintptr socketDescriptor, QByteArray data); + void signalConnected(qintptr socketDecriptor); + void signalDisconnected(qintptr socketDescriptor); +public slots: + void slotSendData(qintptr socketDescriptor, QByteArray data); + void slotDataRecv(qintptr socketDecriptor, QByteArray data); + void slotConnected(); + void slotDisconnected(); +}; diff --git a/CrownServer/TreeView.cpp b/CrownServer/TreeView.cpp new file mode 100644 index 0000000..6a35d8d --- /dev/null +++ b/CrownServer/TreeView.cpp @@ -0,0 +1,21 @@ +#include "TreeView.h" + + +TreeView::TreeView(QWidget *parent) + : QTreeView(parent) +{ + +} + +void TreeView::mousePressEvent(QMouseEvent *event) +{ + QPoint p = event->pos(); + QModelIndex index = indexAt(p); + if (!index.isValid()) + { + setCurrentIndex(QModelIndex()); //实现点空白处取消选择 + emit sigPressEmpty(); + return; + } + QTreeView::mousePressEvent(event); +} diff --git a/CrownServer/TreeView.h b/CrownServer/TreeView.h new file mode 100644 index 0000000..2def3ad --- /dev/null +++ b/CrownServer/TreeView.h @@ -0,0 +1,25 @@ +#ifndef TREE_VIEW_H +#define TREE_VIEW_H + +#include +#include + + +//改造QTreeView,实现点击空白处时取消选择 + +class TreeView : public QTreeView +{ + Q_OBJECT +public: + TreeView(QWidget *parent = Q_NULLPTR); + +signals: + void sigPressEmpty(); + +protected: + void mousePressEvent(QMouseEvent * event); + + +}; + +#endif diff --git a/CrownServer/UrlThread.cpp b/CrownServer/UrlThread.cpp new file mode 100644 index 0000000..60912c3 --- /dev/null +++ b/CrownServer/UrlThread.cpp @@ -0,0 +1,203 @@ +#include "UrlThread.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "Utils.h" + +UrlThread::UrlThread() + : m_wakeUpRequested(false) + , m_isPaused(false) +{ + // 注册自定义类型 + qRegisterMetaType>("QList"); +} + +UrlThread::~UrlThread() +{ + stopImmediately(); + if (this->isRunning()) { + this->wait(1000); + } +} + +void UrlThread::stopImmediately() +{ + { + QMutexLocker lock(&m_mutex); + m_wakeUpRequested = true; + m_isPaused = false; + } + + m_waitCondition.wakeAll(); + this->requestInterruption(); +} + +void UrlThread::interruptibleSleep(int milliseconds) +{ + if (milliseconds <= 0 || this->isInterruptionRequested()) return; + + QMutexLocker lock(&m_mutex); + if (m_wakeUpRequested) return; + + m_waitCondition.wait(&m_mutex, milliseconds); +} + +QByteArray UrlThread::interruptibleNetworkRequest(QNetworkAccessManager& manager, QNetworkRequest& request, const QByteArray& data, int timeoutMs) +{ + if (this->isInterruptionRequested() || m_wakeUpRequested) { + return QByteArray(); + } + + QNetworkReply* reply = manager.post(request, data); + reply->ignoreSslErrors(); + + QEventLoop eventLoop; + QTimer timeoutTimer; + timeoutTimer.setSingleShot(true); + + connect(&manager, &QNetworkAccessManager::finished, &eventLoop, &QEventLoop::quit); + connect(&timeoutTimer, &QTimer::timeout, &eventLoop, &QEventLoop::quit); + connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit); + + // 中断检查定时器 + QTimer interruptTimer; + interruptTimer.setInterval(100); + connect(&interruptTimer, &QTimer::timeout, [&]() { + if (this->isInterruptionRequested() || m_wakeUpRequested) { + reply->abort(); + eventLoop.quit(); + } + }); + + timeoutTimer.start(timeoutMs); + interruptTimer.start(); + eventLoop.exec(); + + interruptTimer.stop(); + timeoutTimer.stop(); + + QByteArray result; + if (!this->isInterruptionRequested() && !m_wakeUpRequested && reply->error() == QNetworkReply::NoError) { + result = reply->readAll(); + } + + reply->deleteLater(); + return result; +} + +void UrlThread::run() +{ + while (!this->isInterruptionRequested() && !m_wakeUpRequested) { + { + QMutexLocker lock(&m_mutex); + if (m_wakeUpRequested) break; + + // 检查暂停状态 + while (m_isPaused && !m_wakeUpRequested && !this->isInterruptionRequested()) { + m_waitCondition.wait(&m_mutex, 100); + } + if (m_wakeUpRequested) break; + } + + // 执行URL获取任务 + getUrls(); + + // 每隔一段时间执行一次(例如5分钟) + interruptibleSleep(5 * 60 * 1000); + } + + //qDebug() << "UrlThread 安全退出"; +} + +void UrlThread::getUrls() +{ + if (this->isInterruptionRequested() || m_wakeUpRequested) { + return; + } + + // 网络请求 + QNetworkAccessManager networkManager; + QNetworkRequest request; + request.setUrl(QUrl(QString(m_url + "transform.php?ver=" + m_ver))); + request.setRawHeader("Accept", "*/*"); + request.setRawHeader("Cookie", m_cookies.toUtf8()); + request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); + request.setRawHeader("Origin", m_url.toUtf8()); + request.setRawHeader("Referer", m_url.toUtf8()); + request.setRawHeader("Host", QUrl(m_url).host().toUtf8()); + + QString data = "p=get_new_url&ver=" + m_ver + "&uid=" + m_uid + "&login_layer=" + m_login_layer + "&layer_id=" + m_layer_id + "&chk_mem=N"; + + QByteArray result = interruptibleNetworkRequest(networkManager, request, data.toUtf8(), 10000); + if (result.isEmpty() || this->isInterruptionRequested() || m_wakeUpRequested) { + return; + } + + // json数据处理 + QJsonDocument document = QJsonDocument::fromJson(result); + if (document.isNull()) { + return; + } + + QJsonObject jsonObject = document.object(); + QJsonArray agentArray = jsonObject["urlData"].toObject()["newagcro666"].toArray(); + QJsonArray userArray = jsonObject["urlData"].toObject()["newcro666"].toArray(); + + //qDebug() << "更新URL返回:" << result; + if (agentArray.isEmpty() || userArray.isEmpty()) { + return; + } + + QList userList; + for (int i = 0; i < userArray.count(); i++) { + QString url = userArray.at(i).toVariant().toString(); + userList.append(url); + } + // 直接更新客户端配置 + emit signalUpdateUserUrlList(userList); + + QList agentList; + for (int i = 0; i < agentArray.count(); i++) { + QString url = agentArray.at(i).toVariant().toString(); + agentList.append(url); + } + + // 发出更新代理网址列表信号 + emit signalUpdateAgentUrlList(agentList); +} + +void UrlThread::pause() +{ + QMutexLocker lock(&m_mutex); + m_isPaused = true; +} + +void UrlThread::resume() +{ + QMutexLocker lock(&m_mutex); + m_isPaused = false; + m_waitCondition.wakeAll(); +} + +void UrlThread::setParam(QString url, QString ver, QString uid, QString login_layer, QString layer_id, QString langx, QString current_username, QString cookies) +{ + QMutexLocker lock(&m_mutex); + m_url = Utils::normalizeUrl(url); + m_ver = ver; + m_uid = uid; + m_login_layer = login_layer; + m_layer_id = layer_id; + m_langx = langx; + m_current_username = current_username; + m_cookies = cookies; +} + + + diff --git a/CrownServer/UrlThread.h b/CrownServer/UrlThread.h new file mode 100644 index 0000000..f85a8a8 --- /dev/null +++ b/CrownServer/UrlThread.h @@ -0,0 +1,60 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define Layer_One "co" +#define Layer_Two "su" +#define Layer_Three "ag" +#define Layer_User "mem" + +class UrlThread : public QThread +{ + Q_OBJECT +public: + UrlThread(); + ~UrlThread(); + + void setParam(QString url, QString ver, QString uid, QString login_layer, QString layer_id, QString langx, QString current_username, QString cookies); + void pause(); + void resume(); + void stopImmediately(); + +signals: + void signalUpdateUserUrlList(QList list); + void signalUpdateAgentUrlList(QList list); + +protected: + void run() override; + +private: + QByteArray interruptibleNetworkRequest(QNetworkAccessManager& manager, QNetworkRequest& request, const QByteArray& data, int timeoutMs); + void interruptibleSleep(int milliseconds); + void getUrls(); + +private: + QMutex m_mutex; + QWaitCondition m_waitCondition; + bool m_wakeUpRequested; + bool m_isPaused; + + QString m_url; + QString m_ver; + QString m_uid; + QString m_login_layer; + QString m_layer_id; + QString m_langx; + QString m_current_username; + QString m_cookies; +}; \ No newline at end of file diff --git a/CrownServer/User.cpp b/CrownServer/User.cpp new file mode 100644 index 0000000..135c945 --- /dev/null +++ b/CrownServer/User.cpp @@ -0,0 +1,133 @@ +#include "User.h" +#include +#include +#include "Global.h" +User::User(QWidget *parent) + : QWidget(parent) +{ + ui.setupUi(this); + + this->setWindowTitle("账户管理"); + // 设置窗口图标 + this->setWindowIcon(QIcon(":/CrownServer/Resources/server.ico")); + setWindowFlags(Qt::Dialog); + setWindowFlags(Qt::WindowCloseButtonHint); + this->setFixedSize(400, 500); + + // 读取配置 + m_users = g_config->usersList(); + for (int i = 0; i < m_users.count(); i++) + { + QMap user = m_users[i]; + // 添加视图 + int index = ui.tableWidget->rowCount(); + ui.tableWidget->insertRow(index); + ui.tableWidget->setItem(index, 0, new QTableWidgetItem(user["username"])); + ui.tableWidget->setItem(index, 1, new QTableWidgetItem(user["password"])); + ui.tableWidget->setItem(index, 2, new QTableWidgetItem(user["level"])); + ui.tableWidget->setItem(index, 3, new QTableWidgetItem(user["safeCode"])); + } + + // 设置禁止编辑 + ui.tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); + // 设置选择行为为整行选中 + ui.tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); + // 设置表头拉伸方式 + ui.tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + // 设置自定义上下文菜单方案 + ui.tableWidget->setContextMenuPolicy(Qt::CustomContextMenu); + + // 创建自定义菜单 + m_menu = new QMenu(ui.tableWidget); + m_actionDelete = new QAction("删除", this); + m_menu->addAction(m_actionDelete); + // 连接自定义菜单请求与槽 + connect(ui.tableWidget, &QTableWidget::customContextMenuRequested, this, [=](QPoint point) { + m_menu->exec(QCursor::pos()); + }); + // 连接动作触发请求与槽 + connect(m_actionDelete, &QAction::triggered, this,&User::slotDelete); + // 设置双击事件 + connect(ui.tableWidget, &QTableWidget::itemDoubleClicked, this, [=]() { + int row = ui.tableWidget->currentRow(); + QString username = ui.tableWidget->item(row, 0)->text(); + QString password = ui.tableWidget->item(row, 1)->text(); + QString level = ui.tableWidget->item(row, 2)->text(); + QString safeCode = ui.tableWidget->item(row, 3)->text(); + emit signalSetUser(username, password, level, safeCode); + }); + +} + +User::~User() +{ + + +} + + + +void User::slotDelete(bool ok) +{ + int row = ui.tableWidget->currentRow(); + QString username = ui.tableWidget->item(row, 0)->text(); + QString password = ui.tableWidget->item(row, 1)->text(); + QString level = ui.tableWidget->item(row, 2)->text(); + QString safeCode = ui.tableWidget->item(row, 3)->text(); + // 删除视图 + ui.tableWidget->removeRow(row); + + // 删除配置 + for (int i = 0; i < m_users.count();i++) + { + QMap user = m_users[i]; + if (user["username"] == username && user["password"] == password && user["level"] == level && user["safeCode"] == safeCode) + { + m_users.removeAt(i); + break; + } + } + g_config->setUsersList(m_users); +} + + +void User::slotAddUser(QString username, QString password, QString level, QString safeCode) +{ + bool found = false; + QList>::iterator iter; + for (iter = m_users.begin(); iter != m_users.end(); iter++) + { + QMap user = *iter; + if (user["username"] == username && user["password"] == password && user["level"] == level && user["safeCode"] == safeCode) + { + found = true; + break; + } + } + // 避免重复添加 + if (found) + { + return; + } + + if (username.isEmpty() || password.isEmpty() || level.isEmpty()) + { + return; + } + // 添加视图 + int index = ui.tableWidget->rowCount(); + ui.tableWidget->insertRow(index); + ui.tableWidget->setItem(index, 0, new QTableWidgetItem(username)); + ui.tableWidget->setItem(index, 1, new QTableWidgetItem(password)); + ui.tableWidget->setItem(index, 2, new QTableWidgetItem(level)); + ui.tableWidget->setItem(index, 3, new QTableWidgetItem(safeCode)); + + // 保存配置 + QMap user; + user["username"] = username; + user["password"] = password; + user["level"] = level; + user["safeCode"] = safeCode; + m_users.append(user); + g_config->setUsersList(m_users); +} \ No newline at end of file diff --git a/CrownServer/User.h b/CrownServer/User.h new file mode 100644 index 0000000..6a7b5a0 --- /dev/null +++ b/CrownServer/User.h @@ -0,0 +1,32 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include "ui_User.h" + +class User : public QWidget +{ + Q_OBJECT + +public: + User(QWidget *parent = nullptr); + ~User(); + +private: + Ui::UserClass ui; + +signals: + void signalSetUser(QString username, QString password, QString level, QString safeCode); +public slots: + void slotAddUser(QString username, QString password,QString level,QString safeCode); + void slotDelete(bool); +private: + QMenu* m_menu; + QAction* m_actionDelete; + QList> m_users; +}; diff --git a/CrownServer/User.ui b/CrownServer/User.ui new file mode 100644 index 0000000..1d45681 --- /dev/null +++ b/CrownServer/User.ui @@ -0,0 +1,46 @@ + + + UserClass + + + + 0 + 0 + 367 + 376 + + + + User + + + + + + + 账号 + + + + + 密码 + + + + + 等级 + + + + + 安全码 + + + + + + + + + + diff --git a/CrownServer/UserThread.cpp b/CrownServer/UserThread.cpp new file mode 100644 index 0000000..26e815c --- /dev/null +++ b/CrownServer/UserThread.cpp @@ -0,0 +1,817 @@ +#include "UserThread.h" +#include "Global.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "Utils.h" + +UserThread::UserThread() + : m_wakeUpRequested(false) + , m_isPaused(false) +{ + qRegisterMetaType>("QList"); +} + +UserThread::~UserThread() +{ + stopImmediately(); + if (this->isRunning()) { + this->wait(1000); + } +} + +void UserThread::stopImmediately() +{ + { + QMutexLocker lock(&m_mutex); + m_wakeUpRequested = true; + m_isPaused = false; + } + + m_waitCondition.wakeAll(); + this->requestInterruption(); +} + +void UserThread::interruptibleSleep(int milliseconds) +{ + if (milliseconds <= 0 || this->isInterruptionRequested()) return; + + QMutexLocker lock(&m_mutex); + if (m_wakeUpRequested) return; + + m_waitCondition.wait(&m_mutex, milliseconds); +} + +QByteArray UserThread::interruptibleNetworkRequest(QNetworkAccessManager& manager, QNetworkRequest& request, const QByteArray& data, int timeoutMs) +{ + if (this->isInterruptionRequested() || m_wakeUpRequested) { + return QByteArray(); + } + + QNetworkReply* reply = manager.post(request, data); + reply->ignoreSslErrors(); + + QEventLoop eventLoop; + QTimer timeoutTimer; + timeoutTimer.setSingleShot(true); + + connect(&manager, &QNetworkAccessManager::finished, &eventLoop, &QEventLoop::quit); + connect(&timeoutTimer, &QTimer::timeout, &eventLoop, &QEventLoop::quit); + connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit); + + // 中断检查定时器 + QTimer interruptTimer; + interruptTimer.setInterval(100); + connect(&interruptTimer, &QTimer::timeout, [&]() { + if (this->isInterruptionRequested() || m_wakeUpRequested) { + reply->abort(); + eventLoop.quit(); + } + }); + + timeoutTimer.start(timeoutMs); + interruptTimer.start(); + eventLoop.exec(); + + interruptTimer.stop(); + timeoutTimer.stop(); + + QByteArray result; + if (!this->isInterruptionRequested() && !m_wakeUpRequested && reply->error() == QNetworkReply::NoError) { + result = reply->readAll(); + } + + reply->deleteLater(); + return result; +} + +QList UserThread::extract_user_list() +{ + QMutexLocker lock(&m_data_mutex); + return m_user_list; +} + +QList UserThread::extract_agent_list() +{ + QMutexLocker lock(&m_data_mutex); + return m_agent_list; +} + +void UserThread::run() +{ + while (!this->isInterruptionRequested() && !m_wakeUpRequested) { + { + QMutexLocker lock(&m_mutex); + if (m_wakeUpRequested) break; + + // 检查暂停状态 + while (m_isPaused && !m_wakeUpRequested && !this->isInterruptionRequested()) { + m_waitCondition.wait(&m_mutex, 100); + } + if (m_wakeUpRequested) break; + + // 检查参数是否有效 + if (m_url.isEmpty() || m_ver.isEmpty() || m_uid.isEmpty() || + m_login_layer.isEmpty() || m_layer_id.isEmpty() || + m_langx.isEmpty() || m_current_username.isEmpty()) { + interruptibleSleep(5000); + continue; + } + } + + // 清空数据 + { + QMutexLocker lock(&m_data_mutex); + m_user_list.clear(); + m_agent_list.clear(); + m_account_list.clear(); + // 添加自身 + QMap current_account; + current_account["username"] = m_current_username; + current_account["level"] = m_login_layer; + m_agent_list.append(m_current_username); + } + + try { + // 登1代理 + if (m_login_layer == "co") { + QList> superAgentList = getSuperAgentList(); + + for (const auto& superAgent : superAgentList) { + if (this->isInterruptionRequested() || m_wakeUpRequested) break; + + { + QMutexLocker lock(&m_data_mutex); + m_agent_list.append(superAgent["username"]); + QMap agent; + agent["username"] = superAgent["username"]; + agent["up_username"] = m_current_username; + agent["up_up_username"] = ""; + agent["level"] = "su"; + m_account_list.append(agent); + } + + QList> agentList = getAgentList(superAgent["id"]); + for (const auto& agent : agentList) { + if (this->isInterruptionRequested() || m_wakeUpRequested) break; + + interruptibleSleep(1000); + QList userList = getUserList(agent["id"]); + + QMutexLocker lock(&m_data_mutex); + m_agent_list.append(agent["username"]); + m_user_list.append(userList); + + // 添加代理账户 + QMap agentAccount; + agentAccount["username"] = agent["username"]; + agentAccount["up_username"] = superAgent["username"]; + agentAccount["up_up_username"] = m_current_username; + agentAccount["level"] = "ag"; + m_account_list.append(agentAccount); + + // 添加用户账户 + for (const auto& user : userList) { + QMap userAccount; + userAccount["username"] = user; + userAccount["up_username"] = agent["username"]; + userAccount["up_up_username"] = superAgent["username"]; + userAccount["level"] = "user"; + m_account_list.append(userAccount); + } + } + } + } + // 登2代理 + else if (m_login_layer == "su") { + QList> agentList = getAgentList(m_layer_id); + + for (const auto& agent : agentList) { + if (this->isInterruptionRequested() || m_wakeUpRequested) break; + + interruptibleSleep(1000); + QList userList = getUserList(agent["id"]); + + QMutexLocker lock(&m_data_mutex); + m_agent_list.append(agent["username"]); + m_user_list.append(userList); + + // 添加代理账户信息 + QMap agentAccount; + agentAccount["username"] = agent["username"]; + agentAccount["up_username"] = m_current_username; + agentAccount["up_up_username"] = ""; // 登2代理的上上级为空 + agentAccount["level"] = "ag"; + m_account_list.append(agentAccount); + + // 添加用户账户信息 + for (const auto& user : userList) { + QMap userAccount; + userAccount["username"] = user; + userAccount["up_username"] = agent["username"]; + userAccount["up_up_username"] = m_current_username; + userAccount["level"] = "user"; + m_account_list.append(userAccount); + } + } + } + // 登3代理 + else if (m_login_layer == "ag") { + QList userList = getUserList(m_layer_id); + + QMutexLocker lock(&m_data_mutex); + m_user_list.append(userList); + + // 添加用户账户信息 + for (const auto& user : userList) { + QMap userAccount; + userAccount["username"] = user; + userAccount["up_username"] = m_current_username; + userAccount["up_up_username"] = ""; // 登3代理的上上级为空 + userAccount["level"] = "user"; + m_account_list.append(userAccount); + } + } + //qDebug() << "User list:" << m_user_list; + //qDebug() << "Account list size:" << m_account_list.size(); + } + + + catch (...) { + //qDebug() << "Exception occurred in UserThread run loop"; + } + + // 等待下一次执行 + interruptibleSleep(g_config->readUserListInterVal() * 1000); + } + + //qDebug() << "UserThread 安全退出"; +} + +QList> UserThread::getSuperAgentList() +{ + if (this->isInterruptionRequested() || m_wakeUpRequested) { + return QList>(); + } + + QNetworkAccessManager networkManager; + QNetworkRequest request; + request.setUrl(QUrl(QString(m_url + "transform.php?ver=" + m_ver))); + request.setRawHeader("Accept", "*/*"); + request.setRawHeader("Cookie", m_cookies.toUtf8()); + request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); + request.setRawHeader("Origin", m_url.toUtf8()); + request.setRawHeader("Referer", m_url.toUtf8()); + request.setRawHeader("Host", QUrl(m_url).host().toUtf8()); + + QString data = "p=get_acc_su_list&ver=" + m_ver + "&uid=" + m_uid + "&login_layer=" + m_login_layer + "&user_name=&enable=Y&sort_type=asc&sort_name=username"; + + QByteArray result = interruptibleNetworkRequest(networkManager, request, data.toUtf8()); + if (result.isEmpty() || this->isInterruptionRequested() || m_wakeUpRequested) { + return QList>(); + } + + QJsonDocument document = QJsonDocument::fromJson(result); + if (document.isNull()) { + qDebug() << "[网络返回异常] getSuperAgentList"; + return QList>(); + } + + QJsonObject jsonObject = document.object(); + if (jsonObject["status"].toString() == "error") { + qDebug() << "[网络返回失败] getSuperAgentList"; + return QList>(); + } + + QJsonArray accountArray = jsonObject["account"].toArray(); + if (accountArray.isEmpty()) { + return QList>(); + } + + QList> list; + for (int i = 0; i < accountArray.count(); i++) { + if (this->isInterruptionRequested() || m_wakeUpRequested) break; + + QJsonObject accountObject = accountArray.at(i).toObject(); + QMap accountMap; + + for (const QString& key : accountObject.keys()) { + accountMap.insert(key, accountObject.value(key).toVariant().toString()); + } + + list.append(accountMap); + } + + return list; +} + +QList> UserThread::getAgentList(QString superAgentId) +{ + if (this->isInterruptionRequested() || m_wakeUpRequested) { + return QList>(); + } + + QNetworkAccessManager networkManager; + QNetworkRequest request; + request.setUrl(QUrl(QString(m_url + "transform.php?ver=" + m_ver))); + request.setRawHeader("Accept", "*/*"); + request.setRawHeader("Cookie", m_cookies.toUtf8()); + request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); + request.setRawHeader("Origin", m_url.toUtf8()); + request.setRawHeader("Referer", m_url.toUtf8()); + request.setRawHeader("Host", QUrl(m_url).host().toUtf8()); + + QString data = "p=get_acc_ag_list&ver=" + m_ver + "&uid=" + m_uid + "&login_layer=" + m_login_layer + "&user_name=&enable=Y&sort_type=asc&sort_name=username&langx=" + m_langx + "&up_id=" + superAgentId + "&pay_type=ALL"; + + QByteArray result = interruptibleNetworkRequest(networkManager, request, data.toUtf8()); + if (result.isEmpty() || this->isInterruptionRequested() || m_wakeUpRequested) { + return QList>(); + } + + QJsonDocument document = QJsonDocument::fromJson(result); + if (document.isNull()) { + qDebug() << "[网络返回异常] getAgentList"; + return QList>(); + } + + QJsonObject jsonObject = document.object(); + if (jsonObject["status"].toString() == "error") { + qDebug() << "[网络返回失败] getAgentList"; + return QList>(); + } + + QJsonArray accountArray = jsonObject["account"].toArray(); + if (accountArray.isEmpty()) { + return QList>(); + } + + QList> list; + for (int i = 0; i < accountArray.count(); i++) { + if (this->isInterruptionRequested() || m_wakeUpRequested) break; + + QJsonObject accountObject = accountArray.at(i).toObject(); + QMap accountMap; + + for (const QString& key : accountObject.keys()) { + accountMap.insert(key, accountObject.value(key).toVariant().toString()); + } + + list.append(accountMap); + } + + return list; +} + +QList UserThread::getUserList(QString agentId) +{ + if (this->isInterruptionRequested() || m_wakeUpRequested) { + return QList(); + } + + QNetworkAccessManager networkManager; + QNetworkRequest request; + request.setUrl(QUrl(QString(m_url + "transform.php?ver=" + m_ver))); + request.setRawHeader("Accept", "*/*"); + request.setRawHeader("Cookie", m_cookies.toUtf8()); + request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); + request.setRawHeader("Origin", m_url.toUtf8()); + request.setRawHeader("Referer", m_url.toUtf8()); + request.setRawHeader("Host", QUrl(m_url).host().toUtf8()); + + QString data = "p=get_acc_mem_list&ver=" + m_ver + "&uid=" + m_uid + "&login_layer=" + m_login_layer + "&user_name=<ype=ALL&enable=Y&sort_type=asc&sort_name=username&langx=" + m_langx + "&up_id=" + agentId +"&up_pay_type=0"; + + QByteArray result = interruptibleNetworkRequest(networkManager, request, data.toUtf8()); + if (result.isEmpty() || this->isInterruptionRequested() || m_wakeUpRequested) { + return QList(); + } + + QJsonDocument document = QJsonDocument::fromJson(result); + if (document.isNull()) { + qDebug() << "[网络返回异常] getUserList:" << result; + return QList(); + } + + QJsonObject jsonObject = document.object(); + if (jsonObject["status"].toString() == "error") { + qDebug() << "[网络返回失败] getUserList"; + return QList(); + } + + QJsonArray accountArray = jsonObject["account"].toArray(); + if (accountArray.isEmpty()) { + return QList(); + } + + QList list; + for (int i = 0; i < accountArray.count(); i++) { + if (this->isInterruptionRequested() || m_wakeUpRequested) break; + + QJsonObject accountObject = accountArray.at(i).toObject(); + if (accountObject.contains("username")) { + list.append(accountObject["username"].toString()); + } + } + + return list; +} + +void UserThread::setParam(QString url, QString ver, QString uid, QString login_layer, QString layer_id, QString langx, QString current_username, QString cookies) +{ + QMutexLocker lock(&m_mutex); + m_url = Utils::normalizeUrl(url); + m_ver = ver; + m_uid = uid; + m_login_layer = login_layer; + m_layer_id = layer_id; + m_langx = langx; + m_current_username = current_username; + m_cookies = cookies; +} + +void UserThread::clearParam() +{ + QMutexLocker lock(&m_mutex); + m_url = ""; + m_ver = ""; + m_uid = ""; + m_login_layer = ""; + m_layer_id = ""; + m_langx = ""; + m_current_username = ""; + m_cookies = ""; +} + +void UserThread::pause() +{ + QMutexLocker lock(&m_mutex); + m_isPaused = true; +} + +void UserThread::resume() +{ + QMutexLocker lock(&m_mutex); + m_isPaused = false; + m_waitCondition.wakeAll(); +} + + + + +// 在 UserThread.cpp 中实现静态方法 +UserThread::UserListResult UserThread::getAllUsersStatic(const QString& url, + const QString& ver, + const QString& uid, + const QString& login_layer, + const QString& layer_id, + const QString& langx, + const QString& cookies, + const QString& current_username, + const QString& pay_type, + int timeoutMs) +{ + UserListResult result; + + if (url.isEmpty() || ver.isEmpty() || uid.isEmpty() || + login_layer.isEmpty() || layer_id.isEmpty() || + langx.isEmpty() || current_username.isEmpty()) { + return result; + } + + // 添加自身到代理列表 + result.agentList.append(current_username); + + // 添加当前代理信息到accountList + QMap currentAccount; + currentAccount["username"] = current_username; + currentAccount["up_username"] = ""; + currentAccount["up_up_username"] = ""; + currentAccount["level"] = login_layer; + result.accountList.append(currentAccount); + + try { + if (login_layer == "co") { + QList> superAgentList = getSuperAgentListStatic(url, ver, uid, login_layer, langx, cookies, timeoutMs); + + for (const auto& superAgent : superAgentList) { + result.agentList.append(superAgent["username"]); + + // 添加总代理账户信息 + QMap superAgentAccount; + superAgentAccount["username"] = superAgent["username"]; + superAgentAccount["up_username"] = current_username; + superAgentAccount["up_up_username"] = ""; + superAgentAccount["level"] = "su"; + result.accountList.append(superAgentAccount); + + QList> agentList = getAgentListStatic(url, ver, uid, login_layer, langx, cookies, superAgent["id"], timeoutMs); + for (const auto& agent : agentList) { + QThread::msleep(1000); // 添加延迟避免请求过快 + QList userList = getUserListStatic(url, ver, uid, login_layer, langx, cookies, agent["id"], agent["pay_type"],timeoutMs); + + result.agentList.append(agent["username"]); + result.userList.append(userList); + + // 添加代理账户信息 + QMap agentAccount; + agentAccount["username"] = agent["username"]; + agentAccount["up_username"] = superAgent["username"]; + agentAccount["up_up_username"] = current_username; + agentAccount["level"] = "ag"; + result.accountList.append(agentAccount); + + // 添加用户账户信息 + for (const auto& user : userList) { + QMap userAccount; + userAccount["username"] = user; + userAccount["up_username"] = agent["username"]; + userAccount["up_up_username"] = superAgent["username"]; + userAccount["level"] = "user"; + result.accountList.append(userAccount); + } + } + } + } + else if (login_layer == "su") { + QList> agentList = getAgentListStatic(url, ver, uid, login_layer, langx, cookies, layer_id, timeoutMs); + + for (const auto& agent : agentList) { + //qDebug() << "代理商:" << agent["username"]; + //QThread::msleep(1000); // 添加延迟避免请求过快 + QList userList = getUserListStatic(url, ver, uid, login_layer, langx, cookies, agent["id"], agent["pay_type"],timeoutMs); + + result.agentList.append(agent["username"]); + result.userList.append(userList); + + // 添加代理账户信息 + QMap agentAccount; + agentAccount["username"] = agent["username"]; + agentAccount["up_username"] = current_username; + agentAccount["up_up_username"] = ""; + agentAccount["level"] = "ag"; + result.accountList.append(agentAccount); + + // 添加用户账户信息 + for (const auto& user : userList) { + //qDebug() << "用户:" << user; + QMap userAccount; + userAccount["username"] = user; + userAccount["up_username"] = agent["username"]; + userAccount["up_up_username"] = current_username; + userAccount["level"] = "user"; + result.accountList.append(userAccount); + } + } + } + else if (login_layer == "ag") { + QList userList = getUserListStatic(url, ver, uid, login_layer, langx, cookies, layer_id, pay_type,timeoutMs); + result.userList.append(userList); + + // 添加用户账户信息 + for (const auto& user : userList) { + QMap userAccount; + userAccount["username"] = user; + userAccount["up_username"] = current_username; + userAccount["up_up_username"] = ""; + userAccount["level"] = "user"; + result.accountList.append(userAccount); + } + } + } + catch (...) { + qDebug() << "Exception occurred in getAllUsersStatic"; + } + + return result; +} + +QList> UserThread::getSuperAgentListStatic(const QString& url, + const QString& ver, + const QString& uid, + const QString& login_layer, + const QString& langx, + const QString& cookies, + int timeoutMs) +{ + QNetworkAccessManager networkManager; + QNetworkRequest request; + request.setUrl(QUrl(QString(url + "transform.php?ver=" + ver))); + request.setRawHeader("Accept", "*/*"); + request.setRawHeader("Cookie", cookies.toUtf8()); + request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); + request.setRawHeader("Origin", url.toUtf8()); + request.setRawHeader("Referer", url.toUtf8()); + request.setRawHeader("Host", QUrl(url).host().toUtf8()); + + QString data = "p=get_acc_su_list&ver=" + ver + "&uid=" + uid + "&login_layer=" + login_layer + "&user_name=&enable=Y&sort_type=asc&sort_name=username"; + + QByteArray result = staticNetworkRequest(networkManager, request, data.toUtf8(), timeoutMs); + if (result.isEmpty()) { + return QList>(); + } + + QJsonDocument document = QJsonDocument::fromJson(result); + if (document.isNull()) { + qDebug() << "[网络返回异常] getSuperAgentListStatic"; + return QList>(); + } + + QJsonObject jsonObject = document.object(); + if (jsonObject["status"].toString() == "error") { + qDebug() << "[网络返回失败] getSuperAgentListStatic"; + return QList>(); + } + + QJsonArray accountArray = jsonObject["account"].toArray(); + if (accountArray.isEmpty()) { + return QList>(); + } + + QList> list; + for (int i = 0; i < accountArray.count(); i++) { + QJsonObject accountObject = accountArray.at(i).toObject(); + QMap accountMap; + + for (const QString& key : accountObject.keys()) { + accountMap.insert(key, accountObject.value(key).toVariant().toString()); + } + + list.append(accountMap); + } + + return list; +} + +QList> UserThread::getAgentListStatic(const QString& url, + const QString& ver, + const QString& uid, + const QString& login_layer, + const QString& langx, + const QString& cookies, + const QString& upId, + int timeoutMs) +{ + QNetworkAccessManager networkManager; + QNetworkRequest request; + request.setUrl(QUrl(QString(url + "transform.php?ver=" + ver))); + request.setRawHeader("Accept", "*/*"); + request.setRawHeader("Cookie", cookies.toUtf8()); + request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); + request.setRawHeader("Origin", url.toUtf8()); + request.setRawHeader("Referer", url.toUtf8()); + request.setRawHeader("Host", QUrl(url).host().toUtf8()); + + QString data = "p=get_acc_ag_list&ver=" + ver + "&uid=" + uid + "&login_layer=" + login_layer + + "&user_name=&enable=Y&sort_type=asc&sort_name=username&langx=" + langx + + "&up_id=" + upId + "&pay_type=ALL"; + + //qDebug() << data; + QByteArray result = staticNetworkRequest(networkManager, request, data.toUtf8(), timeoutMs); + if (result.isEmpty()) { + return QList>(); + } + + QJsonDocument document = QJsonDocument::fromJson(result); + if (document.isNull()) { + qDebug() << "[网络返回异常] getAgentListStatic"; + qDebug() << data; + return QList>(); + } + + QJsonObject jsonObject = document.object(); + if (jsonObject["status"].toString() == "error") { + qDebug() << "[网络返回失败] getAgentListStatic"; + qDebug() << data; + return QList>(); + } + + QJsonArray accountArray = jsonObject["account"].toArray(); + if (accountArray.isEmpty()) { + return QList>(); + } + + QList> list; + for (int i = 0; i < accountArray.count(); i++) { + QJsonObject accountObject = accountArray.at(i).toObject(); + QMap accountMap; + + for (const QString& key : accountObject.keys()) { + accountMap.insert(key, accountObject.value(key).toVariant().toString()); + } + + list.append(accountMap); + } + + return list; +} + +QList UserThread::getUserListStatic(const QString& url, + const QString& ver, + const QString& uid, + const QString& login_layer, + const QString& langx, + const QString& cookies, + const QString& agentId, + const QString& up_pay_type, + int timeoutMs) +{ + QNetworkAccessManager networkManager; + QNetworkRequest request; + request.setUrl(QUrl(QString(url + "transform.php?ver=" + ver))); + request.setRawHeader("Accept", "*/*"); + request.setRawHeader("Cookie", cookies.toUtf8()); + request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); + request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50"); + request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); + request.setRawHeader("Origin", url.toUtf8()); + request.setRawHeader("Referer", url.toUtf8()); + request.setRawHeader("Host", QUrl(url).host().toUtf8()); + + QString data = "p=get_acc_mem_list&ver=" + ver + "&uid=" + uid + "&login_layer=" + login_layer + + "&user_name=<ype=ALL&enable=Y&sort_type=asc&sort_name=username&langx=" + langx + + "&up_id=" + agentId + "&up_pay_type=" + up_pay_type; + //qDebug() << "get_acc_mem_list 地址:" << QString(url + "transform.php?ver=" + ver); + //qDebug() << "get_acc_mem_list 参数:" << data; + + QByteArray result = staticNetworkRequest(networkManager, request, data.toUtf8(), timeoutMs); + //qDebug() << "get_acc_mem_list 返回:" << result; + if (result.isEmpty()) { + return QList(); + } + + QJsonDocument document = QJsonDocument::fromJson(result); + if (document.isNull()) { + qDebug() << "[网络返回异常] getUserListStatic:" << result; + qDebug() << QString(url + "transform.php?ver=" + ver); + qDebug() << data; + return QList(); + } + + QJsonObject jsonObject = document.object(); + if (jsonObject["status"].toString() == "error") { + qDebug() << "[网络返回失败] getUserListStatic"; + qDebug() << QString(url + "transform.php?ver=" + ver); + qDebug() << data; + return QList(); + } + + QJsonArray accountArray = jsonObject["account"].toArray(); + if (accountArray.isEmpty()) { + return QList(); + } + + QList list; + for (int i = 0; i < accountArray.count(); i++) { + QJsonObject accountObject = accountArray.at(i).toObject(); + if (accountObject.contains("username")) { + list.append(accountObject["username"].toString()); + } + } + + return list; +} + +QByteArray UserThread::staticNetworkRequest(QNetworkAccessManager& manager, + QNetworkRequest& request, + const QByteArray& data, + int timeoutMs) +{ + QNetworkReply* reply = manager.post(request, data); + reply->ignoreSslErrors(); + + QEventLoop eventLoop; + QTimer timeoutTimer; + timeoutTimer.setSingleShot(true); + + connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit); + connect(&timeoutTimer, &QTimer::timeout, [&]() { + reply->abort(); + eventLoop.quit(); + }); + + timeoutTimer.start(timeoutMs); + eventLoop.exec(); + timeoutTimer.stop(); + + QByteArray result; + if (reply->error() == QNetworkReply::NoError) { + result = reply->readAll(); + } + + reply->deleteLater(); + return result; +} \ No newline at end of file diff --git a/CrownServer/UserThread.h b/CrownServer/UserThread.h new file mode 100644 index 0000000..803e3c9 --- /dev/null +++ b/CrownServer/UserThread.h @@ -0,0 +1,135 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class UserThread : public QThread +{ + Q_OBJECT +public: + UserThread(); + ~UserThread(); + + // 线程控制方法 + void stopImmediately(); + void pause(); + void resume(); + void clearParam(); + + // 参数设置 + void setParam(QString url, QString ver, QString uid, QString login_layer, + QString layer_id, QString langx, QString current_username, QString cookies); + + // 数据获取方法 + QList extract_user_list(); + QList extract_agent_list(); + +protected: + void run() override; + +private: + // 线程同步 + QMutex m_mutex; + QMutex m_data_mutex; + QWaitCondition m_waitCondition; + + // 线程控制标志 + bool m_wakeUpRequested; + bool m_isPaused; + + // 配置参数 + QString m_url; + QString m_ver; + QString m_uid; + QString m_login_layer; + QString m_layer_id; + QString m_langx; + QString m_current_username; + QString m_cookies; + + // 数据存储 + QList m_user_list; + QList m_agent_list; + QList> m_account_list; + +private: + // 辅助方法 + void interruptibleSleep(int milliseconds); + QByteArray interruptibleNetworkRequest(QNetworkAccessManager& manager, + QNetworkRequest& request, + const QByteArray& data, + int timeoutMs = 10000); + + // 网络请求方法 + QList> getSuperAgentList(); + QList> getAgentList(QString superAgentId); + QList getUserList(QString agentId); + +signals: + // 可以添加一些信号,比如错误信号、数据更新信号等 + void errorOccurred(const QString& errorMessage); + void dataUpdated(); + + +public: + struct UserListResult { + QList userList; + QList agentList; + QList> accountList; + }; + + static UserListResult getAllUsersStatic(const QString& url, + const QString& ver, + const QString& uid, + const QString& login_layer, + const QString& layer_id, + const QString& langx, + const QString& cookies, + const QString& pay_type, + const QString& current_username, + int timeoutMs = 10000); + +private: + static QList> getSuperAgentListStatic(const QString& url, + const QString& ver, + const QString& uid, + const QString& login_layer, + const QString& langx, + const QString& cookies, + int timeoutMs); + + static QList> getAgentListStatic(const QString& url, + const QString& ver, + const QString& uid, + const QString& login_layer, + const QString& langx, + const QString& cookies, + const QString& upId, + int timeoutMs); + + static QList getUserListStatic(const QString& url, + const QString& ver, + const QString& uid, + const QString& login_layer, + const QString& langx, + const QString& cookies, + const QString& agentId, + const QString& up_pay_type, + int timeoutMs); + + static QByteArray staticNetworkRequest(QNetworkAccessManager& manager, + QNetworkRequest& request, + const QByteArray& data, + int timeoutMs); +}; \ No newline at end of file diff --git a/CrownServer/Utils.cpp b/CrownServer/Utils.cpp new file mode 100644 index 0000000..4f001c7 --- /dev/null +++ b/CrownServer/Utils.cpp @@ -0,0 +1,846 @@ +#include "Utils.h" + +Utils::Utils() +{ +} + +Utils::~Utils() +{ +} + +Utils& Utils::instance() +{ + static Utils m_instance; + return m_instance; +} + +// 函数用于在model中查找特定文本,并返回找到的第一个项的索引 +QModelIndex Utils::findItem(QStandardItemModel *model, const QString &text) { + for (int row = 0; row < model->rowCount(); ++row) { + for (int column = 0; column < model->columnCount(); ++column) { + QModelIndex index = model->index(row, column); + QStandardItem *item = model->itemFromIndex(index); + if (item && item->text() == text) { + return index; + } + } + } + return QModelIndex(); // 如果没有找到,返回一个无效的QModelIndex +} + +QString Utils::convertToBase(const QString& input) { + // 假设输入字符串的格式是 "前缀_数字" + // 使用'_'作为分隔符来分割字符串 + QStringList parts = input.split('_'); + + // 检查是否成功分割出至少两部分 + if (parts.size() > 0) { + // 返回第一部分,即前缀 + return parts.first(); + } + else { + // 如果没有'_'或者输入为空,则直接返回原字符串 + return input; + } +} + +QString Utils::getTypeName(QString rtype) +{ + // 让球 + if (rtype == "REH" || rtype == "RH" || rtype == "HREH" || rtype == "HRH") + { + return "让球"; + } + + // 受让 + if (rtype == "REC" || rtype == "RC" || rtype == "HREC" || rtype == "HRC") + { + return "受让"; + } + // 大 + if (rtype == "ROUC" || rtype == "OUC" || rtype == "HROUC" || rtype == "HOUC") + { + return "大"; + } + // 小 + if (rtype == "ROUH" || rtype == "OUH" || rtype == "HROUH" || rtype == "HOUH") + { + return "小"; + } + // 独赢主 + if (rtype == "RMH" || rtype == "MH" || rtype == "HRMH" || rtype == "HMH") + { + return "独赢主"; + } + // 独赢客 + if (rtype == "RMC" || rtype == "MC" || rtype == "HRMC" || rtype == "HMC") + { + return "独赢客"; + } + // 独赢和 + if (rtype == "RMN" || rtype == "MN" || rtype == "HRMN" || rtype == "HMN") + { + return "独赢和"; + } + // 单 + if (rtype == "REOO" || rtype == "EOO" || rtype == "HREOO" || rtype == "HEOO") + { + return "单"; + } + // 双 + if (rtype == "REOE" || rtype == "EOE" || rtype == "HREOE" || rtype == "HEOE") + { + return "双"; + } + + // 改 + //// 单 + //if (rtype == "RODD" || rtype == "ODD" || rtype == "HRODD" || rtype == "HODD") + //{ + // return "单"; + //} + //// 双 + //if (rtype == "REVEN" || rtype == "EVEN" || rtype == "HREVEN" || rtype == "HEVEN") + //{ + // return "双"; + //} + + // 主队大 + if (rtype == "ROUHO" || rtype == "OUHO" || rtype == "HROUHO" || rtype == "HOUHO") + { + return "主队大"; + } + // 主队小 + if (rtype == "ROUHU" || rtype == "OUHU" || rtype == "HROUHU" || rtype == "HOUHU") + { + return "主队小"; + } + // 客队大 + if (rtype == "ROUCO" || rtype == "OUCO" || rtype == "HROUCO" || rtype == "HOUCO") + { + return "客队大"; + } + // 客队小 + if (rtype == "ROUCU" || rtype == "OUCU" || rtype == "HROUCU" || rtype == "HOUCU") + { + return "客队小"; + } + return QString(); +} + +QString Utils::get_wagers_wtype_name(QString wtype) +{ + // 滚球 RE 让球 ROU大小 RM独赢 HRE 让球上半 HROU 大小上半 HRM 独赢上半 RG下个进球 RTS双方球队进球 + // 滚球全场 REO单双 + + if (wtype == "R" || wtype == "RE" || wtype == "HR" || wtype == "HRE") + { + return "让球"; + } + if (wtype == "OU" || wtype == "ROU" || wtype == "HOU" || wtype == "HROU") + { + return "大小"; + } + if (wtype == "M" || wtype == "RM" || wtype == "HM" || wtype == "HRM") + { + return "独赢"; + } + if (wtype == "G" || wtype == "RG" || wtype == "HG" || wtype == "HRG") + { + return "下个进球"; + } + if (wtype == "TS" || wtype == "RTS" || wtype == "HTS" || wtype == "HRTS") + { + return "双方球队进球"; + } + if (wtype == "EO" || wtype == "REO" || wtype == "HEO" || wtype == "HREO") // RT 滚球单双 EO 早盘单双 + { + return "单双"; // ODD / EVEN ? + } + if (wtype == "OUH" || wtype == "ROUH" || wtype == "HOUH" || wtype == "HROUH") + { + return "队伍1进球"; + } + if (wtype == "OUC" || wtype == "ROUC" || wtype == "HOUC" || wtype == "HROUC") + { + return "队伍2进球"; + } + if (wtype == "SH" || wtype == "RSH" || wtype == "HSH" || wtype == "HRSH") + { + return "下个点球"; + } + + return ""; + // R 让球 + // OU 大小 + // M 独赢 + // HR 让球上半场 + // HOU 大小上半场 + // HM 独赢上半场 + + // TS 双方进球 TSY 是/ TSN 否 + // EO 单双 +} + +//QMap Utils::type(QString projcet, QString type) +//{ +// QMap map; +// map["projcet"] = projcet; +// map["type"] = type; +// if (projcet == "足球滚球全场") +// { +// map["gtype"] = "FT"; +// map["session"] = "RB"; +// if (type == "让球") +// { +// map["wtype"] = "RE"; +// map["rtype"] = "REH"; +// } +// else if (type == "受让") +// { +// map["wtype"] = "RE"; +// map["rtype"] = "REC"; +// } +// else if (type == "大") +// { +// map["wtype"] = "ROU"; +// map["rtype"] = "ROUC"; +// } +// else if (type == "小") +// { +// map["wtype"] = "ROU"; +// map["rtype"] = "ROUH"; +// } +// else if (type == "独赢主") +// { +// map["wtype"] = "RM"; +// map["rtype"] = "RMH"; +// } +// else if (type == "独赢客") +// { +// map["wtype"] = "RM"; +// map["rtype"] = "RMC"; +// } +// else if (type == "独赢和") +// { +// map["wtype"] = "RM"; +// map["rtype"] = "RMN"; +// } +// else if (type == "单") +// { +// map["wtype"] = "REO"; +// map["rtype"] = "REOO"; +// } +// else if (type == "双") +// { +// map["wtype"] = "REO"; +// map["rtype"] = "REOE"; +// } +// else if (type == "主队大") +// { +// map["wtype"] = "ROUH"; +// map["rtype"] = "ROUHO"; +// } +// else if (type == "主队小") +// { +// map["wtype"] = "ROUH"; +// map["rtype"] = "ROUHU"; +// } +// else if (type == "客队大") +// { +// map["wtype"] = "ROUC"; +// map["rtype"] = "ROUCO"; +// } +// else if (type == "客队小") +// { +// map["wtype"] = "ROUC"; +// map["rtype"] = "ROUCU"; +// } +// } +// else if (projcet == "足球滚球上半场") +// { +// map["gtype"] = "FT"; +// map["session"] = "RB"; +// if (type == "让球") +// { +// map["wtype"] = "HRE"; +// map["rtype"] = "HREH"; +// } +// else if (type == "受让") +// { +// map["wtype"] = "HRE"; +// map["rtype"] = "HREC"; +// } +// else if (type == "大") +// { +// map["wtype"] = "HROU"; +// map["rtype"] = "HROUC"; +// } +// else if (type == "小") +// { +// map["wtype"] = "HROU"; +// map["rtype"] = "HROUH"; +// } +// else if (type == "独赢主") +// { +// map["wtype"] = "HRM"; +// map["rtype"] = "HRMH"; +// } +// else if (type == "独赢客") +// { +// map["wtype"] = "HRM"; +// map["rtype"] = "HRMC"; +// } +// else if (type == "独赢和") +// { +// map["wtype"] = "HRM"; +// map["rtype"] = "HRMN"; +// } +// else if (type == "单") +// { +// map["wtype"] = "HREO"; +// map["rtype"] = "HREOO"; +// } +// else if (type == "双") +// { +// map["wtype"] = "HREO"; +// map["rtype"] = "HREOE"; +// } +// else if (type == "主队大") +// { +// map["wtype"] = "HROUH"; +// map["rtype"] = "HROUHO"; +// } +// else if (type == "主队小") +// { +// map["wtype"] = "HROUH"; +// map["rtype"] = "HROUHU"; +// } +// else if (type == "客队大") +// { +// map["wtype"] = "HROUC"; +// map["rtype"] = "HROUCO"; +// } +// else if (type == "客队小") +// { +// map["wtype"] = "HROUC"; +// map["rtype"] = "HROUCU"; +// } +// } +// else if (projcet == "足球今日全场") +// { +// map["gtype"] = "FT"; +// map["session"] = "FT"; +// if (type == "让球") +// { +// map["wtype"] = "R"; +// map["rtype"] = "RH"; +// } +// else if (type == "受让") +// { +// map["wtype"] = "R"; +// map["rtype"] = "RC"; +// } +// else if (type == "大") +// { +// map["rtype"] = "OUC"; +// } +// else if (type == "小") +// { +// map["rtype"] = "OUH"; +// } +// else if (type == "独赢主") +// { +// map["rtype"] = "MH"; +// } +// else if (type == "独赢客") +// { +// map["rtype"] = "MC"; +// } +// else if (type == "独赢和") +// { +// map["rtype"] = "MN"; +// } +// else if (type == "单") +// { +// map["rtype"] = "EOO"; +// } +// else if (type == "双") +// { +// map["rtype"] = "EOE"; +// } +// else if (type == "主队大") +// { +// map["rtype"] = "OUHO"; +// } +// else if (type == "主队小") +// { +// map["rtype"] = "OUHU"; +// } +// else if (type == "客队大") +// { +// map["rtype"] = "OUCO"; +// } +// else if (type == "客队小") +// { +// map["rtype"] = "OUCU"; +// } +// } +// else if (projcet == "足球今日上半场") +// { +// map["gtype"] = "FT"; +// map["session"] = "FT"; +// if (type == "让球") +// { +// map["rtype"] = "HRH"; +// } +// else if (type == "受让") +// { +// map["rtype"] = "HRC"; +// } +// else if (type == "大") +// { +// map["rtype"] = "HOUC"; +// } +// else if (type == "小") +// { +// map["rtype"] = "HOUH"; +// } +// else if (type == "独赢主") +// { +// map["rtype"] = "HMH"; +// } +// else if (type == "独赢客") +// { +// map["rtype"] = "HMC"; +// } +// else if (type == "独赢和") +// { +// map["rtype"] = "HMN"; +// } +// else if (type == "单") +// { +// map["rtype"] = "HEOO"; +// } +// else if (type == "双") +// { +// map["rtype"] = "HEOE"; +// } +// else if (type == "主队大") +// { +// map["rtype"] = "HOUHO"; +// } +// else if (type == "主队小") +// { +// map["rtype"] = "HOUHU"; +// } +// else if (type == "客队大") +// { +// map["rtype"] = "HOUCO"; +// } +// else if (type == "客队小") +// { +// map["rtype"] = "HOUCU"; +// } +// } +// else if (projcet == "足球早盘全场") +// { +// map["gtype"] = "FT"; +// map["session"] = "FU"; +// if (type == "让球") +// { +// map["rtype"] = "RH"; +// } +// else if (type == "受让") +// { +// map["rtype"] = "RC"; +// } +// else if (type == "大") +// { +// map["rtype"] = "OUC"; +// } +// else if (type == "小") +// { +// map["rtype"] = "OUH"; +// } +// else if (type == "独赢主") +// { +// map["rtype"] = "MH"; +// } +// else if (type == "独赢客") +// { +// map["rtype"] = "MC"; +// } +// else if (type == "独赢和") +// { +// map["rtype"] = "MN"; +// } +// else if (type == "单") +// { +// map["rtype"] = "EOO"; +// } +// else if (type == "双") +// { +// map["rtype"] = "EOE"; +// } +// else if (type == "主队大") +// { +// map["rtype"] = "OUHO"; +// } +// else if (type == "主队小") +// { +// map["rtype"] = "OUHU"; +// } +// else if (type == "客队大") +// { +// map["rtype"] = "OUCO"; +// } +// else if (type == "客队小") +// { +// map["rtype"] = "OUCU"; +// } +// } +// else if (projcet == "足球早盘上半场") +// { +// map["gtype"] = "FT"; +// map["session"] = "FU"; +// if (type == "让球") +// { +// map["rtype"] = "HRH"; +// } +// else if (type == "受让") +// { +// map["rtype"] = "HRC"; +// } +// else if (type == "大") +// { +// map["rtype"] = "HOUC"; +// } +// else if (type == "小") +// { +// map["rtype"] = "HOUH"; +// } +// else if (type == "独赢主") +// { +// map["rtype"] = "HMH"; +// } +// else if (type == "独赢客") +// { +// map["rtype"] = "HMC"; +// } +// else if (type == "独赢和") +// { +// map["rtype"] = "HMN"; +// } +// else if (type == "单") +// { +// map["rtype"] = "HEOO"; +// } +// else if (type == "双") +// { +// map["rtype"] = "HEOE"; +// } +// else if (type == "主队大") +// { +// map["rtype"] = "HOUHO"; +// } +// else if (type == "主队小") +// { +// map["rtype"] = "HOUHU"; +// } +// else if (type == "客队大") +// { +// map["rtype"] = "HOUCO"; +// } +// else if (type == "客队小") +// { +// map["rtype"] = "HOUCU"; +// } +// } +// else if (projcet == "篮球滚球全场") +// { +// map["gtype"] = "BK"; +// map["session"] = "RB"; +// if (type == "让球") +// { +// map["rtype"] = "REH"; +// } +// else if (type == "受让") +// { +// map["rtype"] = "REC"; +// } +// else if (type == "大") +// { +// map["rtype"] = "ROUC"; +// } +// else if (type == "小") +// { +// map["rtype"] = "ROUH"; +// } +// else if (type == "独赢主") +// { +// map["rtype"] = "RMH"; +// } +// else if (type == "独赢客") +// { +// map["rtype"] = "RMC"; +// } +// else if (type == "独赢和") +// { +// map["rtype"] = "RMN"; +// } +// else if (type == "单") +// { +// map["rtype"] = "REOO"; +// } +// else if (type == "双") +// { +// map["rtype"] = "REOE"; +// } +// else if (type == "主队大") +// { +// map["rtype"] = "ROUHO"; +// } +// else if (type == "主队小") +// { +// map["rtype"] = "ROUHU"; +// } +// else if (type == "客队大") +// { +// map["rtype"] = "ROUCO"; +// } +// else if (type == "客队小") +// { +// map["rtype"] = "ROUCU"; +// } +// } +// else if (projcet == "篮球今日全场") +// { +// map["gtype"] = "BK"; +// map["session"] = "FT"; +// if (type == "让球") +// { +// map["rtype"] = "RH"; +// } +// else if (type == "受让") +// { +// map["rtype"] = "RC"; +// } +// else if (type == "大") +// { +// map["rtype"] = "OUC"; +// } +// else if (type == "小") +// { +// map["rtype"] = "OUH"; +// } +// else if (type == "独赢主") +// { +// map["rtype"] = "MH"; +// } +// else if (type == "独赢客") +// { +// map["rtype"] = "MC"; +// } +// else if (type == "独赢和") +// { +// map["rtype"] = "MN"; +// } +// else if (type == "单") +// { +// map["rtype"] = "EOO"; +// } +// else if (type == "双") +// { +// map["rtype"] = "EOE"; +// } +// else if (type == "主队大") +// { +// map["rtype"] = "OUHO"; +// } +// else if (type == "主队小") +// { +// map["rtype"] = "OUHU"; +// } +// else if (type == "客队大") +// { +// map["rtype"] = "OUCO"; +// } +// else if (type == "客队小") +// { +// map["rtype"] = "OUCU"; +// } +// } +// else if (projcet == "篮球早盘全场") +// { +// map["gtype"] = "BK"; +// map["session"] = "FU"; +// if (type == "让球") +// { +// map["rtype"] = "RH"; +// } +// else if (type == "受让") +// { +// map["rtype"] = "RC"; +// } +// else if (type == "大") +// { +// map["rtype"] = "OUC"; +// } +// else if (type == "小") +// { +// map["rtype"] = "OUH"; +// } +// else if (type == "独赢主") +// { +// map["rtype"] = "MH"; +// } +// else if (type == "独赢客") +// { +// map["rtype"] = "MC"; +// } +// else if (type == "独赢和") +// { +// map["rtype"] = "MN"; +// } +// else if (type == "单") +// { +// map["rtype"] = "EOO"; +// } +// else if (type == "双") +// { +// map["rtype"] = "EOE"; +// } +// else if (type == "主队大") +// { +// map["rtype"] = "OUHO"; +// } +// else if (type == "主队小") +// { +// map["rtype"] = "OUHU"; +// } +// else if (type == "客队大") +// { +// map["rtype"] = "OUCO"; +// } +// else if (type == "客队小") +// { +// map["rtype"] = "OUCU"; +// } +// } +// return map; +//} + + + + + + + + +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#include +#endif + +int Utils::get_number_of_application_name() { + std::string filepath; + + // 获取可执行文件完整路径 +#ifdef _WIN32 + char buffer[MAX_PATH]; + GetModuleFileNameA(nullptr, buffer, MAX_PATH); + filepath = buffer; +#else + char buffer[PATH_MAX]; + ssize_t len = readlink("/proc/self/exe", buffer, sizeof(buffer) - 1); + if (len != -1) { + buffer[len] = '\0'; + filepath = buffer; + } +#endif + + // 从完整路径中提取文件名 + std::string filename; + size_t lastSlash = filepath.find_last_of("/\\"); + if (lastSlash != std::string::npos) { + filename = filepath.substr(lastSlash + 1); + } + else { + filename = filepath; + } + + // 提取文件名中的数字 + std::string numberStr; + bool foundDigit = false; + + for (char c : filename) { + if (std::isdigit(c)) { + numberStr += c; + foundDigit = true; + } + else if (foundDigit) { + // 遇到非数字字符且已经找到过数字,停止提取 + break; + } + } + + // 如果找到数字,转换为整数 + if (!numberStr.empty()) { + try { + // 数字范围超过5,返回默认值1 + if (std::stoi(numberStr) < 1 || std::stoi(numberStr) > 5) + { + return 1; //返回默认值1 + } + return std::stoi(numberStr); + } + catch (const std::exception&) { + return 1; // 转换失败,返回默认值1 + } + } + + return 1; // 未找到数字,返回默认值1 +} + +#include +QString Utils::get_report_date() { + // 获取当前中国本地时间,皇冠时间比中国时间慢12小时 + QDateTime currentChinaTime = QDateTime::currentDateTime(); + QDateTime crownTime = currentChinaTime.addSecs(-12 * 3600); + QDate currentDate = crownTime.date(); + + int year = currentDate.year(); + int month = currentDate.month(); + int day = currentDate.day(); + + // 计算当前周期开始日期(每月8日开始新周期) + QDate currentPeriodStart; + if (day >= 8) { + currentPeriodStart = QDate(year, month, 8); + } + else { + if (month == 1) { + currentPeriodStart = QDate(year - 1, 12, 8); + } + else { + currentPeriodStart = QDate(year, month - 1, 8); + } + } + + // 计算上一周期开始日期(当前周期开始前1天) + QDate previousPeriodStart = currentPeriodStart.addDays(-1); + + // 默认周期长度为28天(基于您的数据,大部分周期都是28天) + int previousPeriodLength = 28; + + // 计算上一周期结束日期 + QDate previousPeriodEnd = previousPeriodStart.addDays(previousPeriodLength - 1); + + return previousPeriodEnd.toString("yyyy-MM-dd"); +} \ No newline at end of file diff --git a/CrownServer/Utils.h b/CrownServer/Utils.h new file mode 100644 index 0000000..66667c3 --- /dev/null +++ b/CrownServer/Utils.h @@ -0,0 +1,232 @@ +#pragma once +#include +#include +#include +#include +#include +typedef enum _ProjectType { + Early, + Today, + RollBall +}ProjectType; + + +class Utils { +private: + Utils(); + ~Utils(); + +public: + static Utils& instance(); +public: + // ABC_0 去除后缀 + QString convertToBase(const QString& input); + QModelIndex findItem(QStandardItemModel *model, const QString &text); + // 获取rtype对应的游戏具体类型名称 + QString getTypeName(QString rtype); + // 获取游戏类型 + QString get_wagers_wtype_name(QString wtype); + // 获取类型代号 + // QMap type(QString projcet, QString type); + + + + // 获取时间类型名称 + static QString get_time_type_name(const QString& showtype) { + // 定义映射表 + static const QMap hash = { + {"rb", "滚球"}, // live + {"ft", "今日"}, // today + {"fu", "早盘"}, // early + {"em", "早盘"} // early + }; + + // 如果映射表中存在对应的键,返回映射值;否则返回原值 + return hash.contains(showtype) ? hash.value(showtype) : showtype; + } + + // 检查是否为半场 + static bool is_half(const QString wtype) { + QStringList halfTypes = { "HR", "HRE", "HPD", "HM", "HRM", "HRPD", "HOU", "HROU" }; + return halfTypes.contains(wtype); + } + // 检查是否为滚球 + static bool is_roll_ball(const QString wtype) { + static const QStringList wtypeRB = { + "RE", "ROU", "HRE", "HROU", "RM", "HRM", "ARE", "BRE", "CRE", "DRE", "ERE", "FRE", + "AROU", "BROU", "CROU", "DROU", "EROU", "FROU", "ARM", "BRM", "CRM", "DRM", "ERM", "FRM", + "ROUH", "ROUC", "HRUH", "HRUC", "RPD", "RPD3", "RPD5", "RPD7", "HRPD", "RDT", "RT", "HRT", + "REO", "HREO", "RF", "RHG", "RMG", "ARG", "BRG", "CRG", "DRG", "ERG", "FRG", "GRG", "HRG", + "IRG", "JRG", "RWM", "RDC", "RCS", "RWN", "RTS", "RWB", "RWE", "RSB", "RT1G", "RT3G" + }; + return wtypeRB.contains(wtype.toUpper()); + } + // 映射 rtype(单双规范化):返回 EOO/EOE/HEOO/HEOE/REOO/REOE/HREOO/HREOE + static QString map_rtype(const QString &rtypeIn) { + QString r = rtypeIn.trimmed().toUpper(); + + // 完整映射表(含简写、滚球、半场、滚球半场、P前缀,以及标准本身) + static const QMap tHash = { + // 简写 → 标准 + {"ODD", "EOO"}, + {"EVEN", "EOE"}, + {"HODD", "HEOO"}, + {"HEVEN","HEOE"}, + {"RODD", "REOO"}, + {"REVEN","REOE"}, + {"HRODD","HREOO"}, + {"HREVEN","HREOE"}, + + // P 前缀(串关) → 标准 + {"PEOO", "EOO"}, + {"PEOE", "EOE"}, + {"HPEOO","HEOO"}, + {"HPEOE","HEOE"}, + + // 标准保持(写全便于查找) + {"EOO", "EOO"}, + {"EOE", "EOE"}, + {"HEOO", "HEOO"}, + {"HEOE", "HEOE"}, + {"REOO", "REOO"}, + {"REOE", "REOE"}, + {"HREOO","HREOO"}, + {"HREOE","HREOE"} + }; + + return tHash.contains(r) ? tHash.value(r) : r; + } + // 映射 wtype(简化版,只根据wtype转换) + static QString map_wtype(const QString &wtypeIn) { + QString w = wtypeIn.trimmed().toUpper(); + + // 已是单双大类,直接返回 + static const QSet eoW = { "EO","REO","HEO","HREO" }; + if (eoW.contains(w)) return w; + + // 单双转换映射表 + static const QMap convertMap = { + {"T", "EO"}, + {"RT", "REO"}, + {"HT", "HEO"}, + {"HRT", "HREO"} + }; + + return convertMap.contains(w) ? convertMap.value(w) : w; + } + + + int get_number_of_application_name(); + + + QString get_report_date(); + + + + static QString format_wagers_type(QMap& order) + { + if (order["WAGERS_TYPE"].contains("让球")) + { + return "让球"; + } + + // 大小 + if (order["WAGERS_TYPE"].contains("大 / 小") && !order["WAGERS_TYPE"].contains(order["TEAM_H"]) && !order["WAGERS_TYPE"].contains(order["TEAM_C"])) + { + return "大小"; + } + if (order["WAGERS_TYPE"].contains("独赢")) + { + return "独赢"; + } + if (order["WAGERS_TYPE"].contains("单 / 双")) + { + return "单双"; + } + + // 主大小 + if (order["WAGERS_TYPE"].contains("大 / 小") && order["WAGERS_TYPE"].contains(order["TEAM_H"])) + { + return "主大小"; + } + + // 客大小 + if (order["WAGERS_TYPE"].contains("大 / 小") && order["WAGERS_TYPE"].contains(order["TEAM_C"])) + { + return "客大小"; + } + + return order["WAGERS_TYPE"]; + } + + + // 繁体转简体 + //static QString traditionalToSimplified(const QString& traditional) { + // if (traditional.isEmpty()) { + // return traditional; + // } + + // // 将 QString 转换为 wchar_t 数组 + // int length = traditional.length(); + // wchar_t* inputBuffer = new wchar_t[length + 1]; + // traditional.toWCharArray(inputBuffer); + // inputBuffer[length] = L'\0'; + + // wchar_t* outputBuffer = new wchar_t[length + 1]; + + // // 使用 LCMapString 进行简繁转换 + // int result = LCMapStringW( + // LOCALE_SYSTEM_DEFAULT, // 系统区域设置 + // LCMAP_SIMPLIFIED_CHINESE, // 简体中文映射 + // inputBuffer, // 输入字符串 + // length, // 输入长度 + // outputBuffer, // 输出缓冲区 + // length // 输出缓冲区大小 + // ); + + // QString simplified; + // if (result > 0) { + // outputBuffer[result] = L'\0'; + // simplified = QString::fromWCharArray(outputBuffer, result); + // } + // else { + // // 如果转换失败,返回原字符串 + // simplified = traditional; + // } + + // delete[] inputBuffer; + // delete[] outputBuffer; + // return simplified; + //} + + + // 标准化URL:保留主机名(包括子域名),移除路径和参数 + static QString normalizeUrl(const QString& url, const QString& defaultUrl = "") + { + // 为空则返回默认值 + if (url.isEmpty()) { + return defaultUrl; + } + + // 去除空格 + QString trimmedUrl = url.trimmed(); + QUrl qurl(trimmedUrl); + + // 如果URL无效或缺少协议,尝试添加https:// + if (!qurl.isValid() || qurl.scheme().isEmpty()) { + qurl = QUrl("https://" + trimmedUrl); + } + + // 如果仍然无效,返回默认值 + if (!qurl.isValid() || qurl.host().isEmpty()) { + return defaultUrl; + } + + // 获取主机名(保留www等子域名) + QString host = qurl.host(); + + // 构建标准化URL + QString scheme = (qurl.scheme() == "http") ? "http" : "https"; + return scheme + "://" + host + "/"; + } +}; \ No newline at end of file diff --git a/CrownServer/Verify.cpp b/CrownServer/Verify.cpp new file mode 100644 index 0000000..dc5ab78 --- /dev/null +++ b/CrownServer/Verify.cpp @@ -0,0 +1,614 @@ +#include "Verify.h" +#include "Global.h" +/// +/// 构造函数 +/// +/// +/// +/// +/// +Verify::Verify(QString Url, QString AppId, QString CommKey, QString Verison) +{ + VMProtectBegin("Verify_Init"); + // 初始化网络权限管理类 + + + // 获取随机Key + this->m_randomeKey = this->GetRandom(32); + + m_appId = this->ParamEncrypt(AppId); + m_commKey = this->ParamEncrypt(CommKey); + m_webApi = this->ParamEncrypt(Url + "/api_new.php?"); + m_machineCode = this->GetCPUID(); + m_version = Verison; + + //qDebug() << "验证网址:" << Url; + //qDebug() << "软件ID:" << AppId; + //qDebug() << "通信密钥:" << CommKey; + //qDebug() << "软件版本:" << Verison; + //qDebug() << "机器码:" << this->GetCPUID(); + VMProtectEnd(); +} + +Verify::~Verify() +{ + +} + + +// 获取计算机的CPU的ID +QString Verify::GetCPUID() +{ + QString strCpuId = ""; + unsigned int dwBuf[4] = { 0 }; + unsigned long long ret = 0; + + __cpuid((int*)(void*)dwBuf, 1); + + ret = dwBuf[3]; + ret = ret << 32; + + QString str0 = QString::number(dwBuf[3], 16).toUpper(); + QString str0_1 = str0.rightJustified(8, '0'); + QString str1 = QString::number(dwBuf[0], 16).toUpper(); + QString str1_1 = str1.rightJustified(8, '0'); + strCpuId = str0_1 + str1_1; + + return strCpuId; +} + +// 取随机文本 +QString Verify::GetRandom(int Length) +{ + srand(QDateTime::currentMSecsSinceEpoch()); + QString String; + const char ch[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + int index = 0; + for (int i = 0; i < Length; ++i) + { + index = rand() % strlen(ch); + String += ch[index]; + } + return String; +} + +// 取随机数 +int Verify::GetRandom(int Min, int Max) +{ + srand(QTime(0, 0, 0).secsTo(QTime::currentTime())); + int Random = rand(); + int Number = Random % (Max - Min + 1) + Min; + return Number; +} + +// 计算CRC32 +unsigned int Verify::Crc32(const void* Buffer, unsigned short Length) +{ + + int i, j; + unsigned int CRC32; + + CRC32 = 0xFFFFFFFF; + for (i = 0; i < Length; i++) + { + for (j = 0; j < 8; j++) + { + if (CRC32 & 1) { + CRC32 = (CRC32 >> 1) ^ 0xEDB88320; + } + else + { + CRC32 = (CRC32 >> 1); + } + if (((unsigned char*)Buffer)[i] & (1 << j)) + { + CRC32 ^= 0xEDB88320; + } + } + } + CRC32 = ~CRC32; + return (CRC32); +} + +// RC4加密 +QByteArray Verify::RC4(QByteArray Data, QString Key) +{ + QByteArray m, k, result; + m.resize(256); + k.resize(256); + result.resize(Data.length()); + if (Data.length() < 1) + { + return ""; + } + for (int i = 0; i < 256; i++) + { + m[i] = i; + } + + if (Key.length() > 0) + { + int j = 0; + for (int i = 0; i < 256; i++) + { + k[i] = Key.toUtf8()[j]; + j++; + if (j > Key.length() - 1) + { + j = 0; + } + } + j = 0; + for (int i = 0; i < 256; i++) + { + j = (j + m[i] + k[i]) & 255; + char temp = m[i]; + m[i] = m[j]; + m[j] = temp; + } + } + int i = 0, j = 0; + for (int x = 0; x < Data.length(); x++) + { + i = (i + 1) & 255; + j = (j + m[i]) & 255; + + char temp = m[i]; + m[i] = m[j]; + m[j] = temp; + result[x] = Data[x] ^ m[(m[i] + m[j]) & 255]; + } + // qDebug() << "RC4:" << result.toHex(); + return result; +} + +// 获取MD5 +QString Verify::Md5(QByteArray Data) +{ + QCryptographicHash hash(QCryptographicHash::Md5); + hash.addData(Data); + QString md5 = hash.result().toHex(); + return md5; +} + +QString Verify::ParamEncrypt(QString Param) +{ + VMProtectBegin("Verify_Enc"); + if (Param.isEmpty()) + { + return ""; + } + // 转为字节数组 + QByteArray paramByteArray = Param.toUtf8(); + // 根据字节数组指针计算CRC32 + unsigned int ParamCrc32 = this->Crc32(paramByteArray.data(), Param.size()); + // 参数 + CRC32 + paramByteArray.append(((char*)&ParamCrc32)[0]); + paramByteArray.append(((char*)&ParamCrc32)[1]); + paramByteArray.append(((char*)&ParamCrc32)[2]); + paramByteArray.append(((char*)&ParamCrc32)[3]); + + int Key = this->GetRandom(1, 65535); + QByteArray keyByteArray; + keyByteArray.append(((char*)&Key)[0]); + keyByteArray.append(((char*)&Key)[1]); + keyByteArray.append(((char*)&Key)[2]); + keyByteArray.append(((char*)&Key)[3]); + + int passwordCRC32 = this->Crc32(m_randomeKey.toUtf8().data(), m_randomeKey.size()); + keyByteArray.append(((char*)&passwordCRC32)[0]); + keyByteArray.append(((char*)&passwordCRC32)[1]); + keyByteArray.append(((char*)&passwordCRC32)[2]); + keyByteArray.append(((char*)&passwordCRC32)[3]); + + // MD5加密 + QCryptographicHash hash(QCryptographicHash::Md5); + hash.addData(keyByteArray); + // 转换为十六进制字符串 + QString md5 = hash.result().toHex(); + int offset = 0; + for (int i = 0; i < paramByteArray.length(); i++) + { + // 防止数组越界 + if (offset > md5.length() - 1) + { + offset = 0; + } + + int location = md5.mid(offset, 1).toInt(nullptr, 16) + 4; + offset++; + if (location > paramByteArray.length() - 1) + { + continue; + } + char TempA = paramByteArray[paramByteArray.size() - 1 - i]; + char TempB = paramByteArray[location]; + paramByteArray[paramByteArray.size() - 1 - i] = TempB; + paramByteArray[location] = TempA; + } + paramByteArray += ((char*)&offset)[0]; + paramByteArray += ((char*)&offset)[1]; + paramByteArray += ((char*)&Key)[0]; + paramByteArray += ((char*)&Key)[1]; + paramByteArray += ((char*)&Key)[2]; + + // XOR + for (unsigned int i = 0; i < paramByteArray.length(); i++) + { + paramByteArray[i] = paramByteArray[i] ^ ((char*)&Key)[3]; + } + paramByteArray.append(((char*)&Key)[3]); + + return paramByteArray.toHex(); + VMProtectEnd(); + +} + +QString Verify::ParamDecrypt(QString Param) +{ + VMProtectBegin("Verify_Dec"); + if (Param.isEmpty()) + { + return ""; + } + QByteArray paramByteArray = QByteArray::fromHex(Param.toUtf8()); + char xorKey = paramByteArray[paramByteArray.size() - 1]; + + QByteArray UnHashData = NULL; + for (unsigned int i = 0; i < paramByteArray.size() - 1; i++) + { + UnHashData += paramByteArray[i] ^ xorKey; + } + QByteArray md5ByteArray; + + // 根据字节数组指针计算CRC32 + int passwordCrc32 = this->Crc32(m_randomeKey.toUtf8().data(), m_randomeKey.size()); + // 参数 + CRC32 + md5ByteArray.append(UnHashData[UnHashData.size() - 3]); + md5ByteArray.append(UnHashData[UnHashData.size() - 2]); + md5ByteArray.append(UnHashData[UnHashData.size() - 1]); + //qDebug() << "RValue:" << md5ByteArray.toHex(); + md5ByteArray.append(xorKey); + md5ByteArray.append(((char*)&passwordCrc32)[0]); + md5ByteArray.append(((char*)&passwordCrc32)[1]); + md5ByteArray.append(((char*)&passwordCrc32)[2]); + md5ByteArray.append(((char*)&passwordCrc32)[3]); + + QCryptographicHash hash(QCryptographicHash::Md5); + hash.addData(md5ByteArray); + // 转换为十六进制字符串 + QString md5 = hash.result().toHex(); + short last; + ((char*)&last)[0] = UnHashData[UnHashData.length() - 5]; + ((char*)&last)[1] = UnHashData[UnHashData.length() - 4]; + + UnHashData = UnHashData.mid(0, UnHashData.length() - 5); + + int offset = 0; + int _last = last; + bool error = false; + for (int i = 0; i < UnHashData.length(); i++) + { + if (UnHashData.length() < _last - 1) + { + break; + } + if (offset > md5.size() - 1) + { + offset = 0; + } + if (last - offset - 1 < 0) + { + last = md5.size(); + offset = 0; + } + int location = md5.mid(last - offset - 1, 1).toInt(nullptr, 16) + 4; + offset = offset + 1; + if (location > UnHashData.size() - 1) + { + continue; + } + char TempA = UnHashData[i]; + char TempB = UnHashData[location]; + UnHashData[i] = TempB; + UnHashData[location] = TempA; + } + + int crc32; + ((char*)&crc32)[0] = UnHashData[UnHashData.length() - 4]; + ((char*)&crc32)[1] = UnHashData[UnHashData.length() - 3]; + ((char*)&crc32)[2] = UnHashData[UnHashData.length() - 2]; + ((char*)&crc32)[3] = UnHashData[UnHashData.length() - 1]; + UnHashData = UnHashData.mid(0, UnHashData.length() - 4); + if (crc32 != this->Crc32(UnHashData.data(), UnHashData.length())) + { + return ""; + } + + return UnHashData; + VMProtectEnd(); +} + + +QString ByteArrayToHexString(QByteArray data) { + QString ret(data.toHex().toUpper()); + int len = ret.length() / 2; + for (int i = 1; i < len; i++) + { + ret.insert(2 * i + i - 1, " "); + } + + return ret; +} + +// 发送网络请求 +bool Verify::Send(QString Option, QString Data, QString& Result, bool async) +{ + VMProtectBegin("Verify_Send"); + QNetworkAccessManager networkAccessManager; + + // 获取当前时间戳 + QDateTime timeDate = QDateTime::currentDateTime(); + QString timestamp = QString::number(timeDate.toSecsSinceEpoch()); + //qDebug() << "解密:" << ParamDecrypt(m_commKey); + // 获取签名 + + // 转为十六进制文本 + QString PostData; + PostData.append(RC4(Data.toUtf8(), ParamDecrypt(m_commKey)).toHex()); + + //qDebug() << "RC4的结果:" << PostData; + QByteArray PostByte = PostData.toUtf8(); + //qDebug() << "RC4结果:" << PostByte.toHex(); + QByteArray SignData = PostByte + timestamp.toUtf8() + ParamDecrypt(m_commKey).toUtf8(); + // 转换为十六进制字符串 + + QString md5 = this->Md5(SignData); + // a98d0872e603bc63f04767a14617df64 + //qDebug() << "md5:" << md5; + QUrl strUrl = ParamDecrypt(m_webApi) + "&mod=" + Option + "&appId=" + this->ParamDecrypt(m_appId) + "&sign=" + md5 + "×tamp=" + timestamp; + //qDebug() << "访问地址:" << strUrl; + // 网络请求 + QNetworkRequest request; + // 设置请求地址 + request.setUrl(strUrl); + // 设置请求头 + // request.setRawHeader("Content-Type", "charset='utf-8'"); + request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");// "charset='utf-8'" + //request.setRawHeader("Content-Type", "application/json"); + // 网络应答 + + QNetworkReply* reply = networkAccessManager.post(request, PostData.toUtf8()); + QByteArray responseData; + // 事件循环 + if (async) + { + + } + QEventLoop eventLoop; + // 连接信号和槽 + connect(&networkAccessManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit())); + // 开始循环 + eventLoop.exec(); + + //错误处理 + if (reply->error() != QNetworkReply::NoError) + { + qDebug() << "Request protobufHttp handle errors here"; + QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); + // statusCodeV是HTTP服务器的相应码,reply->error()是Qt定义的错误码,可以参考QT的文档 + qDebug("request protobufHttp found error ....code: %d %d\n", statusCodeV.toInt(), (int)reply->error()); + qDebug(qPrintable(reply->errorString())); + reply->deleteLater(); + return ""; + } + + //RC4(QByteArray::fromHex(数据.toUtf8()), ParamDecrypt(m_commKey)); + //QString strReply = reply->readAll(); + QString result = reply->readAll();//RC4(QByteArray::fromHex(reply->readAll()),ParamDecrypt(m_commKey)); + //qDebug() << "访问结果:" << result.toStdString().c_str(); + reply->deleteLater(); + + QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); + if (jsonDocument.isNull()) + { + //qDebug() << "String NULL";; + } + QJsonObject jsonObject = jsonDocument.object(); + QString jsonCode = jsonObject["code"].toVariant().toString();//QString::number(jsonObject["code"].toInt()); + QString jsonMsg = jsonObject["msg"].toVariant().toString(); + QString jsonData = jsonObject["data"].toVariant().toString(); + QString jsonSign = jsonObject["sign"].toVariant().toString(); + QString jsonTampstamp = jsonObject["timestamp"].toVariant().toString(); + + Result = RC4(QByteArray::fromHex(jsonData.toUtf8()), ParamDecrypt(m_commKey)); + if (!jsonSign.isEmpty()) + { + QString verifySign = this->Md5(jsonCode.toUtf8() + jsonMsg.toUtf8() + jsonData.toUtf8()); + if (verifySign != jsonSign) + { + Result = "数据校验失败"; + return false; + } + } + + if (jsonCode == "1") + { + return true; + } + Result = jsonMsg; + return false; + VMProtectEnd(); +} + + +bool Verify::Login(QString Username, QString Password, QString& result) +{ + VMProtectBegin("Verify_Login"); + QJsonObject JsonObject; + JsonObject.insert("username", Username); + JsonObject.insert("password", Password); + JsonObject.insert("hardwareCode", m_machineCode); + QJsonDocument jsonDoc = QJsonDocument(JsonObject); + QString post_data = jsonDoc.toJson(QJsonDocument::Compact); + //qDebug() << "参数:" << post_data.toStdString().c_str(); + if (!Send("login", post_data, result)) + { + //qDebug() << "登录失败:" << result.toStdString().c_str(); + //result = "登录失败"; + return false; + } + //qDebug() << "登录成功:" << result.toStdString().c_str(); + QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); + if (jsonDocument.isNull()) + { + //qDebug() << "String NULL";; + result = "登录失败"; + return false; + } + QJsonObject jsonObject = jsonDocument.object(); + QString jsonTime = jsonObject["expireTime"].toVariant().toString(); + m_dueTime = QDateTime::fromString(jsonTime, "yyyy-MM-dd hh:mm:ss"); + m_username = Username; + m_password = Password; + return true; + VMProtectEnd(); +} + +bool Verify::Heartbeat(QString& result) +{ + VMProtectBegin("Verify_Heartbeat"); + QJsonObject JsonObject; + JsonObject.insert("username", m_username); + JsonObject.insert("password", m_password); + JsonObject.insert("hardwareCode", m_machineCode); + QJsonDocument jsonDoc = QJsonDocument(JsonObject); + QString post_data = jsonDoc.toJson(QJsonDocument::Compact); + //qDebug() << "参数:" << post_data.toStdString().c_str(); + if (!Send("heartbeat", post_data, result)) + { + //qDebug() << "心跳失败:" << result.toStdString().c_str(); + return false; + } + //qDebug() << "登录成功:" << result.toStdString().c_str(); + QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); + if (jsonDocument.isNull()) + { + //qDebug() << "String NULL";; + return false; + } + QJsonObject jsonObject = jsonDocument.object(); + QString jsonTime = jsonObject["expireTime"].toVariant().toString(); + m_dueTime = QDateTime::fromString(jsonTime, "yyyy-MM-dd hh:mm:ss"); + + return true; + VMProtectEnd(); +} + +bool Verify::checkUpdate() +{ + VMProtectBegin("Verify_Check"); + QString result; + QJsonObject JsonObject; + JsonObject.insert("username", m_username); + JsonObject.insert("password", m_password); + JsonObject.insert("hardwareCode", m_machineCode); + QJsonDocument jsonDoc = QJsonDocument(JsonObject); + QString post_data = jsonDoc.toJson(QJsonDocument::Compact); + //qDebug() << "参数:" << post_data.toStdString().c_str(); + if (!Send("version", post_data, result)) + { + //qDebug() << "获取版本失败:" << result.toStdString().c_str(); + return false; + } + //qDebug() << "获取版本成功:" << result.toStdString().c_str(); + QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); + if (jsonDocument.isNull()) + { + //qDebug() << "String NULL";; + return false; + } + QJsonObject jsonObject = jsonDocument.object(); + QString version = jsonObject["version"].toVariant().toString(); + //qDebug() << "最新版本:" << version; + if (m_version == version) + { + //qDebug() << "验证结果: 真"; + } + else + { + //qDebug() << "验证结果: 假"; + } + + return version == m_version; + VMProtectEnd(); +} + +QString Verify::Username() +{ + return m_username; +} + +QDateTime Verify::GetDueTime() +{ + return m_dueTime; +} + +bool Verify::push_msg(QString type,QString app,QString account,QMap order) +{ + VMProtectBegin("Verify_Push"); + QString result; + QJsonObject JsonObject; + JsonObject.insert("username", m_username); + JsonObject.insert("password", m_password); + JsonObject.insert("account", m_machineCode); + JsonObject.insert("type", type); + JsonObject.insert("app", app); + JsonObject.insert("account", account); + + // 修复:直接将 QMap 转换为 QJsonObject + QJsonObject orderJson; + for (auto it = order.begin(); it != order.end(); ++it) { + if (it.key() == "TEAM_H") + { + //qDebug() << "队伍H:" << it.value(); + } + if (it.key() == "TEAM_C") + { + //qDebug() << "队伍C:" << it.value(); + } + orderJson.insert(it.key(), it.value()); + } + //qDebug() << orderJson; + JsonObject.insert("order", orderJson); + + QJsonDocument jsonDoc = QJsonDocument(JsonObject); + QString post_data = jsonDoc.toJson(QJsonDocument::Compact); + //qDebug() << "参数:" << post_data.toStdString().c_str(); + if (!Send("push", post_data, result)) + { + //qDebug() << "推送消息失败:" << result.toStdString().c_str(); + return false; + } + //qDebug() << "推送成功:" << result.toStdString().c_str(); + QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); + if (jsonDocument.isNull()) + { + //qDebug() << "String NULL";; + return false; + } + QJsonObject jsonObject = jsonDocument.object(); + QString version = jsonObject["version"].toVariant().toString(); + //qDebug() << "最新版本:" << version; + if (m_version == version) + { + //qDebug() << "验证结果: 真"; + } + else + { + //qDebug() << "验证结果: 假"; + } + + return false; + VMProtectEnd(); +} diff --git a/CrownServer/Verify.h b/CrownServer/Verify.h new file mode 100644 index 0000000..f5d9c05 --- /dev/null +++ b/CrownServer/Verify.h @@ -0,0 +1,70 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +class Verify :public QObject +{ + Q_OBJECT + +public: + Verify(QString Url, QString AppKey, QString CommKey, QString Verison); + ~Verify(); +private: + // 获取机器码 + QString GetCPUID(); + int GetRandom(int Min, int Max); + QString GetRandom(int Length); + unsigned int Crc32(const void* Buffer, unsigned short Length); + QString Md5(QByteArray Data); + QByteArray RC4(QByteArray Data, QString Key); +private: + QString ParamEncrypt(QString Param); + QString ParamDecrypt(QString Param); + bool Send(QString Option, QString Data, QString& Result, bool async = false); +public: + // 登录 + bool Login(QString Username, QString Password, QString& result); + // 心跳 + bool Heartbeat(QString& result); + // 检查更新 + bool checkUpdate(); + // 软件登录账号 + QString Username(); + QDateTime GetDueTime(); +public slots: + // 推送消息 + bool push_msg(QString type,QString app, QString account, QMap order); + +private: + // 随机密码字符串 非十六进制 + QString m_randomeKey; + // 应用密钥 + QString m_appId; + // 通信密钥 + QString m_commKey; + // 网络接口 + QString m_webApi; + // 机器码 + QString m_machineCode; + // 版本 + QString m_version; + // 账号 + QString m_username; + // 密码 + QString m_password; + + +private: + // 到期时间 + QDateTime m_dueTime; + +private: + + +}; \ No newline at end of file diff --git a/CrownServer/VersionUpdate.h b/CrownServer/VersionUpdate.h new file mode 100644 index 0000000..32c666b --- /dev/null +++ b/CrownServer/VersionUpdate.h @@ -0,0 +1,53 @@ +#pragma comment(lib, "version.lib") + +#include +#include +#include + +class VersionUpdate +{ +public: + static QString VersionUpdate::GetVersion() + { + int nMaxPathName = 4096; // Max length of file name/path + TCHAR* pBuffer; + UINT nItemLength; + void* pData, *lpBuffer; + QString sVersion; + DWORD dwInfoSize, dwHandle; + VS_FIXEDFILEINFO* pFileInfo; + + // Get the file path and name + pBuffer = new TCHAR[nMaxPathName]; + GetModuleFileName(NULL, pBuffer, nMaxPathName - 1); + + // Get File Version Info size + dwInfoSize = GetFileVersionInfoSize(pBuffer, &dwHandle); + if (dwInfoSize > 0) + { + pData = new TCHAR[dwInfoSize]; + if (GetFileVersionInfo(pBuffer, dwHandle, dwInfoSize, pData)) + if (VerQueryValue(pData, _T("\\"), &lpBuffer, &nItemLength)) + { + pFileInfo = (VS_FIXEDFILEINFO*)lpBuffer; + sVersion = QString("%1.%2.%3.%4") + .arg(pFileInfo->dwProductVersionMS >> 16) + .arg(pFileInfo->dwProductVersionMS & 0xFFFF) + .arg(pFileInfo->dwProductVersionLS >> 16) + .arg(pFileInfo->dwProductVersionLS & 0xFFFF); + // Calculate the product version as a number, you can delete the next statement if you don't need it. + DWORD dwProductVersion = (pFileInfo->dwProductVersionMS >> 16) * 1000 + + (pFileInfo->dwProductVersionMS & 0xFFFF) * 100 + + (pFileInfo->dwProductVersionLS >> 16) * 10 + + (pFileInfo->dwProductVersionLS & 0xFFFF) * 1; + + } + // Delete the data buffer + delete[] pData; + } + // Get rid of the allocated string buffer + delete[] pBuffer; + return sVersion; + } +private: +}; diff --git a/CrownServer/WebEnginePage.cpp b/CrownServer/WebEnginePage.cpp new file mode 100644 index 0000000..3027f46 --- /dev/null +++ b/CrownServer/WebEnginePage.cpp @@ -0,0 +1,17 @@ +#include "WebEnginePage.h" + +WebEnginePage::WebEnginePage(QObject* parent) + :QWebEnginePage(parent) +{ + +} + +bool WebEnginePage::certificateError(const QWebEngineCertificateError &certificateError) +{ + return true; +} + +void WebEnginePage::javaScriptAlert(const QUrl & securityOrigin, const QString & msg) +{ + return; +} diff --git a/CrownServer/WebEnginePage.h b/CrownServer/WebEnginePage.h new file mode 100644 index 0000000..decf12d --- /dev/null +++ b/CrownServer/WebEnginePage.h @@ -0,0 +1,30 @@ +#pragma once + +#include + +class WebEnginePage : public QWebEnginePage +{ +public: + WebEnginePage(QObject* parent = Q_NULLPTR); +protected: + virtual bool certificateError(const QWebEngineCertificateError &certificateError); + +protected: + //屏蔽alert提示 + virtual void javaScriptAlert(const QUrl &securityOrigin, const QString &msg); + //其他场景自行处理 + /*virtual bool javaScriptConfirm(const QUrl &securityOrigin, const QString &msg) + { + return false; + } + virtual void javaScriptConsoleMessage(QWebEnginePage::JavaScriptConsoleMessageLevel level, const QString &message, int lineNumber, const QString &sourceID) + { + return; + } + virtual bool javaScriptPrompt(const QUrl &securityOrigin, const QString &msg, const QString &defaultValue, QString *result) + { + return false; + }*/ + +}; + diff --git a/CrownServer/main.cpp b/CrownServer/main.cpp new file mode 100644 index 0000000..a04f476 --- /dev/null +++ b/CrownServer/main.cpp @@ -0,0 +1,90 @@ + + +#include + +#include +#include +#include "Login.h" +#include "Global.h" +#include + +#include +#include + +#pragma comment(lib,"D:\\reverse\\vmprotect33\\Lib\\Windows\\VMProtectSDK64.lib") +#include "AppInstanceManager.h" + + +#include "Utils.h" +#include "StyleLoader.h" +#include "MessageHandle.h" +int main(int argc, char* argv[]) +{ + // 禁用GPU加速(如果黑屏) + qputenv("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu"); + // 启用软件渲染 + qputenv("QT_QUICK_BACKEND", "software"); + qputenv("QT_XCB_FORCE_SOFTWARE_OPENGL", "1"); + + + // 检测SSL兼容 + if (!QSslSocket::supportsSsl()) + { + QMessageBox::warning(nullptr,"警告","OpenSSL组件异常"); + return 0; + } + + // DPI兼容 + if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) + { + QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); + } + + // 设置全局字体 + QApplication a(argc, argv); + + if (AppInstanceManager::isAlreadyRunning()) { + return 0; // 直接退出新实例 + } + + qInstallMessageHandler(message_handle); + + qDebug() << "test log"; + // 加载QSS样式 + QString style = StyleLoader::loadStyleFromResource(); + if (!style.isEmpty()) { + a.setStyleSheet(style); + } + + + // 设置调试端口临时环境变量 + qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "7777"); + + // 强制指定语言为简体中文 + // qputenv("LANG", "zh_CN.UTF-8"); + + //QFont font("黑体",10); + //a.setFont(font); + + // 初始化配置 + g_config = new Config(); + // 初始化验证 + g_verify = new Verify("https://gendan.xyz", "72", "NAO87ZGQXTXR1HLFHGL3NSLXD", VERSION); + + + // 检测版本更新 + if (g_verify->checkUpdate()) + { + Login w; + w.show(); + + return a.exec(); + } + else + { + QProcess::execute(QCoreApplication::applicationDirPath() + "/Update.exe"); + QApplication::quit(); + } + + return 0; +} diff --git a/CrownServer/resource.h b/CrownServer/resource.h new file mode 100644 index 0000000..01e0a5f --- /dev/null +++ b/CrownServer/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ Éú³ɵİüº¬Îļþ¡£ +// ¹© CrownServer.rc ʹÓà +// +#define IDI_ICON1 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/CrownServer/sound/exit.mp3 b/CrownServer/sound/exit.mp3 new file mode 100644 index 0000000..1a120d5 Binary files /dev/null and b/CrownServer/sound/exit.mp3 differ diff --git a/CrownServer/sound/exit.wav b/CrownServer/sound/exit.wav new file mode 100644 index 0000000..4293339 Binary files /dev/null and b/CrownServer/sound/exit.wav differ diff --git a/CrownServer/sound/pushFailed.mp3 b/CrownServer/sound/pushFailed.mp3 new file mode 100644 index 0000000..e2ac75a Binary files /dev/null and b/CrownServer/sound/pushFailed.mp3 differ diff --git a/CrownServer/sound/pushFailed.wav b/CrownServer/sound/pushFailed.wav new file mode 100644 index 0000000..d8cc1e0 Binary files /dev/null and b/CrownServer/sound/pushFailed.wav differ diff --git a/CrownServer/sound/readOrder.mp3 b/CrownServer/sound/readOrder.mp3 new file mode 100644 index 0000000..d9c0113 Binary files /dev/null and b/CrownServer/sound/readOrder.mp3 differ diff --git a/CrownServer/sound/readOrder.wav b/CrownServer/sound/readOrder.wav new file mode 100644 index 0000000..51c8d8f Binary files /dev/null and b/CrownServer/sound/readOrder.wav differ diff --git a/CrownServer/sound/relogin.mp3 b/CrownServer/sound/relogin.mp3 new file mode 100644 index 0000000..c0c8834 Binary files /dev/null and b/CrownServer/sound/relogin.mp3 differ diff --git a/CrownServer/sound/relogin.wav b/CrownServer/sound/relogin.wav new file mode 100644 index 0000000..3965462 Binary files /dev/null and b/CrownServer/sound/relogin.wav differ diff --git a/CrownServer/sound/update.mp3 b/CrownServer/sound/update.mp3 new file mode 100644 index 0000000..9c9d050 Binary files /dev/null and b/CrownServer/sound/update.mp3 differ diff --git a/CrownServer/sound/update.wav b/CrownServer/sound/update.wav new file mode 100644 index 0000000..1db16fb Binary files /dev/null and b/CrownServer/sound/update.wav differ diff --git a/CrownServer/sound/手动跟单.mp3 b/CrownServer/sound/手动跟单.mp3 new file mode 100644 index 0000000..28fa985 Binary files /dev/null and b/CrownServer/sound/手动跟单.mp3 differ diff --git a/CrownServer/sound/手动跟单.wav b/CrownServer/sound/手动跟单.wav new file mode 100644 index 0000000..ffef8fe Binary files /dev/null and b/CrownServer/sound/手动跟单.wav differ diff --git a/CrownServer/sound/接收注单.mp3 b/CrownServer/sound/接收注单.mp3 new file mode 100644 index 0000000..8064dd3 Binary files /dev/null and b/CrownServer/sound/接收注单.mp3 differ diff --git a/CrownServer/sound/接收注单.wav b/CrownServer/sound/接收注单.wav new file mode 100644 index 0000000..f583ffe Binary files /dev/null and b/CrownServer/sound/接收注单.wav differ diff --git a/CrownServer/sound/跟单失败.mp3 b/CrownServer/sound/跟单失败.mp3 new file mode 100644 index 0000000..78ca739 Binary files /dev/null and b/CrownServer/sound/跟单失败.mp3 differ diff --git a/CrownServer/sound/跟单失败.wav b/CrownServer/sound/跟单失败.wav new file mode 100644 index 0000000..88b12f2 Binary files /dev/null and b/CrownServer/sound/跟单失败.wav differ diff --git a/CrownServer/sound/跟单成功.mp3 b/CrownServer/sound/跟单成功.mp3 new file mode 100644 index 0000000..5d9e4d5 Binary files /dev/null and b/CrownServer/sound/跟单成功.mp3 differ diff --git a/CrownServer/sound/跟单成功.wav b/CrownServer/sound/跟单成功.wav new file mode 100644 index 0000000..f5f16ca Binary files /dev/null and b/CrownServer/sound/跟单成功.wav differ diff --git a/CrownServer/sound/过滤注单.mp3 b/CrownServer/sound/过滤注单.mp3 new file mode 100644 index 0000000..d94617a Binary files /dev/null and b/CrownServer/sound/过滤注单.mp3 differ diff --git a/CrownServer/sound/过滤注单.wav b/CrownServer/sound/过滤注单.wav new file mode 100644 index 0000000..7238117 Binary files /dev/null and b/CrownServer/sound/过滤注单.wav differ diff --git a/CrownServer/sound/连接断开.mp3 b/CrownServer/sound/连接断开.mp3 new file mode 100644 index 0000000..c68c3b0 Binary files /dev/null and b/CrownServer/sound/连接断开.mp3 differ diff --git a/CrownServer/sound/连接断开.wav b/CrownServer/sound/连接断开.wav new file mode 100644 index 0000000..33028f5 Binary files /dev/null and b/CrownServer/sound/连接断开.wav differ diff --git a/Update/FileInfo.cpp b/Update/FileInfo.cpp new file mode 100644 index 0000000..575a914 --- /dev/null +++ b/Update/FileInfo.cpp @@ -0,0 +1,71 @@ +#include "FileInfo.h" + + +bool FileInfo::QueryValue(const std::wstring wsValueName, const std::wstring wsModuleName, std::wstring &wsRetStr) +{ + bool bSuccess = FALSE; + BYTE *lpVersionData = NULL; + DWORD dwLangCharset = 0; + TCHAR *pStr = NULL; + + do + { + if (wsValueName.empty() || wsModuleName.empty()) + break; + + DWORD dwHandle; + // 判断系统能否检索到指定文件的版本信息 + DWORD dwDataSize = ::GetFileVersionInfoSize((LPCWSTR)wsModuleName.c_str(), &dwHandle); + if (dwDataSize == 0) + break; + + lpVersionData = new (std::nothrow) BYTE[dwDataSize];// 分配缓冲区 + if (NULL == lpVersionData) + break; + + // 检索信息 + if (!::GetFileVersionInfo((LPCWSTR)wsModuleName.c_str(), dwHandle, dwDataSize, (void*)lpVersionData)) + break; + + UINT nQuerySize; + DWORD *pTransTable; + // 设置语言 + if (!::VerQueryValue(lpVersionData, L"\\VarFileInfo\\Translation", (void **)&pTransTable, &nQuerySize)) + break; + + dwLangCharset = MAKELONG(HIWORD(pTransTable[0]), LOWORD(pTransTable[0])); + if (lpVersionData == NULL) + break; + + pStr = new (std::nothrow) TCHAR[128];// 分配缓冲区 + if (NULL == pStr) + break; + + //wchar_t str2[MAX_PATH]; + //wcscpy_s(str2, MAX_PATH, wsValueName.c_str()); + swprintf_s(pStr, 128, L"\\StringFileInfo\\%08lx\\%s", dwLangCharset, wsValueName.c_str()); + + LPVOID lpData; + + // 调用此函数查询前需要先依次调用函数GetFileVersionInfoSize和GetFileVersionInfo + if (::VerQueryValue((void *)lpVersionData, pStr, &lpData, &nQuerySize)) + wsRetStr = (TCHAR *)lpData; + + bSuccess = TRUE; + + } while (FALSE); + + // 销毁缓冲区 + if (lpVersionData) + { + delete[] lpVersionData; + lpVersionData = NULL; + } + if (pStr) + { + delete[] pStr; + pStr = NULL; + } + + return bSuccess; +} diff --git a/Update/FileInfo.h b/Update/FileInfo.h new file mode 100644 index 0000000..3e9d8ad --- /dev/null +++ b/Update/FileInfo.h @@ -0,0 +1,21 @@ +#pragma once +#include +#include + +#pragma comment(lib,"Version.lib") + +class FileInfo +{ +public: + static bool GetFileDescription(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"FileDescription", szModuleName, RetStr); } + static bool GetFileVersion(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"FileVersion", szModuleName, RetStr); } + static bool GetInternalName(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"InternalName", szModuleName, RetStr); } + static bool GetCompanyName(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"CompanyName", szModuleName, RetStr); } + static bool GetLegalCopyright(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"LegalCopyright", szModuleName, RetStr); } + static bool GetOriginalFilename(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"OriginalFilename", szModuleName, RetStr); } + static bool GetProductName(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"ProductName", szModuleName, RetStr); } + static bool GetProductVersion(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"ProductVersion", szModuleName, RetStr); } + +private: + static bool QueryValue(const std::wstring wsValueName, const std::wstring wsModuleName, std::wstring &wsRetStr); +}; diff --git a/Update/Miniz.h b/Update/Miniz.h new file mode 100644 index 0000000..83b1002 --- /dev/null +++ b/Update/Miniz.h @@ -0,0 +1,10148 @@ +#pragma once +/* miniz.c 2.2.0 - public domain deflate/inflate, zlib-subset, ZIP + reading/writing/appending, PNG writing See "unlicense" statement at the end + of this file. Rich Geldreich , last updated Oct. 13, + 2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: + http://www.ietf.org/rfc/rfc1951.txt + + Most API's defined in miniz.c are optional. For example, to disable the + archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of + all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). + + * Low-level Deflate/Inflate implementation notes: + + Compression: Use the "tdefl" API's. The compressor supports raw, static, + and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only, + and Huffman-only streams. It performs and compresses approximately as well as + zlib. + + Decompression: Use the "tinfl" API's. The entire decompressor is + implemented as a single function coroutine: see tinfl_decompress(). It + supports decompression into a 32KB (or larger power of 2) wrapping buffer, or + into a memory block large enough to hold the entire file. + + The low-level tdefl/tinfl API's do not make any use of dynamic memory + allocation. + + * zlib-style API notes: + + miniz.c implements a fairly large subset of zlib. There's enough + functionality present for it to be a drop-in zlib replacement in many apps: + The z_stream struct, optional memory allocation callbacks + deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound + inflateInit/inflateInit2/inflate/inflateReset/inflateEnd + compress, compress2, compressBound, uncompress + CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly + routines. Supports raw deflate streams or standard zlib streams with adler-32 + checking. + + Limitations: + The callback API's are not implemented yet. No support for gzip headers or + zlib static dictionaries. I've tried to closely emulate zlib's various + flavors of stream flushing and return status codes, but there are no + guarantees that miniz.c pulls this off perfectly. + + * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, + originally written by Alex Evans. Supports 1-4 bytes/pixel images. + + * ZIP archive API notes: + + The ZIP archive API's where designed with simplicity and efficiency in + mind, with just enough abstraction to get the job done with minimal fuss. + There are simple API's to retrieve file information, read files from existing + archives, create new archives, append new files to existing archives, or + clone archive data from one archive to another. It supports archives located + in memory or the heap, on disk (using stdio.h), or you can specify custom + file read/write callbacks. + + - Archive reading: Just call this function to read a single file from a + disk archive: + + void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const + char *pArchive_name, size_t *pSize, mz_uint zip_flags); + + For more complex cases, use the "mz_zip_reader" functions. Upon opening an + archive, the entire central directory is located and read as-is into memory, + and subsequent file access only occurs when reading individual files. + + - Archives file scanning: The simple way is to use this function to scan a + loaded archive for a specific file: + + int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, + const char *pComment, mz_uint flags); + + The locate operation can optionally check file comments too, which (as one + example) can be used to identify multiple versions of the same file in an + archive. This function uses a simple linear search through the central + directory, so it's not very fast. + + Alternately, you can iterate through all the files in an archive (using + mz_zip_reader_get_num_files()) and retrieve detailed info on each file by + calling mz_zip_reader_file_stat(). + + - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer + immediately writes compressed file data to disk and builds an exact image of + the central directory in memory. The central directory image is written all + at once at the end of the archive file when the archive is finalized. + + The archive writer can optionally align each file's local header and file + data to any power of 2 alignment, which can be useful when the archive will + be read from optical media. Also, the writer supports placing arbitrary data + blobs at the very beginning of ZIP archives. Archives written using either + feature are still readable by any ZIP tool. + + - Archive appending: The simple way to add a single file to an archive is + to call this function: + + mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, + const char *pArchive_name, const void *pBuf, size_t buf_size, const void + *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + + The archive will be created if it doesn't already exist, otherwise it'll be + appended to. Note the appending is done in-place and is not an atomic + operation, so if something goes wrong during the operation it's possible the + archive could be left without a central directory (although the local file + headers and file data will be fine, so the archive will be recoverable). + + For more complex archive modification scenarios: + 1. The safest way is to use a mz_zip_reader to read the existing archive, + cloning only those bits you want to preserve into a new archive using using + the mz_zip_writer_add_from_zip_reader() function (which compiles the + compressed file data as-is). When you're done, delete the old archive and + rename the newly written archive, and you're done. This is safe but requires + a bunch of temporary disk space or heap memory. + + 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using + mz_zip_writer_init_from_reader(), append new files as needed, then finalize + the archive which will write an updated central directory to the original + archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() + does.) There's a possibility that the archive's central directory could be + lost with this method if anything goes wrong, though. + + - ZIP archive support limitations: + No spanning support. Extraction functions can only handle unencrypted, + stored or deflated files. Requires streams capable of seeking. + + * This is a header file library, like stb_image.c. To get only a header file, + either cut and paste the below header, or create miniz.h, #define + MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. + + * Important: For best perf. be sure to customize the below macros for your + target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define + MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1 + + * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before + including miniz.c to ensure miniz uses the 64-bit variants: fopen64(), + stat64(), etc. Otherwise you won't be able to process large files (i.e. + 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). +*/ +/* Defines to completely disable specific portions of miniz.c: + If all macros here are defined the only functionality remaining will be + CRC-32, adler-32, tinfl, and tdefl. */ + + /* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on + * stdio for file I/O. */ + /*#define MINIZ_NO_STDIO */ + + /* If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able + * to get the current time, or */ + /* get/set file times, and the C run-time funcs that get/set times won't be + * called. */ + /* The current downside is the times written to your archives will be from 1979. + */ + /*#define MINIZ_NO_TIME */ + + /* Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. */ + /*#define MINIZ_NO_ARCHIVE_APIS */ + + /* Define MINIZ_NO_ARCHIVE_WRITING_APIS to disable all writing related ZIP + * archive API's. */ + /*#define MINIZ_NO_ARCHIVE_WRITING_APIS */ + + /* Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression + * API's. */ + /*#define MINIZ_NO_ZLIB_APIS */ + + /* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent + * conflicts against stock zlib. */ + /*#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ + + /* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. + Note if MINIZ_NO_MALLOC is defined then the user must always provide custom + user alloc/free/realloc callbacks to the zlib and archive API's, and a few + stand-alone helper API's which don't provide custom user functions (such as + tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. + */ + /*#define MINIZ_NO_MALLOC */ + +#if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) +/* TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc + * on Linux */ +#define MINIZ_NO_TIME +#endif + +#include + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) +#include +#endif + +#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \ + defined(__i386) || defined(__i486__) || defined(__i486) || \ + defined(i386) || defined(__ia64__) || defined(__x86_64__) + /* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */ +#define MINIZ_X86_OR_X64_CPU 1 +#else +#define MINIZ_X86_OR_X64_CPU 0 +#endif + +#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU + /* Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. */ +#define MINIZ_LITTLE_ENDIAN 1 +#else +#define MINIZ_LITTLE_ENDIAN 0 +#endif + + /* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES only if not set */ +#if !defined(MINIZ_USE_UNALIGNED_LOADS_AND_STORES) +#if MINIZ_X86_OR_X64_CPU +/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient + * integer loads and stores from unaligned addresses. */ +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 +#define MINIZ_UNALIGNED_USE_MEMCPY +#else +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 +#endif +#endif + +#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \ + defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \ + defined(__x86_64__) +/* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are + * reasonably fast (and don't involve compiler generated calls to helper + * functions). */ +#define MINIZ_HAS_64BIT_REGISTERS 1 +#else +#define MINIZ_HAS_64BIT_REGISTERS 0 +#endif + + + +/* ------------------- zlib-style API Definitions. */ + +/* For more compatibility with zlib, miniz.c uses unsigned long for some + * parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! */ +typedef unsigned long mz_ulong; + +/* mz_free() internally uses the MZ_FREE() macro (which by default calls free() + * unless you've modified the MZ_MALLOC macro) to release a block allocated from + * the heap. */ +void mz_free(void* p); + +#define MZ_ADLER32_INIT (1) +/* mz_adler32() returns the initial adler-32 value to use when called with + * ptr==NULL. */ +mz_ulong mz_adler32(mz_ulong adler, const unsigned char* ptr, + size_t buf_len); + +#define MZ_CRC32_INIT (0) +/* mz_crc32() returns the initial CRC-32 value to use when called with + * ptr==NULL. */ +mz_ulong mz_crc32(mz_ulong crc, const unsigned char* ptr, + size_t buf_len); + +/* Compression strategies. */ +enum { + MZ_DEFAULT_STRATEGY = 0, + MZ_FILTERED = 1, + MZ_HUFFMAN_ONLY = 2, + MZ_RLE = 3, + MZ_FIXED = 4 +}; + +/* Method */ +#define MZ_DEFLATED 8 + +/* Heap allocation callbacks. +Note that mz_alloc_func parameter types purposely differ from zlib's: items/size +is size_t, not unsigned long. */ +typedef void* (*mz_alloc_func)(void* opaque, size_t items, size_t size); +typedef void (*mz_free_func)(void* opaque, void* address); +typedef void* (*mz_realloc_func)(void* opaque, void* address, size_t items, + size_t size); + +/* Compression levels: 0-9 are the standard zlib-style levels, 10 is best + * possible compression (not zlib compatible, and may be very slow), + * MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. */ +enum { + MZ_NO_COMPRESSION = 0, + MZ_BEST_SPEED = 1, + MZ_BEST_COMPRESSION = 9, + MZ_UBER_COMPRESSION = 10, + MZ_DEFAULT_LEVEL = 6, + MZ_DEFAULT_COMPRESSION = -1 +}; + +#define MZ_VERSION "10.2.0" +#define MZ_VERNUM 0xA100 +#define MZ_VER_MAJOR 10 +#define MZ_VER_MINOR 2 +#define MZ_VER_REVISION 0 +#define MZ_VER_SUBREVISION 0 + +#ifndef MINIZ_NO_ZLIB_APIS + +/* Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The + * other values are for advanced use (refer to the zlib docs). */ +enum { + MZ_NO_FLUSH = 0, + MZ_PARTIAL_FLUSH = 1, + MZ_SYNC_FLUSH = 2, + MZ_FULL_FLUSH = 3, + MZ_FINISH = 4, + MZ_BLOCK = 5 +}; + +/* Return status codes. MZ_PARAM_ERROR is non-standard. */ +enum { + MZ_OK = 0, + MZ_STREAM_END = 1, + MZ_NEED_DICT = 2, + MZ_ERRNO = -1, + MZ_STREAM_ERROR = -2, + MZ_DATA_ERROR = -3, + MZ_MEM_ERROR = -4, + MZ_BUF_ERROR = -5, + MZ_VERSION_ERROR = -6, + MZ_PARAM_ERROR = -10000 +}; + +/* Window bits */ +#define MZ_DEFAULT_WINDOW_BITS 15 + +struct mz_internal_state; + +/* Compression/decompression stream struct. */ +typedef struct mz_stream_s { + const unsigned char* next_in; /* pointer to next byte to read */ + unsigned int avail_in; /* number of bytes available at next_in */ + mz_ulong total_in; /* total number of bytes consumed so far */ + + unsigned char* next_out; /* pointer to next byte to write */ + unsigned int avail_out; /* number of bytes that can be written to next_out */ + mz_ulong total_out; /* total number of bytes produced so far */ + + char* msg; /* error msg (unused) */ + struct mz_internal_state + * state; /* internal state, allocated by zalloc/zfree */ + + mz_alloc_func + zalloc; /* optional heap allocation function (defaults to malloc) */ + mz_free_func zfree; /* optional heap free function (defaults to free) */ + void* opaque; /* heap alloc function user pointer */ + + int data_type; /* data_type (unused) */ + mz_ulong adler; /* adler32 of the source or uncompressed data */ + mz_ulong reserved; /* not used */ +} mz_stream; + +typedef mz_stream* mz_streamp; + +/* Returns the version string of miniz.c. */ +const char* mz_version(void); + +/* mz_deflateInit() initializes a compressor with default options: */ +/* Parameters: */ +/* pStream must point to an initialized mz_stream struct. */ +/* level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. */ +/* level 1 enables a specially optimized compression function that's been + * optimized purely for performance, not ratio. */ + /* (This special func. is currently only enabled when + * MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) */ + /* Return values: */ + /* MZ_OK on success. */ + /* MZ_STREAM_ERROR if the stream is bogus. */ + /* MZ_PARAM_ERROR if the input parameters are bogus. */ + /* MZ_MEM_ERROR on out of memory. */ +int mz_deflateInit(mz_streamp pStream, int level); + +/* mz_deflateInit2() is like mz_deflate(), except with more control: */ +/* Additional parameters: */ +/* method must be MZ_DEFLATED */ +/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with + * zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no + * header or footer) */ + /* mem_level must be between [1, 9] (it's checked but ignored by miniz.c) */ +int mz_deflateInit2(mz_streamp pStream, int level, int method, + int window_bits, int mem_level, int strategy); + +/* Quickly resets a compressor without having to reallocate anything. Same as + * calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). */ +int mz_deflateReset(mz_streamp pStream); + +/* mz_deflate() compresses the input to output, consuming as much of the input + * and producing as much output as possible. */ + /* Parameters: */ + /* pStream is the stream to read from and write to. You must initialize/update + * the next_in, avail_in, next_out, and avail_out members. */ + /* flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or + * MZ_FINISH. */ + /* Return values: */ + /* MZ_OK on success (when flushing, or if more input is needed but not + * available, and/or there's more output to be written but the output buffer is + * full). */ + /* MZ_STREAM_END if all input has been consumed and all output bytes have been + * written. Don't call mz_deflate() on the stream anymore. */ + /* MZ_STREAM_ERROR if the stream is bogus. */ + /* MZ_PARAM_ERROR if one of the parameters is invalid. */ + /* MZ_BUF_ERROR if no forward progress is possible because the input and/or + * output buffers are empty. (Fill up the input buffer or free up some output + * space and try again.) */ +int mz_deflate(mz_streamp pStream, int flush); + +/* mz_deflateEnd() deinitializes a compressor: */ +/* Return values: */ +/* MZ_OK on success. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +int mz_deflateEnd(mz_streamp pStream); + +/* mz_deflateBound() returns a (very) conservative upper bound on the amount of + * data that could be generated by deflate(), assuming flush is set to only + * MZ_NO_FLUSH or MZ_FINISH. */ +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); + +/* Single-call compression functions mz_compress() and mz_compress2(): */ +/* Returns MZ_OK on success, or one of the error codes from mz_deflate() on + * failure. */ +int mz_compress(unsigned char* pDest, mz_ulong* pDest_len, + const unsigned char* pSource, mz_ulong source_len); +int mz_compress2(unsigned char* pDest, mz_ulong* pDest_len, + const unsigned char* pSource, mz_ulong source_len, + int level); + +/* mz_compressBound() returns a (very) conservative upper bound on the amount of + * data that could be generated by calling mz_compress(). */ +mz_ulong mz_compressBound(mz_ulong source_len); + +/* Initializes a decompressor. */ +int mz_inflateInit(mz_streamp pStream); + +/* mz_inflateInit2() is like mz_inflateInit() with an additional option that + * controls the window size and whether or not the stream has been wrapped with + * a zlib header/footer: */ + /* window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or + * -MZ_DEFAULT_WINDOW_BITS (raw deflate). */ +int mz_inflateInit2(mz_streamp pStream, int window_bits); + +/* Quickly resets a compressor without having to reallocate anything. Same as + * calling mz_inflateEnd() followed by mz_inflateInit()/mz_inflateInit2(). */ +int mz_inflateReset(mz_streamp pStream); + +/* Decompresses the input stream to the output, consuming only as much of the + * input as needed, and writing as much to the output as possible. */ + /* Parameters: */ + /* pStream is the stream to read from and write to. You must initialize/update + * the next_in, avail_in, next_out, and avail_out members. */ + /* flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. */ + /* On the first call, if flush is MZ_FINISH it's assumed the input and output + * buffers are both sized large enough to decompress the entire stream in a + * single call (this is slightly faster). */ + /* MZ_FINISH implies that there are no more source bytes available beside + * what's already in the input buffer, and that the output buffer is large + * enough to hold the rest of the decompressed data. */ + /* Return values: */ + /* MZ_OK on success. Either more input is needed but not available, and/or + * there's more output to be written but the output buffer is full. */ + /* MZ_STREAM_END if all needed input has been consumed and all output bytes + * have been written. For zlib streams, the adler-32 of the decompressed data + * has also been verified. */ + /* MZ_STREAM_ERROR if the stream is bogus. */ + /* MZ_DATA_ERROR if the deflate stream is invalid. */ + /* MZ_PARAM_ERROR if one of the parameters is invalid. */ + /* MZ_BUF_ERROR if no forward progress is possible because the input buffer is + * empty but the inflater needs more input to continue, or if the output buffer + * is not large enough. Call mz_inflate() again */ + /* with more input data, or with more room in the output buffer (except when + * using single call decompression, described above). */ +int mz_inflate(mz_streamp pStream, int flush); + +/* Deinitializes a decompressor. */ +int mz_inflateEnd(mz_streamp pStream); + +/* Single-call decompression. */ +/* Returns MZ_OK on success, or one of the error codes from mz_inflate() on + * failure. */ +int mz_uncompress(unsigned char* pDest, mz_ulong* pDest_len, + const unsigned char* pSource, + mz_ulong source_len); +int mz_uncompress2(unsigned char* pDest, mz_ulong* pDest_len, + const unsigned char* pSource, + mz_ulong* pSource_len); + +/* Returns a string description of the specified error code, or NULL if the + * error code is invalid. */ +const char* mz_error(int err); + +/* Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used + * as a drop-in replacement for the subset of zlib that miniz.c supports. */ + /* Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you + * use zlib in the same project. */ +#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES +typedef unsigned char Byte; +typedef unsigned int uInt; +typedef mz_ulong uLong; +typedef Byte Bytef; +typedef uInt uIntf; +typedef char charf; +typedef int intf; +typedef void* voidpf; +typedef uLong uLongf; +typedef void* voidp; +typedef void* const voidpc; +#define Z_NULL 0 +#define Z_NO_FLUSH MZ_NO_FLUSH +#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH +#define Z_SYNC_FLUSH MZ_SYNC_FLUSH +#define Z_FULL_FLUSH MZ_FULL_FLUSH +#define Z_FINISH MZ_FINISH +#define Z_BLOCK MZ_BLOCK +#define Z_OK MZ_OK +#define Z_STREAM_END MZ_STREAM_END +#define Z_NEED_DICT MZ_NEED_DICT +#define Z_ERRNO MZ_ERRNO +#define Z_STREAM_ERROR MZ_STREAM_ERROR +#define Z_DATA_ERROR MZ_DATA_ERROR +#define Z_MEM_ERROR MZ_MEM_ERROR +#define Z_BUF_ERROR MZ_BUF_ERROR +#define Z_VERSION_ERROR MZ_VERSION_ERROR +#define Z_PARAM_ERROR MZ_PARAM_ERROR +#define Z_NO_COMPRESSION MZ_NO_COMPRESSION +#define Z_BEST_SPEED MZ_BEST_SPEED +#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION +#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION +#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY +#define Z_FILTERED MZ_FILTERED +#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY +#define Z_RLE MZ_RLE +#define Z_FIXED MZ_FIXED +#define Z_DEFLATED MZ_DEFLATED +#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS +#define alloc_func mz_alloc_func +#define free_func mz_free_func +#define internal_state mz_internal_state +#define z_stream mz_stream +#define deflateInit mz_deflateInit +#define deflateInit2 mz_deflateInit2 +#define deflateReset mz_deflateReset +#define deflate mz_deflate +#define deflateEnd mz_deflateEnd +#define deflateBound mz_deflateBound +#define compress mz_compress +#define compress2 mz_compress2 +#define compressBound mz_compressBound +#define inflateInit mz_inflateInit +#define inflateInit2 mz_inflateInit2 +#define inflateReset mz_inflateReset +#define inflate mz_inflate +#define inflateEnd mz_inflateEnd +#define uncompress mz_uncompress +#define uncompress2 mz_uncompress2 +#define crc32 mz_crc32 +#define adler32 mz_adler32 +#define MAX_WBITS 15 +#define MAX_MEM_LEVEL 9 +#define zError mz_error +#define ZLIB_VERSION MZ_VERSION +#define ZLIB_VERNUM MZ_VERNUM +#define ZLIB_VER_MAJOR MZ_VER_MAJOR +#define ZLIB_VER_MINOR MZ_VER_MINOR +#define ZLIB_VER_REVISION MZ_VER_REVISION +#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION +#define zlibVersion mz_version +#define zlib_version mz_version() +#endif /* #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ + +#endif /* MINIZ_NO_ZLIB_APIS */ + + +#pragma once +#include +#include +#include +#include + +/* ------------------- Types and macros */ +typedef unsigned char mz_uint8; +typedef signed short mz_int16; +typedef unsigned short mz_uint16; +typedef unsigned int mz_uint32; +typedef unsigned int mz_uint; +typedef int64_t mz_int64; +typedef uint64_t mz_uint64; +typedef int mz_bool; + +#define MZ_FALSE 0 +#define MZ_TRUE 1 + +/* Works around MSVC's spammy "warning C4127: conditional expression is + * constant" message. */ +#ifdef _MSC_VER +#define MZ_MACRO_END while (0, 0) +#else +#define MZ_MACRO_END while (0) +#endif + +#ifdef MINIZ_NO_STDIO +#define MZ_FILE void * +#else +#include +#define MZ_FILE FILE +#endif /* #ifdef MINIZ_NO_STDIO */ + +#ifdef MINIZ_NO_TIME +typedef struct mz_dummy_time_t_tag { + int m_dummy; +} mz_dummy_time_t; +#define MZ_TIME_T mz_dummy_time_t +#else +#define MZ_TIME_T time_t +#endif + +#define MZ_ASSERT(x) assert(x) + +#ifdef MINIZ_NO_MALLOC +#define MZ_MALLOC(x) NULL +#define MZ_FREE(x) (void)x, ((void)0) +#define MZ_REALLOC(p, x) NULL +#else +#define MZ_MALLOC(x) malloc(x) +#define MZ_FREE(x) free(x) +#define MZ_REALLOC(p, x) realloc(p, x) +#endif + +#define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) +#define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) +#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN +#define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) +#define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) +#else +#define MZ_READ_LE16(p) \ + ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ + ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) +#define MZ_READ_LE32(p) \ + ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ + ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \ + ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \ + ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) +#endif + +#define MZ_READ_LE64(p) \ + (((mz_uint64)MZ_READ_LE32(p)) | \ + (((mz_uint64)MZ_READ_LE32((const mz_uint8 *)(p) + sizeof(mz_uint32))) \ + << 32U)) + +#ifdef _MSC_VER +#define MZ_FORCEINLINE __forceinline +#elif defined(__GNUC__) +#define MZ_FORCEINLINE __inline__ __attribute__((__always_inline__)) +#else +#define MZ_FORCEINLINE inline +#endif + + + +extern void* miniz_def_alloc_func(void* opaque, size_t items, + size_t size); +extern void miniz_def_free_func(void* opaque, void* address); +extern void* miniz_def_realloc_func(void* opaque, void* address, + size_t items, size_t size); + +#define MZ_UINT16_MAX (0xFFFFU) +#define MZ_UINT32_MAX (0xFFFFFFFFU) + +#pragma once + + +/* ------------------- Low-level Compression API Definitions */ + +/* Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly + * slower, and raw/dynamic blocks will be output more frequently). */ +#define TDEFL_LESS_MEMORY 0 + + /* tdefl_init() compression flags logically OR'd together (low 12 bits contain + * the max. number of probes per dictionary search): */ + /* TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes + * per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap + * compression), 4095=Huffman+LZ (slowest/best compression). */ +enum { + TDEFL_HUFFMAN_ONLY = 0, + TDEFL_DEFAULT_MAX_PROBES = 128, + TDEFL_MAX_PROBES_MASK = 0xFFF +}; + +/* TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before + * the deflate data, and the Adler-32 of the source data at the end. Otherwise, + * you'll get raw deflate data. */ + /* TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even + * when not writing zlib headers). */ + /* TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more + * efficient lazy parsing. */ + /* TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's + * initialization time to the minimum, but the output may vary from run to run + * given the same input (depending on the contents of memory). */ + /* TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) + */ + /* TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. */ + /* TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. */ + /* TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. */ + /* The low 12 bits are reserved to control the max # of hash probes per + * dictionary lookup (see TDEFL_MAX_PROBES_MASK). */ +enum { + TDEFL_WRITE_ZLIB_HEADER = 0x01000, + TDEFL_COMPUTE_ADLER32 = 0x02000, + TDEFL_GREEDY_PARSING_FLAG = 0x04000, + TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, + TDEFL_RLE_MATCHES = 0x10000, + TDEFL_FILTER_MATCHES = 0x20000, + TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, + TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 +}; + +/* High level compression functions: */ +/* tdefl_compress_mem_to_heap() compresses a block in memory to a heap block + * allocated via malloc(). */ + /* On entry: */ + /* pSrc_buf, src_buf_len: Pointer and size of source block to compress. */ + /* flags: The max match finder probes (default is 128) logically OR'd against + * the above flags. Higher probes are slower but improve compression. */ + /* On return: */ + /* Function returns a pointer to the compressed data, or NULL on failure. */ + /* *pOut_len will be set to the compressed data's size, which could be larger + * than src_buf_len on uncompressible data. */ + /* The caller must free() the returned block when it's no longer needed. */ +void* tdefl_compress_mem_to_heap(const void* pSrc_buf, + size_t src_buf_len, + size_t* pOut_len, int flags); + +/* tdefl_compress_mem_to_mem() compresses a block in memory to another block in + * memory. */ + /* Returns 0 on failure. */ +size_t tdefl_compress_mem_to_mem(void* pOut_buf, + size_t out_buf_len, + const void* pSrc_buf, + size_t src_buf_len, int flags); + +/* Compresses an image to a compressed PNG file in memory. */ +/* On entry: */ +/* pImage, w, h, and num_chans describe the image to compress. num_chans may be + * 1, 2, 3, or 4. */ + /* The image pitch in bytes per scanline will be w*num_chans. The leftmost + * pixel on the top scanline is stored first in memory. */ + /* level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, + * MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL */ + /* If flip is true, the image will be flipped on the Y axis (useful for OpenGL + * apps). */ + /* On return: */ + /* Function returns a pointer to the compressed data, or NULL on failure. */ + /* *pLen_out will be set to the size of the PNG image file. */ + /* The caller must mz_free() the returned heap block (which will typically be + * larger than *pLen_out) when it's no longer needed. */ +void* +tdefl_write_image_to_png_file_in_memory_ex(const void* pImage, int w, int h, + int num_chans, size_t* pLen_out, + mz_uint level, mz_bool flip); +void* tdefl_write_image_to_png_file_in_memory(const void* pImage, + int w, int h, + int num_chans, + size_t* pLen_out); + +/* Output stream interface. The compressor uses this interface to write + * compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. */ +typedef mz_bool(*tdefl_put_buf_func_ptr)(const void* pBuf, int len, + void* pUser); + +/* tdefl_compress_mem_to_output() compresses a block to an output stream. The + * above helpers use this function internally. */ +mz_bool tdefl_compress_mem_to_output( + const void* pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, + void* pPut_buf_user, int flags); + +enum { + TDEFL_MAX_HUFF_TABLES = 3, + TDEFL_MAX_HUFF_SYMBOLS_0 = 288, + TDEFL_MAX_HUFF_SYMBOLS_1 = 32, + TDEFL_MAX_HUFF_SYMBOLS_2 = 19, + TDEFL_LZ_DICT_SIZE = 32768, + TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, + TDEFL_MIN_MATCH_LEN = 3, + TDEFL_MAX_MATCH_LEN = 258 +}; + +/* TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed + * output block (using static/fixed Huffman codes). */ +#if TDEFL_LESS_MEMORY +enum { + TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, + TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, + TDEFL_MAX_HUFF_SYMBOLS = 288, + TDEFL_LZ_HASH_BITS = 12, + TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, + TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, + TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS +}; +#else +enum { + TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, + TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, + TDEFL_MAX_HUFF_SYMBOLS = 288, + TDEFL_LZ_HASH_BITS = 15, + TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, + TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, + TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS +}; +#endif + +/* The low-level tdefl functions below may be used directly if the above helper + * functions aren't flexible enough. The low-level functions don't make any heap + * allocations, unlike the above helper functions. */ +typedef enum { + TDEFL_STATUS_BAD_PARAM = -2, + TDEFL_STATUS_PUT_BUF_FAILED = -1, + TDEFL_STATUS_OKAY = 0, + TDEFL_STATUS_DONE = 1 +} tdefl_status; + +/* Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums */ +typedef enum { + TDEFL_NO_FLUSH = 0, + TDEFL_SYNC_FLUSH = 2, + TDEFL_FULL_FLUSH = 3, + TDEFL_FINISH = 4 +} tdefl_flush; + +/* tdefl's compression state structure. */ +typedef struct { + tdefl_put_buf_func_ptr m_pPut_buf_func; + void* m_pPut_buf_user; + mz_uint m_flags, m_max_probes[2]; + int m_greedy_parsing; + mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; + mz_uint8* m_pLZ_code_buf, * m_pLZ_flags, * m_pOutput_buf, * m_pOutput_buf_end; + mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, + m_bit_buffer; + mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, + m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, + m_wants_to_finish; + tdefl_status m_prev_return_status; + const void* m_pIn_buf; + void* m_pOut_buf; + size_t* m_pIn_buf_size, * m_pOut_buf_size; + tdefl_flush m_flush; + const mz_uint8* m_pSrc; + size_t m_src_buf_left, m_out_buf_ofs; + mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; + mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; + mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; + mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; + mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; +} tdefl_compressor; + +/* Initializes the compressor. */ +/* There is no corresponding deinit() function because the tdefl API's do not + * dynamically allocate memory. */ + /* pBut_buf_func: If NULL, output data will be supplied to the specified + * callback. In this case, the user should call the tdefl_compress_buffer() API + * for compression. */ + /* If pBut_buf_func is NULL the user should always call the tdefl_compress() + * API. */ + /* flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, + * etc.) */ +tdefl_status tdefl_init(tdefl_compressor* d, + tdefl_put_buf_func_ptr pPut_buf_func, + void* pPut_buf_user, int flags); + +/* Compresses a block of data, consuming as much of the specified input buffer + * as possible, and writing as much compressed data to the specified output + * buffer as possible. */ +tdefl_status tdefl_compress(tdefl_compressor* d, + const void* pIn_buf, + size_t* pIn_buf_size, void* pOut_buf, + size_t* pOut_buf_size, + tdefl_flush flush); + +/* tdefl_compress_buffer() is only usable when the tdefl_init() is called with a + * non-NULL tdefl_put_buf_func_ptr. */ + /* tdefl_compress_buffer() always consumes the entire input buffer. */ +tdefl_status tdefl_compress_buffer(tdefl_compressor* d, + const void* pIn_buf, + size_t in_buf_size, + tdefl_flush flush); + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor* d); +mz_uint32 tdefl_get_adler32(tdefl_compressor* d); + +/* Create tdefl_compress() flags given zlib-style compression parameters. */ +/* level may range from [0,10] (where 10 is absolute max compression, but may be + * much slower on some files) */ + /* window_bits may be -15 (raw deflate) or 15 (zlib) */ + /* strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, + * MZ_RLE, or MZ_FIXED */ +mz_uint tdefl_create_comp_flags_from_zip_params(int level, + int window_bits, + int strategy); + +#ifndef MINIZ_NO_MALLOC +/* Allocate the tdefl_compressor structure in C so that */ +/* non-C language bindings to tdefl_ API don't need to worry about */ +/* structure size and allocation mechanism. */ +tdefl_compressor* tdefl_compressor_alloc(void); +void tdefl_compressor_free(tdefl_compressor* pComp); +#endif + +#pragma once + +/* ------------------- Low-level Decompression API Definitions */ + + +/* Decompression flags used by tinfl_decompress(). */ +/* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and + * ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the + * input is a raw deflate stream. */ + /* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available + * beyond the end of the supplied input buffer. If clear, the input buffer + * contains all remaining input. */ + /* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large + * enough to hold the entire decompressed stream. If clear, the output buffer is + * at least the size of the dictionary (typically 32KB). */ + /* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the + * decompressed bytes. */ +enum { + TINFL_FLAG_PARSE_ZLIB_HEADER = 1, + TINFL_FLAG_HAS_MORE_INPUT = 2, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, + TINFL_FLAG_COMPUTE_ADLER32 = 8 +}; + +/* High level decompression functions: */ +/* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block + * allocated via malloc(). */ + /* On entry: */ + /* pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data + * to decompress. */ + /* On return: */ + /* Function returns a pointer to the decompressed data, or NULL on failure. */ + /* *pOut_len will be set to the decompressed data's size, which could be larger + * than src_buf_len on uncompressible data. */ + /* The caller must call mz_free() on the returned block when it's no longer + * needed. */ +void* tinfl_decompress_mem_to_heap(const void* pSrc_buf, + size_t src_buf_len, + size_t* pOut_len, int flags); + +/* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block + * in memory. */ + /* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes + * written on success. */ +#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) +size_t tinfl_decompress_mem_to_mem(void* pOut_buf, + size_t out_buf_len, + const void* pSrc_buf, + size_t src_buf_len, int flags); + +/* tinfl_decompress_mem_to_callback() decompresses a block in memory to an + * internal 32KB buffer, and a user provided callback function will be called to + * flush the buffer. */ + /* Returns 1 on success or 0 on failure. */ +typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void* pUser); +int +tinfl_decompress_mem_to_callback(const void* pIn_buf, size_t* pIn_buf_size, + tinfl_put_buf_func_ptr pPut_buf_func, + void* pPut_buf_user, int flags); + +struct tinfl_decompressor_tag; +typedef struct tinfl_decompressor_tag tinfl_decompressor; + +#ifndef MINIZ_NO_MALLOC +/* Allocate the tinfl_decompressor structure in C so that */ +/* non-C language bindings to tinfl_ API don't need to worry about */ +/* structure size and allocation mechanism. */ +tinfl_decompressor* tinfl_decompressor_alloc(void); +void tinfl_decompressor_free(tinfl_decompressor* pDecomp); +#endif + +/* Max size of LZ dictionary. */ +#define TINFL_LZ_DICT_SIZE 32768 + +/* Return status. */ +typedef enum { + /* This flags indicates the inflator needs 1 or more input bytes to make + forward progress, but the caller is indicating that no more are available. + The compressed data */ + /* is probably corrupted. If you call the inflator again with more bytes it'll + try to continue processing the input but this is a BAD sign (either the + data is corrupted or you called it incorrectly). */ + /* If you call it again with no input you'll just get + TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */ + TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4, + + /* This flag indicates that one or more of the input parameters was obviously + bogus. (You can try calling it again, but if you get this error the calling + code is wrong.) */ + TINFL_STATUS_BAD_PARAM = -3, + + /* This flags indicate the inflator is finished but the adler32 check of the + uncompressed data didn't match. If you call it again it'll return + TINFL_STATUS_DONE. */ + TINFL_STATUS_ADLER32_MISMATCH = -2, + + /* This flags indicate the inflator has somehow failed (bad code, corrupted + input, etc.). If you call it again without resetting via tinfl_init() it + it'll just keep on returning the same status failure code. */ + TINFL_STATUS_FAILED = -1, + + /* Any status code less than TINFL_STATUS_DONE must indicate a failure. */ + + /* This flag indicates the inflator has returned every byte of uncompressed + data that it can, has consumed every byte that it needed, has successfully + reached the end of the deflate stream, and */ + /* if zlib headers and adler32 checking enabled that it has successfully + checked the uncompressed data's adler32. If you call it again you'll just + get TINFL_STATUS_DONE over and over again. */ + TINFL_STATUS_DONE = 0, + + /* This flag indicates the inflator MUST have more input data (even 1 byte) + before it can make any more forward progress, or you need to clear the + TINFL_FLAG_HAS_MORE_INPUT */ + /* flag on the next call if you don't have any more source data. If the source + data was somehow corrupted it's also possible (but unlikely) for the + inflator to keep on demanding input to */ + /* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */ + TINFL_STATUS_NEEDS_MORE_INPUT = 1, + + /* This flag indicates the inflator definitely has 1 or more bytes of + uncompressed data available, but it cannot write this data into the output + buffer. */ + /* Note if the source compressed data was corrupted it's possible for the + inflator to return a lot of uncompressed data to the caller. I've been + assuming you know how much uncompressed data to expect */ + /* (either exact or worst case) and will stop calling the inflator and fail + after receiving too much. In pure streaming scenarios where you have no + idea how many bytes to expect this may not be possible */ + /* so I may need to add some code to address this. */ + TINFL_STATUS_HAS_MORE_OUTPUT = 2 +} tinfl_status; + +/* Initializes the decompressor to its initial state. */ +#define tinfl_init(r) \ + do { \ + (r)->m_state = 0; \ + } \ + MZ_MACRO_END +#define tinfl_get_adler32(r) (r)->m_check_adler32 + +/* Main low-level decompressor coroutine function. This is the only function + * actually needed for decompression. All the other functions are just + * high-level helpers for improved usability. */ + /* This is a universal API, i.e. it can be used as a building block to build any + * desired higher level decompression API. In the limit case, it can be called + * once per every byte input or output. */ +tinfl_status tinfl_decompress( + tinfl_decompressor* r, const mz_uint8* pIn_buf_next, size_t* pIn_buf_size, + mz_uint8* pOut_buf_start, mz_uint8* pOut_buf_next, size_t* pOut_buf_size, + const mz_uint32 decomp_flags); + +/* Internal/private bits follow. */ +enum { + TINFL_MAX_HUFF_TABLES = 3, + TINFL_MAX_HUFF_SYMBOLS_0 = 288, + TINFL_MAX_HUFF_SYMBOLS_1 = 32, + TINFL_MAX_HUFF_SYMBOLS_2 = 19, + TINFL_FAST_LOOKUP_BITS = 10, + TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS +}; + +typedef struct { + mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; + mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], + m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; +} tinfl_huff_table; + +#if MINIZ_HAS_64BIT_REGISTERS +#define TINFL_USE_64BIT_BITBUF 1 +#else +#define TINFL_USE_64BIT_BITBUF 0 +#endif + +#if TINFL_USE_64BIT_BITBUF +typedef mz_uint64 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (64) +#else +typedef mz_uint32 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (32) +#endif + +struct tinfl_decompressor_tag { + mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, + m_check_adler32, m_dist, m_counter, m_num_extra, + m_table_sizes[TINFL_MAX_HUFF_TABLES]; + tinfl_bit_buf_t m_bit_buf; + size_t m_dist_from_out_buf_start; + tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; + mz_uint8 m_raw_header[4], + m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; +}; + + +#pragma once + +/* ------------------- ZIP archive reading/writing */ + +#ifndef MINIZ_NO_ARCHIVE_APIS + + +enum { + /* Note: These enums can be reduced as needed to save memory or stack space - + they are pretty conservative. */ + MZ_ZIP_MAX_IO_BUF_SIZE = 8 * 1024, + MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 512, + MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 512 +}; + +typedef struct { + /* Central directory file index. */ + mz_uint32 m_file_index; + + /* Byte offset of this entry in the archive's central directory. Note we + * currently only support up to UINT_MAX or less bytes in the central dir. */ + mz_uint64 m_central_dir_ofs; + + /* These fields are copied directly from the zip's central dir. */ + mz_uint16 m_version_made_by; + mz_uint16 m_version_needed; + mz_uint16 m_bit_flag; + mz_uint16 m_method; + +#ifndef MINIZ_NO_TIME + MZ_TIME_T m_time; +#endif + + /* CRC-32 of uncompressed data. */ + mz_uint32 m_crc32; + + /* File's compressed size. */ + mz_uint64 m_comp_size; + + /* File's uncompressed size. Note, I've seen some old archives where directory + * entries had 512 bytes for their uncompressed sizes, but when you try to + * unpack them you actually get 0 bytes. */ + mz_uint64 m_uncomp_size; + + /* Zip internal and external file attributes. */ + mz_uint16 m_internal_attr; + mz_uint32 m_external_attr; + + /* Entry's local header file offset in bytes. */ + mz_uint64 m_local_header_ofs; + + /* Size of comment in bytes. */ + mz_uint32 m_comment_size; + + /* MZ_TRUE if the entry appears to be a directory. */ + mz_bool m_is_directory; + + /* MZ_TRUE if the entry uses encryption/strong encryption (which miniz_zip + * doesn't support) */ + mz_bool m_is_encrypted; + + /* MZ_TRUE if the file is not encrypted, a patch file, and if it uses a + * compression method we support. */ + mz_bool m_is_supported; + + /* Filename. If string ends in '/' it's a subdirectory entry. */ + /* Guaranteed to be zero terminated, may be truncated to fit. */ + char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; + + /* Comment field. */ + /* Guaranteed to be zero terminated, may be truncated to fit. */ + char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; + +} mz_zip_archive_file_stat; + +typedef size_t(*mz_file_read_func)(void* pOpaque, mz_uint64 file_ofs, + void* pBuf, size_t n); +typedef size_t(*mz_file_write_func)(void* pOpaque, mz_uint64 file_ofs, + const void* pBuf, size_t n); +typedef mz_bool(*mz_file_needs_keepalive)(void* pOpaque); + +struct mz_zip_internal_state_tag; +typedef struct mz_zip_internal_state_tag mz_zip_internal_state; + +typedef enum { + MZ_ZIP_MODE_INVALID = 0, + MZ_ZIP_MODE_READING = 1, + MZ_ZIP_MODE_WRITING = 2, + MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 +} mz_zip_mode; + +typedef enum { + MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, + MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, + MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800, + MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG = + 0x1000, /* if enabled, mz_zip_reader_locate_file() will be called on each + file as its validated to ensure the func finds the file in the + central dir (intended for testing) */ + MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY = + 0x2000, /* validate the local headers, but don't decompress the entire + file and check the crc32 */ + MZ_ZIP_FLAG_WRITE_ZIP64 = + 0x4000, /* always use the zip64 file format, instead of the original zip + file format with automatic switch to zip64. Use as flags + parameter with mz_zip_writer_init*_v2 */ + MZ_ZIP_FLAG_WRITE_ALLOW_READING = 0x8000, + MZ_ZIP_FLAG_ASCII_FILENAME = 0x10000, + /*After adding a compressed file, seek back + to local file header and set the correct sizes*/ + MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE = 0x20000 +} mz_zip_flags; + +typedef enum { + MZ_ZIP_TYPE_INVALID = 0, + MZ_ZIP_TYPE_USER, + MZ_ZIP_TYPE_MEMORY, + MZ_ZIP_TYPE_HEAP, + MZ_ZIP_TYPE_FILE, + MZ_ZIP_TYPE_CFILE, + MZ_ZIP_TOTAL_TYPES +} mz_zip_type; + +/* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or + * modify this enum. */ +typedef enum { + MZ_ZIP_NO_ERROR = 0, + MZ_ZIP_UNDEFINED_ERROR, + MZ_ZIP_TOO_MANY_FILES, + MZ_ZIP_FILE_TOO_LARGE, + MZ_ZIP_UNSUPPORTED_METHOD, + MZ_ZIP_UNSUPPORTED_ENCRYPTION, + MZ_ZIP_UNSUPPORTED_FEATURE, + MZ_ZIP_FAILED_FINDING_CENTRAL_DIR, + MZ_ZIP_NOT_AN_ARCHIVE, + MZ_ZIP_INVALID_HEADER_OR_CORRUPTED, + MZ_ZIP_UNSUPPORTED_MULTIDISK, + MZ_ZIP_DECOMPRESSION_FAILED, + MZ_ZIP_COMPRESSION_FAILED, + MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE, + MZ_ZIP_CRC_CHECK_FAILED, + MZ_ZIP_UNSUPPORTED_CDIR_SIZE, + MZ_ZIP_ALLOC_FAILED, + MZ_ZIP_FILE_OPEN_FAILED, + MZ_ZIP_FILE_CREATE_FAILED, + MZ_ZIP_FILE_WRITE_FAILED, + MZ_ZIP_FILE_READ_FAILED, + MZ_ZIP_FILE_CLOSE_FAILED, + MZ_ZIP_FILE_SEEK_FAILED, + MZ_ZIP_FILE_STAT_FAILED, + MZ_ZIP_INVALID_PARAMETER, + MZ_ZIP_INVALID_FILENAME, + MZ_ZIP_BUF_TOO_SMALL, + MZ_ZIP_INTERNAL_ERROR, + MZ_ZIP_FILE_NOT_FOUND, + MZ_ZIP_ARCHIVE_TOO_LARGE, + MZ_ZIP_VALIDATION_FAILED, + MZ_ZIP_WRITE_CALLBACK_FAILED, + MZ_ZIP_TOTAL_ERRORS +} mz_zip_error; + +typedef struct { + mz_uint64 m_archive_size; + mz_uint64 m_central_directory_file_ofs; + + /* We only support up to UINT32_MAX files in zip64 mode. */ + mz_uint32 m_total_files; + mz_zip_mode m_zip_mode; + mz_zip_type m_zip_type; + mz_zip_error m_last_error; + + mz_uint64 m_file_offset_alignment; + + mz_alloc_func m_pAlloc; + mz_free_func m_pFree; + mz_realloc_func m_pRealloc; + void* m_pAlloc_opaque; + + mz_file_read_func m_pRead; + mz_file_write_func m_pWrite; + mz_file_needs_keepalive m_pNeeds_keepalive; + void* m_pIO_opaque; + + mz_zip_internal_state* m_pState; + +} mz_zip_archive; + +typedef struct { + mz_zip_archive* pZip; + mz_uint flags; + + int status; +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + mz_uint file_crc32; +#endif + mz_uint64 read_buf_size, read_buf_ofs, read_buf_avail, comp_remaining, + out_buf_ofs, cur_file_ofs; + mz_zip_archive_file_stat file_stat; + void* pRead_buf; + void* pWrite_buf; + + size_t out_blk_remain; + + tinfl_decompressor inflator; + +} mz_zip_reader_extract_iter_state; + +/* -------- ZIP reading */ + +/* Inits a ZIP archive reader. */ +/* These functions read and validate the archive's central directory. */ +mz_bool mz_zip_reader_init(mz_zip_archive* pZip, mz_uint64 size, + mz_uint flags); + +mz_bool mz_zip_reader_init_mem(mz_zip_archive* pZip, + const void* pMem, size_t size, + mz_uint flags); + +#ifndef MINIZ_NO_STDIO +/* Read a archive from a disk file. */ +/* file_start_ofs is the file offset where the archive actually begins, or 0. */ +/* actual_archive_size is the true total size of the archive, which may be + * smaller than the file's actual size on disk. If zero the entire file is + * treated as the archive. */ +mz_bool mz_zip_reader_init_file(mz_zip_archive* pZip, + const char* pFilename, + mz_uint32 flags); +mz_bool mz_zip_reader_init_file_v2(mz_zip_archive* pZip, + const char* pFilename, + mz_uint flags, + mz_uint64 file_start_ofs, + mz_uint64 archive_size); +mz_bool mz_zip_reader_init_file_v2_rpb(mz_zip_archive* pZip, + const char* pFilename, + mz_uint flags, + mz_uint64 file_start_ofs, + mz_uint64 archive_size); + +/* Read an archive from an already opened FILE, beginning at the current file + * position. */ + /* The archive is assumed to be archive_size bytes long. If archive_size is 0, + * then the entire rest of the file is assumed to contain the archive. */ + /* The FILE will NOT be closed when mz_zip_reader_end() is called. */ +mz_bool mz_zip_reader_init_cfile(mz_zip_archive* pZip, + MZ_FILE* pFile, + mz_uint64 archive_size, + mz_uint flags); +#endif + +/* Ends archive reading, freeing all allocations, and closing the input archive + * file if mz_zip_reader_init_file() was used. */ +mz_bool mz_zip_reader_end(mz_zip_archive* pZip); + +/* -------- ZIP reading or writing */ + +/* Clears a mz_zip_archive struct to all zeros. */ +/* Important: This must be done before passing the struct to any mz_zip + * functions. */ +void mz_zip_zero_struct(mz_zip_archive* pZip); + +mz_zip_mode mz_zip_get_mode(mz_zip_archive* pZip); +mz_zip_type mz_zip_get_type(mz_zip_archive* pZip); + +/* Returns the total number of files in the archive. */ +mz_uint mz_zip_reader_get_num_files(mz_zip_archive* pZip); + +mz_uint64 mz_zip_get_archive_size(mz_zip_archive* pZip); +mz_uint64 +mz_zip_get_archive_file_start_offset(mz_zip_archive* pZip); +MZ_FILE* mz_zip_get_cfile(mz_zip_archive* pZip); + +/* Reads n bytes of raw archive data, starting at file offset file_ofs, to pBuf. + */ +size_t mz_zip_read_archive_data(mz_zip_archive* pZip, + mz_uint64 file_ofs, void* pBuf, + size_t n); + +/* All mz_zip funcs set the m_last_error field in the mz_zip_archive struct. + * These functions retrieve/manipulate this field. */ + /* Note that the m_last_error functionality is not thread safe. */ +mz_zip_error mz_zip_set_last_error(mz_zip_archive* pZip, + mz_zip_error err_num); +mz_zip_error mz_zip_peek_last_error(mz_zip_archive* pZip); +mz_zip_error mz_zip_clear_last_error(mz_zip_archive* pZip); +mz_zip_error mz_zip_get_last_error(mz_zip_archive* pZip); +const char* mz_zip_get_error_string(mz_zip_error mz_err); + +/* MZ_TRUE if the archive file entry is a directory entry. */ +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive* pZip, + mz_uint file_index); + +/* MZ_TRUE if the file is encrypted/strong encrypted. */ +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive* pZip, + mz_uint file_index); + +/* MZ_TRUE if the compression method is supported, and the file is not + * encrypted, and the file is not a compressed patch file. */ +mz_bool mz_zip_reader_is_file_supported(mz_zip_archive* pZip, + mz_uint file_index); + +/* Retrieves the filename of an archive file entry. */ +/* Returns the number of bytes written to pFilename, or if filename_buf_size is + * 0 this function returns the number of bytes needed to fully store the + * filename. */ +mz_uint mz_zip_reader_get_filename(mz_zip_archive* pZip, + mz_uint file_index, + char* pFilename, + mz_uint filename_buf_size); + +/* Attempts to locates a file in the archive's central directory. */ +/* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */ +/* Returns -1 if the file cannot be found. */ +int mz_zip_reader_locate_file(mz_zip_archive* pZip, + const char* pName, + const char* pComment, mz_uint flags); +mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive* pZip, + const char* pName, + const char* pComment, + mz_uint flags, + mz_uint32* file_index); + +/* Returns detailed information about an archive file entry. */ +mz_bool mz_zip_reader_file_stat(mz_zip_archive* pZip, + mz_uint file_index, + mz_zip_archive_file_stat* pStat); + +/* MZ_TRUE if the file is in zip64 format. */ +/* A file is considered zip64 if it contained a zip64 end of central directory + * marker, or if it contained any zip64 extended file information fields in the + * central directory. */ +mz_bool mz_zip_is_zip64(mz_zip_archive* pZip); + +/* Returns the total central directory size in bytes. */ +/* The current max supported size is <= MZ_UINT32_MAX. */ +size_t mz_zip_get_central_dir_size(mz_zip_archive* pZip); + +/* Extracts a archive file to a memory buffer using no memory allocation. */ +/* There must be at least enough room on the stack to store the inflator's state + * (~34KB or so). */ +mz_bool mz_zip_reader_extract_to_mem_no_alloc( + mz_zip_archive* pZip, mz_uint file_index, void* pBuf, size_t buf_size, + mz_uint flags, void* pUser_read_buf, size_t user_read_buf_size); +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( + mz_zip_archive* pZip, const char* pFilename, void* pBuf, size_t buf_size, + mz_uint flags, void* pUser_read_buf, size_t user_read_buf_size); + +/* Extracts a archive file to a memory buffer. */ +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive* pZip, + mz_uint file_index, + void* pBuf, size_t buf_size, + mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive* pZip, + const char* pFilename, + void* pBuf, + size_t buf_size, + mz_uint flags); + +/* Extracts a archive file to a dynamically allocated heap buffer. */ +/* The memory will be allocated via the mz_zip_archive's alloc/realloc + * functions. */ + /* Returns NULL and sets the last error on failure. */ +void* mz_zip_reader_extract_to_heap(mz_zip_archive* pZip, + mz_uint file_index, + size_t* pSize, mz_uint flags); +void* mz_zip_reader_extract_file_to_heap(mz_zip_archive* pZip, + const char* pFilename, + size_t* pSize, + mz_uint flags); + +/* Extracts a archive file using a callback function to output the file's data. + */ +mz_bool mz_zip_reader_extract_to_callback( + mz_zip_archive* pZip, mz_uint file_index, mz_file_write_func pCallback, + void* pOpaque, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_callback( + mz_zip_archive* pZip, const char* pFilename, mz_file_write_func pCallback, + void* pOpaque, mz_uint flags); + +/* Extract a file iteratively */ +mz_zip_reader_extract_iter_state* +mz_zip_reader_extract_iter_new(mz_zip_archive* pZip, mz_uint file_index, + mz_uint flags); +mz_zip_reader_extract_iter_state* +mz_zip_reader_extract_file_iter_new(mz_zip_archive* pZip, const char* pFilename, + mz_uint flags); +size_t mz_zip_reader_extract_iter_read( + mz_zip_reader_extract_iter_state* pState, void* pvBuf, size_t buf_size); +mz_bool +mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState); + +#ifndef MINIZ_NO_STDIO +/* Extracts a archive file to a disk file and sets its last accessed and + * modified times. */ + /* This function only extracts files, not archive directory records. */ +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive* pZip, + mz_uint file_index, + const char* pDst_filename, + mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_file( + mz_zip_archive* pZip, const char* pArchive_filename, + const char* pDst_filename, mz_uint flags); + +/* Extracts a archive file starting at the current position in the destination + * FILE stream. */ +mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive* pZip, + mz_uint file_index, + MZ_FILE* File, + mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_cfile( + mz_zip_archive* pZip, const char* pArchive_filename, MZ_FILE* pFile, + mz_uint flags); +#endif + +#if 0 +/* TODO */ +typedef void* mz_zip_streaming_extract_state_ptr; +mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive* pZip, mz_uint file_index, mz_uint flags); +uint64_t mz_zip_streaming_extract_get_size(mz_zip_archive* pZip, mz_zip_streaming_extract_state_ptr pState); +uint64_t mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive* pZip, mz_zip_streaming_extract_state_ptr pState); +mz_bool mz_zip_streaming_extract_seek(mz_zip_archive* pZip, mz_zip_streaming_extract_state_ptr pState, uint64_t new_ofs); +size_t mz_zip_streaming_extract_read(mz_zip_archive* pZip, mz_zip_streaming_extract_state_ptr pState, void* pBuf, size_t buf_size); +mz_bool mz_zip_streaming_extract_end(mz_zip_archive* pZip, mz_zip_streaming_extract_state_ptr pState); +#endif + +/* This function compares the archive's local headers, the optional local zip64 + * extended information block, and the optional descriptor following the + * compressed data vs. the data in the central directory. */ + /* It also validates that each file can be successfully uncompressed unless the + * MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY is specified. */ +mz_bool mz_zip_validate_file(mz_zip_archive* pZip, + mz_uint file_index, mz_uint flags); + +/* Validates an entire archive by calling mz_zip_validate_file() on each file. + */ +mz_bool mz_zip_validate_archive(mz_zip_archive* pZip, + mz_uint flags); + +/* Misc utils/helpers, valid for ZIP reading or writing */ +mz_bool mz_zip_validate_mem_archive(const void* pMem, size_t size, + mz_uint flags, + mz_zip_error* pErr); +mz_bool mz_zip_validate_file_archive(const char* pFilename, + mz_uint flags, + mz_zip_error* pErr); + +/* Universal end function - calls either mz_zip_reader_end() or + * mz_zip_writer_end(). */ +mz_bool mz_zip_end(mz_zip_archive* pZip); + +/* -------- ZIP writing */ + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +/* Inits a ZIP archive writer. */ +/*Set pZip->m_pWrite (and pZip->m_pIO_opaque) before calling mz_zip_writer_init + * or mz_zip_writer_init_v2*/ + /*The output is streamable, i.e. file_ofs in mz_file_write_func always increases + * only by n*/ +mz_bool mz_zip_writer_init(mz_zip_archive* pZip, + mz_uint64 existing_size); +mz_bool mz_zip_writer_init_v2(mz_zip_archive* pZip, + mz_uint64 existing_size, + mz_uint flags); + +mz_bool mz_zip_writer_init_heap( + mz_zip_archive* pZip, size_t size_to_reserve_at_beginning, + size_t initial_allocation_size); +mz_bool mz_zip_writer_init_heap_v2( + mz_zip_archive* pZip, size_t size_to_reserve_at_beginning, + size_t initial_allocation_size, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +mz_bool +mz_zip_writer_init_file(mz_zip_archive* pZip, const char* pFilename, + mz_uint64 size_to_reserve_at_beginning); +mz_bool mz_zip_writer_init_file_v2( + mz_zip_archive* pZip, const char* pFilename, + mz_uint64 size_to_reserve_at_beginning, mz_uint flags); +mz_bool mz_zip_writer_init_cfile(mz_zip_archive* pZip, + MZ_FILE* pFile, mz_uint flags); +#endif + +/* Converts a ZIP archive reader object into a writer object, to allow efficient + * in-place file appends to occur on an existing archive. */ + /* For archives opened using mz_zip_reader_init_file, pFilename must be the + * archive's filename so it can be reopened for writing. If the file can't be + * reopened, mz_zip_reader_end() will be called. */ + /* For archives opened using mz_zip_reader_init_mem, the memory block must be + * growable using the realloc callback (which defaults to realloc unless you've + * overridden it). */ + /* Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's + * user provided m_pWrite function cannot be NULL. */ + /* Note: In-place archive modification is not recommended unless you know what + * you're doing, because if execution stops or something goes wrong before */ + /* the archive is finalized the file's central directory will be hosed. */ +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive* pZip, + const char* pFilename); +mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive* pZip, + const char* pFilename, + mz_uint flags); +mz_bool mz_zip_writer_init_from_reader_v2_noreopen( + mz_zip_archive* pZip, const char* pFilename, mz_uint flags); + +/* Adds the contents of a memory buffer to an archive. These functions record + * the current local time into the archive. */ + /* To add a directory entry, call this method with an archive name ending in a + * forwardslash with an empty buffer. */ + /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, + * MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or + * just set to MZ_DEFAULT_COMPRESSION. */ +mz_bool mz_zip_writer_add_mem(mz_zip_archive* pZip, + const char* pArchive_name, + const void* pBuf, size_t buf_size, + mz_uint level_and_flags); + +/* Like mz_zip_writer_add_mem(), except you can specify a file comment field, + * and optionally supply the function with already compressed data. */ + /* uncomp_size/uncomp_crc32 are only used if the MZ_ZIP_FLAG_COMPRESSED_DATA + * flag is specified. */ +mz_bool mz_zip_writer_add_mem_ex( + mz_zip_archive* pZip, const char* pArchive_name, const void* pBuf, + size_t buf_size, const void* pComment, mz_uint16 comment_size, + mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); + +mz_bool mz_zip_writer_add_mem_ex_v2( + mz_zip_archive* pZip, const char* pArchive_name, const void* pBuf, + size_t buf_size, const void* pComment, mz_uint16 comment_size, + mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, + MZ_TIME_T* last_modified, const char* user_extra_data_local, + mz_uint user_extra_data_local_len, const char* user_extra_data_central, + mz_uint user_extra_data_central_len); + +/* Adds the contents of a file to an archive. This function also records the + * disk file's modified time into the archive. */ + /* File data is supplied via a read callback function. User + * mz_zip_writer_add_(c)file to add a file directly.*/ +mz_bool mz_zip_writer_add_read_buf_callback( + mz_zip_archive* pZip, const char* pArchive_name, + mz_file_read_func read_callback, void* callback_opaque, mz_uint64 max_size, + const MZ_TIME_T* pFile_time, const void* pComment, mz_uint16 comment_size, + mz_uint level_and_flags, mz_uint32 ext_attributes, + const char* user_extra_data_local, mz_uint user_extra_data_local_len, + const char* user_extra_data_central, mz_uint user_extra_data_central_len); + +#ifndef MINIZ_NO_STDIO +/* Adds the contents of a disk file to an archive. This function also records + * the disk file's modified time into the archive. */ + /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, + * MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or + * just set to MZ_DEFAULT_COMPRESSION. */ +mz_bool mz_zip_writer_add_file( + mz_zip_archive* pZip, const char* pArchive_name, const char* pSrc_filename, + const void* pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint32 ext_attributes); + +/* Like mz_zip_writer_add_file(), except the file data is read from the + * specified FILE stream. */ +mz_bool mz_zip_writer_add_cfile( + mz_zip_archive* pZip, const char* pArchive_name, MZ_FILE* pSrc_file, + mz_uint64 max_size, const MZ_TIME_T* pFile_time, const void* pComment, + mz_uint16 comment_size, mz_uint level_and_flags, mz_uint32 ext_attributes, + const char* user_extra_data_local, mz_uint user_extra_data_local_len, + const char* user_extra_data_central, mz_uint user_extra_data_central_len); +#endif + +/* Adds a file to an archive by fully cloning the data from another archive. */ +/* This function fully clones the source file's compressed data (no + * recompression), along with its full filename, extra data (it may add or + * modify the zip64 local header extra data field), and the optional descriptor + * following the compressed data. */ +mz_bool mz_zip_writer_add_from_zip_reader( + mz_zip_archive* pZip, mz_zip_archive* pSource_zip, mz_uint src_file_index); + +/* Finalizes the archive by writing the central directory records followed by + * the end of central directory record. */ + /* After an archive is finalized, the only valid call on the mz_zip_archive + * struct is mz_zip_writer_end(). */ + /* An archive must be manually finalized by calling this function for it to be + * valid. */ +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive* pZip); + +/* Finalizes a heap archive, returning a poiner to the heap block and its size. + */ + /* The heap block will be allocated using the mz_zip_archive's alloc/realloc + * callbacks. */ +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive* pZip, + void** ppBuf, + size_t* pSize); + +/* Ends archive writing, freeing all allocations, and closing the output file if + * mz_zip_writer_init_file() was used. */ + /* Note for the archive to be valid, it *must* have been finalized before ending + * (this function will not do it for you). */ +mz_bool mz_zip_writer_end(mz_zip_archive* pZip); + +/* -------- Misc. high-level helper functions: */ + +/* mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) + * appends a memory blob to a ZIP archive. */ + /* Note this is NOT a fully safe operation. If it crashes or dies in some way + * your archive can be left in a screwed up state (without a central directory). + */ + /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, + * MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or + * just set to MZ_DEFAULT_COMPRESSION. */ + /* TODO: Perhaps add an option to leave the existing central dir in place in + * case the add dies? We could then truncate the file (so the old central dir + * would be at the end) if something goes wrong. */ +mz_bool mz_zip_add_mem_to_archive_file_in_place( + const char* pZip_filename, const char* pArchive_name, const void* pBuf, + size_t buf_size, const void* pComment, mz_uint16 comment_size, + mz_uint level_and_flags); +mz_bool mz_zip_add_mem_to_archive_file_in_place_v2( + const char* pZip_filename, const char* pArchive_name, const void* pBuf, + size_t buf_size, const void* pComment, mz_uint16 comment_size, + mz_uint level_and_flags, mz_zip_error* pErr); + +/* Reads a single file from an archive into a heap block. */ +/* If pComment is not NULL, only the file with the specified comment will be + * extracted. */ + /* Returns NULL on failure. */ +void* +mz_zip_extract_archive_file_to_heap(const char* pZip_filename, + const char* pArchive_name, size_t* pSize, + mz_uint flags); +void* mz_zip_extract_archive_file_to_heap_v2( + const char* pZip_filename, const char* pArchive_name, const char* pComment, + size_t* pSize, mz_uint flags, mz_zip_error* pErr); + +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ + + +#endif /* MINIZ_NO_ARCHIVE_APIS */ +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + +typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; +typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; +typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; + + + +/* ------------------- zlib-style API's */ + +mz_ulong mz_adler32(mz_ulong adler, const unsigned char* ptr, size_t buf_len) { + mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); + size_t block_len = buf_len % 5552; + if (!ptr) + return MZ_ADLER32_INIT; + while (buf_len) { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { + s1 += ptr[0], s2 += s1; + s1 += ptr[1], s2 += s1; + s1 += ptr[2], s2 += s1; + s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; + s1 += ptr[5], s2 += s1; + s1 += ptr[6], s2 += s1; + s1 += ptr[7], s2 += s1; + } + for (; i < block_len; ++i) + s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; + buf_len -= block_len; + block_len = 5552; + } + return (s2 << 16) + s1; +} + +/* Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C + * implementation that balances processor cache usage against speed": + * http://www.geocities.com/malbrain/ */ +#if 0 +mz_ulong mz_crc32(mz_ulong crc, const mz_uint8* ptr, size_t buf_len) +{ + static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, + 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; + mz_uint32 crcu32 = (mz_uint32)crc; + if (!ptr) + return MZ_CRC32_INIT; + crcu32 = ~crcu32; + while (buf_len--) + { + mz_uint8 b = *ptr++; + crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; + crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; + } + return ~crcu32; +} +#elif defined(USE_EXTERNAL_MZCRC) + /* If USE_EXTERNAL_CRC is defined, an external module will export the + * mz_crc32() symbol for us to use, e.g. an SSE-accelerated version. + * Depending on the impl, it may be necessary to ~ the input/output crc values. + */ +mz_ulong mz_crc32(mz_ulong crc, const mz_uint8* ptr, size_t buf_len); +#else + /* Faster, but larger CPU cache footprint. + */ +mz_ulong mz_crc32(mz_ulong crc, const mz_uint8* ptr, size_t buf_len) { + static const mz_uint32 s_crc_table[256] = { + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, + 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, + 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, + 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, + 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, + 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, + 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, + 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, + 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, + 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, + 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, + 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, + 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, + 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, + 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, + 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, + 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, + 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, + 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, + 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, + 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, + 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, + 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, + 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, + 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, + 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, + 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, + 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, + 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, + 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, + 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, + 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, + 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, + 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, + 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, + 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, + 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, + 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, + 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, + 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, + 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, + 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; + + mz_uint32 crc32 = (mz_uint32)crc ^ 0xFFFFFFFF; + const mz_uint8* pByte_buf = (const mz_uint8*)ptr; + + while (buf_len >= 4) { + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[1]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[2]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[3]) & 0xFF]; + pByte_buf += 4; + buf_len -= 4; + } + + while (buf_len) { + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; + ++pByte_buf; + --buf_len; + } + + return ~crc32; +} +#endif + +void mz_free(void* p) { MZ_FREE(p); } + +void* miniz_def_alloc_func(void* opaque, size_t items, + size_t size) { + (void)opaque, (void)items, (void)size; + return MZ_MALLOC(items * size); +} +void miniz_def_free_func(void* opaque, void* address) { + (void)opaque, (void)address; + MZ_FREE(address); +} +void* miniz_def_realloc_func(void* opaque, void* address, + size_t items, size_t size) { + (void)opaque, (void)address, (void)items, (void)size; + return MZ_REALLOC(address, items * size); +} + +const char* mz_version(void) { return MZ_VERSION; } + +#ifndef MINIZ_NO_ZLIB_APIS + +int mz_deflateInit(mz_streamp pStream, int level) { + return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, + MZ_DEFAULT_STRATEGY); +} + +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, + int mem_level, int strategy) { + tdefl_compressor* pComp; + mz_uint comp_flags = + TDEFL_COMPUTE_ADLER32 | + tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); + + if (!pStream) + return MZ_STREAM_ERROR; + if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || + ((window_bits != MZ_DEFAULT_WINDOW_BITS) && + (-window_bits != MZ_DEFAULT_WINDOW_BITS))) + return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = MZ_ADLER32_INIT; + pStream->msg = NULL; + pStream->reserved = 0; + pStream->total_in = 0; + pStream->total_out = 0; + if (!pStream->zalloc) + pStream->zalloc = miniz_def_alloc_func; + if (!pStream->zfree) + pStream->zfree = miniz_def_free_func; + + pComp = (tdefl_compressor*)pStream->zalloc(pStream->opaque, 1, + sizeof(tdefl_compressor)); + if (!pComp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state*)pComp; + + if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) { + mz_deflateEnd(pStream); + return MZ_PARAM_ERROR; + } + + return MZ_OK; +} + +int mz_deflateReset(mz_streamp pStream) { + if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || + (!pStream->zfree)) + return MZ_STREAM_ERROR; + pStream->total_in = pStream->total_out = 0; + tdefl_init((tdefl_compressor*)pStream->state, NULL, NULL, + ((tdefl_compressor*)pStream->state)->m_flags); + return MZ_OK; +} + +int mz_deflate(mz_streamp pStream, int flush) { + size_t in_bytes, out_bytes; + mz_ulong orig_total_in, orig_total_out; + int mz_status = MZ_OK; + + if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || + (!pStream->next_out)) + return MZ_STREAM_ERROR; + if (!pStream->avail_out) + return MZ_BUF_ERROR; + + if (flush == MZ_PARTIAL_FLUSH) + flush = MZ_SYNC_FLUSH; + + if (((tdefl_compressor*)pStream->state)->m_prev_return_status == + TDEFL_STATUS_DONE) + return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; + + orig_total_in = pStream->total_in; + orig_total_out = pStream->total_out; + for (;;) { + tdefl_status defl_status; + in_bytes = pStream->avail_in; + out_bytes = pStream->avail_out; + + defl_status = tdefl_compress((tdefl_compressor*)pStream->state, + pStream->next_in, &in_bytes, pStream->next_out, + &out_bytes, (tdefl_flush)flush); + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tdefl_get_adler32((tdefl_compressor*)pStream->state); + + pStream->next_out += (mz_uint)out_bytes; + pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; + + if (defl_status < 0) { + mz_status = MZ_STREAM_ERROR; + break; + } + else if (defl_status == TDEFL_STATUS_DONE) { + mz_status = MZ_STREAM_END; + break; + } + else if (!pStream->avail_out) + break; + else if ((!pStream->avail_in) && (flush != MZ_FINISH)) { + if ((flush) || (pStream->total_in != orig_total_in) || + (pStream->total_out != orig_total_out)) + break; + return MZ_BUF_ERROR; /* Can't make forward progress without some input. + */ + } + } + return mz_status; +} + +int mz_deflateEnd(mz_streamp pStream) { + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} + +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) { + (void)pStream; + /* This is really over conservative. (And lame, but it's actually pretty + * tricky to compute a true upper bound given the way tdefl's blocking works.) + */ + return MZ_MAX(128 + (source_len * 110) / 100, + 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); +} + +int mz_compress2(unsigned char* pDest, mz_ulong* pDest_len, + const unsigned char* pSource, mz_ulong source_len, int level) { + int status; + mz_stream stream; + memset(&stream, 0, sizeof(stream)); + + /* In case mz_ulong is 64-bits (argh I hate longs). */ + if ((source_len | *pDest_len) > 0xFFFFFFFFU) + return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_deflateInit(&stream, level); + if (status != MZ_OK) + return status; + + status = mz_deflate(&stream, MZ_FINISH); + if (status != MZ_STREAM_END) { + mz_deflateEnd(&stream); + return (status == MZ_OK) ? MZ_BUF_ERROR : status; + } + + *pDest_len = stream.total_out; + return mz_deflateEnd(&stream); +} + +int mz_compress(unsigned char* pDest, mz_ulong* pDest_len, + const unsigned char* pSource, mz_ulong source_len) { + return mz_compress2(pDest, pDest_len, pSource, source_len, + MZ_DEFAULT_COMPRESSION); +} + +mz_ulong mz_compressBound(mz_ulong source_len) { + return mz_deflateBound(NULL, source_len); +} + +typedef struct { + tinfl_decompressor m_decomp; + mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; + int m_window_bits; + mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; + tinfl_status m_last_status; +} inflate_state; + +int mz_inflateInit2(mz_streamp pStream, int window_bits) { + inflate_state* pDecomp; + if (!pStream) + return MZ_STREAM_ERROR; + if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && + (-window_bits != MZ_DEFAULT_WINDOW_BITS)) + return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = 0; + pStream->msg = NULL; + pStream->total_in = 0; + pStream->total_out = 0; + pStream->reserved = 0; + if (!pStream->zalloc) + pStream->zalloc = miniz_def_alloc_func; + if (!pStream->zfree) + pStream->zfree = miniz_def_free_func; + + pDecomp = (inflate_state*)pStream->zalloc(pStream->opaque, 1, + sizeof(inflate_state)); + if (!pDecomp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state*)pDecomp; + + tinfl_init(&pDecomp->m_decomp); + pDecomp->m_dict_ofs = 0; + pDecomp->m_dict_avail = 0; + pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; + pDecomp->m_first_call = 1; + pDecomp->m_has_flushed = 0; + pDecomp->m_window_bits = window_bits; + + return MZ_OK; +} + +int mz_inflateInit(mz_streamp pStream) { + return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); +} + +int mz_inflateReset(mz_streamp pStream) { + inflate_state* pDecomp; + if (!pStream) + return MZ_STREAM_ERROR; + + pStream->data_type = 0; + pStream->adler = 0; + pStream->msg = NULL; + pStream->total_in = 0; + pStream->total_out = 0; + pStream->reserved = 0; + + pDecomp = (inflate_state*)pStream->state; + + tinfl_init(&pDecomp->m_decomp); + pDecomp->m_dict_ofs = 0; + pDecomp->m_dict_avail = 0; + pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; + pDecomp->m_first_call = 1; + pDecomp->m_has_flushed = 0; + /* pDecomp->m_window_bits = window_bits */; + + return MZ_OK; +} + +int mz_inflate(mz_streamp pStream, int flush) { + inflate_state* pState; + mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; + size_t in_bytes, out_bytes, orig_avail_in; + tinfl_status status; + + if ((!pStream) || (!pStream->state)) + return MZ_STREAM_ERROR; + if (flush == MZ_PARTIAL_FLUSH) + flush = MZ_SYNC_FLUSH; + if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) + return MZ_STREAM_ERROR; + + pState = (inflate_state*)pStream->state; + if (pState->m_window_bits > 0) + decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; + orig_avail_in = pStream->avail_in; + + first_call = pState->m_first_call; + pState->m_first_call = 0; + if (pState->m_last_status < 0) + return MZ_DATA_ERROR; + + if (pState->m_has_flushed && (flush != MZ_FINISH)) + return MZ_STREAM_ERROR; + pState->m_has_flushed |= (flush == MZ_FINISH); + + if ((flush == MZ_FINISH) && (first_call)) { + /* MZ_FINISH on the first call implies that the input and output buffers are + * large enough to hold the entire compressed/decompressed file. */ + decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; + in_bytes = pStream->avail_in; + out_bytes = pStream->avail_out; + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, + pStream->next_out, pStream->next_out, &out_bytes, + decomp_flags); + pState->m_last_status = status; + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); + pStream->next_out += (mz_uint)out_bytes; + pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; + + if (status < 0) + return MZ_DATA_ERROR; + else if (status != TINFL_STATUS_DONE) { + pState->m_last_status = TINFL_STATUS_FAILED; + return MZ_BUF_ERROR; + } + return MZ_STREAM_END; + } + /* flush != MZ_FINISH then we must assume there's more input. */ + if (flush != MZ_FINISH) + decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; + + if (pState->m_dict_avail) { + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; + pStream->avail_out -= n; + pStream->total_out += n; + pState->m_dict_avail -= n; + pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + return ((pState->m_last_status == TINFL_STATUS_DONE) && + (!pState->m_dict_avail)) + ? MZ_STREAM_END + : MZ_OK; + } + + for (;;) { + in_bytes = pStream->avail_in; + out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; + + status = tinfl_decompress( + &pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, + pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); + pState->m_last_status = status; + + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); + + pState->m_dict_avail = (mz_uint)out_bytes; + + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; + pStream->avail_out -= n; + pStream->total_out += n; + pState->m_dict_avail -= n; + pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + + if (status < 0) + return MZ_DATA_ERROR; /* Stream is corrupted (there could be some + uncompressed data left in the output dictionary - + oh well). */ + else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) + return MZ_BUF_ERROR; /* Signal caller that we can't make forward progress + without supplying more input or by setting flush + to MZ_FINISH. */ + else if (flush == MZ_FINISH) { + /* The output buffer MUST be large to hold the remaining uncompressed data + * when flush==MZ_FINISH. */ + if (status == TINFL_STATUS_DONE) + return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; + /* status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's + * at least 1 more byte on the way. If there's no more room left in the + * output buffer then something is wrong. */ + else if (!pStream->avail_out) + return MZ_BUF_ERROR; + } + else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || + (!pStream->avail_out) || (pState->m_dict_avail)) + break; + } + + return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) + ? MZ_STREAM_END + : MZ_OK; +} + +int mz_inflateEnd(mz_streamp pStream) { + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} +int mz_uncompress2(unsigned char* pDest, mz_ulong* pDest_len, + const unsigned char* pSource, mz_ulong* pSource_len) { + mz_stream stream; + int status; + memset(&stream, 0, sizeof(stream)); + + /* In case mz_ulong is 64-bits (argh I hate longs). */ + if ((*pSource_len | *pDest_len) > 0xFFFFFFFFU) + return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)*pSource_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_inflateInit(&stream); + if (status != MZ_OK) + return status; + + status = mz_inflate(&stream, MZ_FINISH); + *pSource_len = *pSource_len - stream.avail_in; + if (status != MZ_STREAM_END) { + mz_inflateEnd(&stream); + return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR + : status; + } + *pDest_len = stream.total_out; + + return mz_inflateEnd(&stream); +} + +int mz_uncompress(unsigned char* pDest, mz_ulong* pDest_len, + const unsigned char* pSource, mz_ulong source_len) { + return mz_uncompress2(pDest, pDest_len, pSource, &source_len); +} + +const char* mz_error(int err) { + static struct { + int m_err; + const char* m_pDesc; + } s_error_descs[] = { {MZ_OK, ""}, + {MZ_STREAM_END, "stream end"}, + {MZ_NEED_DICT, "need dictionary"}, + {MZ_ERRNO, "file error"}, + {MZ_STREAM_ERROR, "stream error"}, + {MZ_DATA_ERROR, "data error"}, + {MZ_MEM_ERROR, "out of memory"}, + {MZ_BUF_ERROR, "buf error"}, + {MZ_VERSION_ERROR, "version error"}, + {MZ_PARAM_ERROR, "parameter error"} }; + mz_uint i; + for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) + if (s_error_descs[i].m_err == err) + return s_error_descs[i].m_pDesc; + return NULL; +} + +#endif /*MINIZ_NO_ZLIB_APIS */ + + + +/* + This is free and unencumbered software released into the public domain. + + Anyone is free to copy, modify, publish, use, compile, sell, or + distribute this software, either in source code form or as a compiled + binary, for any purpose, commercial or non-commercial, and by any + means. + + In jurisdictions that recognize copyright laws, the author or authors + of this software dedicate any and all copyright interest in the + software to the public domain. We make this dedication for the benefit + of the public at large and to the detriment of our heirs and + successors. We intend this dedication to be an overt act of + relinquishment in perpetuity of all present and future rights to this + software under copyright law. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + For more information, please refer to +*/ +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + + + + /* ------------------- Low-level Compression (independent from all decompression + * API's) */ + + /* Purposely making these tables static for faster init and thread safety. */ +static const mz_uint16 s_tdefl_len_sym[256] = { + 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, + 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, + 272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, + 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, + 276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, + 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, + 278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279, + 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, + 280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281, + 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, + 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282, + 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, + 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283, + 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, + 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284, + 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, + 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, + 285 }; + +static const mz_uint8 s_tdefl_len_extra[256] = { + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0 }; + +static const mz_uint8 s_tdefl_small_dist_sym[512] = { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, + 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, + 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, + 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, + 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17 }; + +static const mz_uint8 s_tdefl_small_dist_extra[512] = { + 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }; + +static const mz_uint8 s_tdefl_large_dist_sym[128] = { + 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, + 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, + 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, + 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 }; + +static const mz_uint8 s_tdefl_large_dist_extra[128] = { + 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, + 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13 }; + +/* Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted + * values. */ +typedef struct { + mz_uint16 m_key, m_sym_index; +} tdefl_sym_freq; +static tdefl_sym_freq* tdefl_radix_sort_syms(mz_uint num_syms, + tdefl_sym_freq* pSyms0, + tdefl_sym_freq* pSyms1) { + mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; + tdefl_sym_freq* pCur_syms = pSyms0, * pNew_syms = pSyms1; + MZ_CLEAR_OBJ(hist); + for (i = 0; i < num_syms; i++) { + mz_uint freq = pSyms0[i].m_key; + hist[freq & 0xFF]++; + hist[256 + ((freq >> 8) & 0xFF)]++; + } + while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) + total_passes--; + for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) { + const mz_uint32* pHist = &hist[pass << 8]; + mz_uint offsets[256], cur_ofs = 0; + for (i = 0; i < 256; i++) { + offsets[i] = cur_ofs; + cur_ofs += pHist[i]; + } + for (i = 0; i < num_syms; i++) + pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = + pCur_syms[i]; + { + tdefl_sym_freq* t = pCur_syms; + pCur_syms = pNew_syms; + pNew_syms = t; + } + } + return pCur_syms; +} + +/* tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, + * alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. */ +static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq* A, int n) { + int root, leaf, next, avbl, used, dpth; + if (n == 0) + return; + else if (n == 1) { + A[0].m_key = 1; + return; + } + A[0].m_key += A[1].m_key; + root = 0; + leaf = 2; + for (next = 1; next < n - 1; next++) { + if (leaf >= n || A[root].m_key < A[leaf].m_key) { + A[next].m_key = A[root].m_key; + A[root++].m_key = (mz_uint16)next; + } + else + A[next].m_key = A[leaf++].m_key; + if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) { + A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); + A[root++].m_key = (mz_uint16)next; + } + else + A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); + } + A[n - 2].m_key = 0; + for (next = n - 3; next >= 0; next--) + A[next].m_key = A[A[next].m_key].m_key + 1; + avbl = 1; + used = dpth = 0; + root = n - 2; + next = n - 1; + while (avbl > 0) { + while (root >= 0 && (int)A[root].m_key == dpth) { + used++; + root--; + } + while (avbl > used) { + A[next--].m_key = (mz_uint16)(dpth); + avbl--; + } + avbl = 2 * used; + dpth++; + used = 0; + } +} + +/* Limits canonical Huffman code table's max code size. */ +enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; +static void tdefl_huffman_enforce_max_code_size(int* pNum_codes, + int code_list_len, + int max_code_size) { + int i; + mz_uint32 total = 0; + if (code_list_len <= 1) + return; + for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) + pNum_codes[max_code_size] += pNum_codes[i]; + for (i = max_code_size; i > 0; i--) + total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); + while (total != (1UL << max_code_size)) { + pNum_codes[max_code_size]--; + for (i = max_code_size - 1; i > 0; i--) + if (pNum_codes[i]) { + pNum_codes[i]--; + pNum_codes[i + 1] += 2; + break; + } + total--; + } +} + +static void tdefl_optimize_huffman_table(tdefl_compressor* d, int table_num, + int table_len, int code_size_limit, + int static_table) { + int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; + mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; + MZ_CLEAR_OBJ(num_codes); + if (static_table) { + for (i = 0; i < table_len; i++) + num_codes[d->m_huff_code_sizes[table_num][i]]++; + } + else { + tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], + * pSyms; + int num_used_syms = 0; + const mz_uint16* pSym_count = &d->m_huff_count[table_num][0]; + for (i = 0; i < table_len; i++) + if (pSym_count[i]) { + syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; + syms0[num_used_syms++].m_sym_index = (mz_uint16)i; + } + + pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); + tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); + + for (i = 0; i < num_used_syms; i++) + num_codes[pSyms[i].m_key]++; + + tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, + code_size_limit); + + MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); + MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); + for (i = 1, j = num_used_syms; i <= code_size_limit; i++) + for (l = num_codes[i]; l > 0; l--) + d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); + } + + next_code[1] = 0; + for (j = 0, i = 2; i <= code_size_limit; i++) + next_code[i] = j = ((j + num_codes[i - 1]) << 1); + + for (i = 0; i < table_len; i++) { + mz_uint rev_code = 0, code, code_size; + if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) + continue; + code = next_code[code_size]++; + for (l = code_size; l > 0; l--, code >>= 1) + rev_code = (rev_code << 1) | (code & 1); + d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; + } +} + +#define TDEFL_PUT_BITS(b, l) \ + do { \ + mz_uint bits = b; \ + mz_uint len = l; \ + MZ_ASSERT(bits <= ((1U << len) - 1U)); \ + d->m_bit_buffer |= (bits << d->m_bits_in); \ + d->m_bits_in += len; \ + while (d->m_bits_in >= 8) { \ + if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ + *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ + d->m_bit_buffer >>= 8; \ + d->m_bits_in -= 8; \ + } \ + } \ + MZ_MACRO_END + +#define TDEFL_RLE_PREV_CODE_SIZE() \ + { \ + if (rle_repeat_count) { \ + if (rle_repeat_count < 3) { \ + d->m_huff_count[2][prev_code_size] = \ + (mz_uint16)(d->m_huff_count[2][prev_code_size] + \ + rle_repeat_count); \ + while (rle_repeat_count--) \ + packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ + } else { \ + d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 16; \ + packed_code_sizes[num_packed_code_sizes++] = \ + (mz_uint8)(rle_repeat_count - 3); \ + } \ + rle_repeat_count = 0; \ + } \ + } + +#define TDEFL_RLE_ZERO_CODE_SIZE() \ + { \ + if (rle_z_count) { \ + if (rle_z_count < 3) { \ + d->m_huff_count[2][0] = \ + (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ + while (rle_z_count--) \ + packed_code_sizes[num_packed_code_sizes++] = 0; \ + } else if (rle_z_count <= 10) { \ + d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 17; \ + packed_code_sizes[num_packed_code_sizes++] = \ + (mz_uint8)(rle_z_count - 3); \ + } else { \ + d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 18; \ + packed_code_sizes[num_packed_code_sizes++] = \ + (mz_uint8)(rle_z_count - 11); \ + } \ + rle_z_count = 0; \ + } \ + } + +static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { + 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + +static void tdefl_start_dynamic_block(tdefl_compressor* d) { + int num_lit_codes, num_dist_codes, num_bit_lengths; + mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, + rle_repeat_count, packed_code_sizes_index; + mz_uint8 + code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], + packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], + prev_code_size = 0xFF; + + d->m_huff_count[0][256] = 1; + + tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); + tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); + + for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) + if (d->m_huff_code_sizes[0][num_lit_codes - 1]) + break; + for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) + if (d->m_huff_code_sizes[1][num_dist_codes - 1]) + break; + + memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); + memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], + num_dist_codes); + total_code_sizes_to_pack = num_lit_codes + num_dist_codes; + num_packed_code_sizes = 0; + rle_z_count = 0; + rle_repeat_count = 0; + + memset(&d->m_huff_count[2][0], 0, + sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); + for (i = 0; i < total_code_sizes_to_pack; i++) { + mz_uint8 code_size = code_sizes_to_pack[i]; + if (!code_size) { + TDEFL_RLE_PREV_CODE_SIZE(); + if (++rle_z_count == 138) { + TDEFL_RLE_ZERO_CODE_SIZE(); + } + } + else { + TDEFL_RLE_ZERO_CODE_SIZE(); + if (code_size != prev_code_size) { + TDEFL_RLE_PREV_CODE_SIZE(); + d->m_huff_count[2][code_size] = + (mz_uint16)(d->m_huff_count[2][code_size] + 1); + packed_code_sizes[num_packed_code_sizes++] = code_size; + } + else if (++rle_repeat_count == 6) { + TDEFL_RLE_PREV_CODE_SIZE(); + } + } + prev_code_size = code_size; + } + if (rle_repeat_count) { + TDEFL_RLE_PREV_CODE_SIZE(); + } + else { + TDEFL_RLE_ZERO_CODE_SIZE(); + } + + tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); + + TDEFL_PUT_BITS(2, 2); + + TDEFL_PUT_BITS(num_lit_codes - 257, 5); + TDEFL_PUT_BITS(num_dist_codes - 1, 5); + + for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) + if (d->m_huff_code_sizes + [2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) + break; + num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); + TDEFL_PUT_BITS(num_bit_lengths - 4, 4); + for (i = 0; (int)i < num_bit_lengths; i++) + TDEFL_PUT_BITS( + d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); + + for (packed_code_sizes_index = 0; + packed_code_sizes_index < num_packed_code_sizes;) { + mz_uint code = packed_code_sizes[packed_code_sizes_index++]; + MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); + TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); + if (code >= 16) + TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], + "\02\03\07"[code - 16]); + } +} + +static void tdefl_start_static_block(tdefl_compressor* d) { + mz_uint i; + mz_uint8* p = &d->m_huff_code_sizes[0][0]; + + for (i = 0; i <= 143; ++i) + *p++ = 8; + for (; i <= 255; ++i) + *p++ = 9; + for (; i <= 279; ++i) + *p++ = 7; + for (; i <= 287; ++i) + *p++ = 8; + + memset(d->m_huff_code_sizes[1], 5, 32); + + tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); + tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); + + TDEFL_PUT_BITS(1, 2); +} + +static const mz_uint mz_bitmasks[17] = { + 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, + 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \ + MINIZ_HAS_64BIT_REGISTERS +static mz_bool tdefl_compress_lz_codes(tdefl_compressor* d) { + mz_uint flags; + mz_uint8* pLZ_codes; + mz_uint8* pOutput_buf = d->m_pOutput_buf; + mz_uint8* pLZ_code_buf_end = d->m_pLZ_code_buf; + mz_uint64 bit_buffer = d->m_bit_buffer; + mz_uint bits_in = d->m_bits_in; + +#define TDEFL_PUT_BITS_FAST(b, l) \ + { \ + bit_buffer |= (((mz_uint64)(b)) << bits_in); \ + bits_in += (l); \ + } + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; + flags >>= 1) { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + + if (flags & 1) { + mz_uint s0, s1, n0, n1, sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], + match_dist = *(const mz_uint16*)(pLZ_codes + 1); + pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], + d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], + s_tdefl_len_extra[match_len]); + + /* This sequence coaxes MSVC into using cmov's vs. jmp's. */ + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + n0 = s_tdefl_small_dist_extra[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[match_dist >> 8]; + n1 = s_tdefl_large_dist_extra[match_dist >> 8]; + sym = (match_dist < 512) ? s0 : s1; + num_extra_bits = (match_dist < 512) ? n0 : n1; + + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], + d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], + num_extra_bits); + } + else { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], + d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], + d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], + d->m_huff_code_sizes[0][lit]); + } + } + } + + if (pOutput_buf >= d->m_pOutput_buf_end) + return MZ_FALSE; + + *(mz_uint64*)pOutput_buf = bit_buffer; + pOutput_buf += (bits_in >> 3); + bit_buffer >>= (bits_in & ~7); + bits_in &= 7; + } + +#undef TDEFL_PUT_BITS_FAST + + d->m_pOutput_buf = pOutput_buf; + d->m_bits_in = 0; + d->m_bit_buffer = 0; + + while (bits_in) { + mz_uint32 n = MZ_MIN(bits_in, 16); + TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); + bit_buffer >>= n; + bits_in -= n; + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#else +static mz_bool tdefl_compress_lz_codes(tdefl_compressor* d) { + mz_uint flags; + mz_uint8* pLZ_codes; + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; + flags >>= 1) { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + if (flags & 1) { + mz_uint sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], + match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); + pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], + d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], + s_tdefl_len_extra[match_len]); + + if (match_dist < 512) { + sym = s_tdefl_small_dist_sym[match_dist]; + num_extra_bits = s_tdefl_small_dist_extra[match_dist]; + } + else { + sym = s_tdefl_large_dist_sym[match_dist >> 8]; + num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; + } + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \ + MINIZ_HAS_64BIT_REGISTERS */ + +static mz_bool tdefl_compress_block(tdefl_compressor* d, mz_bool static_block) { + if (static_block) + tdefl_start_static_block(d); + else + tdefl_start_dynamic_block(d); + return tdefl_compress_lz_codes(d); +} + +static int tdefl_flush_block(tdefl_compressor* d, int flush) { + mz_uint saved_bit_buf, saved_bits_in; + mz_uint8* pSaved_output_buf; + mz_bool comp_block_succeeded = MZ_FALSE; + int n, use_raw_block = + ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && + (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; + mz_uint8* pOutput_buf_start = + ((d->m_pPut_buf_func == NULL) && + ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) + ? ((mz_uint8*)d->m_pOut_buf + d->m_out_buf_ofs) + : d->m_output_buf; + + d->m_pOutput_buf = pOutput_buf_start; + d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; + + MZ_ASSERT(!d->m_output_flush_remaining); + d->m_output_flush_ofs = 0; + d->m_output_flush_remaining = 0; + + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); + d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); + + if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) { + TDEFL_PUT_BITS(0x78, 8); + TDEFL_PUT_BITS(0x01, 8); + } + + TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); + + pSaved_output_buf = d->m_pOutput_buf; + saved_bit_buf = d->m_bit_buffer; + saved_bits_in = d->m_bits_in; + + if (!use_raw_block) + comp_block_succeeded = + tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || + (d->m_total_lz_bytes < 48)); + + /* If the block gets expanded, forget the current contents of the output + * buffer and send a raw block instead. */ + if (((use_raw_block) || + ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= + d->m_total_lz_bytes))) && + ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) { + mz_uint i; + d->m_pOutput_buf = pSaved_output_buf; + d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + TDEFL_PUT_BITS(0, 2); + if (d->m_bits_in) { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) { + TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); + } + for (i = 0; i < d->m_total_lz_bytes; ++i) { + TDEFL_PUT_BITS( + d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], + 8); + } + } + /* Check for the extremely unlikely (if not impossible) case of the compressed + block not fitting into the output buffer when using dynamic codes. */ + else if (!comp_block_succeeded) { + d->m_pOutput_buf = pSaved_output_buf; + d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + tdefl_compress_block(d, MZ_TRUE); + } + + if (flush) { + if (flush == TDEFL_FINISH) { + if (d->m_bits_in) { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { + mz_uint i, a = d->m_adler32; + for (i = 0; i < 4; i++) { + TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); + a <<= 8; + } + } + } + else { + mz_uint i, z = 0; + TDEFL_PUT_BITS(0, 3); + if (d->m_bits_in) { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + for (i = 2; i; --i, z ^= 0xFFFF) { + TDEFL_PUT_BITS(z & 0xFFFF, 16); + } + } + } + + MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); + + memset(&d->m_huff_count[0][0], 0, + sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, + sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; + d->m_pLZ_flags = d->m_lz_code_buf; + d->m_num_flags_left = 8; + d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; + d->m_total_lz_bytes = 0; + d->m_block_index++; + + if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) { + if (d->m_pPut_buf_func) { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8*)d->m_pIn_buf; + if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) + return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); + } + else if (pOutput_buf_start == d->m_output_buf) { + int bytes_to_copy = (int)MZ_MIN( + (size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); + memcpy((mz_uint8*)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, + bytes_to_copy); + d->m_out_buf_ofs += bytes_to_copy; + if ((n -= bytes_to_copy) != 0) { + d->m_output_flush_ofs = bytes_to_copy; + d->m_output_flush_remaining = n; + } + } + else { + d->m_out_buf_ofs += n; + } + } + + return d->m_output_flush_remaining; +} + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES +#ifdef MINIZ_UNALIGNED_USE_MEMCPY +static mz_uint16 TDEFL_READ_UNALIGNED_WORD(const mz_uint8* p) { + mz_uint16 ret; + memcpy(&ret, p, sizeof(mz_uint16)); + return ret; +} +static mz_uint16 TDEFL_READ_UNALIGNED_WORD2(const mz_uint16* p) { + mz_uint16 ret; + memcpy(&ret, p, sizeof(mz_uint16)); + return ret; +} +#else +#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p) +#define TDEFL_READ_UNALIGNED_WORD2(p) *(const mz_uint16 *)(p) +#endif +static MZ_FORCEINLINE void +tdefl_find_match(tdefl_compressor* d, mz_uint lookahead_pos, mz_uint max_dist, + mz_uint max_match_len, mz_uint* pMatch_dist, + mz_uint* pMatch_len) { + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, + match_len = *pMatch_len, probe_pos = pos, next_probe_pos, + probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint16* s = (const mz_uint16*)(d->m_dict + pos), * p, * q; + mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), + s01 = TDEFL_READ_UNALIGNED_WORD2(s); + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); + if (max_match_len <= match_len) + return; + for (;;) { + for (;;) { + if (--num_probes_left == 0) + return; +#define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || \ + ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ + return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ + break; + TDEFL_PROBE; + TDEFL_PROBE; + TDEFL_PROBE; + } + if (!dist) + break; + q = (const mz_uint16*)(d->m_dict + probe_pos); + if (TDEFL_READ_UNALIGNED_WORD2(q) != s01) + continue; + p = s; + probe_len = 32; + do { + } while ( + (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && + (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && + (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && + (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && + (--probe_len > 0)); + if (!probe_len) { + *pMatch_dist = dist; + *pMatch_len = MZ_MIN(max_match_len, (mz_uint)TDEFL_MAX_MATCH_LEN); + break; + } + else if ((probe_len = ((mz_uint)(p - s) * 2) + + (mz_uint)(*(const mz_uint8*)p == + *(const mz_uint8*)q)) > match_len) { + *pMatch_dist = dist; + if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == + max_match_len) + break; + c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); + } + } +} +#else +static MZ_FORCEINLINE void +tdefl_find_match(tdefl_compressor* d, mz_uint lookahead_pos, mz_uint max_dist, + mz_uint max_match_len, mz_uint* pMatch_dist, + mz_uint* pMatch_len) { + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, + match_len = *pMatch_len, probe_pos = pos, next_probe_pos, + probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint8* s = d->m_dict + pos, * p, * q; + mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); + if (max_match_len <= match_len) + return; + for (;;) { + for (;;) { + if (--num_probes_left == 0) + return; +#define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || \ + ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ + return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if ((d->m_dict[probe_pos + match_len] == c0) && \ + (d->m_dict[probe_pos + match_len - 1] == c1)) \ + break; + TDEFL_PROBE; + TDEFL_PROBE; + TDEFL_PROBE; + } + if (!dist) + break; + p = s; + q = d->m_dict + probe_pos; + for (probe_len = 0; probe_len < max_match_len; probe_len++) + if (*p++ != *q++) + break; + if (probe_len > match_len) { + *pMatch_dist = dist; + if ((*pMatch_len = match_len = probe_len) == max_match_len) + return; + c0 = d->m_dict[pos + match_len]; + c1 = d->m_dict[pos + match_len - 1]; + } + } +} +#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES */ + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN +#ifdef MINIZ_UNALIGNED_USE_MEMCPY +static mz_uint32 TDEFL_READ_UNALIGNED_WORD32(const mz_uint8* p) { + mz_uint32 ret; + memcpy(&ret, p, sizeof(mz_uint32)); + return ret; +} +#else +#define TDEFL_READ_UNALIGNED_WORD32(p) *(const mz_uint32 *)(p) +#endif +static mz_bool tdefl_compress_fast(tdefl_compressor* d) { + /* Faster, minimally featured LZRW1-style match+parse loop with better + * register utilization. Intended for applications where raw throughput is + * valued more highly than ratio. */ + mz_uint lookahead_pos = d->m_lookahead_pos, + lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, + total_lz_bytes = d->m_total_lz_bytes, + num_flags_left = d->m_num_flags_left; + mz_uint8* pLZ_code_buf = d->m_pLZ_code_buf, * pLZ_flags = d->m_pLZ_flags; + mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + + while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) { + const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; + mz_uint dst_pos = + (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( + d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); + d->m_src_buf_left -= num_bytes_to_process; + lookahead_size += num_bytes_to_process; + + while (num_bytes_to_process) { + mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); + memcpy(d->m_dict + dst_pos, d->m_pSrc, n); + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, + MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); + d->m_pSrc += n; + dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; + num_bytes_to_process -= n; + } + + dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); + if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) + break; + + while (lookahead_size >= 4) { + mz_uint cur_match_dist, cur_match_len = 1; + mz_uint8* pCur_dict = d->m_dict + cur_pos; + mz_uint first_trigram = TDEFL_READ_UNALIGNED_WORD32(pCur_dict) & 0xFFFFFF; + mz_uint hash = + (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & + TDEFL_LEVEL1_HASH_SIZE_MASK; + mz_uint probe_pos = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)lookahead_pos; + + if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= + dict_size) && + ((TDEFL_READ_UNALIGNED_WORD32( + d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & + 0xFFFFFF) == first_trigram)) { + const mz_uint16* p = (const mz_uint16*)pCur_dict; + const mz_uint16* q = (const mz_uint16*)(d->m_dict + probe_pos); + mz_uint32 probe_len = 32; + do { + } while ((TDEFL_READ_UNALIGNED_WORD2(++p) == + TDEFL_READ_UNALIGNED_WORD2(++q)) && + (TDEFL_READ_UNALIGNED_WORD2(++p) == + TDEFL_READ_UNALIGNED_WORD2(++q)) && + (TDEFL_READ_UNALIGNED_WORD2(++p) == + TDEFL_READ_UNALIGNED_WORD2(++q)) && + (TDEFL_READ_UNALIGNED_WORD2(++p) == + TDEFL_READ_UNALIGNED_WORD2(++q)) && + (--probe_len > 0)); + cur_match_len = ((mz_uint)(p - (const mz_uint16*)pCur_dict) * 2) + + (mz_uint)(*(const mz_uint8*)p == *(const mz_uint8*)q); + if (!probe_len) + cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; + + if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || + ((cur_match_len == TDEFL_MIN_MATCH_LEN) && + (cur_match_dist >= 8U * 1024U))) { + cur_match_len = 1; + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + else { + mz_uint32 s0, s1; + cur_match_len = MZ_MIN(cur_match_len, lookahead_size); + + MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && + (cur_match_dist >= 1) && + (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); + + cur_match_dist--; + + pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); +#ifdef MINIZ_UNALIGNED_USE_MEMCPY + memcpy(&pLZ_code_buf[1], &cur_match_dist, sizeof(cur_match_dist)); +#else + * (mz_uint16*)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; +#endif + pLZ_code_buf += 3; + *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); + + s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; + s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; + d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; + + d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - + TDEFL_MIN_MATCH_LEN]]++; + } + } + else { + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + + if (--num_flags_left == 0) { + num_flags_left = 8; + pLZ_flags = pLZ_code_buf++; + } + + total_lz_bytes += cur_match_len; + lookahead_pos += cur_match_len; + dict_size = + MZ_MIN(dict_size + cur_match_len, (mz_uint)TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; + MZ_ASSERT(lookahead_size >= cur_match_len); + lookahead_size -= cur_match_len; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { + int n; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; + pLZ_code_buf = d->m_pLZ_code_buf; + pLZ_flags = d->m_pLZ_flags; + num_flags_left = d->m_num_flags_left; + } + } + + while (lookahead_size) { + mz_uint8 lit = d->m_dict[cur_pos]; + + total_lz_bytes++; + *pLZ_code_buf++ = lit; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + if (--num_flags_left == 0) { + num_flags_left = 8; + pLZ_flags = pLZ_code_buf++; + } + + d->m_huff_count[0][lit]++; + + lookahead_pos++; + dict_size = MZ_MIN(dict_size + 1, (mz_uint)TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + lookahead_size--; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { + int n; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; + pLZ_code_buf = d->m_pLZ_code_buf; + pLZ_flags = d->m_pLZ_flags; + num_flags_left = d->m_num_flags_left; + } + } + } + + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + return MZ_TRUE; +} +#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ + +static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor* d, + mz_uint8 lit) { + d->m_total_lz_bytes++; + *d->m_pLZ_code_buf++ = lit; + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); + if (--d->m_num_flags_left == 0) { + d->m_num_flags_left = 8; + d->m_pLZ_flags = d->m_pLZ_code_buf++; + } + d->m_huff_count[0][lit]++; +} + +static MZ_FORCEINLINE void +tdefl_record_match(tdefl_compressor* d, mz_uint match_len, mz_uint match_dist) { + mz_uint32 s0, s1; + + MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && + (match_dist <= TDEFL_LZ_DICT_SIZE)); + + d->m_total_lz_bytes += match_len; + + d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); + + match_dist -= 1; + d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); + d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); + d->m_pLZ_code_buf += 3; + + *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); + if (--d->m_num_flags_left == 0) { + d->m_num_flags_left = 8; + d->m_pLZ_flags = d->m_pLZ_code_buf++; + } + + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; + d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; + d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; +} + +static mz_bool tdefl_compress_normal(tdefl_compressor* d) { + const mz_uint8* pSrc = d->m_pSrc; + size_t src_buf_left = d->m_src_buf_left; + tdefl_flush flush = d->m_flush; + + while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) { + mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; + /* Update dictionary and hash chains. Keeps the lookahead size equal to + * TDEFL_MAX_MATCH_LEN. */ + if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) { + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & + TDEFL_LZ_DICT_SIZE_MASK, + ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; + mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] + << TDEFL_LZ_HASH_SHIFT) ^ + d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( + src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); + const mz_uint8* pSrc_end = pSrc + num_bytes_to_process; + src_buf_left -= num_bytes_to_process; + d->m_lookahead_size += num_bytes_to_process; + while (pSrc != pSrc_end) { + mz_uint8 c = *pSrc++; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)(ins_pos); + dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + ins_pos++; + } + } + else { + while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) { + mz_uint8 c = *pSrc++; + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & + TDEFL_LZ_DICT_SIZE_MASK; + src_buf_left--; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) { + mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; + mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] + << (TDEFL_LZ_HASH_SHIFT * 2)) ^ + (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] + << TDEFL_LZ_HASH_SHIFT) ^ + c) & + (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)(ins_pos); + } + } + } + d->m_dict_size = + MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); + if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + break; + + /* Simple lazy/greedy parsing state machine. */ + len_to_move = 1; + cur_match_dist = 0; + cur_match_len = + d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); + cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) { + if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) { + mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; + cur_match_len = 0; + while (cur_match_len < d->m_lookahead_size) { + if (d->m_dict[cur_pos + cur_match_len] != c) + break; + cur_match_len++; + } + if (cur_match_len < TDEFL_MIN_MATCH_LEN) + cur_match_len = 0; + else + cur_match_dist = 1; + } + } + else { + tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, + d->m_lookahead_size, &cur_match_dist, &cur_match_len); + } + if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && + (cur_match_dist >= 8U * 1024U)) || + (cur_pos == cur_match_dist) || + ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) { + cur_match_dist = cur_match_len = 0; + } + if (d->m_saved_match_len) { + if (cur_match_len > d->m_saved_match_len) { + tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); + if (cur_match_len >= 128) { + tdefl_record_match(d, cur_match_len, cur_match_dist); + d->m_saved_match_len = 0; + len_to_move = cur_match_len; + } + else { + d->m_saved_lit = d->m_dict[cur_pos]; + d->m_saved_match_dist = cur_match_dist; + d->m_saved_match_len = cur_match_len; + } + } + else { + tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); + len_to_move = d->m_saved_match_len - 1; + d->m_saved_match_len = 0; + } + } + else if (!cur_match_dist) + tdefl_record_literal(d, + d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); + else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || + (cur_match_len >= 128)) { + tdefl_record_match(d, cur_match_len, cur_match_dist); + len_to_move = cur_match_len; + } + else { + d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; + d->m_saved_match_dist = cur_match_dist; + d->m_saved_match_len = cur_match_len; + } + /* Move the lookahead forward by len_to_move bytes. */ + d->m_lookahead_pos += len_to_move; + MZ_ASSERT(d->m_lookahead_size >= len_to_move); + d->m_lookahead_size -= len_to_move; + d->m_dict_size = + MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE); + /* Check if it's time to flush the current LZ codes to the internal output + * buffer. */ + if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || + ((d->m_total_lz_bytes > 31 * 1024) && + (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= + d->m_total_lz_bytes) || + (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) { + int n; + d->m_pSrc = pSrc; + d->m_src_buf_left = src_buf_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + } + } + + d->m_pSrc = pSrc; + d->m_src_buf_left = src_buf_left; + return MZ_TRUE; +} + +static tdefl_status tdefl_flush_output_buffer(tdefl_compressor* d) { + if (d->m_pIn_buf_size) { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8*)d->m_pIn_buf; + } + + if (d->m_pOut_buf_size) { + size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, + d->m_output_flush_remaining); + memcpy((mz_uint8*)d->m_pOut_buf + d->m_out_buf_ofs, + d->m_output_buf + d->m_output_flush_ofs, n); + d->m_output_flush_ofs += (mz_uint)n; + d->m_output_flush_remaining -= (mz_uint)n; + d->m_out_buf_ofs += n; + + *d->m_pOut_buf_size = d->m_out_buf_ofs; + } + + return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE + : TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_compress(tdefl_compressor* d, const void* pIn_buf, + size_t* pIn_buf_size, void* pOut_buf, + size_t* pOut_buf_size, tdefl_flush flush) { + if (!d) { + if (pIn_buf_size) + *pIn_buf_size = 0; + if (pOut_buf_size) + *pOut_buf_size = 0; + return TDEFL_STATUS_BAD_PARAM; + } + + d->m_pIn_buf = pIn_buf; + d->m_pIn_buf_size = pIn_buf_size; + d->m_pOut_buf = pOut_buf; + d->m_pOut_buf_size = pOut_buf_size; + d->m_pSrc = (const mz_uint8*)(pIn_buf); + d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; + d->m_out_buf_ofs = 0; + d->m_flush = flush; + + if (((d->m_pPut_buf_func != NULL) == + ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || + (d->m_prev_return_status != TDEFL_STATUS_OKAY) || + (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || + (pIn_buf_size && *pIn_buf_size && !pIn_buf) || + (pOut_buf_size && *pOut_buf_size && !pOut_buf)) { + if (pIn_buf_size) + *pIn_buf_size = 0; + if (pOut_buf_size) + *pOut_buf_size = 0; + return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); + } + d->m_wants_to_finish |= (flush == TDEFL_FINISH); + + if ((d->m_output_flush_remaining) || (d->m_finished)) + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && + ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && + ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | + TDEFL_RLE_MATCHES)) == 0)) { + if (!tdefl_compress_fast(d)) + return d->m_prev_return_status; + } + else +#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ + { + if (!tdefl_compress_normal(d)) + return d->m_prev_return_status; + } + + if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && + (pIn_buf)) + d->m_adler32 = + (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8*)pIn_buf, + d->m_pSrc - (const mz_uint8*)pIn_buf); + + if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && + (!d->m_output_flush_remaining)) { + if (tdefl_flush_block(d, flush) < 0) + return d->m_prev_return_status; + d->m_finished = (flush == TDEFL_FINISH); + if (flush == TDEFL_FULL_FLUSH) { + MZ_CLEAR_OBJ(d->m_hash); + MZ_CLEAR_OBJ(d->m_next); + d->m_dict_size = 0; + } + } + + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); +} + +tdefl_status tdefl_compress_buffer(tdefl_compressor* d, const void* pIn_buf, + size_t in_buf_size, tdefl_flush flush) { + MZ_ASSERT(d->m_pPut_buf_func); + return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); +} + +tdefl_status tdefl_init(tdefl_compressor* d, + tdefl_put_buf_func_ptr pPut_buf_func, + void* pPut_buf_user, int flags) { + d->m_pPut_buf_func = pPut_buf_func; + d->m_pPut_buf_user = pPut_buf_user; + d->m_flags = (mz_uint)(flags); + d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; + d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; + d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) + MZ_CLEAR_OBJ(d->m_hash); + d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = + d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; + d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = + d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; + d->m_pLZ_flags = d->m_lz_code_buf; + *d->m_pLZ_flags = 0; + d->m_num_flags_left = 8; + d->m_pOutput_buf = d->m_output_buf; + d->m_pOutput_buf_end = d->m_output_buf; + d->m_prev_return_status = TDEFL_STATUS_OKAY; + d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; + d->m_adler32 = 1; + d->m_pIn_buf = NULL; + d->m_pOut_buf = NULL; + d->m_pIn_buf_size = NULL; + d->m_pOut_buf_size = NULL; + d->m_flush = TDEFL_NO_FLUSH; + d->m_pSrc = NULL; + d->m_src_buf_left = 0; + d->m_out_buf_ofs = 0; + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) + MZ_CLEAR_OBJ(d->m_dict); + memset(&d->m_huff_count[0][0], 0, + sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, + sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + return TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor* d) { + return d->m_prev_return_status; +} + +mz_uint32 tdefl_get_adler32(tdefl_compressor* d) { return d->m_adler32; } + +mz_bool tdefl_compress_mem_to_output(const void* pBuf, size_t buf_len, + tdefl_put_buf_func_ptr pPut_buf_func, + void* pPut_buf_user, int flags) { + tdefl_compressor* pComp; + mz_bool succeeded; + if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) + return MZ_FALSE; + pComp = (tdefl_compressor*)MZ_MALLOC(sizeof(tdefl_compressor)); + if (!pComp) + return MZ_FALSE; + succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == + TDEFL_STATUS_OKAY); + succeeded = + succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == + TDEFL_STATUS_DONE); + MZ_FREE(pComp); + return succeeded; +} + +typedef struct { + size_t m_size, m_capacity; + mz_uint8* m_pBuf; + mz_bool m_expandable; +} tdefl_output_buffer; + +static mz_bool tdefl_output_buffer_putter(const void* pBuf, int len, + void* pUser) { + tdefl_output_buffer* p = (tdefl_output_buffer*)pUser; + size_t new_size = p->m_size + len; + if (new_size > p->m_capacity) { + size_t new_capacity = p->m_capacity; + mz_uint8* pNew_buf; + if (!p->m_expandable) + return MZ_FALSE; + do { + new_capacity = MZ_MAX(128U, new_capacity << 1U); + } while (new_size > new_capacity); + pNew_buf = (mz_uint8*)MZ_REALLOC(p->m_pBuf, new_capacity); + if (!pNew_buf) + return MZ_FALSE; + p->m_pBuf = pNew_buf; + p->m_capacity = new_capacity; + } + memcpy((mz_uint8*)p->m_pBuf + p->m_size, pBuf, len); + p->m_size = new_size; + return MZ_TRUE; +} + +void* tdefl_compress_mem_to_heap(const void* pSrc_buf, size_t src_buf_len, + size_t* pOut_len, int flags) { + tdefl_output_buffer out_buf; + MZ_CLEAR_OBJ(out_buf); + if (!pOut_len) + return MZ_FALSE; + else + *pOut_len = 0; + out_buf.m_expandable = MZ_TRUE; + if (!tdefl_compress_mem_to_output( + pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + return NULL; + *pOut_len = out_buf.m_size; + return out_buf.m_pBuf; +} + +size_t tdefl_compress_mem_to_mem(void* pOut_buf, size_t out_buf_len, + const void* pSrc_buf, size_t src_buf_len, + int flags) { + tdefl_output_buffer out_buf; + MZ_CLEAR_OBJ(out_buf); + if (!pOut_buf) + return 0; + out_buf.m_pBuf = (mz_uint8*)pOut_buf; + out_buf.m_capacity = out_buf_len; + if (!tdefl_compress_mem_to_output( + pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + return 0; + return out_buf.m_size; +} + +static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, + 128, 256, 512, 768, 1500 }; + +/* level may actually range from [0,10] (10 is a "hidden" max level, where we + * want a bit more compression and it's fine if throughput to fall off a cliff + * on some files). */ +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, + int strategy) { + mz_uint comp_flags = + s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | + ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); + if (window_bits > 0) + comp_flags |= TDEFL_WRITE_ZLIB_HEADER; + + if (!level) + comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; + else if (strategy == MZ_FILTERED) + comp_flags |= TDEFL_FILTER_MATCHES; + else if (strategy == MZ_HUFFMAN_ONLY) + comp_flags &= ~TDEFL_MAX_PROBES_MASK; + else if (strategy == MZ_FIXED) + comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; + else if (strategy == MZ_RLE) + comp_flags |= TDEFL_RLE_MATCHES; + + return comp_flags; +} + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4204) /* nonstandard extension used : non-constant \ + aggregate initializer (also supported by \ + GNU C and C99, so no big deal) */ +#endif + +/* Simple PNG writer function by Alex Evans, 2011. Released into the public + domain: https://gist.github.com/908299, more context at + http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. + This is actually a modification of Alex's original code so PNG files generated + by this function pass pngcheck. */ +void* tdefl_write_image_to_png_file_in_memory_ex(const void* pImage, int w, + int h, int num_chans, + size_t* pLen_out, + mz_uint level, mz_bool flip) { + /* Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was + * defined. */ + static const mz_uint s_tdefl_png_num_probes[11] = { + 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + tdefl_compressor* pComp = + (tdefl_compressor*)MZ_MALLOC(sizeof(tdefl_compressor)); + tdefl_output_buffer out_buf; + int i, bpl = w * num_chans, y, z; + mz_uint32 c; + *pLen_out = 0; + if (!pComp) + return NULL; + MZ_CLEAR_OBJ(out_buf); + out_buf.m_expandable = MZ_TRUE; + out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); + if (NULL == (out_buf.m_pBuf = (mz_uint8*)MZ_MALLOC(out_buf.m_capacity))) { + MZ_FREE(pComp); + return NULL; + } + /* write dummy header */ + for (z = 41; z; --z) + tdefl_output_buffer_putter(&z, 1, &out_buf); + /* compress image data */ + tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, + s_tdefl_png_num_probes[MZ_MIN(10, level)] | + TDEFL_WRITE_ZLIB_HEADER); + for (y = 0; y < h; ++y) { + tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); + tdefl_compress_buffer(pComp, + (mz_uint8*)pImage + (flip ? (h - 1 - y) : y) * bpl, + bpl, TDEFL_NO_FLUSH); + } + if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != + TDEFL_STATUS_DONE) { + MZ_FREE(pComp); + MZ_FREE(out_buf.m_pBuf); + return NULL; + } + /* write real header */ + *pLen_out = out_buf.m_size - 41; + { + static const mz_uint8 chans[] = { 0x00, 0x00, 0x04, 0x02, 0x06 }; + mz_uint8 pnghdr[41] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, + 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x49, 0x44, 0x41, 0x54 }; + pnghdr[18] = (mz_uint8)(w >> 8); + pnghdr[19] = (mz_uint8)w; + pnghdr[22] = (mz_uint8)(h >> 8); + pnghdr[23] = (mz_uint8)h; + pnghdr[25] = chans[num_chans]; + pnghdr[33] = (mz_uint8)(*pLen_out >> 24); + pnghdr[34] = (mz_uint8)(*pLen_out >> 16); + pnghdr[35] = (mz_uint8)(*pLen_out >> 8); + pnghdr[36] = (mz_uint8)*pLen_out; + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); + for (i = 0; i < 4; ++i, c <<= 8) + ((mz_uint8*)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); + memcpy(out_buf.m_pBuf, pnghdr, 41); + } + /* write footer (IDAT CRC-32, followed by IEND chunk) */ + if (!tdefl_output_buffer_putter( + "\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { + *pLen_out = 0; + MZ_FREE(pComp); + MZ_FREE(out_buf.m_pBuf); + return NULL; + } + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, + *pLen_out + 4); + for (i = 0; i < 4; ++i, c <<= 8) + (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); + /* compute final size of file, grab compressed data buffer and return */ + *pLen_out += 57; + MZ_FREE(pComp); + return out_buf.m_pBuf; +} +void* tdefl_write_image_to_png_file_in_memory(const void* pImage, int w, int h, + int num_chans, size_t* pLen_out) { + /* Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we + * can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's + * where #defined out) */ + return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, + pLen_out, 6, MZ_FALSE); +} + +#ifndef MINIZ_NO_MALLOC +/* Allocate the tdefl_compressor and tinfl_decompressor structures in C so that + */ + /* non-C language bindings to tdefL_ and tinfl_ API don't need to worry about */ + /* structure size and allocation mechanism. */ +tdefl_compressor* tdefl_compressor_alloc() { + return (tdefl_compressor*)MZ_MALLOC(sizeof(tdefl_compressor)); +} + +void tdefl_compressor_free(tdefl_compressor* pComp) { MZ_FREE(pComp); } +#endif + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + + +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + + /* ------------------- Low-level Decompression (completely independent from all + * compression API's) */ + +#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) +#define TINFL_MEMSET(p, c, l) memset(p, c, l) + +#define TINFL_CR_BEGIN \ + switch (r->m_state) { \ + case 0: +#define TINFL_CR_RETURN(state_index, result) \ + do { \ + status = result; \ + r->m_state = state_index; \ + goto common_exit; \ + case state_index:; \ + } \ + MZ_MACRO_END +#define TINFL_CR_RETURN_FOREVER(state_index, result) \ + do { \ + for (;;) { \ + TINFL_CR_RETURN(state_index, result); \ + } \ + } \ + MZ_MACRO_END +#define TINFL_CR_FINISH } + +#define TINFL_GET_BYTE(state_index, c) \ + do { \ + while (pIn_buf_cur >= pIn_buf_end) { \ + TINFL_CR_RETURN(state_index, \ + (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) \ + ? TINFL_STATUS_NEEDS_MORE_INPUT \ + : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); \ + } \ + c = *pIn_buf_cur++; \ + } \ + MZ_MACRO_END + +#define TINFL_NEED_BITS(state_index, n) \ + do { \ + mz_uint c; \ + TINFL_GET_BYTE(state_index, c); \ + bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ + num_bits += 8; \ + } while (num_bits < (mz_uint)(n)) +#define TINFL_SKIP_BITS(state_index, n) \ + do { \ + if (num_bits < (mz_uint)(n)) { \ + TINFL_NEED_BITS(state_index, n); \ + } \ + bit_buf >>= (n); \ + num_bits -= (n); \ + } \ + MZ_MACRO_END +#define TINFL_GET_BITS(state_index, b, n) \ + do { \ + if (num_bits < (mz_uint)(n)) { \ + TINFL_NEED_BITS(state_index, n); \ + } \ + b = bit_buf & ((1 << (n)) - 1); \ + bit_buf >>= (n); \ + num_bits -= (n); \ + } \ + MZ_MACRO_END + + /* TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes + * remaining in the input buffer falls below 2. */ + /* It reads just enough bytes from the input stream that are needed to decode + * the next Huffman code (and absolutely no more). It works by trying to fully + * decode a */ + /* Huffman code by using whatever bits are currently present in the bit buffer. + * If this fails, it reads another byte, and tries again until it succeeds or + * until the */ + /* bit buffer contains >=15 bits (deflate's max. Huffman code size). */ +#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ + do { \ + temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ + if (temp >= 0) { \ + code_len = temp >> 9; \ + if ((code_len) && (num_bits >= code_len)) \ + break; \ + } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do { \ + temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while ((temp < 0) && (num_bits >= (code_len + 1))); \ + if (temp >= 0) \ + break; \ + } \ + TINFL_GET_BYTE(state_index, c); \ + bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ + num_bits += 8; \ + } while (num_bits < 15); + +/* TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex + * than you would initially expect because the zlib API expects the decompressor + * to never read */ + /* beyond the final byte of the deflate stream. (In other words, when this macro + * wants to read another byte from the input, it REALLY needs another byte in + * order to fully */ + /* decode the next Huffman code.) Handling this properly is particularly + * important on raw deflate (non-zlib) streams, which aren't followed by a byte + * aligned adler-32. */ + /* The slow path is only executed at the very end of the input buffer. */ + /* v1.16: The original macro handled the case at the very end of the passed-in + * input buffer, but we also need to handle the case where the user passes in + * 1+zillion bytes */ + /* following the deflate data and our non-conservative read-ahead path won't + * kick in here on this code. This is much trickier. */ +#define TINFL_HUFF_DECODE(state_index, sym, pHuff) \ + do { \ + int temp; \ + mz_uint code_len, c; \ + if (num_bits < 15) { \ + if ((pIn_buf_end - pIn_buf_cur) < 2) { \ + TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ + } else { \ + bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | \ + (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ + pIn_buf_cur += 2; \ + num_bits += 16; \ + } \ + } \ + if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= \ + 0) \ + code_len = temp >> 9, temp &= 511; \ + else { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do { \ + temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while (temp < 0); \ + } \ + sym = temp; \ + bit_buf >>= code_len; \ + num_bits -= code_len; \ + } \ + MZ_MACRO_END + +tinfl_status tinfl_decompress(tinfl_decompressor* r, + const mz_uint8* pIn_buf_next, + size_t* pIn_buf_size, mz_uint8* pOut_buf_start, + mz_uint8* pOut_buf_next, size_t* pOut_buf_size, + const mz_uint32 decomp_flags) { + static const int s_length_base[31] = { + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 }; + static const int s_length_extra[31] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, + 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, + 4, 4, 5, 5, 5, 5, 0, 0, 0 }; + static const int s_dist_base[32] = { + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, + 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, + 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 }; + static const int s_dist_extra[32] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, + 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, + 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; + static const mz_uint8 s_length_dezigzag[19] = { + 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + static const int s_min_table_sizes[3] = { 257, 1, 4 }; + + tinfl_status status = TINFL_STATUS_FAILED; + mz_uint32 num_bits, dist, counter, num_extra; + tinfl_bit_buf_t bit_buf; + const mz_uint8* pIn_buf_cur = pIn_buf_next, * const pIn_buf_end = + pIn_buf_next + *pIn_buf_size; + mz_uint8* pOut_buf_cur = pOut_buf_next, * const pOut_buf_end = + pOut_buf_next + *pOut_buf_size; + size_t out_buf_size_mask = + (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) + ? (size_t)-1 + : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, + dist_from_out_buf_start; + + /* Ensure the output buffer's size is a power of 2, unless the output buffer + * is large enough to hold the entire output file (in which case it doesn't + * matter). */ + if (((out_buf_size_mask + 1) & out_buf_size_mask) || + (pOut_buf_next < pOut_buf_start)) { + *pIn_buf_size = *pOut_buf_size = 0; + return TINFL_STATUS_BAD_PARAM; + } + + num_bits = r->m_num_bits; + bit_buf = r->m_bit_buf; + dist = r->m_dist; + counter = r->m_counter; + num_extra = r->m_num_extra; + dist_from_out_buf_start = r->m_dist_from_out_buf_start; + TINFL_CR_BEGIN + + bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; + r->m_z_adler32 = r->m_check_adler32 = 1; + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { + TINFL_GET_BYTE(1, r->m_zhdr0); + TINFL_GET_BYTE(2, r->m_zhdr1); + counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || + (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); + if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || + ((out_buf_size_mask + 1) < + (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); + if (counter) { + TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); + } + } + + do { + TINFL_GET_BITS(3, r->m_final, 3); + r->m_type = r->m_final >> 1; + if (r->m_type == 0) { + TINFL_SKIP_BITS(5, num_bits & 7); + for (counter = 0; counter < 4; ++counter) { + if (num_bits) + TINFL_GET_BITS(6, r->m_raw_header[counter], 8); + else + TINFL_GET_BYTE(7, r->m_raw_header[counter]); + } + if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != + (mz_uint)(0xFFFF ^ + (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { + TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); + } + while ((counter) && (num_bits)) { + TINFL_GET_BITS(51, dist, 8); + while (pOut_buf_cur >= pOut_buf_end) { + TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = (mz_uint8)dist; + counter--; + } + while (counter) { + size_t n; + while (pOut_buf_cur >= pOut_buf_end) { + TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); + } + while (pIn_buf_cur >= pIn_buf_end) { + TINFL_CR_RETURN(38, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) + ? TINFL_STATUS_NEEDS_MORE_INPUT + : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); + } + n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), + (size_t)(pIn_buf_end - pIn_buf_cur)), + counter); + TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); + pIn_buf_cur += n; + pOut_buf_cur += n; + counter -= (mz_uint)n; + } + } + else if (r->m_type == 3) { + TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); + } + else { + if (r->m_type == 1) { + mz_uint8* p = r->m_tables[0].m_code_size; + mz_uint i; + r->m_table_sizes[0] = 288; + r->m_table_sizes[1] = 32; + TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); + for (i = 0; i <= 143; ++i) + *p++ = 8; + for (; i <= 255; ++i) + *p++ = 9; + for (; i <= 279; ++i) + *p++ = 7; + for (; i <= 287; ++i) + *p++ = 8; + } + else { + for (counter = 0; counter < 3; counter++) { + TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); + r->m_table_sizes[counter] += s_min_table_sizes[counter]; + } + MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); + for (counter = 0; counter < r->m_table_sizes[2]; counter++) { + mz_uint s; + TINFL_GET_BITS(14, s, 3); + r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; + } + r->m_table_sizes[2] = 19; + } + for (; (int)r->m_type >= 0; r->m_type--) { + int tree_next, tree_cur; + tinfl_huff_table* pTable; + mz_uint i, j, used_syms, total, sym_index, next_code[17], + total_syms[16]; + pTable = &r->m_tables[r->m_type]; + MZ_CLEAR_OBJ(total_syms); + MZ_CLEAR_OBJ(pTable->m_look_up); + MZ_CLEAR_OBJ(pTable->m_tree); + for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) + total_syms[pTable->m_code_size[i]]++; + used_syms = 0, total = 0; + next_code[0] = next_code[1] = 0; + for (i = 1; i <= 15; ++i) { + used_syms += total_syms[i]; + next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); + } + if ((65536 != total) && (used_syms > 1)) { + TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); + } + for (tree_next = -1, sym_index = 0; + sym_index < r->m_table_sizes[r->m_type]; ++sym_index) { + mz_uint rev_code = 0, l, cur_code, + code_size = pTable->m_code_size[sym_index]; + + if (!code_size) + continue; + cur_code = next_code[code_size]++; + for (l = code_size; l > 0; l--, cur_code >>= 1) + rev_code = (rev_code << 1) | (cur_code & 1); + if (code_size <= TINFL_FAST_LOOKUP_BITS) { + mz_int16 k = (mz_int16)((code_size << 9) | sym_index); + while (rev_code < TINFL_FAST_LOOKUP_SIZE) { + pTable->m_look_up[rev_code] = k; + rev_code += (1 << code_size); + } + continue; + } + if (0 == + (tree_cur = pTable->m_look_up[rev_code & + (TINFL_FAST_LOOKUP_SIZE - 1)])) { + pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = + (mz_int16)tree_next; + tree_cur = tree_next; + tree_next -= 2; + } + rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); + for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) { + tree_cur -= ((rev_code >>= 1) & 1); + if (!pTable->m_tree[-tree_cur - 1]) { + pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; + tree_cur = tree_next; + tree_next -= 2; + } + else + tree_cur = pTable->m_tree[-tree_cur - 1]; + } + tree_cur -= ((rev_code >>= 1) & 1); + (void)rev_code; // unused + pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; + } + if (r->m_type == 2) { + for (counter = 0; + counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) { + mz_uint s; + TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); + if (dist < 16) { + r->m_len_codes[counter++] = (mz_uint8)dist; + continue; + } + if ((dist == 16) && (!counter)) { + TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); + } + num_extra = "\02\03\07"[dist - 16]; + TINFL_GET_BITS(18, s, num_extra); + s += "\03\03\013"[dist - 16]; + TINFL_MEMSET(r->m_len_codes + counter, + (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); + counter += s; + } + if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) { + TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); + } + TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, + r->m_table_sizes[0]); + TINFL_MEMCPY(r->m_tables[1].m_code_size, + r->m_len_codes + r->m_table_sizes[0], + r->m_table_sizes[1]); + } + } + for (;;) { + mz_uint8* pSrc; + for (;;) { + if (((pIn_buf_end - pIn_buf_cur) < 4) || + ((pOut_buf_end - pOut_buf_cur) < 2)) { + TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); + if (counter >= 256) + break; + while (pOut_buf_cur >= pOut_buf_end) { + TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = (mz_uint8)counter; + } + else { + int sym2; + mz_uint code_len; +#if TINFL_USE_64BIT_BITBUF + if (num_bits < 30) { + bit_buf |= + (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 4; + num_bits += 32; + } +#else + if (num_bits < 15) { + bit_buf |= + (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 2; + num_bits += 16; + } +#endif + if ((sym2 = + r->m_tables[0] + .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= + 0) + code_len = sym2 >> 9; + else { + code_len = TINFL_FAST_LOOKUP_BITS; + do { + sym2 = r->m_tables[0] + .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; + } while (sym2 < 0); + } + counter = sym2; + bit_buf >>= code_len; + num_bits -= code_len; + if (counter & 256) + break; + +#if !TINFL_USE_64BIT_BITBUF + if (num_bits < 15) { + bit_buf |= + (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 2; + num_bits += 16; + } +#endif + if ((sym2 = + r->m_tables[0] + .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= + 0) + code_len = sym2 >> 9; + else { + code_len = TINFL_FAST_LOOKUP_BITS; + do { + sym2 = r->m_tables[0] + .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; + } while (sym2 < 0); + } + bit_buf >>= code_len; + num_bits -= code_len; + + pOut_buf_cur[0] = (mz_uint8)counter; + if (sym2 & 256) { + pOut_buf_cur++; + counter = sym2; + break; + } + pOut_buf_cur[1] = (mz_uint8)sym2; + pOut_buf_cur += 2; + } + } + if ((counter &= 511) == 256) + break; + + num_extra = s_length_extra[counter - 257]; + counter = s_length_base[counter - 257]; + if (num_extra) { + mz_uint extra_bits; + TINFL_GET_BITS(25, extra_bits, num_extra); + counter += extra_bits; + } + + TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); + num_extra = s_dist_extra[dist]; + dist = s_dist_base[dist]; + if (num_extra) { + mz_uint extra_bits; + TINFL_GET_BITS(27, extra_bits, num_extra); + dist += extra_bits; + } + + dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; + if ((dist == 0 || dist > dist_from_out_buf_start || + dist_from_out_buf_start == 0) && + (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { + TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); + } + + pSrc = pOut_buf_start + + ((dist_from_out_buf_start - dist) & out_buf_size_mask); + + if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) { + while (counter--) { + while (pOut_buf_cur >= pOut_buf_end) { + TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = + pOut_buf_start[(dist_from_out_buf_start++ - dist) & + out_buf_size_mask]; + } + continue; + } +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES + else if ((counter >= 9) && (counter <= dist)) { + const mz_uint8* pSrc_end = pSrc + (counter & ~7); + do { +#ifdef MINIZ_UNALIGNED_USE_MEMCPY + memcpy(pOut_buf_cur, pSrc, sizeof(mz_uint32) * 2); +#else + ((mz_uint32*)pOut_buf_cur)[0] = ((const mz_uint32*)pSrc)[0]; + ((mz_uint32*)pOut_buf_cur)[1] = ((const mz_uint32*)pSrc)[1]; +#endif + pOut_buf_cur += 8; + } while ((pSrc += 8) < pSrc_end); + if ((counter &= 7) < 3) { + if (counter) { + pOut_buf_cur[0] = pSrc[0]; + if (counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + continue; + } + } +#endif + while (counter > 2) { + pOut_buf_cur[0] = pSrc[0]; + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur[2] = pSrc[2]; + pOut_buf_cur += 3; + pSrc += 3; + counter -= 3; + } + if (counter > 0) { + pOut_buf_cur[0] = pSrc[0]; + if (counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + } + } + } while (!(r->m_final & 1)); + + /* Ensure byte alignment and put back any bytes from the bitbuf if we've + * looked ahead too far on gzip, or other Deflate streams followed by + * arbitrary data. */ + /* I'm being super conservative here. A number of simplifications can be made + * to the byte alignment part, and the Adler32 check shouldn't ever need to + * worry about reading from the bitbuf now. */ + TINFL_SKIP_BITS(32, num_bits & 7); + while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) { + --pIn_buf_cur; + num_bits -= 8; + } + bit_buf &= (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1); + MZ_ASSERT(!num_bits); /* if this assert fires then we've read beyond the end + of non-deflate/zlib streams with following data (such + as gzip streams). */ + + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { + for (counter = 0; counter < 4; ++counter) { + mz_uint s; + if (num_bits) + TINFL_GET_BITS(41, s, 8); + else + TINFL_GET_BYTE(42, s); + r->m_z_adler32 = (r->m_z_adler32 << 8) | s; + } + } + TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); + + TINFL_CR_FINISH + + common_exit : + /* As long as we aren't telling the caller that we NEED more input to make + * forward progress: */ + /* Put back any bytes from the bitbuf in case we've looked ahead too far on + * gzip, or other Deflate streams followed by arbitrary data. */ + /* We need to be very careful here to NOT push back any bytes we definitely + * know we need to make forward progress, though, or we'll lock the caller up + * into an inf loop. */ + if ((status != TINFL_STATUS_NEEDS_MORE_INPUT) && + (status != TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS)) { + while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) { + --pIn_buf_cur; + num_bits -= 8; + } + } + r->m_num_bits = num_bits; + r->m_bit_buf = + bit_buf & (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1); + r->m_dist = dist; + r->m_counter = counter; + r->m_num_extra = num_extra; + r->m_dist_from_out_buf_start = dist_from_out_buf_start; + *pIn_buf_size = pIn_buf_cur - pIn_buf_next; + *pOut_buf_size = pOut_buf_cur - pOut_buf_next; + if ((decomp_flags & + (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && + (status >= 0)) { + const mz_uint8* ptr = pOut_buf_next; + size_t buf_len = *pOut_buf_size; + mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, + s2 = r->m_check_adler32 >> 16; + size_t block_len = buf_len % 5552; + while (buf_len) { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { + s1 += ptr[0], s2 += s1; + s1 += ptr[1], s2 += s1; + s1 += ptr[2], s2 += s1; + s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; + s1 += ptr[5], s2 += s1; + s1 += ptr[6], s2 += s1; + s1 += ptr[7], s2 += s1; + } + for (; i < block_len; ++i) + s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; + buf_len -= block_len; + block_len = 5552; + } + r->m_check_adler32 = (s2 << 16) + s1; + if ((status == TINFL_STATUS_DONE) && + (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && + (r->m_check_adler32 != r->m_z_adler32)) + status = TINFL_STATUS_ADLER32_MISMATCH; + } + return status; +} + +/* Higher level helper functions. */ +void* tinfl_decompress_mem_to_heap(const void* pSrc_buf, size_t src_buf_len, + size_t* pOut_len, int flags) { + tinfl_decompressor decomp; + void* pBuf = NULL, * pNew_buf; + size_t src_buf_ofs = 0, out_buf_capacity = 0; + *pOut_len = 0; + tinfl_init(&decomp); + for (;;) { + size_t src_buf_size = src_buf_len - src_buf_ofs, + dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; + tinfl_status status = tinfl_decompress( + &decomp, (const mz_uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, + (mz_uint8*)pBuf, pBuf ? (mz_uint8*)pBuf + *pOut_len : NULL, + &dst_buf_size, + (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) { + MZ_FREE(pBuf); + *pOut_len = 0; + return NULL; + } + src_buf_ofs += src_buf_size; + *pOut_len += dst_buf_size; + if (status == TINFL_STATUS_DONE) + break; + new_out_buf_capacity = out_buf_capacity * 2; + if (new_out_buf_capacity < 128) + new_out_buf_capacity = 128; + pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); + if (!pNew_buf) { + MZ_FREE(pBuf); + *pOut_len = 0; + return NULL; + } + pBuf = pNew_buf; + out_buf_capacity = new_out_buf_capacity; + } + return pBuf; +} + +size_t tinfl_decompress_mem_to_mem(void* pOut_buf, size_t out_buf_len, + const void* pSrc_buf, size_t src_buf_len, + int flags) { + tinfl_decompressor decomp; + tinfl_status status; + tinfl_init(&decomp); + status = + tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, + (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, + (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED + : out_buf_len; +} + +int tinfl_decompress_mem_to_callback(const void* pIn_buf, size_t* pIn_buf_size, + tinfl_put_buf_func_ptr pPut_buf_func, + void* pPut_buf_user, int flags) { + int result = 0; + tinfl_decompressor decomp; + mz_uint8* pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE); + size_t in_buf_ofs = 0, dict_ofs = 0; + if (!pDict) + return TINFL_STATUS_FAILED; + tinfl_init(&decomp); + for (;;) { + size_t in_buf_size = *pIn_buf_size - in_buf_ofs, + dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; + tinfl_status status = + tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, + &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, + (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); + in_buf_ofs += in_buf_size; + if ((dst_buf_size) && + (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) + break; + if (status != TINFL_STATUS_HAS_MORE_OUTPUT) { + result = (status == TINFL_STATUS_DONE); + break; + } + dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); + } + MZ_FREE(pDict); + *pIn_buf_size = in_buf_ofs; + return result; +} + +#ifndef MINIZ_NO_MALLOC +tinfl_decompressor* tinfl_decompressor_alloc() { + tinfl_decompressor* pDecomp = + (tinfl_decompressor*)MZ_MALLOC(sizeof(tinfl_decompressor)); + if (pDecomp) + tinfl_init(pDecomp); + return pDecomp; +} + +void tinfl_decompressor_free(tinfl_decompressor* pDecomp) { MZ_FREE(pDecomp); } +#endif + +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * Copyright 2016 Martin Raiber + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + +#ifndef MINIZ_NO_ARCHIVE_APIS + + + /* ------------------- .ZIP archive reading */ + +#ifdef MINIZ_NO_STDIO +#define MZ_FILE void * +#else +#include + +#if defined(_MSC_VER) +#include +#ifndef MINIZ_NO_TIME +#include +#endif +static wchar_t* str2wstr(const char* str) { + size_t len = strlen(str) + 1; + wchar_t* wstr = (wchar_t*)malloc(len * sizeof(wchar_t)); + MultiByteToWideChar(CP_UTF8, 0, str, (int)(len * sizeof(char)), wstr, + (int)len); + return wstr; +} + +static FILE* mz_fopen(const char* pFilename, const char* pMode) { + FILE* pFile = NULL; + wchar_t* wFilename = str2wstr(pFilename); + wchar_t* wMode = str2wstr(pMode); + +#ifdef ZIP_ENABLE_SHARABLE_FILE_OPEN + pFile = _wfopen(wFilename, wMode); +#else + _wfopen_s(&pFile, wFilename, wMode); +#endif + free(wFilename); + free(wMode); + + return pFile; +} + +static FILE* mz_freopen(const char* pPath, const char* pMode, FILE* pStream) { + FILE* pFile = NULL; + int res = 0; + + wchar_t* wPath = str2wstr(pPath); + wchar_t* wMode = str2wstr(pMode); + +#ifdef ZIP_ENABLE_SHARABLE_FILE_OPEN + pFile = _wfreopen(wPath, wMode, pStream); +#else + res = _wfreopen_s(&pFile, wPath, wMode, pStream); +#endif + + free(wPath); + free(wMode); + +#ifndef ZIP_ENABLE_SHARABLE_FILE_OPEN + if (res) { + return NULL; + } +#endif + + return pFile; +} + +static int mz_stat(const char* pPath, struct _stat64* buffer) { + wchar_t* wPath = str2wstr(pPath); + int res = _wstat64(wPath, buffer); + + free(wPath); + + return res; +} + +static int mz_mkdir(const char* pDirname) { + wchar_t* wDirname = str2wstr(pDirname); + int res = _wmkdir(wDirname); + + free(wDirname); + + return res; +} + +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftell +#define MZ_FSEEK64 fseek +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#define MZ_MKDIR(d) _mkdir(d) + +#elif defined(__MINGW32__) || defined(__MINGW64__) +#include +#ifndef MINIZ_NO_TIME +#include +#endif + +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftell +#define MZ_FSEEK64 fseek +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#define MZ_MKDIR(d) _mkdir(d) + +#elif defined(__TINYC__) +#ifndef MINIZ_NO_TIME +#include +#endif + +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftell +#define MZ_FSEEK64 fseek +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#if defined(_WIN32) || defined(_WIN64) +#define MZ_MKDIR(d) _mkdir(d) +#else +#define MZ_MKDIR(d) mkdir(d, 0755) +#endif + +#elif defined(__USE_LARGEFILE64) /* gcc, clang */ +#ifndef MINIZ_NO_TIME +#include +#endif + +#define MZ_FOPEN(f, m) fopen64(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello64 +#define MZ_FSEEK64 fseeko64 +#define MZ_FILE_STAT_STRUCT stat64 +#define MZ_FILE_STAT stat64 +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(p, m, s) freopen64(p, m, s) +#define MZ_DELETE_FILE remove +#define MZ_MKDIR(d) mkdir(d, 0755) + +#elif defined(__APPLE__) +#ifndef MINIZ_NO_TIME +#include +#endif + +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello +#define MZ_FSEEK64 fseeko +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(p, m, s) freopen(p, m, s) +#define MZ_DELETE_FILE remove +#define MZ_MKDIR(d) mkdir(d, 0755) + +#else +#pragma message( \ + "Using fopen, ftello, fseeko, stat() etc. path for file I/O - this path may not support large files.") +#ifndef MINIZ_NO_TIME +#include +#endif + +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#ifdef __STRICT_ANSI__ +#define MZ_FTELL64 ftell +#define MZ_FSEEK64 fseek +#else +#define MZ_FTELL64 ftello +#define MZ_FSEEK64 fseeko +#endif +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#define MZ_MKDIR(d) mkdir(d, 0755) + +#endif /* #ifdef _MSC_VER */ +#endif /* #ifdef MINIZ_NO_STDIO */ + +#ifndef CHMOD +// Upon successful completion, a value of 0 is returned. +// Otherwise, a value of -1 is returned and errno is set to indicate the error. +// int chmod(const char *path, mode_t mode); +#define CHMOD(f, m) chmod(f, m) +#endif + +#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) + +/* Various ZIP archive enums. To completely avoid cross platform compiler + * alignment and platform endian issues, miniz.c doesn't use structs for any of + * this stuff. */ +enum { + /* ZIP archive identifiers and record sizes */ + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, + MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, + + /* ZIP64 archive identifier and record sizes */ + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06064b50, + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG = 0x07064b50, + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE = 56, + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE = 20, + MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID = 0x0001, + MZ_ZIP_DATA_DESCRIPTOR_ID = 0x08074b50, + MZ_ZIP_DATA_DESCRIPTER_SIZE64 = 24, + MZ_ZIP_DATA_DESCRIPTER_SIZE32 = 16, + + /* Central directory header record offsets */ + MZ_ZIP_CDH_SIG_OFS = 0, + MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, + MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, + MZ_ZIP_CDH_BIT_FLAG_OFS = 8, + MZ_ZIP_CDH_METHOD_OFS = 10, + MZ_ZIP_CDH_FILE_TIME_OFS = 12, + MZ_ZIP_CDH_FILE_DATE_OFS = 14, + MZ_ZIP_CDH_CRC32_OFS = 16, + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, + MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, + MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, + MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, + MZ_ZIP_CDH_DISK_START_OFS = 34, + MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, + MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, + + /* Local directory header offsets */ + MZ_ZIP_LDH_SIG_OFS = 0, + MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, + MZ_ZIP_LDH_BIT_FLAG_OFS = 6, + MZ_ZIP_LDH_METHOD_OFS = 8, + MZ_ZIP_LDH_FILE_TIME_OFS = 10, + MZ_ZIP_LDH_FILE_DATE_OFS = 12, + MZ_ZIP_LDH_CRC32_OFS = 14, + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, + MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, + MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, + MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR = 1 << 3, + + /* End of central directory offsets */ + MZ_ZIP_ECDH_SIG_OFS = 0, + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, + MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, + MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, + MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, + + /* ZIP64 End of central directory locator offsets */ + MZ_ZIP64_ECDL_SIG_OFS = 0, /* 4 bytes */ + MZ_ZIP64_ECDL_NUM_DISK_CDIR_OFS = 4, /* 4 bytes */ + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS = 8, /* 8 bytes */ + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS = 16, /* 4 bytes */ + + /* ZIP64 End of central directory header offsets */ + MZ_ZIP64_ECDH_SIG_OFS = 0, /* 4 bytes */ + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS = 4, /* 8 bytes */ + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS = 12, /* 2 bytes */ + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS = 14, /* 2 bytes */ + MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS = 16, /* 4 bytes */ + MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS = 20, /* 4 bytes */ + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 24, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS = 32, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_SIZE_OFS = 40, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_OFS_OFS = 48, /* 8 bytes */ + MZ_ZIP_VERSION_MADE_BY_DOS_FILESYSTEM_ID = 0, + MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG = 0x10, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED = 1, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG = 32, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION = 64, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED = 8192, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8 = 1 << 11 +}; + +typedef struct { + void* m_p; + size_t m_size, m_capacity; + mz_uint m_element_size; +} mz_zip_array; + +struct mz_zip_internal_state_tag { + mz_zip_array m_central_dir; + mz_zip_array m_central_dir_offsets; + mz_zip_array m_sorted_central_dir_offsets; + + /* The flags passed in when the archive is initially opened. */ + uint32_t m_init_flags; + + /* MZ_TRUE if the archive has a zip64 end of central directory headers, etc. + */ + mz_bool m_zip64; + + /* MZ_TRUE if we found zip64 extended info in the central directory (m_zip64 + * will also be slammed to true too, even if we didn't find a zip64 end of + * central dir header, etc.) */ + mz_bool m_zip64_has_extended_info_fields; + + /* These fields are used by the file, FILE, memory, and memory/heap read/write + * helpers. */ + MZ_FILE* m_pFile; + mz_uint64 m_file_archive_start_ofs; + + void* m_pMem; + size_t m_mem_size; + size_t m_mem_capacity; +}; + +#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) \ + (array_ptr)->m_element_size = element_size + +#if defined(DEBUG) || defined(_DEBUG) +static MZ_FORCEINLINE mz_uint +mz_zip_array_range_check(const mz_zip_array* pArray, mz_uint index) { + MZ_ASSERT(index < pArray->m_size); + return index; +} +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \ + ((element_type *)((array_ptr) \ + ->m_p))[mz_zip_array_range_check(array_ptr, index)] +#else +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \ + ((element_type *)((array_ptr)->m_p))[index] +#endif + +static MZ_FORCEINLINE void mz_zip_array_init(mz_zip_array* pArray, + mz_uint32 element_size) { + memset(pArray, 0, sizeof(mz_zip_array)); + pArray->m_element_size = element_size; +} + +static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive* pZip, + mz_zip_array* pArray) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); + memset(pArray, 0, sizeof(mz_zip_array)); +} + +static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive* pZip, + mz_zip_array* pArray, + size_t min_new_capacity, + mz_uint growing) { + void* pNew_p; + size_t new_capacity = min_new_capacity; + MZ_ASSERT(pArray->m_element_size); + if (pArray->m_capacity >= min_new_capacity) + return MZ_TRUE; + if (growing) { + new_capacity = MZ_MAX(1, pArray->m_capacity); + while (new_capacity < min_new_capacity) + new_capacity *= 2; + } + if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, + pArray->m_element_size, new_capacity))) + return MZ_FALSE; + pArray->m_p = pNew_p; + pArray->m_capacity = new_capacity; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive* pZip, + mz_zip_array* pArray, + size_t new_capacity, + mz_uint growing) { + if (new_capacity > pArray->m_capacity) { + if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) + return MZ_FALSE; + } + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive* pZip, + mz_zip_array* pArray, + size_t new_size, + mz_uint growing) { + if (new_size > pArray->m_capacity) { + if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) + return MZ_FALSE; + } + pArray->m_size = new_size; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive* pZip, + mz_zip_array* pArray, + size_t n) { + return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive* pZip, + mz_zip_array* pArray, + const void* pElements, + size_t n) { + size_t orig_size = pArray->m_size; + if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) + return MZ_FALSE; + if (n > 0) + memcpy((mz_uint8*)pArray->m_p + orig_size * pArray->m_element_size, + pElements, n * pArray->m_element_size); + return MZ_TRUE; +} + +#ifndef MINIZ_NO_TIME +static MZ_TIME_T mz_zip_dos_to_time_t(int dos_time, int dos_date) { + struct tm tm; + memset(&tm, 0, sizeof(tm)); + tm.tm_isdst = -1; + tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; + tm.tm_mon = ((dos_date >> 5) & 15) - 1; + tm.tm_mday = dos_date & 31; + tm.tm_hour = (dos_time >> 11) & 31; + tm.tm_min = (dos_time >> 5) & 63; + tm.tm_sec = (dos_time << 1) & 62; + return mktime(&tm); +} + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS +static void mz_zip_time_t_to_dos_time(MZ_TIME_T time, mz_uint16* pDOS_time, + mz_uint16* pDOS_date) { +#ifdef _MSC_VER + struct tm tm_struct; + struct tm* tm = &tm_struct; + errno_t err = localtime_s(tm, &time); + if (err) { + *pDOS_date = 0; + *pDOS_time = 0; + return; + } +#else + struct tm* tm = localtime(&time); +#endif /* #ifdef _MSC_VER */ + + * pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + + ((tm->tm_sec) >> 1)); + *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + + ((tm->tm_mon + 1) << 5) + tm->tm_mday); +} +#endif /* MINIZ_NO_ARCHIVE_WRITING_APIS */ + +#ifndef MINIZ_NO_STDIO +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS +static mz_bool mz_zip_get_file_modified_time(const char* pFilename, + MZ_TIME_T* pTime) { + struct MZ_FILE_STAT_STRUCT file_stat; + + /* On Linux with x86 glibc, this call will fail on large files (I think >= + * 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. */ + if (MZ_FILE_STAT(pFilename, &file_stat) != 0) + return MZ_FALSE; + + *pTime = file_stat.st_mtime; + + return MZ_TRUE; +} +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS*/ + +static mz_bool mz_zip_set_file_times(const char* pFilename, + MZ_TIME_T access_time, + MZ_TIME_T modified_time) { + struct utimbuf t; + + memset(&t, 0, sizeof(t)); + t.actime = access_time; + t.modtime = modified_time; + + return !utime(pFilename, &t); +} +#endif /* #ifndef MINIZ_NO_STDIO */ +#endif /* #ifndef MINIZ_NO_TIME */ + +static MZ_FORCEINLINE mz_bool mz_zip_set_error(mz_zip_archive* pZip, + mz_zip_error err_num) { + if (pZip) + pZip->m_last_error = err_num; + return MZ_FALSE; +} + +static mz_bool mz_zip_reader_init_internal(mz_zip_archive* pZip, + mz_uint flags) { + (void)flags; + if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!pZip->m_pAlloc) + pZip->m_pAlloc = miniz_def_alloc_func; + if (!pZip->m_pFree) + pZip->m_pFree = miniz_def_free_func; + if (!pZip->m_pRealloc) + pZip->m_pRealloc = miniz_def_realloc_func; + + pZip->m_archive_size = 0; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + pZip->m_last_error = MZ_ZIP_NO_ERROR; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state*)pZip->m_pAlloc( + pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, + sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, + sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, + sizeof(mz_uint32)); + pZip->m_pState->m_init_flags = flags; + pZip->m_pState->m_zip64 = MZ_FALSE; + pZip->m_pState->m_zip64_has_extended_info_fields = MZ_FALSE; + + pZip->m_zip_mode = MZ_ZIP_MODE_READING; + + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool +mz_zip_reader_filename_less(const mz_zip_array* pCentral_dir_array, + const mz_zip_array* pCentral_dir_offsets, + mz_uint l_index, mz_uint r_index) { + const mz_uint8* pL = &MZ_ZIP_ARRAY_ELEMENT( + pCentral_dir_array, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, + l_index)), + * pE; + const mz_uint8* pR = &MZ_ZIP_ARRAY_ELEMENT( + pCentral_dir_array, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), + r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; + pR++; + } + return (pL == pE) ? (l_len < r_len) : (l < r); +} + +#define MZ_SWAP_UINT32(a, b) \ + do { \ + mz_uint32 t = a; \ + a = b; \ + b = t; \ + } \ + MZ_MACRO_END + +/* Heap sort of lowercased filenames, used to help accelerate plain central + * directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), + * but it could allocate memory.) */ +static void +mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive* pZip) { + mz_zip_internal_state* pState = pZip->m_pState; + const mz_zip_array* pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array* pCentral_dir = &pState->m_central_dir; + mz_uint32* pIndices; + mz_uint32 start, end; + const mz_uint32 size = pZip->m_total_files; + + if (size <= 1U) + return; + + pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, + mz_uint32, 0); + + start = (size - 2U) >> 1U; + for (;;) { + mz_uint64 child, root = start; + for (;;) { + if ((child = (root << 1U) + 1U) >= size) + break; + child += (((child + 1U) < size) && + (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, + pIndices[child], + pIndices[child + 1U]))); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, + pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); + root = child; + } + if (!start) + break; + start--; + } + + end = size - 1; + while (end > 0) { + mz_uint64 child, root = 0; + MZ_SWAP_UINT32(pIndices[end], pIndices[0]); + for (;;) { + if ((child = (root << 1U) + 1U) >= end) + break; + child += + (((child + 1U) < end) && + mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, + pIndices[child], pIndices[child + 1U])); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, + pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); + root = child; + } + end--; + } +} + +static mz_bool mz_zip_reader_locate_header_sig(mz_zip_archive* pZip, + mz_uint32 record_sig, + mz_uint32 record_size, + mz_int64* pOfs) { + mz_int64 cur_file_ofs; + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; + mz_uint8* pBuf = (mz_uint8*)buf_u32; + + /* Basic sanity checks - reject files which are too small */ + if (pZip->m_archive_size < record_size) + return MZ_FALSE; + + /* Find the record by scanning the file from the end towards the beginning. */ + cur_file_ofs = + MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); + for (;;) { + int i, + n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); + + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) + return MZ_FALSE; + + for (i = n - 4; i >= 0; --i) { + mz_uint s = MZ_READ_LE32(pBuf + i); + if (s == record_sig) { + if ((pZip->m_archive_size - (cur_file_ofs + i)) >= record_size) + break; + } + } + + if (i >= 0) { + cur_file_ofs += i; + break; + } + + /* Give up if we've searched the entire file, or we've gone back "too far" + * (~64kb) */ + if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= + (MZ_UINT16_MAX + record_size))) + return MZ_FALSE; + + cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); + } + + *pOfs = cur_file_ofs; + return MZ_TRUE; +} + +static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive* pZip, + mz_uint flags) { + mz_uint cdir_size = 0, cdir_entries_on_this_disk = 0, num_this_disk = 0, + cdir_disk_index = 0; + mz_uint64 cdir_ofs = 0; + mz_int64 cur_file_ofs = 0; + const mz_uint8* p; + + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; + mz_uint8* pBuf = (mz_uint8*)buf_u32; + mz_bool sort_central_dir = + ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); + mz_uint32 zip64_end_of_central_dir_locator_u32 + [(MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + sizeof(mz_uint32) - 1) / + sizeof(mz_uint32)]; + mz_uint8* pZip64_locator = (mz_uint8*)zip64_end_of_central_dir_locator_u32; + + mz_uint32 zip64_end_of_central_dir_header_u32 + [(MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / + sizeof(mz_uint32)]; + mz_uint8* pZip64_end_of_central_dir = + (mz_uint8*)zip64_end_of_central_dir_header_u32; + + mz_uint64 zip64_end_of_central_dir_ofs = 0; + + /* Basic sanity checks - reject files which are too small, and check the first + * 4 bytes of the file to make sure a local header is there. */ + if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (!mz_zip_reader_locate_header_sig( + pZip, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG, + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE, &cur_file_ofs)) + return mz_zip_set_error(pZip, MZ_ZIP_FAILED_FINDING_CENTRAL_DIR); + + /* Read and verify the end of central directory record. */ + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (cur_file_ofs >= (MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) { + if (pZip->m_pRead(pZip->m_pIO_opaque, + cur_file_ofs - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE, + pZip64_locator, + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) == + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) { + if (MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_SIG_OFS) == + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG) { + zip64_end_of_central_dir_ofs = MZ_READ_LE64( + pZip64_locator + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS); + if (zip64_end_of_central_dir_ofs > + (pZip->m_archive_size - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (pZip->m_pRead(pZip->m_pIO_opaque, zip64_end_of_central_dir_ofs, + pZip64_end_of_central_dir, + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) == + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) { + if (MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIG_OFS) == + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG) { + pZip->m_pState->m_zip64 = MZ_TRUE; + } + } + } + } + } + + pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS); + cdir_entries_on_this_disk = + MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); + num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); + cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); + cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS); + cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); + + if (pZip->m_pState->m_zip64) { + mz_uint32 zip64_total_num_of_disks = + MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS); + mz_uint64 zip64_cdir_total_entries = MZ_READ_LE64( + pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS); + mz_uint64 zip64_cdir_total_entries_on_this_disk = MZ_READ_LE64( + pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); + mz_uint64 zip64_size_of_end_of_central_dir_record = MZ_READ_LE64( + pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS); + mz_uint64 zip64_size_of_central_directory = + MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_SIZE_OFS); + + if (zip64_size_of_end_of_central_dir_record < + (MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - 12)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (zip64_total_num_of_disks != 1U) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + /* Check for miniz's practical limits */ + if (zip64_cdir_total_entries > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + pZip->m_total_files = (mz_uint32)zip64_cdir_total_entries; + + if (zip64_cdir_total_entries_on_this_disk > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + cdir_entries_on_this_disk = + (mz_uint32)zip64_cdir_total_entries_on_this_disk; + + /* Check for miniz's current practical limits (sorry, this should be enough + * for millions of files) */ + if (zip64_size_of_central_directory > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + cdir_size = (mz_uint32)zip64_size_of_central_directory; + + num_this_disk = MZ_READ_LE32(pZip64_end_of_central_dir + + MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS); + + cdir_disk_index = MZ_READ_LE32(pZip64_end_of_central_dir + + MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS); + + cdir_ofs = + MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_OFS_OFS); + } + + if (pZip->m_total_files != cdir_entries_on_this_disk) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (((num_this_disk | cdir_disk_index) != 0) && + ((num_this_disk != 1) || (cdir_disk_index != 1))) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (cdir_size < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pZip->m_central_directory_file_ofs = cdir_ofs; + + if (pZip->m_total_files) { + mz_uint i, n; + /* Read the entire central directory into a heap block, and allocate another + * heap block to hold the unsorted central dir file record offsets, and + * possibly another to hold the sorted indices. */ + if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, + MZ_FALSE)) || + (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, + pZip->m_total_files, MZ_FALSE))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (sort_central_dir) { + if (!mz_zip_array_resize(pZip, + &pZip->m_pState->m_sorted_central_dir_offsets, + pZip->m_total_files, MZ_FALSE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, + pZip->m_pState->m_central_dir.m_p, + cdir_size) != cdir_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + /* Now create an index into the central directory file records, do some + * basic sanity checking on each record */ + p = (const mz_uint8*)pZip->m_pState->m_central_dir.m_p; + for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) { + mz_uint total_header_size, disk_index, bit_flags, filename_size, + ext_data_size; + mz_uint64 comp_size, decomp_size, local_header_ofs; + + if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || + (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, + i) = + (mz_uint32)(p - (const mz_uint8*)pZip->m_pState->m_central_dir.m_p); + + if (sort_central_dir) + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, + mz_uint32, i) = i; + + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + filename_size = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + ext_data_size = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); + + if ((!pZip->m_pState->m_zip64_has_extended_info_fields) && + (ext_data_size) && + (MZ_MAX(MZ_MAX(comp_size, decomp_size), local_header_ofs) == + MZ_UINT32_MAX)) { + /* Attempt to find zip64 extended information field in the entry's extra + * data */ + mz_uint32 extra_size_remaining = ext_data_size; + + if (extra_size_remaining) { + const mz_uint8* pExtra_data; + void* buf = NULL; + + if (MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + ext_data_size > + n) { + buf = MZ_MALLOC(ext_data_size); + if (buf == NULL) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (pZip->m_pRead(pZip->m_pIO_opaque, + cdir_ofs + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + filename_size, + buf, ext_data_size) != ext_data_size) { + MZ_FREE(buf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + pExtra_data = (mz_uint8*)buf; + } + else { + pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size; + } + + do { + mz_uint32 field_id; + mz_uint32 field_data_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) { + MZ_FREE(buf); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + + if ((field_data_size + sizeof(mz_uint16) * 2) > + extra_size_remaining) { + MZ_FREE(buf); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { + /* Ok, the archive didn't have any zip64 headers but it uses a + * zip64 extended information field so mark it as zip64 anyway + * (this can occur with infozip's zip util when it reads + * compresses files from stdin). */ + pZip->m_pState->m_zip64 = MZ_TRUE; + pZip->m_pState->m_zip64_has_extended_info_fields = MZ_TRUE; + break; + } + + pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; + extra_size_remaining = + extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; + } while (extra_size_remaining); + + MZ_FREE(buf); + } + } + + /* I've seen archives that aren't marked as zip64 that uses zip64 ext + * data, argh */ + if ((comp_size != MZ_UINT32_MAX) && (decomp_size != MZ_UINT32_MAX)) { + if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && + (decomp_size != comp_size)) || + (decomp_size && !comp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); + if ((disk_index == MZ_UINT16_MAX) || + ((disk_index != num_this_disk) && (disk_index != 1))) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (comp_size != MZ_UINT32_MAX) { + if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + bit_flags = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + if (bit_flags & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > + n) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + n -= total_header_size; + p += total_header_size; + } + } + + if (sort_central_dir) + mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); + + return MZ_TRUE; +} + +void mz_zip_zero_struct(mz_zip_archive* pZip) { + if (pZip) + MZ_CLEAR_OBJ(*pZip); +} + +static mz_bool mz_zip_reader_end_internal(mz_zip_archive* pZip, + mz_bool set_last_error) { + mz_bool status = MZ_TRUE; + + if (!pZip) + return MZ_FALSE; + + if ((!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || + (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) { + if (set_last_error) + pZip->m_last_error = MZ_ZIP_INVALID_PARAMETER; + + return MZ_FALSE; + } + + if (pZip->m_pState) { + mz_zip_internal_state* pState = pZip->m_pState; + pZip->m_pState = NULL; + + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) { + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) { + if (MZ_FCLOSE(pState->m_pFile) == EOF) { + if (set_last_error) + pZip->m_last_error = MZ_ZIP_FILE_CLOSE_FAILED; + status = MZ_FALSE; + } + } + pState->m_pFile = NULL; + } +#endif /* #ifndef MINIZ_NO_STDIO */ + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + } + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + + return status; +} + +mz_bool mz_zip_reader_end(mz_zip_archive* pZip) { + return mz_zip_reader_end_internal(pZip, MZ_TRUE); +} +mz_bool mz_zip_reader_init(mz_zip_archive* pZip, mz_uint64 size, + mz_uint flags) { + if ((!pZip) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_USER; + pZip->m_archive_size = size; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +static size_t mz_zip_mem_read_func(void* pOpaque, mz_uint64 file_ofs, + void* pBuf, size_t n) { + mz_zip_archive* pZip = (mz_zip_archive*)pOpaque; + size_t s = (file_ofs >= pZip->m_archive_size) + ? 0 + : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); + memcpy(pBuf, (const mz_uint8*)pZip->m_pState->m_pMem + file_ofs, s); + return s; +} + +mz_bool mz_zip_reader_init_mem(mz_zip_archive* pZip, const void* pMem, + size_t size, mz_uint flags) { + if (!pMem) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_MEMORY; + pZip->m_archive_size = size; + pZip->m_pRead = mz_zip_mem_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pNeeds_keepalive = NULL; + +#ifdef __cplusplus + pZip->m_pState->m_pMem = const_cast(pMem); +#else + pZip->m_pState->m_pMem = (void*)pMem; +#endif + + pZip->m_pState->m_mem_size = size; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_read_func(void* pOpaque, mz_uint64 file_ofs, + void* pBuf, size_t n) { + mz_zip_archive* pZip = (mz_zip_archive*)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + + file_ofs += pZip->m_pState->m_file_archive_start_ofs; + + if (((mz_int64)file_ofs < 0) || + (((cur_ofs != (mz_int64)file_ofs)) && + (MZ_FSEEK64(pZip->m_pState->m_pFile, (long)file_ofs, SEEK_SET)))) + return 0; + + return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_reader_init_file(mz_zip_archive* pZip, const char* pFilename, + mz_uint32 flags) { + return mz_zip_reader_init_file_v2(pZip, pFilename, flags, 0, 0); +} + +mz_bool mz_zip_reader_init_file_v2(mz_zip_archive* pZip, const char* pFilename, + mz_uint flags, mz_uint64 file_start_ofs, + mz_uint64 archive_size) { + mz_uint64 file_size; + MZ_FILE* pFile; + + if ((!pZip) || (!pFilename) || + ((archive_size) && + (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pFile = MZ_FOPEN(pFilename, "rb"); + if (!pFile) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + file_size = archive_size; + if (!file_size) { + if (MZ_FSEEK64(pFile, 0, SEEK_END)) { + MZ_FCLOSE(pFile); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + } + + file_size = MZ_FTELL64(pFile); + } + + /* TODO: Better sanity check archive_size and the # of actual remaining bytes + */ + + if (file_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) { + MZ_FCLOSE(pFile); + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + } + + if (!mz_zip_reader_init_internal(pZip, flags)) { + MZ_FCLOSE(pFile); + return MZ_FALSE; + } + + pZip->m_zip_type = MZ_ZIP_TYPE_FILE; + pZip->m_pRead = mz_zip_file_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = file_size; + pZip->m_pState->m_file_archive_start_ofs = file_start_ofs; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_reader_init_file_v2_rpb(mz_zip_archive* pZip, + const char* pFilename, mz_uint flags, + mz_uint64 file_start_ofs, + mz_uint64 archive_size) { + mz_uint64 file_size; + MZ_FILE* pFile; + + if ((!pZip) || (!pFilename) || + ((archive_size) && + (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pFile = MZ_FOPEN(pFilename, "r+b"); + if (!pFile) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + file_size = archive_size; + if (!file_size) { + if (MZ_FSEEK64(pFile, 0, SEEK_END)) { + MZ_FCLOSE(pFile); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + } + + file_size = MZ_FTELL64(pFile); + } + + /* TODO: Better sanity check archive_size and the # of actual remaining bytes + */ + + if (file_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) { + MZ_FCLOSE(pFile); + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + } + + if (!mz_zip_reader_init_internal(pZip, flags)) { + MZ_FCLOSE(pFile); + return MZ_FALSE; + } + + pZip->m_zip_type = MZ_ZIP_TYPE_FILE; + pZip->m_pRead = mz_zip_file_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = file_size; + pZip->m_pState->m_file_archive_start_ofs = file_start_ofs; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_reader_init_cfile(mz_zip_archive* pZip, MZ_FILE* pFile, + mz_uint64 archive_size, mz_uint flags) { + mz_uint64 cur_file_ofs; + + if ((!pZip) || (!pFile)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + cur_file_ofs = MZ_FTELL64(pFile); + + if (!archive_size) { + if (MZ_FSEEK64(pFile, 0, SEEK_END)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + + archive_size = MZ_FTELL64(pFile) - cur_file_ofs; + + if (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + } + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = archive_size; + pZip->m_pState->m_file_archive_start_ofs = cur_file_ofs; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +#endif /* #ifndef MINIZ_NO_STDIO */ + +static MZ_FORCEINLINE const mz_uint8* mz_zip_get_cdh(mz_zip_archive* pZip, + mz_uint file_index) { + if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files)) + return NULL; + return &MZ_ZIP_ARRAY_ELEMENT( + &pZip->m_pState->m_central_dir, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, + file_index)); +} + +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive* pZip, + mz_uint file_index) { + mz_uint m_bit_flag; + const mz_uint8* p = mz_zip_get_cdh(pZip, file_index); + if (!p) { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + return (m_bit_flag & + (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) != 0; +} + +mz_bool mz_zip_reader_is_file_supported(mz_zip_archive* pZip, + mz_uint file_index) { + mz_uint bit_flag; + mz_uint method; + + const mz_uint8* p = mz_zip_get_cdh(pZip, file_index); + if (!p) { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); + bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + + if ((method != 0) && (method != MZ_DEFLATED)) { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + return MZ_FALSE; + } + + if (bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + return MZ_FALSE; + } + + if (bit_flag & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG) { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive* pZip, + mz_uint file_index) { + mz_uint filename_len, attribute_mapping_id, external_attr; + const mz_uint8* p = mz_zip_get_cdh(pZip, file_index); + if (!p) { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_len) { + if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') + return MZ_TRUE; + } + + /* Bugfix: This code was also checking if the internal attribute was non-zero, + * which wasn't correct. */ + /* Most/all zip writers (hopefully) set DOS file/directory attributes in the + * low 16-bits, so check for the DOS directory flag and ignore the source OS + * ID in the created by field. */ + /* FIXME: Remove this check? Is it necessary - we already check the filename. + */ + attribute_mapping_id = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS) >> 8; + (void)attribute_mapping_id; + + external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + if ((external_attr & MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG) != 0) { + return MZ_TRUE; + } + + return MZ_FALSE; +} + +static mz_bool mz_zip_file_stat_internal(mz_zip_archive* pZip, + mz_uint file_index, + const mz_uint8* pCentral_dir_header, + mz_zip_archive_file_stat* pStat, + mz_bool* pFound_zip64_extra_data) { + mz_uint n; + const mz_uint8* p = pCentral_dir_header; + + if (pFound_zip64_extra_data) + *pFound_zip64_extra_data = MZ_FALSE; + + if ((!p) || (!pStat)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Extract fields from the central directory record. */ + pStat->m_file_index = file_index; + pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT( + &pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); + pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); + pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); + pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); +#ifndef MINIZ_NO_TIME + pStat->m_time = + mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), + MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); +#endif + pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); + pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); + pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + + /* Copy as much of the filename and comment as possible. */ + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); + memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pStat->m_filename[n] = '\0'; + + n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); + n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); + pStat->m_comment_size = n; + memcpy(pStat->m_comment, + p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), + n); + pStat->m_comment[n] = '\0'; + + /* Set some flags for convienance */ + pStat->m_is_directory = mz_zip_reader_is_file_a_directory(pZip, file_index); + pStat->m_is_encrypted = mz_zip_reader_is_file_encrypted(pZip, file_index); + pStat->m_is_supported = mz_zip_reader_is_file_supported(pZip, file_index); + + /* See if we need to read any zip64 extended information fields. */ + /* Confusingly, these zip64 fields can be present even on non-zip64 archives + * (Debian zip on a huge files from stdin piped to stdout creates them). */ + if (MZ_MAX(MZ_MAX(pStat->m_comp_size, pStat->m_uncomp_size), + pStat->m_local_header_ofs) == MZ_UINT32_MAX) { + /* Attempt to find zip64 extended information field in the entry's extra + * data */ + mz_uint32 extra_size_remaining = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); + + if (extra_size_remaining) { + const mz_uint8* pExtra_data = + p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + + do { + mz_uint32 field_id; + mz_uint32 field_data_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + + if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { + const mz_uint8* pField_data = pExtra_data + sizeof(mz_uint16) * 2; + mz_uint32 field_data_remaining = field_data_size; + + if (pFound_zip64_extra_data) + *pFound_zip64_extra_data = MZ_TRUE; + + if (pStat->m_uncomp_size == MZ_UINT32_MAX) { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_uncomp_size = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + if (pStat->m_comp_size == MZ_UINT32_MAX) { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_comp_size = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + if (pStat->m_local_header_ofs == MZ_UINT32_MAX) { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_local_header_ofs = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + (void)pField_data; // unused + + field_data_remaining -= sizeof(mz_uint64); + (void)field_data_remaining; // unused + } + + break; + } + + pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; + extra_size_remaining = + extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; + } while (extra_size_remaining); + } + } + + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_string_equal(const char* pA, + const char* pB, mz_uint len, + mz_uint flags) { + mz_uint i; + if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) + return 0 == memcmp(pA, pB, len); + for (i = 0; i < len; ++i) + if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) + return MZ_FALSE; + return MZ_TRUE; +} + +static MZ_FORCEINLINE int +mz_zip_filename_compare(const mz_zip_array* pCentral_dir_array, + const mz_zip_array* pCentral_dir_offsets, + mz_uint l_index, const char* pR, mz_uint r_len) { + const mz_uint8* pL = &MZ_ZIP_ARRAY_ELEMENT( + pCentral_dir_array, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, + l_index)), + * pE; + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; + pR++; + } + return (pL == pE) ? (int)(l_len - r_len) : (l - r); +} + +static mz_bool mz_zip_locate_file_binary_search(mz_zip_archive* pZip, + const char* pFilename, + mz_uint32* pIndex) { + mz_zip_internal_state* pState = pZip->m_pState; + const mz_zip_array* pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array* pCentral_dir = &pState->m_central_dir; + mz_uint32* pIndices = &MZ_ZIP_ARRAY_ELEMENT( + &pState->m_sorted_central_dir_offsets, mz_uint32, 0); + const uint32_t size = pZip->m_total_files; + const mz_uint filename_len = (mz_uint)strlen(pFilename); + + if (pIndex) + *pIndex = 0; + + if (size) { + /* yes I could use uint32_t's, but then we would have to add some special + * case checks in the loop, argh, and */ + /* honestly the major expense here on 32-bit CPU's will still be the + * filename compare */ + mz_int64 l = 0, h = (mz_int64)size - 1; + + while (l <= h) { + mz_int64 m = l + ((h - l) >> 1); + uint32_t file_index = pIndices[(uint32_t)m]; + + int comp = mz_zip_filename_compare(pCentral_dir, pCentral_dir_offsets, + file_index, pFilename, filename_len); + if (!comp) { + if (pIndex) + *pIndex = file_index; + return MZ_TRUE; + } + else if (comp < 0) + l = m + 1; + else + h = m - 1; + } + } + + return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); +} + +int mz_zip_reader_locate_file(mz_zip_archive* pZip, const char* pName, + const char* pComment, mz_uint flags) { + mz_uint32 index; + if (!mz_zip_reader_locate_file_v2(pZip, pName, pComment, flags, &index)) + return -1; + else + return (int)index; +} + +mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive* pZip, const char* pName, + const char* pComment, mz_uint flags, + mz_uint32* pIndex) { + mz_uint file_index; + size_t name_len, comment_len; + + if (pIndex) + *pIndex = 0; + + if ((!pZip) || (!pZip->m_pState) || (!pName)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* See if we can use a binary search */ + if (((pZip->m_pState->m_init_flags & + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) && + (pZip->m_zip_mode == MZ_ZIP_MODE_READING) && + ((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && + (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) { + return mz_zip_locate_file_binary_search(pZip, pName, pIndex); + } + + /* Locate the entry by scanning the entire central directory */ + name_len = strlen(pName); + if (name_len > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + comment_len = pComment ? strlen(pComment) : 0; + if (comment_len > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + for (file_index = 0; file_index < pZip->m_total_files; file_index++) { + const mz_uint8* pHeader = &MZ_ZIP_ARRAY_ELEMENT( + &pZip->m_pState->m_central_dir, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, + file_index)); + mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); + const char* pFilename = + (const char*)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + if (filename_len < name_len) + continue; + if (comment_len) { + mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), + file_comment_len = + MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); + const char* pFile_comment = pFilename + filename_len + file_extra_len; + if ((file_comment_len != comment_len) || + (!mz_zip_string_equal(pComment, pFile_comment, file_comment_len, + flags))) + continue; + } + if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) { + int ofs = filename_len - 1; + do { + if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || + (pFilename[ofs] == ':')) + break; + } while (--ofs >= 0); + ofs++; + pFilename += ofs; + filename_len -= ofs; + } + if ((filename_len == name_len) && + (mz_zip_string_equal(pName, pFilename, filename_len, flags))) { + if (pIndex) + *pIndex = file_index; + return MZ_TRUE; + } + } + + return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); +} + +static mz_bool mz_zip_reader_extract_to_mem_no_alloc1( + mz_zip_archive* pZip, mz_uint file_index, void* pBuf, size_t buf_size, + mz_uint flags, void* pUser_read_buf, size_t user_read_buf_size, + const mz_zip_archive_file_stat* st) { + int status = TINFL_STATUS_DONE; + mz_uint64 needed_size, cur_file_ofs, comp_remaining, + out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; + mz_zip_archive_file_stat file_stat; + void* pRead_buf; + mz_uint32 + local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / + sizeof(mz_uint32)]; + mz_uint8* pLocal_header = (mz_uint8*)local_header_u32; + tinfl_decompressor inflator; + + if ((!pZip) || (!pZip->m_pState) || ((buf_size) && (!pBuf)) || + ((user_read_buf_size) && (!pUser_read_buf)) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (st) { + file_stat = *st; + } + else if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_bit_flag & + (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && + (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + /* Ensure supplied output buffer is large enough. */ + needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size + : file_stat.m_uncomp_size; + if (buf_size < needed_size) + return mz_zip_set_error(pZip, MZ_ZIP_BUF_TOO_SMALL); + + /* Read and parse the local directory entry. */ + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { + /* The file is stored or the caller has requested the compressed data. */ + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, + (size_t)needed_size) != needed_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) == 0) { + if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8*)pBuf, + (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) + return mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); + } +#endif + + return MZ_TRUE; + } + + /* Decompress the file either directly from memory or from a file input + * buffer. */ + tinfl_init(&inflator); + + if (pZip->m_pState->m_pMem) { + /* Read directly from the archive in memory. */ + pRead_buf = (mz_uint8*)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else if (pUser_read_buf) { + /* Use a user provided read buffer. */ + if (!user_read_buf_size) + return MZ_FALSE; + pRead_buf = (mz_uint8*)pUser_read_buf; + read_buf_size = user_read_buf_size; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + else { + /* Temporarily allocate a read buffer. */ + read_buf_size = + MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, + (size_t)read_buf_size))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + do { + /* The size_t cast here should be OK because we've verified that the output + * buffer is >= file_stat.m_uncomp_size above */ + size_t in_buf_size, + out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, + (size_t)read_buf_avail) != read_buf_avail) { + status = TINFL_STATUS_FAILED; + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress( + &inflator, (mz_uint8*)pRead_buf + read_buf_ofs, &in_buf_size, + (mz_uint8*)pBuf, (mz_uint8*)pBuf + out_buf_ofs, &out_buf_size, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | + (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + out_buf_ofs += out_buf_size; + } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); + + if (status == TINFL_STATUS_DONE) { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (out_buf_ofs != file_stat.m_uncomp_size) { + mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8*)pBuf, + (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) { + mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); + status = TINFL_STATUS_FAILED; + } +#endif + } + + if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + + return status == TINFL_STATUS_DONE; +} + +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive* pZip, + mz_uint file_index, void* pBuf, + size_t buf_size, mz_uint flags, + void* pUser_read_buf, + size_t user_read_buf_size) { + return mz_zip_reader_extract_to_mem_no_alloc1(pZip, file_index, pBuf, + buf_size, flags, pUser_read_buf, + user_read_buf_size, NULL); +} + +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( + mz_zip_archive* pZip, const char* pFilename, void* pBuf, size_t buf_size, + mz_uint flags, void* pUser_read_buf, size_t user_read_buf_size) { + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return MZ_FALSE; + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, + flags, pUser_read_buf, + user_read_buf_size); +} + +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive* pZip, mz_uint file_index, + void* pBuf, size_t buf_size, + mz_uint flags) { + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, + flags, NULL, 0); +} + +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive* pZip, + const char* pFilename, void* pBuf, + size_t buf_size, mz_uint flags) { + return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, + buf_size, flags, NULL, 0); +} + +void* mz_zip_reader_extract_to_heap(mz_zip_archive* pZip, mz_uint file_index, + size_t* pSize, mz_uint flags) { + mz_zip_archive_file_stat file_stat; + mz_uint64 alloc_size; + void* pBuf; + + if (pSize) + *pSize = 0; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return NULL; + + alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size + : file_stat.m_uncomp_size; + if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) { + mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + return NULL; + } + + if (NULL == + (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return NULL; + } + + if (!mz_zip_reader_extract_to_mem_no_alloc1(pZip, file_index, pBuf, + (size_t)alloc_size, flags, NULL, + 0, &file_stat)) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return NULL; + } + + if (pSize) + *pSize = (size_t)alloc_size; + return pBuf; +} + +void* mz_zip_reader_extract_file_to_heap(mz_zip_archive* pZip, + const char* pFilename, size_t* pSize, + mz_uint flags) { + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, + &file_index)) { + if (pSize) + *pSize = 0; + return MZ_FALSE; + } + return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); +} + +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive* pZip, + mz_uint file_index, + mz_file_write_func pCallback, + void* pOpaque, mz_uint flags) { + int status = TINFL_STATUS_DONE; +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + mz_uint file_crc32 = MZ_CRC32_INIT; +#endif + mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, + out_buf_ofs = 0, cur_file_ofs; + mz_zip_archive_file_stat file_stat; + void* pRead_buf = NULL; + void* pWrite_buf = NULL; + mz_uint32 + local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / + sizeof(mz_uint32)]; + mz_uint8* pLocal_header = (mz_uint8*)local_header_u32; + + if ((!pZip) || (!pZip->m_pState) || (!pCallback) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + /* A directory or zero length file */ + if (file_stat.m_is_directory || (!file_stat.m_comp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_bit_flag & + (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && + (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + /* Read and do some minimal validation of the local directory entry (this + * doesn't crack the zip64 stuff, which we already have from the central dir) + */ + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + /* Decompress the file either directly from memory or from a file input + * buffer. */ + if (pZip->m_pState->m_pMem) { + pRead_buf = (mz_uint8*)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else { + read_buf_size = + MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, + (size_t)read_buf_size))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { + /* The file is stored or the caller has requested the compressed data. */ + if (pZip->m_pState->m_pMem) { + if (((sizeof(size_t) == sizeof(mz_uint32))) && + (file_stat.m_comp_size > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, + (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + } + else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + file_crc32 = + (mz_uint32)mz_crc32(file_crc32, (const mz_uint8*)pRead_buf, + (size_t)file_stat.m_comp_size); +#endif + } + + cur_file_ofs += file_stat.m_comp_size; + out_buf_ofs += file_stat.m_comp_size; + comp_remaining = 0; + } + else { + while (comp_remaining) { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, + (size_t)read_buf_avail) != read_buf_avail) { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { + file_crc32 = (mz_uint32)mz_crc32( + file_crc32, (const mz_uint8*)pRead_buf, (size_t)read_buf_avail); + } +#endif + + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, + (size_t)read_buf_avail) != read_buf_avail) { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + + cur_file_ofs += read_buf_avail; + out_buf_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + } + } + } + else { + tinfl_decompressor inflator; + tinfl_init(&inflator); + + if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, + TINFL_LZ_DICT_SIZE))) { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + status = TINFL_STATUS_FAILED; + } + else { + do { + mz_uint8* pWrite_buf_cur = + (mz_uint8*)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + size_t in_buf_size, + out_buf_size = + TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, + (size_t)read_buf_avail) != read_buf_avail) { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress( + &inflator, (const mz_uint8*)pRead_buf + read_buf_ofs, &in_buf_size, + (mz_uint8*)pWrite_buf, pWrite_buf_cur, &out_buf_size, + comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + + if (out_buf_size) { + if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != + out_buf_size) { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + file_crc32 = + (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); +#endif + if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) { + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + } + } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || + (status == TINFL_STATUS_HAS_MORE_OUTPUT)); + } + } + + if ((status == TINFL_STATUS_DONE) && + (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (out_buf_ofs != file_stat.m_uncomp_size) { + mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (file_crc32 != file_stat.m_crc32) { + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + status = TINFL_STATUS_FAILED; + } +#endif + } + + if (!pZip->m_pState->m_pMem) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + + if (pWrite_buf) + pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); + + return status == TINFL_STATUS_DONE; +} + +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive* pZip, + const char* pFilename, + mz_file_write_func pCallback, + void* pOpaque, mz_uint flags) { + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, + flags); +} + +mz_zip_reader_extract_iter_state* +mz_zip_reader_extract_iter_new(mz_zip_archive* pZip, mz_uint file_index, + mz_uint flags) { + mz_zip_reader_extract_iter_state* pState; + mz_uint32 + local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / + sizeof(mz_uint32)]; + mz_uint8* pLocal_header = (mz_uint8*)local_header_u32; + + /* Argument sanity check */ + if ((!pZip) || (!pZip->m_pState)) + return NULL; + + /* Allocate an iterator status structure */ + pState = (mz_zip_reader_extract_iter_state*)pZip->m_pAlloc( + pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_reader_extract_iter_state)); + if (!pState) { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return NULL; + } + + /* Fetch file details */ + if (!mz_zip_reader_file_stat(pZip, file_index, &pState->file_stat)) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* Encryption and patch files are not supported. */ + if (pState->file_stat.m_bit_flag & + (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && + (pState->file_stat.m_method != 0) && + (pState->file_stat.m_method != MZ_DEFLATED)) { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* Init state - save args */ + pState->pZip = pZip; + pState->flags = flags; + + /* Init state - reset variables to defaults */ + pState->status = TINFL_STATUS_DONE; +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + pState->file_crc32 = MZ_CRC32_INIT; +#endif + pState->read_buf_ofs = 0; + pState->out_buf_ofs = 0; + pState->pRead_buf = NULL; + pState->pWrite_buf = NULL; + pState->out_blk_remain = 0; + + /* Read and parse the local directory entry. */ + pState->cur_file_ofs = pState->file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, pState->cur_file_ofs, pLocal_header, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + pState->cur_file_ofs += + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((pState->cur_file_ofs + pState->file_stat.m_comp_size) > + pZip->m_archive_size) { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* Decompress the file either directly from memory or from a file input + * buffer. */ + if (pZip->m_pState->m_pMem) { + pState->pRead_buf = + (mz_uint8*)pZip->m_pState->m_pMem + pState->cur_file_ofs; + pState->read_buf_size = pState->read_buf_avail = + pState->file_stat.m_comp_size; + pState->comp_remaining = pState->file_stat.m_comp_size; + } + else { + if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || + (!pState->file_stat.m_method))) { + /* Decompression required, therefore intermediate read buffer required */ + pState->read_buf_size = MZ_MIN(pState->file_stat.m_comp_size, + (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + if (NULL == + (pState->pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, + (size_t)pState->read_buf_size))) { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + } + else { + /* Decompression not required - we will be reading directly into user + * buffer, no temp buf required */ + pState->read_buf_size = 0; + } + pState->read_buf_avail = 0; + pState->comp_remaining = pState->file_stat.m_comp_size; + } + + if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || + (!pState->file_stat.m_method))) { + /* Decompression required, init decompressor */ + tinfl_init(&pState->inflator); + + /* Allocate write buffer */ + if (NULL == (pState->pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, + TINFL_LZ_DICT_SIZE))) { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + if (pState->pRead_buf) + pZip->m_pFree(pZip->m_pAlloc_opaque, pState->pRead_buf); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + } + + return pState; +} + +mz_zip_reader_extract_iter_state* +mz_zip_reader_extract_file_iter_new(mz_zip_archive* pZip, const char* pFilename, + mz_uint flags) { + mz_uint32 file_index; + + /* Locate file index by name */ + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return NULL; + + /* Construct iterator */ + return mz_zip_reader_extract_iter_new(pZip, file_index, flags); +} + +size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state* pState, + void* pvBuf, size_t buf_size) { + size_t copied_to_caller = 0; + + /* Argument sanity check */ + if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState) || (!pvBuf)) + return 0; + + if ((pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || + (!pState->file_stat.m_method)) { + /* The file is stored or the caller has requested the compressed data, calc + * amount to return. */ + copied_to_caller = (size_t)MZ_MIN(buf_size, pState->comp_remaining); + + /* Zip is in memory....or requires reading from a file? */ + if (pState->pZip->m_pState->m_pMem) { + /* Copy data to caller's buffer */ + memcpy(pvBuf, pState->pRead_buf, copied_to_caller); + pState->pRead_buf = ((mz_uint8*)pState->pRead_buf) + copied_to_caller; + } + else { + /* Read directly into caller's buffer */ + if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, + pState->cur_file_ofs, pvBuf, + copied_to_caller) != copied_to_caller) { + /* Failed to read all that was asked for, flag failure and alert user */ + mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED); + pState->status = TINFL_STATUS_FAILED; + copied_to_caller = 0; + } + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + /* Compute CRC if not returning compressed data only */ + if (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + pState->file_crc32 = (mz_uint32)mz_crc32( + pState->file_crc32, (const mz_uint8*)pvBuf, copied_to_caller); +#endif + + /* Advance offsets, dec counters */ + pState->cur_file_ofs += copied_to_caller; + pState->out_buf_ofs += copied_to_caller; + pState->comp_remaining -= copied_to_caller; + } + else { + do { + /* Calc ptr to write buffer - given current output pos and block size */ + mz_uint8* pWrite_buf_cur = + (mz_uint8*)pState->pWrite_buf + + (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + + /* Calc max output size - given current output pos and block size */ + size_t in_buf_size, + out_buf_size = TINFL_LZ_DICT_SIZE - + (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + + if (!pState->out_blk_remain) { + /* Read more data from file if none available (and reading from file) */ + if ((!pState->read_buf_avail) && (!pState->pZip->m_pState->m_pMem)) { + /* Calc read size */ + pState->read_buf_avail = + MZ_MIN(pState->read_buf_size, pState->comp_remaining); + if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, + pState->cur_file_ofs, pState->pRead_buf, + (size_t)pState->read_buf_avail) != + pState->read_buf_avail) { + mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED); + pState->status = TINFL_STATUS_FAILED; + break; + } + + /* Advance offsets, dec counters */ + pState->cur_file_ofs += pState->read_buf_avail; + pState->comp_remaining -= pState->read_buf_avail; + pState->read_buf_ofs = 0; + } + + /* Perform decompression */ + in_buf_size = (size_t)pState->read_buf_avail; + pState->status = tinfl_decompress( + &pState->inflator, + (const mz_uint8*)pState->pRead_buf + pState->read_buf_ofs, + &in_buf_size, (mz_uint8*)pState->pWrite_buf, pWrite_buf_cur, + &out_buf_size, + pState->comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); + pState->read_buf_avail -= in_buf_size; + pState->read_buf_ofs += in_buf_size; + + /* Update current output block size remaining */ + pState->out_blk_remain = out_buf_size; + } + + if (pState->out_blk_remain) { + /* Calc amount to return. */ + size_t to_copy = + MZ_MIN((buf_size - copied_to_caller), pState->out_blk_remain); + + /* Copy data to caller's buffer */ + memcpy((uint8_t*)pvBuf + copied_to_caller, pWrite_buf_cur, to_copy); + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + /* Perform CRC */ + pState->file_crc32 = + (mz_uint32)mz_crc32(pState->file_crc32, pWrite_buf_cur, to_copy); +#endif + + /* Decrement data consumed from block */ + pState->out_blk_remain -= to_copy; + + /* Inc output offset, while performing sanity check */ + if ((pState->out_buf_ofs += to_copy) > + pState->file_stat.m_uncomp_size) { + mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED); + pState->status = TINFL_STATUS_FAILED; + break; + } + + /* Increment counter of data copied to caller */ + copied_to_caller += to_copy; + } + } while ((copied_to_caller < buf_size) && + ((pState->status == TINFL_STATUS_NEEDS_MORE_INPUT) || + (pState->status == TINFL_STATUS_HAS_MORE_OUTPUT))); + } + + /* Return how many bytes were copied into user buffer */ + return copied_to_caller; +} + +mz_bool +mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState) { + int status; + + /* Argument sanity check */ + if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState)) + return MZ_FALSE; + + /* Was decompression completed and requested? */ + if ((pState->status == TINFL_STATUS_DONE) && + (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (pState->out_buf_ofs != pState->file_stat.m_uncomp_size) { + mz_zip_set_error(pState->pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + pState->status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (pState->file_crc32 != pState->file_stat.m_crc32) { + mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED); + pState->status = TINFL_STATUS_FAILED; + } +#endif + } + + /* Free buffers */ + if (!pState->pZip->m_pState->m_pMem) + pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pRead_buf); + if (pState->pWrite_buf) + pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pWrite_buf); + + /* Save status */ + status = pState->status; + + /* Free context */ + pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState); + + return status == TINFL_STATUS_DONE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_callback(void* pOpaque, mz_uint64 ofs, + const void* pBuf, size_t n) { + (void)ofs; + + return MZ_FWRITE(pBuf, 1, n, (MZ_FILE*)pOpaque); +} + +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive* pZip, mz_uint file_index, + const char* pDst_filename, + mz_uint flags) { + mz_bool status; + mz_zip_archive_file_stat file_stat; + MZ_FILE* pFile; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + if (file_stat.m_is_directory || (!file_stat.m_is_supported)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + pFile = MZ_FOPEN(pDst_filename, "wb"); + if (!pFile) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + status = mz_zip_reader_extract_to_callback( + pZip, file_index, mz_zip_file_write_callback, pFile, flags); + + if (MZ_FCLOSE(pFile) == EOF) { + if (status) + mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); + + status = MZ_FALSE; + } + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) + if (status) + mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); +#endif + + return status; +} + +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive* pZip, + const char* pArchive_filename, + const char* pDst_filename, + mz_uint flags) { + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, + &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); +} + +mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive* pZip, mz_uint file_index, + MZ_FILE* pFile, mz_uint flags) { + mz_zip_archive_file_stat file_stat; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + if (file_stat.m_is_directory || (!file_stat.m_is_supported)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + return mz_zip_reader_extract_to_callback( + pZip, file_index, mz_zip_file_write_callback, pFile, flags); +} + +mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive* pZip, + const char* pArchive_filename, + MZ_FILE* pFile, mz_uint flags) { + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, + &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_cfile(pZip, file_index, pFile, flags); +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +static size_t mz_zip_compute_crc32_callback(void* pOpaque, mz_uint64 file_ofs, + const void* pBuf, size_t n) { + mz_uint32* p = (mz_uint32*)pOpaque; + (void)file_ofs; + *p = (mz_uint32)mz_crc32(*p, (const mz_uint8*)pBuf, n); + return n; +} + +mz_bool mz_zip_validate_file(mz_zip_archive* pZip, mz_uint file_index, + mz_uint flags) { + mz_zip_archive_file_stat file_stat; + mz_zip_internal_state* pState; + const mz_uint8* pCentral_dir_header; + mz_bool found_zip64_ext_data_in_cdir = MZ_FALSE; + mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; + mz_uint32 + local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / + sizeof(mz_uint32)]; + mz_uint8* pLocal_header = (mz_uint8*)local_header_u32; + mz_uint64 local_header_ofs = 0; + mz_uint32 local_header_filename_len, local_header_extra_len, + local_header_crc32; + mz_uint64 local_header_comp_size, local_header_uncomp_size; + mz_uint32 uncomp_crc32 = MZ_CRC32_INIT; + mz_bool has_data_descriptor; + mz_uint32 local_header_bit_flags; + + mz_zip_array file_data_array; + mz_zip_array_init(&file_data_array, 1); + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || + (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (file_index > pZip->m_total_files) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + pCentral_dir_header = mz_zip_get_cdh(pZip, file_index); + + if (!mz_zip_file_stat_internal(pZip, file_index, pCentral_dir_header, + &file_stat, &found_zip64_ext_data_in_cdir)) + return MZ_FALSE; + + /* A directory or zero length file */ + if (file_stat.m_is_directory || (!file_stat.m_uncomp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_is_encrypted) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports stored and deflate. */ + if ((file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + if (!file_stat.m_is_supported) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + /* Read and parse the local directory entry. */ + local_header_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs, pLocal_header, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + local_header_filename_len = + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); + local_header_extra_len = + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + local_header_comp_size = + MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); + local_header_uncomp_size = + MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); + local_header_crc32 = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_CRC32_OFS); + local_header_bit_flags = + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + has_data_descriptor = (local_header_bit_flags & 8) != 0; + + if (local_header_filename_len != strlen(file_stat.m_filename)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + + local_header_filename_len + local_header_extra_len + + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (!mz_zip_array_resize( + pZip, &file_data_array, + MZ_MAX(local_header_filename_len, local_header_extra_len), + MZ_FALSE)) { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + goto handle_failure; + } + + if (local_header_filename_len) { + if (pZip->m_pRead(pZip->m_pIO_opaque, + local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE, + file_data_array.m_p, + local_header_filename_len) != local_header_filename_len) { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + /* I've seen 1 archive that had the same pathname, but used backslashes in + * the local dir and forward slashes in the central dir. Do we care about + * this? For now, this case will fail validation. */ + if (memcmp(file_stat.m_filename, file_data_array.m_p, + local_header_filename_len) != 0) { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + + if ((local_header_extra_len) && + ((local_header_comp_size == MZ_UINT32_MAX) || + (local_header_uncomp_size == MZ_UINT32_MAX))) { + mz_uint32 extra_size_remaining = local_header_extra_len; + const mz_uint8* pExtra_data = (const mz_uint8*)file_data_array.m_p; + + if (pZip->m_pRead(pZip->m_pIO_opaque, + local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + + local_header_filename_len, + file_data_array.m_p, + local_header_extra_len) != local_header_extra_len) { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + do { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + goto handle_failure; + } + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + goto handle_failure; + } + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { + const mz_uint8* pSrc_field_data = pExtra_data + sizeof(mz_uint32); + + if (field_data_size < sizeof(mz_uint64) * 2) { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + goto handle_failure; + } + + local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); + local_header_comp_size = + MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); + + found_zip64_ext_data_in_ldir = MZ_TRUE; + break; + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + } + + /* TODO: parse local header extra data when local_header_comp_size is + * 0xFFFFFFFF! (big_descriptor.zip) */ + /* I've seen zips in the wild with the data descriptor bit set, but proper + * local header values and bogus data descriptors */ + if ((has_data_descriptor) && (!local_header_comp_size) && + (!local_header_crc32)) { + mz_uint8 descriptor_buf[32]; + mz_bool has_id; + const mz_uint8* pSrc; + mz_uint32 file_crc32; + mz_uint64 comp_size = 0, uncomp_size = 0; + + mz_uint32 num_descriptor_uint32s = + ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) ? 6 : 4; + + if (pZip->m_pRead(pZip->m_pIO_opaque, + local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + + local_header_filename_len + local_header_extra_len + + file_stat.m_comp_size, + descriptor_buf, + sizeof(mz_uint32) * num_descriptor_uint32s) != + (sizeof(mz_uint32) * num_descriptor_uint32s)) { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + has_id = (MZ_READ_LE32(descriptor_buf) == MZ_ZIP_DATA_DESCRIPTOR_ID); + pSrc = has_id ? (descriptor_buf + sizeof(mz_uint32)) : descriptor_buf; + + file_crc32 = MZ_READ_LE32(pSrc); + + if ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) { + comp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32)); + uncomp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32) + sizeof(mz_uint64)); + } + else { + comp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32)); + uncomp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32) + sizeof(mz_uint32)); + } + + if ((file_crc32 != file_stat.m_crc32) || + (comp_size != file_stat.m_comp_size) || + (uncomp_size != file_stat.m_uncomp_size)) { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + else { + if ((local_header_crc32 != file_stat.m_crc32) || + (local_header_comp_size != file_stat.m_comp_size) || + (local_header_uncomp_size != file_stat.m_uncomp_size)) { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + + mz_zip_array_clear(pZip, &file_data_array); + + if ((flags & MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY) == 0) { + if (!mz_zip_reader_extract_to_callback( + pZip, file_index, mz_zip_compute_crc32_callback, &uncomp_crc32, 0)) + return MZ_FALSE; + + /* 1 more check to be sure, although the extract checks too. */ + if (uncomp_crc32 != file_stat.m_crc32) { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + return MZ_FALSE; + } + } + + return MZ_TRUE; + +handle_failure: + mz_zip_array_clear(pZip, &file_data_array); + return MZ_FALSE; +} + +mz_bool mz_zip_validate_archive(mz_zip_archive* pZip, mz_uint flags) { + mz_zip_internal_state* pState; + uint32_t i; + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || + (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + /* Basic sanity checks */ + if (!pState->m_zip64) { + if (pZip->m_total_files > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (pZip->m_archive_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + else { + if (pZip->m_total_files >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + + for (i = 0; i < pZip->m_total_files; i++) { + if (MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG & flags) { + mz_uint32 found_index; + mz_zip_archive_file_stat stat; + + if (!mz_zip_reader_file_stat(pZip, i, &stat)) + return MZ_FALSE; + + if (!mz_zip_reader_locate_file_v2(pZip, stat.m_filename, NULL, 0, + &found_index)) + return MZ_FALSE; + + /* This check can fail if there are duplicate filenames in the archive + * (which we don't check for when writing - that's up to the user) */ + if (found_index != i) + return mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + } + + if (!mz_zip_validate_file(pZip, i, flags)) + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_validate_mem_archive(const void* pMem, size_t size, + mz_uint flags, mz_zip_error* pErr) { + mz_bool success = MZ_TRUE; + mz_zip_archive zip; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + if ((!pMem) || (!size)) { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + mz_zip_zero_struct(&zip); + + if (!mz_zip_reader_init_mem(&zip, pMem, size, flags)) { + if (pErr) + *pErr = zip.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_validate_archive(&zip, flags)) { + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (!mz_zip_reader_end_internal(&zip, success)) { + if (!actual_err) + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (pErr) + *pErr = actual_err; + + return success; +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_validate_file_archive(const char* pFilename, mz_uint flags, + mz_zip_error* pErr) { + mz_bool success = MZ_TRUE; + mz_zip_archive zip; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + if (!pFilename) { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + mz_zip_zero_struct(&zip); + + if (!mz_zip_reader_init_file_v2(&zip, pFilename, flags, 0, 0)) { + if (pErr) + *pErr = zip.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_validate_archive(&zip, flags)) { + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (!mz_zip_reader_end_internal(&zip, success)) { + if (!actual_err) + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (pErr) + *pErr = actual_err; + + return success; +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +/* ------------------- .ZIP archive writing */ + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +static MZ_FORCEINLINE void mz_write_le16(mz_uint8* p, mz_uint16 v) { + p[0] = (mz_uint8)v; + p[1] = (mz_uint8)(v >> 8); +} +static MZ_FORCEINLINE void mz_write_le32(mz_uint8* p, mz_uint32 v) { + p[0] = (mz_uint8)v; + p[1] = (mz_uint8)(v >> 8); + p[2] = (mz_uint8)(v >> 16); + p[3] = (mz_uint8)(v >> 24); +} +static MZ_FORCEINLINE void mz_write_le64(mz_uint8* p, mz_uint64 v) { + mz_write_le32(p, (mz_uint32)v); + mz_write_le32(p + sizeof(mz_uint32), (mz_uint32)(v >> 32)); +} + +#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) +#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) +#define MZ_WRITE_LE64(p, v) mz_write_le64((mz_uint8 *)(p), (mz_uint64)(v)) + +static size_t mz_zip_heap_write_func(void* pOpaque, mz_uint64 file_ofs, + const void* pBuf, size_t n) { + mz_zip_archive* pZip = (mz_zip_archive*)pOpaque; + mz_zip_internal_state* pState = pZip->m_pState; + mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); + + if (!n) + return 0; + + /* An allocation this big is likely to just fail on 32-bit systems, so don't + * even go there. */ + if ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)) { + mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + return 0; + } + + if (new_size > pState->m_mem_capacity) { + void* pNew_block; + size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); + + while (new_capacity < new_size) + new_capacity *= 2; + + if (NULL == (pNew_block = pZip->m_pRealloc( + pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return 0; + } + + pState->m_pMem = pNew_block; + pState->m_mem_capacity = new_capacity; + } + memcpy((mz_uint8*)pState->m_pMem + file_ofs, pBuf, n); + pState->m_mem_size = (size_t)new_size; + return n; +} + +static mz_bool mz_zip_writer_end_internal(mz_zip_archive* pZip, + mz_bool set_last_error) { + mz_zip_internal_state* pState; + mz_bool status = MZ_TRUE; + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || + ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && + (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) { + if (set_last_error) + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + pState = pZip->m_pState; + pZip->m_pState = NULL; + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) { + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) { + if (MZ_FCLOSE(pState->m_pFile) == EOF) { + if (set_last_error) + mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); + status = MZ_FALSE; + } + } + + pState->m_pFile = NULL; + } +#endif /* #ifndef MINIZ_NO_STDIO */ + + if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); + pState->m_pMem = NULL; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + return status; +} + +mz_bool mz_zip_writer_init_v2(mz_zip_archive* pZip, mz_uint64 existing_size, + mz_uint flags) { + mz_bool zip64 = (flags & MZ_ZIP_FLAG_WRITE_ZIP64) != 0; + + if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || + (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) { + if (!pZip->m_pRead) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + if (pZip->m_file_offset_alignment) { + /* Ensure user specified file offset alignment is a power of 2. */ + if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + if (!pZip->m_pAlloc) + pZip->m_pAlloc = miniz_def_alloc_func; + if (!pZip->m_pFree) + pZip->m_pFree = miniz_def_free_func; + if (!pZip->m_pRealloc) + pZip->m_pRealloc = miniz_def_realloc_func; + + pZip->m_archive_size = existing_size; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state*)pZip->m_pAlloc( + pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, + sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, + sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, + sizeof(mz_uint32)); + + pZip->m_pState->m_zip64 = zip64; + pZip->m_pState->m_zip64_has_extended_info_fields = zip64; + + pZip->m_zip_type = MZ_ZIP_TYPE_USER; + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init(mz_zip_archive* pZip, mz_uint64 existing_size) { + return mz_zip_writer_init_v2(pZip, existing_size, 0); +} + +mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive* pZip, + size_t size_to_reserve_at_beginning, + size_t initial_allocation_size, + mz_uint flags) { + pZip->m_pWrite = mz_zip_heap_write_func; + pZip->m_pNeeds_keepalive = NULL; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_mem_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_HEAP; + + if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, + size_to_reserve_at_beginning))) { + if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc( + pZip->m_pAlloc_opaque, 1, initial_allocation_size))) { + mz_zip_writer_end_internal(pZip, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + pZip->m_pState->m_mem_capacity = initial_allocation_size; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_heap(mz_zip_archive* pZip, + size_t size_to_reserve_at_beginning, + size_t initial_allocation_size) { + return mz_zip_writer_init_heap_v2(pZip, size_to_reserve_at_beginning, + initial_allocation_size, 0); +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_func(void* pOpaque, mz_uint64 file_ofs, + const void* pBuf, size_t n) { + mz_zip_archive* pZip = (mz_zip_archive*)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + + file_ofs += pZip->m_pState->m_file_archive_start_ofs; + + if (((mz_int64)file_ofs < 0) || + (((cur_ofs != (mz_int64)file_ofs)) && + (MZ_FSEEK64(pZip->m_pState->m_pFile, (long)file_ofs, SEEK_SET)))) { + mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + return 0; + } + + return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_writer_init_file(mz_zip_archive* pZip, const char* pFilename, + mz_uint64 size_to_reserve_at_beginning) { + return mz_zip_writer_init_file_v2(pZip, pFilename, + size_to_reserve_at_beginning, 0); +} + +mz_bool mz_zip_writer_init_file_v2(mz_zip_archive* pZip, const char* pFilename, + mz_uint64 size_to_reserve_at_beginning, + mz_uint flags) { + MZ_FILE* pFile; + + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) + return MZ_FALSE; + + if (NULL == (pFile = MZ_FOPEN( + pFilename, + (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) ? "w+b" : "wb"))) { + mz_zip_writer_end(pZip); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + } + + pZip->m_pState->m_pFile = pFile; + pZip->m_zip_type = MZ_ZIP_TYPE_FILE; + + if (size_to_reserve_at_beginning) { + mz_uint64 cur_ofs = 0; + char buf[4096]; + + MZ_CLEAR_OBJ(buf); + + do { + size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) { + mz_zip_writer_end(pZip); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_ofs += n; + size_to_reserve_at_beginning -= n; + } while (size_to_reserve_at_beginning); + } + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_cfile(mz_zip_archive* pZip, MZ_FILE* pFile, + mz_uint flags) { + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, 0, flags)) + return MZ_FALSE; + + pZip->m_pState->m_pFile = pFile; + pZip->m_pState->m_file_archive_start_ofs = + MZ_FTELL64(pZip->m_pState->m_pFile); + pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; + + return MZ_TRUE; +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive* pZip, + const char* pFilename, + mz_uint flags) { + mz_zip_internal_state* pState; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (flags & MZ_ZIP_FLAG_WRITE_ZIP64) { + /* We don't support converting a non-zip64 file to zip64 - this seems like + * more trouble than it's worth. (What about the existing 32-bit data + * descriptors that could follow the compressed data?) */ + if (!pZip->m_pState->m_zip64) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + /* No sense in trying to write to an archive that's already at the support max + * size */ + if (pZip->m_pState->m_zip64) { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else { + if (pZip->m_total_files == MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + if ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + } + + pState = pZip->m_pState; + + if (pState->m_pFile) { +#ifdef MINIZ_NO_STDIO + (void)pFilename; + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); +#else + if (pZip->m_pIO_opaque != pZip) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) { + if (!pFilename) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Archive is being read from stdio and was originally opened only for + * reading. Try to reopen as writable. */ + if (NULL == + (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) { + /* The mz_zip_archive is now in a bogus state because pState->m_pFile is + * NULL, so just close it. */ + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + } + } + + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; +#endif /* #ifdef MINIZ_NO_STDIO */ + } + else if (pState->m_pMem) { + /* Archive lives in a memory block. Assume it's from the heap that we can + * resize using the realloc callback. */ + if (pZip->m_pIO_opaque != pZip) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState->m_mem_capacity = pState->m_mem_size; + pZip->m_pWrite = mz_zip_heap_write_func; + pZip->m_pNeeds_keepalive = NULL; + } + /* Archive is being read via a user provided read function - make sure the + user has specified a write function too. */ + else if (!pZip->m_pWrite) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Start writing new files at the archive's current central directory + * location. */ + /* TODO: We could add a flag that lets the user start writing immediately + * AFTER the existing central dir - this would be safer. */ + pZip->m_archive_size = pZip->m_central_directory_file_ofs; + pZip->m_central_directory_file_ofs = 0; + + /* Clear the sorted central dir offsets, they aren't useful or maintained now. + */ + /* Even though we're now in write mode, files can still be extracted and + * verified, but file locates will be slow. */ + /* TODO: We could easily maintain the sorted central directory offsets. */ + mz_zip_array_clear(pZip, &pZip->m_pState->m_sorted_central_dir_offsets); + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_from_reader_v2_noreopen(mz_zip_archive* pZip, + const char* pFilename, + mz_uint flags) { + mz_zip_internal_state* pState; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (flags & MZ_ZIP_FLAG_WRITE_ZIP64) { + /* We don't support converting a non-zip64 file to zip64 - this seems like + * more trouble than it's worth. (What about the existing 32-bit data + * descriptors that could follow the compressed data?) */ + if (!pZip->m_pState->m_zip64) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + /* No sense in trying to write to an archive that's already at the support max + * size */ + if (pZip->m_pState->m_zip64) { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else { + if (pZip->m_total_files == MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + if ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + } + + pState = pZip->m_pState; + + if (pState->m_pFile) { +#ifdef MINIZ_NO_STDIO + (void)pFilename; + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); +#else + if (pZip->m_pIO_opaque != pZip) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) { + if (!pFilename) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; +#endif /* #ifdef MINIZ_NO_STDIO */ + } + else if (pState->m_pMem) { + /* Archive lives in a memory block. Assume it's from the heap that we can + * resize using the realloc callback. */ + if (pZip->m_pIO_opaque != pZip) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState->m_mem_capacity = pState->m_mem_size; + pZip->m_pWrite = mz_zip_heap_write_func; + pZip->m_pNeeds_keepalive = NULL; + } + /* Archive is being read via a user provided read function - make sure the + user has specified a write function too. */ + else if (!pZip->m_pWrite) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Start writing new files at the archive's current central directory + * location. */ + /* TODO: We could add a flag that lets the user start writing immediately + * AFTER the existing central dir - this would be safer. */ + pZip->m_archive_size = pZip->m_central_directory_file_ofs; + pZip->m_central_directory_file_ofs = 0; + + /* Clear the sorted central dir offsets, they aren't useful or maintained now. + */ + /* Even though we're now in write mode, files can still be extracted and + * verified, but file locates will be slow. */ + /* TODO: We could easily maintain the sorted central directory offsets. */ + mz_zip_array_clear(pZip, &pZip->m_pState->m_sorted_central_dir_offsets); + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive* pZip, + const char* pFilename) { + return mz_zip_writer_init_from_reader_v2(pZip, pFilename, 0); +} + +/* TODO: pArchive_name is a terrible name here! */ +mz_bool mz_zip_writer_add_mem(mz_zip_archive* pZip, const char* pArchive_name, + const void* pBuf, size_t buf_size, + mz_uint level_and_flags) { + return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, + level_and_flags, 0, 0); +} + +typedef struct { + mz_zip_archive* m_pZip; + mz_uint64 m_cur_archive_file_ofs; + mz_uint64 m_comp_size; +} mz_zip_writer_add_state; + +static mz_bool mz_zip_writer_add_put_buf_callback(const void* pBuf, int len, + void* pUser) { + mz_zip_writer_add_state* pState = (mz_zip_writer_add_state*)pUser; + if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, + pState->m_cur_archive_file_ofs, pBuf, + len) != len) + return MZ_FALSE; + + pState->m_cur_archive_file_ofs += len; + pState->m_comp_size += len; + return MZ_TRUE; +} + +#define MZ_ZIP64_MAX_LOCAL_EXTRA_FIELD_SIZE \ + (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 2) +#define MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE \ + (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 3) +static mz_uint32 +mz_zip_writer_create_zip64_extra_data(mz_uint8* pBuf, mz_uint64* pUncomp_size, + mz_uint64* pComp_size, + mz_uint64* pLocal_header_ofs) { + mz_uint8* pDst = pBuf; + mz_uint32 field_size = 0; + + MZ_WRITE_LE16(pDst + 0, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); + MZ_WRITE_LE16(pDst + 2, 0); + pDst += sizeof(mz_uint16) * 2; + + if (pUncomp_size) { + MZ_WRITE_LE64(pDst, *pUncomp_size); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + if (pComp_size) { + MZ_WRITE_LE64(pDst, *pComp_size); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + if (pLocal_header_ofs) { + MZ_WRITE_LE64(pDst, *pLocal_header_ofs); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + MZ_WRITE_LE16(pBuf + 2, field_size); + + return (mz_uint32)(pDst - pBuf); +} + +static mz_bool mz_zip_writer_create_local_dir_header( + mz_zip_archive* pZip, mz_uint8* pDst, mz_uint16 filename_size, + mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, + mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, + mz_uint16 dos_time, mz_uint16 dos_date) { + (void)pZip; + memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, + MZ_MIN(comp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, + MZ_MIN(uncomp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_create_central_dir_header( + mz_zip_archive* pZip, mz_uint8* pDst, mz_uint16 filename_size, + mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, + mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, + mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, + mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { + (void)pZip; + memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, + MZ_MIN(comp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, + MZ_MIN(uncomp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, + MZ_MIN(local_header_ofs, MZ_UINT32_MAX)); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_add_to_central_dir( + mz_zip_archive* pZip, const char* pFilename, mz_uint16 filename_size, + const void* pExtra, mz_uint16 extra_size, const void* pComment, + mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, + mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, + mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, + mz_uint32 ext_attributes, const char* user_extra_data, + mz_uint user_extra_data_len) { + mz_zip_internal_state* pState = pZip->m_pState; + mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; + size_t orig_central_dir_size = pState->m_central_dir.m_size; + mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + + if (!pZip->m_pState->m_zip64) { + if (local_header_ofs > 0xFFFFFFFF) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + } + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + + user_extra_data_len + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!mz_zip_writer_create_central_dir_header( + pZip, central_dir_header, filename_size, + (mz_uint16)(extra_size + user_extra_data_len), comment_size, + uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, + dos_date, local_header_ofs, ext_attributes)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, + filename_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, + extra_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, user_extra_data, + user_extra_data_len)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, + comment_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, + ¢ral_dir_ofs, 1))) { + /* Try to resize the central directory array back into its original state. + */ + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, + MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_validate_archive_name(const char* pArchive_name) { + /* Basic ZIP archive filename validity checks: Valid filenames cannot start + * with a forward slash, cannot contain a drive letter, and cannot use + * DOS-style backward slashes. */ + if (*pArchive_name == '/') + return MZ_FALSE; + + /* Making sure the name does not contain drive letters or DOS style backward + * slashes is the responsibility of the program using miniz*/ + + return MZ_TRUE; +} + +static mz_uint +mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive* pZip) { + mz_uint32 n; + if (!pZip->m_file_offset_alignment) + return 0; + n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); + return (mz_uint)((pZip->m_file_offset_alignment - n) & + (pZip->m_file_offset_alignment - 1)); +} + +static mz_bool mz_zip_writer_write_zeros(mz_zip_archive* pZip, + mz_uint64 cur_file_ofs, mz_uint32 n) { + char buf[4096]; + memset(buf, 0, MZ_MIN(sizeof(buf), n)); + while (n) { + mz_uint32 s = MZ_MIN(sizeof(buf), n); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_file_ofs += s; + n -= s; + } + return MZ_TRUE; +} + +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive* pZip, + const char* pArchive_name, const void* pBuf, + size_t buf_size, const void* pComment, + mz_uint16 comment_size, + mz_uint level_and_flags, mz_uint64 uncomp_size, + mz_uint32 uncomp_crc32) { + return mz_zip_writer_add_mem_ex_v2( + pZip, pArchive_name, pBuf, buf_size, pComment, comment_size, + level_and_flags, uncomp_size, uncomp_crc32, NULL, NULL, 0, NULL, 0); +} + +mz_bool mz_zip_writer_add_mem_ex_v2( + mz_zip_archive* pZip, const char* pArchive_name, const void* pBuf, + size_t buf_size, const void* pComment, mz_uint16 comment_size, + mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, + MZ_TIME_T* last_modified, const char* user_extra_data, + mz_uint user_extra_data_len, const char* user_extra_data_central, + mz_uint user_extra_data_central_len) { + mz_uint16 method = 0, dos_time = 0, dos_date = 0; + mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; + mz_uint64 local_dir_header_ofs = 0, cur_archive_file_ofs = 0, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + tdefl_compressor* pComp = NULL; + mz_bool store_data_uncompressed; + mz_zip_internal_state* pState; + mz_uint8* pExtra_data = NULL; + mz_uint32 extra_size = 0; + mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; + mz_uint16 bit_flags = 0; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + + if (uncomp_size || + (buf_size && !(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + bit_flags |= MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; + + if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME)) + bit_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; + + level = level_and_flags & 0xF; + store_data_uncompressed = + ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); + + if ((!pZip) || (!pZip->m_pState) || + (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || + (!pArchive_name) || ((comment_size) && (!pComment)) || + (level > MZ_UBER_COMPRESSION)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + local_dir_header_ofs = pZip->m_archive_size; + cur_archive_file_ofs = pZip->m_archive_size; + + if (pState->m_zip64) { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else { + if (pZip->m_total_files == MZ_UINT16_MAX) { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ + } + if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + + if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + +#ifndef MINIZ_NO_TIME + if (last_modified != NULL) { + mz_zip_time_t_to_dos_time(*last_modified, &dos_time, &dos_date); + } + else { + MZ_TIME_T cur_time; + time(&cur_time); + mz_zip_time_t_to_dos_time(cur_time, &dos_time, &dos_date); + } +#endif /* #ifndef MINIZ_NO_TIME */ + + if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { + uncomp_crc32 = + (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8*)pBuf, buf_size); + uncomp_size = buf_size; + if (uncomp_size <= 3) { + level = 0; + store_data_uncompressed = MZ_TRUE; + } + } + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + num_alignment_padding_bytes = + mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!pState->m_zip64) { + /* Bail early if the archive would obviously become too large */ + if ((pZip->m_archive_size + num_alignment_padding_bytes + + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + + user_extra_data_len + pState->m_central_dir.m_size + + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + user_extra_data_central_len + + MZ_ZIP_DATA_DESCRIPTER_SIZE32) > 0xFFFFFFFF) { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + + if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) { + /* Set DOS Subdirectory attribute bit. */ + ext_attributes |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG; + + /* Subdirectories cannot contain data. */ + if ((buf_size) || (uncomp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + /* Try to do any allocations before writing to the archive, so if an + * allocation fails the file remains unmodified. (A good idea if we're doing + * an in-place modification.) */ + if ((!mz_zip_array_ensure_room( + pZip, &pState->m_central_dir, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + + (pState->m_zip64 ? MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE : 0))) || + (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if ((!store_data_uncompressed) && (buf_size)) { + if (NULL == (pComp = (tdefl_compressor*)pZip->m_pAlloc( + pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, + num_alignment_padding_bytes)) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + + local_dir_header_ofs += num_alignment_padding_bytes; + if (pZip->m_file_offset_alignment) { + MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == + 0); + } + cur_archive_file_ofs += num_alignment_padding_bytes; + + MZ_CLEAR_OBJ(local_dir_header); + + if (!store_data_uncompressed || + (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { + method = MZ_DEFLATED; + } + + if (pState->m_zip64) { + if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) { + pExtra_data = extra_data; + extra_size = mz_zip_writer_create_zip64_extra_data( + extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, + (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs + : NULL); + } + + if (!mz_zip_writer_create_local_dir_header( + pZip, local_dir_header, (mz_uint16)archive_name_size, + (mz_uint16)(extra_size + user_extra_data_len), 0, 0, 0, method, + bit_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, + local_dir_header, + sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, + archive_name_size) != archive_name_size) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_archive_file_ofs += archive_name_size; + + if (pExtra_data != NULL) { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, + extra_size) != extra_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += extra_size; + } + } + else { + if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + if (!mz_zip_writer_create_local_dir_header( + pZip, local_dir_header, (mz_uint16)archive_name_size, + (mz_uint16)user_extra_data_len, 0, 0, 0, method, bit_flags, + dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, + local_dir_header, + sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, + archive_name_size) != archive_name_size) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_archive_file_ofs += archive_name_size; + } + + if (user_extra_data_len > 0) { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, + user_extra_data, + user_extra_data_len) != user_extra_data_len) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += user_extra_data_len; + } + + if (store_data_uncompressed) { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, + buf_size) != buf_size) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += buf_size; + comp_size = buf_size; + } + else if (buf_size) { + mz_zip_writer_add_state state; + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, + tdefl_create_comp_flags_from_zip_params( + level, -15, MZ_DEFAULT_STRATEGY)) != + TDEFL_STATUS_OKAY) || + (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != + TDEFL_STATUS_DONE)) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pComp = NULL; + + if (uncomp_size) { + mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; + mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; + + MZ_ASSERT(bit_flags & MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR); + + MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); + MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); + if (pExtra_data == NULL) { + if (comp_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(local_dir_footer + 8, comp_size); + MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); + } + else { + MZ_WRITE_LE64(local_dir_footer + 8, comp_size); + MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); + local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, + local_dir_footer, + local_dir_footer_size) != local_dir_footer_size) + return MZ_FALSE; + + cur_archive_file_ofs += local_dir_footer_size; + } + + if (pExtra_data != NULL) { + extra_size = mz_zip_writer_create_zip64_extra_data( + extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, + (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_add_to_central_dir( + pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, + (mz_uint16)extra_size, pComment, comment_size, uncomp_size, comp_size, + uncomp_crc32, method, bit_flags, dos_time, dos_date, + local_dir_header_ofs, ext_attributes, user_extra_data_central, + user_extra_data_central_len)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_add_read_buf_callback( + mz_zip_archive* pZip, const char* pArchive_name, + mz_file_read_func read_callback, void* callback_opaque, mz_uint64 max_size, + const MZ_TIME_T* pFile_time, const void* pComment, mz_uint16 comment_size, + mz_uint level_and_flags, mz_uint32 ext_attributes, + const char* user_extra_data, mz_uint user_extra_data_len, + const char* user_extra_data_central, mz_uint user_extra_data_central_len) { + mz_uint16 gen_flags = (level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE) + ? 0 + : MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; + mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; + mz_uint16 method = 0, dos_time = 0, dos_date = 0; + mz_uint64 local_dir_header_ofs, cur_archive_file_ofs = 0, uncomp_size = 0, + comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + mz_uint8* pExtra_data = NULL; + mz_uint32 extra_size = 0; + mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; + mz_zip_internal_state* pState; + mz_uint64 file_ofs = 0, cur_archive_header_file_ofs; + + if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME)) + gen_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + level = level_and_flags & 0xF; + + /* Sanity checks */ + if ((!pZip) || (!pZip->m_pState) || + (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || + ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + cur_archive_file_ofs = pZip->m_archive_size; + + if ((!pState->m_zip64) && (max_size > MZ_UINT32_MAX)) { + /* Source file is too large for non-zip64 */ + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + pState->m_zip64 = MZ_TRUE; + } + + /* We could support this, but why? */ + if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + if (pState->m_zip64) { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else { + if (pZip->m_total_files == MZ_UINT16_MAX) { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ + } + } + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + num_alignment_padding_bytes = + mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!pState->m_zip64) { + /* Bail early if the archive would obviously become too large */ + if ((pZip->m_archive_size + num_alignment_padding_bytes + + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + + user_extra_data_len + pState->m_central_dir.m_size + + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 1024 + + MZ_ZIP_DATA_DESCRIPTER_SIZE32 + user_extra_data_central_len) > + 0xFFFFFFFF) { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + +#ifndef MINIZ_NO_TIME + if (pFile_time) { + mz_zip_time_t_to_dos_time(*pFile_time, &dos_time, &dos_date); + } +#endif + + if (max_size <= 3) + level = 0; + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, + num_alignment_padding_bytes)) { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += num_alignment_padding_bytes; + local_dir_header_ofs = cur_archive_file_ofs; + + if (pZip->m_file_offset_alignment) { + MZ_ASSERT((cur_archive_file_ofs & (pZip->m_file_offset_alignment - 1)) == + 0); + } + + if (max_size && level) { + method = MZ_DEFLATED; + } + + MZ_CLEAR_OBJ(local_dir_header); + if (pState->m_zip64) { + if (max_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) { + pExtra_data = extra_data; + if (level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE) + extra_size = mz_zip_writer_create_zip64_extra_data( + extra_data, (max_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (max_size >= MZ_UINT32_MAX) ? &comp_size : NULL, + (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs + : NULL); + else + extra_size = mz_zip_writer_create_zip64_extra_data( + extra_data, NULL, NULL, + (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs + : NULL); + } + + if (!mz_zip_writer_create_local_dir_header( + pZip, local_dir_header, (mz_uint16)archive_name_size, + (mz_uint16)(extra_size + user_extra_data_len), 0, 0, 0, method, + gen_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, + local_dir_header, + sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, + archive_name_size) != archive_name_size) { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += archive_name_size; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, + extra_size) != extra_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += extra_size; + } + else { + if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + if (!mz_zip_writer_create_local_dir_header( + pZip, local_dir_header, (mz_uint16)archive_name_size, + (mz_uint16)user_extra_data_len, 0, 0, 0, method, gen_flags, + dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, + local_dir_header, + sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, + archive_name_size) != archive_name_size) { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += archive_name_size; + } + + if (user_extra_data_len > 0) { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, + user_extra_data, + user_extra_data_len) != user_extra_data_len) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += user_extra_data_len; + } + + if (max_size) { + void* pRead_buf = + pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); + if (!pRead_buf) { + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!level) { + while (1) { + size_t n = read_callback(callback_opaque, file_ofs, pRead_buf, + MZ_ZIP_MAX_IO_BUF_SIZE); + if (n == 0) + break; + + if ((n > MZ_ZIP_MAX_IO_BUF_SIZE) || (file_ofs + n > max_size)) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, + n) != n) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + file_ofs += n; + uncomp_crc32 = + (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8*)pRead_buf, n); + cur_archive_file_ofs += n; + } + uncomp_size = file_ofs; + comp_size = uncomp_size; + } + else { + mz_bool result = MZ_FALSE; + mz_zip_writer_add_state state; + tdefl_compressor* pComp = (tdefl_compressor*)pZip->m_pAlloc( + pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, + tdefl_create_comp_flags_from_zip_params( + level, -15, MZ_DEFAULT_STRATEGY)) != + TDEFL_STATUS_OKAY) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + } + + for (;;) { + tdefl_status status; + tdefl_flush flush = TDEFL_NO_FLUSH; + + size_t n = read_callback(callback_opaque, file_ofs, pRead_buf, + MZ_ZIP_MAX_IO_BUF_SIZE); + if ((n > MZ_ZIP_MAX_IO_BUF_SIZE) || (file_ofs + n > max_size)) { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + break; + } + + file_ofs += n; + uncomp_crc32 = + (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8*)pRead_buf, n); + + if (pZip->m_pNeeds_keepalive != NULL && + pZip->m_pNeeds_keepalive(pZip->m_pIO_opaque)) + flush = TDEFL_FULL_FLUSH; + + if (n == 0) + flush = TDEFL_FINISH; + + status = tdefl_compress_buffer(pComp, pRead_buf, n, flush); + if (status == TDEFL_STATUS_DONE) { + result = MZ_TRUE; + break; + } + else if (status != TDEFL_STATUS_OKAY) { + mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); + break; + } + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + + if (!result) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return MZ_FALSE; + } + + uncomp_size = file_ofs; + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + } + + if (!(level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE)) { + mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; + mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; + + MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); + MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); + if (pExtra_data == NULL) { + if (comp_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(local_dir_footer + 8, comp_size); + MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); + } + else { + MZ_WRITE_LE64(local_dir_footer + 8, comp_size); + MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); + local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, + local_dir_footer, + local_dir_footer_size) != local_dir_footer_size) + return MZ_FALSE; + + cur_archive_file_ofs += local_dir_footer_size; + } + + if (level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE) { + if (pExtra_data != NULL) { + extra_size = mz_zip_writer_create_zip64_extra_data( + extra_data, (max_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (max_size >= MZ_UINT32_MAX) ? &comp_size : NULL, + (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs + : NULL); + } + + if (!mz_zip_writer_create_local_dir_header( + pZip, local_dir_header, (mz_uint16)archive_name_size, + (mz_uint16)(extra_size + user_extra_data_len), + (max_size >= MZ_UINT32_MAX) ? MZ_UINT32_MAX : uncomp_size, + (max_size >= MZ_UINT32_MAX) ? MZ_UINT32_MAX : comp_size, + uncomp_crc32, method, gen_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + cur_archive_header_file_ofs = local_dir_header_ofs; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_header_file_ofs, + local_dir_header, + sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + if (pExtra_data != NULL) { + cur_archive_header_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_header_file_ofs, + pArchive_name, + archive_name_size) != archive_name_size) { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_header_file_ofs += archive_name_size; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_header_file_ofs, + extra_data, extra_size) != extra_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_header_file_ofs += extra_size; + } + } + + if (pExtra_data != NULL) { + extra_size = mz_zip_writer_create_zip64_extra_data( + extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, + (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_add_to_central_dir( + pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, + (mz_uint16)extra_size, pComment, comment_size, uncomp_size, comp_size, + uncomp_crc32, method, gen_flags, dos_time, dos_date, + local_dir_header_ofs, ext_attributes, user_extra_data_central, + user_extra_data_central_len)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO + +static size_t mz_file_read_func_stdio(void* pOpaque, mz_uint64 file_ofs, + void* pBuf, size_t n) { + MZ_FILE* pSrc_file = (MZ_FILE*)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pSrc_file); + + if (((mz_int64)file_ofs < 0) || + (((cur_ofs != (mz_int64)file_ofs)) && + (MZ_FSEEK64(pSrc_file, (long)file_ofs, SEEK_SET)))) + return 0; + + return MZ_FREAD(pBuf, 1, n, pSrc_file); +} + +mz_bool mz_zip_writer_add_cfile( + mz_zip_archive* pZip, const char* pArchive_name, MZ_FILE* pSrc_file, + mz_uint64 max_size, const MZ_TIME_T* pFile_time, const void* pComment, + mz_uint16 comment_size, mz_uint level_and_flags, mz_uint32 ext_attributes, + const char* user_extra_data, mz_uint user_extra_data_len, + const char* user_extra_data_central, mz_uint user_extra_data_central_len) { + return mz_zip_writer_add_read_buf_callback( + pZip, pArchive_name, mz_file_read_func_stdio, pSrc_file, max_size, + pFile_time, pComment, comment_size, level_and_flags, ext_attributes, + user_extra_data, user_extra_data_len, user_extra_data_central, + user_extra_data_central_len); +} + +mz_bool mz_zip_writer_add_file(mz_zip_archive* pZip, const char* pArchive_name, + const char* pSrc_filename, const void* pComment, + mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint32 ext_attributes) { + MZ_FILE* pSrc_file = NULL; + mz_uint64 uncomp_size = 0; + MZ_TIME_T file_modified_time; + MZ_TIME_T* pFile_time = NULL; + mz_bool status; + + memset(&file_modified_time, 0, sizeof(file_modified_time)); + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) + pFile_time = &file_modified_time; + if (!mz_zip_get_file_modified_time(pSrc_filename, &file_modified_time)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_STAT_FAILED); +#endif + + pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); + if (!pSrc_file) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + MZ_FSEEK64(pSrc_file, 0, SEEK_END); + uncomp_size = MZ_FTELL64(pSrc_file); + MZ_FSEEK64(pSrc_file, 0, SEEK_SET); + + status = mz_zip_writer_add_cfile( + pZip, pArchive_name, pSrc_file, uncomp_size, pFile_time, pComment, + comment_size, level_and_flags, ext_attributes, NULL, 0, NULL, 0); + + MZ_FCLOSE(pSrc_file); + + return status; +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +static mz_bool mz_zip_writer_update_zip64_extension_block( + mz_zip_array* pNew_ext, mz_zip_archive* pZip, const mz_uint8* pExt, + uint32_t ext_len, mz_uint64* pComp_size, mz_uint64* pUncomp_size, + mz_uint64* pLocal_header_ofs, mz_uint32* pDisk_start) { + /* + 64 should be enough for any new zip64 data */ + if (!mz_zip_array_reserve(pZip, pNew_ext, ext_len + 64, MZ_FALSE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + mz_zip_array_resize(pZip, pNew_ext, 0, MZ_FALSE); + + if ((pUncomp_size) || (pComp_size) || (pLocal_header_ofs) || (pDisk_start)) { + mz_uint8 new_ext_block[64]; + mz_uint8* pDst = new_ext_block; + mz_write_le16(pDst, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); + mz_write_le16(pDst + sizeof(mz_uint16), 0); + pDst += sizeof(mz_uint16) * 2; + + if (pUncomp_size) { + mz_write_le64(pDst, *pUncomp_size); + pDst += sizeof(mz_uint64); + } + + if (pComp_size) { + mz_write_le64(pDst, *pComp_size); + pDst += sizeof(mz_uint64); + } + + if (pLocal_header_ofs) { + mz_write_le64(pDst, *pLocal_header_ofs); + pDst += sizeof(mz_uint64); + } + + if (pDisk_start) { + mz_write_le32(pDst, *pDisk_start); + pDst += sizeof(mz_uint32); + } + + mz_write_le16(new_ext_block + sizeof(mz_uint16), + (mz_uint16)((pDst - new_ext_block) - sizeof(mz_uint16) * 2)); + + if (!mz_zip_array_push_back(pZip, pNew_ext, new_ext_block, + pDst - new_ext_block)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if ((pExt) && (ext_len)) { + mz_uint32 extra_size_remaining = ext_len; + const mz_uint8* pExtra_data = pExt; + + do { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id != MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { + if (!mz_zip_array_push_back(pZip, pNew_ext, pExtra_data, + field_total_size)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + } + + return MZ_TRUE; +} + +/* TODO: This func is now pretty freakin complex due to zip64, split it up? */ +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive* pZip, + mz_zip_archive* pSource_zip, + mz_uint src_file_index) { + mz_uint n, bit_flags, num_alignment_padding_bytes, + src_central_dir_following_data_size; + mz_uint64 src_archive_bytes_remaining, local_dir_header_ofs; + mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; + mz_uint32 + local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / + sizeof(mz_uint32)]; + mz_uint8* pLocal_header = (mz_uint8*)local_header_u32; + mz_uint8 new_central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + size_t orig_central_dir_size; + mz_zip_internal_state* pState; + void* pBuf; + const mz_uint8* pSrc_central_header; + mz_zip_archive_file_stat src_file_stat; + mz_uint32 src_filename_len, src_comment_len, src_ext_len; + mz_uint32 local_header_filename_size, local_header_extra_len; + mz_uint64 local_header_comp_size, local_header_uncomp_size; + mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; + + /* Sanity checks */ + if ((!pZip) || (!pZip->m_pState) || + (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pSource_zip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + /* Don't support copying files from zip64 archives to non-zip64, even though + * in some cases this is possible */ + if ((pSource_zip->m_pState->m_zip64) && (!pZip->m_pState->m_zip64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Get pointer to the source central dir header and crack it */ + if (NULL == + (pSrc_central_header = mz_zip_get_cdh(pSource_zip, src_file_index))) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_SIG_OFS) != + MZ_ZIP_CENTRAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + src_filename_len = + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS); + src_comment_len = + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); + src_ext_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS); + src_central_dir_following_data_size = + src_filename_len + src_ext_len + src_comment_len; + + /* TODO: We don't support central dir's >= MZ_UINT32_MAX bytes right now (+32 + * fudge factor in case we need to add more extra data) */ + if ((pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + src_central_dir_following_data_size + 32) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + num_alignment_padding_bytes = + mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + if (!pState->m_zip64) { + if (pZip->m_total_files == MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else { + /* TODO: Our zip64 support still has some 32-bit limits that may not be + * worth fixing. */ + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + + if (!mz_zip_file_stat_internal(pSource_zip, src_file_index, + pSrc_central_header, &src_file_stat, NULL)) + return MZ_FALSE; + + cur_src_file_ofs = src_file_stat.m_local_header_ofs; + cur_dst_file_ofs = pZip->m_archive_size; + + /* Read the source archive's local dir header */ + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, + pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + /* Compute the total size we need to copy (filename+extra data+compressed + * data) */ + local_header_filename_size = + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); + local_header_extra_len = + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + local_header_comp_size = + MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); + local_header_uncomp_size = + MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); + src_archive_bytes_remaining = local_header_filename_size + + local_header_extra_len + + src_file_stat.m_comp_size; + + /* Try to find a zip64 extended information field */ + if ((local_header_extra_len) && + ((local_header_comp_size == MZ_UINT32_MAX) || + (local_header_uncomp_size == MZ_UINT32_MAX))) { + mz_zip_array file_data_array; + const mz_uint8* pExtra_data; + mz_uint32 extra_size_remaining = local_header_extra_len; + + mz_zip_array_init(&file_data_array, 1); + if (!mz_zip_array_resize(pZip, &file_data_array, local_header_extra_len, + MZ_FALSE)) { + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, + src_file_stat.m_local_header_ofs + + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + + local_header_filename_size, + file_data_array.m_p, local_header_extra_len) != + local_header_extra_len) { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + pExtra_data = (const mz_uint8*)file_data_array.m_p; + + do { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { + const mz_uint8* pSrc_field_data = pExtra_data + sizeof(mz_uint32); + + if (field_data_size < sizeof(mz_uint64) * 2) { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); + local_header_comp_size = MZ_READ_LE64( + pSrc_field_data + + sizeof(mz_uint64)); /* may be 0 if there's a descriptor */ + + found_zip64_ext_data_in_ldir = MZ_TRUE; + break; + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + + mz_zip_array_clear(pZip, &file_data_array); + } + + if (!pState->m_zip64) { + /* Try to detect if the new archive will most likely wind up too big and + * bail early (+(sizeof(mz_uint32) * 4) is for the optional descriptor which + * could be present, +64 is a fudge factor). */ + /* We also check when the archive is finalized so this doesn't need to be + * perfect. */ + mz_uint64 approx_new_archive_size = + cur_dst_file_ofs + num_alignment_padding_bytes + + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + src_archive_bytes_remaining + + (sizeof(mz_uint32) * 4) + pState->m_central_dir.m_size + + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 64; + + if (approx_new_archive_size >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + + /* Write dest archive padding */ + if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, + num_alignment_padding_bytes)) + return MZ_FALSE; + + cur_dst_file_ofs += num_alignment_padding_bytes; + + local_dir_header_ofs = cur_dst_file_ofs; + if (pZip->m_file_offset_alignment) { + MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == + 0); + } + + /* The original zip's local header+ext block doesn't change, even with zip64, + * so we can just copy it over to the dest zip */ + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + /* Copy over the source archive bytes to the dest archive, also ensure we have + * enough buf space to handle optional data descriptor */ + if (NULL == (pBuf = pZip->m_pAlloc( + pZip->m_pAlloc_opaque, 1, + (size_t)MZ_MAX(32U, MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, + src_archive_bytes_remaining))))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + while (src_archive_bytes_remaining) { + n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, + src_archive_bytes_remaining); + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, + n) != n) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + cur_src_file_ofs += n; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_dst_file_ofs += n; + + src_archive_bytes_remaining -= n; + } + + /* Now deal with the optional data descriptor */ + bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + if (bit_flags & 8) { + /* Copy data descriptor */ + if ((pSource_zip->m_pState->m_zip64) || (found_zip64_ext_data_in_ldir)) { + /* src is zip64, dest must be zip64 */ + + /* name uint32_t's */ + /* id 1 (optional in zip64?) */ + /* crc 1 */ + /* comp_size 2 */ + /* uncomp_size 2 */ + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, + pBuf, (sizeof(mz_uint32) * 6)) != + (sizeof(mz_uint32) * 6)) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + n = sizeof(mz_uint32) * + ((MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID) ? 6 : 5); + } + else { + /* src is NOT zip64 */ + mz_bool has_id; + + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, + pBuf, sizeof(mz_uint32) * 4) != + sizeof(mz_uint32) * 4) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + has_id = (MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID); + + if (pZip->m_pState->m_zip64) { + /* dest is zip64, so upgrade the data descriptor */ + const mz_uint32* pSrc_descriptor = + (const mz_uint32*)((const mz_uint8*)pBuf + + (has_id ? sizeof(mz_uint32) : 0)); + const mz_uint32 src_crc32 = pSrc_descriptor[0]; + const mz_uint64 src_comp_size = pSrc_descriptor[1]; + const mz_uint64 src_uncomp_size = pSrc_descriptor[2]; + + mz_write_le32((mz_uint8*)pBuf, MZ_ZIP_DATA_DESCRIPTOR_ID); + mz_write_le32((mz_uint8*)pBuf + sizeof(mz_uint32) * 1, src_crc32); + mz_write_le64((mz_uint8*)pBuf + sizeof(mz_uint32) * 2, src_comp_size); + mz_write_le64((mz_uint8*)pBuf + sizeof(mz_uint32) * 4, + src_uncomp_size); + + n = sizeof(mz_uint32) * 6; + } + else { + /* dest is NOT zip64, just copy it as-is */ + n = sizeof(mz_uint32) * (has_id ? 4 : 3); + } + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_src_file_ofs += n; + cur_dst_file_ofs += n; + } + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + + /* Finally, add the new central dir header */ + orig_central_dir_size = pState->m_central_dir.m_size; + + memcpy(new_central_header, pSrc_central_header, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + + if (pState->m_zip64) { + /* This is the painful part: We need to write a new central dir header + ext + * block with updated zip64 fields, and ensure the old fields (if any) are + * not included. */ + const mz_uint8* pSrc_ext = + pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len; + mz_zip_array new_ext_block; + + mz_zip_array_init(&new_ext_block, sizeof(mz_uint8)); + + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, + MZ_UINT32_MAX); + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, + MZ_UINT32_MAX); + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, + MZ_UINT32_MAX); + + if (!mz_zip_writer_update_zip64_extension_block( + &new_ext_block, pZip, pSrc_ext, src_ext_len, + &src_file_stat.m_comp_size, &src_file_stat.m_uncomp_size, + &local_dir_header_ofs, NULL)) { + mz_zip_array_clear(pZip, &new_ext_block); + return MZ_FALSE; + } + + MZ_WRITE_LE16(new_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS, + new_ext_block.m_size); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, + new_central_header, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) { + mz_zip_array_clear(pZip, &new_ext_block); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, + pSrc_central_header + + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, + src_filename_len)) { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, + MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_ext_block.m_p, + new_ext_block.m_size)) { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, + MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, + pSrc_central_header + + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + src_filename_len + src_ext_len, + src_comment_len)) { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, + MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + mz_zip_array_clear(pZip, &new_ext_block); + } + else { + /* sanity checks */ + if (cur_dst_file_ofs > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (local_dir_header_ofs >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, + local_dir_header_ofs); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, + new_central_header, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, + pSrc_central_header + + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, + src_central_dir_following_data_size)) { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, + MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + } + + /* This shouldn't trigger unless we screwed up during the initial sanity + * checks */ + if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) { + /* TODO: Support central dirs >= 32-bits in size */ + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, + MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + } + + n = (mz_uint32)orig_central_dir_size; + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, + MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + pZip->m_total_files++; + pZip->m_archive_size = cur_dst_file_ofs; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive* pZip) { + mz_zip_internal_state* pState; + mz_uint64 central_dir_ofs, central_dir_size; + mz_uint8 hdr[256]; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if (pState->m_zip64) { + if ((pZip->m_total_files > MZ_UINT32_MAX) || + (pState->m_central_dir.m_size >= MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else { + if ((pZip->m_total_files > MZ_UINT16_MAX) || + ((pZip->m_archive_size + pState->m_central_dir.m_size + + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + + central_dir_ofs = 0; + central_dir_size = 0; + if (pZip->m_total_files) { + /* Write central directory */ + central_dir_ofs = pZip->m_archive_size; + central_dir_size = pState->m_central_dir.m_size; + pZip->m_central_directory_file_ofs = central_dir_ofs; + if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, + pState->m_central_dir.m_p, + (size_t)central_dir_size) != central_dir_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += central_dir_size; + } + + if (pState->m_zip64) { + /* Write zip64 end of central directory header */ + mz_uint64 rel_ofs_to_zip64_ecdr = pZip->m_archive_size; + + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDH_SIG_OFS, + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS, + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - sizeof(mz_uint32) - + sizeof(mz_uint64)); + MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS, + 0x031E); /* TODO: always Unix */ + MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS, 0x002D); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, + pZip->m_total_files); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS, + pZip->m_total_files); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_SIZE_OFS, central_dir_size); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_OFS_OFS, central_dir_ofs); + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) != + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE; + + /* Write zip64 end of central directory locator */ + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_SIG_OFS, + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS, + rel_ofs_to_zip64_ecdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS, 1); + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) != + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE; + } + + /* Write end of central directory record */ + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, + MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, + MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, + MZ_MIN(MZ_UINT32_MAX, central_dir_size)); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, + MZ_MIN(MZ_UINT32_MAX, central_dir_ofs)); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + +#ifndef MINIZ_NO_STDIO + if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); +#endif /* #ifndef MINIZ_NO_STDIO */ + + pZip->m_archive_size += MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE; + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive* pZip, void** ppBuf, + size_t* pSize) { + if ((!ppBuf) || (!pSize)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + *ppBuf = NULL; + *pSize = 0; + + if ((!pZip) || (!pZip->m_pState)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (pZip->m_pWrite != mz_zip_heap_write_func) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_finalize_archive(pZip)) + return MZ_FALSE; + + *ppBuf = pZip->m_pState->m_pMem; + *pSize = pZip->m_pState->m_mem_size; + pZip->m_pState->m_pMem = NULL; + pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_end(mz_zip_archive* pZip) { + return mz_zip_writer_end_internal(pZip, MZ_TRUE); +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_add_mem_to_archive_file_in_place( + const char* pZip_filename, const char* pArchive_name, const void* pBuf, + size_t buf_size, const void* pComment, mz_uint16 comment_size, + mz_uint level_and_flags) { + return mz_zip_add_mem_to_archive_file_in_place_v2( + pZip_filename, pArchive_name, pBuf, buf_size, pComment, comment_size, + level_and_flags, NULL); +} + +mz_bool mz_zip_add_mem_to_archive_file_in_place_v2( + const char* pZip_filename, const char* pArchive_name, const void* pBuf, + size_t buf_size, const void* pComment, mz_uint16 comment_size, + mz_uint level_and_flags, mz_zip_error* pErr) { + mz_bool status, created_new_archive = MZ_FALSE; + mz_zip_archive zip_archive; + struct MZ_FILE_STAT_STRUCT file_stat; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + mz_zip_zero_struct(&zip_archive); + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + + if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || + ((comment_size) && (!pComment)) || + ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) { + if (pErr) + *pErr = MZ_ZIP_INVALID_FILENAME; + return MZ_FALSE; + } + + /* Important: The regular non-64 bit version of stat() can fail here if the + * file is very large, which could cause the archive to be overwritten. */ + /* So be sure to compile with _LARGEFILE64_SOURCE 1 */ + if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) { + /* Create a new archive. */ + if (!mz_zip_writer_init_file_v2(&zip_archive, pZip_filename, 0, + level_and_flags)) { + if (pErr) + *pErr = zip_archive.m_last_error; + return MZ_FALSE; + } + + created_new_archive = MZ_TRUE; + } + else { + /* Append to an existing archive. */ + if (!mz_zip_reader_init_file_v2( + &zip_archive, pZip_filename, + level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, + 0)) { + if (pErr) + *pErr = zip_archive.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_writer_init_from_reader_v2(&zip_archive, pZip_filename, + level_and_flags)) { + if (pErr) + *pErr = zip_archive.m_last_error; + + mz_zip_reader_end_internal(&zip_archive, MZ_FALSE); + + return MZ_FALSE; + } + } + + status = + mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, + pComment, comment_size, level_and_flags, 0, 0); + actual_err = zip_archive.m_last_error; + + /* Always finalize, even if adding failed for some reason, so we have a valid + * central directory. (This may not always succeed, but we can try.) */ + if (!mz_zip_writer_finalize_archive(&zip_archive)) { + if (!actual_err) + actual_err = zip_archive.m_last_error; + + status = MZ_FALSE; + } + + if (!mz_zip_writer_end_internal(&zip_archive, status)) { + if (!actual_err) + actual_err = zip_archive.m_last_error; + + status = MZ_FALSE; + } + + if ((!status) && (created_new_archive)) { + /* It's a new archive and something went wrong, so just delete it. */ + int ignoredStatus = MZ_DELETE_FILE(pZip_filename); + (void)ignoredStatus; + } + + if (pErr) + *pErr = actual_err; + + return status; +} + +void* mz_zip_extract_archive_file_to_heap_v2(const char* pZip_filename, + const char* pArchive_name, + const char* pComment, + size_t* pSize, mz_uint flags, + mz_zip_error* pErr) { + mz_uint32 file_index; + mz_zip_archive zip_archive; + void* p = NULL; + + if (pSize) + *pSize = 0; + + if ((!pZip_filename) || (!pArchive_name)) { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + + return NULL; + } + + mz_zip_zero_struct(&zip_archive); + if (!mz_zip_reader_init_file_v2( + &zip_archive, pZip_filename, + flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) { + if (pErr) + *pErr = zip_archive.m_last_error; + + return NULL; + } + + if (mz_zip_reader_locate_file_v2(&zip_archive, pArchive_name, pComment, flags, + &file_index)) { + p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); + } + + mz_zip_reader_end_internal(&zip_archive, p != NULL); + + if (pErr) + *pErr = zip_archive.m_last_error; + + return p; +} + +void* mz_zip_extract_archive_file_to_heap(const char* pZip_filename, + const char* pArchive_name, + size_t* pSize, mz_uint flags) { + return mz_zip_extract_archive_file_to_heap_v2(pZip_filename, pArchive_name, + NULL, pSize, flags, NULL); +} + +#endif /* #ifndef MINIZ_NO_STDIO */ + +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ + +/* ------------------- Misc utils */ + +mz_zip_mode mz_zip_get_mode(mz_zip_archive* pZip) { + return pZip ? pZip->m_zip_mode : MZ_ZIP_MODE_INVALID; +} + +mz_zip_type mz_zip_get_type(mz_zip_archive* pZip) { + return pZip ? pZip->m_zip_type : MZ_ZIP_TYPE_INVALID; +} + +mz_zip_error mz_zip_set_last_error(mz_zip_archive* pZip, mz_zip_error err_num) { + mz_zip_error prev_err; + + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + prev_err = pZip->m_last_error; + + pZip->m_last_error = err_num; + return prev_err; +} + +mz_zip_error mz_zip_peek_last_error(mz_zip_archive* pZip) { + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + return pZip->m_last_error; +} + +mz_zip_error mz_zip_clear_last_error(mz_zip_archive* pZip) { + return mz_zip_set_last_error(pZip, MZ_ZIP_NO_ERROR); +} + +mz_zip_error mz_zip_get_last_error(mz_zip_archive* pZip) { + mz_zip_error prev_err; + + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + prev_err = pZip->m_last_error; + + pZip->m_last_error = MZ_ZIP_NO_ERROR; + return prev_err; +} + +const char* mz_zip_get_error_string(mz_zip_error mz_err) { + switch (mz_err) { + case MZ_ZIP_NO_ERROR: + return "no error"; + case MZ_ZIP_UNDEFINED_ERROR: + return "undefined error"; + case MZ_ZIP_TOO_MANY_FILES: + return "too many files"; + case MZ_ZIP_FILE_TOO_LARGE: + return "file too large"; + case MZ_ZIP_UNSUPPORTED_METHOD: + return "unsupported method"; + case MZ_ZIP_UNSUPPORTED_ENCRYPTION: + return "unsupported encryption"; + case MZ_ZIP_UNSUPPORTED_FEATURE: + return "unsupported feature"; + case MZ_ZIP_FAILED_FINDING_CENTRAL_DIR: + return "failed finding central directory"; + case MZ_ZIP_NOT_AN_ARCHIVE: + return "not a ZIP archive"; + case MZ_ZIP_INVALID_HEADER_OR_CORRUPTED: + return "invalid header or archive is corrupted"; + case MZ_ZIP_UNSUPPORTED_MULTIDISK: + return "unsupported multidisk archive"; + case MZ_ZIP_DECOMPRESSION_FAILED: + return "decompression failed or archive is corrupted"; + case MZ_ZIP_COMPRESSION_FAILED: + return "compression failed"; + case MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE: + return "unexpected decompressed size"; + case MZ_ZIP_CRC_CHECK_FAILED: + return "CRC-32 check failed"; + case MZ_ZIP_UNSUPPORTED_CDIR_SIZE: + return "unsupported central directory size"; + case MZ_ZIP_ALLOC_FAILED: + return "allocation failed"; + case MZ_ZIP_FILE_OPEN_FAILED: + return "file open failed"; + case MZ_ZIP_FILE_CREATE_FAILED: + return "file create failed"; + case MZ_ZIP_FILE_WRITE_FAILED: + return "file write failed"; + case MZ_ZIP_FILE_READ_FAILED: + return "file read failed"; + case MZ_ZIP_FILE_CLOSE_FAILED: + return "file close failed"; + case MZ_ZIP_FILE_SEEK_FAILED: + return "file seek failed"; + case MZ_ZIP_FILE_STAT_FAILED: + return "file stat failed"; + case MZ_ZIP_INVALID_PARAMETER: + return "invalid parameter"; + case MZ_ZIP_INVALID_FILENAME: + return "invalid filename"; + case MZ_ZIP_BUF_TOO_SMALL: + return "buffer too small"; + case MZ_ZIP_INTERNAL_ERROR: + return "internal error"; + case MZ_ZIP_FILE_NOT_FOUND: + return "file not found"; + case MZ_ZIP_ARCHIVE_TOO_LARGE: + return "archive is too large"; + case MZ_ZIP_VALIDATION_FAILED: + return "validation failed"; + case MZ_ZIP_WRITE_CALLBACK_FAILED: + return "write callback failed"; + case MZ_ZIP_TOTAL_ERRORS: + return "total errors"; + default: + break; + } + + return "unknown error"; +} + +/* Note: Just because the archive is not zip64 doesn't necessarily mean it + * doesn't have Zip64 extended information extra field, argh. */ +mz_bool mz_zip_is_zip64(mz_zip_archive* pZip) { + if ((!pZip) || (!pZip->m_pState)) + return MZ_FALSE; + + return pZip->m_pState->m_zip64; +} + +size_t mz_zip_get_central_dir_size(mz_zip_archive* pZip) { + if ((!pZip) || (!pZip->m_pState)) + return 0; + + return pZip->m_pState->m_central_dir.m_size; +} + +mz_uint mz_zip_reader_get_num_files(mz_zip_archive* pZip) { + return pZip ? pZip->m_total_files : 0; +} + +mz_uint64 mz_zip_get_archive_size(mz_zip_archive* pZip) { + if (!pZip) + return 0; + return pZip->m_archive_size; +} + +mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive* pZip) { + if ((!pZip) || (!pZip->m_pState)) + return 0; + return pZip->m_pState->m_file_archive_start_ofs; +} + +MZ_FILE* mz_zip_get_cfile(mz_zip_archive* pZip) { + if ((!pZip) || (!pZip->m_pState)) + return 0; + return pZip->m_pState->m_pFile; +} + +size_t mz_zip_read_archive_data(mz_zip_archive* pZip, mz_uint64 file_ofs, + void* pBuf, size_t n) { + if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + return pZip->m_pRead(pZip->m_pIO_opaque, file_ofs, pBuf, n); +} + +mz_uint mz_zip_reader_get_filename(mz_zip_archive* pZip, mz_uint file_index, + char* pFilename, mz_uint filename_buf_size) { + mz_uint n; + const mz_uint8* p = mz_zip_get_cdh(pZip, file_index); + if (!p) { + if (filename_buf_size) + pFilename[0] = '\0'; + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return 0; + } + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_buf_size) { + n = MZ_MIN(n, filename_buf_size - 1); + memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pFilename[n] = '\0'; + } + return n + 1; +} + +mz_bool mz_zip_reader_file_stat(mz_zip_archive* pZip, mz_uint file_index, + mz_zip_archive_file_stat* pStat) { + return mz_zip_file_stat_internal( + pZip, file_index, mz_zip_get_cdh(pZip, file_index), pStat, NULL); +} + +mz_bool mz_zip_end(mz_zip_archive* pZip) { + if (!pZip) + return MZ_FALSE; + + if (pZip->m_zip_mode == MZ_ZIP_MODE_READING) + return mz_zip_reader_end(pZip); +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + else if ((pZip->m_zip_mode == MZ_ZIP_MODE_WRITING) || + (pZip->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)) + return mz_zip_writer_end(pZip); +#endif + + return MZ_FALSE; +} + + +#endif /*#ifndef MINIZ_NO_ARCHIVE_APIS*/ diff --git a/Update/Update.cpp b/Update/Update.cpp new file mode 100644 index 0000000..3275f24 --- /dev/null +++ b/Update/Update.cpp @@ -0,0 +1,57 @@ +#include "Update.h" +#include "Worker.h" +#include +#include +Update::Update(QWidget *parent):QWidget(parent) +{ + ui.setupUi(this); + + Worker* worker = new Worker(); + + + connect(worker,&Worker::signalProgress,this,&Update::slotUpdateProgress); + connect(worker,&Worker::sigShowStatus,this,&Update::slotUpdateInfo); + connect(worker, &Worker::signalFinished, this, &Update::slotFinished); + worker->start(); +} + +Update::~Update() +{ + +} + + + +// 更新进度 +void Update::slotUpdateProgress(qintptr progress, qintptr max) +{ + qDebug() << "更新进度"; + if (progress > 0 && max > 0) + { + qDebug() << "设置进度:" << progress << "|" << max; + ui.progressBar->setMaximum(max); + ui.progressBar->setValue(progress); + if (progress == max) + { + slotFinished(); + } + } + + +} + +// 完成更新 +void Update::slotFinished() +{ + QMessageBox::information(NULL, "提示", "更新完成!"); + exit(1); + // 启动主程序 + + // 关闭更新程序自身 + +} + +void Update::slotUpdateInfo(QString info) +{ + ui.versionInfo->append(info); +} diff --git a/Update/Update.h b/Update/Update.h new file mode 100644 index 0000000..177bd5f --- /dev/null +++ b/Update/Update.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include "ui_Update.h" + +class Update : public QWidget +{ + Q_OBJECT + +public: + Update(QWidget *parent = nullptr); + ~Update(); + +public slots: + void slotUpdateProgress(qintptr progress, qintptr max); + void slotFinished(); + void slotUpdateInfo(QString info); + +private: + Ui::UpdateClass ui; +}; diff --git a/Update/Update.qrc b/Update/Update.qrc new file mode 100644 index 0000000..9ca172d --- /dev/null +++ b/Update/Update.qrc @@ -0,0 +1,9 @@ + + + res/alert.png + res/close_0_28_28.png + res/close_1_28_28.png + res/close_2_28_28.png + res/bg.gif + + diff --git a/Update/Update.rc b/Update/Update.rc new file mode 100644 index 0000000..51a448f --- /dev/null +++ b/Update/Update.rc @@ -0,0 +1,100 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// ÖÐÎÄ(¼òÌ壬Öйú) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS) +LANGUAGE LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED +#pragma code_page(936) + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,0,0,1 + PRODUCTVERSION 1,0,0,1 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x40004L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "080404b0" + BEGIN + VALUE "CompanyName", "TODO: <¹«˾Ãû>" + VALUE "FileDescription", "TODO: <Îļþ˵Ã÷>" + VALUE "FileVersion", "1.0.0.1" + VALUE "InternalName", "Update.exe" + VALUE "LegalCopyright", "Copyright (C) 2023" + VALUE "OriginalFilename", "Update.exe" + VALUE "ProductName", "TODO: <²úƷÃû>" + VALUE "ProductVersion", "1.0.0.1" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x804, 1200 + END +END + +#endif // ÖÐÎÄ(¼òÌ壬Öйú) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/Update/Update.ui b/Update/Update.ui new file mode 100644 index 0000000..81c6a9c --- /dev/null +++ b/Update/Update.ui @@ -0,0 +1,79 @@ + + + UpdateClass + + + + 0 + 0 + 540 + 370 + + + + Update + + + + + + 7 + + + QLayout::SetDefaultConstraint + + + + + + 微软雅黑 + 10 + + + + 0 + + + true + + + Qt::Horizontal + + + QProgressBar::TopToBottom + + + + + + + + 0 + 50 + + + + + 微软雅黑 + 12 + + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'微软雅黑'; font-size:12pt; font-weight:400; font-style:normal;"> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> + + + + + + + + + + + + + diff --git a/Update/Update.vcxproj b/Update/Update.vcxproj new file mode 100644 index 0000000..ba159b1 --- /dev/null +++ b/Update/Update.vcxproj @@ -0,0 +1,214 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {9CBBB245-EA92-4F87-A00E-70C3D10F86E8} + QtVS_v304 + 10.0 + 10.0.17763.0 + 10.0.17763.0 + 10.0.17763.0 + $(MSBuildProjectDirectory)\QtMsBuild + + + + Application + v143 + + + Application + v141 + + + Application + v143 + + + Application + v141 + + + + + + + 5.12.5_msvc2017_64 + core;xml;network;gui;widgets + debug + + + 5.15.2_msvc2017_static + core;xml;network;gui;widgets + debug + + + 5.12.5_msvc2017_64 + core;xml;network;gui;widgets + release + + + 5.15.2_msvc2017_static + core;xml;network;gui;widgets + release + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /utf-8 %(AdditionalOptions) + + + + + + + /utf-8 %(AdditionalOptions) + MultiThreaded + + + + + + /utf-8 %(AdditionalOptions) + + + + + + /utf-8 %(AdditionalOptions) + MultiThreadedDebug + + + + + true + true + ProgramDatabase + Disabled + + + Windows + true + + + + + true + true + ProgramDatabase + Disabled + + + Windows + true + + + + + true + true + None + MaxSpeed + + + Windows + false + + + + + true + true + None + MaxSpeed + + + Windows + false + + + + + + + + + + + + input + input + %(Filename).moc + %(Filename).moc + input + input + %(Filename).moc + %(Filename).moc + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Update/Update.vcxproj.filters b/Update/Update.vcxproj.filters new file mode 100644 index 0000000..30fba93 --- /dev/null +++ b/Update/Update.vcxproj.filters @@ -0,0 +1,90 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + qml;cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + qrc;rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + {639EADAA-A684-42e4-A9AD-28FC9BCB8F7C} + ts + + + {4e4e8d8b-11ef-46c3-b18a-14d84970aaef} + + + {2c7bc095-d5bd-4ead-8de0-85ce763a70b8} + + + {222b971c-a4d2-4003-9645-92207e952f59} + + + + + Resource Files + + + + + Source Files + + + Source Files + + + Source Files\Form + + + Source Files\FileInfo + + + Source Files + + + Source Files\Zip + + + + + Source Files + + + Source Files\Form + + + + + Source Files\Form + + + + + Source Files\FileInfo + + + Source Files + + + Header Files + + + Source Files\Zip + + + Source Files\Zip + + + + + Resource Files + + + \ No newline at end of file diff --git a/Update/Update.xml b/Update/Update.xml new file mode 100644 index 0000000..23d7c10 --- /dev/null +++ b/Update/Update.xml @@ -0,0 +1,157 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Update/Utils.cpp b/Update/Utils.cpp new file mode 100644 index 0000000..c77bb2a --- /dev/null +++ b/Update/Utils.cpp @@ -0,0 +1,41 @@ +#include "Utils.h" + +Utils::Utils() +{ +} + +Utils::~Utils() +{ +} + +Utils &Utils::instance() +{ + static Utils m_instance; + return m_instance; +} +// 不要忘记在使用完wchar_t*后delete[]释放内存 +WCHAR* Utils::A2W(const CHAR* ansi) +{ + // 第一次调用返回转换后的字符串长度,用于确认为wchar_t*开辟多大的内存空间 + int size = MultiByteToWideChar(CP_OEMCP, 0, ansi, strlen(ansi) + 1, NULL, 0); + WCHAR* buffer = new WCHAR[size]; + // 第二次调用将单字节字符串转换成双字节字符串 + MultiByteToWideChar(CP_OEMCP, 0, ansi, strlen(ansi) + 1, buffer, size); + return buffer; +} + +// 不要忘记使用完char*后delete[]释放内存 +CHAR* Utils::W2A(const WCHAR* unicode) +{ + //第一次调用确认转换后单字节字符串的长度,用于开辟空间 + int length = WideCharToMultiByte(CP_OEMCP, 0, unicode, wcslen(unicode), NULL, 0, NULL, NULL); + char* buffer = new char[length + 1]; + //第二次调用将双字节字符串转换成单字节字符串 + WideCharToMultiByte(CP_OEMCP, 0, unicode, wcslen(unicode), buffer, length, NULL, NULL); + buffer[length] = '\0'; + return buffer; + + //如果想要转换成string,直接赋值即可 + //string pKey = pCStrKey; +} + diff --git a/Update/Utils.h b/Update/Utils.h new file mode 100644 index 0000000..01e87a7 --- /dev/null +++ b/Update/Utils.h @@ -0,0 +1,14 @@ +#pragma once +#include +#include +class Utils +{ +private: + Utils(); + ~Utils(); +public: + static Utils& instance(); +public: + WCHAR* A2W(const CHAR* ansi); + CHAR* W2A(const WCHAR* unicode); +}; \ No newline at end of file diff --git a/Update/Worker.cpp b/Update/Worker.cpp new file mode 100644 index 0000000..7d0b9f1 --- /dev/null +++ b/Update/Worker.cpp @@ -0,0 +1,435 @@ +#include "Worker.h" +#include +#include +#include +#include +#include +#include +#include "FileInfo.h" +#include "Utils.h" +#include + + +Worker::Worker() +{ + qDebug() << "线程初始化"; + // 初始化文件总大小 + m_downloadSize=0; + m_filesSize = 0; + // 保存XML文件下载地址 + m_url = "http://88.151.33.134:5666/Crown"; + + connect(this,&Worker::signalCheckUpdate,this,&Worker::slotCheckUpdate); +} + +Worker::~Worker() +{ + +} + +void Worker::slotCheckUpdate() +{ + QList files; + // 解析XML文件获取最新文件列表 + this->parseXML(QCoreApplication::applicationDirPath() + "/Update.xml"); + for (int i = 0; i < m_fileInfo.count(); i++) + { + QFileInfo fileInfo(QCoreApplication::applicationDirPath() + "/" + m_fileInfo.at(i).path); + QDir dir(QCoreApplication::applicationDirPath() + "/" + m_fileInfo.at(i).path); + // 如果文件不存在则直接下载文件或创建文件夹 + if (!fileInfo.exists()) + { + if (m_fileInfo[i].type == "File") + { + // 下载文件 + qDebug() << "文件大小" << m_fileInfo[i].size; + m_filesSize += m_fileInfo[i].size; + files.append(m_fileInfo[i]); + } + else if (m_fileInfo[i].type == "Dir") + { + // 创建文件夹 + dir.mkpath(QCoreApplication::applicationDirPath() + "/" + m_fileInfo.at(i).path); + } + continue; + } + + // 存在版本信息则对比版本 + if (!m_fileInfo[i].version.isEmpty()) + { + // 如果是文件则获取版本对比 + if (fileInfo.isFile()) + { + QString version = this->getFileVertion(QCoreApplication::applicationDirPath() + "/" + m_fileInfo.at(i).path); + + if (!version.contains(m_fileInfo[i].version)) + { + qDebug() << m_fileInfo [i].path << "当前版本: " << version << "| 最新版本: " << m_fileInfo[i].version; + m_filesSize += m_fileInfo[i].size; + // 版本号不一致则下载文件 + files.append(m_fileInfo[i]); + continue; + } + } + } + + } + + qDebug() << "更新文件数量:" << files.count(); + qDebug() << "更新文件总大小:" << m_filesSize; + + for (int i = 0; i < files.count(); i++) + { + QUrl url = QUrl::fromUserInput(m_url + "/Update/"+ files[i].path); + // 失败直接加上目标文件大小 + if (FAILURE == download(&url, QCoreApplication::applicationDirPath() + "/" + files[i].path, "正在下载:" + files[i].name)) + { + m_downloadSize += files[i].size; + } + } + + + +} + +QString Worker::getFileVertion(QString fullName) +{ + QString result = ""; + char* pData = nullptr; + do + { + DWORD dwLen = GetFileVersionInfoSize(fullName.toStdWString().c_str(), 0); + if (0 == dwLen) + { + break; + } + pData = new char[dwLen + 1]; + BOOL bSuccess = GetFileVersionInfo(fullName.toStdWString().c_str(), 0, dwLen, pData); + if (!bSuccess) + { + break; + } + struct LANGANDCODEPAGE + { + WORD wLanguage; + WORD wCodePage; + } *lpTranslate; + LPVOID lpBuffer = nullptr; + UINT uLen = 0; + bSuccess = VerQueryValue(pData, (TEXT("\\VarFileInfo\\Translation")), (LPVOID*)&lpTranslate, &uLen); + if (!bSuccess) + { + break; + } + QString str1, str2; + str1.setNum(lpTranslate->wLanguage, 16); + str2.setNum(lpTranslate->wCodePage, 16); + str1 = "000" + str1; + str2 = "000" + str2; + QString verPath = "\\StringFileInfo\\" + str1.right(4) + str2.right(4) + "\\FileVersion";//ProductVersion:产品版本号 FileVersion:文件版本号 + bSuccess = VerQueryValue(pData, (verPath.toStdWString().c_str()), &lpBuffer, &uLen); + if (!bSuccess) + { + break; + } + result = QString::fromUtf16((const unsigned short int *)lpBuffer); + } while (false); + if (nullptr != pData) + { + delete pData; + } + return result; +} + +QList Worker::FindFile(const QString& path) +{ + QList result; + + // QDir的路径一定要是全路径,相对路径会有错误 + QDir dir(path); + if (!dir.exists()) + { + return result; + } + + + // 取到所有的文件和文件名,去掉.和..文件夹 + dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot); + // 设置排序方式 + dir.setSorting(QDir::DirsFirst); + // 将其转化为一个list + QFileInfoList list = dir.entryInfoList(); + if (list.size() < 1) + { + return result; + } + + + int i = 0; + // 采用递归算法 + do { + QFileInfo fileInfo = list.at(i); + FILE_INFO file; + // 判断是否为文件夹 + bool isDirectory = fileInfo.isDir(); + if (isDirectory) + { + qDebug() << "[Dir]" << fileInfo.filePath() << " -> " << fileInfo.size() << " -> " << file.version; + // 获取文件信息 + file.path = fileInfo.filePath(); + file.size = 0; + file.type = "Dir"; + file.version.clear(); + auto tmp = FindFile(fileInfo.filePath()); + result = result + tmp; + } + else + { + // 获取文件信息 + file.path = fileInfo.filePath(); + file.size = fileInfo.size(); + file.type = "File"; + file.version = this->getFileVertion(file.path); + result.append(file); + // qDebug() << "[File]" << fileInfo.filePath() << " -> " << fileInfo.size() << " -> " << file.version; + } + ++i; + } while (i < list.size()); + + return result; +} + +void Worker::run() +{ + // 开始工作 + m_currentState = DownloadXML; + // 下载XML文件 + QUrl xmlUrl = QUrl::fromUserInput(m_url + "/Update.xml"); + qDebug() << "下载地址:" << m_url + "/Update.xml"; + download(&xmlUrl, QCoreApplication::applicationDirPath() + "/Update.xml", "正在检查更新"); +} + +void Worker::updateProgress(qint64 dowloadedBytes, qint64 totalBytes) +{ + + + int statusCode = m_networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + if (m_currentState!= DownloadXML) + { + m_downloadTempSize = dowloadedBytes; + if (dowloadedBytes == totalBytes) + { + // 下载完成一个文件清空临时大小并附加到总大小 + m_downloadSize += m_downloadTempSize; + m_downloadTempSize = 0; + emit signalProgress(m_downloadSize, m_filesSize); + } + else + { + emit signalProgress(m_downloadSize + m_downloadTempSize, m_filesSize); + } + qDebug() << "下载进度: " << m_downloadSize << "|" << dowloadedBytes << "|"<< totalBytes << "|"; + + + + + } +} + +void Worker::slotReadyRead() +{ + int statusCode = m_networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + if (statusCode == 200) + { + + QByteArray bytes = m_networkReply->readAll(); + m_downloadFile->write(bytes); + } +} + +void Worker::slotFinished() +{ + + int statusCode = m_networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + qDebug() << "代码:" << statusCode; + switch (statusCode) + { + case 200: + // 关闭文件 + m_downloadFile->close(); + // 销毁文件类 + delete m_downloadFile; + // 销毁网络请求类 + m_networkReply->deleteLater(); + // 销毁网络管理类 + m_networkManager->deleteLater(); + + switch (m_currentState) + { + case DownloadXML: + connect(this, SIGNAL(sigCheckUpdate()), this, SLOT(checkUpdate())); + // 更新状态 + m_currentState = DownloadUpdate; + // 发出检查更新信号 + emit signalCheckUpdate(); + break; + case DownloadUpdate: + qDebug() << "[结束]下载进度: "<< m_downloadSize ; + break; + default: + break; + } + break; + case 302: + { + qDebug() << "重定向"; + // 重定向 再次尝试 + QUrl url = m_networkReply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); + m_networkReply = m_networkManager->get(QNetworkRequest(url)); + connect(m_networkReply, SIGNAL(readyRead()), this, SLOT(slotReadyRead())); + connect(m_networkReply, SIGNAL(finished()), this, SLOT(slotFinished())); + connect(m_networkReply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(updateProgress(qint64, qint64))); + break; + } + default: + qDebug() << "网络错误"; + emit signalError("网络错误", "错误代码: " + QString::number(statusCode)); + m_downloadFile->close(); + delete m_downloadFile; + m_networkReply->deleteLater(); + m_networkManager->deleteLater(); + break; + } +} + +// 下载文件 +int Worker::download(QUrl *url, QString path, QString status) +{ + if (!url->isValid()) + { + qDebug() << "下载失败: 网址无效"; + emit signalError("无效网址", "目标网址无效"); + return FAILURE; + } + m_downloadFile = new QFile(path); + if (!m_downloadFile->open(QIODevice::WriteOnly)) + { + qDebug() << "下载失败: 无法打开文件" << path; + emit signalError("文件操作失败", "无法打开临时文件!"); + return FAILURE; + } + + + + m_networkManager = new QNetworkAccessManager; + m_networkReply = m_networkManager->get(QNetworkRequest(*url)); + connect(m_networkReply, SIGNAL(readyRead()), this, SLOT(slotReadyRead())); + connect(m_networkReply, SIGNAL(finished()), this, SLOT(slotFinished())); + connect(m_networkReply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(updateProgress(qint64, qint64))); + + emit sigShowStatus(status); + // 事件循环 + QEventLoop eventLoop; + // 连接信号和槽 + connect(m_networkManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit())); + // 开始循环 + eventLoop.exec(); + + qDebug() << "开始下载"; + // 更新状态 + + return SUCCESS; +} + + + +// 解析XML文件 +void Worker::parseXML(QString fileName) +{ + // 避免中文乱码 + QTextCodec *codec = QTextCodec::codecForName("UTF8"); + QFile file(fileName); + + // 打开XML文件 + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) + { + emit signalError("文件操作失败", "无法打开XML文件!"); + return; + } + + // 读取XML文件并解析 + QDomDocument doc; + if (!doc.setContent(&file)) + { + emit signalError("文件操作失败","无法解析XML文件!"); + file.close(); + return; + } + file.close(); + + // 获取根节点 + QDomElement root = doc.documentElement(); + // 获取第一个子节点 + QDomNode node = root.firstChild(); + // 遍历子节点 + while (!node.isNull()) + { + // 如果节点是元素 + if (node.isElement()) + { + // 转换为元素 + QDomElement element = node.toElement(); + if (!element.isNull()) + { + FILE_INFO fileInfo; + fileInfo.name = element.attribute("name"); + fileInfo.path = element.attribute("path"); + fileInfo.size = element.attribute("size").toInt(); + + fileInfo.type = element.attribute("type"); + fileInfo.version = element.attribute("version"); + m_fileInfo.append(fileInfo); + } + } + // 下一个兄弟节点 + node = node.nextSibling(); + } +} + +// 删除文件或目录 +bool Worker::deleteFileOrDirectory(QString path) +{ + // 判断路径是否为空 + if (path.isEmpty() || !QDir().exists(path)) + { + return false; + } + + QFileInfo fileInfo(path); + // 删除文件 + if (fileInfo.isFile()) + { + return QFile::remove(path); + } + // 删除目录 + else if (fileInfo.isDir()) + { + QDir dir(path); + dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); + QFileInfoList fileList = dir.entryInfoList(); + foreach(QFileInfo fi, fileList) + { + if (fi.isFile()) + { + fi.dir().remove(fi.fileName()); + } + else + { + deleteFileOrDirectory(fi.absoluteFilePath()); + } + } + dir.rmpath(dir.absolutePath()); + } + return true; +} + diff --git a/Update/Worker.h b/Update/Worker.h new file mode 100644 index 0000000..64e903f --- /dev/null +++ b/Update/Worker.h @@ -0,0 +1,92 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + + +// 检查更新 +#define MSG_CHECK_UPDATE "正在检查更新..." +// 更新中 +#define MSG_UPDATE "更新中..." +// 正在启动游戏 +#define MSG_LAUNCH "Launching the game..." +#define SUCCESS 1 +#define FAILURE 0 + + +typedef enum _ProgramState +{ + // 下载XML + DownloadXML, + // 下载游戏 + DownloadUpdate, +}ProgramState; + +typedef struct _FILE_INFO { + QString name; + QString path; + QString type; + QString version; + int size; +}FILE_INFO; + + +class Worker : public QThread { + + Q_OBJECT +public: + Worker(); + ~Worker(); +private: + QNetworkAccessManager* m_networkManager; + QNetworkReply* m_networkReply; + QList m_fileInfo; +private: + QString getFileVertion(QString fullName); + QList FindFile(const QString& path); +signals: + // 显示下载进度 + void signalProgress(qint64, qint64); + // 显示状态信息 + void sigShowStatus(const QString &); + // 显示更新信息 + void sigShowInfo(const QString &); + // 显示错误信息 + void signalError(const QString &, const QString &); + // 检查更新 + void signalCheckUpdate(); + // 启动客户端 + void sigLaunchGame(); + // 退出 + void signalFinished(); + +private slots: + void slotCheckUpdate(); + void updateProgress(qint64, qint64); // update the progress bar + + void slotReadyRead(); + void slotFinished(); +public: + void run(); +private: + // 当前状态 + ProgramState m_currentState; + // XML文件下载地址 + QString m_url; + + // 全部文件下载大小 + qint64 m_downloadSize; + // 需要下载文件总大小 + qint64 m_filesSize; + // 当前文件大小 + qint64 m_downloadTempSize; + QFile* m_downloadFile; + bool showProgress; + int download(QUrl*, QString, QString); + void parseXML(QString); + bool deleteFileOrDirectory(QString path); +}; diff --git a/Update/Zip.cpp b/Update/Zip.cpp new file mode 100644 index 0000000..cc432e8 --- /dev/null +++ b/Update/Zip.cpp @@ -0,0 +1,1791 @@ +/* + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ +#define __STDC_WANT_LIB_EXT1__ 1 + +#include +#include +#include + +#if defined(_WIN32) || defined(__WIN32__) || defined(_MSC_VER) || \ + defined(__MINGW32__) + /* Win32, DOS, MSVC, MSVS */ +#include + +#define STRCLONE(STR) ((STR) ? _strdup(STR) : NULL) +#define HAS_DEVICE(P) \ + ((((P)[0] >= 'A' && (P)[0] <= 'Z') || ((P)[0] >= 'a' && (P)[0] <= 'z')) && \ + (P)[1] == ':') +#define FILESYSTEM_PREFIX_LEN(P) (HAS_DEVICE(P) ? 2 : 0) + +#else + +#include // needed for symlink() +#define STRCLONE(STR) ((STR) ? strdup(STR) : NULL) + +#endif + +#ifdef __MINGW32__ +#include +#include +#endif + +#include "miniz.h" +#include "zip.h" + +#ifdef _MSC_VER +#include + +#define ftruncate(fd, sz) (-(_chsize_s((fd), (sz)) != 0)) +#define fileno _fileno +#endif + +#if defined(__TINYC__) && (defined(_WIN32) || defined(_WIN64)) +#include + +#define ftruncate(fd, sz) (-(_chsize_s((fd), (sz)) != 0)) +#define fileno _fileno +#endif + +#ifndef HAS_DEVICE +#define HAS_DEVICE(P) 0 +#endif + +#ifndef FILESYSTEM_PREFIX_LEN +#define FILESYSTEM_PREFIX_LEN(P) 0 +#endif + +#ifndef ISSLASH +#define ISSLASH(C) ((C) == '/' || (C) == '\\') +#endif + +#define CLEANUP(ptr) \ + do { \ + if (ptr) { \ + free((void *)ptr); \ + ptr = NULL; \ + } \ + } while (0) + +#define UNX_IFDIR 0040000 /* Unix directory */ +#define UNX_IFREG 0100000 /* Unix regular file */ +#define UNX_IFSOCK 0140000 /* Unix socket (BSD, not SysV or Amiga) */ +#define UNX_IFLNK 0120000 /* Unix symbolic link (not SysV, Amiga) */ +#define UNX_IFBLK 0060000 /* Unix block special (not Amiga) */ +#define UNX_IFCHR 0020000 /* Unix character special (not Amiga) */ +#define UNX_IFIFO 0010000 /* Unix fifo (BCC, not MSC or Amiga) */ + +struct zip_entry_t { + ssize_t index; + char* name; + mz_uint64 uncomp_size; + mz_uint64 comp_size; + mz_uint32 uncomp_crc32; + mz_uint64 offset; + mz_uint8 header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + mz_uint64 header_offset; + mz_uint16 method; + mz_zip_writer_add_state state; + tdefl_compressor comp; + mz_uint32 external_attr; + time_t m_time; +}; + +struct zip_t { + mz_zip_archive archive; + mz_uint level; + struct zip_entry_t entry; +}; + +enum zip_modify_t { + MZ_KEEP = 0, + MZ_DELETE = 1, + MZ_MOVE = 2, +}; + +struct zip_entry_mark_t { + ssize_t file_index; + enum zip_modify_t type; + mz_uint64 m_local_header_ofs; + size_t lf_length; +}; + +static const char* const zip_errlist[30] = { + NULL, + "not initialized\0", + "invalid entry name\0", + "entry not found\0", + "invalid zip mode\0", + "invalid compression level\0", + "no zip 64 support\0", + "memset error\0", + "cannot write data to entry\0", + "cannot initialize tdefl compressor\0", + "invalid index\0", + "header not found\0", + "cannot flush tdefl buffer\0", + "cannot write entry header\0", + "cannot create entry header\0", + "cannot write to central dir\0", + "cannot open file\0", + "invalid entry type\0", + "extracting data using no memory allocation\0", + "file not found\0", + "no permission\0", + "out of memory\0", + "invalid zip archive name\0", + "make dir error\0", + "symlink error\0", + "close archive error\0", + "capacity size too small\0", + "fseek error\0", + "fread error\0", + "fwrite error\0", +}; + +const char* zip_strerror(int errnum) { + errnum = -errnum; + if (errnum <= 0 || errnum >= 30) { + return NULL; + } + + return zip_errlist[errnum]; +} + +static const char* zip_basename(const char* name) { + char const* p; + char const* base = name += FILESYSTEM_PREFIX_LEN(name); + int all_slashes = 1; + + for (p = name; *p; p++) { + if (ISSLASH(*p)) + base = p + 1; + else + all_slashes = 0; + } + + /* If NAME is all slashes, arrange to return `/'. */ + if (*base == '\0' && ISSLASH(*name) && all_slashes) + --base; + + return base; +} + +static int zip_mkpath(char* path) { + char* p; + char npath[MAX_PATH + 1]; + int len = 0; + int has_device = HAS_DEVICE(path); + + memset(npath, 0, MAX_PATH + 1); + if (has_device) { + // only on windows + npath[0] = path[0]; + npath[1] = path[1]; + len = 2; + } + for (p = path + len; *p && len < MAX_PATH; p++) { + if (ISSLASH(*p) && ((!has_device && len > 0) || (has_device && len > 2))) { +#if defined(_WIN32) || defined(__WIN32__) || defined(_MSC_VER) || \ + defined(__MINGW32__) +#else + if ('\\' == *p) { + *p = '/'; + } +#endif + + if (MZ_MKDIR(npath) == -1) { + if (errno != EEXIST) { + return ZIP_EMKDIR; + } + } + } + npath[len++] = *p; + } + + return 0; +} + +static char* zip_strrpl(const char* str, size_t n, char oldchar, char newchar) { + char c; + size_t i; + char* rpl = (char*)calloc((1 + n), sizeof(char)); + char* begin = rpl; + if (!rpl) { + return NULL; + } + + for (i = 0; (i < n) && (c = *str++); ++i) { + if (c == oldchar) { + c = newchar; + } + *rpl++ = c; + } + + return begin; +} + +static char* zip_name_normalize(char* name, char* const nname, size_t len) { + size_t offn = 0; + size_t offnn = 0, ncpy = 0; + + if (name == NULL || nname == NULL || len <= 0) { + return NULL; + } + // skip trailing '/' + while (ISSLASH(*name)) + name++; + + for (; offn < len; offn++) { + if (ISSLASH(name[offn])) { + if (ncpy > 0 && strcmp(&nname[offnn], ".\0") && + strcmp(&nname[offnn], "..\0")) { + offnn += ncpy; + nname[offnn++] = name[offn]; // append '/' + } + ncpy = 0; + } + else { + nname[offnn + ncpy] = name[offn]; + ncpy++; + } + } + + // at the end, extra check what we've already copied + if (ncpy == 0 || !strcmp(&nname[offnn], ".\0") || + !strcmp(&nname[offnn], "..\0")) { + nname[offnn] = 0; + } + return nname; +} + +static mz_bool zip_name_match(const char* name1, const char* name2) { + char* nname2 = NULL; + +#ifdef ZIP_RAW_ENTRYNAME + nname2 = STRCLONE(name2); +#else + nname2 = zip_strrpl(name2, strlen(name2), '\\', '/'); +#endif + + if (!nname2) { + return MZ_FALSE; + } + + mz_bool res = (strcmp(name1, nname2) == 0) ? MZ_TRUE : MZ_FALSE; + CLEANUP(nname2); + return res; +} + +static int zip_archive_truncate(mz_zip_archive* pzip) { + mz_zip_internal_state* pState = pzip->m_pState; + mz_uint64 file_size = pzip->m_archive_size; + if ((pzip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) { + return 0; + } + if (pzip->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED) { + if (pState->m_pFile) { + int fd = fileno(pState->m_pFile); + return ftruncate(fd, file_size); + } + } + return 0; +} + +static int zip_archive_extract(mz_zip_archive* zip_archive, const char* dir, + int (*on_extract)(const char* filename, + void* arg), + void* arg) { + int err = 0; + mz_uint i, n; + char path[MAX_PATH + 1]; + char symlink_to[MAX_PATH + 1]; + mz_zip_archive_file_stat info; + size_t dirlen = 0, filename_size = MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE; + mz_uint32 xattr = 0; + + memset(path, 0, sizeof(path)); + memset(symlink_to, 0, sizeof(symlink_to)); + + dirlen = strlen(dir); + if (dirlen + 1 > MAX_PATH) { + return ZIP_EINVENTNAME; + } + + memset((void*)&info, 0, sizeof(mz_zip_archive_file_stat)); + +#if defined(_MSC_VER) + strcpy_s(path, MAX_PATH, dir); +#else + strcpy(path, dir); +#endif + + if (!ISSLASH(path[dirlen - 1])) { +#if defined(_WIN32) || defined(__WIN32__) + path[dirlen] = '\\'; +#else + path[dirlen] = '/'; +#endif + ++dirlen; + } + + if (filename_size > MAX_PATH - dirlen) { + filename_size = MAX_PATH - dirlen; + } + // Get and print information about each file in the archive. + n = mz_zip_reader_get_num_files(zip_archive); + for (i = 0; i < n; ++i) { + if (!mz_zip_reader_file_stat(zip_archive, i, &info)) { + // Cannot get information about zip archive; + err = ZIP_ENOENT; + goto out; + } + + if (!zip_name_normalize(info.m_filename, info.m_filename, + strlen(info.m_filename))) { + // Cannot normalize file name; + err = ZIP_EINVENTNAME; + goto out; + } + +#if defined(_MSC_VER) + strncpy_s(&path[dirlen], filename_size, info.m_filename, + filename_size); +#else + strncpy(&path[dirlen], info.m_filename, filename_size); +#endif + err = zip_mkpath(path); + if (err < 0) { + // Cannot make a path + goto out; + } + + if ((((info.m_version_made_by >> 8) == 3) || + ((info.m_version_made_by >> 8) == + 19)) // if zip is produced on Unix or macOS (3 and 19 from + // section 4.4.2.2 of zip standard) + && info.m_external_attr & + (0x20 << 24)) { // and has sym link attribute (0x80 is file, 0x40 + // is directory) +#if defined(_WIN32) || defined(__WIN32__) || defined(_MSC_VER) || \ + defined(__MINGW32__) +#else + if (info.m_uncomp_size > MAX_PATH || + !mz_zip_reader_extract_to_mem_no_alloc(zip_archive, i, symlink_to, + MAX_PATH, 0, NULL, 0)) { + err = ZIP_EMEMNOALLOC; + goto out; + } + symlink_to[info.m_uncomp_size] = '\0'; + if (symlink(symlink_to, path) != 0) { + err = ZIP_ESYMLINK; + goto out; + } +#endif + } + else { + if (!mz_zip_reader_is_file_a_directory(zip_archive, i)) { + if (!mz_zip_reader_extract_to_file(zip_archive, i, path, 0)) { + // Cannot extract zip archive to file + err = ZIP_ENOFILE; + goto out; + } + } + +#if defined(_MSC_VER) || defined(PS4) + (void)xattr; // unused +#else + xattr = (info.m_external_attr >> 16) & 0xFFFF; + if (xattr > 0 && xattr <= MZ_UINT16_MAX) { + if (CHMOD(path, (mode_t)xattr) < 0) { + err = ZIP_ENOPERM; + goto out; + } + } +#endif + } + + if (on_extract) { + if (on_extract(path, arg) < 0) { + goto out; + } + } + } + +out: + // Close the archive, freeing any resources it was using + if (!mz_zip_reader_end(zip_archive)) { + // Cannot end zip reader + err = ZIP_ECLSZIP; + } + return err; +} + +static inline void zip_archive_finalize(mz_zip_archive* pzip) { + mz_zip_writer_finalize_archive(pzip); + zip_archive_truncate(pzip); +} + +static ssize_t zip_entry_mark(struct zip_t* zip, + struct zip_entry_mark_t* entry_mark, + const ssize_t n, char* const entries[], + const size_t len) { + ssize_t i = 0; + ssize_t err = 0; + if (!zip || !entry_mark || !entries) { + return ZIP_ENOINIT; + } + + mz_zip_archive_file_stat file_stat; + mz_uint64 d_pos = ~0UL; + for (i = 0; i < n; ++i) { + if ((err = zip_entry_openbyindex(zip, i))) { + return (ssize_t)err; + } + + mz_bool name_matches = MZ_FALSE; + { + size_t j; + for (j = 0; j < len; ++j) { + if (zip_name_match(zip->entry.name, entries[j])) { + name_matches = MZ_TRUE; + break; + } + } + } + if (name_matches) { + entry_mark[i].type = MZ_DELETE; + } + else { + entry_mark[i].type = MZ_KEEP; + } + + if (!mz_zip_reader_file_stat(&zip->archive, i, &file_stat)) { + return ZIP_ENOENT; + } + + zip_entry_close(zip); + + entry_mark[i].m_local_header_ofs = file_stat.m_local_header_ofs; + entry_mark[i].file_index = (ssize_t)-1; + entry_mark[i].lf_length = 0; + if ((entry_mark[i].type) == MZ_DELETE && + (d_pos > entry_mark[i].m_local_header_ofs)) { + d_pos = entry_mark[i].m_local_header_ofs; + } + } + + for (i = 0; i < n; ++i) { + if ((entry_mark[i].m_local_header_ofs > d_pos) && + (entry_mark[i].type != MZ_DELETE)) { + entry_mark[i].type = MZ_MOVE; + } + } + return err; +} + +static ssize_t zip_index_next(mz_uint64* local_header_ofs_array, + ssize_t cur_index) { + ssize_t new_index = 0, i; + for (i = cur_index - 1; i >= 0; --i) { + if (local_header_ofs_array[cur_index] > local_header_ofs_array[i]) { + new_index = i + 1; + return new_index; + } + } + return new_index; +} + +static ssize_t zip_sort(mz_uint64* local_header_ofs_array, ssize_t cur_index) { + ssize_t nxt_index = zip_index_next(local_header_ofs_array, cur_index); + + if (nxt_index != cur_index) { + mz_uint64 temp = local_header_ofs_array[cur_index]; + ssize_t i; + for (i = cur_index; i > nxt_index; i--) { + local_header_ofs_array[i] = local_header_ofs_array[i - 1]; + } + local_header_ofs_array[nxt_index] = temp; + } + return nxt_index; +} + +static int zip_index_update(struct zip_entry_mark_t* entry_mark, + ssize_t last_index, ssize_t nxt_index) { + ssize_t j; + for (j = 0; j < last_index; j++) { + if (entry_mark[j].file_index >= nxt_index) { + entry_mark[j].file_index += 1; + } + } + entry_mark[nxt_index].file_index = last_index; + return 0; +} + +static int zip_entry_finalize(struct zip_t* zip, + struct zip_entry_mark_t* entry_mark, + const ssize_t n) { + + ssize_t i = 0; + mz_uint64* local_header_ofs_array = (mz_uint64*)calloc(n, sizeof(mz_uint64)); + if (!local_header_ofs_array) { + return ZIP_EOOMEM; + } + + for (i = 0; i < n; ++i) { + local_header_ofs_array[i] = entry_mark[i].m_local_header_ofs; + ssize_t index = zip_sort(local_header_ofs_array, i); + + if (index != i) { + zip_index_update(entry_mark, i, index); + } + entry_mark[i].file_index = index; + } + + size_t* length = (size_t*)calloc(n, sizeof(size_t)); + if (!length) { + CLEANUP(local_header_ofs_array); + return ZIP_EOOMEM; + } + for (i = 0; i < n - 1; i++) { + length[i] = + (size_t)(local_header_ofs_array[i + 1] - local_header_ofs_array[i]); + } + length[n - 1] = + (size_t)(zip->archive.m_archive_size - local_header_ofs_array[n - 1]); + + for (i = 0; i < n; i++) { + entry_mark[i].lf_length = length[entry_mark[i].file_index]; + } + + CLEANUP(length); + CLEANUP(local_header_ofs_array); + return 0; +} + +static ssize_t zip_entry_set(struct zip_t* zip, + struct zip_entry_mark_t* entry_mark, ssize_t n, + char* const entries[], const size_t len) { + ssize_t err = 0; + + if ((err = zip_entry_mark(zip, entry_mark, n, entries, len)) < 0) { + return err; + } + if ((err = zip_entry_finalize(zip, entry_mark, n)) < 0) { + return err; + } + return 0; +} + +static ssize_t zip_file_move(MZ_FILE* m_pFile, const mz_uint64 to, + const mz_uint64 from, const size_t length, + mz_uint8* move_buf, const size_t capacity_size) { + if (length > capacity_size) { + return ZIP_ECAPSIZE; + } + if (MZ_FSEEK64(m_pFile, (long)from, SEEK_SET)) { + return ZIP_EFSEEK; + } + if (fread(move_buf, 1, length, m_pFile) != length) { + return ZIP_EFREAD; + } + if (MZ_FSEEK64(m_pFile, (long)to, SEEK_SET)) { + return ZIP_EFSEEK; + } + if (fwrite(move_buf, 1, length, m_pFile) != length) { + return ZIP_EFWRITE; + } + return (ssize_t)length; +} + +static ssize_t zip_files_move(MZ_FILE* m_pFile, mz_uint64 writen_num, + mz_uint64 read_num, size_t length) { + ssize_t n = 0; + const size_t page_size = 1 << 12; // 4K + mz_uint8* move_buf = (mz_uint8*)calloc(1, page_size); + if (!move_buf) { + return ZIP_EOOMEM; + } + + ssize_t moved_length = 0; + ssize_t move_count = 0; + while ((mz_int64)length > 0) { + move_count = (length >= page_size) ? page_size : length; + n = zip_file_move(m_pFile, writen_num, read_num, move_count, move_buf, + page_size); + if (n < 0) { + moved_length = n; + goto cleanup; + } + + if (n != move_count) { + goto cleanup; + } + + writen_num += move_count; + read_num += move_count; + length -= move_count; + moved_length += move_count; + } + +cleanup: + CLEANUP(move_buf); + return moved_length; +} + +static int zip_central_dir_move(mz_zip_internal_state* pState, int begin, + int end, int entry_num) { + if (begin == entry_num) { + return 0; + } + + size_t l_size = 0; + size_t r_size = 0; + mz_uint32 d_size = 0; + mz_uint8* next = NULL; + mz_uint8* deleted = &MZ_ZIP_ARRAY_ELEMENT( + &pState->m_central_dir, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, mz_uint32, begin)); + l_size = (size_t)(deleted - (mz_uint8*)(pState->m_central_dir.m_p)); + if (end == entry_num) { + r_size = 0; + } + else { + next = &MZ_ZIP_ARRAY_ELEMENT( + &pState->m_central_dir, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, mz_uint32, end)); + r_size = pState->m_central_dir.m_size - + (mz_uint32)(next - (mz_uint8*)(pState->m_central_dir.m_p)); + d_size = (mz_uint32)(next - deleted); + } + + if (next && l_size == 0) { + memmove(pState->m_central_dir.m_p, next, r_size); + pState->m_central_dir.m_p = MZ_REALLOC(pState->m_central_dir.m_p, r_size); + { + int i; + for (i = end; i < entry_num; i++) { + MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, mz_uint32, i) -= + d_size; + } + } + } + + if (next && l_size * r_size != 0) { + memmove(deleted, next, r_size); + { + int i; + for (i = end; i < entry_num; i++) { + MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, mz_uint32, i) -= + d_size; + } + } + } + + pState->m_central_dir.m_size = l_size + r_size; + return 0; +} + +static int zip_central_dir_delete(mz_zip_internal_state* pState, + int* deleted_entry_index_array, + int entry_num) { + int i = 0; + int begin = 0; + int end = 0; + int d_num = 0; + while (i < entry_num) { + while ((i < entry_num) && (!deleted_entry_index_array[i])) { + i++; + } + begin = i; + + while ((i < entry_num) && (deleted_entry_index_array[i])) { + i++; + } + end = i; + zip_central_dir_move(pState, begin, end, entry_num); + } + + i = 0; + while (i < entry_num) { + while ((i < entry_num) && (!deleted_entry_index_array[i])) { + i++; + } + begin = i; + if (begin == entry_num) { + break; + } + while ((i < entry_num) && (deleted_entry_index_array[i])) { + i++; + } + end = i; + int k = 0, j; + for (j = end; j < entry_num; j++) { + MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, mz_uint32, + begin + k) = + (mz_uint32)MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, + mz_uint32, j); + k++; + } + d_num += end - begin; + } + + pState->m_central_dir_offsets.m_size = + sizeof(mz_uint32) * (entry_num - d_num); + return 0; +} + +static ssize_t zip_entries_delete_mark(struct zip_t* zip, + struct zip_entry_mark_t* entry_mark, + int entry_num) { + mz_uint64 writen_num = 0; + mz_uint64 read_num = 0; + size_t deleted_length = 0; + size_t move_length = 0; + int i = 0; + size_t deleted_entry_num = 0; + ssize_t n = 0; + + mz_bool* deleted_entry_flag_array = + (mz_bool*)calloc(entry_num, sizeof(mz_bool)); + if (deleted_entry_flag_array == NULL) { + return ZIP_EOOMEM; + } + + mz_zip_internal_state* pState = zip->archive.m_pState; + zip->archive.m_zip_mode = MZ_ZIP_MODE_WRITING; + + if ((!pState->m_pFile) || MZ_FSEEK64(pState->m_pFile, 0, SEEK_SET)) { + CLEANUP(deleted_entry_flag_array); + return ZIP_ENOENT; + } + + while (i < entry_num) { + while ((i < entry_num) && (entry_mark[i].type == MZ_KEEP)) { + writen_num += entry_mark[i].lf_length; + read_num = writen_num; + i++; + } + + while ((i < entry_num) && (entry_mark[i].type == MZ_DELETE)) { + deleted_entry_flag_array[i] = MZ_TRUE; + read_num += entry_mark[i].lf_length; + deleted_length += entry_mark[i].lf_length; + i++; + deleted_entry_num++; + } + + while ((i < entry_num) && (entry_mark[i].type == MZ_MOVE)) { + move_length += entry_mark[i].lf_length; + mz_uint8* p = &MZ_ZIP_ARRAY_ELEMENT( + &pState->m_central_dir, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, mz_uint32, i)); + if (!p) { + CLEANUP(deleted_entry_flag_array); + return ZIP_ENOENT; + } + mz_uint32 offset = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + offset -= (mz_uint32)deleted_length; + MZ_WRITE_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS, offset); + i++; + } + + n = zip_files_move(pState->m_pFile, writen_num, read_num, move_length); + if (n != (ssize_t)move_length) { + CLEANUP(deleted_entry_flag_array); + return n; + } + writen_num += move_length; + read_num += move_length; + } + + zip->archive.m_archive_size -= (mz_uint64)deleted_length; + zip->archive.m_total_files = + (mz_uint32)entry_num - (mz_uint32)deleted_entry_num; + + zip_central_dir_delete(pState, deleted_entry_flag_array, entry_num); + CLEANUP(deleted_entry_flag_array); + + return (ssize_t)deleted_entry_num; +} + +struct zip_t* zip_open(const char* zipname, int level, char mode) { + struct zip_t* zip = NULL; + + if (!zipname || strlen(zipname) < 1) { + // zip_t archive name is empty or NULL + goto cleanup; + } + + if (level < 0) + level = MZ_DEFAULT_LEVEL; + if ((level & 0xF) > MZ_UBER_COMPRESSION) { + // Wrong compression level + goto cleanup; + } + + zip = (struct zip_t*)calloc((size_t)1, sizeof(struct zip_t)); + if (!zip) + goto cleanup; + + zip->level = (mz_uint)level; + switch (mode) { + case 'w': + // Create a new archive. + if (!mz_zip_writer_init_file_v2(&(zip->archive), zipname, 0, + MZ_ZIP_FLAG_WRITE_ZIP64)) { + // Cannot initialize zip_archive writer + goto cleanup; + } + break; + + case 'r': + case 'a': + case 'd': + if (!mz_zip_reader_init_file_v2_rpb( + &(zip->archive), zipname, + zip->level | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) { + // An archive file does not exist or cannot initialize + // zip_archive reader + goto cleanup; + } + if ((mode == 'a' || mode == 'd')) { + if (!mz_zip_writer_init_from_reader_v2_noreopen(&(zip->archive), zipname, + 0)) { + mz_zip_reader_end(&(zip->archive)); + goto cleanup; + } + } + break; + + default: + goto cleanup; + } + + return zip; + +cleanup: + CLEANUP(zip); + return NULL; +} + +void zip_close(struct zip_t* zip) { + if (zip) { + // Always finalize, even if adding failed for some reason, so we have a + // valid central directory. + mz_zip_writer_finalize_archive(&(zip->archive)); + zip_archive_truncate(&(zip->archive)); + mz_zip_writer_end(&(zip->archive)); + mz_zip_reader_end(&(zip->archive)); + + CLEANUP(zip); + } +} + +int zip_is64(struct zip_t* zip) { + if (!zip || !zip->archive.m_pState) { + // zip_t handler or zip state is not initialized + return ZIP_ENOINIT; + } + + return (int)zip->archive.m_pState->m_zip64; +} + +static int _zip_entry_open(struct zip_t* zip, const char* entryname, + int case_sensitive) { + size_t entrylen = 0; + mz_zip_archive* pzip = NULL; + mz_uint num_alignment_padding_bytes, level; + mz_zip_archive_file_stat stats; + int err = 0; + mz_uint16 dos_time, dos_date; + mz_uint32 extra_size = 0; + mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; + mz_uint64 local_dir_header_ofs = 0; + + if (!zip) { + return ZIP_ENOINIT; + } + + local_dir_header_ofs = zip->archive.m_archive_size; + + if (!entryname) { + return ZIP_EINVENTNAME; + } + + entrylen = strlen(entryname); + if (entrylen == 0) { + return ZIP_EINVENTNAME; + } + + /* + .ZIP File Format Specification Version: 6.3.3 + + 4.4.17.1 The name of the file, with optional relative path. + The path stored MUST not contain a drive or + device letter, or a leading slash. All slashes + MUST be forward slashes '/' as opposed to + backwards slashes '\' for compatibility with Amiga + and UNIX file systems etc. If input came from standard + input, there is no file name field. + */ + if (zip->entry.name) { + CLEANUP(zip->entry.name); + } +#ifdef ZIP_RAW_ENTRYNAME + zip->entry.name = STRCLONE(entryname); +#else + zip->entry.name = zip_strrpl(entryname, entrylen, '\\', '/'); +#endif + + if (!zip->entry.name) { + // Cannot parse zip entry name + return ZIP_EINVENTNAME; + } + + pzip = &(zip->archive); + if (pzip->m_zip_mode == MZ_ZIP_MODE_READING) { + zip->entry.index = (ssize_t)mz_zip_reader_locate_file( + pzip, zip->entry.name, NULL, + case_sensitive ? MZ_ZIP_FLAG_CASE_SENSITIVE : 0); + if (zip->entry.index < (ssize_t)0) { + err = ZIP_ENOENT; + goto cleanup; + } + + if (!mz_zip_reader_file_stat(pzip, (mz_uint)zip->entry.index, &stats)) { + err = ZIP_ENOENT; + goto cleanup; + } + + zip->entry.comp_size = stats.m_comp_size; + zip->entry.uncomp_size = stats.m_uncomp_size; + zip->entry.uncomp_crc32 = stats.m_crc32; + zip->entry.offset = stats.m_central_dir_ofs; + zip->entry.header_offset = stats.m_local_header_ofs; + zip->entry.method = stats.m_method; + zip->entry.external_attr = stats.m_external_attr; +#ifndef MINIZ_NO_TIME + zip->entry.m_time = stats.m_time; +#endif + + return 0; + } + + level = zip->level & 0xF; + + zip->entry.index = (ssize_t)zip->archive.m_total_files; + zip->entry.comp_size = 0; + zip->entry.uncomp_size = 0; + zip->entry.uncomp_crc32 = MZ_CRC32_INIT; + zip->entry.offset = zip->archive.m_archive_size; + zip->entry.header_offset = zip->archive.m_archive_size; + memset(zip->entry.header, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE * sizeof(mz_uint8)); + zip->entry.method = level ? MZ_DEFLATED : 0; + + // UNIX or APPLE +#if MZ_PLATFORM == 3 || MZ_PLATFORM == 19 + // regular file with rw-r--r-- permissions + zip->entry.external_attr = (mz_uint32)(0100644) << 16; +#else + zip->entry.external_attr = 0; +#endif + + num_alignment_padding_bytes = + mz_zip_writer_compute_padding_needed_for_file_alignment(pzip); + + if (!pzip->m_pState || (pzip->m_zip_mode != MZ_ZIP_MODE_WRITING)) { + // Invalid zip mode + err = ZIP_EINVMODE; + goto cleanup; + } + if (zip->level & MZ_ZIP_FLAG_COMPRESSED_DATA) { + // Invalid zip compression level + err = ZIP_EINVLVL; + goto cleanup; + } + + if (!mz_zip_writer_write_zeros(pzip, zip->entry.offset, + num_alignment_padding_bytes)) { + // Cannot memset zip entry header + err = ZIP_EMEMSET; + goto cleanup; + } + local_dir_header_ofs += num_alignment_padding_bytes; + + zip->entry.m_time = time(NULL); +#ifndef MINIZ_NO_TIME + mz_zip_time_t_to_dos_time(zip->entry.m_time, &dos_time, &dos_date); +#endif + + // ZIP64 header with NULL sizes (sizes will be in the data descriptor, just + // after file data) + extra_size = mz_zip_writer_create_zip64_extra_data( + extra_data, NULL, NULL, + (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + + if (!mz_zip_writer_create_local_dir_header( + pzip, zip->entry.header, (mz_uint16)entrylen, (mz_uint16)extra_size, 0, 0, 0, + zip->entry.method, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8 | + MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR, + dos_time, dos_date)) { + // Cannot create zip entry header + err = ZIP_EMEMSET; + goto cleanup; + } + + zip->entry.header_offset = zip->entry.offset + num_alignment_padding_bytes; + + if (pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.header_offset, + zip->entry.header, + sizeof(zip->entry.header)) != sizeof(zip->entry.header)) { + // Cannot write zip entry header + err = ZIP_EMEMSET; + goto cleanup; + } + + if (pzip->m_file_offset_alignment) { + MZ_ASSERT( + (zip->entry.header_offset & (pzip->m_file_offset_alignment - 1)) == 0); + } + zip->entry.offset += num_alignment_padding_bytes + sizeof(zip->entry.header); + + if (pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.offset, zip->entry.name, + entrylen) != entrylen) { + // Cannot write data to zip entry + err = ZIP_EWRTENT; + goto cleanup; + } + + zip->entry.offset += entrylen; + + if (pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.offset, extra_data, + extra_size) != extra_size) { + // Cannot write ZIP64 data to zip entry + err = ZIP_EWRTENT; + goto cleanup; + } + zip->entry.offset += extra_size; + + if (level) { + zip->entry.state.m_pZip = pzip; + zip->entry.state.m_cur_archive_file_ofs = zip->entry.offset; + zip->entry.state.m_comp_size = 0; + + if (tdefl_init(&(zip->entry.comp), mz_zip_writer_add_put_buf_callback, + &(zip->entry.state), + (int)tdefl_create_comp_flags_from_zip_params( + (int)level, -15, MZ_DEFAULT_STRATEGY)) != + TDEFL_STATUS_OKAY) { + // Cannot initialize the zip compressor + err = ZIP_ETDEFLINIT; + goto cleanup; + } + } + + return 0; + +cleanup: + CLEANUP(zip->entry.name); + return err; +} + +int zip_entry_open(struct zip_t* zip, const char* entryname) { + return _zip_entry_open(zip, entryname, 0); +} + +int zip_entry_opencasesensitive(struct zip_t* zip, const char* entryname) { + return _zip_entry_open(zip, entryname, 1); +} + +int zip_entry_openbyindex(struct zip_t* zip, size_t index) { + mz_zip_archive* pZip = NULL; + mz_zip_archive_file_stat stats; + mz_uint namelen; + const mz_uint8* pHeader; + const char* pFilename; + + if (!zip) { + // zip_t handler is not initialized + return ZIP_ENOINIT; + } + + pZip = &(zip->archive); + if (pZip->m_zip_mode != MZ_ZIP_MODE_READING) { + // open by index requires readonly mode + return ZIP_EINVMODE; + } + + if (index >= (size_t)pZip->m_total_files) { + // index out of range + return ZIP_EINVIDX; + } + + if (!(pHeader = &MZ_ZIP_ARRAY_ELEMENT( + &pZip->m_pState->m_central_dir, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, + mz_uint32, index)))) { + // cannot find header in central directory + return ZIP_ENOHDR; + } + + namelen = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); + pFilename = (const char*)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + + /* + .ZIP File Format Specification Version: 6.3.3 + + 4.4.17.1 The name of the file, with optional relative path. + The path stored MUST not contain a drive or + device letter, or a leading slash. All slashes + MUST be forward slashes '/' as opposed to + backwards slashes '\' for compatibility with Amiga + and UNIX file systems etc. If input came from standard + input, there is no file name field. + */ + if (zip->entry.name) { + CLEANUP(zip->entry.name); + } +#ifdef ZIP_RAW_ENTRYNAME + zip->entry.name = STRCLONE(pFilename); +#else + zip->entry.name = zip_strrpl(pFilename, namelen, '\\', '/'); +#endif + + if (!zip->entry.name) { + // local entry name is NULL + return ZIP_EINVENTNAME; + } + + if (!mz_zip_reader_file_stat(pZip, (mz_uint)index, &stats)) { + return ZIP_ENOENT; + } + + zip->entry.index = (ssize_t)index; + zip->entry.comp_size = stats.m_comp_size; + zip->entry.uncomp_size = stats.m_uncomp_size; + zip->entry.uncomp_crc32 = stats.m_crc32; + zip->entry.offset = stats.m_central_dir_ofs; + zip->entry.header_offset = stats.m_local_header_ofs; + zip->entry.method = stats.m_method; + zip->entry.external_attr = stats.m_external_attr; +#ifndef MINIZ_NO_TIME + zip->entry.m_time = stats.m_time; +#endif + + return 0; +} + +int zip_entry_close(struct zip_t* zip) { + mz_zip_archive* pzip = NULL; + mz_uint level; + tdefl_status done; + mz_uint16 entrylen; + mz_uint16 dos_time = 0, dos_date = 0; + int err = 0; + mz_uint8* pExtra_data = NULL; + mz_uint32 extra_size = 0; + mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; + mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; + mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; + + if (!zip) { + // zip_t handler is not initialized + err = ZIP_ENOINIT; + goto cleanup; + } + + pzip = &(zip->archive); + if (pzip->m_zip_mode == MZ_ZIP_MODE_READING) { + goto cleanup; + } + + level = zip->level & 0xF; + if (level) { + done = tdefl_compress_buffer(&(zip->entry.comp), "", 0, TDEFL_FINISH); + if (done != TDEFL_STATUS_DONE && done != TDEFL_STATUS_OKAY) { + // Cannot flush compressed buffer + err = ZIP_ETDEFLBUF; + goto cleanup; + } + zip->entry.comp_size = zip->entry.state.m_comp_size; + zip->entry.offset = zip->entry.state.m_cur_archive_file_ofs; + zip->entry.method = MZ_DEFLATED; + } + + entrylen = (mz_uint16)strlen(zip->entry.name); +#ifndef MINIZ_NO_TIME + mz_zip_time_t_to_dos_time(zip->entry.m_time, &dos_time, &dos_date); +#endif + + MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); + MZ_WRITE_LE32(local_dir_footer + 4, zip->entry.uncomp_crc32); + MZ_WRITE_LE64(local_dir_footer + 8, zip->entry.comp_size); + MZ_WRITE_LE64(local_dir_footer + 16, zip->entry.uncomp_size); + + if (pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.offset, local_dir_footer, + local_dir_footer_size) != local_dir_footer_size) { + // Cannot write zip entry header + err = ZIP_EWRTHDR; + goto cleanup; + } + zip->entry.offset += local_dir_footer_size; + + pExtra_data = extra_data; + extra_size = mz_zip_writer_create_zip64_extra_data( + extra_data, + (zip->entry.uncomp_size >= MZ_UINT32_MAX) ? &zip->entry.uncomp_size + : NULL, + (zip->entry.comp_size >= MZ_UINT32_MAX) ? &zip->entry.comp_size : NULL, + (zip->entry.header_offset >= MZ_UINT32_MAX) ? &zip->entry.header_offset + : NULL); + + if ((entrylen) && (zip->entry.name[entrylen - 1] == '/') && + !zip->entry.uncomp_size) { + /* Set DOS Subdirectory attribute bit. */ + zip->entry.external_attr |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG; + } + + if (!mz_zip_writer_add_to_central_dir( + pzip, zip->entry.name, entrylen, pExtra_data, (mz_uint16)extra_size, + "", 0, zip->entry.uncomp_size, zip->entry.comp_size, + zip->entry.uncomp_crc32, zip->entry.method, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8 | + MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR, + dos_time, dos_date, zip->entry.header_offset, + zip->entry.external_attr, NULL, 0)) { + // Cannot write to zip central dir + err = ZIP_EWRTDIR; + goto cleanup; + } + + pzip->m_total_files++; + pzip->m_archive_size = zip->entry.offset; + +cleanup: + if (zip) { + zip->entry.m_time = 0; + CLEANUP(zip->entry.name); + } + return err; +} + +const char* zip_entry_name(struct zip_t* zip) { + if (!zip) { + // zip_t handler is not initialized + return NULL; + } + + return zip->entry.name; +} + +ssize_t zip_entry_index(struct zip_t* zip) { + if (!zip) { + // zip_t handler is not initialized + return (ssize_t)ZIP_ENOINIT; + } + + return zip->entry.index; +} + +int zip_entry_isdir(struct zip_t* zip) { + if (!zip) { + // zip_t handler is not initialized + return ZIP_ENOINIT; + } + + if (zip->entry.index < (ssize_t)0) { + // zip entry is not opened + return ZIP_EINVIDX; + } + + return (int)mz_zip_reader_is_file_a_directory(&zip->archive, + (mz_uint)zip->entry.index); +} + +unsigned long long zip_entry_size(struct zip_t* zip) { + return zip_entry_uncomp_size(zip); +} + +unsigned long long zip_entry_uncomp_size(struct zip_t* zip) { + return zip ? zip->entry.uncomp_size : 0; +} + +unsigned long long zip_entry_comp_size(struct zip_t* zip) { + return zip ? zip->entry.comp_size : 0; +} + +unsigned int zip_entry_crc32(struct zip_t* zip) { + return zip ? zip->entry.uncomp_crc32 : 0; +} + +int zip_entry_write(struct zip_t* zip, const void* buf, size_t bufsize) { + mz_uint level; + mz_zip_archive* pzip = NULL; + tdefl_status status; + + if (!zip) { + // zip_t handler is not initialized + return ZIP_ENOINIT; + } + + pzip = &(zip->archive); + if (buf && bufsize > 0) { + zip->entry.uncomp_size += bufsize; + zip->entry.uncomp_crc32 = (mz_uint32)mz_crc32( + zip->entry.uncomp_crc32, (const mz_uint8*)buf, bufsize); + + level = zip->level & 0xF; + if (!level) { + if ((pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.offset, buf, + bufsize) != bufsize)) { + // Cannot write buffer + return ZIP_EWRTENT; + } + zip->entry.offset += bufsize; + zip->entry.comp_size += bufsize; + } + else { + status = tdefl_compress_buffer(&(zip->entry.comp), buf, bufsize, + TDEFL_NO_FLUSH); + if (status != TDEFL_STATUS_DONE && status != TDEFL_STATUS_OKAY) { + // Cannot compress buffer + return ZIP_ETDEFLBUF; + } + } + } + + return 0; +} + +int zip_entry_fwrite(struct zip_t* zip, const char* filename) { + int err = 0; + size_t n = 0; + MZ_FILE* stream = NULL; + mz_uint8 buf[MZ_ZIP_MAX_IO_BUF_SIZE]; + struct MZ_FILE_STAT_STRUCT file_stat; + mz_uint16 modes; + + if (!zip) { + // zip_t handler is not initialized + return ZIP_ENOINIT; + } + + memset(buf, 0, MZ_ZIP_MAX_IO_BUF_SIZE); + memset((void*)&file_stat, 0, sizeof(struct MZ_FILE_STAT_STRUCT)); + if (MZ_FILE_STAT(filename, &file_stat) != 0) { + // problem getting information - check errno + return ZIP_ENOENT; + } + +#if defined(_WIN32) || defined(__WIN32__) || defined(DJGPP) + (void)modes; // unused +#else + /* Initialize with permission bits--which are not implementation-optional */ + modes = file_stat.st_mode & + (S_IRWXU | S_IRWXG | S_IRWXO | S_ISUID | S_ISGID | S_ISVTX); + if (S_ISDIR(file_stat.st_mode)) + modes |= UNX_IFDIR; + if (S_ISREG(file_stat.st_mode)) + modes |= UNX_IFREG; + if (S_ISLNK(file_stat.st_mode)) + modes |= UNX_IFLNK; + if (S_ISBLK(file_stat.st_mode)) + modes |= UNX_IFBLK; + if (S_ISCHR(file_stat.st_mode)) + modes |= UNX_IFCHR; + if (S_ISFIFO(file_stat.st_mode)) + modes |= UNX_IFIFO; + if (S_ISSOCK(file_stat.st_mode)) + modes |= UNX_IFSOCK; + zip->entry.external_attr = (modes << 16) | !(file_stat.st_mode & S_IWUSR); + if ((file_stat.st_mode & S_IFMT) == S_IFDIR) { + zip->entry.external_attr |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG; + } +#endif + + zip->entry.m_time = file_stat.st_mtime; + + if (!(stream = MZ_FOPEN(filename, "rb"))) { + // Cannot open filename + return ZIP_EOPNFILE; + } + + while ((n = fread(buf, sizeof(mz_uint8), MZ_ZIP_MAX_IO_BUF_SIZE, stream)) > + 0) { + if (zip_entry_write(zip, buf, n) < 0) { + err = ZIP_EWRTENT; + break; + } + } + fclose(stream); + + return err; +} + +ssize_t zip_entry_read(struct zip_t* zip, void** buf, size_t* bufsize) { + mz_zip_archive* pzip = NULL; + mz_uint idx; + size_t size = 0; + + if (!zip) { + // zip_t handler is not initialized + return (ssize_t)ZIP_ENOINIT; + } + + pzip = &(zip->archive); + if (pzip->m_zip_mode != MZ_ZIP_MODE_READING || + zip->entry.index < (ssize_t)0) { + // the entry is not found or we do not have read access + return (ssize_t)ZIP_ENOENT; + } + + idx = (mz_uint)zip->entry.index; + if (mz_zip_reader_is_file_a_directory(pzip, idx)) { + // the entry is a directory + return (ssize_t)ZIP_EINVENTTYPE; + } + + *buf = mz_zip_reader_extract_to_heap(pzip, idx, &size, 0); + if (*buf && bufsize) { + *bufsize = size; + } + return (ssize_t)size; +} + +ssize_t zip_entry_noallocread(struct zip_t* zip, void* buf, size_t bufsize) { + mz_zip_archive* pzip = NULL; + + if (!zip) { + // zip_t handler is not initialized + return (ssize_t)ZIP_ENOINIT; + } + + pzip = &(zip->archive); + if (pzip->m_zip_mode != MZ_ZIP_MODE_READING || + zip->entry.index < (ssize_t)0) { + // the entry is not found or we do not have read access + return (ssize_t)ZIP_ENOENT; + } + + if (!mz_zip_reader_extract_to_mem_no_alloc(pzip, (mz_uint)zip->entry.index, + buf, bufsize, 0, NULL, 0)) { + return (ssize_t)ZIP_EMEMNOALLOC; + } + + return (ssize_t)zip->entry.uncomp_size; +} + +int zip_entry_fread(struct zip_t* zip, const char* filename) { + mz_zip_archive* pzip = NULL; + mz_uint idx; + mz_uint32 xattr = 0; + mz_zip_archive_file_stat info; + + if (!zip) { + // zip_t handler is not initialized + return ZIP_ENOINIT; + } + + memset((void*)&info, 0, sizeof(mz_zip_archive_file_stat)); + pzip = &(zip->archive); + if (pzip->m_zip_mode != MZ_ZIP_MODE_READING || + zip->entry.index < (ssize_t)0) { + // the entry is not found or we do not have read access + return ZIP_ENOENT; + } + + idx = (mz_uint)zip->entry.index; + if (mz_zip_reader_is_file_a_directory(pzip, idx)) { + // the entry is a directory + return ZIP_EINVENTTYPE; + } + + if (!mz_zip_reader_extract_to_file(pzip, idx, filename, 0)) { + return ZIP_ENOFILE; + } + +#if defined(_MSC_VER) || defined(PS4) + (void)xattr; // unused +#else + if (!mz_zip_reader_file_stat(pzip, idx, &info)) { + // Cannot get information about zip archive; + return ZIP_ENOFILE; + } + + xattr = (info.m_external_attr >> 16) & 0xFFFF; + if (xattr > 0 && xattr <= MZ_UINT16_MAX) { + if (CHMOD(filename, (mode_t)xattr) < 0) { + return ZIP_ENOPERM; + } + } +#endif + + return 0; +} + +int zip_entry_extract(struct zip_t* zip, + size_t(*on_extract)(void* arg, uint64_t offset, + const void* buf, size_t bufsize), + void* arg) { + mz_zip_archive* pzip = NULL; + mz_uint idx; + + if (!zip) { + // zip_t handler is not initialized + return ZIP_ENOINIT; + } + + pzip = &(zip->archive); + if (pzip->m_zip_mode != MZ_ZIP_MODE_READING || + zip->entry.index < (ssize_t)0) { + // the entry is not found or we do not have read access + return ZIP_ENOENT; + } + + idx = (mz_uint)zip->entry.index; + return (mz_zip_reader_extract_to_callback(pzip, idx, on_extract, arg, 0)) + ? 0 + : ZIP_EINVIDX; +} + +ssize_t zip_entries_total(struct zip_t* zip) { + if (!zip) { + // zip_t handler is not initialized + return ZIP_ENOINIT; + } + + return (ssize_t)zip->archive.m_total_files; +} + +ssize_t zip_entries_delete(struct zip_t* zip, char* const entries[], + size_t len) { + ssize_t n = 0; + ssize_t err = 0; + struct zip_entry_mark_t* entry_mark = NULL; + + if (zip == NULL || (entries == NULL && len != 0)) { + return ZIP_ENOINIT; + } + + if (entries == NULL && len == 0) { + return 0; + } + + n = zip_entries_total(zip); + + entry_mark = (struct zip_entry_mark_t*)calloc( + (size_t)n, sizeof(struct zip_entry_mark_t)); + if (!entry_mark) { + return ZIP_EOOMEM; + } + + zip->archive.m_zip_mode = MZ_ZIP_MODE_READING; + + err = zip_entry_set(zip, entry_mark, n, entries, len); + if (err < 0) { + CLEANUP(entry_mark); + return err; + } + + err = zip_entries_delete_mark(zip, entry_mark, (int)n); + CLEANUP(entry_mark); + return err; +} + +int zip_stream_extract(const char* stream, size_t size, const char* dir, + int (*on_extract)(const char* filename, void* arg), + void* arg) { + mz_zip_archive zip_archive; + if (!stream || !dir) { + // Cannot parse zip archive stream + return ZIP_ENOINIT; + } + if (!memset(&zip_archive, 0, sizeof(mz_zip_archive))) { + // Cannot memset zip archive + return ZIP_EMEMSET; + } + if (!mz_zip_reader_init_mem(&zip_archive, stream, size, 0)) { + // Cannot initialize zip_archive reader + return ZIP_ENOINIT; + } + + return zip_archive_extract(&zip_archive, dir, on_extract, arg); +} + +struct zip_t* zip_stream_open(const char* stream, size_t size, int level, + char mode) { + struct zip_t* zip = (struct zip_t*)calloc((size_t)1, sizeof(struct zip_t)); + if (!zip) { + return NULL; + } + + if (level < 0) { + level = MZ_DEFAULT_LEVEL; + } + if ((level & 0xF) > MZ_UBER_COMPRESSION) { + // Wrong compression level + goto cleanup; + } + zip->level = (mz_uint)level; + + if ((stream != NULL) && (size > 0) && (mode == 'r')) { + if (!mz_zip_reader_init_mem(&(zip->archive), stream, size, 0)) { + goto cleanup; + } + } + else if ((stream == NULL) && (size == 0) && (mode == 'w')) { + // Create a new archive. + if (!mz_zip_writer_init_heap(&(zip->archive), 0, 1024)) { + // Cannot initialize zip_archive writer + goto cleanup; + } + } + else { + goto cleanup; + } + return zip; + +cleanup: + CLEANUP(zip); + return NULL; +} + +ssize_t zip_stream_copy(struct zip_t* zip, void** buf, size_t* bufsize) { + size_t n; + + if (!zip) { + return (ssize_t)ZIP_ENOINIT; + } + zip_archive_finalize(&(zip->archive)); + + n = (size_t)zip->archive.m_archive_size; + if (bufsize != NULL) { + *bufsize = n; + } + + *buf = calloc(sizeof(unsigned char), n); + memcpy(*buf, zip->archive.m_pState->m_pMem, n); + + return (ssize_t)n; +} + +void zip_stream_close(struct zip_t* zip) { + if (zip) { + mz_zip_writer_end(&(zip->archive)); + mz_zip_reader_end(&(zip->archive)); + CLEANUP(zip); + } +} + +int zip_create(const char* zipname, const char* filenames[], size_t len) { + int err = 0; + size_t i; + mz_zip_archive zip_archive; + struct MZ_FILE_STAT_STRUCT file_stat; + mz_uint32 ext_attributes = 0; + mz_uint16 modes; + + if (!zipname || strlen(zipname) < 1) { + // zip_t archive name is empty or NULL + return ZIP_EINVZIPNAME; + } + + // Create a new archive. + if (!memset(&(zip_archive), 0, sizeof(zip_archive))) { + // Cannot memset zip archive + return ZIP_EMEMSET; + } + + if (!mz_zip_writer_init_file(&zip_archive, zipname, 0)) { + // Cannot initialize zip_archive writer + return ZIP_ENOINIT; + } + + if (!memset((void*)&file_stat, 0, sizeof(struct MZ_FILE_STAT_STRUCT))) { + return ZIP_EMEMSET; + } + + for (i = 0; i < len; ++i) { + const char* name = filenames[i]; + if (!name) { + err = ZIP_EINVENTNAME; + break; + } + + if (MZ_FILE_STAT(name, &file_stat) != 0) { + // problem getting information - check errno + err = ZIP_ENOFILE; + break; + } + +#if defined(_WIN32) || defined(__WIN32__) || defined(DJGPP) + (void)modes; // unused +#else + + /* Initialize with permission bits--which are not implementation-optional */ + modes = file_stat.st_mode & + (S_IRWXU | S_IRWXG | S_IRWXO | S_ISUID | S_ISGID | S_ISVTX); + if (S_ISDIR(file_stat.st_mode)) + modes |= UNX_IFDIR; + if (S_ISREG(file_stat.st_mode)) + modes |= UNX_IFREG; + if (S_ISLNK(file_stat.st_mode)) + modes |= UNX_IFLNK; + if (S_ISBLK(file_stat.st_mode)) + modes |= UNX_IFBLK; + if (S_ISCHR(file_stat.st_mode)) + modes |= UNX_IFCHR; + if (S_ISFIFO(file_stat.st_mode)) + modes |= UNX_IFIFO; + if (S_ISSOCK(file_stat.st_mode)) + modes |= UNX_IFSOCK; + ext_attributes = (modes << 16) | !(file_stat.st_mode & S_IWUSR); + if ((file_stat.st_mode & S_IFMT) == S_IFDIR) { + ext_attributes |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG; + } +#endif + + if (!mz_zip_writer_add_file(&zip_archive, zip_basename(name), name, "", 0, + ZIP_DEFAULT_COMPRESSION_LEVEL, + ext_attributes)) { + // Cannot add file to zip_archive + err = ZIP_ENOFILE; + break; + } + } + + mz_zip_writer_finalize_archive(&zip_archive); + mz_zip_writer_end(&zip_archive); + return err; +} + +int zip_extract(const char* zipname, const char* dir, + int (*on_extract)(const char* filename, void* arg), void* arg) { + mz_zip_archive zip_archive; + + if (!zipname || !dir) { + // Cannot parse zip archive name + return ZIP_EINVZIPNAME; + } + + if (!memset(&zip_archive, 0, sizeof(mz_zip_archive))) { + // Cannot memset zip archive + return ZIP_EMEMSET; + } + + // Now try to open the archive. + if (!mz_zip_reader_init_file(&zip_archive, zipname, 0)) { + // Cannot initialize zip_archive reader + return ZIP_ENOINIT; + } + + return zip_archive_extract(&zip_archive, dir, on_extract, arg); +} diff --git a/Update/Zip.h b/Update/Zip.h new file mode 100644 index 0000000..0b771b6 --- /dev/null +++ b/Update/Zip.h @@ -0,0 +1,448 @@ +/* + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +#pragma once +#ifndef ZIP_H +#define ZIP_H +//#include "public/define.h" +#include +#include +#include + + +#if !defined(_POSIX_C_SOURCE) && defined(_MSC_VER) + // 64-bit Windows is the only mainstream platform + // where sizeof(long) != sizeof(void*) +#ifdef _WIN64 +typedef long long ssize_t; /* byte count or error */ +#else +typedef long ssize_t; /* byte count or error */ +#endif +#endif + +#ifndef MAX_PATH +#define MAX_PATH 1024 /* # chars in a path name including NULL */ +#endif + +/** + * @mainpage + * + * Documenation for @ref zip. + */ + + /** + * @addtogroup zip + * @{ + */ + + /** + * Default zip compression level. + */ +#define ZIP_DEFAULT_COMPRESSION_LEVEL 6 + + /** + * Error codes + */ +#define ZIP_ENOINIT -1 // not initialized +#define ZIP_EINVENTNAME -2 // invalid entry name +#define ZIP_ENOENT -3 // entry not found +#define ZIP_EINVMODE -4 // invalid zip mode +#define ZIP_EINVLVL -5 // invalid compression level +#define ZIP_ENOSUP64 -6 // no zip 64 support +#define ZIP_EMEMSET -7 // memset error +#define ZIP_EWRTENT -8 // cannot write data to entry +#define ZIP_ETDEFLINIT -9 // cannot initialize tdefl compressor +#define ZIP_EINVIDX -10 // invalid index +#define ZIP_ENOHDR -11 // header not found +#define ZIP_ETDEFLBUF -12 // cannot flush tdefl buffer +#define ZIP_ECRTHDR -13 // cannot create entry header +#define ZIP_EWRTHDR -14 // cannot write entry header +#define ZIP_EWRTDIR -15 // cannot write to central dir +#define ZIP_EOPNFILE -16 // cannot open file +#define ZIP_EINVENTTYPE -17 // invalid entry type +#define ZIP_EMEMNOALLOC -18 // extracting data using no memory allocation +#define ZIP_ENOFILE -19 // file not found +#define ZIP_ENOPERM -20 // no permission +#define ZIP_EOOMEM -21 // out of memory +#define ZIP_EINVZIPNAME -22 // invalid zip archive name +#define ZIP_EMKDIR -23 // make dir error +#define ZIP_ESYMLINK -24 // symlink error +#define ZIP_ECLSZIP -25 // close archive error +#define ZIP_ECAPSIZE -26 // capacity size too small +#define ZIP_EFSEEK -27 // fseek error +#define ZIP_EFREAD -28 // fread error +#define ZIP_EFWRITE -29 // fwrite error + + /** + * Looks up the error message string coresponding to an error number. + * @param errnum error number + * @return error message string coresponding to errnum or NULL if error is not + * found. + */ +const char* zip_strerror(int errnum); + +/** + * @struct zip_t + * + * This data structure is used throughout the library to represent zip archive - + * forward declaration. + */ +struct zip_t; + +/** + * Opens zip archive with compression level using the given mode. + * + * @param zipname zip archive file name. + * @param level compression level (0-9 are the standard zlib-style levels). + * @param mode file access mode. + * - 'r': opens a file for reading/extracting (the file must exists). + * - 'w': creates an empty file for writing. + * - 'a': appends to an existing archive. + * + * @return the zip archive handler or NULL on error + */ +struct zip_t* zip_open(const char* zipname, int level, + char mode); + +/** + * Closes the zip archive, releases resources - always finalize. + * + * @param zip zip archive handler. + */ +void zip_close(struct zip_t* zip); + +/** + * Determines if the archive has a zip64 end of central directory headers. + * + * @param zip zip archive handler. + * + * @return the return code - 1 (true), 0 (false), negative number (< 0) on + * error. + */ +int zip_is64(struct zip_t* zip); + +/** + * Opens an entry by name in the zip archive. + * + * For zip archive opened in 'w' or 'a' mode the function will append + * a new entry. In readonly mode the function tries to locate the entry + * in global dictionary. + * + * @param zip zip archive handler. + * @param entryname an entry name in local dictionary. + * + * @return the return code - 0 on success, negative number (< 0) on error. + */ +int zip_entry_open(struct zip_t* zip, const char* entryname); + +/** + * Opens an entry by name in the zip archive. + * + * For zip archive opened in 'w' or 'a' mode the function will append + * a new entry. In readonly mode the function tries to locate the entry + * in global dictionary (case sensitive). + * + * @param zip zip archive handler. + * @param entryname an entry name in local dictionary (case sensitive). + * + * @return the return code - 0 on success, negative number (< 0) on error. + */ +int zip_entry_opencasesensitive(struct zip_t* zip, + const char* entryname); + +/** + * Opens a new entry by index in the zip archive. + * + * This function is only valid if zip archive was opened in 'r' (readonly) mode. + * + * @param zip zip archive handler. + * @param index index in local dictionary. + * + * @return the return code - 0 on success, negative number (< 0) on error. + */ +int zip_entry_openbyindex(struct zip_t* zip, size_t index); + +/** + * Closes a zip entry, flushes buffer and releases resources. + * + * @param zip zip archive handler. + * + * @return the return code - 0 on success, negative number (< 0) on error. + */ +int zip_entry_close(struct zip_t* zip); + +/** + * Returns a local name of the current zip entry. + * + * The main difference between user's entry name and local entry name + * is optional relative path. + * Following .ZIP File Format Specification - the path stored MUST not contain + * a drive or device letter, or a leading slash. + * All slashes MUST be forward slashes '/' as opposed to backwards slashes '\' + * for compatibility with Amiga and UNIX file systems etc. + * + * @param zip: zip archive handler. + * + * @return the pointer to the current zip entry name, or NULL on error. + */ +const char* zip_entry_name(struct zip_t* zip); + +/** + * Returns an index of the current zip entry. + * + * @param zip zip archive handler. + * + * @return the index on success, negative number (< 0) on error. + */ +ssize_t zip_entry_index(struct zip_t* zip); + +/** + * Determines if the current zip entry is a directory entry. + * + * @param zip zip archive handler. + * + * @return the return code - 1 (true), 0 (false), negative number (< 0) on + * error. + */ +int zip_entry_isdir(struct zip_t* zip); + +/** + * Returns the uncompressed size of the current zip entry. + * Alias for zip_entry_uncomp_size (for backward compatibility). + * + * @param zip zip archive handler. + * + * @return the uncompressed size in bytes. + */ +unsigned long long zip_entry_size(struct zip_t* zip); + +/** + * Returns the uncompressed size of the current zip entry. + * + * @param zip zip archive handler. + * + * @return the uncompressed size in bytes. + */ +unsigned long long zip_entry_uncomp_size(struct zip_t* zip); + +/** + * Returns the compressed size of the current zip entry. + * + * @param zip zip archive handler. + * + * @return the compressed size in bytes. + */ +unsigned long long zip_entry_comp_size(struct zip_t* zip); + +/** + * Returns CRC-32 checksum of the current zip entry. + * + * @param zip zip archive handler. + * + * @return the CRC-32 checksum. + */ +unsigned int zip_entry_crc32(struct zip_t* zip); + +/** + * Compresses an input buffer for the current zip entry. + * + * @param zip zip archive handler. + * @param buf input buffer. + * @param bufsize input buffer size (in bytes). + * + * @return the return code - 0 on success, negative number (< 0) on error. + */ +int zip_entry_write(struct zip_t* zip, const void* buf, + size_t bufsize); + +/** + * Compresses a file for the current zip entry. + * + * @param zip zip archive handler. + * @param filename input file. + * + * @return the return code - 0 on success, negative number (< 0) on error. + */ +int zip_entry_fwrite(struct zip_t* zip, const char* filename); + +/** + * Extracts the current zip entry into output buffer. + * + * The function allocates sufficient memory for a output buffer. + * + * @param zip zip archive handler. + * @param buf output buffer. + * @param bufsize output buffer size (in bytes). + * + * @note remember to release memory allocated for a output buffer. + * for large entries, please take a look at zip_entry_extract function. + * + * @return the return code - the number of bytes actually read on success. + * Otherwise a negative number (< 0) on error. + */ +ssize_t zip_entry_read(struct zip_t* zip, void** buf, + size_t* bufsize); + +/** + * Extracts the current zip entry into a memory buffer using no memory + * allocation. + * + * @param zip zip archive handler. + * @param buf preallocated output buffer. + * @param bufsize output buffer size (in bytes). + * + * @note ensure supplied output buffer is large enough. + * zip_entry_size function (returns uncompressed size for the current + * entry) can be handy to estimate how big buffer is needed. + * For large entries, please take a look at zip_entry_extract function. + * + * @return the return code - the number of bytes actually read on success. + * Otherwise a negative number (< 0) on error (e.g. bufsize is not large + * enough). + */ +ssize_t zip_entry_noallocread(struct zip_t* zip, void* buf, + size_t bufsize); + +/** + * Extracts the current zip entry into output file. + * + * @param zip zip archive handler. + * @param filename output file. + * + * @return the return code - 0 on success, negative number (< 0) on error. + */ +int zip_entry_fread(struct zip_t* zip, const char* filename); + +/** + * Extracts the current zip entry using a callback function (on_extract). + * + * @param zip zip archive handler. + * @param on_extract callback function. + * @param arg opaque pointer (optional argument, which you can pass to the + * on_extract callback) + * + * @return the return code - 0 on success, negative number (< 0) on error. + */ +int +zip_entry_extract(struct zip_t* zip, + size_t(*on_extract)(void* arg, uint64_t offset, + const void* data, size_t size), + void* arg); + +/** + * Returns the number of all entries (files and directories) in the zip archive. + * + * @param zip zip archive handler. + * + * @return the return code - the number of entries on success, negative number + * (< 0) on error. + */ +ssize_t zip_entries_total(struct zip_t* zip); + +/** + * Deletes zip archive entries. + * + * @param zip zip archive handler. + * @param entries array of zip archive entries to be deleted. + * @param len the number of entries to be deleted. + * @return the number of deleted entries, or negative number (< 0) on error. + */ +ssize_t zip_entries_delete(struct zip_t* zip, + char* const entries[], size_t len); + +/** + * Extracts a zip archive stream into directory. + * + * If on_extract is not NULL, the callback will be called after + * successfully extracted each zip entry. + * Returning a negative value from the callback will cause abort and return an + * error. The last argument (void *arg) is optional, which you can use to pass + * data to the on_extract callback. + * + * @param stream zip archive stream. + * @param size stream size. + * @param dir output directory. + * @param on_extract on extract callback. + * @param arg opaque pointer. + * + * @return the return code - 0 on success, negative number (< 0) on error. + */ +int +zip_stream_extract(const char* stream, size_t size, const char* dir, + int (*on_extract)(const char* filename, void* arg), + void* arg); + +/** + * Opens zip archive stream into memory. + * + * @param stream zip archive stream. + * @param size stream size. + * + * @return the zip archive handler or NULL on error + */ +struct zip_t* zip_stream_open(const char* stream, size_t size, + int level, char mode); + +/** + * Copy zip archive stream output buffer. + * + * @param zip zip archive handler. + * @param buf output buffer. User should free buf. + * @param bufsize output buffer size (in bytes). + * + * @return copy size + */ +ssize_t zip_stream_copy(struct zip_t* zip, void** buf, + size_t* bufsize); + +/** + * Close zip archive releases resources. + * + * @param zip zip archive handler. + * + * @return + */ +void zip_stream_close(struct zip_t* zip); + +/** + * Creates a new archive and puts files into a single zip archive. + * + * @param zipname zip archive file. + * @param filenames input files. + * @param len: number of input files. + * + * @return the return code - 0 on success, negative number (< 0) on error. + */ +int zip_create(const char* zipname, const char* filenames[], + size_t len); + +/** + * Extracts a zip archive file into directory. + * + * If on_extract_entry is not NULL, the callback will be called after + * successfully extracted each zip entry. + * Returning a negative value from the callback will cause abort and return an + * error. The last argument (void *arg) is optional, which you can use to pass + * data to the on_extract_entry callback. + * + * @param zipname zip archive file. + * @param dir output directory. + * @param on_extract_entry on extract callback. + * @param arg opaque pointer. + * + * @return the return code - 0 on success, negative number (< 0) on error. + */ +int zip_extract(const char* zipname, const char* dir, + int (*on_extract_entry)(const char* filename, + void* arg), + void* arg); + + +#endif diff --git a/Update/main.cpp b/Update/main.cpp new file mode 100644 index 0000000..0207423 --- /dev/null +++ b/Update/main.cpp @@ -0,0 +1,13 @@ +#include "Update.h" +#include +#include +#include +int main(int argc, char *argv[]) +{ + QApplication a(argc, argv); + + QStringList list_parm = QCoreApplication::arguments(); + Update w; + w.show(); + return a.exec(); +} diff --git a/Update/res/alert.png b/Update/res/alert.png new file mode 100644 index 0000000..5bf67ce Binary files /dev/null and b/Update/res/alert.png differ diff --git a/Update/res/bg.gif b/Update/res/bg.gif new file mode 100644 index 0000000..9cbeff9 Binary files /dev/null and b/Update/res/bg.gif differ diff --git a/Update/res/close_0_28_28.png b/Update/res/close_0_28_28.png new file mode 100644 index 0000000..93ad7da Binary files /dev/null and b/Update/res/close_0_28_28.png differ diff --git a/Update/res/close_1_28_28.png b/Update/res/close_1_28_28.png new file mode 100644 index 0000000..5de06aa Binary files /dev/null and b/Update/res/close_1_28_28.png differ diff --git a/Update/res/close_2_28_28.png b/Update/res/close_2_28_28.png new file mode 100644 index 0000000..d65e71e Binary files /dev/null and b/Update/res/close_2_28_28.png differ diff --git a/Update/resource.h b/Update/resource.h new file mode 100644 index 0000000..a77d67d --- /dev/null +++ b/Update/resource.h @@ -0,0 +1,14 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Update.rc + +// 新对象的下一组默认值 +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/ssl问题.txt b/ssl问题.txt new file mode 100644 index 0000000..633140c --- /dev/null +++ b/ssl问题.txt @@ -0,0 +1 @@ +QtCreator的bin目录下 复制libssl 和libcrypto到程序目录 \ No newline at end of file diff --git a/temp_add.txt b/temp_add.txt new file mode 100644 index 0000000..bbc2fe1 --- /dev/null +++ b/temp_add.txt @@ -0,0 +1,2 @@ +// ×Զ¨Òå±êÌâÀ¸ +CustomTitleBar* m_customTitleBar; diff --git a/一些问题.txt b/一些问题.txt new file mode 100644 index 0000000..31881fc --- /dev/null +++ b/一些问题.txt @@ -0,0 +1,58 @@ +1.服务端数据库写入问题 + +订单信息Json + +{ + "page" : 1, + "row0" : [ + { + "GT" : "足球", + "CON" : "0 / 0.5", + "TID" : "17763496010", + "DATE" : "07-11-2023", + "FROM" : "totalbet_wager", + "GOLD" : "50.0", + "IS_P" : "", + "TIME" : "12:08:28", + "NAME0" : "cammvip11", + "NUM_C" : "21405", + "NUM_H" : "21406", + "SCORE" : "", + "TNAME" : "美国足球乙组联赛
  • 北卡罗莱纳U23 v 西维吉尼亚联
  • 北卡罗莱纳U23 +0 / 0.5 @ 0.74
  • 让球
  • ", + "ALIAS0" : "vip", + "FS_DIS" : "", + "G_TIME" : "07-11-2023 18:00:00", + "LEAGUE" : "美国足球乙组联赛", + "M_TYPE" : "C", + "SRV_IP" : "", + "STRONG" : "N", + "TEAM_C" : "西维吉尼亚联 ", + "TEAM_H" : "北卡罗莱纳U23 ", + "ARESULT" : "0", + "CRESULT" : "80", + "IORATIO" : "0.74", + "SETTLED" : "N", + "SRESULT" : "0", + "BALL_ACT" : "", + "BET_TYPE" : "H", + "DATETIME" : "12:08:28", + "IN_RADIO" : "0.75", + "DIF_SCORE" : "", + "ODDF_TYPE" : "香港盘", + "ORDER_CON" : " +0 / 0.5", + "RESULT_WL" : "注单平局
    取消", + "CANCEL_APN" : "", + "CANCEL_DIS" : "style='display:none'", + "CANCEL_MSG" : "", + "COMWINLOSS" : "20", + "ORDER_TYPE" : "北卡罗莱纳U23 ", + "WAGERS_TYPE" : "让球", + "RESULT_WL_CLASS" : "" + } + ], + "UPPER" : "aid=7019470", + "SGOLD0" : "50.0", + "UPPER0" : "mid=&mem_user=cammvip11", + "WCOUNT" : 1, + "total_page" : 1 +} \ No newline at end of file diff --git a/接口/a.txt b/接口/a.txt new file mode 100644 index 0000000..e69de29 diff --git a/接口/get_league_wager.txt b/接口/get_league_wager.txt new file mode 100644 index 0000000..0af3ac8 --- /dev/null +++ b/接口/get_league_wager.txt @@ -0,0 +1,21 @@ +login_layer=ag +uid=64cd29e2m10096949l748529201xw +langx=zh-cn +ver=version-06-02 +p=get_league_wager +session=RB +gtype=FT +date=all +market= +gold=0 +percentage=full +down_id=all +league_id=all +filter=Y +symbol=more + + +login_layer=ag&uid=182faa7dm10096949l748534421xw&langx=zh-cn&ver=version-06-02&p=get_league_wager&session=RB>ype=BK&date=all&market=&gold=0&percentage=full&down_id=all&league_id=all&filter=Y&symbol=more + +login_layer=ag&uid=6f0f3920m10096949l748533262xw&langx=zh-cn&ver=version-06- +02&p=get_league_wager&session=RB>ype=FT&date=&market=&gold=0&percentage=full&down_id=all&league_id=all&filter=Y&symbol=more \ No newline at end of file diff --git a/接口/get_league_wager_ori.txt b/接口/get_league_wager_ori.txt new file mode 100644 index 0000000..569dade --- /dev/null +++ b/接口/get_league_wager_ori.txt @@ -0,0 +1,15 @@ +login_layer=ag +uid=69d57cb5m10096949l748528713xw +langx=zh-cn +ver=version-06-02 +p=get_league_wager +session=RB +gtype=FT +date= +market= +gold=0 +percentage=full +down_id=all +league_id=all +filter=Y +symbol=more \ No newline at end of file diff --git a/更新记录.txt b/更新记录.txt new file mode 100644 index 0000000..daf9fc2 --- /dev/null +++ b/更新记录.txt @@ -0,0 +1,6 @@ +2025.04.30: +修复网络访问超时问题 +QNetworkRequest request; +request.setUrl(QUrl("https://example.com/api")); +request.setAttribute(QNetworkRequest::Http2AllowedAttribute, true); // 允许 HTTP/2(可选) +request.setTransferTimeout(30000); // 设置超时为 30 秒(Qt 5.15+)