Files
verify/shell/duilib/shell9_v6.cpp
T

1942 lines
86 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// shell9.cpp —— DuiLib 版 Windows 验证壳(多套结构不同的皮肤)
//
// 与平台验证方式严格对齐(/api/v1/app/<appKey>/login):
// POST {username, password, device_id, device_name, device_type, instance_id}
// 即「账号(或卡密)+ 密码 + 设备绑定」,不是只填一个卡密框。
//
// 对外接口不变:
// int VerifyMain(void *oep, const char *cfgjson);
// int VerifyShellVersion(void); // 9
// const char *VerifyShellThemes(void); // 主题清单
#include <windows.h>
#include <winhttp.h>
#include <shlobj.h>
#include <shellapi.h>
#include <bcrypt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include "UIlib.h"
#include "Utils/WinImplBase.h"
#pragma comment(lib, "winhttp.lib")
using namespace DuiLib;
/* ============================== cfg ============================== */
static char g_cfg[4096];
static char g_api[512];
static char g_name[128] = "\xE6\xBC\x94\xE7\xA4\xBA\xE7\xA8\x8B\xE5\xBA\x8F"; // 演示程序
static char g_theme[32] = "dark";
static char g_device[64] = "";
static char g_instance[64] = "";
static int g_deviceAuto = 1;
static int g_codeLeft = 0; // 验证码倒计时(秒)
static char g_ver[32] = ""; // 目标程序版本(cfg.ver),空则不做更新比对
static char g_appkey[64] = ""; // 从 api 地址里抽出来的 appKey
static char g_user[128] = ""; // 本次登录用的账号/口令,解绑设备要复用
static char g_pass[128] = "";
static char g_lastResp[8192] = ""; // 上一次 /login 原始响应(设备超限时里面带设备列表)
static int g_overlay = 0; // 0=正常 1=公告 2=更新 3=设备
static int g_devManage = 0; // 1 = 设备面板处于「我的设备」自助模式
struct DevItem { char id[64]; char name[64]; char created[32]; int online; };
static DevItem g_devs[16];
static int g_devCount = 0, g_devMax = 0;
static int g_selIdx = 0; // 设备页手动选中的那台(1 起;0=未选)
struct Notice { int id; char title[128]; char body[1024]; };
static Notice g_notices[8];
static int g_noticeCount = 0, g_noticeIdx = 0;
static char g_updateUrl[768] = "";
static long g_updateVersionId = 0;
static int g_updateForced = 0;
static int json_str(const char *src, const char *key, char *out, int cap) {
char pat[64]; snprintf(pat, sizeof(pat), "\"%s\"", key);
const char *p = strstr(src, pat);
if (!p) return 0;
p = strchr(p + strlen(pat), ':');
if (!p) return 0;
while (*p && *p != '"') p++;
if (!*p) return 0;
p++;
int i = 0;
while (*p && *p != '"' && i < cap - 1) out[i++] = *p++;
out[i] = 0;
return 1;
}
static int json_bool(const char *src, const char *key, int def) {
char pat[128];
snprintf(pat, sizeof(pat), "\"%s\"", key);
const char *p = strstr(src, pat);
if (!p) return def;
p = strchr(p + strlen(pat), ':');
if (!p) return def;
p++;
while (*p == ' ' || *p == '\t') p++;
if (!strncmp(p, "true", 4)) return 1;
if (!strncmp(p, "false", 5)) return 0;
return atoi(p) ? 1 : 0;
}
static int json_int(const char *src, const char *key, int def) {
char pat[64]; snprintf(pat, sizeof(pat), "\"%s\"", key);
const char *p = strstr(src, pat);
if (!p) return def;
p = strchr(p + strlen(pat), ':');
if (!p) return def;
return atoi(p + 1);
}
// 后台开关:从 /info 拉下来的界面配置
static int g_allowRegister = 1, g_regVerify = 0, g_allowReset = 0;
static char g_loginMode[16] = "account"; // account / card / both
static int g_maxDevices = 1, g_trialDays = 0, g_enableTrial = 0;
static char g_resetMethod[16] = "email", g_billing[16] = "free";
static int g_infoLoaded = 0;
// 把 JSON 里的 \n 转义还原成真换行(更新说明、变更日志都要用)
static void unescape_nl(char *p) {
char *w = p;
while (*p) {
if (p[0] == '\\' && p[1] == 'n') { *w++ = '\n'; p += 2; }
else if (p[0] == '\\' && p[1] == 'r') { p += 2; }
else if (p[0] == '\\' && p[1] == 't') { *w++ = ' '; p += 2; }
else if (p[0] == '\\' && p[1]) { *w++ = p[1]; p += 2; }
else *w++ = *p++;
}
*w = 0;
}
static void make_machine_id(char *out, int cap);
static void load_cfg(const char *json);
/* ============================ 工具 ============================ */
static std::wstring U8(const char *s) {
if (!s) return L"";
int n = ::MultiByteToWideChar(CP_UTF8, 0, s, -1, NULL, 0);
std::wstring w(n > 0 ? n - 1 : 0, L'\0');
if (n > 1) ::MultiByteToWideChar(CP_UTF8, 0, s, -1, &w[0], n);
return w;
}
static std::string W2U8(const std::wstring &w) {
if (w.empty()) return std::string();
int n = ::WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, NULL, 0, NULL, NULL);
std::string s(n > 0 ? n - 1 : 0, '\0');
if (n > 1) ::WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, &s[0], n, NULL, NULL);
return s;
}
// MachineGuid + 系统盘卷序列号 → 稳定机器码(重装系统才变)
static void make_machine_id(char *out, int cap) {
wchar_t guid[128] = {0};
HKEY hk = NULL;
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Cryptography",
0, KEY_READ | KEY_WOW64_64KEY, &hk) == ERROR_SUCCESS) {
DWORD sz = sizeof(guid) - sizeof(wchar_t), type = 0;
RegQueryValueExW(hk, L"MachineGuid", NULL, &type, (LPBYTE)guid, &sz);
RegCloseKey(hk);
}
DWORD serial = 0;
GetVolumeInformationW(L"C:\\", NULL, 0, &serial, NULL, NULL, NULL, 0);
unsigned int h1 = 2166136261u, h2 = 3735928559u;
for (const wchar_t *p = guid; *p; p++) {
h1 = (h1 ^ (unsigned int)(*p & 0xFF)) * 16777619u;
h2 = (h2 ^ (unsigned int)(*p >> 8)) * 16777619u;
}
h1 = (h1 ^ serial) * 16777619u;
h2 = (h2 ^ (serial >> 16)) * 16777619u;
snprintf(out, cap, "%04X-%04X-%04X", h1 & 0xFFFF, (h1 >> 16) & 0xFFFF, h2 & 0xFFFF);
}
static std::wstring AccountIniPath() {
wchar_t app[MAX_PATH] = {0};
::SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, 0, app);
std::wstring dir = std::wstring(app) + L"\\vfy";
::CreateDirectoryW(dir.c_str(), NULL);
return dir + L"\\account.ini";
}
static void SaveAccount(const std::wstring &user, bool remember) {
std::wstring p = AccountIniPath();
::WritePrivateProfileStringW(L"login", L"remember", remember ? L"1" : L"0", p.c_str());
if (remember) ::WritePrivateProfileStringW(L"login", L"user", user.c_str(), p.c_str());
}
static std::wstring LoadAccount(bool &remember) {
std::wstring p = AccountIniPath();
wchar_t buf[256] = {0};
::GetPrivateProfileStringW(L"login", L"remember", L"0", buf, 256, p.c_str());
remember = (buf[0] == L'1');
wchar_t user[256] = {0};
::GetPrivateProfileStringW(L"login", L"user", L"", user, 256, p.c_str());
return remember ? std::wstring(user) : std::wstring();
}
/* --------------------------- 皮肤 ---------------------------
* 7 套在「结构」上彼此不同,字段集统一按平台验证方式:
* 账号(账号或卡密)/ 密码 / 记住账号 / 设备信息 / 登录 / 状态行 / 注册·卡密充值·忘记密码
* 注意:老 DuiLib 的 Edit 是「真 EDIT 子窗口」,必须用 nativebkcolor 指定它自己的底色,
* 否则聚焦时会出现刺眼的白条(这是它构造里写死 0xFFFFFFFF 导致的)。
*/
#include "skins_v4.h"
// 每套皮肤的强调色:输入框聚焦时用它描 1px 边
static DWORD theme_accent(const char *theme) {
if (!strcmp(theme, "light")) return 0xFF1B6FD6;
if (!strcmp(theme, "split")) return 0xFF4CC2FF;
if (!strcmp(theme, "card")) return 0xFF3B2BD6;
if (!strcmp(theme, "industrial")) return 0xFF1FA0E0;
if (!strcmp(theme, "terminal")) return 0xFF7FE39B;
if (!strcmp(theme, "compact")) return 0xFF2E9E6B;
return 0xFF4EA3E8; // dark / classic
}
static const SkinDef *skin_for(const char *theme) {
for (int i = 0; kSkins[i].name; i++)
if (!strcmp(theme, kSkins[i].name)) return &kSkins[i];
return &kSkins[0];
}
/* ---------------------------- 接口请求 ---------------------------- */
// 平台接口:POST /api/v1/app/<appKey>/login
// {"username","password","device_id","device_name","device_type","instance_id"}
static int api_login(const char *user, const char *pass, char *msg, int cap) {
msg[0] = 0;
if (!g_api[0]) { snprintf(msg, cap, "配置缺少验证地址"); return 0; }
const char *rest = g_api;
if (!strncmp(g_api, "https://", 8)) rest = g_api + 8;
else if (!strncmp(g_api, "http://", 7)) rest = g_api + 7;
bool https = (rest != g_api && g_api[4] == 's');
char host[256] = {0}, path[512] = "/";
const char *slash = strchr(rest, '/');
if (slash) {
int hl = (int)(slash - rest);
if (hl > 255) hl = 255;
memcpy(host, rest, hl);
snprintf(path, sizeof(path), "%s", slash);
} else {
snprintf(host, sizeof(host), "%s", rest);
}
unsigned short port = https ? 443 : 80;
char *colon = strrchr(host, ':');
if (colon) { *colon = 0; port = (unsigned short)atoi(colon + 1); }
char cname[256] = {0}; DWORD cn = sizeof(cname);
::GetComputerNameA(cname, &cn);
char body[2048];
if (!strcmp(g_loginMode, "card")) {
snprintf(body, sizeof(body),
"{\"login_type\":\"card\",\"card_key\":\"%s\",\"device_id\":\"%s\","
"\"device_name\":\"%s\",\"device_type\":\"windows\",\"instance_id\":\"%s\"}",
user, g_device, cname, g_instance);
} else {
// both = 密码留空就按卡密走,由服务端定(壳不猜格式)
const char *ltype = strcmp(g_loginMode, "both") ? "account" : "auto";
snprintf(body, sizeof(body),
"{\"login_type\":\"%s\",\"username\":\"%s\",\"password\":\"%s\",\"device_id\":\"%s\","
"\"device_name\":\"%s\",\"device_type\":\"windows\",\"instance_id\":\"%s\"}",
ltype, user, pass, g_device, cname, g_instance);
}
std::wstring wHost = U8(host), wPath = U8(path);
HINTERNET hS = WinHttpOpen(L"vfy/9.0", WINHTTP_ACCESS_TYPE_NO_PROXY, NULL, NULL, 0);
if (!hS) { snprintf(msg, cap, "网络初始化失败"); return 0; }
HINTERNET hC = WinHttpConnect(hS, wHost.c_str(), port, 0);
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"POST", wPath.c_str(), NULL, NULL, NULL, 0) : NULL;
int ok = 0;
if (hR) {
WinHttpSendRequest(hR, L"Content-Type: application/json\r\n", (DWORD)-1,
(LPVOID)body, (DWORD)strlen(body), (DWORD)strlen(body), 0);
WinHttpReceiveResponse(hR, NULL);
char resp[4096] = {0};
DWORD cl = 0, total = 0;
while (WinHttpReadData(hR, resp + total, sizeof(resp) - 1 - total, &cl) && cl > 0) {
total += cl;
if (total >= sizeof(resp) - 1) break;
}
resp[total] = 0;
// 设备超限的 403 里带整份设备列表,留给「设备已满」页展示与解绑
snprintf(g_lastResp, sizeof(g_lastResp), "%s", resp);
if (strstr(resp, "\"code\":0") || strstr(resp, "\"code\":200") || strstr(resp, "\"success\":true")) ok = 1;
if (!json_str(resp, "message", msg, cap) || !msg[0]) {
if (strstr(resp, "DEVICE_LIMIT")) snprintf(msg, cap, "设备数量已达上限,请先在平台解绑一台设备");
else if (strstr(resp, "IP_LIMIT")) snprintf(msg, cap, "IP 绑定已达上限,请解绑后再试");
else if (ok) snprintf(msg, cap, "登录成功");
else snprintf(msg, cap, "账号或密码错误");
}
} else {
snprintf(msg, cap, "无法连接验证服务器");
}
if (hR) WinHttpCloseHandle(hR);
if (hC) WinHttpCloseHandle(hC);
WinHttpCloseHandle(hS);
return ok;
}
// 注册:POST /api/v1/app/<appKey>/register
static int api_register(const char *user, const char *email, const char *code,
const char *pass, char *msg, int cap) {
msg[0] = 0;
if (!g_api[0]) { snprintf(msg, cap, "配置缺少验证地址"); return 0; }
std::string reg = g_api;
size_t pos = reg.rfind("/login");
if (pos != std::string::npos) reg = reg.substr(0, pos) + "/register";
const char *rest = reg.c_str();
bool https = false;
if (!strncmp(rest, "https://", 8)) { rest += 8; https = true; }
else if (!strncmp(rest, "http://", 7)) rest += 7;
char host[256] = {0}, path[512] = "/";
const char *slash = strchr(rest, '/');
if (slash) { int hl = (int)(slash - rest); if (hl > 255) hl = 255; memcpy(host, rest, hl); snprintf(path, sizeof(path), "%s", slash); }
else snprintf(host, sizeof(host), "%s", rest);
unsigned short port = https ? 443 : 80;
char *colon = strrchr(host, ':');
if (colon) { *colon = 0; port = (unsigned short)atoi(colon + 1); }
char cname[256] = {0}; DWORD cn = sizeof(cname);
::GetComputerNameA(cname, &cn);
char body[2048];
snprintf(body, sizeof(body),
"{\"username\":\"%s\",\"email\":\"%s\",\"email_code\":\"%s\",\"password\":\"%s\","
"\"device_id\":\"%s\",\"device_name\":\"%s\",\"device_type\":\"windows\",\"instance_id\":\"%s\"}",
user, email, code, pass, g_device, cname, g_instance);
std::wstring wHost = U8(host), wPath = U8(path);
HINTERNET hS = WinHttpOpen(L"vfy/9.0", WINHTTP_ACCESS_TYPE_NO_PROXY, NULL, NULL, 0);
if (!hS) { snprintf(msg, cap, "网络初始化失败"); return 0; }
HINTERNET hC = WinHttpConnect(hS, wHost.c_str(), port, 0);
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"POST", wPath.c_str(), NULL, NULL, NULL, 0) : NULL;
int ok = 0;
if (hR) {
WinHttpSendRequest(hR, L"Content-Type: application/json\r\n", (DWORD)-1,
(LPVOID)body, (DWORD)strlen(body), (DWORD)strlen(body), 0);
WinHttpReceiveResponse(hR, NULL);
char resp[4096] = {0}; DWORD cl = 0, total = 0;
while (WinHttpReadData(hR, resp + total, sizeof(resp) - 1 - total, &cl) && cl > 0) {
total += cl; if (total >= sizeof(resp) - 1) break;
}
resp[total] = 0;
if (strstr(resp, "\"code\":0") || strstr(resp, "\"code\":200") || strstr(resp, "\"success\":true")) ok = 1;
if (!json_str(resp, "message", msg, cap) || !msg[0])
snprintf(msg, cap, ok ? "注册成功,正在登录…" : "注册失败,请检查邮箱验证码");
} else {
snprintf(msg, cap, "无法连接验证服务器");
}
if (hR) WinHttpCloseHandle(hR);
if (hC) WinHttpCloseHandle(hC);
WinHttpCloseHandle(hS);
return ok;
}
// 发送邮箱验证码:POST /api/v1/app/<appKey>/send-email-code
static int api_send_code(const char *email, const char *purpose, char *msg, int cap) {
msg[0] = 0;
std::string u = g_api;
size_t pos = u.rfind("/login");
if (pos != std::string::npos) u = u.substr(0, pos) + "/send-email-code";
const char *rest = u.c_str();
bool https = false;
if (!strncmp(rest, "https://", 8)) { rest += 8; https = true; }
else if (!strncmp(rest, "http://", 7)) rest += 7;
char host[256] = {0}, path[512] = "/";
const char *slash = strchr(rest, '/');
if (slash) { int hl = (int)(slash - rest); if (hl > 255) hl = 255; memcpy(host, rest, hl); snprintf(path, sizeof(path), "%s", slash); }
else snprintf(host, sizeof(host), "%s", rest);
unsigned short port = https ? 443 : 80;
char *colon = strrchr(host, ':');
if (colon) { *colon = 0; port = (unsigned short)atoi(colon + 1); }
char body[512];
snprintf(body, sizeof(body), "{\"email\":\"%s\",\"purpose\":\"%s\"}", email, purpose);
std::wstring wHost = U8(host), wPath = U8(path);
HINTERNET hS = WinHttpOpen(L"vfy/9.0", WINHTTP_ACCESS_TYPE_NO_PROXY, NULL, NULL, 0);
if (!hS) { snprintf(msg, cap, "网络初始化失败"); return 0; }
HINTERNET hC = WinHttpConnect(hS, wHost.c_str(), port, 0);
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"POST", wPath.c_str(), NULL, NULL, NULL, 0) : NULL;
int ok = 0;
if (hR) {
WinHttpSendRequest(hR, L"Content-Type: application/json\r\n", (DWORD)-1,
(LPVOID)body, (DWORD)strlen(body), (DWORD)strlen(body), 0);
WinHttpReceiveResponse(hR, NULL);
char resp[2048] = {0}; DWORD cl = 0;
WinHttpReadData(hR, resp, sizeof(resp) - 1, &cl);
resp[cl < sizeof(resp) ? cl : sizeof(resp) - 1] = 0;
if (strstr(resp, "\"code\":0") || strstr(resp, "\"code\":200") || strstr(resp, "\"success\":true")) ok = 1;
if (!json_str(resp, "message", msg, cap) || !msg[0])
snprintf(msg, cap, ok ? "验证码已发送" : "发送失败");
} else {
snprintf(msg, cap, "无法连接验证服务器");
}
if (hR) WinHttpCloseHandle(hR);
if (hC) WinHttpCloseHandle(hC);
WinHttpCloseHandle(hS);
return ok;
}
// 通用 POST:把 JSON 发到 api 的某个兄弟路径(/login → /recharge 之类)
static int api_post_sibling(const char *sibling, const char *body, char *msg, int cap) {
msg[0] = 0;
std::string u = g_api;
size_t pos = u.rfind("/login");
if (pos != std::string::npos) u = u.substr(0, pos) + sibling;
const char *rest = u.c_str();
bool https = false;
if (!strncmp(rest, "https://", 8)) { rest += 8; https = true; }
else if (!strncmp(rest, "http://", 7)) rest += 7;
char host[256] = {0}, path[512] = "/";
const char *slash = strchr(rest, '/');
if (slash) { int hl = (int)(slash - rest); if (hl > 255) hl = 255; memcpy(host, rest, hl); snprintf(path, sizeof(path), "%s", slash); }
else snprintf(host, sizeof(host), "%s", rest);
unsigned short port = https ? 443 : 80;
char *colon = strrchr(host, ':');
if (colon) { *colon = 0; port = (unsigned short)atoi(colon + 1); }
std::wstring wHost = U8(host), wPath = U8(path);
HINTERNET hS = WinHttpOpen(L"vfy/9.0", WINHTTP_ACCESS_TYPE_NO_PROXY, NULL, NULL, 0);
if (!hS) { snprintf(msg, cap, "网络初始化失败"); return 0; }
HINTERNET hC = WinHttpConnect(hS, wHost.c_str(), port, 0);
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"POST", wPath.c_str(), NULL, NULL, NULL, 0) : NULL;
int ok = 0;
if (hR) {
WinHttpSendRequest(hR, L"Content-Type: application/json\r\n", (DWORD)-1,
(LPVOID)body, (DWORD)strlen(body), (DWORD)strlen(body), 0);
WinHttpReceiveResponse(hR, NULL);
char resp[4096] = {0}; DWORD cl = 0, total = 0;
while (WinHttpReadData(hR, resp + total, sizeof(resp) - 1 - total, &cl) && cl > 0) {
total += cl; if (total >= sizeof(resp) - 1) break;
}
resp[total] = 0;
if (strstr(resp, "\"code\":0") || strstr(resp, "\"code\":200") || strstr(resp, "\"success\":true")) ok = 1;
if (!json_str(resp, "message", msg, cap) || !msg[0]) {
if (ok) snprintf(msg, cap, "操作成功");
else snprintf(msg, cap, "操作失败");
}
} else {
snprintf(msg, cap, "无法连接验证服务器");
}
if (hR) WinHttpCloseHandle(hR);
if (hC) WinHttpCloseHandle(hC);
WinHttpCloseHandle(hS);
return ok;
}
// GET 兄弟路径(只读,用于拉 /info 拿到界面开关)
static int api_get_sibling(const char *sibling, char *resp, int cap) {
resp[0] = 0; cap--;
std::string u = g_api;
size_t pos = u.rfind("/login");
if (pos != std::string::npos) u = u.substr(0, pos) + sibling;
const char *rest = u.c_str();
bool https = false;
if (!strncmp(rest, "https://", 8)) { rest += 8; https = true; }
else if (!strncmp(rest, "http://", 7)) rest += 7;
char host[256] = {0}, path[512] = "/";
const char *slash = strchr(rest, '/');
if (slash) { int hl = (int)(slash - rest); if (hl > 255) hl = 255; memcpy(host, rest, hl); snprintf(path, sizeof(path), "%s", slash); }
else snprintf(host, sizeof(host), "%s", rest);
unsigned short port = https ? 443 : 80;
char *colon = strrchr(host, ':');
if (colon) { *colon = 0; port = (unsigned short)atoi(colon + 1); }
std::wstring wHost = U8(host), wPath = U8(path);
HINTERNET hS = WinHttpOpen(L"vfy/9.0", WINHTTP_ACCESS_TYPE_NO_PROXY, NULL, NULL, 0);
if (!hS) return 0;
HINTERNET hC = WinHttpConnect(hS, wHost.c_str(), port, 0);
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"GET", wPath.c_str(), NULL, NULL, NULL, 0) : NULL;
int ok = 0;
if (hR) {
WinHttpSendRequest(hR, WINHTTP_NO_ADDITIONAL_HEADERS, 0, NULL, 0, 0, 0);
WinHttpReceiveResponse(hR, NULL);
DWORD cl = 0, total = 0;
while (WinHttpReadData(hR, resp + total, cap - total, &cl) && cl > 0) {
total += cl;
if ((int)total >= cap) break;
}
resp[total] = 0;
ok = total > 0;
WinHttpCloseHandle(hR);
}
if (hC) WinHttpCloseHandle(hC);
WinHttpCloseHandle(hS);
return ok;
}
// 把 URL 内容下载到文件(自动更新用)
static bool download_to_file(const char *url, const wchar_t *dst) {
const char *rest = url;
bool https = false;
if (!strncmp(rest, "https://", 8)) { rest += 8; https = true; }
else if (!strncmp(rest, "http://", 7)) rest += 7;
char host[256] = {0}, path[1024] = "/";
const char *slash = strchr(rest, '/');
if (slash) { int hl = (int)(slash - rest); if (hl > 255) hl = 255; memcpy(host, rest, hl); snprintf(path, sizeof(path), "%s", slash); }
else snprintf(host, sizeof(host), "%s", rest);
unsigned short port = https ? 443 : 80;
char *colon = strrchr(host, ':');
if (colon) { *colon = 0; port = (unsigned short)atoi(colon + 1); }
std::wstring wHost = U8(host), wPath = U8(path);
HINTERNET hS = WinHttpOpen(L"vfy/9.0", WINHTTP_ACCESS_TYPE_NO_PROXY, NULL, NULL, 0);
if (!hS) return false;
HINTERNET hC = WinHttpConnect(hS, wHost.c_str(), port, 0);
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"GET", wPath.c_str(), NULL, NULL, NULL, https ? WINHTTP_FLAG_SECURE : 0) : NULL;
bool ok = false;
if (hR) {
WinHttpSendRequest(hR, WINHTTP_NO_ADDITIONAL_HEADERS, 0, NULL, 0, 0, 0);
if (WinHttpReceiveResponse(hR, NULL)) {
HANDLE f = ::CreateFileW(dst, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (f != INVALID_HANDLE_VALUE) {
char buf[64 * 1024]; DWORD rd = 0, wr = 0; ok = true;
while (WinHttpReadData(hR, buf, sizeof(buf), &rd) && rd > 0) {
if (!::WriteFile(f, buf, rd, &wr, NULL) || wr != rd) { ok = false; break; }
}
::CloseHandle(f);
}
}
WinHttpCloseHandle(hR);
}
if (hC) WinHttpCloseHandle(hC);
WinHttpCloseHandle(hS);
return ok;
}
// 同 api_post_sibling,但把原始响应也交出来(设备自助页要自己解析列表)
static int api_post_sibling_raw(const char *sibling, const char *body, char *respOut, int cap, char *msg, int msgCap) {
msg[0] = 0;
if (respOut && cap > 0) respOut[0] = 0;
std::string u = g_api;
size_t pos = u.rfind("/login");
if (pos != std::string::npos) u = u.substr(0, pos) + sibling;
const char *rest = u.c_str();
bool https = false;
if (!strncmp(rest, "https://", 8)) { rest += 8; https = true; }
else if (!strncmp(rest, "http://", 7)) rest += 7;
char host[256] = {0}, path[512] = "/";
const char *slash = strchr(rest, '/');
if (slash) { int hl = (int)(slash - rest); if (hl > 255) hl = 255; memcpy(host, rest, hl); snprintf(path, sizeof(path), "%s", slash); }
else snprintf(host, sizeof(host), "%s", rest);
unsigned short port = https ? 443 : 80;
char *colon = strrchr(host, ':');
if (colon) { *colon = 0; port = (unsigned short)atoi(colon + 1); }
std::wstring wHost = U8(host), wPath = U8(path);
HINTERNET hS = WinHttpOpen(L"vfy/9.0", WINHTTP_ACCESS_TYPE_NO_PROXY, NULL, NULL, 0);
if (!hS) { snprintf(msg, msgCap, "网络初始化失败"); return 0; }
HINTERNET hC = WinHttpConnect(hS, wHost.c_str(), port, 0);
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"POST", wPath.c_str(), NULL, NULL, NULL, https ? WINHTTP_FLAG_SECURE : 0) : NULL;
int ok = 0;
if (hR) {
WinHttpSendRequest(hR, L"Content-Type: application/json\r\n", (DWORD)-1,
(LPVOID)body, (DWORD)strlen(body), (DWORD)strlen(body), 0);
WinHttpReceiveResponse(hR, NULL);
char tmp[8192] = {0};
DWORD cl = 0, total = 0;
while (WinHttpReadData(hR, tmp + total, sizeof(tmp) - 1 - total, &cl) && cl > 0) {
total += cl;
if (total >= sizeof(tmp) - 1) break;
}
tmp[total] = 0;
if (respOut) snprintf(respOut, cap, "%s", tmp);
if (strstr(tmp, "\"code\":200") || strstr(tmp, "\"code\":0")) ok = 1;
if (!json_str(tmp, "message", msg, msgCap) || !msg[0])
snprintf(msg, msgCap, ok ? "操作成功" : "操作失败");
} else {
snprintf(msg, msgCap, "无法连接验证服务器");
}
if (hR) WinHttpCloseHandle(hR);
if (hC) WinHttpCloseHandle(hC);
WinHttpCloseHandle(hS);
return ok;
}
/* ===================== 多文件更新(按清单只补改动的文件) ===================== */
struct ManifestFile {
char path[260]; // 相对程序根目录
long long size;
char hash[96]; // sha256 十六进制
char url[1024]; // 可能是相对地址,下载前要补 origin
};
static ManifestFile g_mf[256];
static int g_mfCount = 0;
// 取 g_api 的 scheme://host[:port],用于把清单里的相对下载地址补全
static std::string origin_of(const char *api) {
std::string u(api ? api : "");
size_t schemeEnd = u.find("://");
if (schemeEnd == std::string::npos) return "";
size_t slash = u.find('/', schemeEnd + 3);
return slash == std::string::npos ? u : u.substr(0, slash);
}
static std::wstring exe_dir() {
wchar_t buf[MAX_PATH] = {0};
::GetModuleFileNameW(NULL, buf, MAX_PATH);
std::wstring p(buf);
size_t pos = p.find_last_of(L'\\');
return pos == std::wstring::npos ? p : p.substr(0, pos);
}
static std::wstring exe_path() {
wchar_t buf[MAX_PATH] = {0};
::GetModuleFileNameW(NULL, buf, MAX_PATH);
return std::wstring(buf);
}
// 相对路径 → 本地完整路径(分号左边是程序根目录)
static std::wstring local_of(const char *rel) {
std::wstring out = exe_dir() + L"\\";
for (const char *c = rel; *c; ++c) {
out += (*c == '/') ? L'\\' : (wchar_t)U8((char[2]){*c, 0})[0];
}
return out;
}
// 递归建目录
static void ensure_parent_dir(const std::wstring &file) {
size_t pos = file.find_last_of(L'\\');
if (pos == std::wstring::npos) return;
std::wstring dir = file.substr(0, pos);
for (size_t i = 3; i < dir.size(); ++i) {
if (dir[i] == L'\\') ::CreateDirectoryW(dir.substr(0, i).c_str(), NULL);
}
::CreateDirectoryW(dir.c_str(), NULL);
}
static std::string to_hex(const unsigned char *d, int n) {
static const char *hx = "0123456789abcdef";
std::string s;
for (int i = 0; i < n; i++) { s += hx[d[i] >> 4]; s += hx[d[i] & 0xF]; }
return s;
}
// 用 Windows CNG 算文件 sha256(不引第三方库)
static bool sha256_file(const std::wstring &path, std::string &outHex) {
outHex.clear();
HANDLE f = ::CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (f == INVALID_HANDLE_VALUE) return false;
BCRYPT_ALG_HANDLE hAlg = NULL;
BCRYPT_HASH_HANDLE hHash = NULL;
bool ok = false;
DWORD objLen = 0, got = 0;
std::vector<unsigned char> obj, buf(64 * 1024);
unsigned char digest[32] = {0};
if (BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_SHA256_ALGORITHM, NULL, 0) == 0 &&
BCryptGetProperty(hAlg, BCRYPT_OBJECT_LENGTH, (PUCHAR)&objLen, sizeof(objLen), &got, 0) == 0) {
obj.resize(objLen);
if (BCryptCreateHash(hAlg, &hHash, obj.data(), objLen, NULL, 0, 0) == 0) {
DWORD rd = 0;
bool readOk = true;
while (::ReadFile(f, buf.data(), (DWORD)buf.size(), &rd, NULL) && rd > 0) {
if (BCryptHashData(hHash, buf.data(), rd, 0) != 0) { readOk = false; break; }
}
if (readOk && BCryptFinishHash(hHash, digest, 32, 0) == 0) {
outHex = to_hex(digest, 32);
ok = true;
}
BCryptDestroyHash(hHash);
}
}
if (hAlg) BCryptCloseAlgorithmProvider(hAlg, 0);
::CloseHandle(f);
return ok;
}
// 拉取清单:/versions/manifest?version_id=N
static bool fetch_manifest(long versionId) {
g_mfCount = 0;
char path[128];
snprintf(path, sizeof(path), "/versions/manifest?version_id=%ld", versionId);
static char buf[512 * 1024];
if (!api_get_sibling(path, buf, sizeof(buf))) return false;
if (!strstr(buf, "\"files\"")) return false;
const char *p = strstr(buf, "\"files\":[");
if (!p) return false;
while ((p = strchr(p, '{')) != NULL && g_mfCount < 256) {
const char *e = strchr(p, '}');
if (!e) break;
std::string obj(p, e - p + 1);
auto pick = [&obj](const char *key, char *out, int cap) {
out[0] = 0;
std::string k = std::string("\"") + key + "\":\"";
size_t at = obj.find(k);
if (at == std::string::npos) return false;
at += k.size();
size_t end = obj.find('"', at);
if (end == std::string::npos) return false;
std::string v = obj.substr(at, end - at);
snprintf(out, cap, "%s", v.c_str());
return true;
};
ManifestFile &m = g_mf[g_mfCount];
if (!pick("path", m.path, sizeof(m.path)) || !m.path[0]) { p = e + 1; continue; }
pick("hash", m.hash, sizeof(m.hash));
pick("url", m.url, sizeof(m.url));
std::string sk = "\"size\":";
size_t sat = obj.find(sk);
m.size = (sat == std::string::npos) ? 0 : atoll(obj.c_str() + sat + sk.size());
g_mfCount++;
p = e + 1;
const char *rest = p;
while (*rest == ' ' || *rest == ',' || *rest == '\n' || *rest == '\r') rest++;
if (*rest == ']') break;
}
return g_mfCount > 0;
}
// 按清单更新:只下变了的文件,校验 sha256,最后换主程序并重启
static int update_by_manifest(long versionId, std::wstring &errMsg, int *changedOut) {
if (changedOut) *changedOut = 0;
if (!fetch_manifest(versionId)) { errMsg = L"清单为空或没落盘,回退整包"; return 0; }
const std::wstring dir = exe_dir();
std::string origin = origin_of(g_api);
std::vector<std::wstring> pendingNew; // 已下载待替换
std::vector<std::wstring> pendingDst;
std::wstring mainExe = exe_path();
// 先清理上一轮残留
for (int i = 0; i < g_mfCount; i++) {
std::wstring dst = local_of(g_mf[i].path);
::DeleteFileW((dst + L".vfynew").c_str());
::DeleteFileW((dst + L".vfyold").c_str());
}
for (int i = 0; i < g_mfCount; i++) {
ManifestFile &m = g_mf[i];
std::wstring dst = local_of(m.path);
// 本地已一致就跳过:先比大小,再比 sha256
WIN32_FILE_ATTRIBUTE_DATA fad = {0};
bool need = true;
if (::GetFileAttributesExW(dst.c_str(), GetFileExInfoStandard, &fad)) {
long long localSize = ((long long)fad.nFileSizeHigh << 32) | fad.nFileSizeLow;
if (m.size > 0 && localSize == m.size) {
std::string localHash;
if (sha256_file(dst, localHash) && m.hash[0] && localHash == m.hash) need = false;
}
}
if (!need) continue;
if (!m.url[0]) { errMsg = L"清单里有文件没有下载地址,回退整包"; return 0; }
std::string full = m.url;
if (full.rfind("http", 0) != 0) full = origin + full;
ensure_parent_dir(dst);
std::wstring tmp = dst + L".vfynew";
::DeleteFileW(tmp.c_str());
if (!download_to_file(full.c_str(), tmp.c_str())) {
errMsg = L"下载失败:" + U8(m.path);
return 0;
}
if (m.hash[0]) {
std::string got;
if (!sha256_file(tmp, got) || got != m.hash) {
::DeleteFileW(tmp.c_str());
errMsg = L"校验失败:" + U8(m.path);
return 0;
}
}
pendingNew.push_back(tmp);
pendingDst.push_back(dst);
}
if (changedOut) *changedOut = (int)pendingDst.size();
if (pendingDst.empty()) { errMsg = L"文件已是最新,无需下载"; return 1; }
// 替换:主程序放最后(它正在运行,只能改名腾位置)
for (size_t i = 0; i < pendingDst.size(); ++i) {
if (_wcsicmp(pendingDst[i].c_str(), mainExe.c_str()) == 0) continue;
std::wstring oldf = pendingDst[i] + L".vfyold";
::DeleteFileW(oldf.c_str());
::MoveFileW(pendingDst[i].c_str(), oldf.c_str()); // 存在才改名,不存在直接放新
if (!::MoveFileW(pendingNew[i].c_str(), pendingDst[i].c_str())) {
::MoveFileW(oldf.c_str(), pendingDst[i].c_str()); // 回滚
errMsg = L"替换失败:" + pendingDst[i];
return 0;
}
}
// 主程序(只有清单里含主程序时才需要重启)
bool mainReplaced = false;
for (size_t i = 0; i < pendingDst.size(); ++i) {
if (_wcsicmp(pendingDst[i].c_str(), mainExe.c_str()) != 0) continue;
std::wstring oldf = mainExe + L".vfyold";
::DeleteFileW(oldf.c_str());
if (!::MoveFileW(mainExe.c_str(), oldf.c_str())) { errMsg = L"主程序被占用,无法替换"; return 0; }
if (!::MoveFileW(pendingNew[i].c_str(), mainExe.c_str())) {
::MoveFileW(oldf.c_str(), mainExe.c_str());
errMsg = L"主程序替换失败,已回滚";
return 0;
}
mainReplaced = true;
}
if (!mainReplaced) {
// 只更新了附属文件:删掉备份,让用户自己选择何时重启
for (int i = 0; i < g_mfCount; i++) {
std::wstring dst = local_of(g_mf[i].path);
::DeleteFileW((dst + L".vfyold").c_str());
}
errMsg = L"更新完成,重启程序后生效";
return 1;
}
// 重启新程序
STARTUPINFOW si = { sizeof(si) };
PROCESS_INFORMATION pi = { 0 };
std::wstring cmd = L"\"" + mainExe + L"\"";
if (::CreateProcessW(mainExe.c_str(), (LPWSTR)cmd.c_str(), NULL, NULL, FALSE, 0, NULL, dir.c_str(), &si, &pi)) {
::CloseHandle(pi.hThread);
::CloseHandle(pi.hProcess);
}
::ExitProcess(0);
return 2;
}
/* ---------------------------- 窗口 ---------------------------- */
typedef void (*PFN_OEP)(void);
static PFN_OEP g_oep = NULL;
static int g_logged_in = 0;
// 从 cfg 的 api 里抽出站点根地址(去掉 /api/v1/... 部分)
static std::wstring SiteRoot() {
std::string a(g_api);
size_t p = a.find("/api/");
if (p != std::string::npos) a = a.substr(0, p);
return U8(a.c_str());
}
static bool g_remember = false;
static int g_tab = 0; // 0=登录 1=注册 2=充值 3=重置
// 递归找可见控件里最低的底边(布局跑完后才有值)
static int MaxVisibleBottom(CControlUI *c) {
if (!c || !c->IsVisible()) return 0;
int best = 0;
if (CContainerUI *box = dynamic_cast<CContainerUI *>(c)) {
int n = box->GetCount();
for (int i = 0; i < n; i++) {
int b = MaxVisibleBottom(box->GetItemAt(i));
if (b > best) best = b;
}
return best;
}
RECT r = c->GetPos();
return r.bottom;
}
// 面板内容高度 = 所有子控件固定高度之和(面板 height=auto,pos 不可靠)
static int PanelContentHeight(CControlUI *panel) {
CContainerUI *box = dynamic_cast<CContainerUI *>(panel);
if (!box) return 0;
int n = box->GetCount(), sum = 0;
for (int i = 0; i < n; i++) {
CControlUI *c = box->GetItemAt(i);
if (!c) continue;
int h = c->GetFixedHeight();
if (h <= 0) { RECT pr = c->GetPos(); h = pr.bottom - pr.top; }
if (h > 0) sum += h;
}
return sum;
}
class CVerifyWnd : public CWindowWnd, public INotifyUI {
public:
explicit CVerifyWnd(const char *skin) : m_skin(skin) {}
LPCTSTR GetWindowClassName() const override { return _T("VfyDuiWnd"); }
UINT GetClassStyle() const override { return CS_DBLCLKS; }
void Notify(TNotifyUI &msg) override {
if (msg.sType == _T("click")) {
CControlUI *p = msg.pSender;
LPCTSTR nm = p ? p->GetName().GetData() : NULL;
if (!nm) return;
if (!_tcsicmp(nm, _T("btnClose")) || !_tcsicmp(nm, _T("btnQuit"))) { ::PostQuitMessage(0); return; }
if (!_tcsicmp(nm, _T("btnLogin"))) { DoLogin(); return; }
if (!_tcsicmp(nm, _T("tabLogin"))) { SwitchTab(0); return; }
if (!_tcsicmp(nm, _T("tabRegister"))) { SwitchTab(1); return; }
if (!_tcsicmp(nm, _T("tabCard"))) { SwitchTab(2); return; }
if (!_tcsicmp(nm, _T("tabReset"))) { SwitchTab(3); return; }
if (!_tcsicmp(nm, _T("btnRecharge"))) { DoRecharge(); return; }
if (!_tcsicmp(nm, _T("btnReset"))) { DoReset(); return; }
if (!_tcsicmp(nm, _T("btnSendCode2"))) { DoSendResetCode(); return; }
if (!_tcsicmp(nm, _T("btnNoticePrev"))) { ShowNotice(g_noticeIdx - 1); return; }
if (!_tcsicmp(nm, _T("btnNoticeNext"))) { ShowNotice(g_noticeIdx + 1); return; }
if (!_tcsicmp(nm, _T("btnNoticeOk"))) { SaveNoticeSeen(); HideOverlays(); return; }
if (!_tcsicmp(nm, _T("btnUpdate"))) { DoUpdate(); return; }
if (!_tcsicmp(nm, _T("btnUpdLater"))) { HideOverlays(); return; }
if (!_tcsicmp(nm, _T("btnUnbind"))) { UnbindByIndex(); return; }
if (!_tcsicmp(nm, _T("btnUnbindOld"))) { UnbindOldest(); return; }
if (!_tcsicmp(nm, _T("btnRetryLogin"))) { HideOverlays(); DoLogin(); return; }
if (!_tcsicmp(nm, _T("btnBack"))) { HideOverlays(); return; }
if (!_tcsicmp(nm, _T("btnRegister"))) { DoRegister(); return; }
if (!_tcsicmp(nm, _T("btnSendCode"))) { DoSendCode(); return; }
if (!_tcsicmp(nm, _T("btnLinkReg")) || !_tcsicmp(nm, _T("btnLinkCard")) ||
!_tcsicmp(nm, _T("btnLinkForgot"))) {
std::wstring url = SiteRoot();
// 平台只有 /login 与 /register 是公开页:注册直开,其余引导到登录页
url += _tcsicmp(nm, _T("btnLinkReg")) == 0 ? L"/register" : L"/login";
::ShellExecuteW(NULL, L"open", url.c_str(), NULL, NULL, SW_SHOWNORMAL);
return;
}
if (!_tcsicmp(nm, _T("btnRemember"))) {
g_remember = !g_remember;
UpdateRememberButton();
return;
}
} else if (msg.sType == _T("return")) {
DoLogin();
} else if (msg.sType == _T("setfocus") || msg.sType == _T("killfocus")) {
CControlUI *p = msg.pSender;
if (!p) return;
LPCTSTR nm = p->GetName().GetData();
if (!nm || (_tcsicmp(nm, _T("editUser")) && _tcsicmp(nm, _T("editPass")))) return;
bool focus = !_tcsicmp(msg.sType.GetData(), _T("setfocus"));
if (CEditUI *e = static_cast<CEditUI *>(p)) {
DWORD bg = e->GetBkColor();
// 聚焦时把原生 EDIT 窗口底色提亮一档(纯 XML 画不出描边,用亮度做反馈)
if (focus) {
BYTE r = GetRValue(bg) + 10 > 255 ? 255 : GetRValue(bg) + 10;
BYTE g = GetGValue(bg) + 10 > 255 ? 255 : GetGValue(bg) + 10;
BYTE b = GetBValue(bg) + 14 > 255 ? 255 : GetBValue(bg) + 14;
e->SetNativeEditBkColor(RGB(r, g, b));
} else {
e->SetNativeEditBkColor(bg);
}
e->Invalidate();
}
}
}
// ---------------- 四个 tab:登录 / 注册 / 卡密充值 / 忘记密码 ----------------
void SwitchTab(int tab) {
if (!strcmp(g_loginMode, "card") && tab == 1) { ShowManageDevices(); return; }
int old = g_tab;
g_tab = tab;
// 从覆盖页回到 tab 时把覆盖层收掉
if (g_overlay) {
HideByName("panelNotice"); HideByName("panelUpdate"); HideByName("panelDevice");
g_overlay = 0; g_devManage = 0;
HideByName("lblDevCard"); HideByName("devCardKey"); HideByName("spDevCard");
if (CButtonUI *b = static_cast<CButtonUI *>(m_pm.FindControl(_T("btnRetryLogin")))) b->SetVisible(true);
}
const char *panels[4] = { "panelLogin", "panelRegister", "panelCard", "panelReset" };
for (int i = 0; i < 4; i++) {
if (CControlUI *p = m_pm.FindControl(U8(panels[i]).c_str()))
p->SetVisible(i == tab);
}
UpdateTabStyle();
ResizeForTab(tab, old);
}
// 面板高度不同:切换后按新面板高度改窗口高度,避免大片空白或内容被切
void ResizeForTab(int tab, int old) {
(void)tab; (void)old;
// 窗口高度不再靠 chrome 估算:布局跑完后按「可见内容最低底边」收一次
m_pm.GetRoot()->NeedUpdate();
::InvalidateRect(m_hWnd, NULL, TRUE);
ScheduleFit();
}
// 每套皮肤的 tab 表达方式不同,这里按主题分别上色
void UpdateTabStyle() {
const char *names[4] = { "tabLogin", "tabRegister", "tabCard", "tabReset" };
CButtonUI *btns[4] = { NULL, NULL, NULL, NULL };
for (int i = 0; i < 4; i++)
btns[i] = static_cast<CButtonUI *>(m_pm.FindControl(U8(names[i]).c_str()));
if (!btns[0]) return;
std::string th(g_theme);
DWORD actBg = 0, idleBg = 0, actFg = 0, idleFg = 0;
bool bgMode = true;
if (th == "dark") { bgMode = false; actFg = 0xFF4EA3E8; idleFg = 0xFF85858F; }
else if (th == "light") { actBg = 0xFF1B6FD6; idleBg = 0xFFEBEFF6; actFg = 0xFFFFFFFF; idleFg = 0xFF5B6270; }
else if (th == "split") { bgMode = false; actFg = 0xFF4CC2FF; idleFg = 0xFF7A8794; }
else if (th == "card") { actBg = 0xFFFFFFFF; idleBg = 0xFFE8E6FF; actFg = 0xFF3B2BD6; idleFg = 0xFF5B56A8; }
else if (th == "industrial") { actBg = 0xFF1A5A8C; idleBg = 0x00000000; actFg = 0xFFFFFFFF; idleFg = 0xFF9FC8E6; }
else if (th == "terminal") { bgMode = false; actFg = 0xFF7FE39B; idleFg = 0xFF4E7A5C; }
else if (th == "compact") { actBg = 0xFF2E9E6B; idleBg = 0xFF161C22; actFg = 0xFFFFFFFF; idleFg = 0xFF9FB3C8; }
for (int i = 0; i < 4; i++) {
if (!btns[i]) continue;
bool on = (i == g_tab);
if (bgMode) btns[i]->SetBkColor(on ? actBg : idleBg);
btns[i]->SetTextColor(on ? actFg : idleFg);
btns[i]->Invalidate();
}
// dark 皮肤用下划线指示条
const char *lines[4] = { "lineLogin", "lineRegister", "lineCard", "lineReset" };
for (int i = 0; i < 4; i++) {
if (CControlUI *l = m_pm.FindControl(U8(lines[i]).c_str()))
l->SetBkColor(i == g_tab ? 0xFF4EA3E8 : 0x00000000);
}
}
void DoRecharge() {
CEditUI *u = static_cast<CEditUI *>(m_pm.FindControl(_T("cardUser")));
CEditUI *k = static_cast<CEditUI *>(m_pm.FindControl(_T("cardKey")));
CLabelUI *tip = static_cast<CLabelUI *>(m_pm.FindControl(_T("cardTip")));
if (!u || !k || !tip) return;
std::wstring user = u->GetText().GetData(), key = k->GetText().GetData();
if (user.empty()) { tip->SetText(L"请输入用户名"); return; }
if (key.empty()) { tip->SetText(L"请输入卡密"); return; }
char body[1024];
snprintf(body, sizeof(body), "{\"username\":\"%s\",\"card_key\":\"%s\",\"device_id\":\"%s\"}",
W2U8(user).c_str(), W2U8(key).c_str(), g_device);
tip->SetText(L"正在提交充值…");
char msg[1024] = {0};
if (api_post_sibling("/recharge", body, msg, sizeof(msg))) {
tip->SetText(U8(msg).c_str());
if (CEditUI *lu = static_cast<CEditUI *>(m_pm.FindControl(_T("editUser")))) lu->SetText(user.c_str());
} else {
tip->SetText(U8(msg).c_str());
}
}
void DoReset() {
if (!strcmp(g_loginMode, "card")) { DoCardBind(); return; }
CEditUI *e = static_cast<CEditUI *>(m_pm.FindControl(_T("resetEmail")));
CEditUI *c = static_cast<CEditUI *>(m_pm.FindControl(_T("resetCode")));
CEditUI *p = static_cast<CEditUI *>(m_pm.FindControl(_T("resetPass")));
CLabelUI *tip = static_cast<CLabelUI *>(m_pm.FindControl(_T("resetTip")));
if (!e || !c || !p || !tip) return;
std::wstring email = e->GetText().GetData(), code = c->GetText().GetData(), pass = p->GetText().GetData();
if (email.empty()) { tip->SetText(L"请输入邮箱"); return; }
if (code.empty()) { tip->SetText(L"请输入验证码"); return; }
if (pass.size() < 6) { tip->SetText(L"新密码至少 6 位"); return; }
char body[1024];
snprintf(body, sizeof(body), "{\"email\":\"%s\",\"code\":\"%s\",\"password\":\"%s\"}",
W2U8(email).c_str(), W2U8(code).c_str(), W2U8(pass).c_str());
tip->SetText(L"正在重置…");
char msg[1024] = {0};
int ok = api_post_sibling("/reset-password", body, msg, sizeof(msg));
tip->SetText(U8(msg).c_str());
if (ok) {
if (CEditUI *lp = static_cast<CEditUI *>(m_pm.FindControl(_T("editPass")))) lp->SetText(pass.c_str());
SwitchTab(0);
}
}
// 卡密主体把卡密换成「邮箱 + 密码」这把备用钥匙
void DoCardBind() {
CEditUI *k = static_cast<CEditUI *>(m_pm.FindControl(_T("resetCardKey")));
CEditUI *e = static_cast<CEditUI *>(m_pm.FindControl(_T("resetEmail")));
CEditUI *c = static_cast<CEditUI *>(m_pm.FindControl(_T("resetCode")));
CEditUI *p = static_cast<CEditUI *>(m_pm.FindControl(_T("resetPass")));
CLabelUI *tip = static_cast<CLabelUI *>(m_pm.FindControl(_T("resetTip")));
if (!k || !e || !c || !p || !tip) return;
std::wstring key = k->GetText().GetData(), email = e->GetText().GetData(),
code = c->GetText().GetData(), pass = p->GetText().GetData();
if (key.empty()) { tip->SetText(L"请输入卡密"); return; }
if (pass.size() < 6) { tip->SetText(L"密码至少 6 位"); return; }
// 不填邮箱验证码 = 只用卡密改密码(卡密本身就是钥匙,不需要旧密码)
if (code.empty()) {
char b2[512];
snprintf(b2, sizeof(b2), "{\"card_key\":\"%s\",\"password\":\"%s\"}",
W2U8(key).c_str(), W2U8(pass).c_str());
tip->SetText(L"正在设置密码…");
char m2[768] = {0};
if (api_post_sibling("/card-set-password", b2, m2, sizeof(m2))) {
tip->SetText(U8(m2).c_str());
if (CButtonUI *b = static_cast<CButtonUI *>(m_pm.FindControl(_T("btnReset")))) b->SetText(L"密码已更新");
} else {
tip->SetText(U8(m2).c_str());
}
return;
}
if (email.empty()) { tip->SetText(L"请输入邮箱"); return; }
char body[1024];
snprintf(body, sizeof(body),
"{\"card_key\":\"%s\",\"email\":\"%s\",\"code\":\"%s\",\"password\":\"%s\"}",
W2U8(key).c_str(), W2U8(email).c_str(), W2U8(code).c_str(), W2U8(pass).c_str());
tip->SetText(L"正在绑定…");
char msg[1024] = {0};
if (api_post_sibling("/card-bind", body, msg, sizeof(msg))) {
tip->SetText(U8(msg).c_str());
if (CEditUI *lu = static_cast<CEditUI *>(m_pm.FindControl(_T("editUser")))) lu->SetText(key.c_str());
if (CButtonUI *b = static_cast<CButtonUI *>(m_pm.FindControl(_T("btnReset")))) b->SetText(L"已绑定");
} else {
tip->SetText(U8(msg).c_str());
}
}
void DoSendResetCode() {
CEditUI *e = static_cast<CEditUI *>(m_pm.FindControl(_T("resetEmail")));
CLabelUI *tip = static_cast<CLabelUI *>(m_pm.FindControl(_T("resetTip")));
if (!e || !tip) return;
std::wstring email = e->GetText().GetData();
if (email.empty()) { tip->SetText(L"请先填邮箱"); return; }
char msg[512] = {0};
api_send_code(W2U8(email).c_str(), !strcmp(g_loginMode, "card") ? "bind_email" : "reset_password", msg, sizeof(msg));
tip->SetText(U8(msg).c_str());
}
void DoRegister() {
CEditUI *u = static_cast<CEditUI *>(m_pm.FindControl(_T("regUser")));
CEditUI *e = static_cast<CEditUI *>(m_pm.FindControl(_T("regEmail")));
CEditUI *c = static_cast<CEditUI *>(m_pm.FindControl(_T("regCode")));
CEditUI *p1 = static_cast<CEditUI *>(m_pm.FindControl(_T("regPass")));
CEditUI *p2 = static_cast<CEditUI *>(m_pm.FindControl(_T("regPass2")));
CLabelUI *tip = static_cast<CLabelUI *>(m_pm.FindControl(_T("regTip")));
if (!u || !e || !c || !p1 || !p2 || !tip) return;
std::wstring user = u->GetText().GetData(), email = e->GetText().GetData();
std::wstring code = c->GetText().GetData(), pass = p1->GetText().GetData();
std::wstring pass2 = p2->GetText().GetData();
if (user.empty()) { tip->SetText(L"请输入用户名"); return; }
if (email.empty()) { tip->SetText(L"请输入邮箱"); return; }
if (code.empty()) { tip->SetText(L"请输入邮箱验证码"); return; }
if (pass.size() < 6) { tip->SetText(L"密码至少 6 位"); return; }
if (pass != pass2) { tip->SetText(L"两次输入的密码不一致"); return; }
tip->SetText(L"正在提交注册…");
char msg[1024] = {0};
int ok = api_register(W2U8(user).c_str(), W2U8(email).c_str(), W2U8(code).c_str(),
W2U8(pass).c_str(), msg, sizeof(msg));
if (!ok) { tip->SetText(U8(msg).c_str()); return; }
// 注册成功直接登录
if (CEditUI *lu = static_cast<CEditUI *>(m_pm.FindControl(_T("editUser")))) lu->SetText(user.c_str());
if (CEditUI *lp = static_cast<CEditUI *>(m_pm.FindControl(_T("editPass")))) lp->SetText(pass.c_str());
SwitchTab(0);
DoLogin();
}
// ==================== 覆盖页:公告 / 更新 / 设备已满 ====================
// 布局跑完之后按页脚实际底边收窗口高度:比任何 chrome 估算都准
void FitWindowToFooter(int extraPad) {
CControlUI *root = m_pm.GetRoot();
if (!root) return;
int bottom = MaxVisibleBottom(root);
if (bottom <= 0) return; // 布局还没跑(首次创建时就是这样),等下一拍
int want = bottom + extraPad;
if (want < 300) want = 300;
RECT wr = {0};
::GetWindowRect(m_hWnd, &wr);
int curH = wr.bottom - wr.top;
int curW = wr.right - wr.left;
if (want == curH) return;
::SetWindowPos(m_hWnd, NULL, 0, 0, curW, want, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
}
// 布局是异步的:切完面板先挂一个一次性定时器,下一拍再量窗口高度
void ScheduleFit() {
::SetTimer(m_hWnd, 3, 16, NULL);
}
void ResizeToPanel(const char *name) {
CControlUI *p = m_pm.FindControl(U8(name).c_str());
if (!p) return;
m_pm.GetRoot()->NeedUpdate();
::InvalidateRect(m_hWnd, NULL, TRUE);
ScheduleFit();
}
void ShowOverlay(const char *name) {
const char *panels[4] = { "panelLogin", "panelRegister", "panelCard", "panelReset" };
for (int i = 0; i < 4; i++) HideByName(panels[i]);
HideByName("panelNotice"); HideByName("panelUpdate"); HideByName("panelDevice");
if (CControlUI *c = m_pm.FindControl(U8(name).c_str())) c->SetVisible(true);
g_overlay = !strcmp(name, "panelNotice") ? 1 : (!strcmp(name, "panelUpdate") ? 2 : 3);
ResizeToPanel(name);
// 面板是运行时才显示的,原生 EDIT 子窗口要等一次真正的布局/绘制才落到正确位置
m_pm.GetRoot()->NeedUpdate();
::InvalidateRect(m_hWnd, NULL, TRUE);
::UpdateWindow(m_hWnd);
if (!strcmp(name, "panelDevice")) {
if (CEditUI *e = static_cast<CEditUI *>(m_pm.FindControl(_T("devIdx")))) e->SetFocus();
}
}
void HideOverlays() {
HideByName("panelNotice"); HideByName("panelUpdate"); HideByName("panelDevice");
g_overlay = 0;
SwitchTab(g_tab);
}
// ---------------- 公告 ----------------
void LoadNotices() {
static char buf[24576];
if (!api_get_sibling("/announcements", buf, sizeof(buf))) return;
g_noticeCount = 0; g_noticeIdx = 0;
int maxId = 0;
// gin 的 map 序列化按键名排序:content, created_at, id, is_top, title
// 所以以 "content":" 作为一条公告的起点,往后取 id 与 title 才是同一条
const char *p = buf;
while ((p = strstr(p, "\"content\":\"")) && g_noticeCount < 8) {
p += 11;
char body[1024] = {0}; int j = 0;
while (*p && *p != '"' && j < 1023) {
if (*p == '\\' && p[1]) {
if (p[1] == 'n') { body[j++] = '\n'; p += 2; continue; }
p++;
}
body[j++] = *p++;
}
int id = 0;
if (const char *q = strstr(p, "\"id\":")) id = atoi(q + 5);
char title[128] = {0};
if (const char *t = strstr(p, "\"title\":\"")) {
t += 9; int k = 0;
while (*t && *t != '"' && k < 127) { if (*t == '\\' && t[1]) t++; title[k++] = *t++; }
}
g_notices[g_noticeCount].id = id;
snprintf(g_notices[g_noticeCount].title, sizeof(g_notices[0].title), "%s", title);
snprintf(g_notices[g_noticeCount].body, sizeof(g_notices[0].body), "%s", body);
g_noticeCount++;
if (id > maxId) maxId = id;
p++;
}
if (g_noticeCount > 0 && maxId > NoticeSeenId()) ShowNotice(0);
}
static int NoticeSeenId() {
std::wstring p = AccountIniPath();
return (int)::GetPrivateProfileIntW(L"notice", L"seen", 0, p.c_str());
}
void SaveNoticeSeen() {
int maxId = 0;
for (int i = 0; i < g_noticeCount; i++) if (g_notices[i].id > maxId) maxId = g_notices[i].id;
std::wstring p = AccountIniPath();
wchar_t v[32]; swprintf(v, 32, L"%d", maxId);
::WritePrivateProfileStringW(L"notice", L"seen", v, p.c_str());
}
void ShowNotice(int idx) {
if (g_noticeCount <= 0) return;
if (idx < 0) idx = 0;
if (idx >= g_noticeCount) idx = g_noticeCount - 1;
g_noticeIdx = idx;
if (CLabelUI *t = static_cast<CLabelUI *>(m_pm.FindControl(_T("noticeTitle"))))
t->SetText(U8(g_notices[idx].title).c_str());
if (CLabelUI *b = static_cast<CLabelUI *>(m_pm.FindControl(_T("noticeBody"))))
b->SetText(U8(g_notices[idx].body).c_str());
if (CLabelUI *i = static_cast<CLabelUI *>(m_pm.FindControl(_T("noticeIdx")))) {
char t2[32]; snprintf(t2, sizeof(t2), "%d / %d", idx + 1, g_noticeCount);
i->SetText(U8(t2).c_str());
}
ShowOverlay("panelNotice");
}
// ---------------- 版本更新 ----------------
void CheckUpdate() {
if (!g_ver[0]) return; // 没登记版本的程序不打扰用户
char path[160], buf[8192];
snprintf(path, sizeof(path), "/check-update?version=%s", g_ver);
if (!api_get_sibling(path, buf, sizeof(buf))) return;
if (!json_bool(buf, "has_update", 0)) return;
char lv[64] = {0}, notes[2048] = {0}, strat[32] = {0}, dl[768] = {0};
json_str(buf, "latest_version", lv, sizeof(lv));
if (!json_str(buf, "update_notes", notes, sizeof(notes)) || !notes[0])
json_str(buf, "changelog", notes, sizeof(notes)); // 平台字段名是 changelog
unescape_nl(notes);
json_str(buf, "update_strategy", strat, sizeof(strat));
json_str(buf, "download_url", dl, sizeof(dl));
snprintf(g_updateUrl, sizeof(g_updateUrl), "%s", dl);
g_updateVersionId = (long)json_int(buf, "latest_version_id", 0);
g_updateForced = !strcmp(strat, "forced");
wchar_t title[256];
swprintf(title, 256, L"发现新版本 %ls(当前 %ls)", U8(lv).c_str(), U8(g_ver).c_str());
if (CLabelUI *t = static_cast<CLabelUI *>(m_pm.FindControl(_T("updTitle")))) t->SetText(title);
if (CLabelUI *n = static_cast<CLabelUI *>(m_pm.FindControl(_T("updNotes"))))
n->SetText(notes[0] ? U8(notes).c_str() : L"该版本没有填写更新说明");
if (CLabelUI *tp = static_cast<CLabelUI *>(m_pm.FindControl(_T("updTip"))))
tp->SetText(g_updateForced ? L"这是强制更新,需完成后才能继续使用" : L"可以先稍后,不影响当前使用");
if (CButtonUI *later = static_cast<CButtonUI *>(m_pm.FindControl(_T("btnUpdLater"))))
later->SetVisible(!g_updateForced);
ShowOverlay("panelUpdate");
}
void DoUpdate() {
CLabelUI *tip0 = static_cast<CLabelUI *>(m_pm.FindControl(_T("updTip")));
CButtonUI *btn0 = static_cast<CButtonUI *>(m_pm.FindControl(_T("btnUpdate")));
if (btn0) { btn0->SetText(L"更新中…"); btn0->SetEnabled(false); }
// 优先按文件清单更新(只补改动的文件)
if (g_updateVersionId > 0) {
if (tip0) tip0->SetText(L"正在按文件清单校验…");
std::wstring err;
int changed = 0;
int r = update_by_manifest(g_updateVersionId, err, &changed);
if (r == 2) return; // 已重启
if (r == 1) {
if (tip0) tip0->SetText(err.c_str());
if (btn0) { btn0->SetText(changed > 0 ? L"已更新" : L"已是最新"); btn0->SetEnabled(true); }
return;
}
if (tip0) tip0->SetText(err.c_str()); // 清单不可用 → 回退整包
}
if (!g_updateUrl[0]) {
if (tip0) tip0->SetText(L"没有可用的更新地址");
if (btn0) { btn0->SetText(L"立即更新"); btn0->SetEnabled(true); }
return;
}
CLabelUI *tip = static_cast<CLabelUI *>(m_pm.FindControl(_T("updTip")));
CButtonUI *btn = static_cast<CButtonUI *>(m_pm.FindControl(_T("btnUpdate")));
if (btn) { btn->SetText(L"下载中…"); btn->SetEnabled(false); }
wchar_t exe[MAX_PATH] = {0};
::GetModuleFileNameW(NULL, exe, MAX_PATH);
std::wstring path(exe);
std::wstring dst = path + L".new";
::DeleteFileW(dst.c_str());
if (tip) tip->SetText(L"正在下载新版本,请稍候…");
if (!download_to_file(g_updateUrl, dst.c_str())) {
if (tip) tip->SetText(L"下载失败,请检查网络后重试");
if (btn) { btn->SetText(L"立即更新"); btn->SetEnabled(true); }
return;
}
// 运行中的 exe 不能覆盖写,但可以先改名腾出名字,再把新文件放回原处
std::wstring old = path + L".old";
::DeleteFileW(old.c_str());
if (!::MoveFileW(path.c_str(), old.c_str())) {
if (tip) tip->SetText(L"替换失败:程序目录没有写权限,请用管理员身份运行");
if (btn) { btn->SetText(L"立即更新"); btn->SetEnabled(true); }
return;
}
if (!::MoveFileW(dst.c_str(), path.c_str())) {
::MoveFileW(old.c_str(), path.c_str()); // 回滚
if (tip) tip->SetText(L"替换失败,已回滚");
if (btn) { btn->SetText(L"立即更新"); btn->SetEnabled(true); }
return;
}
if (tip) tip->SetText(L"更新完成,正在重启…");
std::wstring dir = path.substr(0, path.find_last_of(L'\\'));
STARTUPINFOW si = { sizeof(si) };
PROCESS_INFORMATION pi = { 0 };
std::wstring cmd = L"\"" + path + L"\"";
if (::CreateProcessW(path.c_str(), (LPWSTR)cmd.c_str(), NULL, NULL, FALSE, 0, NULL, dir.c_str(), &si, &pi)) {
::CloseHandle(pi.hThread); ::CloseHandle(pi.hProcess);
}
::ExitProcess(0);
}
// ---------------- 设备已满:列设备 + 就地解绑 ----------------
// 把 g_lastResp 里的设备数组解析到 g_devs/后面统一渲染
void ParseDevicesInto() {
g_devCount = 0;
g_selIdx = 0;
g_devMax = json_int(g_lastResp, "max_devices", g_maxDevices);
const char *p = g_lastResp;
while ((p = strstr(p, "\"device_id\":\"")) && g_devCount < 16) {
p += 13;
char id[64] = {0}; int i = 0;
while (*p && *p != '"' && i < 63) id[i++] = *p++;
char name[64] = {0};
if (const char *n = strstr(p, "\"device_name\":\"")) {
n += 15; int j = 0;
while (*n && *n != '"' && j < 63) name[j++] = *n++;
}
snprintf(g_devs[g_devCount].id, sizeof(g_devs[0].id), "%s", id);
snprintf(g_devs[g_devCount].name, sizeof(g_devs[0].name), "%s", name[0] ? name : "未命名设备");
g_devs[g_devCount].online = 0;
if (const char *oc = strstr(p, "\"online_count\":")) g_devs[g_devCount].online = atoi(oc + 15);
g_devCount++;
p++;
}
}
// 设备列表渲染:写进 devBody 这个多行 Label(与原资产一致的单标签写法)
void RenderDeviceList() {
std::wstring body;
for (int i = 0; i < g_devCount; i++) {
wchar_t line[320];
swprintf(line, 320, L"%d. %ls %ls %ls\r\n", i + 1,
U8(g_devs[i].name).c_str(), U8(g_devs[i].id).c_str(),
g_devs[i].online > 0 ? L"\u25cf \u5728\u7ebf" : L"\u25cb \u79bb\u7ebf");
body += line;
}
if (CLabelUI *b = static_cast<CLabelUI *>(m_pm.FindControl(_T("devBody")))) b->SetText(body.c_str());
}
void ShowDevicePanel() {
ParseDevicesInto();
g_selIdx = 0;
std::wstring body;
for (int i = 0; i < g_devCount; i++) {
wchar_t line[256];
swprintf(line, 256, L"%d. %ls %ls\r\n", i + 1, U8(g_devs[i].name).c_str(), U8(g_devs[i].id).c_str());
body += line;
}
if (body.empty()) body = L"(服务器没有返回设备明细,可直接重试登录)";
else body = L"点选下面要解绑的那台设备,再按「解绑该设备」";
#ifdef VFY_DEBUG
{ HANDLE f = ::CreateFileW(L"C:\\vfy_dev.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
if (f != INVALID_HANDLE_VALUE) { std::string dump; char tmp[2048];
snprintf(tmp, sizeof(tmp), "count=%d max=%d\nRAW:\n%s\n", g_devCount, g_devMax, g_lastResp);
dump = tmp; for (int i2 = 0; i2 < g_devCount; i2++) { snprintf(tmp, sizeof(tmp), "ITEM[%d] name=<%s> id=<%s>\n", i2, g_devs[i2].name, g_devs[i2].id); dump += tmp; }
DWORD wr = 0; ::WriteFile(f, dump.c_str(), (DWORD)dump.size(), &wr, NULL); ::CloseHandle(f); } }
#endif
RenderDeviceList(); // 列表正文由它写进 devBody
wchar_t title[160];
swprintf(title, 160, L"已绑定 %d / %d 台,解绑一台后即可登录", g_devCount, g_devMax > 0 ? g_devMax : g_maxDevices);
if (CLabelUI *t = static_cast<CLabelUI *>(m_pm.FindControl(_T("devTitle")))) t->SetText(title);
ShowOverlay("panelDevice");
if (CLabelUI *tp = static_cast<CLabelUI *>(m_pm.FindControl(_T("devTip"))))
tp->SetText(L"点选上面要解绑的那台设备,再按「解绑该设备」");
if (CEditUI *e = static_cast<CEditUI *>(m_pm.FindControl(_T("devIdx")))) e->SetText(L"");
}
// 一键解绑最早绑定的一台(服务器按 created_at DESC 返回,最后一台最老)
void UnbindOldest() {
if (g_devCount <= 0) return;
UnbindDeviceIdx(g_devCount);
}
// 卡密用户的「我的设备」:卡密就是身份,不用先登录
void ShowManageDevices() {
CEditUI *k = static_cast<CEditUI *>(m_pm.FindControl(_T("devCardKey")));
CEditUI *src = static_cast<CEditUI *>(m_pm.FindControl(_T("editUser")));
CLabelUI *tip = static_cast<CLabelUI *>(m_pm.FindControl(_T("devTip")));
if (!k) return;
if (k->GetText().IsEmpty() && src && !src->GetText().IsEmpty()) k->SetText(src->GetText());
std::wstring key = k->GetText().GetData();
if (key.empty()) {
// 还没填卡密:先切到登录页把卡密填了再来
g_tab = 1;
g_devManage = 1;
ShowOverlay("panelDevice");
HideByName("lblDevCard"); HideByName("devCardKey"); HideByName("spDevCard");
if (CButtonUI *b = static_cast<CButtonUI *>(m_pm.FindControl(_T("btnRetryLogin")))) b->SetVisible(false);
if (CLabelUI *t = static_cast<CLabelUI *>(m_pm.FindControl(_T("devTitle")))) t->SetText(L"先在「登录」里填入卡密,再点这里的「我的设备」");
if (CLabelUI *b = static_cast<CLabelUI *>(m_pm.FindControl(_T("devBody")))) b->SetText(L"");
return;
}
char body[512];
snprintf(body, sizeof(body), "{\"card_key\":\"%s\"}", W2U8(key).c_str());
char resp[8192] = {0};
char msg[512] = {0};
if (!api_post_sibling_raw("/card-devices", body, resp, sizeof(resp), msg, sizeof(msg))) {
if (tip) tip->SetText(U8(msg).c_str());
g_devCount = 0;
} else {
snprintf(g_lastResp, sizeof(g_lastResp), "%s", resp);
ParseDevicesInto();
}
g_devManage = 1;
ShowOverlay("panelDevice");
if (CControlUI *c = m_pm.FindControl(_T("lblDevCard"))) c->SetVisible(true);
if (CControlUI *c = m_pm.FindControl(_T("devCardKey"))) c->SetVisible(true);
if (CControlUI *c = m_pm.FindControl(_T("spDevCard"))) c->SetVisible(true);
if (CLabelUI *h = static_cast<CLabelUI *>(m_pm.FindControl(_T("devHead")))) h->SetText(L"我的设备");
if (CButtonUI *b = static_cast<CButtonUI *>(m_pm.FindControl(_T("btnRetryLogin")))) {
b->SetVisible(true);
b->SetText(L"返回登录");
}
if (CButtonUI *b = static_cast<CButtonUI *>(m_pm.FindControl(_T("btnBack")))) b->SetVisible(false);
std::wstring text;
for (int i = 0; i < g_devCount; i++) {
wchar_t line[256];
swprintf(line, 256, L"%d. %ls %ls\r\n", i + 1, U8(g_devs[i].name).c_str(), U8(g_devs[i].id).c_str());
text += line;
}
if (text.empty()) text = L"当前没有已绑定设备";
RenderDeviceList(); // 列表正文由它写进 devBody
wchar_t title[160];
swprintf(title, 160, L"已绑定 %d / %d 台,解绑一台即可换设备登录", g_devCount, g_devMax > 0 ? g_devMax : g_maxDevices);
if (CLabelUI *t = static_cast<CLabelUI *>(m_pm.FindControl(_T("devTitle")))) t->SetText(title);
}
void UnbindByIndex() {
CEditUI *e = static_cast<CEditUI *>(m_pm.FindControl(_T("devIdx")));
CLabelUI *tip = static_cast<CLabelUI *>(m_pm.FindControl(_T("devTip")));
if (!e || !tip) return;
int idx = _wtoi(e->GetText().GetData());
if (idx < 1) idx = g_selIdx; // 没填序号时用列表里点选的那台
if (idx < 1 || idx > g_devCount) { tip->SetText(L"请先在「输入要解绑的设备序号」里填上列表中的序号(例如 1),再按「解绑该设备」"); return; }
{
wchar_t conf[256];
swprintf(conf, 256, L"正在解绑第 %d 台:%ls(%ls)", idx,
U8(g_devs[idx - 1].name).c_str(), g_devs[idx - 1].online > 0 ? L"在线" : L"离线");
tip->SetText(conf);
}
UnbindDeviceIdx(idx);
}
void UnbindDeviceIdx(int idx) {
CLabelUI *tip = static_cast<CLabelUI *>(m_pm.FindControl(_T("devTip")));
if (!tip) return;
char body[768];
const char *path = "/unbind-device-with-auth";
if (g_devManage) {
CEditUI *k = static_cast<CEditUI *>(m_pm.FindControl(_T("devCardKey")));
std::wstring key = k ? k->GetText().GetData() : L"";
snprintf(body, sizeof(body), "{\"card_key\":\"%s\",\"device_id\":\"%s\"}",
W2U8(key).c_str(), g_devs[idx - 1].id);
path = "/card-unbind";
} else {
snprintf(body, sizeof(body), "{\"username\":\"%s\",\"password\":\"%s\",\"device_id\":\"%s\"}",
g_user, g_pass, g_devs[idx - 1].id);
}
char msg[512] = {0};
tip->SetText(L"正在解绑…");
if (api_post_sibling(path, body, msg, sizeof(msg))) {
if (g_devManage) {
tip->SetText(L"解绑成功");
ShowManageDevices();
} else {
tip->SetText(L"解绑成功,正在重试登录…");
HideOverlays();
DoLogin();
}
} else {
tip->SetText(U8(msg).c_str());
}
}
// ---------------- 后台开关 → 界面 ----------------
void FetchAppInfo() {
char buf[8192] = {0};
if (!api_get_sibling("/info", buf, sizeof(buf))) return;
char v[256];
if (json_str(buf, "name", v, sizeof(v)) && v[0])
snprintf(g_name, sizeof(g_name), "%s", v);
if (json_str(buf, "billing_type", v, sizeof(v)) && v[0])
snprintf(g_billing, sizeof(g_billing), "%s", v);
if (json_str(buf, "password_reset_method", v, sizeof(v)) && v[0])
snprintf(g_resetMethod, sizeof(g_resetMethod), "%s", v);
g_allowRegister = json_bool(buf, "allow_register", 1);
g_regVerify = json_bool(buf, "enable_register_verify", 0);
g_allowReset = json_bool(buf, "enable_password_reset", 0);
g_enableTrial = json_bool(buf, "enable_trial", 0);
g_maxDevices = json_int(buf, "max_devices", 1);
if (json_str(buf, "login_mode", v, sizeof(v)) && v[0])
snprintf(g_loginMode, sizeof(g_loginMode), "%s", v);
g_trialDays = json_int(buf, "trial_days", 0);
g_infoLoaded = 1;
ApplyAppInfo();
}
void ApplyAppInfo() {
if (!g_infoLoaded) return;
// 应用名以服务器为准
if (CLabelUI *p = static_cast<CLabelUI *>(m_pm.FindControl(_T("lblApp"))))
p->SetText(U8(g_name).c_str());
// 注册:后台关掉就整条 tab 拿掉
if (!g_allowRegister) {
HideByName("tabRegister"); HideByName("panelRegister");
if (CEditUI *b = static_cast<CEditUI *>(m_pm.FindControl(_T("regTip")))) (void)b;
if (CLabelUI *t = static_cast<CLabelUI *>(m_pm.FindControl(_T("regTip"))))
{ t->SetTextColor(0xFF8A8F99); t->SetText(L"本应用未开放注册"); }
} else if (!g_regVerify) {
// 不需要邮箱验证:把「邮箱验证码」整行收起来,注册只要账号+密码
HideByName("lblRegCode"); HideByName("regCode"); HideByName("btnSendCode");
if (CLabelUI *t = static_cast<CLabelUI *>(m_pm.FindControl(_T("regTip"))))
{ t->SetTextColor(0xFF8A8F99); t->SetText(L"本应用注册无需邮箱验证"); }
}
// 忘记密码:后台没启用就是 0 个入口,别放个点了报错的按钮
if (!g_allowReset) {
HideByName("tabReset"); HideByName("panelReset");
} else if (CLabelUI *t = static_cast<CLabelUI *>(m_pm.FindControl(_T("resetTip")))) {
t->SetTextColor(0xFF8A8F99);
if (!strcmp(g_loginMode, "card"))
t->SetText(L"填验证码 = 绑定邮箱找回;不填验证码 = 直接用卡密改密码");
else
t->SetText(strcmp(g_resetMethod, "email") ? L"验证码将发送到绑定手机" : L"验证码将发送到注册邮箱");
}
// 登录方式:单卡密模式下把密码/记住账号收起,输入框直接写「卡密」
bool cardOnly = !strcmp(g_loginMode, "card");
if (cardOnly) {
if (CLabelUI *l = static_cast<CLabelUI *>(m_pm.FindControl(_T("lblUser")))) l->SetText(L"卡密");
HideByName("lblPass"); HideByName("editPass"); HideByName("rowRemember");
if (CButtonUI *b = static_cast<CButtonUI *>(m_pm.FindControl(_T("btnLogin")))) b->SetText(L"卡密登录");
// 注册是账号专属;「忘记密码」在卡密模式下改造成「找回/绑定」(卡密 + 邮箱 + 验证码 + 新密码)
HideByName("panelRegister");
if (CButtonUI *t = static_cast<CButtonUI *>(m_pm.FindControl(_T("tabRegister")))) {
t->SetVisible(true);
t->SetText(L"我的设备");
}
if (CButtonUI *t = static_cast<CButtonUI *>(m_pm.FindControl(_T("tabReset")))) {
t->SetVisible(true);
t->SetText(L"找回/绑定");
}
if (CControlUI *c = m_pm.FindControl(_T("lblResetCard"))) c->SetVisible(true);
if (CControlUI *c = m_pm.FindControl(_T("resetCardKey"))) c->SetVisible(true);
} else if (CLabelUI *l = static_cast<CLabelUI *>(m_pm.FindControl(_T("lblUser")))) {
l->SetText(!strcmp(g_loginMode, "both") ? L"账号或卡密" : L"账号");
}
if (!strcmp(g_loginMode, "account")) { /* 账号模式保持原样 */ }
// 免费/试用模式没有余额概念,卡密充值不出现
if (!strcmp(g_billing, "free")) {
HideByName("tabCard"); HideByName("panelCard");
}
// 当前 tab 若已被隐藏,退回登录
if (g_tab == 1 && (!g_allowRegister || 0)) SwitchTab(0);
if (g_tab == 3 && !g_allowReset) SwitchTab(0);
if (g_tab == 2 && !strcmp(g_billing, "free")) SwitchTab(0);
}
void HideByName(const char *name) {
if (CControlUI *c = m_pm.FindControl(U8(name).c_str())) c->SetVisible(false);
}
// ---------------- 验证码倒计时 ----------------
void StartCodeCountdown() {
g_codeLeft = 60;
::SetTimer(m_hWnd, 2, 1000, NULL);
UpdateCodeButtons();
}
void UpdateCodeButtons() {
char label[32];
if (g_codeLeft > 0) snprintf(label, sizeof(label), "%ds", g_codeLeft);
const char *names[2] = { "btnSendCode", "btnSendCode2" };
for (int i = 0; i < 2; i++) {
CButtonUI *b = static_cast<CButtonUI *>(m_pm.FindControl(U8(names[i]).c_str()));
if (!b) continue;
b->SetText(g_codeLeft > 0 ? U8(label).c_str() : L"发送验证码");
b->SetEnabled(g_codeLeft <= 0);
}
}
void DoSendCode() {
CEditUI *e = static_cast<CEditUI *>(m_pm.FindControl(_T("regEmail")));
CLabelUI *tip = static_cast<CLabelUI *>(m_pm.FindControl(_T("regTip")));
if (!e || !tip) return;
std::wstring email = e->GetText().GetData();
if (email.empty()) { tip->SetText(L"请先填邮箱"); return; }
char msg[512] = {0};
if (api_send_code(W2U8(email).c_str(), !strcmp(g_loginMode, "card") ? "bind_email" : "reset_password", msg, sizeof(msg))) StartCodeCountdown();
tip->SetText(U8(msg).c_str());
}
// 自绘勾选框:选中时方框填充主色(老 DuiLib 没有勾选图片资源,只能用色块表达)
// 输入框聚焦描边:DuiLib 会把自己认为的焦点控件记在 paint manager 上,
// 轮询它就能知道该给哪个 Edit 描边(老版本 DuiLib 没有 focusbordercolor 属性)
void UpdateFocusRing() {
CControlUI *focused = m_pm.GetFocus();
static const char *names[] = {
"editUser", "editPass", "regUser", "regEmail", "regCode", "regPass", "regPass2",
"cardUser", "cardKey", "resetEmail", "resetCode", "resetPass", "resetCardKey",
"devIdx", "devCardKey"
};
const int n = (int)(sizeof(names) / sizeof(names[0]));
DWORD accent = theme_accent(g_theme);
for (int i = 0; i < n; i++) {
CControlUI *c = m_pm.FindControl(U8(names[i]).c_str());
if (!c) continue;
bool on = (CControlUI *)c == focused;
DWORD want = on ? accent : m_editBorder[i]; // 失焦时还原皮肤原本的边框色
if (c->GetBorderColor() != want) {
c->SetBorderColor(want);
c->SetBorderSize(on ? 2 : 1);
c->Invalidate();
}
}
}
void CaptureBorders() {
static const char *names[] = {
"editUser", "editPass", "regUser", "regEmail", "regCode", "regPass", "regPass2",
"cardUser", "cardKey", "resetEmail", "resetCode", "resetPass", "resetCardKey",
"devIdx", "devCardKey"
};
for (int i = 0; i < 15; i++) {
CControlUI *c = m_pm.FindControl(U8(names[i]).c_str());
m_editBorder[i] = c ? c->GetBorderColor() : 0;
}
}
void UpdateRememberButton() {
if (CButtonUI *b = static_cast<CButtonUI *>(m_pm.FindControl(_T("btnRemember"))))
b->SetText(g_remember ? L"[ ✓ ] 记住账号" : L"[ ] 记住账号");
}
void DoLogin() {
CEditUI *pUser = static_cast<CEditUI *>(m_pm.FindControl(_T("editUser")));
CEditUI *pPass = static_cast<CEditUI *>(m_pm.FindControl(_T("editPass")));
CLabelUI *pTip = static_cast<CLabelUI *>(m_pm.FindControl(_T("lblTip")));
CButtonUI *pBtn = static_cast<CButtonUI *>(m_pm.FindControl(_T("btnLogin")));
if (!pUser || !pPass || !pTip) return;
std::wstring user = pUser->GetText().GetData();
std::wstring pass = pPass->GetText().GetData();
if (user.empty()) {
pTip->SetText(!strcmp(g_loginMode, "card") ? L"请输入卡密" : L"请输入账号或卡密");
return;
}
if (pass.empty() && strcmp(g_loginMode, "card")) {
if (!strcmp(g_loginMode, "both")) {
// 密码留空 = 按卡密登录,直接把输入当卡密
} else {
pTip->SetText(L"请输入密码");
return;
}
}
SaveAccount(user, g_remember);
snprintf(g_user, sizeof(g_user), "%s", W2U8(user).c_str());
snprintf(g_pass, sizeof(g_pass), "%s", W2U8(pass).c_str());
if (pBtn) { pBtn->SetText(L"验证中…"); pBtn->SetEnabled(false); }
pTip->SetText(L"正在连接验证服务器…");
char msg[1024] = {0};
int ok = api_login(W2U8(user).c_str(), W2U8(pass).c_str(), msg, sizeof(msg));
if (ok) {
g_logged_in = 1;
pTip->SetText(L"验证成功,正在启动程序…");
::SetTimer(m_hWnd, 1, 600, NULL);
} else if (strstr(g_lastResp, "DEVICE_LIMIT_EXCEEDED")) {
ShowDevicePanel();
if (pBtn) {
pBtn->SetText(!strcmp(g_loginMode, "card") ? L"卡密登录" : L"登 录");
pBtn->SetEnabled(true);
}
} else {
std::wstring tipText = U8(msg);
if (tipText.find(L"设备") != std::wstring::npos && tipText.find(L"上限") != std::wstring::npos) {
wchar_t extra[128];
swprintf(extra, 128, L"(本应用上限 %d 台,可在官网「我的设备」解绑后重试)", g_maxDevices);
tipText += extra;
}
pTip->SetText(tipText.c_str());
if (pBtn) {
pBtn->SetText(!strcmp(g_loginMode, "card") ? L"卡密登录" : L"登 录");
pBtn->SetEnabled(true);
}
}
}
LRESULT HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam) override {
if (uMsg == WM_CREATE) {
m_pm.Init(m_hWnd);
// 之前 font="1"/font="2" 全是未定义的 id,全走默认字体 → 层级全平。
// 这里把三档字体显式注册:0=正文 1=小标题/按钮 2=大标题
m_pm.SetDefaultFont(L"Microsoft YaHei UI", 12, false, false, false);
m_pm.AddFont(1, L"Microsoft YaHei UI", 14, true, false, false);
m_pm.AddFont(2, L"Microsoft YaHei UI", 19, true, false, false);
CDialogBuilder builder;
std::wstring xml = U8(m_skin);
CControlUI *pRoot = builder.Create(xml.c_str(), (UINT)0, NULL, &m_pm);
if (!pRoot) { ::MessageBoxW(m_hWnd, L"界面加载失败", L"验证", MB_ICONERROR); return 0; }
m_pm.AttachDialog(pRoot);
m_pm.AddNotifier(this);
if (CLabelUI *p = static_cast<CLabelUI *>(m_pm.FindControl(_T("lblApp"))))
p->SetText(U8(g_name).c_str());
std::wstring devText = L"设备 ";
devText += U8(g_device);
if (CLabelUI *p = static_cast<CLabelUI *>(m_pm.FindControl(_T("lblDevice"))))
p->SetText(devText.c_str());
bool remember = false;
std::wstring saved = LoadAccount(remember);
g_remember = remember;
UpdateRememberButton();
#ifdef VFY_DEBUG
{
HANDLE f = ::CreateFileW(L"C:\\vfy_layout.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
if (f != INVALID_HANDLE_VALUE) {
std::string dump;
const wchar_t *names[] = { L"lblApp", L"panelLogin", L"btnLogin", L"lblTip", L"lblDevice", L"tabLogin" };
for (int i = 0; i < 6; i++) {
CControlUI *c = m_pm.FindControl(names[i]);
if (!c) { dump += "missing\n"; continue; }
RECT r = c->GetPos();
char line[256];
snprintf(line, sizeof(line), "%ls: top=%ld bottom=%ld h=%ld fixed=%d visible=%d\n",
names[i], r.top, r.bottom, r.bottom - r.top, c->GetFixedHeight(), (int)c->IsVisible());
dump += line;
}
RECT wr; ::GetWindowRect(m_hWnd, &wr);
char l2[128]; snprintf(l2, sizeof(l2), "window: %ld x %ld\n", wr.right - wr.left, wr.bottom - wr.top);
dump += l2;
DWORD wr2 = 0; ::WriteFile(f, dump.c_str(), (DWORD)dump.size(), &wr2, NULL); ::CloseHandle(f);
}
}
#endif
RECT rc = {0};
::GetClientRect(m_hWnd, &rc);
m_iWidth = rc.right - rc.left;
CControlUI *lp = m_pm.FindControl(_T("panelLogin"));
int loginH = lp ? lp->GetFixedHeight() : 0;
if (loginH > 0) m_chromeH = (rc.bottom - rc.top) - loginH;
SwitchTab(0);
CaptureBorders();
::SetTimer(m_hWnd, 4, 150, NULL); // 焦点描边轮询
FetchAppInfo(); // 按后台设置裁剪界面(注册/重置/充值 tab、注册验证码)
CheckUpdate(); // 有强制更新就先拦更新页
if (!g_overlay) LoadNotices(); // 没有强制更新再看公告
if (CEditUI *pUser = static_cast<CEditUI *>(m_pm.FindControl(_T("editUser")))) {
if (!saved.empty()) pUser->SetText(saved.c_str());
pUser->SetFocus();
}
return 0;
}
if (uMsg == WM_TIMER && wParam == 4) {
UpdateFocusRing();
return 0;
}
if (uMsg == WM_TIMER && wParam == 3) {
::KillTimer(m_hWnd, 3);
FitWindowToFooter(22);
return 0;
}
if (uMsg == WM_TIMER && wParam == 2) {
if (g_codeLeft > 0) g_codeLeft--;
if (g_codeLeft <= 0) { g_codeLeft = 0; ::KillTimer(m_hWnd, 2); }
UpdateCodeButtons();
return 0;
}
if (uMsg == WM_TIMER && wParam == 1) {
::KillTimer(m_hWnd, 1);
::ShowWindow(m_hWnd, SW_HIDE);
if (g_oep) g_oep();
::PostQuitMessage(0);
return 0;
}
if (uMsg == WM_DESTROY) { ::KillTimer(m_hWnd, 4); ::PostQuitMessage(0); return 0; }
LRESULT lr = 0;
if (m_pm.MessageHandler(uMsg, wParam, lParam, lr)) return lr;
return CWindowWnd::HandleMessage(uMsg, wParam, lParam);
}
CPaintManagerUI m_pm;
const char *m_skin;
DWORD m_editBorder[15] = {0};
int m_chromeH = 0; // 除面板外的固定高度(标题栏 + tab 行 + 页脚)
int m_iWidth = 0;
int m_iMinH = 380;
};
static int RunShell(void *oep) {
g_oep = (PFN_OEP)oep;
const SkinDef *sk = skin_for(g_theme);
CPaintManagerUI::SetInstance(::GetModuleHandle(NULL));
::CoInitialize(NULL);
CVerifyWnd wnd(sk->xml);
UINT style = WS_POPUP | WS_CLIPCHILDREN;
UINT exstyle = WS_EX_TOPMOST | WS_EX_APPWINDOW;
wnd.Create(NULL, L"软件授权验证", style, exstyle, 0, 0, sk->w, sk->h);
wnd.CenterWindow();
::ShowWindow(wnd, SW_SHOW);
CPaintManagerUI::MessageLoop();
::CoUninitialize();
return g_logged_in ? 0 : 6;
}
/* ---------------------------- 对外接口 ---------------------------- */
// 从 api 地址里抽 appKey:.../api/v1/app/<key>/login
static void extract_appkey(const char *api, char *out, int cap) {
out[0] = 0;
const char *p = strstr(api, "/app/");
if (!p) return;
p += 5;
const char *e = strchr(p, '/');
int n = e ? (int)(e - p) : (int)strlen(p);
if (n <= 0 || n >= cap) return;
memcpy(out, p, n); out[n] = 0;
}
static void load_cfg(const char *json) {
snprintf(g_cfg, sizeof(g_cfg), "%s", json ? json : "");
json_str(g_cfg, "api", g_api, sizeof(g_api));
json_str(g_cfg, "name", g_name, sizeof(g_name));
g_deviceAuto = json_int(g_cfg, "device_auto", 1);
char mid[64] = {0};
make_machine_id(mid, sizeof(mid));
snprintf(g_instance, sizeof(g_instance), "%s", mid);
if (!json_str(g_cfg, "device", g_device, sizeof(g_device)) || !g_device[0]) {
if (g_deviceAuto) snprintf(g_device, sizeof(g_device), "%s", mid);
else snprintf(g_device, sizeof(g_device), "%s", "UNKNOWN-DEVICE");
}
if (!json_str(g_cfg, "theme", g_theme, sizeof(g_theme))) snprintf(g_theme, sizeof(g_theme), "dark");
// 目标程序版本:只有加壳时登记过来源版本才会有值,空则不做更新比对
if (!json_str(g_cfg, "ver", g_ver, sizeof(g_ver))) g_ver[0] = 0;
extract_appkey(g_api, g_appkey, sizeof(g_appkey));
}
#ifdef SHELL_EXE
int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR lpCmdLine, int) {
const char *cfg = (lpCmdLine && lpCmdLine[0]) ? lpCmdLine : getenv("VFY_CFG");
if (!cfg || !cfg[0]) cfg = "{\"theme\":\"dark\"}";
load_cfg(cfg);
return RunShell(NULL);
}
#else
extern "C" __declspec(dllexport) int VerifyMain(void *oep, const char *cfgjson) {
load_cfg(cfgjson);
return RunShell(oep);
}
extern "C" __declspec(dllexport) int VerifyShellVersion(void) { return 9; }
extern "C" __declspec(dllexport) const char *VerifyShellThemes(void) {
return "dark,light,split,card,industrial,terminal,compact";
}
BOOL WINAPI DllMain(HINSTANCE h, DWORD reason, LPVOID) {
if (reason == DLL_PROCESS_ATTACH) DisableThreadLibraryCalls(h);
return TRUE;
}
#endif