Fix auto-reply duplication, message parsing and console stability

- dedupe by buyer message fingerprint and pending-message detection
- stop treating platform auto-reply and order/product cards as chat messages
- reply to buyer-sent product cards, inject card price and goods id
- add optional human-intervention fallback to debug mode
- configurable personal-order cache, block WebView2 new windows
- capture crash dumps, bump version to 1.1.2
This commit is contained in:
zhangyu
2026-11-18 23:00:57 +08:00
parent 2b55aa5a44
commit db5cc03fd2
18 changed files with 3786 additions and 266 deletions
+4
View File
@@ -10,6 +10,10 @@ config/shops.json
config/shops/
config/mail.json
# 本机登录态与界面状态,不进仓库
config/auth.json
config/ui.json
# Optional local runtime files.
*.pid
+694 -46
View File
File diff suppressed because it is too large Load Diff
+7 -5
View File
@@ -18,19 +18,21 @@ echo [2/3] 编译源码
if exist "%OUT%\PddAI.exe" del /f /q "%OUT%\PddAI.exe" >nul 2>&1
set SUBSYS=WINDOWS
if /i "%1"=="console" set SUBSYS=CONSOLE
set SRCS=src\main.cpp src\Resources.cpp src\Log.cpp src\Util.cpp src\Config.cpp src\Server.cpp src\Pipeline.cpp src\Http.cpp src\Smtp.cpp src\Stats.cpp src\Cdp.cpp src\Browser.cpp src\WebConsole.cpp
set SRCS=src\main.cpp src\Resources.cpp src\Log.cpp src\Util.cpp src\Config.cpp src\Server.cpp src\Pipeline.cpp src\Http.cpp src\Smtp.cpp src\Stats.cpp src\Cdp.cpp src\Browser.cpp src\WebConsole.cpp src\Auth.cpp src\Update.cpp
set CFLAGS=/nologo /std:c++17 /EHsc /O2 /MT /W3 /utf-8 /DUNICODE /D_UNICODE /DWIN32 /D_WINDOWS /D_CRT_SECURE_NO_WARNINGS
set INC=/I"src" /I"thirdparty" /I"%WV2%\include"
cl %CFLAGS% %INC% /Fo"%OUT%\\" /Fd"%OUT%\pddai.pdb" %SRCS% /link /OUT:"%OUT%\PddAI.exe" ^
/SUBSYSTEM:%SUBSYS% /MACHINE:X64 ^
"%OUT%\app.res" "%WV2%\x64\WebView2LoaderStatic.lib" ^
user32.lib gdi32.lib ole32.lib oleaut32.lib shell32.lib shlwapi.lib advapi32.lib comdlg32.lib version.lib ws2_32.lib iphlpapi.lib winhttp.lib secur32.lib windowscodecs.lib
user32.lib gdi32.lib ole32.lib oleaut32.lib shell32.lib shlwapi.lib advapi32.lib comdlg32.lib version.lib ws2_32.lib iphlpapi.lib winhttp.lib secur32.lib bcrypt.lib windowscodecs.lib winmm.lib
if errorlevel 1 goto :fail
echo [3/3] 完成
echo 产物: %OUT%\PddAI.exe
if exist "%OUT%\PddAI.exe" dir "%OUT%\PddAI.exe"
echo [3/4] 重命名为中文程序名
powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference = 'Stop'; $d = Join-Path (Get-Location) 'bin'; $n = [string][char]0x62FC + [char]0x591A + [char]0x591A + [char]0x5BA2 + [char]0x670D + [char]0x52A9 + [char]0x624B + '.exe'; $dst = Join-Path $d $n; if (Test-Path -LiteralPath $dst) { Remove-Item -LiteralPath $dst -Force }; Rename-Item -LiteralPath (Join-Path $d 'PddAI.exe') -NewName $n; $f = Get-Item -LiteralPath $dst; Write-Output ('OK ' + $f.FullName + ' ' + $f.Length)"
if errorlevel 1 goto :fail
echo [4/4] 完成
endlocal
exit /b 0
+8 -7
View File
@@ -9,10 +9,11 @@ IDR_INJECT_CONTENT_CSS RCDATA "..\\..\\extension\\content.css"
IDR_EXT_MANIFEST RCDATA "..\\..\\extension\\manifest.json"
IDR_EXT_BACKGROUND RCDATA "..\\..\\extension\\background.js"
IDR_INJECT_STEALTH_JS RCDATA "..\\..\\extension\\stealth.js"
IDI_APP_ICON ICON "..\\..\\res\\黑色.ico"
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,0,0
PRODUCTVERSION 1,0,0,0
FILEVERSION 1,1,2,0
PRODUCTVERSION 1,1,2,0
FILEFLAGSMASK 0x3fL
FILEFLAGS 0x0L
FILEOS 0x40004L
@@ -24,12 +25,12 @@ BEGIN
BLOCK "080404b0"
BEGIN
VALUE "CompanyName", "PddAI"
VALUE "FileDescription", "PddAI 客服助手"
VALUE "FileVersion", "1.0.0"
VALUE "FileDescription", "拼多多客服助手"
VALUE "FileVersion", "1.1.2"
VALUE "InternalName", "PddAI"
VALUE "OriginalFilename", "PddAI.exe"
VALUE "ProductName", "PddAI 客服助手"
VALUE "ProductVersion", "1.0.0"
VALUE "OriginalFilename", "拼多多客服助手.exe"
VALUE "ProductName", "拼多多客服助手"
VALUE "ProductVersion", "1.1.2"
END
END
BLOCK "VarFileInfo"
+384
View File
@@ -0,0 +1,384 @@
#include "Auth.h"
#include <windows.h>
#include <bcrypt.h>
#include <cstdio>
#include <ctime>
#include <mutex>
#include <stdexcept>
#include <vector>
#include "Config.h"
#include "Http.h"
#include "Log.h"
#include "Util.h"
namespace pddai {
namespace {
constexpr const char* kStateFile = "auth.json";
// 验证服务地址、应用 appKey、AES 密钥全部内置,不支持环境变量或配置文件覆盖
constexpr const char* kBaseUrl = "https://v.viaeon.com";
constexpr const char* kAppKey = "f26091ac15457317f59af0c01ef698b9";
constexpr const char* kEncryptKey = "289cbdcf5ce206f7c5a8a8533bc368f4031dd87f1fa3ece014a1cd691ef5fcb2";
constexpr int kTimeoutMs = 10000;
std::mutex g_mutex;
json g_state = json::object();
bool g_loaded = false;
std::string Str(const json& obj, const char* key) {
if (!obj.is_object()) return "";
const auto it = obj.find(key);
return it != obj.end() && it->is_string() ? it->get<std::string>() : std::string();
}
// 与 verify 服务端 padKey 一致:长度不是 16/24/32 时按原字符循环补齐到 32 字节
std::string NormalizeAesKey(const std::string& key) {
if (key.size() == 16 || key.size() == 24 || key.size() == 32) return key;
if (key.empty()) return std::string();
std::string padded(32, '\0');
for (size_t i = 0; i < padded.size(); ++i) padded[i] = key[i % key.size()];
return padded;
}
// 解密 verify 的 AES-GCM 响应:Base64(nonce(12) + 密文 + tag(16)),无附加认证数据
bool AesGcmDecrypt(const std::string& key, const std::string& cipherText, std::string& plain) {
constexpr size_t kNonceSize = 12;
constexpr size_t kTagSize = 16;
const std::string raw = Base64Decode(cipherText);
if (raw.size() <= kNonceSize + kTagSize) return false;
const std::string keyBytes = NormalizeAesKey(key);
if (keyBytes.empty()) return false;
BCRYPT_ALG_HANDLE alg = nullptr;
BCRYPT_KEY_HANDLE handle = nullptr;
bool ok = false;
do {
if (!BCRYPT_SUCCESS(BCryptOpenAlgorithmProvider(&alg, BCRYPT_AES_ALGORITHM, nullptr, 0))) break;
if (!BCRYPT_SUCCESS(BCryptSetProperty(
alg, BCRYPT_CHAINING_MODE,
reinterpret_cast<PUCHAR>(const_cast<wchar_t*>(BCRYPT_CHAIN_MODE_GCM)),
sizeof(BCRYPT_CHAIN_MODE_GCM), 0))) {
break;
}
DWORD objectLength = 0, written0 = 0;
if (!BCRYPT_SUCCESS(BCryptGetProperty(alg, BCRYPT_OBJECT_LENGTH,
reinterpret_cast<PUCHAR>(&objectLength),
sizeof(objectLength), &written0, 0))) {
break;
}
std::vector<unsigned char> object(objectLength);
if (!BCRYPT_SUCCESS(BCryptGenerateSymmetricKey(
alg, &handle, object.data(), objectLength,
reinterpret_cast<PUCHAR>(const_cast<char*>(keyBytes.data())),
static_cast<ULONG>(keyBytes.size()), 0))) {
break;
}
BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info;
BCRYPT_INIT_AUTH_MODE_INFO(info);
info.pbNonce = reinterpret_cast<PUCHAR>(const_cast<char*>(raw.data()));
info.cbNonce = static_cast<ULONG>(kNonceSize);
info.pbTag = reinterpret_cast<PUCHAR>(const_cast<char*>(raw.data() + raw.size() - kTagSize));
info.cbTag = static_cast<ULONG>(kTagSize);
std::vector<unsigned char> buffer(raw.size());
ULONG written = 0;
const ULONG cipherLength = static_cast<ULONG>(raw.size() - kNonceSize - kTagSize);
const NTSTATUS status = BCryptDecrypt(
handle, reinterpret_cast<PUCHAR>(const_cast<char*>(raw.data() + kNonceSize)), cipherLength,
&info, nullptr, 0, buffer.data(), static_cast<ULONG>(buffer.size()), &written, 0);
if (!BCRYPT_SUCCESS(status)) break;
plain.assign(reinterpret_cast<const char*>(buffer.data()), written);
ok = true;
} while (false);
if (handle) BCryptDestroyKey(handle);
if (alg) BCryptCloseAlgorithmProvider(alg, 0);
return ok;
}
// 记住的密码做轻量混淆,避免在 auth.json 里直接暴露明文(防窥屏,不是加密)
std::string Obfuscate(const std::string& text) {
std::string mixed = text;
for (size_t i = 0; i < mixed.size(); ++i) {
mixed[i] = static_cast<char>(mixed[i] ^ (0x5B + static_cast<int>((i * 7) % 31)));
}
return Base64Encode(mixed);
}
std::string Deobfuscate(const std::string& text) {
if (text.empty()) return std::string();
std::string mixed = Base64Decode(text);
for (size_t i = 0; i < mixed.size(); ++i) {
mixed[i] = static_cast<char>(mixed[i] ^ (0x5B + static_cast<int>((i * 7) % 31)));
}
return mixed;
}
// 卷序列号 + 计算机名做 FNV-1a,保证同一台机器重启后 device_id 不变
std::string MakeDeviceId() {
const std::wstring exe = ExeDir();
std::wstring root = L"C:\\";
if (exe.size() >= 2 && exe[1] == L':') root = exe.substr(0, 2) + L"\\";
DWORD serial = 0;
wchar_t volume[256]{}, fs[256]{};
DWORD maxComponent = 0, flags = 0;
if (!::GetVolumeInformationW(root.c_str(), volume, 256, &serial, &maxComponent, &flags, fs, 256)) {
serial = 0;
}
unsigned long long hash = 14695981039346656037ull;
const std::string seed = std::to_string(serial) + "|" + ComputerNameUtf8();
for (const unsigned char c : seed) {
hash ^= c;
hash *= 1099511628211ull;
}
char buf[32]{};
std::snprintf(buf, sizeof(buf), "%016llx", hash);
return std::string(buf);
}
// 下面三个函数都要求调用方已持有 g_mutex
json LoadLocked() {
if (!g_loaded) {
try {
const json saved = Config::GetJsonGlobal(kStateFile, json::object());
if (saved.is_object()) g_state = saved;
} catch (const std::exception& error) {
Log::Error(std::string("读取验证配置失败: ") + error.what());
}
g_loaded = true;
}
if (!g_state.is_object()) g_state = json::object();
return g_state;
}
void SaveLocked(const json& state) {
g_state = state;
g_loaded = true;
try {
Config::WriteTextGlobal(kStateFile, g_state.dump(2));
} catch (const std::exception& error) {
Log::Error(std::string("保存验证配置失败: ") + error.what());
}
}
json Ensure() {
std::lock_guard<std::mutex> lock(g_mutex);
json state = LoadLocked();
bool changed = false;
// 旧版本写在 auth.json 里的连接配置已不再使用,读到就清理掉
for (const char* legacy : {"baseUrl", "appKey", "encryptKey"}) {
if (state.contains(legacy)) { state.erase(legacy); changed = true; }
}
if (Str(state, "device_id").empty()) { state["device_id"] = MakeDeviceId(); changed = true; }
if (changed) SaveLocked(state);
return state;
}
std::string Endpoint(const std::string& leaf) {
return std::string(kBaseUrl) + "/api/v1/app/" + kAppKey + "/" + leaf;
}
std::string EncryptKey() {
return kEncryptKey;
}
// 开启加密时整个响应被包成 {"data":"<base64>"},这里解包成内部真实的 {code,message,data}
bool UnwrapEncrypted(const std::string& key, const json& doc, json& out) {
if (!doc.is_object() || doc.size() != 1) return false;
const auto it = doc.find("data");
if (it == doc.end() || !it->is_string()) return false;
std::string plain;
if (!AesGcmDecrypt(key, it->get<std::string>(), plain)) return false;
out = json::parse(plain, nullptr, false);
return !out.is_discarded();
}
AuthResult Call(const std::string& leaf, const json& body, const std::string& token, bool get) {
AuthResult out;
const std::string url = Endpoint(leaf);
Http::Headers headers;
if (!token.empty()) headers.emplace_back("Authorization", "Bearer " + token);
try {
const HttpResponse resp = get
? Http::GetJson(url, headers, kTimeoutMs, std::string())
: Http::PostJson(url, headers, body, kTimeoutMs, std::string());
out.status = resp.status;
json doc = resp.data;
if (UnwrapEncrypted(EncryptKey(), doc, doc)) {
// 解包成功,按内部结构解析
} else if (resp.status == 200 && doc.is_object() && doc.size() == 1 &&
doc.contains("data") && doc["data"].is_string()) {
out.message = "验证服务响应解密失败,请检查 AES 密钥是否与后台一致";
return out;
}
if (doc.is_object()) {
out.message = Str(doc, "message");
const auto code = doc.find("code");
if (code != doc.end() && code->is_number_integer()) out.status = code->get<int>();
const auto data = doc.find("data");
if (data != doc.end()) out.data = *data;
}
out.ok = out.status == 200;
if (out.message.empty()) {
out.message = out.ok ? "操作成功" : ("请求失败(" + std::to_string(out.status) + ")");
}
} catch (const std::exception& error) {
out.status = 0;
out.message = "无法连接验证服务器:" + std::string(error.what());
}
return out;
}
json CommonBody(const json& state, const std::string& username) {
json body = json::object();
body["username"] = username;
body["device_id"] = Str(state, "device_id");
body["device_name"] = ComputerNameUtf8();
body["device_type"] = "windows";
return body;
}
} // namespace
json Auth::State() {
std::lock_guard<std::mutex> lock(g_mutex);
return LoadLocked();
}
void Auth::ClearSession() {
std::lock_guard<std::mutex> lock(g_mutex);
json state = LoadLocked();
state["token"] = "";
state["user_id"] = 0;
state["last_ok"] = 0;
SaveLocked(state);
}
void Auth::RememberCredentials(const std::string& username, const std::string& password) {
std::lock_guard<std::mutex> lock(g_mutex);
json state = LoadLocked();
state["remember"] = true;
state["saved_username"] = username;
state["saved_password"] = Obfuscate(password);
SaveLocked(state);
}
void Auth::ForgetCredentials() {
std::lock_guard<std::mutex> lock(g_mutex);
json state = LoadLocked();
state["remember"] = false;
state["saved_username"] = "";
state["saved_password"] = "";
SaveLocked(state);
}
bool Auth::Remembered() {
std::lock_guard<std::mutex> lock(g_mutex);
const json state = LoadLocked();
return state.value("remember", false);
}
std::string Auth::SavedUsername() {
std::lock_guard<std::mutex> lock(g_mutex);
const json state = LoadLocked();
return state.value("remember", false) ? Str(state, "saved_username") : std::string();
}
std::string Auth::SavedPassword() {
std::lock_guard<std::mutex> lock(g_mutex);
const json state = LoadLocked();
if (!state.value("remember", false)) return std::string();
return Deobfuscate(Str(state, "saved_password"));
}
AuthResult Auth::Register(const std::string& username, const std::string& password) {
const json state = Ensure();
json body = CommonBody(state, username);
body["password"] = password;
return Call("register", body, std::string(), false);
}
AuthResult Auth::Login(const std::string& username, const std::string& password) {
const json state = Ensure();
json body = CommonBody(state, username);
body["password"] = password;
AuthResult result = Call("login", body, std::string(), false);
if (result.ok) {
const std::string token = Str(result.data, "token");
if (token.empty()) {
result.ok = false;
result.message = "登录响应缺少 token";
} else {
std::lock_guard<std::mutex> lock(g_mutex);
json saved = LoadLocked();
saved["username"] = username;
saved["user_id"] = result.data.value("user_id", 0);
saved["token"] = token;
saved["last_ok"] = static_cast<long long>(std::time(nullptr));
SaveLocked(saved);
}
}
return result;
}
AuthResult Auth::Recharge(const std::string& username, const std::string& cardKey) {
const json state = Ensure();
json body = json::object();
body["username"] = username;
body["card_key"] = cardKey;
body["device_id"] = Str(state, "device_id");
return Call("recharge", body, std::string(), false);
}
AuthResult Auth::Heartbeat() {
const json state = Ensure();
const std::string token = Str(state, "token");
if (token.empty()) {
AuthResult out;
out.status = 401;
out.message = "尚未登录";
return out;
}
AuthResult result = Call("heartbeat", json::object(), token, false);
// token 失效或余额/订阅异常时清掉本地登录态;只在 token 未被并发登录替换时清
if (!result.ok && (result.status == 401 || result.status == 403)) {
std::lock_guard<std::mutex> lock(g_mutex);
json saved = LoadLocked();
if (Str(saved, "token") == token) {
saved["token"] = "";
SaveLocked(saved);
}
}
return result;
}
AuthResult Auth::Info() {
return Call("info", json::object(), std::string(), true);
}
AuthResult Auth::CheckUpdate(const std::string& version) {
return Call("check-update?version=" + version, json::object(), std::string(), true);
}
std::string Auth::ResolveUrl(const std::string& url) {
if (url.empty()) return url;
if (url.rfind("http://", 0) == 0 || url.rfind("https://", 0) == 0) return url;
if (url[0] == '/') return std::string(kBaseUrl) + url;
return std::string(kBaseUrl) + "/" + url;
}
}
+44
View File
@@ -0,0 +1,44 @@
#pragma once
#include <string>
#include "Json.h"
namespace pddai {
struct AuthResult {
bool ok = false;
int status = 0; // HTTP 状态码;0 表示网络层失败
std::string message; // 服务端 message 或本地错误说明
json data; // 响应中的 data 字段
};
// 对接验证平台 /api/v1/app/{appKey}/* 的公开接口与心跳。
// 所有网络调用都是同步的,调用方需放在工作线程里执行。
class Auth {
public:
// 缓存的本地状态(config/auth.json),不含密码与卡密
static json State();
// 退出登录:只清 token / user_id,保留账号名与设备标识
static void ClearSession();
// 记住账号密码:密码做轻量混淆后随登录态一起写入 auth.json
static void RememberCredentials(const std::string& username, const std::string& password);
static void ForgetCredentials();
static bool Remembered();
static std::string SavedUsername();
static std::string SavedPassword();
static AuthResult Register(const std::string& username, const std::string& password);
static AuthResult Login(const std::string& username, const std::string& password);
static AuthResult Recharge(const std::string& username, const std::string& cardKey);
static AuthResult Heartbeat();
static AuthResult Info();
// 版本检测:version 为当前客户端版本号
static AuthResult CheckUpdate(const std::string& version);
// 把服务端返回的相对地址(如 /uploads/xxx.zip)补全为完整 URL
static std::string ResolveUrl(const std::string& url);
};
}
+95 -4
View File
@@ -7,6 +7,7 @@
#include <cmath>
#include <cstdio>
#include <functional>
#include <random>
#include <set>
#include <stdexcept>
#include <string>
@@ -279,6 +280,8 @@ json NormalizeMessages(const json& raw) {
const json config = Config::GetJson("server.json", json::object());
long long historyLimit = 6;
// 全部历史:不截断
if (config.is_object() && config.value("historyAll", false)) historyLimit = 0;
const json limit = config.is_object() ? config.value("historyLimit", json()) : json();
if (limit.is_number_integer()) {
const long long value = limit.get<long long>();
@@ -471,15 +474,28 @@ void ApplyMatchedImages(json& data, const json& images) {
if (!withText) data["reply"] = "";
}
// 返回 {name, reply, images?} 或 null
// 随机回复:命中后从 replies 里随机取一条,没配则用 reply 单条
std::string PickQuickReplyText(const json& rule) {
std::vector<std::string> candidates;
for (const std::string& line : StringArray(GetMember(rule, "replies"))) {
if (!line.empty()) candidates.push_back(line);
}
if (candidates.empty()) return JsString(GetMember(rule, "reply"));
static thread_local std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<size_t> dist(0, candidates.size() - 1);
return candidates[dist(rng)];
}
json MatchQuickReply(const std::string& text, const json& quickReplies, const json& imageLibrary) {
const std::string normalized = NormalizeForQuickReply(text);
if (normalized.empty() || !quickReplies.is_array()) return json();
for (const json& rule : quickReplies) {
if (!rule.is_object()) continue;
// 默认按包含关键词匹配(关键词是买家消息的一部分即可),只有显式写 exact 才要求整句一致
const std::string matchMode = JsString(GetMember(rule, "match"));
const bool includesMode = matchMode == "includes";
const bool includesMode = matchMode != "exact";
bool matched = false;
for (const std::string& keyword : StringArray(GetMember(rule, "keywords"))) {
@@ -497,7 +513,7 @@ json MatchQuickReply(const std::string& text, const json& quickReplies, const js
std::string name = JsString(GetMember(rule, "name"));
if (name.empty()) name = "quick-reply";
out["name"] = name;
out["reply"] = JsString(GetMember(rule, "reply"));
out["reply"] = PickQuickReplyText(rule);
json images = json::array();
for (const std::string& key : StringArray(GetMember(rule, "imageIds"))) {
@@ -1963,6 +1979,32 @@ std::string BuildCozeProductContext(const json& context) {
for (const std::string& part : parts) {
if (seen.insert(part).second) unique.push_back(part);
}
// 商品属性(是否换底、是否裁切、规格、工艺等)必须一起给模型,
// 否则模型只能靠通用常识猜,容易把别的商品规则套过来。
const json product = GetMember(context, "product");
bool hasAttributes = false;
if (product.is_object()) {
const std::string name = JsString(GetMember(product, "name"));
if (!name.empty()) unique.push_back("商品名称:" + name);
const json attributes = GetMember(product, "attributes");
if (attributes.is_object()) {
std::vector<std::string> items;
for (auto it = attributes.begin(); it != attributes.end(); ++it) {
const std::string value = JsString(it.value());
if (value.empty()) continue;
items.push_back(it.key() + ":" + value);
if (items.size() >= 30) break;
}
if (!items.empty()) {
unique.push_back("商品属性:" + JoinStrings(items, ";"));
hasAttributes = true;
}
}
}
if (!hasAttributes) {
unique.push_back("商品属性:未提供,不要自行推断能否换底、裁切或其它工艺限制");
}
return JoinStrings(unique, "\n");
}
@@ -2066,6 +2108,8 @@ std::string BuildCozeCustomerQuery(const std::string& requestId, const json& con
"如果客户最新问题是通用问题或标准话术问题,例如正品、防伪、发货、售后配节、价格、赠品、包装、发票、优惠、保修等,请优先检索并参考知识库文件“标准FAQ.md”。",
"如果“标准FAQ.md”中有同义或近似问题,优先使用其中的标准回答和语气,再结合商品上下文做必要补充。",
"知识库检索时必须优先使用“当前商品卡片信息”和“客户最新问题”共同判断商品型号/规格。",
"回答换底色、裁剪、尺寸、材质、工艺等商品能力问题时,必须以“当前商品卡片信息”里的商品属性为准,不要用其它商品的规则代替。",
"商品属性里没有写的,不要断言“不能换底”“不做裁剪”这类限制;确实需要确认时,用不确定的语气请客户稍等核实。",
"如果当前商品卡片信息包含型号、米数、套餐、规格,请优先匹配对应型号的话术;不要笼统回复“规格参数未提供”。",
"只有当前商品为0且最近聊天也没有商品线索时,才可以说明需要客户提供具体规格。",
"如果 orders 中有当前买家订单,买家询问订单号、下单时间、商品、订单状态或售后时,直接引用其中的真实数据,不要要求买家提供订单号。",
@@ -2403,6 +2447,15 @@ json Pipeline::Run(const json& payload, const json& shop) {
productCandidates.push_back(rankedCandidates[i]);
}
// 属性有没有随请求带给模型,直接看日志就能确认
if (product.is_object()) {
const json attributes = GetMember(product, "attributes");
Log::Info("商品匹配:" + JsString(GetMember(product, "name")) + ",属性=" +
std::to_string(attributes.is_object() ? attributes.size() : 0) + " 项");
} else {
Log::Info("商品匹配:未匹配到商品,回复不推断换底/裁切等工艺");
}
std::string latestCustomerMessage;
for (size_t i = messages.size(); i > 0; --i) {
const json& item = messages[i - 1];
@@ -2413,7 +2466,45 @@ json Pipeline::Run(const json& payload, const json& shop) {
}
// 1) 快捷回复
const json quickReply = MatchQuickReply(latestCustomerMessage, quickReplies, imageLibrary);
// 只看最近一条客服消息之后买家发的内容:买家连发「你好」+图片时,前面那句文字也要参与命中
std::vector<std::string> pendingCustomerTexts;
for (size_t i = messages.size(); i > 0; --i) {
const json& item = messages[i - 1];
const std::string usertype = JsString(GetMember(item, "usertype"));
if (usertype == "sys") break;
if (usertype != "cus") continue;
pendingCustomerTexts.push_back(JsString(GetMember(item, "msg")));
}
// 末尾是客服/系统消息时说明买家上一条已经回复过,不能再把那条旧消息
// 塞回来命中快捷回复,否则会把上一次的回复内容原样再发一遍。
// latestCustomerMessage 仍用于后面的高危意图与模型上下文,不受影响。
Log::Info("快捷回复检查:规则=" + std::to_string(quickReplies.is_array() ? quickReplies.size() : 0) +
",待回复买家消息=" + JoinStrings(pendingCustomerTexts, " | "));
// 最近一条客服消息之后没有买家内容,说明这一轮没有新消息要回。
// 不能再拿更早的买家消息去命中快捷回复或让模型生成,否则会把上次的回复原样再发一遍。
if (pendingCustomerTexts.empty()) {
json data = json::object();
data["requestId"] = requestId;
data["action"] = "skip";
data["reason"] = "no-pending-message";
data["manualRequired"] = false;
data["reply"] = "";
data["shopId"] = shopId;
data["shopName"] = shopName;
data["pid"] = pid;
data["riskIntents"] = json::array();
data["source"] = "no-pending-message";
return data;
}
json quickReply;
for (const std::string& text : pendingCustomerTexts) {
if (text.empty() || text == "[图片]" || text == "[视频]") continue;
quickReply = MatchQuickReply(text, quickReplies, imageLibrary);
if (quickReply.is_object()) break;
}
if (quickReply.is_object()) {
json data = json::object();
data["requestId"] = requestId;
+25
View File
@@ -3,6 +3,7 @@
#include <winsock2.h>
#include <windows.h>
#include <mmsystem.h>
#include <winhttp.h>
#include <iphlpapi.h>
#include <objbase.h>
@@ -625,6 +626,8 @@ bool IsTrustedOrigin(const httplib::Request& req) {
}
long long RuntimeHistoryLimit(const json& config) {
// historyAll:读取全部历史,等价于 0
if (config.is_object() && config.value("historyAll", false)) return 0;
const json value = config.is_object() ? config.value("historyLimit", json()) : json();
if (!value.is_number_integer()) return 6;
const long long limit = value.get<long long>();
@@ -852,8 +855,11 @@ void HandleRuntimeConfig(const httplib::Request& req, httplib::Response& res) {
json data = json::object();
data["ok"] = true;
data["historyLimit"] = RuntimeHistoryLimit(config);
data["historyAll"] = config.is_object() && config.value("historyAll", false);
data["imageOutputDir"] = PickString(config, "imageOutputDir");
data["imageSaveEnabled"] = PickBool(config, "imageSaveEnabled", true);
// 买家把图片当文件发送时,也按聊天图片识别、下载、计数
data["imageFileAsImage"] = PickBool(config, "imageFileAsImage", true);
const std::string mode = PickString(config, "imageAssignMode");
data["imageAssignMode"] = (mode == "time" || mode == "sequence" || mode == "sequence-reverse" || mode == "hybrid")
? mode : "hybrid";
@@ -864,6 +870,8 @@ void HandleRuntimeConfig(const httplib::Request& req, httplib::Response& res) {
data["imageHistoryLeadMs"] = (std::max)(60000LL, (std::min)(86400000LL,
PickIntMs(config, "imageHistoryLeadMs", 600000)));
data["imageCountCheck"] = PickBool(config, "imageCountCheck", true);
// 商品关键词固定张数:命中后整单按固定值校验,忽略规格里的「N张」
data["imageKeywordFixedCount"] = PickString(config, "imageKeywordFixedCount");
data["imageReviewEnabled"] = PickBool(config, "imageReviewEnabled", true);
data["imageKeepOrderTab"] = PickBool(config, "imageKeepOrderTab", true);
// 数量不符时给订单文件夹加备注、并自动回复买家差值
@@ -906,6 +914,8 @@ void HandleRuntimeConfig(const httplib::Request& req, httplib::Response& res) {
? Config::DefaultAdjustDeleteReply() : adjustDeleteReply;
data["minPageDelayMs"] = (std::max)(0LL, (std::min)(60000LL, PickIntMs(config, "minPageDelayMs", 150)));
data["maxPageDelayMs"] = (std::max)(0LL, (std::min)(60000LL, PickIntMs(config, "maxPageDelayMs", 400)));
// 个人订单面板缓存时长:读一次要点开页签再点回去,太频繁会看到右侧闪动;0 表示每轮都重读
data["orderCacheMs"] = (std::max)(0LL, (std::min)(3600000LL, PickIntMs(config, "orderCacheMs", 300000)));
// 命中高危意图后,是否把该会话标记为转人工(后续消息不再自动回复)
data["riskStopOnHit"] = PickBool(config, "riskStopOnHit", true);
// 开场说明:首次咨询 / 有新订单时,先单独发一段规则说明
@@ -2213,6 +2223,18 @@ json HandleReplyCore(const json& payload, const json& shop) {
return Pipeline::Run(payload, shop);
}
// 命中风险意图时按店铺配置播放提醒声音(mail.json 的 riskSoundEnabled / riskSoundPath)
void PlayRiskSound() {
try {
const json mail = Config::GetJson("mail.json", json::object());
if (!mail.is_object() || !mail.value("riskSoundEnabled", false)) return;
const std::string path = mail.value("riskSoundPath", std::string());
PlayAudioFile(path);
Log::Info("命中风险意图,已播放提醒声音");
} catch (const std::exception&) {
}
}
// 只做计数,不影响任何返回给插件的字段
void RecordReplyStats(const json& result) {
if (!result.is_object()) return;
@@ -2258,6 +2280,9 @@ void HandleReply(const httplib::Request& req, httplib::Response& res) {
const json result = HandleReplyCore(body, shop);
RecordReplyStats(result);
const auto riskIt = result.find("riskIntents");
if (riskIt != result.end() && riskIt->is_array() && !riskIt->empty()) PlayRiskSound();
const long long targetDelay = PickReplyDelayMs();
const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - started)
+458
View File
@@ -0,0 +1,458 @@
#include "Update.h"
#include <windows.h>
#include <winhttp.h>
#include <winver.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include "Auth.h"
#include "Json.h"
#include "Log.h"
#include "Util.h"
namespace pddai {
namespace {
constexpr int kTimeoutMs = 15000;
std::wstring ExePath() {
std::vector<wchar_t> buf(MAX_PATH);
for (;;) {
const DWORD n = ::GetModuleFileNameW(nullptr, buf.data(), static_cast<DWORD>(buf.size()));
if (n == 0) return std::wstring();
if (n < buf.size() - 1) break;
buf.resize(buf.size() * 2);
}
return std::wstring(buf.data());
}
std::string Str(const json& obj, const char* key) {
const auto it = obj.find(key);
if (it == obj.end() || !it->is_string()) return std::string();
return it->get<std::string>();
}
long long Int64(const json& obj, const char* key) {
const auto it = obj.find(key);
if (it == obj.end() || !it->is_number()) return 0;
return static_cast<long long>(it->get<double>());
}
bool EnsureDir(const std::wstring& dir) {
if (::CreateDirectoryW(dir.c_str(), nullptr)) return true;
return ::GetLastError() == ERROR_ALREADY_EXISTS;
}
struct UrlParts {
bool https = false;
std::wstring host;
int port = 0;
std::wstring path;
};
bool CrackUrl(const std::string& url, UrlParts& out) {
const std::wstring wide = Utf8ToWide(url);
URL_COMPONENTSW comp{};
comp.dwStructSize = sizeof(comp);
wchar_t scheme[32]{};
wchar_t host[512]{};
wchar_t path[8192]{};
wchar_t extra[8192]{};
comp.lpszScheme = scheme;
comp.dwSchemeLength = 32;
comp.lpszHostName = host;
comp.dwHostNameLength = 512;
comp.lpszUrlPath = path;
comp.dwUrlPathLength = 8192;
comp.lpszExtraInfo = extra;
comp.dwExtraInfoLength = 8192;
if (!::WinHttpCrackUrl(wide.c_str(), static_cast<DWORD>(wide.size()), 0, &comp)) return false;
out.https = comp.nScheme == INTERNET_SCHEME_HTTPS;
out.host.assign(host, comp.dwHostNameLength);
out.port = static_cast<int>(comp.nPort);
out.path.assign(path, comp.dwUrlPathLength);
out.path.append(extra, comp.dwExtraInfoLength);
if (out.path.empty()) out.path = L"/";
return true;
}
struct HandleGuard {
HINTERNET h = nullptr;
~HandleGuard() {
if (h) ::WinHttpCloseHandle(h);
}
};
// 流式下载到文件,失败时 error 带 Win32 码
bool DownloadFile(const std::string& url, const std::wstring& destPath,
const std::function<void(int)>& progress, std::string& error) {
UrlParts parts;
if (!CrackUrl(url, parts)) {
error = "下载地址无效:" + url;
return false;
}
HandleGuard session{::WinHttpOpen(L"PddAI-Updater/1.0", WINHTTP_ACCESS_TYPE_NO_PROXY,
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0)};
if (!session.h) {
error = "初始化下载失败";
return false;
}
::WinHttpSetTimeouts(session.h, kTimeoutMs, kTimeoutMs, kTimeoutMs, 60000);
HandleGuard connect{::WinHttpConnect(session.h, parts.host.c_str(),
static_cast<INTERNET_PORT>(parts.port), 0)};
if (!connect.h) {
error = "连接更新服务器失败";
return false;
}
HandleGuard request{::WinHttpOpenRequest(connect.h, L"GET", parts.path.c_str(), nullptr,
WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES,
parts.https ? WINHTTP_FLAG_SECURE : 0)};
if (!request.h) {
error = "创建下载请求失败";
return false;
}
if (!::WinHttpSendRequest(request.h, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA,
0, 0, 0) ||
!::WinHttpReceiveResponse(request.h, nullptr)) {
error = "下载请求失败,Win32=" + std::to_string(::GetLastError());
return false;
}
DWORD status = 0;
DWORD size = sizeof(status);
::WinHttpQueryHeaders(request.h, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX, &status, &size, WINHTTP_NO_HEADER_INDEX);
if (status != 200) {
error = "下载失败,HTTP " + std::to_string(status);
return false;
}
long long total = 0;
wchar_t lengthText[64]{};
size = sizeof(lengthText);
if (::WinHttpQueryHeaders(request.h, WINHTTP_QUERY_CONTENT_LENGTH, WINHTTP_HEADER_NAME_BY_INDEX,
lengthText, &size, WINHTTP_NO_HEADER_INDEX)) {
total = _wtoi64(lengthText);
}
HANDLE file = ::CreateFileW(destPath.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) {
error = "无法创建更新文件";
return false;
}
std::vector<char> buffer(64 * 1024);
long long received = 0;
bool ok = true;
for (;;) {
DWORD read = 0;
if (!::WinHttpReadData(request.h, buffer.data(), static_cast<DWORD>(buffer.size()), &read)) {
error = "下载中断,Win32=" + std::to_string(::GetLastError());
ok = false;
break;
}
if (read == 0) break;
DWORD written = 0;
if (!::WriteFile(file, buffer.data(), read, &written, nullptr) || written != read) {
error = "写入更新文件失败";
ok = false;
break;
}
received += read;
if (total > 0 && progress) {
progress(static_cast<int>(received * 100 / total));
}
}
::CloseHandle(file);
if (ok && received == 0) {
error = "更新包内容为空";
ok = false;
}
return ok;
}
bool ReadWholeFile(const std::wstring& path, std::string& out) {
HANDLE file = ::CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) return false;
LARGE_INTEGER size{};
if (!::GetFileSizeEx(file, &size) || size.QuadPart > 512LL * 1024 * 1024) {
::CloseHandle(file);
return false;
}
out.resize(static_cast<size_t>(size.QuadPart));
DWORD read = 0;
const bool ok = out.empty() ||
(::ReadFile(file, out.data(), static_cast<DWORD>(out.size()), &read, nullptr) &&
read == out.size());
::CloseHandle(file);
return ok;
}
bool RunHiddenAndWait(const std::wstring& commandLine, std::string& error) {
// 把子进程输出重定向到文件,失败时便于把真实原因带回去
const std::wstring logPath = DataDir() + L"\\update\\extract.log";
HANDLE log = ::CreateFileW(logPath.c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
STARTUPINFOW si{};
si.cb = sizeof(si);
if (log != INVALID_HANDLE_VALUE) {
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
si.hStdOutput = log;
si.hStdError = log;
}
PROCESS_INFORMATION pi{};
std::wstring cmd = commandLine;
if (!::CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, log != INVALID_HANDLE_VALUE,
CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi)) {
if (log != INVALID_HANDLE_VALUE) ::CloseHandle(log);
error = "无法启动解压进程,Win32=" + std::to_string(::GetLastError());
return false;
}
::WaitForSingleObject(pi.hProcess, 120000);
DWORD code = 1;
::GetExitCodeProcess(pi.hProcess, &code);
::CloseHandle(pi.hThread);
::CloseHandle(pi.hProcess);
if (log != INVALID_HANDLE_VALUE) ::CloseHandle(log);
if (code != 0) {
error = "解压更新包失败";
std::string text;
if (ReadWholeFile(logPath, text) && !text.empty()) {
if (text.size() > 300) text = text.substr(text.size() - 300);
error += ":" + text;
}
return false;
}
return true;
}
// 用系统自带 Expand-Archive 解压,避免引入第三方解压库
bool ExtractZip(const std::wstring& zip, const std::wstring& dest, std::string& error) {
std::wstring cmd = L"powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command ";
cmd += L"\"Expand-Archive -LiteralPath '" + zip + L"' -DestinationPath '" + dest + L"' -Force\"";
return RunHiddenAndWait(cmd, error);
}
std::wstring FileNameOf(const std::wstring& path) {
const size_t pos = path.find_last_of(L"\\/");
return pos == std::wstring::npos ? path : path.substr(pos + 1);
}
std::wstring FindExeInDir(const std::wstring& dir, const std::wstring& preferred, int depth = 0) {
if (depth > 4) return std::wstring();
WIN32_FIND_DATAW data{};
HANDLE find = ::FindFirstFileW((dir + L"\\*").c_str(), &data);
if (find == INVALID_HANDLE_VALUE) return std::wstring();
std::wstring fallback;
do {
if (wcscmp(data.cFileName, L".") == 0 || wcscmp(data.cFileName, L"..") == 0) continue;
const std::wstring full = dir + L"\\" + data.cFileName;
if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
const std::wstring nested = FindExeInDir(full, preferred, depth + 1);
if (!nested.empty()) {
::FindClose(find);
return nested;
}
continue;
}
if (!preferred.empty() && _wcsicmp(data.cFileName, preferred.c_str()) == 0) {
::FindClose(find);
return full;
}
if (fallback.empty()) {
const size_t dot = std::wstring(data.cFileName).find_last_of(L'.');
if (dot != std::wstring::npos && _wcsicmp(data.cFileName + dot, L".exe") == 0) {
fallback = full;
}
}
} while (::FindNextFileW(find, &data));
::FindClose(find);
return fallback;
}
bool IsZipFile(const std::wstring& path) {
HANDLE file = ::CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) return false;
char magic[4]{};
DWORD read = 0;
const bool ok = ::ReadFile(file, magic, 4, &read, nullptr) && read == 4;
::CloseHandle(file);
return ok && magic[0] == 'P' && magic[1] == 'K';
}
} // namespace
std::string Update::CurrentVersion() {
const std::wstring path = ExePath();
DWORD dummy = 0;
const DWORD size = ::GetFileVersionInfoSizeW(path.c_str(), &dummy);
if (size == 0) return "1.1.2";
std::vector<char> data(size);
if (!::GetFileVersionInfoW(path.c_str(), 0, size, data.data())) return "1.1.2";
VS_FIXEDFILEINFO* info = nullptr;
UINT len = 0;
if (!::VerQueryValueW(data.data(), L"\\", reinterpret_cast<void**>(&info), &len) || !info) {
return "1.1.2";
}
const DWORD ms = info->dwFileVersionMS;
const DWORD ls = info->dwFileVersionLS;
char text[32]{};
std::snprintf(text, sizeof(text), "%u.%u.%u", HIWORD(ms), LOWORD(ms), HIWORD(ls));
return text;
}
UpdateInfo Update::Check() {
UpdateInfo out;
out.currentVersion = CurrentVersion();
const AuthResult result = Auth::CheckUpdate(out.currentVersion);
if (!result.ok) {
out.error = result.message;
Log::Warn("版本检测失败:" + result.message);
return out;
}
const json& data = result.data;
out.latestVersion = Str(data, "latest_version");
out.notes = Str(data, "update_notes");
out.fileHash = Str(data, "file_hash");
out.entryFile = Str(data, "entry_file");
out.fileSize = Int64(data, "file_size");
out.forced = Str(data, "update_strategy") == "forced";
// 安装器模式会对未登记的版本也返回 has_update=true,这里按版本号再判一次
const auto hasUpdate = data.find("has_update");
if (hasUpdate == data.end() || !hasUpdate->is_boolean() || !hasUpdate->get<bool>()) {
return out;
}
if (out.latestVersion.empty() || LowerAscii(out.latestVersion) == LowerAscii(out.currentVersion)) {
return out;
}
out.downloadUrl = Str(data, "download_url");
if (out.downloadUrl.empty()) out.downloadUrl = Str(data, "full_package_url");
if (out.downloadUrl.empty()) {
out.error = "服务端未提供下载地址";
return out;
}
out.available = true;
Log::Info("发现新版本 " + out.latestVersion + "(当前 " + out.currentVersion + ")");
return out;
}
bool Update::Apply(const UpdateInfo& info, const std::function<void(int)>& progress,
std::string& error) {
if (info.downloadUrl.empty()) {
error = "缺少下载地址";
return false;
}
const std::wstring temp = DataDir() + L"\\update";
if (!EnsureDir(temp)) {
error = "无法创建更新目录:" + WideToUtf8(temp);
return false;
}
// Expand-Archive 只接受 .zip 后缀,所以下载文件固定带 .zip
const std::wstring package = temp + L"\\package.zip";
const std::wstring extractDir = temp + L"\\files";
::DeleteFileW(package.c_str());
const std::string url = Auth::ResolveUrl(info.downloadUrl);
Log::Info("开始下载更新包:" + url);
if (!DownloadFile(url, package, [&progress](int percent) {
if (progress) progress(percent * 70 / 100);
}, error)) {
Log::Error("下载更新包失败:" + error);
return false;
}
if (!info.fileHash.empty()) {
std::string bytes;
if (!ReadWholeFile(package, bytes)) {
error = "读取更新包失败";
return false;
}
const std::string actual = Sha256Hex(bytes);
if (LowerAscii(actual) != LowerAscii(info.fileHash)) {
error = "更新包校验失败(哈希不一致),已放弃更新";
Log::Error(error);
return false;
}
}
if (progress) progress(72);
std::wstring candidate = package;
if (IsZipFile(package)) {
::RemoveDirectoryW(extractDir.c_str());
EnsureDir(extractDir);
if (!ExtractZip(package, extractDir, error)) {
Log::Error(error);
return false;
}
candidate = FindExeInDir(extractDir, FileNameOf(Utf8ToWide(info.entryFile)));
if (candidate.empty()) {
error = "更新包中未找到可执行文件";
return false;
}
}
if (progress) progress(85);
const std::wstring exe = ExePath();
const std::wstring backup = exe + L".old";
::DeleteFileW(backup.c_str());
::SetFileAttributesW(backup.c_str(), FILE_ATTRIBUTE_NORMAL);
if (!::MoveFileExW(exe.c_str(), backup.c_str(), MOVEFILE_REPLACE_EXISTING)) {
error = "无法替换当前程序(文件被占用),请关闭后重试";
Log::Error(error + ",Win32=" + std::to_string(::GetLastError()));
return false;
}
bool placed = ::MoveFileExW(candidate.c_str(), exe.c_str(), MOVEFILE_REPLACE_EXISTING) != FALSE;
if (!placed) placed = ::CopyFileW(candidate.c_str(), exe.c_str(), FALSE) != FALSE;
if (!placed) {
::MoveFileExW(backup.c_str(), exe.c_str(), MOVEFILE_REPLACE_EXISTING);
error = "写入新版本失败,已还原旧版本";
Log::Error(error);
return false;
}
if (progress) progress(100);
STARTUPINFOW si{};
si.cb = sizeof(si);
PROCESS_INFORMATION pi{};
const std::wstring dir = ExeDir();
if (::CreateProcessW(exe.c_str(), nullptr, nullptr, nullptr, FALSE, 0, nullptr, dir.c_str(), &si,
&pi)) {
::CloseHandle(pi.hThread);
::CloseHandle(pi.hProcess);
Log::Info("新版本已就位,正在重启");
::Sleep(300);
::ExitProcess(0);
}
error = "新版本已替换,请手动重新打开程序";
return true;
}
}
+36
View File
@@ -0,0 +1,36 @@
#pragma once
#include <functional>
#include <string>
namespace pddai {
// 版本检测与自动更新:走验证平台的 /check-update,下载完整包后替换自身并重启
struct UpdateInfo {
bool available = false;
bool forced = false;
std::string currentVersion;
std::string latestVersion;
std::string notes;
std::string downloadUrl;
std::string fileHash;
std::string entryFile;
long long fileSize = 0;
std::string error;
};
class Update {
public:
// 当前 exe 的文件版本,格式化为 a.b.c
static std::string CurrentVersion();
// 查询服务端最新版本;网络错误或服务端异常时 available=false 并填 error
static UpdateInfo Check();
// 下载 → 校验 SHA256 → 解压(zip 包)→ 替换 exe → 启动新进程并退出。
// progress 回调传入 0~100 的进度,可能在工作线程中被调用。
static bool Apply(const UpdateInfo& info, const std::function<void(int)>& progress,
std::string& error);
};
}
+85 -11
View File
@@ -1,5 +1,6 @@
#include "Util.h"
#include <mmsystem.h>
#include <shlobj.h>
#include <wincrypt.h>
@@ -8,6 +9,8 @@
#include <string>
#include <vector>
#include "Log.h"
namespace pddai {
std::wstring Utf8ToWide(std::string_view s) {
@@ -235,21 +238,17 @@ std::string Base64Encode(const std::string& bytes) {
}
std::string Base64Decode(const std::string& text) {
static const int table[256] = {
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,0,-1,-1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,-1,-1,-1,-1,-1,-1,-1,12,13,14,15,16,17,18,19,20,21,22,23,
24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,
50,51,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
};
int accum = 0;
int bits = 0;
std::string out;
for (const char c : text) {
const int v = table[static_cast<unsigned char>(c)];
const unsigned char ch = static_cast<unsigned char>(c);
int v = -1;
if (ch >= 'A' && ch <= 'Z') v = ch - 'A';
else if (ch >= 'a' && ch <= 'z') v = ch - 'a' + 26;
else if (ch >= '0' && ch <= '9') v = ch - '0' + 52;
else if (ch == '+') v = 62;
else if (ch == '/') v = 63;
if (v < 0) continue;
accum = (accum << 6) | v;
bits += 6;
@@ -327,4 +326,79 @@ std::string LowerAscii(std::string_view s) {
return out;
}
namespace {
// PlaySound 只认 WAV,其它格式它会「返回成功但不出声」,所以 mp3 等一律走 MCI
bool PlayViaMci(const std::wstring& file, const wchar_t* type) {
constexpr const wchar_t* kAlias = L"pddai_audio";
::mciSendStringW(L"close pddai_audio", nullptr, 0, nullptr);
std::wstring open = L"open \"" + file + L"\"";
if (type && *type) open += std::wstring(L" type ") + type;
open += std::wstring(L" alias ") + kAlias;
MCIERROR status = ::mciSendStringW(open.c_str(), nullptr, 0, nullptr);
if (status != 0) {
wchar_t text[256]{};
::mciGetErrorStringW(status, text, 256);
Log::Error("MCI open 失败: " + WideToUtf8(text));
return false;
}
status = ::mciSendStringW(L"play pddai_audio", nullptr, 0, nullptr);
if (status != 0) {
wchar_t text[256]{};
::mciGetErrorStringW(status, text, 256);
Log::Error("MCI play 失败: " + WideToUtf8(text));
::mciSendStringW(L"close pddai_audio", nullptr, 0, nullptr);
return false;
}
return true;
}
void PlaySystemAlert() {
// 控制面板里系统声音可能被设为「无声」,此时 PlaySound 也毫无声音,补一声蜂鸣兜底
if (!::PlaySoundW(L"SystemExclamation", nullptr, SND_ALIAS | SND_ASYNC)) {
::MessageBeep(MB_ICONWARNING);
}
::Beep(880, 200);
}
} // namespace
void PlayAudioFile(const std::string& path) {
Log::Info("试听/播放提醒声音: " + (path.empty() ? std::string("<未选择,使用系统提示音>") : path));
if (path.empty()) {
PlaySystemAlert();
return;
}
const std::wstring file = Utf8ToWide(path);
if (::GetFileAttributesW(file.c_str()) == INVALID_FILE_ATTRIBUTES) {
Log::Error("音频文件不存在,回落系统提示音");
PlaySystemAlert();
return;
}
// 取扩展名决定播放方式:wav 走 PlaySound,其余按 MCI 解码
std::wstring ext;
const size_t dot = file.find_last_of(L'.');
if (dot != std::wstring::npos) ext = file.substr(dot + 1);
for (wchar_t& c : ext) c = static_cast<wchar_t>(towlower(c));
if (ext == L"wav" &&
::PlaySoundW(file.c_str(), nullptr, SND_FILENAME | SND_ASYNC | SND_NODEFAULT)) {
Log::Info("PlaySound 播放成功");
return;
}
// mp3 必须显式指定 mpegvideo 设备;wma 等先按原样打开,再试 mpegvideo
const wchar_t* type = ext == L"mp3" ? L"mpegvideo" : L"";
if (PlayViaMci(file, type)) {
Log::Info("MCI 播放成功(" + WideToUtf8(ext) + ")");
return;
}
if (ext != L"mp3" && PlayViaMci(file, L"mpegvideo")) {
Log::Info("MCI(mpegvideo) 播放成功(" + WideToUtf8(ext) + ")");
return;
}
Log::Error("PlaySound/MCI 都失败,回落系统提示音");
PlaySystemAlert();
}
}
+3
View File
@@ -42,6 +42,9 @@ std::string Sha256Hex(const std::string& data);
std::string Rfc2822NowUtc();
std::string ComputerNameUtf8();
void SleepMs(int ms);
// 播放本地音频文件(WAV 走 PlaySound,其他格式走 MCI);路径为空或文件无效时播放系统提示音
void PlayAudioFile(const std::string& path);
std::string LowerAscii(std::string_view s);
}
+256 -30
View File
@@ -423,9 +423,22 @@ struct ShopConsole {
ComPtr<ICoreWebView2Environment> env;
ComPtr<ICoreWebView2Controller> controller;
ComPtr<ICoreWebView2> webView;
// 商家后台视图:和客服台共用同一个 Environment(同一 user data folder),
// 但要独立的 Controller 才能在标签里各自保留页面状态
HWND backendHost = nullptr;
ComPtr<ICoreWebView2Controller> backendController;
ComPtr<ICoreWebView2> backendWebView;
bool backendCreating = false;
bool backendPending = false; // 等 Environment 就绪后再建后台视图
// 两个视图各自的当前地址:用来判断谁停在登录页,登录后自动把另一侧刷新成登录态
std::string chatUrl;
std::string backendUrl;
ULONGLONG chatSyncMs = 0;
ULONGLONG backendSyncMs = 0;
bool creating = false;
bool canceled = false;
bool visible = false;
bool backendVisible = false;
double zoom = 1.0;
bool measuring = false;
int measureRound = 0;
@@ -438,6 +451,11 @@ HWND g_owner = nullptr;
std::mutex g_mutex;
std::map<std::string, std::shared_ptr<ShopConsole>> g_consoles;
std::string g_active;
// 当前显示的视图:"chat"(客服台)或 "backend"(商家后台)
std::string g_view = "chat";
// 前置声明:Environment 就绪后可能要立刻建后台视图
void CreateBackendView(const std::shared_ptr<ShopConsole>& console);
RECT g_layout{0, 0, 0, 0};
bool g_layoutVisible = false;
@@ -628,7 +646,8 @@ void MeasureConsole(const std::shared_ptr<ShopConsole>& console) {
// 所以对当前可见的店铺每 5 秒补量一次(隐藏的店铺在屏幕外,不浪费时间扫 DOM)
std::shared_ptr<ShopConsole> ActiveConsole() {
std::lock_guard<std::mutex> lock(g_mutex);
if (!g_layoutVisible || g_active.empty()) return nullptr;
// 只有客服台视图需要测量分栏;后台视图是普通网页,不参与缩放校正
if (!g_layoutVisible || g_active.empty() || g_view != "chat") return nullptr;
const auto it = g_consoles.find(g_active);
return it == g_consoles.end() ? nullptr : it->second;
}
@@ -637,27 +656,39 @@ void CALLBACK MeasureTimerProc(HWND, UINT, UINT_PTR, DWORD) {
MeasureConsole(ActiveConsole());
}
// 摆放几何 + 显隐。隐藏不用 put_IsVisible(FALSE)/SW_HIDE:WebView2 被判定为不可见后
// 会挂起渲染,CDP 的 Input 回调直接不返回,后台店铺的自动回复会全部超时。
// 改成把宿主窗口挪到屏幕外侧,页面始终处于「可见」状态。
// 宿主窗口的摆放:显示时贴到前端上报的内容区,隐藏时挪到屏幕外。
// 隐藏不用 put_IsVisible(FALSE)/SW_HIDE:WebView2 被判定为不可见后会挂起渲染,
// CDP 的 Input 回调直接不返回,后台店铺的自动回复会全部超时。
void PlaceHost(HWND host, const RECT& layout, bool show) {
if (!host || !::IsWindow(host)) return;
const int width = (std::max)(1, static_cast<int>(layout.right - layout.left));
const int height = (std::max)(1, static_cast<int>(layout.bottom - layout.top));
if (show) {
// 主界面的 WebView 会把自己的 HWND 提到最前,每次显示都重新抢一次置顶
::SetWindowPos(host, HWND_TOP, layout.left, layout.top, width, height,
SWP_NOACTIVATE | SWP_SHOWWINDOW);
} else {
::SetWindowPos(host, nullptr, -20000, -20000, width, height,
SWP_NOACTIVATE | SWP_SHOWWINDOW);
}
}
// 摆放几何 + 显隐。同一店铺的客服台与后台视图各有一个宿主窗口,
// 只有「当前店铺 + 当前视图」对应的那个显示,其余都挪到屏幕外。
void ApplyGeometry(const std::shared_ptr<ShopConsole>& console, const RECT& layout,
const std::string& active, bool visible) {
const std::string& active, const std::string& view, bool visible) {
if (!console) return;
const int width = layout.right - layout.left;
const int height = layout.bottom - layout.top;
if (width < 1 || height < 1) return;
const bool show = visible && !active.empty() && console->shopId == active;
if (console->host && ::IsWindow(console->host)) {
if (show) {
// 主界面的 WebView 会把自己的 HWND 提到最前,每次显示都重新抢一次置顶
::SetWindowPos(console->host, HWND_TOP, layout.left, layout.top, width, height,
SWP_NOACTIVATE | SWP_SHOWWINDOW);
} else {
::SetWindowPos(console->host, nullptr, -20000, -20000, width, height,
SWP_NOACTIVATE | SWP_SHOWWINDOW);
}
}
const bool activeShop = visible && !active.empty() && console->shopId == active;
// 后台视图还没建好时先继续显示客服台,避免切过去先白屏
const bool showChat = activeShop && (view != "backend" || !console->backendController);
const bool showBackend = activeShop && !showChat;
PlaceHost(console->host, layout, showChat);
PlaceHost(console->backendHost, layout, showBackend);
if (console->controller) {
// 页面铺满整个宿主区域,不再在右侧留白
const int webWidth = (std::max)(1, width - kRightGutter);
@@ -666,16 +697,16 @@ void ApplyGeometry(const std::shared_ptr<ShopConsole>& console, const RECT& layo
console->controller->put_IsVisible(TRUE);
// 客服页是「会话列表 + 聊天区 + 右侧商品抽屉」三栏,右侧抽屉固定约 460px,
// 聊天区本身也有最小宽度;内容区窄于 1200 时右侧会被挤掉一截,
// 这里按可用宽度等比缩小(窄于 1200 才生效),保证整页都留在可视区。
// 只在尺寸真的变化时才重设缩放:否则会把测量得到的更小缩放值反复顶回去
// 聊天区本身也有最小宽度。实测页面所需最小宽度是 1228 CSS px(不是 1200),
// 这里按 1228 + 8px 余量作为基准,开屏就把缩放算到位;否则初始值会偏大,
// 5 秒一次的测量再缩一档,表现为打开客服台几秒后整页突然「抖动」一下。
const bool resized = console->lastW != width || console->lastH != height;
if (resized) {
console->lastW = width;
console->lastH = height;
console->measureRound = 0; // 尺寸变了才重新给满校正次数
// 基准按实际可见宽度算,留白不参与排版,页面 CSS 视口仍是 1200
const double target = (std::min)(1.0, static_cast<double>(webWidth) / 1200.0);
// 基准按实际可见宽度算,留白不参与排版
const double target = (std::min)(1.0, static_cast<double>(webWidth) / 1236.0);
if (std::fabs(target - console->zoom) > 0.004) {
console->zoom = target;
console->controller->put_ZoomFactor(target);
@@ -685,25 +716,37 @@ void ApplyGeometry(const std::shared_ptr<ShopConsole>& console, const RECT& layo
}
}
if (console->backendController) {
RECT bounds{0, 0, (std::max)(1, width), height};
console->backendController->put_Bounds(bounds);
console->backendController->put_IsVisible(TRUE);
}
// 从后台切回前台时把键盘焦点交给它,否则上一次会话的焦点可能还留在被挪走的页面里
if (show && !console->visible && console->controller) {
if (showChat && !console->visible && console->controller) {
console->controller->MoveFocus(COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC);
}
console->visible = show;
if (showBackend && !console->backendVisible && console->backendController) {
console->backendController->MoveFocus(COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC);
}
console->visible = showChat;
console->backendVisible = showBackend;
}
// 在 UI 线程按当前布局刷新一个店铺的几何与可见性(快照从锁里取,COM 调用不放锁)
void ApplyConsoleState(const std::shared_ptr<ShopConsole>& console) {
RECT layout{};
std::string active;
std::string view;
bool visible = false;
{
std::lock_guard<std::mutex> lock(g_mutex);
layout = g_layout;
active = g_active;
view = g_view;
visible = g_layoutVisible;
}
ApplyGeometry(console, layout, active, visible);
ApplyGeometry(console, layout, active, view, visible);
}
std::shared_ptr<ShopConsole> FindConsole(const std::string& shopId) {
@@ -712,19 +755,90 @@ std::shared_ptr<ShopConsole> FindConsole(const std::string& shopId) {
return it == g_consoles.end() ? nullptr : it->second;
}
// 拼多多客服台和商家后台都在 mms.pinduoduo.com,登录后会离开 /login。
// 两个视图共用同一配置目录,cookie 本来就是同步的;差别只是「登录前就已打开的页面」
// 会一直停在旧的登录页,看上去像没同步。切过去时刷新一次即可复用登录态,不必再扫码。
bool IsLoginUrl(const std::string& url) {
return url.find("/login") != std::string::npos;
}
// 客服台里的商品卡片、广告位常用 window.open 打开链接,WebView2 默认把它丢给系统浏览器。
// 那些是手机版商品页(mobile.yangkeduo.com),需要手机号登录,和商家后台的登录态不通用,
// 于是会频繁弹出登录页。内嵌台不需要新窗口,统一拦掉。
void BlockNewWindows(ICoreWebView2* view) {
if (!view) return;
view->add_NewWindowRequested(
Callback<ICoreWebView2NewWindowRequestedEventHandler>(
[](ICoreWebView2*, ICoreWebView2NewWindowRequestedEventArgs* args) -> HRESULT {
if (!args) return S_OK;
args->put_Handled(TRUE);
return S_OK;
})
.Get(),
nullptr);
}
// 记录每个视图当前地址,用于判断哪一侧还停在登录页
void TrackViewUrl(const std::shared_ptr<ShopConsole>& console, ICoreWebView2* view, bool backend) {
if (!view) return;
BlockNewWindows(view);
view->add_NavigationStarting(
Callback<ICoreWebView2NavigationStartingEventHandler>(
[console, backend](ICoreWebView2*,
ICoreWebView2NavigationStartingEventArgs* args) -> HRESULT {
if (!args) return S_OK;
LPWSTR uri = nullptr;
if (SUCCEEDED(args->get_Uri(&uri)) && uri) {
const std::string url = WideToUtf8(uri);
::CoTaskMemFree(uri);
if (backend) console->backendUrl = url;
else console->chatUrl = url;
}
return S_OK;
})
.Get(),
nullptr);
}
// 切到某个视图时调用:它停在登录页、另一侧已经登录,就刷新它
void SyncLoginState(const std::shared_ptr<ShopConsole>& console) {
if (!console) return;
const ULONGLONG now = static_cast<ULONGLONG>(::GetTickCount64());
const bool chatLogin = IsLoginUrl(console->chatUrl);
const bool backendLogin = IsLoginUrl(console->backendUrl);
if (chatLogin && !console->backendUrl.empty() && !backendLogin && console->webView) {
if (now - console->chatSyncMs < 4000) return; // 防止和页面自身跳转互相触发
console->chatSyncMs = now;
console->webView->Reload();
Log::Info("[内嵌台] 店铺 " + console->shopId + " 的商家后台已登录,刷新客服台同步登录态");
} else if (backendLogin && !console->chatUrl.empty() && !chatLogin && console->backendWebView) {
if (now - console->backendSyncMs < 4000) return;
console->backendSyncMs = now;
console->backendWebView->Reload();
Log::Info("[内嵌台] 店铺 " + console->shopId + " 的客服台已登录,刷新商家后台同步登录态");
}
}
void MarkFailed(const std::shared_ptr<ShopConsole>& console) {
HWND host = nullptr;
HWND backendHost = nullptr;
{
std::lock_guard<std::mutex> lock(g_mutex);
console->creating = false;
const auto it = g_consoles.find(console->shopId);
if (it != g_consoles.end() && it->second == console) {
if (g_active == console->shopId) g_active.clear();
if (g_active == console->shopId) {
g_active.clear();
g_view = "chat";
}
g_consoles.erase(it);
}
host = console->host;
console->host = nullptr;
backendHost = console->backendHost;
console->backendHost = nullptr;
}
if (backendHost && ::IsWindow(backendHost)) ::DestroyWindow(backendHost);
if (host && ::IsWindow(host)) ::DestroyWindow(host);
}
@@ -1006,6 +1120,10 @@ void StartConsole(HWND owner, const std::shared_ptr<ShopConsole>& console) {
return S_OK;
}
console->env = env;
if (console->backendPending) {
console->backendPending = false;
CreateBackendView(console);
}
if (!console->host || !::IsWindow(console->host)) {
MarkFailed(console);
return S_OK;
@@ -1039,6 +1157,8 @@ void StartConsole(HWND owner, const std::shared_ptr<ShopConsole>& console) {
if (SUCCEEDED(console->webView->get_Settings(&settings)) && settings) {
settings->put_IsStatusBarEnabled(FALSE);
}
// 记录当前地址:登录后靠它判断另一侧是否还停在登录页
TrackViewUrl(console, console->webView.Get(), false);
// 通知权限一律静默拒绝:否则 WebView2 会弹「是否允许发送通知」的
// 浏览器提示框,和页面自己的「浏览器未开启通知」引导框一起挡消息区。
@@ -1089,6 +1209,83 @@ void StartConsole(HWND owner, const std::shared_ptr<ShopConsole>& console) {
.Get());
}
// ---------------- 商家后台视图(与客服台共用同一 Environment) ----------------
// 同一店铺的客服台和后台视图共用一个 ICoreWebView2Environment,也就是同一个 user data
// folder,所以 cookie、localStorage 天然共享:客服台登录过,后台标签打开就是登录态。
// 一个 Environment 可以创建多个 Controller,所以两个视图各自保留页面状态,切回来不刷新。
std::string BackendUrl() {
std::string url;
try {
const json server = Config::GetJson("server.json", json::object());
url = Trim(server.value("pddBackendUrl", std::string()));
} catch (const std::exception&) {
url.clear();
}
return url.empty() ? std::string("https://mms.pinduoduo.com/") : url;
}
// 懒创建:第一次切到该店铺的后台标签时才建 Controller 并加载后台页面
void CreateBackendView(const std::shared_ptr<ShopConsole>& console) {
if (!console || !console->env || console->backendCreating) return;
if (console->backendController) {
ApplyConsoleState(console);
return;
}
if (!console->backendHost || !::IsWindow(console->backendHost)) {
console->backendHost = CreateHost(g_owner);
}
if (!console->backendHost) {
Log::Error("[内嵌台] 店铺 " + console->shopId + " 的后台视图宿主窗口创建失败");
return;
}
console->backendCreating = true;
console->env->CreateCoreWebView2Controller(
console->backendHost,
Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(
[console](HRESULT r, ICoreWebView2Controller* controller) -> HRESULT {
console->backendCreating = false;
if (FAILED(r) || !controller) {
Log::Error("[内嵌台] 店铺 " + console->shopId + " 的后台视图创建失败");
return S_OK;
}
console->backendController = controller;
controller->get_CoreWebView2(&console->backendWebView);
ComPtr<ICoreWebView2Controller2> c2;
if (SUCCEEDED(console->backendController.As(&c2)) && c2) {
COREWEBVIEW2_COLOR bg{255, 255, 255, 255};
c2->put_DefaultBackgroundColor(bg);
}
if (console->backendWebView) {
TrackViewUrl(console, console->backendWebView.Get(), true);
ComPtr<ICoreWebView2Settings> settings;
if (SUCCEEDED(console->backendWebView->get_Settings(&settings)) && settings) {
settings->put_IsStatusBarEnabled(FALSE);
}
// 与客服台保持同一套 stealth 补丁,避免同一账号在两处露出不同的 WebView2 指纹
std::string script = kPatchScript;
const std::string stealth = LoadTextResource(IDR_INJECT_STEALTH_JS);
if (!stealth.empty()) script = stealth + "\n" + script;
script += "\n";
console->backendWebView->AddScriptToExecuteOnDocumentCreated(
Utf8ToWide(script).c_str(), nullptr);
const std::wstring url = Utf8ToWide(BackendUrl());
console->backendWebView->Navigate(url.c_str());
}
controller->put_IsVisible(TRUE);
ApplyConsoleState(console);
Log::Info("[内嵌台] 店铺 " + console->shopId + " 的后台视图已打开");
return S_OK;
})
.Get());
}
// ---------------- 真实输入:HTTP 线程封送到 UI 线程 ----------------
int RandomInt(int min, int max) {
@@ -1325,7 +1522,7 @@ void ExecuteInput(const json& payload, const std::shared_ptr<InputRequest>& requ
} // namespace
bool WebConsole::Open(HWND owner, const std::string& shopId) {
bool WebConsole::Open(HWND owner, const std::string& shopId, const std::string& view) {
if (!owner || !::IsWindow(owner)) {
Log::Error("[内嵌台] 主窗口无效,无法打开");
return false;
@@ -1343,13 +1540,16 @@ bool WebConsole::Open(HWND owner, const std::string& shopId) {
return false;
}
const bool wantBackend = view == "backend";
std::shared_ptr<ShopConsole> console;
bool create = false;
bool backendReady = false;
std::vector<std::shared_ptr<ShopConsole>> all;
{
std::lock_guard<std::mutex> lock(g_mutex);
g_owner = owner;
g_active = id;
g_view = wantBackend ? "backend" : "chat";
const auto it = g_consoles.find(id);
if (it != g_consoles.end()) {
console = it->second;
@@ -1360,6 +1560,11 @@ bool WebConsole::Open(HWND owner, const std::string& shopId) {
g_consoles[id] = console;
create = true;
}
// 后台视图要等这个店铺的 Environment 就绪;已经有了就直接建
if (wantBackend && !create && !console->backendController) {
if (console->env) backendReady = true;
else console->backendPending = true;
}
for (const auto& pair : g_consoles) all.push_back(pair.second);
}
@@ -1374,8 +1579,14 @@ bool WebConsole::Open(HWND owner, const std::string& shopId) {
::SetTimer(nullptr, 1, 5000, MeasureTimerProc);
timerStarted = true;
}
if (wantBackend) {
if (backendReady) CreateBackendView(console); // 已就绪,直接建/显示后台视图
else if (create) { /* Environment 就绪后由 StartConsole 回调接手 */ }
}
// 先隐藏其它店铺,再把当前店铺的几何与可见性刷新一遍
for (const auto& item : all) ApplyConsoleState(item);
// 切过来时如果这一侧还停在登录页、另一侧已经登录,刷新一次拿到共享的登录态
SyncLoginState(console);
return true;
}
@@ -1419,8 +1630,10 @@ bool WebConsole::Logout(const std::string& shopId) {
[console](HRESULT errorCode) -> HRESULT {
if (FAILED(errorCode)) {
Log::Error("[内嵌台] 清除登录数据失败");
} else if (console->webView) {
console->webView->Reload();
} else {
// 两个视图共用同一配置目录,清完后都回到未登录状态
if (console->webView) console->webView->Reload();
if (console->backendWebView) console->backendWebView->Reload();
Log::Info("[内嵌台] 已清除登录数据,页面重新加载");
}
return S_OK;
@@ -1437,24 +1650,35 @@ bool WebConsole::Logout(const std::string& shopId) {
void WebConsole::Close(const std::string& shopId) {
std::shared_ptr<ShopConsole> console;
HWND host = nullptr;
HWND backendHost = nullptr;
{
std::lock_guard<std::mutex> lock(g_mutex);
const auto it = g_consoles.find(shopId);
if (it == g_consoles.end()) return;
console = it->second;
g_consoles.erase(it);
if (g_active == shopId) g_active.clear();
if (g_active == shopId) {
g_active.clear();
g_view = "chat";
}
host = console->host;
console->host = nullptr;
backendHost = console->backendHost;
console->backendHost = nullptr;
}
console->canceled = true;
// 后台视图和客服台共用配置目录,关店铺时一起销毁,避免留下孤立的 WebView2
if (console->backendController) console->backendController->Close();
console->backendController.Reset();
console->backendWebView.Reset();
if (console->controller) {
console->controller->put_IsVisible(FALSE);
console->controller->Close();
}
console->controller.Reset();
console->webView.Reset();
if (backendHost && ::IsWindow(backendHost)) ::DestroyWindow(backendHost);
if (host && ::IsWindow(host)) ::DestroyWindow(host);
Log::Info("[内嵌台] 已关闭店铺 " + shopId);
}
@@ -1482,6 +1706,7 @@ std::vector<std::string> WebConsole::OpenShopIds() {
void WebConsole::SetLayout(const RECT& rect, bool visible) {
std::vector<std::shared_ptr<ShopConsole>> all;
std::string active;
std::string view;
bool show = false;
RECT layout{};
{
@@ -1496,10 +1721,11 @@ void WebConsole::SetLayout(const RECT& rect, bool visible) {
}
layout = g_layout;
active = g_active;
view = g_view;
show = g_layoutVisible && layout.right > layout.left && layout.bottom > layout.top;
for (const auto& pair : g_consoles) all.push_back(pair.second);
}
for (const auto& console : all) ApplyGeometry(console, layout, active, show);
for (const auto& console : all) ApplyGeometry(console, layout, active, view, show);
}
bool WebConsole::DispatchInput(const json& payload, std::string& error) {
+4 -2
View File
@@ -18,8 +18,10 @@ namespace pddai {
class WebConsole {
public:
// 打开并切换到该店铺的内嵌台;首次调用时异步创建 Environment 与 Controller。
// shopId 为空时取 shops.json 里的第一个店铺。
static bool Open(HWND owner, const std::string& shopId);
// view = "chat" 显示客服台,view = "backend" 显示商家后台(共用同一 Environment,
// 因此 cookie / 登录态天然共享)。shopId 为空时取 shops.json 里的第一个店铺。
static bool Open(HWND owner, const std::string& shopId,
const std::string& view = std::string("chat"));
// 销毁某个店铺的 Controller 并释放它的配置目录占用
static void Close(const std::string& shopId);
+761 -24
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -13,6 +13,7 @@
#define WM_APP_LOG (WM_APP + 3)
#define WM_APP_POSTJSON (WM_APP + 4)
#define WM_APP_CONSOLE_INPUT (WM_APP + 5)
#define WM_APP_AUTH (WM_APP + 6)
#define IDC_TRAY_OPEN 2001
#define IDC_TRAY_PAUSE 2002
+921 -137
View File
File diff suppressed because it is too large Load Diff
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB