Add native client with image adjustment and AI hybrid intent mode

Switch to WebView2 host with embedded resources, save chat images by order, and support buyer photo replace/delete via rules, dHash matching, and optional model-assisted intent parsing.
This commit is contained in:
zhangyu
2026-11-11 02:19:26 +08:00
parent acf2f659d1
commit 2b55aa5a44
77 changed files with 56999 additions and 138 deletions
+6
View File
@@ -7,7 +7,13 @@ logs/
# Real deployment secrets and shop-specific credentials.
config/shops.json
config/shops/
config/mail.json
# Optional local runtime files.
*.pid
# Native build outputs and downloaded packages.
native/bin/
native/packages/
dist/
+47 -52
View File
@@ -1,74 +1,69 @@
[
{
"id": 1,
"name": "汉鼎螺纹钢鲢鳙",
"aliases": ["螺纹钢鲢","鲢鳙杆"],
"name": "证件照打印 一寸二寸",
"aliases": ["一寸照", "二寸照", "证件照", "换底色"],
"attributes": {
"品牌": "汉鼎",
"适用": "台钓、黑坑、鲢鳙杆",
"售后-配节": "找本店售后,如有损坏,凭照片免费全杆配节,但需要用户付10元运费",
"赠品": "无备用竿稍,无赠品",
"售后-退货": "不支持下水试用",
"硬度": "4.5H",
"包装": "硬纸筒包装"
"规格": "一寸 25×35mm、二寸 35×49mm,可按考试或办证用途排版",
"底色": "白底、蓝底、红底都能换",
"像素要求": "建议人像清晰、正面免冠,原图不低于 600×800 像素",
"工艺": "高清冲印,含裁切排版",
"发货时效": "下单后 48 小时内发出,节假日顺延",
"包装": "硬卡纸加防水袋包装",
"售后-补印": "打印模糊、明显划痕、裁切错误、明显偏色的,凭问题照片核实后免费补印;轻微色差、拍错尺寸或张数不属于质量问题"
}
},
{
"id": 2,
"name": "汉鼎螺纹钢极轻小综合",
"aliases": ["螺纹钢极", "小综合竿","鲫鱼竿"],
"name": "照片冲印 5寸6寸7寸",
"aliases": ["洗照片", "冲印", "5寸照片", "6寸照片"],
"attributes": {
"品牌": "汉鼎",
"适用": "台钓、鲫鱼",
"售后-配节": "找本店售后,如有损坏,凭照片免费全杆配节,但需要用户付10元运费",
"赠品": "无备用竿稍,无赠品",
"售后-退货": "不支持下水试用",
"硬度": "3.5H",
"包装": "硬纸筒包装"
"规格": "5寸 89×127mm、6寸 102×152mm、7寸 127×178mm",
"相纸": "富士、柯达相纸,光面与绒面可选",
"像素要求": "5寸建议不低于 1280×960,6寸不低于 1440×1080",
"工艺": "原图调色后冲印,可按需留白边",
"发货时效": "下单后 48 小时内发出,节假日顺延",
"包装": "防水袋加硬纸板,避免折痕",
"售后-补印": "打印模糊、明显划痕、裁切错误、明显偏色的,凭问题照片核实后免费补印;轻微色差、拍错尺寸或张数不属于质量问题"
}
}
,
{
},
{
"id": 3,
"name": "烈火战马pro湖库野钓杆",
"aliases": ["湖库", "小综合竿"],
"name": "照片书 相册定制",
"aliases": ["照片书", "相册", "DIY相册", "纪念册"],
"attributes": {
"品牌": "烈火战马",
"适用": "台钓、黑坑",
"售后-配节": "本店旗舰店皆可售后,凭竿身电子保卡条形码可以免费配一节,手把除外;后续配节成本价10-30一节越粗越贵,手把60;运费15一次(包含首次)",
"赠品": "无备用竿稍,无赠品",
"硬度": "4H",
"售后-退货": "不支持下水试用",
"包装": "礼盒包装"
"规格": "软壳、硬壳,常规 20 页 / 30 页",
"容量": "按每页 2 张估算,20 页约 40 张,30 页约 60 张",
"工艺": "高清印刷,内页覆膜,可协助排版",
"制作周期": "下单后 3-5 天制作,制作完成后 48 小时内发出",
"包装": "气泡袋加纸箱",
"售后-补印": "印刷漏页、装订错位、明显印刷瑕疵的,凭照片核实后免费重做;轻微色差和买家确认过的排版不在重做范围"
}
}
,
},
{
"id": 4,
"name": "汉鼎螺纹钢宗综合杆",
"aliases": ["螺纹钢宗", "综合竿"],
"name": "海报写真打印 A4A3",
"aliases": ["海报", "写真", "A3打印", "A4打印"],
"attributes": {
"品牌": "汉鼎",
"适用": "台钓、鲫鱼",
"售后-配节": "找本店售后,如有损坏,凭照片免费全杆配节,但需要用户付10元运费",
"赠品": "无备用竿稍,无赠品",
"售后-退货": "不支持下水试用",
"硬度": "4.5H",
"包装": "硬纸筒包装"
"规格": "A4、A3、A2,可按需裁切",
"工艺": "写真机打印,可选覆膜",
"像素要求": "原图建议 300dpi,尺寸越大越需要高清原图",
"发货时效": "下单后 48 小时内发出,节假日顺延",
"包装": "卷筒或硬纸板平铺包装",
"售后-补印": "打印模糊、明显划痕、裁切错误、明显偏色的,凭问题照片核实后免费补印;轻微色差、拍错尺寸或张数不属于质量问题"
}
}
,
},
{
"id": 4,
"name": "汉鼎卓越小综合",
"aliases": ["小综合", "螺纹钢卓越"],
"id": 5,
"name": "照片塑封 过塑",
"aliases": ["塑封", "过塑", "过胶", "封膜"],
"attributes": {
"品牌": "汉鼎",
"售后-配节": "找本店售后,如有损坏,凭照片免费全杆配节,但需要用户付10元运费",
"赠品": "带备用竿稍,无其他赠品",
"售后-退货": "不支持下水试用",
"硬度": "3.5H",
"包装": "硬纸筒包装"
"规格": "5寸、6寸、7寸、A4 均可塑封",
"工艺": "热压过塑,可选圆角",
"效果": "防水、防折、表面耐刮",
"发货时效": "下单后 48 小时内发出,节假日顺延",
"包装": "防水袋加硬纸板",
"售后-补印": "打印模糊、明显划痕、裁切错误、明显偏色的,凭问题照片核实后免费补印;轻微色差、拍错尺寸或张数不属于质量问题"
}
}
]
+2 -3
View File
@@ -1,5 +1,4 @@
你是一个专业的拼多多商家后台的客服,你经营的店铺主营渔具,你了解汉鼎、烈火战马等钓竿的各个型号的详细信息。你是资深钓鱼玩家,懂得钓鱼专业术语。你必须基于商品配置、FAQ、真实对话示例和聊天上下文回复,不可虚构参数。
你是一个专业的拼多多商家后台的客服,你经营的店铺是一家照片打印店,主营证件照打印、照片冲印、照片书相册、海报写真和照片塑封。你熟悉常见尺寸、相纸、像素要求和冲印工艺。你必须基于商品配置、知识库、真实对话示例和聊天上下文回复,不可虚构参数。
规则:
- 最简短、清晰、准确的话回复,不需要客套,不要有多余的引导词句,减少"哦"等语气词,避免机械感。
@@ -11,4 +10,4 @@
- 只输出最终客服回复,不输出分析过程、JSON、标题或解释。
- 综合上下文,只回复用户的最后一条消息,且不要说之前回复过的话
- 产品参数要有明确依据,要准确,来源必须是官方数据
- 介绍产品时不要说售后、赠品相关
- 介绍产品时不要说售后、赠品相关
+54 -54
View File
@@ -1,86 +1,86 @@
[
{
"id": "tone-price-001",
"scene": "买家问售后",
"customer": "坏了能不能换新的",
"goodReply": "哥,烈火战马凭竿身电子保卡条形码可以免费配一节,手把除外;后续配节成本价10-30一节越粗越贵,手把60;运费15一次(包含首次)",
"notes": "具体型号售后不同,找到该型号的售后政策回复用户。"
"id": "tone-size-001",
"scene": "买家问证件照尺寸",
"customer": "一寸二寸都能打吗",
"goodReply": "亲,一寸二寸都能打,白底蓝底红底也可以换,您把原图发我,我帮您排版好再印。",
"notes": "证件照按用途排版,先确认尺寸和底色。"
},
{
"id": "tone-price-002",
"scene": "买家问售后",
"customer": "怎么配节",
"goodReply": "哥,汉鼎如有损坏,凭照片免费全杆配节,但需要您付10元运费就可以啦",
"notes": "具体型号售后不同,找到该型号的售后政策回复用户。"
"id": "tone-size-002",
"scene": "买家问冲印尺寸",
"customer": "5寸和6寸差多少",
"goodReply": "亲,5寸是89×127mm,6寸是102×152mm,6寸比5寸大一圈,放相册5寸够用,摆台6寸更好看。",
"notes": ""
},
{
"id": "tone-price-003",
"scene": "买家问售后",
"customer": "全国门店免费配节吗",
"goodReply": "哥,汉鼎的售后找本店,凭照片免费全杆配节,但需要您付10元运费就可以啦",
"notes": "具体型号售后不同,找到该型号的售后政策回复用户。"
"id": "tone-quality-003",
"scene": "买家担心清晰度",
"customer": "像素有点低能印清楚吗",
"goodReply": "亲,原图越清晰印出来越好,5寸建议不低于1280×960,6寸不低于1440×1080;像素偏低也能印,但放大后可能会虚,您把图发我先帮您看。",
"notes": "先看原图再判断,不直接承诺效果。"
},
{
"id": "tone-quality-004",
"scene": "买家担心真假和质量",
"customer": "是正品吗",
"goodReply": "哥,全店所有鱼竿,保证全新正品,防伪可查,假一赔十,您放心,现在就是小店刚开,不赚钱纯用成本价拉新客,全新正品这两点您就放心!",
"notes": ""
"scene": "买家问相纸",
"customer": "用的什么相纸",
"goodReply": "亲,用的是富士和柯达相纸,光面和绒面都有,光面颜色更亮,绒面不反光也不容易留指纹。",
"notes": "按商品配置里实际的相纸品牌回复。"
},
{
"id": "tone-stock-005",
"scene": "买家问是否有货",
"customer": "现在有现货吗",
"goodReply": "哥,页面能正常下单的一般都有库存,您拍就行哈",
"notes": ""
"id": "tone-quality-005",
"scene": "买家问色差",
"customer": "印出来会不会偏色",
"goodReply": "亲,冲印都会有轻微色差,屏幕和相纸的颜色不会完全一样,我们会按原图调色,偏得明显可以补印。",
"notes": "轻微色差属正常,明显偏色核实后补印。"
},
{
"id": "tone-stock-006",
"scene": "买家问发货时间",
"customer": "今天能发吗",
"goodReply": "哥,今天大概率给您发出,要是仓库忙的实在顾不上,最晚最晚明天提早给您发!",
"notes": "一般当天12点前下单,大概率当天发,12点后一般第二天发"
"goodReply": "亲,现货一般 48 小时内发出,节假日会顺延,急用的话拍前先跟我说一声。",
"notes": "下单后48小时内发出,节假日顺延。"
},
{
"id": "tone-stock-007",
"scene": "买家问运费险",
"customer": "没有运费险吗",
"goodReply": "是的哥,现在没有退货包运费,几乎成本价给您发货,就为了新店拉新客,回来的运费成本都包不住哥,但全新正品这方面您就放一百个心!",
"notes": ""
"scene": "买家要加急",
"customer": "明天要用能加急吗",
"goodReply": "亲,可以帮您加急,拍下后把要用的时间发我,我这边优先安排,具体到达时间以物流为准。",
"notes": "加急只优先安排,不承诺物流到达时间。"
},
{
"id": "tone-price-008",
"scene": "买家要优惠",
"customer": "还能便宜吗",
"goodReply": "哥,现在的价格已经找不到第二家,新店初开,都是用成本价打销量,一点也不能再优惠啦,请您见谅哈",
"notes": ""
"customer": "洗得多能便宜吗",
"goodReply": "亲,价格已经是冲印成本价了,您把张数和尺寸发我,我帮您算总价,能省的都给您省。",
"notes": "批量按张数核算,不直接打折。"
},
{
"id": "tone-price-009",
"scene": "买家要赠品",
"customer": "带竿稍吗",
"goodReply": "新店开张,所有鱼竿都是成本价冲销量,实在没有多余的利润给您赠送东西,抱歉哥",
"notes": ""
},
{
"id": "tone-quality-10",
"scene": "买家担心真假和质量",
"customer": "怎么这么便宜",
"goodReply": "哥,全店所有鱼竿,保证全新正品,防伪可查,假一赔十,您放心,现在就是小店刚开,不赚钱纯用成本价拉新客,全新正品这两点您就放心!",
"notes": ""
},
{
"id": "tone-quality-11",
"id": "tone-service-009",
"scene": "买家问售后",
"customer": "能下水吗",
"goodReply": "不支持哥,新店初开,一分钱不挣就冲销量,全新正品这两点您就放一百个心,有七天无理由退货,您尽管到手查验,但不支持下水哥,拆封退回变二手得倒贴,请您理解哈",
"notes": "7天无理由退货,但需产品礼盒与杆袋完整,未损坏;竿稍未打结,同时不支持试用;产品不能出现损坏、污染、划痕等"
"customer": "印坏了怎么办",
"goodReply": "亲,打印模糊、有明显划痕、裁切错或者偏色很明显的,您拍张问题照片发我,核实后免费补印;轻微色差和拍错尺寸这类不算质量问题哈。",
"notes": "模糊/划痕/裁切错/明显偏色免费补印,需问题照片;轻微色差、拍错尺寸不补。"
},
{
"id": "tone-quality-12",
"id": "tone-service-010",
"scene": "买家问塑封",
"customer": "照片能塑封吗",
"goodReply": "亲,可以塑封,5寸、6寸、7寸和A4都能做,还能选圆角,塑封后防水不容易折。",
"notes": ""
},
{
"id": "tone-service-011",
"scene": "买家问相册容量",
"customer": "相册能放多少张",
"goodReply": "亲,20页的相册大概放40张,30页大概放60张,您把张数发我,我帮您算要多少页。",
"notes": "按每页约2张估算。"
},
{
"id": "tone-stock-012",
"scene": "买家问发货地",
"customer": "哪里发货",
"goodReply": "威海",
"notes": ""
"goodReply": "亲,具体发货地和快递您看下商品页,急用的话我帮您确认能不能加急。",
"notes": "发货地按店铺实际填写,不虚构。"
}
]
+13
View File
@@ -0,0 +1,13 @@
CODEX_API_URL=https://api.openai.com/v1/responses
CODEX_API_KEY=sk-your-api-key
CODEX_MODEL=gpt-5.1
CODEX_CLASSIFIER_MODEL=gpt-4o-mini
CODEX_API_MODE=responses
CODEX_PROXY_URL=http://127.0.0.1:7890
PDD_MAIL_AUTH_CODE=your-smtp-auth-code
PDD_ASSISTANT_HOST=0.0.0.0
PDD_CONTROL_TOKEN=your-control-password
PDD_DAILY_PAUSE_TIME=07:50
COZE_API_BASE=https://api.coze.cn
COZE_API_TOKEN=your-coze-service-identity-token
COZE_BOT_ID=your-coze-bot-id
+13
View File
@@ -0,0 +1,13 @@
node_modules/
.env
.env.*
!.env.example
*.log
logs/
# Real deployment secrets and shop-specific credentials.
config/shops.json
config/mail.json
# Optional local runtime files.
*.pid
+544
View File
@@ -0,0 +1,544 @@
# 拼多多商家后台客服回复助手
这是一个本地运行的客服辅助工具,包含两部分:
- `extension/`:Chrome 浏览器插件,运行在拼多多商家后台客服页面中,监听待回复用户、提取聊天记录、回填回复。
- `server/`:本地 Node.js 服务,接收插件传来的会话,读取商品、FAQ、高危意图、邮件配置,并调用大模型接口或本地兜底规则生成回复。
## 当前行为
- 监听白天的 `ul.five-minute` 待回复列表,也兼容夜间的 `ul.timeout-unreply` 夜间待回复列表。
- 发现新消息后点击首个可自动处理的用户。
- 等待 `#msgListContainer` 与 `#replyTextarea` 出现后提取聊天记录,但发送给服务端时只保留 `pid` 商品信息和最近 6 条消息。
- 发送给本地服务的数据格式为:
```json
{
"pid": "汉鼎螺纹钢极轻小综合鱼竿手杆超轻硬台钓竿 螺纹钢极5.4米",
"msgList": [
{ "usertype": "cus", "msg": "客户的聊天文本" },
{ "usertype": "sys", "msg": "客服的聊天文本" }
]
}
```
- 浏览器插件不再拉取商品库,也不判断商品 ID。
- 如果历史聊天里有商品卡片,插件会读取最后一个商品卡片上的商品名;如果卡片里有型号/规格,会拼接成 `商品名 + 型号/规格` 放入 `pid`。
- 如果历史聊天里没有商品卡片,`pid` 为 `0`。
- 普通会话:
- 调试模式:只回填输入框,不自动点击发送。
- 自动模式:回填后自动点击发送。
- 高危会话:
- 服务端命中 `config/risk-intents.json` 后不生成回复。
- 服务端发送邮件给人工客服。
- 插件不会填输入框,也不会点击发送。
- 插件会跳过当前需要人工介入的用户,继续监听并处理列表中的其他新消息。
## 启动本地服务
需要 Node.js 18 或更高版本。
在 `D:\code\pdd` 目录运行:
```powershell
npm start
```
健康检查:
```text
http://127.0.0.1:3456/health
```
服务默认会读取 `config/server.json` 里的监听地址。为了让同一 WiFi 下的 iPhone 能访问控制页,当前配置使用:
```json
{
"host": "0.0.0.0",
"port": 3456
}
```
启动后控制台会打印局域网地址,例如:
```text
http://192.168.1.23:3456/control
```
如果手机打不开,请检查电脑和 iPhone 是否在同一个 WiFi,并允许 Windows 防火墙放行 Node.js 或端口 `3456`。
## 手机暂停/恢复监听
电脑保持本地服务、Chrome 插件、拼多多客服页面都打开。iPhone 连接同一个 WiFi 后,在 Safari 访问服务启动时打印的局域网控制页:
```text
http://电脑局域网IP:3456/control
```
页面里有“暂停监听”和“恢复监听”两个按钮。浏览器插件会每 1.5 秒同步一次手机端状态;插件面板里的暂停/恢复按钮仍然会本地立即生效,并异步同步给手机控制页。
如果配置了多家店铺,手机控制页会按多行展示:
```text
汉鼎主店 监听中 [暂停监听] [恢复监听]
烈火战马店 已暂停 [暂停监听] [恢复监听]
```
可选:如果想给手机控制页加密码,在 `.env` 或 `config/server.json` 里设置:
```text
PDD_CONTROL_TOKEN=你的控制密码
```
然后手机访问:
```text
http://电脑局域网IP:3456/control?token=你的控制密码
```
## 安装浏览器插件
1. 打开 Chrome 扩展管理页:
```text
chrome://extensions/
```
2. 打开“开发者模式”。
3. 点击“加载已解压的扩展程序”。
4. 选择:
```text
D:\code\pdd\extension
```
5. 回到拼多多客服页面并刷新。
## 多店铺配置
服务端店铺配置文件:
```text
D:\code\pdd\config\shops.json
```
示例:
```json
[
{
"id": "handing-main",
"name": "汉鼎主店",
"pluginToken": "9f8f2f5b60d04e11a4e7b43d7a8f3c91",
"cozeApiBase": "https://api.coze.cn",
"cozeApiToken": "扣子服务身份凭证",
"cozeApiTokenEnv": "",
"cozeBotId": "扣子智能体ID"
},
{
"id": "liehuo-main",
"name": "烈火战马店",
"pluginToken": "2f80ab0936914e12a1ef90e2b24f16c8",
"cozeApiBase": "https://api.coze.cn",
"cozeApiToken": "扣子服务身份凭证",
"cozeApiTokenEnv": "",
"cozeBotId": "扣子智能体ID"
}
]
```
`pluginToken` 是你自己设置的店铺访问密码。可以用 PowerShell 生成:
```powershell
[guid]::NewGuid().ToString("N")
```
每个 Chrome 用户资料夹登录一个拼多多店铺,并在插件面板点击“配置”,分别填写:
```text
服务地址:http://127.0.0.1:3456
店铺ID:handing-main
店铺名:汉鼎主店
店铺Token:shops.json 里 handing-main 对应的 pluginToken
```
迁移到云服务器后,服务地址改成你的云端地址,例如:
```text
https://pdd-ai.example.com
```
插件每次请求都会带 `shopId` 和店铺 Token。服务端会校验通过后,才允许该插件读取对应店铺的控制状态或调用回复接口。
普通售前回复会优先调用店铺对应的 Coze 智能体。推荐不要把真实 Coze Token 直接写进仓库,可以使用环境变量:
```json
{
"id": "handing-main",
"name": "汉鼎主店",
"pluginToken": "店铺Token",
"cozeApiBase": "https://api.coze.cn",
"cozeApiTokenEnv": "COZE_TOKEN_HANDING",
"cozeBotId": "扣子智能体ID"
}
```
启动服务前设置:
```powershell
$env:COZE_TOKEN_HANDING="你的扣子服务身份凭证"
npm start
```
如果 `cozeApiToken/cozeApiTokenEnv/cozeBotId` 没有配置完整,服务端会回退到原来的模型接口或本地兜底回复。
## 每日自动关闭监听
服务端会在每天 `07:50` 自动把所有店铺切换为暂停监听。配置位置:
```text
D:\code\pdd\config\server.json
```
```json
{
"dailyPauseTime": "07:50"
}
```
也可以用环境变量覆盖:
```text
PDD_DAILY_PAUSE_TIME=07:50
```
注意:这个时间使用服务器本地时区。部署到 Ubuntu 后建议设置为上海时区:
```bash
sudo timedatectl set-timezone Asia/Shanghai
timedatectl
```
## 邮件配置
邮件配置文件:
```text
D:\code\pdd\config\mail.json
```
默认不会发送邮件。启用时把 `enabled` 改为 `true`,并设置收件人:
```json
{
"enabled": true,
"provider": "qq",
"host": "smtp.qq.com",
"port": 465,
"secure": true,
"startTls": false,
"user": "your-email@qq.com",
"authCodeEnv": "PDD_MAIL_AUTH_CODE",
"from": "your-email@qq.com",
"senderName": "PDD客服助手",
"to": ["owner@example.com"],
"subjectPrefix": "[PDD客服高危会话]",
"dedupMs": 600000
}
```
推荐用环境变量保存邮箱 SMTP 授权码:
```powershell
$env:PDD_MAIL_AUTH_CODE="你的邮箱SMTP授权码"
npm start
```
更多示例见 [docs/email-config.md](D:/code/pdd/docs/email-config.md)。
## 商品配置
编辑 `config/products.json`:
```json
[
{
"id": 1,
"name": "商品完整标题",
"aliases": ["短名称", "关键词", "页面卡片可能出现的词"],
"attributes": {
"品牌": "品牌名",
"售后": "按店铺页面与平台规则执行"
}
}
]
```
商品配置现在由服务端传给大模型作为商品知识,不再由浏览器插件读取。配置变更后,重启本地服务。
## FAQ配置
编辑 `config/faq.json`:
```json
[
{
"id": "price-001",
"productId": 1,
"keywords": ["便宜", "优惠", "少点"],
"answer": "您好,{{商品名}}目前按页面活动价为准,能用的优惠会在下单页自动抵扣。"
}
]
```
`productId` 可选。不填时表示通用 FAQ。
## 真实对话与语气示例
把真实客服对话、希望模型学习的表达风格放在:
```text
D:\code\pdd\config\tone-examples.json
```
示例:
```json
[
{
"id": "tone-price-001",
"scene": "买家问能否便宜",
"customer": "这个还能便宜点吗",
"goodReply": "您好,目前就是页面活动价,能用的优惠会在下单页自动抵扣,您可以放心拍。",
"notes": "语气自然,不承诺额外优惠。"
}
]
```
这些不是训练数据上传,而是每次请求时作为参考样例传给大模型。建议放 10 到 30 条高质量示例,覆盖常见场景。
## 全局回复规则
编辑:
```text
D:\code\pdd\config\reply-guidelines.md
```
这里适合写全局语气要求、禁用话术、平台规则边界、售后表达规范等。
## 高危意图配置
编辑 `config/risk-intents.json`:
```json
[
{
"name": "平台外交易",
"keywords": ["微信", "vx", "qq", "支付宝", "私下"]
}
]
```
命中后不会发送 `reply`,而是返回:
```json
{
"action": "manual",
"manualRequired": true,
"reply": "",
"riskIntents": ["平台外交易"]
}
```
## 人工接手白名单
编辑:
```text
D:\code\pdd\config\manual-handoff-whitelist.json
```
示例:
```json
[
{
"name": "退款退货",
"semantics": "买家表达退款、退货、退换货、取消订单、仅退款、退差价等诉求。",
"keywords": ["退款", "退货", "退换", "仅退款", "退差价", "取消订单"]
},
{
"name": "商品损坏",
"semantics": "买家表示商品坏了、断了、裂了、破损、不能用、收到后有问题。",
"keywords": ["坏了", "断了", "裂了", "破损", "不能用", "有问题"]
}
]
```
服务端会先用现有高危意图规则兜底,然后调用大模型根据上下文判断是否命中人工接手白名单。命中后:
- 不生成回复。
- 不回填输入框。
- 复用 `config/mail.json` 发送邮件。
- 插件继续监听其他新消息。
如果模型分类失败,但最近客户消息明显命中 `keywords`,服务端会用关键词兜底转人工。
## 快捷固定回复
编辑:
```text
D:\code\pdd\config\quick-replies.json
```
当前内置:
```json
[
{
"name": "问候",
"match": "exact",
"keywords": ["你好", "您好", "在吗", "在"],
"reply": "您好,请问有什么需要帮忙的?"
},
{
"name": "确认",
"match": "exact",
"keywords": ["好的", "行", "ok", "OK", "好"],
"reply": "🌹"
}
]
```
快捷回复在高危判断和大模型调用之前执行,命中后不消耗模型 token。
## 大模型接口配置
默认 `config/server.json` 没有配置模型接口,服务会走本地 FAQ/规则兜底,方便先测试链路。
### 智增增 API
如果使用智增增的 OpenAI 兼容接口,推荐在 `.env` 中配置:
```text
CODEX_API_URL=https://api.zhizengzeng.com/v1/chat/completions
ZZZ_API_KEY=你的智增增API Key
CODEX_MODEL=你在智增增后台可用的模型名
CODEX_CLASSIFIER_MODEL=你在智增增后台可用的轻量模型名
CODEX_API_MODE=chat
```
如果之前为了访问 OpenAI 配过本地代理,但智增增可以直连,可以删除或注释:
```text
CODEX_PROXY_URL=...
```
改完后重启本地服务。
### OpenAI API
如果使用 OpenAI Responses API,可设置:
```powershell
$env:CODEX_API_URL="https://api.openai.com/v1/responses"
$env:CODEX_API_KEY="你的OpenAI API Key"
$env:CODEX_MODEL="gpt-5.1"
$env:CODEX_API_MODE="responses"
npm start
```
也可以把这些变量写到项目根目录的 `.env` 文件里,服务启动时会自动读取:
```text
CODEX_API_URL=https://api.openai.com/v1/responses
CODEX_API_KEY=你的OpenAI API Key
CODEX_MODEL=gpt-5.1
CODEX_CLASSIFIER_MODEL=gpt-4o-mini
CODEX_API_MODE=responses
# 如果你的电脑需要通过本地代理访问 OpenAI,例如 Clash 常见端口 7890,可加:
# CODEX_PROXY_URL=http://127.0.0.1:7890
```
或者编辑 `config/server.json`:
```json
{
"port": 3456,
"apiMode": "responses",
"codexApiUrl": "https://api.openai.com/v1/responses",
"codexModel": "gpt-5.1",
"mockWhenNoApiKey": true,
"modelTimeoutMs": 45000
}
```
说明:
- `CODEX_API_URL` 是模型接口地址。
- `CODEX_API_KEY` 是接口密钥。
- `CODEX_MODEL` 是模型名称。
- `CODEX_API_MODE=responses` 会发送 `{ model, input: [...] }` 格式。
- 当前变量名保留 `CODEX_` 是为了兼容你最初说的 Codex/API 服务;接 OpenAI API 时同样可用。
## 页面选择器
当前插件使用的关键页面结构:
```js
urgentLists: ["ul.five-minute", "ul.timeout-unreply"]
messageList: "#msgListContainer"
replyTextarea: "#replyTextarea"
sendButton: ".send-btn"
```
如果拼多多页面结构变化,优先修改 `extension/content.js` 顶部的 `selectors`。
## 建议流程
1. 先不配置大模型,只启动本地服务,确认插件能监听、提取、回填。
2. 配好商品、FAQ、高危意图。
3. 开启邮件配置,测试高危会话是否能收到邮件。
4. 接入大模型接口。
5. 先用调试模式观察回复质量,再切换自动模式。
## Token成本优化
服务端不会再把所有配置每次都发给大模型,而是先在本地检索和裁剪:
- 商品资料:只传和 `pid` 最相关的前 3 个商品候选。
- FAQ:只传和最近消息、商品信息相关的前 5 条。
- 真实语气示例:只传最相关的前 3 条。
- 全局回复规则:默认最多传 1200 个字符。
- 高危意图:回复模型只接收规则名称,不接收完整配置。
- 邮件配置:不会传给回复模型。
- 人工接手分类:本地明确命中关键词就直接转人工;命中排除词就直接放行;只有模糊场景才调用分类模型。
这些数量可在 `config/server.json` 中调整:
```json
{
"manualHandoffClassifierMode": "ambiguous",
"maxProductCandidates": 3,
"maxFaqItems": 5,
"maxToneExamples": 3,
"maxReplyGuidelinesChars": 1200,
"minReplyDelayMs": 3000
}
```
`minReplyDelayMs` 会让服务端从收到请求开始至少等待指定毫秒数再返回回复,默认 3000,降低机器感。
`manualHandoffClassifierMode` 可选:
- `ambiguous`:默认,只在模糊人工接手场景调用分类模型。
- `always`:每次都调用分类模型,判断更细但更费 token。
- `off`:完全关闭分类模型,只使用本地关键词和排除词。
服务端日志会打印每次发给回复模型的上下文大小,例如:
```text
[PDD Assistant] model context ... chars=3500, messages=6, products=2, faq=3, toneExamplesTextChars=260
```
+3
View File
@@ -0,0 +1,3 @@
[
]
+18
View File
@@ -0,0 +1,18 @@
{
"enabled": true,
"provider": "qq",
"host": "smtp.qq.com",
"port": 465,
"secure": true,
"startTls": false,
"rejectUnauthorized": true,
"user": "your-email@qq.com",
"authCodeEnv": "PDD_MAIL_AUTH_CODE",
"authCode": "",
"from": "your-email@qq.com",
"senderName": "PDD客服助手",
"to": ["owner@example.com"],
"cc": [],
"subjectPrefix": "[PDD客服会话,需人工处理]",
"dedupMs": 600000
}
@@ -0,0 +1,20 @@
[
{
"name": "退款退货",
"semantics": "买家表达退款、退货、退换货、取消订单、仅退款、退差价等诉求。",
"keywords": ["补发", "漏发", "没发","退款", "退货", "退换", "仅退款", "退差价", "取消订单"],
"excludeKeywords": ["退货规则怎么写", "七天无理由吗"]
},
{
"name": "商品损坏",
"semantics": "买家表示已收到或已使用的商品坏了、断了、裂了、破损、不能用、收到后有问题。",
"keywords": ["坏了", "断了", "裂了", "破损", "不能用", "有问题"],
"excludeKeywords": ["容易坏吗", "会不会断", "结实吗", "耐用吗"]
},
{
"name": "物流异常",
"semantics": "买家表达没收到、丢件、物流停滞、拒收、地址异常等需要人工核实的情况。",
"keywords": ["没收到", "丢件", "物流不动", "拒收", "地址错了"],
"excludeKeywords": ["多久到", "什么时候发", "发什么快递"]
}
]
+74
View File
@@ -0,0 +1,74 @@
[
{
"id": 1,
"name": "汉鼎螺纹钢鲢鳙",
"aliases": ["螺纹钢鲢","鲢鳙杆"],
"attributes": {
"品牌": "汉鼎",
"适用": "台钓、黑坑、鲢鳙杆",
"售后-配节": "找本店售后,如有损坏,凭照片免费全杆配节,但需要用户付10元运费",
"赠品": "无备用竿稍,无赠品",
"售后-退货": "不支持下水试用",
"硬度": "4.5H",
"包装": "硬纸筒包装"
}
},
{
"id": 2,
"name": "汉鼎螺纹钢极轻小综合",
"aliases": ["螺纹钢极", "小综合竿","鲫鱼竿"],
"attributes": {
"品牌": "汉鼎",
"适用": "台钓、鲫鱼",
"售后-配节": "找本店售后,如有损坏,凭照片免费全杆配节,但需要用户付10元运费",
"赠品": "无备用竿稍,无赠品",
"售后-退货": "不支持下水试用",
"硬度": "3.5H",
"包装": "硬纸筒包装"
}
}
,
{
"id": 3,
"name": "烈火战马pro湖库野钓杆",
"aliases": ["湖库", "小综合竿"],
"attributes": {
"品牌": "烈火战马",
"适用": "台钓、黑坑",
"售后-配节": "本店旗舰店皆可售后,凭竿身电子保卡条形码可以免费配一节,手把除外;后续配节成本价10-30一节越粗越贵,手把60;运费15一次(包含首次)",
"赠品": "无备用竿稍,无赠品",
"硬度": "4H",
"售后-退货": "不支持下水试用",
"包装": "礼盒包装"
}
}
,
{
"id": 4,
"name": "汉鼎螺纹钢宗综合杆",
"aliases": ["螺纹钢宗", "综合竿"],
"attributes": {
"品牌": "汉鼎",
"适用": "台钓、鲫鱼",
"售后-配节": "找本店售后,如有损坏,凭照片免费全杆配节,但需要用户付10元运费",
"赠品": "无备用竿稍,无赠品",
"售后-退货": "不支持下水试用",
"硬度": "4.5H",
"包装": "硬纸筒包装"
}
}
,
{
"id": 4,
"name": "汉鼎卓越小综合",
"aliases": ["小综合", "螺纹钢卓越"],
"attributes": {
"品牌": "汉鼎",
"售后-配节": "找本店售后,如有损坏,凭照片免费全杆配节,但需要用户付10元运费",
"赠品": "带备用竿稍,无其他赠品",
"售后-退货": "不支持下水试用",
"硬度": "3.5H",
"包装": "硬纸筒包装"
}
}
]
+14
View File
@@ -0,0 +1,14 @@
[
{
"name": "问候",
"match": "exact",
"keywords": ["你好", "您好", "在吗", "在"],
"reply": "您好,请问有什么需要帮忙的?"
},
{
"name": "确认",
"match": "exact",
"keywords": ["好的", "行", "ok", "OK", "好","👌","哦","噢","嗯","恩","en"],
"reply": "🌹🌹🌹"
}
]
+22
View File
@@ -0,0 +1,22 @@
[
{
"name": "平台外交易",
"keywords": ["微信", "vx", "qq", "支付宝", "转账", "加我", "私下", "线下交易"],
"reply": "您好,为保障您的权益,请您通过平台内正常下单和沟通,我这边不能引导平台外交易。"
},
{
"name": "辱骂争议",
"keywords": ["投诉", "举报", "差评", "骗子", "假货", "骂"],
"reply": "非常抱歉给您带来不好的体验,我这边先帮您核实订单和问题,请您稍等。"
},
{
"name": "敏感隐私",
"keywords": ["手机号", "身份证", "银行卡", "密码", "验证码"],
"reply": "您好,为保护您的信息安全,请不要在聊天中发送身份证、银行卡、验证码等敏感信息。"
},
{
"name": "default",
"keywords": [],
"defaultReply": "您好,这个问题我需要为您转人工进一步核实处理,请您稍等一下。"
}
]
+19
View File
@@ -0,0 +1,19 @@
{
"port": 3456,
"host": "0.0.0.0",
"controlToken": "",
"dailyPauseTime": "07:50",
"apiMode": "responses",
"codexApiUrl": "",
"codexModel": "",
"classifierModel": "",
"manualHandoffClassifierMode": "off",
"maxProductCandidates": 3,
"maxFaqItems": 5,
"maxToneExamples": 3,
"maxReplyGuidelinesChars": 1200,
"minReplyDelayMs": 3000,
"proxyUrl": "",
"mockWhenNoApiKey": true,
"modelTimeoutMs": 45000
}
+10
View File
@@ -0,0 +1,10 @@
[
{
"id": "shop-1",
"name": "示例店铺",
"pluginToken": "replace-with-plugin-token",
"cozeApiBase": "https://api.coze.cn",
"cozeApiToken": "",
"cozeBotId": "replace-with-coze-bot-id"
}
]
+14
View File
@@ -0,0 +1,14 @@
你是一个专业的拼多多商家后台的客服,你经营的店铺主营渔具,你了解汉鼎、烈火战马等钓竿的各个型号的详细信息。你是资深钓鱼玩家,懂得钓鱼专业术语。你必须基于商品配置、FAQ、真实对话示例和聊天上下文回复,不可虚构参数。
规则:
- 最简短、清晰、准确的话回复,不需要客套,不要有多余的引导词句,减少"哦"等语气词,避免机械感。
- 不引导平台外交易,不索要敏感信息。
- toneExamples 是常见问题的标准回答,相似的问题直接把参考答案轻微调整或原样输出。
- 参考 toneExamples 学习客服语气和表达方式。
- 商品咨询的问题,参考 toneExamples、商品配置作答。
- payload.pid 可能是商品卡片上的商品名,也可能是“商品名 + 型号/规格”;请结合商品候选信息判断具体商品。
- 只输出最终客服回复,不输出分析过程、JSON、标题或解释。
- 综合上下文,只回复用户的最后一条消息,且不要说之前回复过的话
- 产品参数要有明确依据,要准确,来源必须是官方数据
- 介绍产品时不要说售后、赠品相关
+86
View File
@@ -0,0 +1,86 @@
[
{
"id": "tone-price-001",
"scene": "买家问售后",
"customer": "坏了能不能换新的",
"goodReply": "哥,烈火战马凭竿身电子保卡条形码可以免费配一节,手把除外;后续配节成本价10-30一节越粗越贵,手把60;运费15一次(包含首次)",
"notes": "具体型号售后不同,找到该型号的售后政策回复用户。"
},
{
"id": "tone-price-002",
"scene": "买家问售后",
"customer": "怎么配节",
"goodReply": "哥,汉鼎如有损坏,凭照片免费全杆配节,但需要您付10元运费就可以啦",
"notes": "具体型号售后不同,找到该型号的售后政策回复用户。"
},
{
"id": "tone-price-003",
"scene": "买家问售后",
"customer": "全国门店免费配节吗",
"goodReply": "哥,汉鼎的售后找本店,凭照片免费全杆配节,但需要您付10元运费就可以啦",
"notes": "具体型号售后不同,找到该型号的售后政策回复用户。"
},
{
"id": "tone-quality-004",
"scene": "买家担心真假和质量",
"customer": "是正品吗",
"goodReply": "哥,全店所有鱼竿,保证全新正品,防伪可查,假一赔十,您放心,现在就是小店刚开,不赚钱纯用成本价拉新客,全新正品这两点您就放心!",
"notes": ""
},
{
"id": "tone-stock-005",
"scene": "买家问是否有货",
"customer": "现在有现货吗",
"goodReply": "哥,页面能正常下单的一般都有库存,您拍就行哈",
"notes": ""
},
{
"id": "tone-stock-006",
"scene": "买家问发货时间",
"customer": "今天能发吗",
"goodReply": "哥,今天大概率给您发出,要是仓库忙的实在顾不上,最晚最晚明天提早给您发!",
"notes": "一般当天12点前下单,大概率当天发,12点后一般第二天发"
},
{
"id": "tone-stock-007",
"scene": "买家问运费险",
"customer": "没有运费险吗",
"goodReply": "是的哥,现在没有退货包运费,几乎成本价给您发货,就为了新店拉新客,回来的运费成本都包不住哥,但全新正品这方面您就放一百个心!",
"notes": ""
},
{
"id": "tone-price-008",
"scene": "买家要优惠",
"customer": "还能便宜吗",
"goodReply": "哥,现在的价格已经找不到第二家,新店初开,都是用成本价打销量,一点也不能再优惠啦,请您见谅哈",
"notes": ""
},
{
"id": "tone-price-009",
"scene": "买家要赠品",
"customer": "带竿稍吗",
"goodReply": "新店开张,所有鱼竿都是成本价冲销量,实在没有多余的利润给您赠送东西,抱歉哥",
"notes": ""
},
{
"id": "tone-quality-10",
"scene": "买家担心真假和质量",
"customer": "怎么这么便宜",
"goodReply": "哥,全店所有鱼竿,保证全新正品,防伪可查,假一赔十,您放心,现在就是小店刚开,不赚钱纯用成本价拉新客,全新正品这两点您就放心!",
"notes": ""
},
{
"id": "tone-quality-11",
"scene": "买家问售后",
"customer": "能下水吗",
"goodReply": "不支持哥,新店初开,一分钱不挣就冲销量,全新正品这两点您就放一百个心,有七天无理由退货,您尽管到手查验,但不支持下水哥,拆封退回变二手得倒贴,请您理解哈",
"notes": "7天无理由退货,但需产品礼盒与杆袋完整,未损坏;竿稍未打结,同时不支持试用;产品不能出现损坏、污染、划痕等"
},
{
"id": "tone-quality-12",
"scene": "买家问发货地",
"customer": "哪里发货",
"goodReply": "威海",
"notes": ""
}
]
+92
View File
@@ -0,0 +1,92 @@
# 邮件配置
高危意图命中后,服务端不会生成客服回复,而是发送邮件提醒人工处理。邮件配置位于:
```text
D:\code\pdd\config\mail.json
```
## 推荐配置方式
不要把邮箱授权码直接写进仓库。推荐在 `mail.json` 中保留:
```json
{
"authCodeEnv": "PDD_MAIL_AUTH_CODE",
"authCode": ""
}
```
启动服务前在 PowerShell 设置授权码:
```powershell
$env:PDD_MAIL_AUTH_CODE="你的邮箱SMTP授权码"
npm start
```
## QQ邮箱示例
```json
{
"enabled": true,
"provider": "qq",
"host": "smtp.qq.com",
"port": 465,
"secure": true,
"startTls": false,
"user": "your-email@qq.com",
"authCodeEnv": "PDD_MAIL_AUTH_CODE",
"from": "your-email@qq.com",
"senderName": "PDD客服助手",
"to": ["owner@example.com"],
"subjectPrefix": "[PDD客服高危会话]",
"dedupMs": 600000
}
```
## 163邮箱示例
```json
{
"enabled": true,
"provider": "163",
"host": "smtp.163.com",
"port": 465,
"secure": true,
"startTls": false,
"user": "your-email@163.com",
"authCodeEnv": "PDD_MAIL_AUTH_CODE",
"from": "your-email@163.com",
"senderName": "PDD客服助手",
"to": ["owner@example.com"],
"subjectPrefix": "[PDD客服高危会话]",
"dedupMs": 600000
}
```
## Gmail示例
```json
{
"enabled": true,
"provider": "gmail",
"host": "smtp.gmail.com",
"port": 465,
"secure": true,
"startTls": false,
"user": "your-email@gmail.com",
"authCodeEnv": "PDD_MAIL_AUTH_CODE",
"from": "your-email@gmail.com",
"senderName": "PDD客服助手",
"to": ["owner@example.com"],
"subjectPrefix": "[PDD客服高危会话]",
"dedupMs": 600000
}
```
说明:
- `enabled`:设为 `true` 后才会发送邮件。
- `authCodeEnv`:读取邮箱授权码的环境变量名。
- `dedupMs`:同一高危会话邮件去重时间,默认 10 分钟。
- 大多数国内邮箱需要先在邮箱设置中开启 SMTP,并生成“授权码”,不是登录密码。
+99
View File
@@ -0,0 +1,99 @@
# Git 部署到 CentOS
## 1. 本地首次推送
在 Windows PowerShell 中进入项目目录:
```powershell
cd D:\code\pdd
git init
git branch -M main
git add .
git status
git commit -m "Initial pdd assistant"
git remote add origin https://github.com/octopuszycn-droid/pdd_AI.git
git push -u origin main
```
`config/shops.json`、`config/mail.json`、`.env` 不会被提交。真实 Token 和邮箱授权码只放服务器本地。
## 2. 服务器克隆
```bash
cd /opt
git clone https://github.com/octopuszycn-droid/pdd_AI.git pdd
cd /opt/pdd
```
## 3. 创建真实配置
```bash
cp config/shops.example.json config/shops.json
cp config/mail.example.json config/mail.json
vi config/shops.json
vi config/mail.json
```
创建 `.env`:
```bash
cat > /opt/pdd/.env <<'EOF'
PDD_ASSISTANT_HOST=0.0.0.0
PDD_ASSISTANT_PORT=3456
PDD_DAILY_PAUSE_TIME=07:50
PDD_CONTROL_TOKEN=replace-with-control-password
COZE_API_TOKEN=replace-with-coze-service-token
PDD_MAIL_AUTH_CODE=replace-with-mail-auth-code
EOF
chmod 600 /opt/pdd/.env
```
## 4. 启动
```bash
npm start
```
后台运行用 systemd:
```bash
cat > /etc/systemd/system/pdd-assistant.service <<'EOF'
[Unit]
Description=PDD Customer Service Reply Assistant
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
WorkingDirectory=/opt/pdd
EnvironmentFile=/opt/pdd/.env
ExecStart=/usr/bin/node /opt/pdd/server/index.js
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now pdd-assistant
```
## 5. 后续更新
本地提交并推送:
```powershell
git add .
git commit -m "Update assistant"
git push
```
服务器拉取并重启:
```bash
cd /opt/pdd
git pull
systemctl restart pdd-assistant
```
+83
View File
@@ -0,0 +1,83 @@
"use strict";
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (!message || message.source !== "pdd-reply-assistant") return false;
const tabId = sender.tab && sender.tab.id;
if (!tabId) {
sendResponse({ ok: false, error: "missing-tab-id" });
return false;
}
handleTrustedInput(tabId, message)
.then((result) => sendResponse(result))
.catch((error) => sendResponse({ ok: false, error: error.message || String(error) }));
return true;
});
async function handleTrustedInput(tabId, message) {
const target = { tabId };
await attachDebugger(target);
try {
if (message.action === "trusted-click") {
const x = Number(message.x);
const y = Number(message.y);
await sendCommand(target, "Input.dispatchMouseEvent", { type: "mouseMoved", x, y, button: "none" });
await sendCommand(target, "Input.dispatchMouseEvent", { type: "mousePressed", x, y, button: "left", clickCount: 1 });
await sendCommand(target, "Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button: "left", clickCount: 1 });
return { ok: true };
}
if (message.action === "trusted-insert-text") {
await sendCommand(target, "Input.insertText", { text: String(message.text || "") });
return { ok: true };
}
if (message.action === "trusted-enter") {
await sendCommand(target, "Input.dispatchKeyEvent", {
type: "keyDown",
key: "Enter",
code: "Enter",
windowsVirtualKeyCode: 13,
nativeVirtualKeyCode: 13
});
await sendCommand(target, "Input.dispatchKeyEvent", {
type: "keyUp",
key: "Enter",
code: "Enter",
windowsVirtualKeyCode: 13,
nativeVirtualKeyCode: 13
});
return { ok: true };
}
return { ok: false, error: "unknown-action" };
} finally {
await detachDebugger(target);
}
}
function attachDebugger(target) {
return new Promise((resolve, reject) => {
chrome.debugger.attach(target, "1.3", () => {
const error = chrome.runtime.lastError;
if (error) reject(new Error(error.message));
else resolve();
});
});
}
function detachDebugger(target) {
return new Promise((resolve) => {
chrome.debugger.detach(target, () => resolve());
});
}
function sendCommand(target, method, params) {
return new Promise((resolve, reject) => {
chrome.debugger.sendCommand(target, method, params, (result) => {
const error = chrome.runtime.lastError;
if (error) reject(new Error(error.message));
else resolve(result);
});
});
}
+213
View File
@@ -0,0 +1,213 @@
#pdd-reply-assistant-root {
--pdd-ra-blue: #3b63f6;
--pdd-ra-green: #17a56b;
--pdd-ra-red: #d93025;
--pdd-ra-text: #1f2937;
--pdd-ra-muted: #64748b;
--pdd-ra-border: #dbe3ef;
--pdd-ra-bg: #ffffff;
--pdd-ra-soft: #f6f8fb;
color: var(--pdd-ra-text);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", sans-serif;
font-size: 13px;
position: fixed;
z-index: 2147483647;
}
#pdd-reply-assistant-root * {
box-sizing: border-box;
}
.pdd-ra-panel {
width: 320px;
border: 1px solid var(--pdd-ra-border);
border-radius: 8px;
background: var(--pdd-ra-bg);
box-shadow: 0 12px 34px rgba(15, 23, 42, 0.18);
overflow: hidden;
user-select: none;
}
.pdd-ra-header {
align-items: center;
background: #1f2937;
color: #fff;
cursor: move;
display: flex;
gap: 8px;
height: 38px;
padding: 0 10px;
}
.pdd-ra-title {
flex: 1;
font-size: 13px;
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.pdd-ra-status {
border-radius: 999px;
height: 8px;
width: 8px;
}
.pdd-ra-status.is-idle {
background: #94a3b8;
}
.pdd-ra-status.is-listening {
background: var(--pdd-ra-green);
}
.pdd-ra-status.is-busy {
background: #f59e0b;
}
.pdd-ra-status.is-error {
background: var(--pdd-ra-red);
}
.pdd-ra-icon-btn {
align-items: center;
background: transparent;
border: 0;
border-radius: 6px;
color: inherit;
cursor: pointer;
display: inline-flex;
font-size: 16px;
height: 26px;
justify-content: center;
padding: 0;
width: 26px;
}
.pdd-ra-icon-btn:hover {
background: rgba(255, 255, 255, 0.14);
}
.pdd-ra-body {
padding: 10px;
}
.pdd-ra-controls {
align-items: center;
display: grid;
gap: 8px;
grid-template-columns: 1fr 1fr 1fr;
}
.pdd-ra-button {
align-items: center;
border: 1px solid var(--pdd-ra-border);
border-radius: 7px;
background: var(--pdd-ra-soft);
color: var(--pdd-ra-text);
cursor: pointer;
display: inline-flex;
font-size: 13px;
font-weight: 600;
height: 32px;
justify-content: center;
padding: 0 10px;
}
.pdd-ra-button:hover {
border-color: #a9b8cf;
}
.pdd-ra-button.is-primary {
background: var(--pdd-ra-blue);
border-color: var(--pdd-ra-blue);
color: #fff;
}
.pdd-ra-button.is-paused {
background: #fff7ed;
border-color: #fdba74;
color: #9a3412;
}
.pdd-ra-config {
display: none;
gap: 8px;
margin-top: 10px;
}
.pdd-ra-config.is-open {
display: grid;
}
.pdd-ra-field {
display: grid;
gap: 4px;
}
.pdd-ra-field span {
color: var(--pdd-ra-muted);
font-size: 12px;
}
.pdd-ra-field input {
border: 1px solid var(--pdd-ra-border);
border-radius: 6px;
color: var(--pdd-ra-text);
font: inherit;
height: 30px;
outline: none;
padding: 0 8px;
user-select: text;
width: 100%;
}
.pdd-ra-field input:focus {
border-color: var(--pdd-ra-blue);
box-shadow: 0 0 0 2px rgba(59, 99, 246, 0.12);
}
.pdd-ra-meta {
color: var(--pdd-ra-muted);
font-size: 12px;
line-height: 1.45;
margin-top: 8px;
}
.pdd-ra-log {
background: #0f172a;
border-radius: 7px;
color: #dbeafe;
height: 168px;
line-height: 1.45;
margin-top: 10px;
overflow: auto;
padding: 8px;
user-select: text;
white-space: pre-wrap;
}
.pdd-ra-bubble {
align-items: center;
background: var(--pdd-ra-blue);
border: 2px solid #fff;
border-radius: 999px;
box-shadow: 0 10px 26px rgba(15, 23, 42, 0.22);
color: #fff;
cursor: move;
display: none;
font-size: 14px;
font-weight: 700;
height: 54px;
justify-content: center;
width: 54px;
}
#pdd-reply-assistant-root.is-minimized .pdd-ra-panel {
display: none;
}
#pdd-reply-assistant-root.is-minimized .pdd-ra-bubble {
display: flex;
}
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
{
"manifest_version": 3,
"name": "PDD客服自动回复助手",
"description": "监听拼多多商家后台客服新会话,调用本地服务生成回复并回填发送。",
"version": "0.1.0",
"permissions": ["storage", "debugger"],
"host_permissions": [
"http://127.0.0.1:3456/*",
"http://localhost:3456/*",
"http://*/*",
"https://*/*",
"https://mms.pinduoduo.com/*"
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": [
"https://mms.pinduoduo.com/*"
],
"js": ["content.js"],
"css": ["content.css"],
"run_at": "document_idle"
}
]
}
+13
View File
@@ -0,0 +1,13 @@
{
"name": "pdd-customer-service-reply-assistant",
"version": "0.1.0",
"private": true,
"description": "拼多多商家后台客服自动回复浏览器插件与本地服务。",
"scripts": {
"start": "node server/index.js",
"dev": "node server/index.js"
},
"engines": {
"node": ">=18"
}
}
File diff suppressed because it is too large Load Diff
+39 -4
View File
@@ -62,6 +62,11 @@
background: var(--pdd-ra-green);
}
/* 调试模式:蓝色,和自动模式的绿色区分开 */
.pdd-ra-status.is-debug {
background: #3b82f6;
}
.pdd-ra-status.is-busy {
background: #f59e0b;
}
@@ -125,10 +130,23 @@
color: #fff;
}
/* 模式按钮:自动=绿、调试=蓝,靠颜色区分而不是只看文字 */
.pdd-ra-button.is-auto {
background: var(--pdd-ra-green);
border-color: var(--pdd-ra-green);
color: #fff;
}
.pdd-ra-button.is-debug {
background: #3b82f6;
border-color: #3b82f6;
color: #fff;
}
.pdd-ra-button.is-paused {
background: #fff7ed;
border-color: #fdba74;
color: #9a3412;
background: #f59e0b;
border-color: #f59e0b;
color: #fff;
}
.pdd-ra-config {
@@ -181,13 +199,30 @@
color: #dbeafe;
height: 168px;
line-height: 1.45;
margin-top: 10px;
margin-top: 6px;
overflow: auto;
padding: 8px;
user-select: text;
white-space: pre-wrap;
}
.pdd-ra-logtools {
align-items: center;
display: flex;
gap: 8px;
margin-top: 10px;
}
.pdd-ra-logtools .pdd-ra-button {
font-size: 12px;
padding: 4px 10px;
}
.pdd-ra-loghint {
color: var(--pdd-ra-muted);
font-size: 11px;
}
.pdd-ra-bubble {
align-items: center;
background: var(--pdd-ra-blue);
+1981 -25
View File
File diff suppressed because it is too large Load Diff
+9
View File
@@ -15,6 +15,15 @@
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": [
"https://mms.pinduoduo.com/*"
],
"js": ["stealth.js"],
"run_at": "document_start",
"all_frames": true,
"world": "MAIN"
},
{
"matches": [
"https://mms.pinduoduo.com/*"
+414
View File
@@ -0,0 +1,414 @@
(() => {
"use strict";
// 页面级反检测层:CDP 在 document_start 注入,早于站点任何脚本执行。
// 目标不是"换成另一套指纹",而是抹平自动化痕迹,并让同一 profile 的指纹恒定。
// 原则:能不 patch 就不 patch,patch 后的函数必须与原生描述符完全一致。
const fakeSource = new WeakMap();
const patchedWindows = new WeakSet();
const touchedBuffers = new WeakSet();
const FIXED_GPU_VENDOR = "Google Inc. (NVIDIA)";
const FIXED_GPU_RENDERER =
"ANGLE (NVIDIA, NVIDIA GeForce GTX 1660 SUPER Direct3D11 vs_5_0 ps_5_0, D3D11)";
// 把补丁函数的 name/length/toString 对齐原生,否则检测脚本一句 toString 就穿了
function markNative(fn, name, arity) {
try {
Object.defineProperty(fn, "name", { value: name, configurable: true });
Object.defineProperty(fn, "length", { value: arity || 0, configurable: true });
} catch (error) {
// 某些宿主对象的函数名不可改写,忽略即可
}
fakeSource.set(fn, "function " + name + "() { [native code] }");
return fn;
}
function installFunctionMask(win) {
const realmToString = win.Function.prototype.toString;
const patched = markNative(function toString() {
if (fakeSource.has(this)) return fakeSource.get(this);
return realmToString.call(this);
}, "toString", 0);
Object.defineProperty(win.Function.prototype, "toString", {
value: patched,
writable: true,
enumerable: false,
configurable: true
});
}
// JS 层改不了已创建事件的 isTrusted:它是实例 own accessor 且 configurable=false,
// 改 Event.prototype 只会留下一个多余属性(反而是新痕迹)。
// 这里换一条路:包住事件构造器,new 出来的实例用 Proxy 把 isTrusted 读成 true;
// dispatchEvent 时再把 Proxy 解包回真实事件,业务派发不受影响。
const proxyToEvent = new WeakMap();
const eventToProxy = new WeakMap();
const EVENT_CONSTRUCTORS = [
"Event",
"UIEvent",
"MouseEvent",
"PointerEvent",
"KeyboardEvent",
"InputEvent",
"FocusEvent",
"CustomEvent",
"WheelEvent",
"TouchEvent",
"CompositionEvent"
];
function wrapEvent(win, event) {
if (eventToProxy.has(event)) return eventToProxy.get(event);
const proxy = new win.Proxy(event, {
get(target, key) {
if (key === "isTrusted") return true;
return Reflect.get(target, key, target);
},
has(target, key) {
if (key === "isTrusted") return true;
return Reflect.has(target, key);
}
});
proxyToEvent.set(proxy, event);
eventToProxy.set(event, proxy);
return proxy;
}
function installEventConstructorMask(win) {
if (typeof win.Proxy !== "function") return;
for (const name of EVENT_CONSTRUCTORS) {
const Original = win[name];
if (typeof Original !== "function") continue;
const Wrapped = function (type, init) {
return wrapEvent(win, new Original(type, init));
};
markNative(Wrapped, name, Original.length);
try {
// 构造函数返回 Proxy 时,原型链要指回原构造器的 prototype,否则 instanceof 会崩
Object.defineProperty(Wrapped, "prototype", {
value: Original.prototype,
writable: false,
enumerable: false,
configurable: false
});
Object.defineProperty(win, name, {
value: Wrapped,
writable: true,
enumerable: false,
configurable: true
});
// event.constructor 必须指回新的构造器,否则 === Event 的比较会露馅
Original.prototype.constructor = Wrapped;
} catch (error) {
// 个别构造器不可覆写,跳过
}
}
const documentProto = win.Document && win.Document.prototype;
if (documentProto && typeof documentProto.createEvent === "function") {
const originalCreate = documentProto.createEvent;
documentProto.createEvent = markNative(function createEvent(type) {
return wrapEvent(win, originalCreate.call(this, type));
}, "createEvent", 1);
}
const targetProto = win.EventTarget && win.EventTarget.prototype;
if (targetProto && typeof targetProto.dispatchEvent === "function") {
const originalDispatch = targetProto.dispatchEvent;
targetProto.dispatchEvent = markNative(function dispatchEvent(event) {
return originalDispatch.call(this, proxyToEvent.get(event) || event);
}, "dispatchEvent", 1);
}
}
const TRACE_PREFIXES = [
"cdc_",
"$cdc_",
"__webdriver",
"__driver",
"__selenium",
"_selenium",
"callSelenium",
"domAutomation",
"__nightmare",
"_phantom",
"callPhantom",
"__playwright",
"__puppeteer",
"__pw_"
];
function installAutomationTraces(win) {
let names = [];
try {
names = Object.getOwnPropertyNames(win);
} catch (error) {
return;
}
for (const name of names) {
if (!TRACE_PREFIXES.some((prefix) => name.startsWith(prefix))) continue;
try {
delete win[name];
} catch (error) {
// 不可配置的残留属性删不掉,交给后续兜底
}
}
}
// navigator.webdriver 优先靠启动参数 --disable-blink-features=AutomationControlled 归零,
// 那样属性形态完全是原生的。只有浏览器仍报 true 时才兜底改写。
function installWebdriver(win) {
let nav = null;
try {
nav = win.navigator;
} catch (error) {
return;
}
if (!nav || nav.webdriver !== true) return;
try {
Object.defineProperty(win.Navigator.prototype, "webdriver", {
get: markNative(function webdriver() {
return false;
}, "get webdriver", 0),
set: undefined,
enumerable: true,
configurable: true
});
} catch (error) {
// 忽略
}
}
function installPermissions(win) {
const proto = win.Permissions && win.Permissions.prototype;
if (!proto || typeof proto.query !== "function") return;
const original = proto.query;
proto.query = markNative(function query(descriptor) {
const notification = win.Notification;
if (descriptor && descriptor.name === "notifications" && notification &&
notification.permission === "denied") {
return Promise.resolve({ state: "prompt", onchange: null });
}
return original.apply(this, arguments);
}, "query", 1);
}
// 只在检测到软件渲染(SwiftShader / llvmpipe)时替换:真机有头模式透传真值,痕迹最小。
function installWebGL(win) {
const patch = (proto) => {
if (!proto || typeof proto.getParameter !== "function") return;
const original = proto.getParameter;
let software = null;
proto.getParameter = markNative(function getParameter(param) {
const value = original.apply(this, arguments);
if (param !== 37445 && param !== 37446) return value;
if (software === null) {
const renderer = param === 37446
? String(value || "")
: String(original.call(this, 37446) || "");
software = /swiftshader|llvmpipe|software|basic render/i.test(renderer);
}
if (!software) return value;
return param === 37445 ? FIXED_GPU_VENDOR : FIXED_GPU_RENDERER;
}, "getParameter", 1);
};
patch(win.WebGLRenderingContext && win.WebGLRenderingContext.prototype);
patch(win.WebGL2RenderingContext && win.WebGL2RenderingContext.prototype);
}
// canvas 指纹:只扰动小画布(指纹探针的典型尺寸),且扰动位置/幅度完全确定,
// 同一画布反复读取结果一致,不会因为"两次读取不同"被抓。
function installCanvas(win) {
const proto = win.CanvasRenderingContext2D && win.CanvasRenderingContext2D.prototype;
if (!proto || typeof proto.getImageData !== "function") return;
const original = proto.getImageData;
proto.getImageData = markNative(function getImageData() {
const data = original.apply(this, arguments);
try {
const canvas = this.canvas;
if (!canvas || !data || !data.data || data.data.length < 8) return data;
if (canvas.width > 320 || canvas.height > 320) return data;
const pixels = data.data.length >>> 2;
const seed = ((canvas.width * 31 + canvas.height * 131 + data.data.length) >>> 0);
const index = (seed % pixels) * 4;
const delta = (seed & 1) === 1 ? 1 : -1;
const next = data.data[index] + delta;
data.data[index] = next < 0 ? 0 : next > 255 ? 255 : next;
} catch (error) {
// 扰动失败就返回原数据
}
return data;
}, "getImageData", 4);
}
// AudioBuffer 的极小幅噪声:足以改变音频指纹哈希,听感与业务无影响。
function installAudio(win) {
const proto = win.AudioBuffer && win.AudioBuffer.prototype;
if (!proto || typeof proto.getChannelData !== "function") return;
const original = proto.getChannelData;
proto.getChannelData = markNative(function getChannelData() {
const data = original.apply(this, arguments);
try {
if (!data || data.length < 64 || touchedBuffers.has(this)) return data;
touchedBuffers.add(this);
const seed = (data.length * 2654435761) >>> 0;
const index = seed % data.length;
data[index] = data[index] + ((seed & 1) === 1 ? 1e-7 : -1e-7);
} catch (error) {
// 忽略
}
return data;
}, "getChannelData", 1);
}
// 无头环境 enumerateDevices 返回空数组,是常见判定点;真机有设备列表时不动。
function installMediaDevices(win) {
const proto = win.MediaDevices && win.MediaDevices.prototype;
if (!proto || typeof proto.enumerateDevices !== "function") return;
const original = proto.enumerateDevices;
proto.enumerateDevices = markNative(function enumerateDevices() {
return original.apply(this, arguments).then((list) => {
if (list && list.length > 0) return list;
return [
{ deviceId: "default", kind: "audioinput", label: "", groupId: "default" },
{ deviceId: "default", kind: "audiooutput", label: "", groupId: "default" },
{ deviceId: "default", kind: "videoinput", label: "", groupId: "default" }
];
});
}, "enumerateDevices", 0);
}
// NetworkInformation 在容器/无网卡环境下 rtt、downlink 会归零,补成常见值。
function installConnection(win) {
let connection = null;
try {
connection = win.navigator.connection;
} catch (error) {
return;
}
if (!connection) return;
const fix = (key, value) => {
try {
const current = connection[key];
if (current !== undefined && current !== 0 && current !== "") return;
Object.defineProperty(connection, key, {
get: markNative(function () {
return value;
}, "get " + key, 0),
set: undefined,
enumerable: true,
configurable: true
});
} catch (error) {
// 忽略
}
};
fix("rtt", 50);
fix("downlink", 10);
fix("effectiveType", "4g");
}
// 无头 UA 里带 HeadlessChrome,同步改掉 userAgent 与 UA-CH,避免两处不一致。
function installUaHints(win) {
let ua = "";
try {
ua = String(win.navigator.userAgent || "");
} catch (error) {
return;
}
if (ua.indexOf("HeadlessChrome") === -1) return;
const fixed = ua.replace("HeadlessChrome", "Chrome");
try {
Object.defineProperty(win.Navigator.prototype, "userAgent", {
get: markNative(function userAgent() {
return fixed;
}, "get userAgent", 0),
set: undefined,
enumerable: true,
configurable: true
});
} catch (error) {
// 忽略
}
}
// iframe 里的检测最容易被漏掉:contentWindow 一被读取就先给子窗口打一遍补丁。
// CDP 的 addScriptToEvaluateOnNewDocument 本身覆盖子 frame,这里是双保险。
function installIframeHook(win) {
const proto = win.HTMLIFrameElement && win.HTMLIFrameElement.prototype;
if (!proto) return;
let descriptor = null;
try {
descriptor = Object.getOwnPropertyDescriptor(proto, "contentWindow");
} catch (error) {
return;
}
if (!descriptor || typeof descriptor.get !== "function") return;
const original = descriptor.get;
const getter = markNative(function contentWindow() {
const child = original.call(this);
if (child) {
try {
install(child);
} catch (error) {
// 跨域子窗口访问会抛,交给 CDP 自己注入
}
}
return child;
}, "get contentWindow", 0);
try {
Object.defineProperty(proto, "contentWindow", {
get: getter,
set: undefined,
enumerable: descriptor.enumerable,
configurable: true
});
} catch (error) {
// 忽略
}
}
function install(win) {
if (!win || patchedWindows.has(win)) return;
patchedWindows.add(win);
// toString 必须先装,后面所有 markNative 的函数才经得起 toString 检查
installFunctionMask(win);
installEventConstructorMask(win);
installAutomationTraces(win);
installWebdriver(win);
installPermissions(win);
installWebGL(win);
installCanvas(win);
installAudio(win);
installMediaDevices(win);
installConnection(win);
installUaHints(win);
installIframeHook(win);
}
install(window);
})();
+45
View File
@@ -0,0 +1,45 @@
@echo off
setlocal
cd /d "%~dp0"
set "VCVARS=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat"
if not exist "%VCVARS%" goto :novcvars
call "%VCVARS%" x64 >nul
set WV2=%~dp0packages\Microsoft.Web.WebView2.1.0.2420.47\build\native
set OUT=%~dp0bin
if not exist "%OUT%" mkdir "%OUT%"
echo [1/3] 编译资源
rc /nologo /fo "%OUT%\app.res" res\app.rc
if errorlevel 1 goto :fail
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 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
if errorlevel 1 goto :fail
echo [3/3] 完成
echo 产物: %OUT%\PddAI.exe
if exist "%OUT%\PddAI.exe" dir "%OUT%\PddAI.exe"
endlocal
exit /b 0
:fail
echo [x] 构建失败
endlocal
exit /b 1
:novcvars
echo [x] 找不到 vcvarsall.bat: %VCVARS%
endlocal
exit /b 1
+1
View File
@@ -0,0 +1 @@
{"msgList":[{"usertype":"cus","msg":"你好"}]}
+1
View File
@@ -0,0 +1 @@
{"msgList":[{"usertype":"cus","msg":"好的"}]}
+1
View File
@@ -0,0 +1 @@
{"msgList":[{"usertype":"cus","msg":"在"}]}
+1
View File
@@ -0,0 +1 @@
{"msgList":[{"usertype":"cus","msg":"你加我微信聊吧"}]}
+1
View File
@@ -0,0 +1 @@
{"msgList":[{"usertype":"cus","msg":"我要投诉你们,卖假货"}]}
+1
View File
@@ -0,0 +1 @@
{"msgList":[{"usertype":"cus","msg":"这款螺纹钢鲢鳙的调性怎么样"}]}
+1
View File
@@ -0,0 +1 @@
{"msgList":[{"usertype":"cus","msg":"能便宜点吗,最低多少"}]}
+1
View File
@@ -0,0 +1 @@
{"pid":1,"msgList":[{"usertype":"cus","msg":"这个有货吗"},{"usertype":"sys","msg":"欢迎光临"}]}
+1
View File
@@ -0,0 +1 @@
{"pid":2,"msgList":[{"usertype":"sys","msg":"您好"},{"usertype":"cus","msg":"多长尺寸"},{"usertype":"cus","msg":"1.8还是2.1"}]}
+1
View File
@@ -0,0 +1 @@
{"msgList":[]}
+1
View File
@@ -0,0 +1 @@
{"pid":1}
+1
View File
@@ -0,0 +1 @@
{"pid":4,"msgList":[{"usertype":"cus","msg":"综合竿和鲫鱼竿有什么区别"}]}
+5
View File
@@ -0,0 +1,5 @@
{
"msgList": [
{ "usertype": "cus", "msg": "这个竿子多重?" }
]
}
+5
View File
@@ -0,0 +1,5 @@
{
"msgList": [
{ "usertype": "cus", "msg": "能送备用竿稍吗" }
]
}
+5
View File
@@ -0,0 +1,5 @@
{
"msgList": [
{ "usertype": "cus", "msg": "帮我处理一下" }
]
}
+9
View File
@@ -0,0 +1,9 @@
$files = Get-ChildItem -Path "cases" -Filter "*.json" | Sort-Object Name
foreach ($f in $files) {
$native = curl.exe -s --data-binary "@$($f.FullName)" -H "Content-Type: application/json" http://127.0.0.1:3456/api/reply
$node = curl.exe -s --data-binary "@$($f.FullName)" -H "Content-Type: application/json" http://127.0.0.1:3457/api/reply
"### " + $f.Name
" N: " + $native
" J: " + $node
""
}
+39
View File
@@ -0,0 +1,39 @@
#include <windows.h>
#include <winver.h>
#include "../src/resource.h"
#pragma code_page(65001)
IDR_UI_HTML RCDATA "..\\ui\\index.html"
IDR_INJECT_CONTENT_JS RCDATA "..\\..\\extension\\content.js"
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"
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,0,0
PRODUCTVERSION 1,0,0,0
FILEFLAGSMASK 0x3fL
FILEFLAGS 0x0L
FILEOS 0x40004L
FILETYPE 0x1L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "080404b0"
BEGIN
VALUE "CompanyName", "PddAI"
VALUE "FileDescription", "PddAI 客服助手"
VALUE "FileVersion", "1.0.0"
VALUE "InternalName", "PddAI"
VALUE "OriginalFilename", "PddAI.exe"
VALUE "ProductName", "PddAI 客服助手"
VALUE "ProductVersion", "1.0.0"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x804, 1200
END
END
+856
View File
@@ -0,0 +1,856 @@
// winsock2.h 必须先于 windows.h 引入,否则会被 winsock.h 抢先定义
#include <winsock2.h>
#include <ws2tcpip.h>
#include "Browser.h"
#include <windows.h>
#include <shlobj.h>
#include <atomic>
#include <chrono>
#include <cwchar>
#include <cstring>
#include <memory>
#include <mutex>
#include <random>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
#include "Cdp.h"
#include "Config.h"
#include "Http.h"
#include "Json.h"
#include "Log.h"
#include "Resources.h"
#include "Util.h"
#include "WebConsole.h"
#include "resource.h"
namespace pddai {
namespace {
constexpr int kDefaultDebugPort = 9222;
// 客服工作台入口:商家后台根路径只是首页,待回复列表在这个地址里
constexpr const char* kDefaultTargetUrl = "https://mms.pinduoduo.com/chat-merchant/index.html#/";
// 允许用 server.json 的 chatUrl 覆盖(换入口或换域名时不用重新编译)
std::string TargetUrl() {
std::string url;
try {
const json server = Config::GetJson("server.json", json::object());
url = server.value("chatUrl", "");
} catch (const std::exception&) {
url.clear();
}
std::string trimmed = Trim(url);
return trimmed.empty() ? std::string(kDefaultTargetUrl) : trimmed;
}
std::mutex g_mutex;
Browser::Info g_info;
PROCESS_INFORMATION g_process{};
HANDLE g_job = nullptr;
std::atomic<bool> g_launching{false};
// 页面发来的真实输入请求要复用同一条 CDP 连接,socket 本身不可并发,加锁串行化
std::mutex g_cdpMutex;
std::shared_ptr<Cdp> g_cdp;
std::string g_cdpSession;
std::mt19937& RandomEngine() {
static std::mt19937 engine(static_cast<unsigned>(::GetTickCount64()));
return engine;
}
int RandomInt(int min, int max) {
if (max <= min) return min;
std::uniform_int_distribution<int> dist(min, max);
return dist(RandomEngine());
}
// 随机挑一个空闲的本地端口:固定 9222 会让页面直接探到调试端口
int PickFreePort() {
WSADATA data{};
if (::WSAStartup(MAKEWORD(2, 2), &data) != 0) return kDefaultDebugPort;
int picked = 0;
for (int attempt = 0; attempt < 30 && picked == 0; ++attempt) {
const int port = RandomInt(20000, 60000);
SOCKET sock = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET) continue;
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(static_cast<u_short>(port));
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (::bind(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) == 0) picked = port;
::closesocket(sock);
}
::WSACleanup();
return picked == 0 ? kDefaultDebugPort : picked;
}
std::wstring LocalAppData() {
wchar_t path[MAX_PATH]{};
if (SUCCEEDED(::SHGetFolderPathW(nullptr, CSIDL_LOCAL_APPDATA, nullptr, 0, path))) {
return std::wstring(path) + L"\\PddAI";
}
return L"PddAI";
}
std::string RegReadString(HKEY root, const std::wstring& subKey, const std::wstring& value) {
HKEY key = nullptr;
if (::RegOpenKeyExW(root, subKey.c_str(), 0, KEY_READ, &key) != ERROR_SUCCESS) return "";
DWORD type = 0;
DWORD size = 0;
std::string result;
if (::RegQueryValueExW(key, value.c_str(), nullptr, &type, nullptr, &size) == ERROR_SUCCESS &&
(type == REG_SZ || type == REG_EXPAND_SZ) && size > 0) {
std::vector<wchar_t> buffer(size / sizeof(wchar_t) + 1, L'\0');
DWORD written = size;
if (::RegQueryValueExW(key, value.c_str(), nullptr, &type,
reinterpret_cast<LPBYTE>(buffer.data()), &written) == ERROR_SUCCESS) {
result = WideToUtf8(buffer.data());
}
}
::RegCloseKey(key);
return result;
}
struct BrowserCandidate {
std::string name;
std::wstring path;
};
std::vector<BrowserCandidate> Candidates() {
std::vector<BrowserCandidate> list;
const std::string edgeApp = RegReadString(
HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\msedge.exe", L"");
if (!edgeApp.empty()) list.push_back({"Edge", Utf8ToWide(edgeApp)});
const std::string chromeApp = RegReadString(
HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe", L"");
if (!chromeApp.empty()) list.push_back({"Chrome", Utf8ToWide(chromeApp)});
const std::wstring local = LocalAppData();
list.push_back({"Edge", L"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"});
list.push_back({"Edge", L"C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe"});
list.push_back({"Chrome", L"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"});
list.push_back({"Chrome", L"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"});
list.push_back({"Chrome", local + L"\\Google\\Chrome\\Application\\chrome.exe"});
return list;
}
bool FileExists(const std::wstring& path) {
const DWORD attr = ::GetFileAttributesW(path.c_str());
return attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0;
}
BrowserCandidate PickBrowser() {
for (const BrowserCandidate& item : Candidates()) {
if (FileExists(item.path)) return item;
}
return {};
}
std::string SafeId(const std::string& id) {
std::string out;
for (const char c : id) {
const bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
c == '_' || c == '-';
out += ok ? c : '_';
}
return out.empty() ? "default" : out;
}
// 预置 localStorage + 注入 CSS + 注入 content.js,三者合成一个 document_start 脚本
std::string BuildInjectSource(const std::string& serverBase, const std::string& shopId,
const std::string& shopName, const std::string& shopToken) {
json state = json::object();
state["mode"] = "debug";
state["paused"] = false;
state["serverBase"] = serverBase;
state["shopId"] = shopId;
state["shopName"] = shopName;
state["shopToken"] = shopToken;
const std::string css = LoadTextResource(IDR_INJECT_CONTENT_CSS);
const std::string contentJs = LoadTextResource(IDR_INJECT_CONTENT_JS);
const std::string stealthJs = LoadTextResource(IDR_INJECT_STEALTH_JS);
std::string source;
// 反检测层必须第一个执行:它要抢在站点任何脚本之前改写 API 描述符
if (!stealthJs.empty()) source += stealthJs + "\n";
source += "(function(){try{localStorage.setItem('pddReplyAssistantState'," +
json(state.dump()).dump() + ");}catch(e){}})();\n";
if (!css.empty()) {
source += "(function(){var add=function(){try{var s=document.createElement('style');s.textContent=" +
json(css).dump() +
";(document.head||document.documentElement||document.body).appendChild(s);}catch(e){}};" +
"if(document.head||document.documentElement)add();" +
"else document.addEventListener('DOMContentLoaded',add);})();\n";
}
// content.js 在扩展里是 document_idle 注入,而 CDP 是 document_start,
// 必须等 body 就绪再运行,否则 buildWidget 拿不到 document.body
source += "(function(){var run=function(){" + contentJs + "};";
source += "if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',run);";
source += "else run();})();\n";
return source;
}
// 等待浏览器的 /json/version 就绪,返回 browser 级 WebSocket 地址
std::string WaitForDevTools(int port, int timeoutMs) {
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
while (std::chrono::steady_clock::now() < deadline) {
try {
const HttpResponse response = Http::GetJson("http://127.0.0.1:" + std::to_string(port) +
"/json/version",
{}, 1500, "");
if (response.status >= 200 && response.status < 300 && response.data.is_object()) {
const std::string ws = response.data.value("webSocketDebuggerUrl", std::string());
if (!ws.empty()) return ws;
}
} catch (const std::exception&) {
// 浏览器还没起来,继续等
}
SleepMs(500);
}
throw std::runtime_error("等待浏览器调试端口超时");
}
void CloseProcessHandles() {
if (g_process.hThread) {
::CloseHandle(g_process.hThread);
g_process.hThread = nullptr;
}
if (g_process.hProcess) {
::CloseHandle(g_process.hProcess);
g_process.hProcess = nullptr;
}
if (g_job) {
::CloseHandle(g_job);
g_job = nullptr;
}
}
void LaunchWorker(std::function<void(bool, const std::string&)> done) {
bool ok = false;
std::string message;
try {
const BrowserCandidate browser = PickBrowser();
if (browser.path.empty()) throw std::runtime_error("未检测到 Chrome 或 Edge");
const json shops = Config::LoadShops();
const json shop = shops.is_array() && !shops.empty() ? shops[0] : json::object();
const std::string shopId = shop.value("id", std::string("default"));
const std::string shopName = shop.value("name", std::string("默认店铺"));
const std::string shopToken = shop.value("pluginToken", std::string());
const int serverPort = Config::Port();
const std::string serverBase = "http://127.0.0.1:" + std::to_string(serverPort);
const std::wstring profile = LocalAppData() + L"\\profiles\\" + Utf8ToWide(SafeId(shopId));
::CreateDirectoryW((LocalAppData() + L"\\profiles").c_str(), nullptr);
::CreateDirectoryW(profile.c_str(), nullptr);
const int debugPort = PickFreePort();
std::wstring args = L"--remote-debugging-port=" + std::to_wstring(debugPort);
args += L" --remote-allow-origins=*"; // Chrome 111+ 拒绝了非浏览器来源的 WS 握手
args += L" --user-data-dir=\"" + profile + L"\"";
args += L" --no-first-run --no-default-browser-check --disable-popup-blocking";
args += L" --start-maximized";
// 关掉 Blink 的自动化标记:navigator.webdriver 直接为 false,属性形态保持原生
args += L" --disable-blink-features=AutomationControlled";
// WebRTC 不许绕过代理走 UDP,内网 IP 不再成为额外的指纹维度
args += L" --force-webrtc-ip-handling-policy=disable_non_proxied_udp";
args += L" " + Utf8ToWide(TargetUrl());
// 作业对象用于最后一次性结束整个进程树
g_job = ::CreateJobObjectW(nullptr, nullptr);
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit{};
limit.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
::SetInformationJobObject(g_job, JobObjectExtendedLimitInformation, &limit, sizeof(limit));
STARTUPINFOW si{};
si.cb = sizeof(si);
PROCESS_INFORMATION pi{};
std::wstring commandLine = L"\"" + browser.path + L"\" " + args;
if (!::CreateProcessW(nullptr, const_cast<LPWSTR>(commandLine.data()), nullptr, nullptr, FALSE,
CREATE_SUSPENDED, nullptr, nullptr, &si, &pi)) {
throw std::runtime_error("启动浏览器失败");
}
::AssignProcessToJobObject(g_job, pi.hProcess);
::ResumeThread(pi.hThread);
g_process = pi;
{
std::lock_guard<std::mutex> lock(g_mutex);
g_info = Browser::Info{};
g_info.running = true;
g_info.browserName = browser.name;
g_info.browserPath = WideToUtf8(browser.path);
g_info.port = debugPort;
g_info.profileDir = WideToUtf8(profile);
}
Log::Info("已启动 " + browser.name + ",调试端口 " + std::to_string(debugPort));
const std::string wsUrl = WaitForDevTools(debugPort, 30000);
auto cdp = std::make_shared<Cdp>();
cdp->Connect(wsUrl);
// 先建空白页再导航:直接带 URL 创建会多加载一次客服页
const json target = cdp->Command("Target.createTarget",
json::object({{"url", "about:blank"}}));
const std::string targetId = target.value("targetId", std::string());
if (targetId.empty()) throw std::runtime_error("创建标签页失败");
const json attached = cdp->Command("Target.attachToTarget",
json::object({{"targetId", targetId}, {"flatten", true}}));
const std::string sessionId = attached.value("sessionId", std::string());
if (sessionId.empty()) throw std::runtime_error("连接标签页失败");
cdp->Command("Page.enable", json::object(), sessionId);
// 客服页的 CSP connect-src 只放行自家域名,会拦掉 127.0.0.1:3456;
// 必须在导航前开,新文档加载时才生效(扩展 content script 天然豁免,CDP 注入不行)
cdp->Command("Page.setBypassCSP", json::object({{"enabled", true}}), sessionId);
cdp->Command("Page.addScriptToEvaluateOnNewDocument",
json::object({{"source", BuildInjectSource(serverBase, shopId, shopName, shopToken)}}),
sessionId);
cdp->Command("Page.navigate", json::object({{"url", TargetUrl()}}), sessionId);
// 交给输入桥复用:页面通过 /api/trusted 请求真实鼠标/键盘事件
{
std::lock_guard<std::mutex> lock(g_cdpMutex);
g_cdp = cdp;
g_cdpSession = sessionId;
}
// 关掉命令行带出来的那个未注入的标签页,避免客服页开两份
try {
const auto list = Http::GetJson(
"http://127.0.0.1:" + std::to_string(debugPort) + "/json/list", {}, 3000, "");
if (list.data.is_array()) {
for (const json& item : list.data) {
const std::string id = item.value("id", std::string());
const std::string type = item.value("type", std::string());
if (id.empty() || id == targetId || type != "page") continue;
cdp->Command("Target.closeTarget", json::object({{"targetId", id}}));
}
}
} catch (const std::exception&) {
// 清理失败不影响主流程
}
{
std::lock_guard<std::mutex> lock(g_mutex);
g_info.injected = true;
}
ok = true;
message = "已启动" + browser.name + "并注入助手脚本(店铺 " + shopName + ")";
Log::Info(message);
} catch (const std::exception& error) {
message = std::string(error.what());
Log::Error("一键启动失败:" + message);
std::lock_guard<std::mutex> lock(g_mutex);
g_info.error = message;
}
g_launching = false;
if (done) done(ok, message);
}
} // namespace
std::string Browser::DetectName() {
const BrowserCandidate browser = PickBrowser();
return browser.path.empty() ? std::string() : browser.name;
}
Browser::Info Browser::GetInfo() {
std::lock_guard<std::mutex> lock(g_mutex);
return g_info;
}
void Browser::LaunchAsync(std::function<void(bool, const std::string&)> done) {
if (g_launching.exchange(true)) {
if (done) done(false, "正在启动中,请稍候");
return;
}
std::thread([done] { LaunchWorker(done); }).detach();
}
void Browser::Stop() {
{
std::lock_guard<std::mutex> lock(g_mutex);
g_info = Browser::Info{};
}
{
std::lock_guard<std::mutex> lock(g_cdpMutex);
if (g_cdp) {
g_cdp->Close();
g_cdp.reset();
}
g_cdpSession.clear();
}
if (g_job) {
// KILL_ON_JOB_CLOSE:关闭作业句柄即可结束整个进程树
::TerminateJobObject(g_job, 0);
::CloseHandle(g_job);
g_job = nullptr;
}
CloseProcessHandles();
Log::Info("已停止浏览器");
}
// ==================== 物理输入(SendInput)====================
// 安装扩展的场景下浏览器不是客户端拉起的,走不了 CDP;这里用系统级输入注入,
// 事件由操作系统产生,isTrusted 与 user activation 都是真的,且不建立任何调试会话。
namespace {
std::mutex g_physicalMutex;
bool ProcessNameMatches(HWND hwnd, const wchar_t* expected) {
DWORD pid = 0;
::GetWindowThreadProcessId(hwnd, &pid);
if (!pid) return false;
HANDLE process = ::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (!process) return false;
wchar_t path[MAX_PATH]{};
DWORD size = MAX_PATH;
bool matched = false;
// size 是输入输出参数:进来给缓冲区容量,出去给实际长度
if (::QueryFullProcessImageNameW(process, 0, path, &size)) {
const std::wstring full(path, size);
const size_t slash = full.find_last_of(L"\\/");
const std::wstring base = slash == std::wstring::npos ? full : full.substr(slash + 1);
matched = (_wcsicmp(base.c_str(), expected) == 0);
}
::CloseHandle(process);
return matched;
}
bool IsBrowserWindow(HWND hwnd) {
if (!hwnd || !::IsWindow(hwnd)) return false;
return ProcessNameMatches(hwnd, L"chrome.exe") || ProcessNameMatches(hwnd, L"msedge.exe");
}
struct BrowserWindowSearch {
HWND pdd = nullptr;
HWND any = nullptr;
};
BOOL CALLBACK EnumBrowserWindow(HWND hwnd, LPARAM param) {
auto* found = reinterpret_cast<BrowserWindowSearch*>(param);
if (!::IsWindowVisible(hwnd)) return TRUE;
if (::GetWindow(hwnd, GW_OWNER) != nullptr) return TRUE;
if (!IsBrowserWindow(hwnd)) return TRUE;
// 弹窗、气泡这类小窗点上去也落不到页面,按客户区尺寸筛掉
RECT client{};
if (!::GetClientRect(hwnd, &client)) return TRUE;
if (client.right - client.left < 400 || client.bottom - client.top < 300) return TRUE;
wchar_t title[256]{};
::GetWindowTextW(hwnd, title, 256);
if (::wcsstr(title, L"\u62fc\u591a\u591a") != nullptr) {
found->pdd = hwnd;
return FALSE;
}
if (!found->any) found->any = hwnd;
return TRUE;
}
bool IsForegroundOf(HWND target) {
if (!target) return false;
const HWND current = ::GetForegroundWindow();
if (!current) return false;
return current == target || ::GetAncestor(current, GA_ROOT) == target;
}
// SetForegroundWindow 对后台进程默认无效(系统只让任务栏闪一下)。
// 把自己的输入队列临时挂到前台线程和目标线程上,就绕开了那条前台锁。
bool ForceForeground(HWND target) {
if (!target || !::IsWindow(target)) return false;
if (IsForegroundOf(target)) return true;
const HWND previous = ::GetForegroundWindow();
const DWORD selfThread = ::GetCurrentThreadId();
const DWORD previousThread = previous ? ::GetWindowThreadProcessId(previous, nullptr) : 0;
const DWORD targetThread = ::GetWindowThreadProcessId(target, nullptr);
bool attachedPrevious = false;
bool attachedTarget = false;
if (previousThread && previousThread != selfThread) {
attachedPrevious = ::AttachThreadInput(selfThread, previousThread, TRUE) != FALSE;
}
if (targetThread && targetThread != selfThread && targetThread != previousThread) {
attachedTarget = ::AttachThreadInput(selfThread, targetThread, TRUE) != FALSE;
}
if (::IsIconic(target)) {
::ShowWindow(target, SW_RESTORE);
} else {
::ShowWindow(target, SW_SHOW);
}
::BringWindowToTop(target);
::SetForegroundWindow(target);
::SetActiveWindow(target);
if (attachedTarget) ::AttachThreadInput(selfThread, targetThread, FALSE);
if (attachedPrevious) ::AttachThreadInput(selfThread, previousThread, FALSE);
// 前台切换是异步的,轮询几次再判定,避免刚好撞上空档期
for (int attempt = 0; attempt < 12; ++attempt) {
if (IsForegroundOf(target)) return true;
SleepMs(30);
}
return IsForegroundOf(target);
}
// 优先用前台窗口;不在前台时找一个浏览器窗口并抢焦点,抢不到就放弃(绝不乱点别的窗口)
HWND ForegroundBrowserWindow() {
HWND foreground = ::GetForegroundWindow();
if (IsBrowserWindow(foreground)) return foreground;
BrowserWindowSearch found;
::EnumWindows(&EnumBrowserWindow, reinterpret_cast<LPARAM>(&found));
HWND target = found.pdd ? found.pdd : found.any;
if (!target) return nullptr;
if (!ForceForeground(target)) return nullptr;
return target;
}
bool SendClickAt(int screenX, int screenY) {
const int vx = ::GetSystemMetrics(SM_XVIRTUALSCREEN);
const int vy = ::GetSystemMetrics(SM_YVIRTUALSCREEN);
const int vw = ::GetSystemMetrics(SM_CXVIRTUALSCREEN);
const int vh = ::GetSystemMetrics(SM_CYVIRTUALSCREEN);
if (vw <= 1 || vh <= 1) return false;
POINT saved{};
::GetCursorPos(&saved);
auto make = [&](DWORD extra) {
INPUT input{};
input.type = INPUT_MOUSE;
input.mi.dx = static_cast<LONG>(((screenX - vx) * 65535LL) / (vw - 1));
input.mi.dy = static_cast<LONG>(((screenY - vy) * 65535LL) / (vh - 1));
input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK | extra;
return input;
};
INPUT move = make(0);
INPUT down = make(MOUSEEVENTF_LEFTDOWN);
INPUT up = make(MOUSEEVENTF_LEFTUP);
::SendInput(1, &move, sizeof(INPUT));
SleepMs(RandomInt(24, 60));
::SendInput(1, &down, sizeof(INPUT));
SleepMs(RandomInt(36, 90));
::SendInput(1, &up, sizeof(INPUT));
::SetCursorPos(saved.x, saved.y); // 点完把光标还给用户
return true;
}
// 页面只报视口比例和视口尺寸:客户区里除视口外还有标签栏、地址栏。
// 用「客户区宽 / 视口宽」现场标定 CSS 到客户区的换算比例,比猜 dpr 稳:
// 宿主进程声明 DPI 感知时 GetClientRect 给物理像素,不声明时给逻辑像素,
// 两种情况下这个比值都是对的,窗口边框和页面缩放也一并绕开。
bool ClickInViewport(HWND hwnd, double ratioX, double ratioY,
double innerWidth, double innerHeight,
double uiHeight, double dpr) {
RECT client{};
if (!::GetClientRect(hwnd, &client)) return false;
POINT origin{ 0, 0 };
if (!::ClientToScreen(hwnd, &origin)) return false;
const int clientWidth = client.right - client.left;
const int clientHeight = client.bottom - client.top;
if (clientWidth <= 1 || clientHeight <= 1) return false;
const double dpiScale = dpr > 0.1 ? dpr : 1.0;
double viewportHeight = 0.0;
double uiInClient = 0.0;
if (innerWidth > 1.0 && innerHeight > 1.0) {
const double k = static_cast<double>(clientWidth) / innerWidth;
viewportHeight = innerHeight * k;
uiInClient = static_cast<double>(clientHeight) - viewportHeight;
}
// 页面没报视口尺寸,或算出来的 UI 高度离谱,就退回按 dpr 估算
if (viewportHeight <= 1.0 || uiInClient < 0.0 || uiInClient > clientHeight * 0.7) {
uiInClient = uiHeight * dpiScale;
if (uiInClient < 0.0) uiInClient = 0.0;
viewportHeight = static_cast<double>(clientHeight) - uiInClient;
}
if (viewportHeight <= 1.0) return false;
const int screenX = origin.x + static_cast<int>(ratioX * clientWidth);
const int screenY = origin.y + static_cast<int>(uiInClient + ratioY * viewportHeight);
return SendClickAt(screenX, screenY);
}
bool SendVirtualKey(WORD vk) {
INPUT inputs[2]{};
inputs[0].type = INPUT_KEYBOARD;
inputs[0].ki.wVk = vk;
inputs[1].type = INPUT_KEYBOARD;
inputs[1].ki.wVk = vk;
inputs[1].ki.dwFlags = KEYEVENTF_KEYUP;
return ::SendInput(2, inputs, sizeof(INPUT)) == 2;
}
bool SendCtrlKey(WORD vk) {
INPUT inputs[4]{};
for (int i = 0; i < 4; ++i) inputs[i].type = INPUT_KEYBOARD;
inputs[0].ki.wVk = VK_CONTROL;
inputs[1].ki.wVk = vk;
inputs[2].ki.wVk = vk;
inputs[2].ki.dwFlags = KEYEVENTF_KEYUP;
inputs[3].ki.wVk = VK_CONTROL;
inputs[3].ki.dwFlags = KEYEVENTF_KEYUP;
return ::SendInput(4, inputs, sizeof(INPUT)) == 4;
}
std::wstring ReadClipboardText() {
std::wstring text;
if (!::OpenClipboard(nullptr)) return text;
if (HANDLE data = ::GetClipboardData(CF_UNICODETEXT)) {
const auto* raw = static_cast<const wchar_t*>(::GlobalLock(data));
if (raw) {
text.assign(raw);
::GlobalUnlock(data);
}
}
::CloseClipboard();
return text;
}
bool WriteClipboardText(const std::wstring& text) {
if (!::OpenClipboard(nullptr)) return false;
::EmptyClipboard();
const size_t bytes = (text.size() + 1) * sizeof(wchar_t);
HGLOBAL memory = ::GlobalAlloc(GMEM_MOVEABLE, bytes);
if (!memory) {
::CloseClipboard();
return false;
}
void* target = ::GlobalLock(memory);
if (!target) {
::GlobalFree(memory);
::CloseClipboard();
return false;
}
std::memcpy(target, text.c_str(), bytes);
::GlobalUnlock(memory);
if (!::SetClipboardData(CF_UNICODETEXT, memory)) {
::GlobalFree(memory);
::CloseClipboard();
return false;
}
::CloseClipboard();
return true;
}
// 中文走 SendInput 是死路(要过 IME),走剪贴板 + Ctrl+V 才和真人粘贴一致
bool TypeViaClipboard(const std::string& utf8) {
const std::wstring text = Utf8ToWide(utf8);
if (text.empty()) return false;
const std::wstring saved = ReadClipboardText();
if (!WriteClipboardText(text)) return false;
SleepMs(60);
const bool ok = SendCtrlKey('V');
SleepMs(180); // 等页面把剪贴板吃进去再把原内容还回去
if (!saved.empty()) WriteClipboardText(saved);
return ok;
}
bool DispatchPhysical(const json& payload, const std::string& action, std::string& error) {
if (action == "trusted-click") {
const double ratioX = payload.value("ratioX", -1.0);
const double ratioY = payload.value("ratioY", -1.0);
if (!(ratioX >= 0.0) || !(ratioY >= 0.0)) {
error = "缺少视口比例坐标";
return false;
}
HWND hwnd = ForegroundBrowserWindow();
if (!hwnd) {
error = "找不到浏览器窗口或无法切入前台";
return false;
}
if (!ClickInViewport(hwnd, ratioX, ratioY,
payload.value("innerWidth", 0.0),
payload.value("innerHeight", 0.0),
payload.value("uiHeight", 0.0),
payload.value("devicePixelRatio", 1.0))) {
error = "物理点击失败";
return false;
}
return true;
}
if (action == "trusted-insert-text") {
if (!ForegroundBrowserWindow()) {
error = "找不到浏览器窗口或无法切入前台";
return false;
}
if (!TypeViaClipboard(payload.value("text", std::string()))) {
error = "剪贴板输入失败";
return false;
}
return true;
}
if (action == "trusted-enter") {
if (!ForegroundBrowserWindow()) {
error = "找不到浏览器窗口或无法切入前台";
return false;
}
if (!SendVirtualKey(VK_RETURN)) {
error = "回车派发失败";
return false;
}
return true;
}
return false; // 未知动作交给 CDP 分支报错
}
}
// 客户端自己拉起浏览器时才会走到这条路:CDP 直接派发,不动光标、不抢焦点
bool DispatchViaCdp(const json& payload, const std::string& action, std::string& error) {
if (!g_cdp || !g_cdp->Connected()) {
error = "浏览器未启动或调试连接已断开";
return false;
}
// 真实事件由浏览器自己派发:isTrusted 天然为 true,还会触发 user activation,
// 这是页面脚本层面无法伪造的两样东西。
try {
const std::string session = g_cdpSession;
if (action == "trusted-click") {
const double x = payload.value("x", 0.0);
const double y = payload.value("y", 0.0);
if (!(x >= 0.0) || !(y >= 0.0)) {
error = "点击坐标无效";
return false;
}
json move = json::object();
move["type"] = "mouseMoved";
move["x"] = x;
move["y"] = y;
move["button"] = "none";
g_cdp->Command("Input.dispatchMouseEvent", move, session);
SleepMs(RandomInt(20, 60));
json down = json::object();
down["type"] = "mousePressed";
down["x"] = x;
down["y"] = y;
down["button"] = "left";
down["buttons"] = 1;
down["clickCount"] = 1;
g_cdp->Command("Input.dispatchMouseEvent", down, session);
SleepMs(RandomInt(40, 90));
json up = json::object();
up["type"] = "mouseReleased";
up["x"] = x;
up["y"] = y;
up["button"] = "left";
up["buttons"] = 0;
up["clickCount"] = 1;
g_cdp->Command("Input.dispatchMouseEvent", up, session);
return true;
}
if (action == "trusted-insert-text") {
json params = json::object();
params["text"] = payload.value("text", std::string());
g_cdp->Command("Input.insertText", params, session);
return true;
}
if (action == "trusted-enter") {
json down = json::object();
down["type"] = "keyDown";
down["key"] = "Enter";
down["code"] = "Enter";
down["windowsVirtualKeyCode"] = 13;
down["nativeVirtualKeyCode"] = 13;
g_cdp->Command("Input.dispatchKeyEvent", down, session);
SleepMs(RandomInt(30, 70));
json up = json::object();
up["type"] = "keyUp";
up["key"] = "Enter";
up["code"] = "Enter";
up["windowsVirtualKeyCode"] = 13;
up["nativeVirtualKeyCode"] = 13;
g_cdp->Command("Input.dispatchKeyEvent", up, session);
return true;
}
error = "未知动作:" + action;
return false;
} catch (const std::exception& exception) {
error = exception.what();
return false;
}
}
bool Browser::DispatchInput(const json& payload, std::string& error) {
if (!payload.is_object()) {
error = "请求体必须是对象";
return false;
}
const std::string action = payload.value("action", std::string());
const std::string shopId = payload.value("shopId", std::string());
// 内嵌客服台里页面发的动作必须回到它自己那个店铺的 Controller,
// 否则两个店铺同时开着时点击会串台
if (!shopId.empty() && WebConsole::IsOpen(shopId)) {
return WebConsole::DispatchInput(payload, error);
}
// 客户端拉起的浏览器有 CDP,那条路最无感:不动光标、不抢焦点
{
std::lock_guard<std::mutex> lock(g_cdpMutex);
if (g_cdp && g_cdp->Connected() && DispatchViaCdp(payload, action, error)) return true;
}
// 内嵌客服台打开时,输入走 WebView2 自己的输入管线:无调试端口、无横幅、不动真实光标。
// 它失败就直接把错误回给页面,不退回物理点击 —— 两套坐标体系,点错地方更糟
if (WebConsole::IsOpen()) {
return WebConsole::DispatchInput(payload, error);
}
// 安装扩展模式下没有 CDP 会话,改由系统注入物理输入;
// 失败时的 error 会原样回给页面,由它决定是否退回扩展的 debugger 通道
std::lock_guard<std::mutex> lock(g_physicalMutex);
return DispatchPhysical(payload, action, error);
}
}
+39
View File
@@ -0,0 +1,39 @@
#pragma once
#include <functional>
#include <string>
#include "Json.h"
namespace pddai {
// 一键启动:独立配置目录拉起 Chrome/Edge,再通过 CDP 注入 content.js
class Browser {
public:
struct Info {
bool running = false;
std::string browserName; // Chrome / Edge
std::string browserPath;
int port = 0; // 远程调试端口
bool injected = false;
std::string profileDir;
std::string error;
};
// 只用注册表与常见安装路径探测,不启动进程
static std::string DetectName();
static Info GetInfo();
// 异步执行(内部开工作线程),done(成功, 说明) 在结束时回调一次
static void LaunchAsync(std::function<void(bool, const std::string&)> done);
// 关闭 CDP 连接并结束整个浏览器进程树
static void Stop();
// 把页面发来的输入动作转成 CDP Input.* 事件。
// 由浏览器自己派发的事件 isTrusted 天然为 true,页面脚本无法在 JS 层伪造。
static bool DispatchInput(const json& payload, std::string& error);
};
}
+200
View File
@@ -0,0 +1,200 @@
#include "Cdp.h"
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0A00 // WinHTTP WebSocket 需要 Win8 以上
#endif
#include <windows.h>
#include <winhttp.h>
#include <chrono>
#include <stdexcept>
#include <thread>
#include <vector>
#include "Log.h"
#include "Util.h"
namespace pddai {
namespace {
struct UrlParts {
std::wstring host;
int port = 0;
std::wstring path;
};
bool ParseWsUrl(const std::string& url, UrlParts& out) {
// 只支持 ws://,本地调试端口无需 TLS
const std::string prefix = "ws://";
if (url.compare(0, prefix.size(), prefix) != 0) return false;
const size_t hostStart = prefix.size();
const size_t slash = url.find('/', hostStart);
const std::string authority = url.substr(hostStart, slash == std::string::npos ? std::string::npos : slash - hostStart);
out.path = slash == std::string::npos ? std::wstring(L"/") : Utf8ToWide(url.substr(slash));
const size_t colon = authority.rfind(':');
if (colon == std::string::npos) return false;
out.host = Utf8ToWide(authority.substr(0, colon));
try {
out.port = std::stoi(authority.substr(colon + 1));
} catch (const std::exception&) {
return false;
}
return out.port > 0;
}
constexpr DWORD kRecvBufferSize = 256 * 1024;
} // namespace
Cdp::~Cdp() {
Close();
}
bool Cdp::Connect(const std::string& wsUrl) {
Close();
UrlParts parts;
if (!ParseWsUrl(wsUrl, parts)) {
throw std::runtime_error("CDP 地址格式不正确:" + wsUrl);
}
HINTERNET session = ::WinHttpOpen(L"PddAI/1.0", WINHTTP_ACCESS_TYPE_NO_PROXY,
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (!session) throw std::runtime_error("WinHttpOpen 失败");
HINTERNET connect = ::WinHttpConnect(session, parts.host.c_str(), static_cast<INTERNET_PORT>(parts.port), 0);
if (!connect) {
::WinHttpCloseHandle(session);
throw std::runtime_error("WinHttpConnect 失败");
}
HINTERNET request = ::WinHttpOpenRequest(connect, L"GET", parts.path.c_str(), nullptr,
WINHTTP_NO_REFERER, nullptr, 0);
if (!request) {
::WinHttpCloseHandle(connect);
::WinHttpCloseHandle(session);
throw std::runtime_error("WinHttpOpenRequest 失败");
}
// 升级到 WebSocket
BOOL upgraded = ::WinHttpSetOption(request, WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET, nullptr, 0);
if (!upgraded || !::WinHttpSendRequest(request, WINHTTP_NO_REQUEST_DATA, 0,
WINHTTP_NO_REQUEST_DATA, 0, 0, 0) ||
!::WinHttpReceiveResponse(request, nullptr)) {
::WinHttpCloseHandle(request);
::WinHttpCloseHandle(connect);
::WinHttpCloseHandle(session);
throw std::runtime_error("WebSocket 握手失败");
}
HINTERNET socket = ::WinHttpWebSocketCompleteUpgrade(request, 0);
if (!socket) {
::WinHttpCloseHandle(request);
::WinHttpCloseHandle(connect);
::WinHttpCloseHandle(session);
throw std::runtime_error("WebSocket 升级失败(需要 Windows 8 以上)");
}
// 升级成功后 request 句柄即 WebSocket 句柄,不再单独关闭
session_ = session;
connect_ = connect;
socket_ = socket;
nextId_ = 1;
return true;
}
void Cdp::Close() {
if (socket_) {
::WinHttpWebSocketClose(static_cast<HINTERNET>(socket_), WINHTTP_WEB_SOCKET_SUCCESS_CLOSE_STATUS,
nullptr, 0);
::WinHttpCloseHandle(static_cast<HINTERNET>(socket_));
socket_ = nullptr;
}
if (connect_) {
::WinHttpCloseHandle(static_cast<HINTERNET>(connect_));
connect_ = nullptr;
}
if (session_) {
::WinHttpCloseHandle(static_cast<HINTERNET>(session_));
session_ = nullptr;
}
}
bool Cdp::Connected() const {
return socket_ != nullptr;
}
bool Cdp::SendRaw(const std::string& text) {
if (!socket_) return false;
const DWORD result = ::WinHttpWebSocketSend(
static_cast<HINTERNET>(socket_), WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE,
reinterpret_cast<PVOID>(const_cast<char*>(text.data())), static_cast<DWORD>(text.size()));
return result == ERROR_SUCCESS;
}
bool Cdp::RecvRaw(std::string& out, int timeoutMs) {
if (!socket_) return false;
std::vector<char> buffer(kRecvBufferSize);
out.clear();
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
for (;;) {
DWORD read = 0;
WINHTTP_WEB_SOCKET_BUFFER_TYPE type = static_cast<WINHTTP_WEB_SOCKET_BUFFER_TYPE>(0);
const DWORD result = ::WinHttpWebSocketReceive(static_cast<HINTERNET>(socket_), buffer.data(),
static_cast<DWORD>(buffer.size()), &read, &type);
if (result != ERROR_SUCCESS) return false;
if (read > 0) out.append(buffer.data(), static_cast<size_t>(read));
// 分片消息一直收到完整消息为止;关闭帧直接结束
if (type == WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE) return false;
if (type == WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE) return true;
if (std::chrono::steady_clock::now() >= deadline) return !out.empty();
}
}
json Cdp::Command(const std::string& method, const json& params, const std::string& sessionId,
int timeoutMs) {
if (!socket_) throw std::runtime_error("CDP 未连接");
const int id = nextId_++;
json request = json::object();
request["id"] = id;
request["method"] = method;
request["params"] = params.is_null() ? json::object() : params;
if (!sessionId.empty()) request["sessionId"] = sessionId;
if (!SendRaw(request.dump())) throw std::runtime_error("CDP 发送失败:" + method);
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
while (std::chrono::steady_clock::now() < deadline) {
std::string raw;
const int remain = static_cast<int>(
std::chrono::duration_cast<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now()).count());
if (!RecvRaw(raw, remain > 0 ? remain : 1)) break;
const json message = json::parse(raw, nullptr, false);
if (message.is_discarded() || !message.is_object()) continue;
// 事件消息没有 id,直接跳过
const auto idIt = message.find("id");
if (idIt == message.end() || !idIt->is_number_integer() || idIt->get<int>() != id) continue;
const auto errorIt = message.find("error");
if (errorIt != message.end() && errorIt->is_object()) {
const std::string text = errorIt->value("message", std::string());
throw std::runtime_error("CDP " + method + " 失败:" + text);
}
const auto resultIt = message.find("result");
return resultIt == message.end() ? json::object() : *resultIt;
}
throw std::runtime_error("CDP " + method + " 超时未响应");
}
}
+37
View File
@@ -0,0 +1,37 @@
#pragma once
#include <string>
#include "Json.h"
namespace pddai {
// 极简 CDP 客户端:WinHTTP 的 WebSocket 升级实现,只覆盖注入脚本所需的能力
class Cdp {
public:
Cdp() = default;
~Cdp();
// wsUrl 形如 ws://127.0.0.1:9222/devtools/browser/xxxxxxxx
bool Connect(const std::string& wsUrl);
void Close();
bool Connected() const;
// sessionId 为空表示浏览器级命令;返回 result 字段,错误抛 std::runtime_error
json Command(const std::string& method, const json& params,
const std::string& sessionId = std::string(), int timeoutMs = 15000);
private:
Cdp(const Cdp&) = delete;
Cdp& operator=(const Cdp&) = delete;
bool SendRaw(const std::string& text);
bool RecvRaw(std::string& out, int timeoutMs);
void* session_ = nullptr;
void* connect_ = nullptr;
void* socket_ = nullptr;
int nextId_ = 1;
};
}
+769
View File
@@ -0,0 +1,769 @@
#include "Config.h"
#include <windows.h>
#include <shlobj.h>
#include <algorithm>
#include <cstdio>
#include <fstream>
#include <mutex>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <vector>
#include "Log.h"
#include "Util.h"
namespace pddai {
namespace {
struct CacheEntry {
uint64_t size = 0;
int64_t mtime = 0;
json value;
};
std::mutex g_mutex;
std::wstring g_dir;
std::unordered_map<std::wstring, CacheEntry> g_cache;
std::unordered_map<std::string, std::string> g_env;
// 每请求 / 每 UI 消息的店铺作用域,空表示全局配置
thread_local std::string g_shop;
std::string ToLower(std::string s) {
for (char& c : s) {
if (c >= 'A' && c <= 'Z') c = static_cast<char>(c - 'A' + 'a');
}
return s;
}
bool IsDirectory(const std::wstring& path) {
const DWORD attr = ::GetFileAttributesW(path.c_str());
return attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0;
}
bool FileExists(const std::wstring& path) {
const DWORD attr = ::GetFileAttributesW(path.c_str());
return attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0;
}
std::wstring JoinPath(const std::wstring& dir, const std::wstring& name) {
if (dir.empty()) return name;
if (dir.back() == L'\\' || dir.back() == L'/') return dir + name;
return dir + L"\\" + name;
}
bool IsWritableDir(const std::wstring& dir) {
const std::wstring probe = JoinPath(dir, L".pddai-write-test");
HANDLE h = ::CreateFileW(probe.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, nullptr);
if (h == INVALID_HANDLE_VALUE) return false;
::CloseHandle(h);
return true;
}
std::wstring Canonicalize(const std::wstring& path) {
wchar_t buf[MAX_PATH]{};
const DWORD n = ::GetFullPathNameW(path.c_str(), MAX_PATH, buf, nullptr);
return n > 0 && n < MAX_PATH ? std::wstring(buf, n) : path;
}
std::wstring LowerPathKey(std::wstring path) {
for (wchar_t& c : path) {
if (c >= L'A' && c <= L'Z') c = static_cast<wchar_t>(c - L'A' + L'a');
}
return path;
}
std::string TrimShopId(const std::string& id) {
size_t begin = 0;
size_t end = id.size();
while (begin < end && (id[begin] == ' ' || id[begin] == '\t' || id[begin] == '\r' || id[begin] == '\n')) ++begin;
while (end > begin && (id[end - 1] == ' ' || id[end - 1] == '\t' || id[end - 1] == '\r' || id[end - 1] == '\n')) --end;
return id.substr(begin, end - begin);
}
std::wstring ShopRoot() {
return JoinPath(g_dir, L"shops");
}
bool QueryStamp(const std::wstring& path, uint64_t& size, int64_t& mtime);
std::string ReadFileUtf8(const std::wstring& path);
void WriteFileUtf8At(const std::wstring& path, const std::string& fileName, const std::string& text);
std::wstring ShopFile(const std::string& shopId, const std::string& fileName) {
return JoinPath(JoinPath(ShopRoot(), Utf8ToWide(shopId)), Utf8ToWide(fileName));
}
// 店铺文件存在就用店铺文件,否则回落全局文件
std::wstring ResolvePath(const std::string& fileName, bool scoped) {
const std::wstring global = JoinPath(g_dir, Utf8ToWide(fileName));
if (!scoped || g_shop.empty()) return global;
const std::wstring inner = ShopFile(g_shop, fileName);
return FileExists(inner) ? inner : global;
}
json ReadJsonAt(const std::wstring& path, const std::string& fileName) {
uint64_t size = 0;
int64_t mtime = 0;
if (!QueryStamp(path, size, mtime)) return json();
const std::wstring key = LowerPathKey(path);
{
std::lock_guard<std::mutex> lock(g_mutex);
const auto it = g_cache.find(key);
if (it != g_cache.end() && it->second.size == size && it->second.mtime == mtime) {
return it->second.value;
}
}
std::string content;
json parsed;
try {
content = ReadFileUtf8(path);
parsed = json::parse(content, nullptr, false);
} catch (const std::exception& error) {
throw std::runtime_error("读取配置失败 " + fileName + ": " + error.what());
}
if (parsed.is_discarded()) {
throw std::runtime_error("读取配置失败 " + fileName + ": JSON 格式错误");
}
CacheEntry entry;
entry.size = size;
entry.mtime = mtime;
entry.value = parsed;
std::lock_guard<std::mutex> lock(g_mutex);
g_cache[key] = entry;
return entry.value;
}
bool QueryStamp(const std::wstring& path, uint64_t& size, int64_t& mtime) {
WIN32_FILE_ATTRIBUTE_DATA data{};
if (!::GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &data)) return false;
if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) return false;
size = (static_cast<uint64_t>(data.nFileSizeHigh) << 32) | data.nFileSizeLow;
ULARGE_INTEGER ul{};
ul.HighPart = data.ftLastWriteTime.dwHighDateTime;
ul.LowPart = data.ftLastWriteTime.dwLowDateTime;
mtime = static_cast<int64_t>(ul.QuadPart);
return true;
}
std::string ReadFileUtf8(const std::wstring& path) {
std::ifstream in(path, std::ios::binary);
if (!in) throw std::runtime_error("无法打开文件");
std::string content((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
// 去掉 UTF-8 BOM
if (content.size() >= 3 && static_cast<unsigned char>(content[0]) == 0xEF &&
static_cast<unsigned char>(content[1]) == 0xBB && static_cast<unsigned char>(content[2]) == 0xBF) {
content.erase(0, 3);
}
return content;
}
void WriteFileUtf8At(const std::wstring& path, const std::string& fileName, const std::string& text) {
std::ofstream out(path, std::ios::binary | std::ios::trunc);
if (!out) throw std::runtime_error("无法写入配置 " + fileName);
out << text;
out.flush();
if (!out) throw std::runtime_error("写入配置失败 " + fileName);
// JSON 缓存按 (大小, mtime) 判脏,同名同长时可能命中旧值,这里按路径直接失效
std::lock_guard<std::mutex> lock(g_mutex);
g_cache.erase(LowerPathKey(path));
}
// 复刻 JS 的 String(value)
std::string AsString(const json& value) {
if (value.is_string()) return value.get<std::string>();
if (value.is_null()) return "";
if (value.is_boolean()) return value.get<bool>() ? "true" : "false";
if (value.is_number_integer()) return std::to_string(value.get<long long>());
if (value.is_number_unsigned()) return std::to_string(value.get<unsigned long long>());
if (value.is_number_float()) {
char buf[64];
std::snprintf(buf, sizeof(buf), "%.17g", value.get<double>());
return std::string(buf);
}
return value.dump();
}
json NormalizeShop(const json& item, int index) {
if (!item.is_object()) return json(); // null,对应 filter(Boolean)
json out = item;
std::string id = AsString(item.value("id", json()));
if (id.empty()) id = AsString(item.value("shopId", json()));
id = Trim(id);
if (id.empty()) return json();
std::string name = AsString(item.value("name", json()));
if (name.empty()) name = AsString(item.value("shopName", json()));
name = Trim(name);
if (name.empty()) name = "店铺" + std::to_string(index + 1);
std::string token = AsString(item.value("pluginToken", json()));
if (token.empty()) token = AsString(item.value("token", json()));
out["id"] = id;
out["name"] = name;
out["pluginToken"] = Trim(token);
return out;
}
void WriteDefaultConfig(const std::wstring& dir) {
::CreateDirectoryW(dir.c_str(), nullptr);
const std::wstring serverPath = JoinPath(dir, L"server.json");
if (!FileExists(serverPath)) {
const std::string server =
"{\n"
" \"port\": 3456,\n"
" \"host\": \"127.0.0.1\",\n"
" \"controlToken\": \"\",\n"
" \"dailyPauseTime\": \"07:50\",\n"
" \"apiMode\": \"responses\",\n"
" \"imageSaveEnabled\": true,\n"
" \"imageGroupByShop\": true,\n"
" \"imageGroupByOrder\": true,\n"
" \"imageAssignMode\": \"hybrid\",\n"
" \"imageConcurrentMs\": 60000,\n"
" \"imageBatchGapMs\": 180000,\n"
" \"imageHistoryLeadMs\": 600000,\n"
" \"imageCountCheck\": true,\n"
" \"imageCountNoteEnabled\": true,\n"
" \"imageReceiptReplyEnabled\": false,\n"
" \"receiptShortageReply\": \"已收到您发来的{total}张照片,规格是{expected}张,还差{gap}张,麻烦您补齐后我一并处理。\",\n"
" \"receiptOverflowReply\": \"已收到您发来的{total}张照片,规格是{expected}张,多了{gap}张,我先按规格数量处理,您看多余的照片是否需要调整。\",\n"
" \"imageReviewEnabled\": true,\n"
" \"imageReviewDirName\": \"待确认\",\n"
" \"imageAdjustEnabled\": true,\n"
" \"imageAdjustReplyEnabled\": true,\n"
" \"imageAdjustReplaceWords\": \"替换,换成,换掉,换一张,换一下,换下,更换,改成,改为,换个\",\n"
" \"imageAdjustDeleteWords\": \"删掉,删除,去掉,不要,不想要,不需要,不用,取消,移除,删了\",\n"
" \"imageAdjustResendWords\": \"重新发,重发,再发一张,补发\",\n"
" \"imageAdjustPointWords\": \"这个,这张,那张,这幅,那幅,这张图,这个图,它\",\n"
" \"imageAdjustNegativeWords\": \"不要,不用,不需要,无需,别,勿\",\n"
" \"imageAdjustMatchThreshold\": 8,\n"
" \"imageAdjustMode\": \"rules\",\n"
" \"imageAdjustAiConfidence\": 0.75,\n"
" \"imageReplacedDirName\": \"已替换\",\n"
" \"adjustReplaceReply\": \"好的,已用您新发的照片替换第{index}张,当前共{total}张。\",\n"
" \"adjustDeleteReply\": \"好的,已为您删除第{index}张,当前共{total}张。\",\n"
" \"imageKeepOrderTab\": true,\n"
" \"orderStatusNormal\": true,\n"
" \"orderStatusDone\": true,\n"
" \"orderStatusRefund\": true,\n"
" \"imageOutputDir\": \"\",\n"
" \"historyLimit\": 6,\n"
" \"minReplyDelayMs\": 3000,\n"
" \"maxReplyDelayMs\": 8000,\n"
" \"minPageDelayMs\": 150,\n"
" \"maxPageDelayMs\": 400,\n"
" \"riskStopOnHit\": true,\n"
" \"mockWhenNoApiKey\": true,\n"
" \"modelTimeoutMs\": 45000\n"
"}\n";
std::ofstream out(serverPath, std::ios::binary);
out << server;
}
const std::wstring shopsPath = JoinPath(dir, L"shops.json");
if (!FileExists(shopsPath)) {
const std::string shops =
"[\n"
" { \"id\": \"default\", \"name\": \"默认店铺\", \"pluginToken\": \"\" }\n"
"]\n";
std::ofstream out(shopsPath, std::ios::binary);
out << shops;
}
}
void ParseDotEnv(const std::wstring& path) {
std::string content;
try {
content = ReadFileUtf8(path);
} catch (const std::exception&) {
return;
}
size_t pos = 0;
while (pos <= content.size()) {
const size_t end = content.find('\n', pos);
const size_t stop = end == std::string::npos ? content.size() : end;
std::string line = content.substr(pos, stop - pos);
pos = stop + 1;
if (!line.empty() && line.back() == '\r') line.pop_back();
const std::string trimmed = Trim(line);
if (trimmed.empty() || trimmed[0] == '#') continue;
const size_t eq = trimmed.find('=');
if (eq == std::string::npos || eq == 0) continue;
const std::string key = Trim(trimmed.substr(0, eq));
std::string value = Trim(trimmed.substr(eq + 1));
if (value.size() >= 2) {
const char first = value.front();
const char last = value.back();
if ((first == '"' && last == '"') || (first == '\'' && last == '\'')) {
value = value.substr(1, value.size() - 2);
}
}
if (key.empty()) continue;
// 对齐 Node:已有同名进程环境变量时不覆盖
const std::wstring wkey = Utf8ToWide(key);
if (::GetEnvironmentVariableW(wkey.c_str(), nullptr, 0) > 0) continue;
g_env[key] = value;
}
}
} // namespace
Config::InitResult Config::Init(const std::wstring& cliDir) {
std::lock_guard<std::mutex> lock(g_mutex);
InitResult result{};
const std::wstring exe = ExeDir();
const std::wstring localApp = GetLocalAppDataDir();
std::vector<std::wstring> candidates;
if (!cliDir.empty()) candidates.push_back(cliDir);
// 绿色分发:优先 exe 目录下的 config,其次开发目录(exe\..\..\config),
// 最后才是旧版本遗留的用户目录配置
candidates.push_back(JoinPath(exe, L"config"));
candidates.push_back(JoinPath(JoinPath(exe, L".."), L"..\\config"));
candidates.push_back(JoinPath(JoinPath(localApp, L"PddAI"), L"config"));
for (const std::wstring& c : candidates) {
if (IsDirectory(c)) {
result.dir = Canonicalize(c);
break;
}
}
if (result.dir.empty()) {
// 默认生成在 exe 目录旁;exe 目录只读(如 Program Files)才退回用户目录
std::wstring dir = JoinPath(exe, L"config");
if (!IsWritableDir(exe)) {
dir = JoinPath(JoinPath(localApp, L"PddAI"), L"config");
}
WriteDefaultConfig(dir);
result.dir = Canonicalize(dir);
result.seeded = true;
}
g_dir = result.dir;
g_cache.clear();
g_env.clear();
// .env:配置目录的上一级优先,其次配置目录本身
const std::wstring parentEnv = JoinPath(JoinPath(g_dir, L".."), L".env");
if (FileExists(parentEnv)) {
ParseDotEnv(parentEnv);
} else {
ParseDotEnv(JoinPath(g_dir, L".env"));
}
return result;
}
const std::wstring& Config::Dir() {
std::lock_guard<std::mutex> lock(g_mutex);
return g_dir;
}
json Config::GetJson(const std::string& fileName, const json& fallback) {
const std::wstring path = ResolvePath(fileName, true);
uint64_t size = 0;
int64_t mtime = 0;
if (!QueryStamp(path, size, mtime)) return fallback;
const json value = ReadJsonAt(path, fileName);
if (!value.is_object() && !value.is_array()) return value.is_null() ? fallback : value;
// 店铺只存与店铺相关的键,端口/监听地址这类仍取全局,合并后店铺值优先
if (!g_shop.empty() && fileName == "server.json" && value.is_object()) {
const std::wstring globalPath = JoinPath(g_dir, Utf8ToWide(fileName));
if (path != globalPath) {
json base = ReadJsonAt(globalPath, fileName);
if (base.is_object()) {
for (auto it = value.begin(); it != value.end(); ++it) base[it.key()] = it.value();
return base;
}
}
}
return value;
}
std::string Config::GetText(const std::string& fileName, const std::string& fallback) {
const std::wstring path = ResolvePath(fileName, true);
uint64_t size = 0;
int64_t mtime = 0;
if (!QueryStamp(path, size, mtime)) return fallback;
try {
return ReadFileUtf8(path);
} catch (const std::exception& error) {
throw std::runtime_error("读取配置失败 " + fileName + ": " + error.what());
}
}
json Config::GetJsonGlobal(const std::string& fileName, const json& fallback) {
const std::wstring path = JoinPath(Dir(), Utf8ToWide(fileName));
uint64_t size = 0;
int64_t mtime = 0;
if (!QueryStamp(path, size, mtime)) return fallback;
const json value = ReadJsonAt(path, fileName);
return value.is_null() ? fallback : value;
}
std::string Config::GetTextGlobal(const std::string& fileName, const std::string& fallback) {
const std::wstring path = JoinPath(Dir(), Utf8ToWide(fileName));
uint64_t size = 0;
int64_t mtime = 0;
if (!QueryStamp(path, size, mtime)) return fallback;
try {
return ReadFileUtf8(path);
} catch (const std::exception& error) {
throw std::runtime_error("读取配置失败 " + fileName + ": " + error.what());
}
}
std::wstring Config::ShopDir(const std::string& shopId) {
const std::string id = TrimShopId(shopId);
if (!IsSafeShopId(id)) return std::wstring();
::CreateDirectoryW(ShopRoot().c_str(), nullptr);
const std::wstring dir = JoinPath(ShopRoot(), Utf8ToWide(id));
::CreateDirectoryW(dir.c_str(), nullptr);
return dir;
}
static bool IsImageFileName(const std::string& name) {
const std::string lower = ToLower(name);
const size_t dot = lower.find_last_of('.');
if (dot == std::string::npos) return false;
const std::string ext = lower.substr(dot + 1);
return ext == "png" || ext == "jpg" || ext == "jpeg" || ext == "gif" || ext == "webp" || ext == "bmp";
}
std::wstring Config::ImageLibraryDir(const std::string& shopId) {
std::wstring dir = JoinPath(ExeDir(), L"images");
const std::wstring shopDir = ShopDir(shopId);
if (!shopDir.empty()) {
const std::wstring configPath = JoinPath(shopDir, L"image-library.json");
if (FileExists(configPath)) {
const json parsed = json::parse(ReadFileUtf8(configPath), nullptr, false);
if (parsed.is_object()) {
const std::string custom = parsed.value("dir", std::string());
if (!custom.empty()) dir = Utf8ToWide(custom);
}
}
}
if (!IsDirectory(dir)) ::CreateDirectoryW(dir.c_str(), nullptr);
return dir;
}
// 旧版界面把上传的图片放在店铺目录的 images/ 下;拷进图片库目录,保证升级后仍能在图片库里看到
static void MigrateLegacyImages(const std::wstring& shopDir, const std::wstring& libraryDir) {
if (shopDir.empty()) return;
const std::wstring legacy = JoinPath(shopDir, L"images");
if (!IsDirectory(legacy) || LowerPathKey(legacy) == LowerPathKey(libraryDir)) return;
WIN32_FIND_DATAW fd{};
HANDLE h = ::FindFirstFileW(JoinPath(legacy, L"*").c_str(), &fd);
if (h == INVALID_HANDLE_VALUE) return;
do {
if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) continue;
const std::string name = WideToUtf8(fd.cFileName);
if (!IsImageFileName(name)) continue;
const std::wstring src = JoinPath(legacy, Utf8ToWide(name));
const std::wstring dst = JoinPath(libraryDir, Utf8ToWide(name));
if (FileExists(dst)) continue;
// 迁移后删掉旧副本,避免用户从图片库删图后又被自动拷回来
if (!::MoveFileExW(src.c_str(), dst.c_str(), MOVEFILE_COPY_ALLOWED)) continue;
Log::Info("已迁移旧版配图 " + name + " 到图片库目录");
} while (::FindNextFileW(h, &fd));
::FindClose(h);
}
json Config::ScanImageLibrary(const std::string& shopId) {
json out = json::array();
const std::wstring dir = ImageLibraryDir(shopId);
if (!IsDirectory(dir)) return out;
// 元数据按文件名索引;文件本身才是图片库的真实内容
json meta = json::array();
const std::wstring shopDir = ShopDir(shopId);
MigrateLegacyImages(shopDir, dir);
if (!shopDir.empty()) {
const std::wstring metaPath = JoinPath(shopDir, L"images.json");
if (FileExists(metaPath)) {
meta = json::parse(ReadFileUtf8(metaPath), nullptr, false);
if (!meta.is_array()) meta = json::array();
}
}
std::vector<std::string> files;
WIN32_FIND_DATAW fd{};
HANDLE h = ::FindFirstFileW(JoinPath(dir, L"*").c_str(), &fd);
if (h != INVALID_HANDLE_VALUE) {
do {
if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) continue;
const std::string name = WideToUtf8(fd.cFileName);
if (IsImageFileName(name)) files.push_back(name);
} while (::FindNextFileW(h, &fd));
::FindClose(h);
}
std::sort(files.begin(), files.end());
for (const std::string& file : files) {
json entry = json::object();
entry["file"] = file;
const size_t dot = file.find_last_of('.');
entry["name"] = dot == std::string::npos ? file : file.substr(0, dot);
entry["keywords"] = json::array();
entry["withText"] = true;
for (const json& item : meta) {
if (!item.is_object()) continue;
std::string metaFile = item.value("file", std::string());
const size_t slash = metaFile.find_last_of('/');
if (slash != std::string::npos) metaFile = metaFile.substr(slash + 1);
if (metaFile != file) continue;
const std::string name = item.value("name", std::string());
if (!name.empty()) entry["name"] = name;
if (item.contains("keywords") && item["keywords"].is_array()) entry["keywords"] = item["keywords"];
if (item.contains("withText") && item["withText"].is_boolean()) entry["withText"] = item["withText"];
break;
}
out.push_back(entry);
}
return out;
}
std::wstring Config::Path(const std::string& fileName) {
return ResolvePath(fileName, true);
}
void Config::WriteText(const std::string& fileName, const std::string& text) {
std::wstring path = JoinPath(Dir(), Utf8ToWide(fileName));
if (!g_shop.empty()) {
const std::wstring dir = JoinPath(ShopRoot(), Utf8ToWide(g_shop));
::CreateDirectoryW(ShopRoot().c_str(), nullptr);
::CreateDirectoryW(dir.c_str(), nullptr);
path = JoinPath(dir, Utf8ToWide(fileName));
}
WriteFileUtf8At(path, fileName, text);
}
void Config::WriteTextGlobal(const std::string& fileName, const std::string& text) {
const std::wstring path = JoinPath(Dir(), Utf8ToWide(fileName));
WriteFileUtf8At(path, fileName, text);
}
std::string Config::Env(const std::string& key) {
const std::wstring wkey = Utf8ToWide(key);
const DWORD need = ::GetEnvironmentVariableW(wkey.c_str(), nullptr, 0);
if (need > 0) {
std::wstring buf(static_cast<size_t>(need), L'\0');
const DWORD n = ::GetEnvironmentVariableW(wkey.c_str(), buf.data(), need);
if (n > 0 && n < need) {
buf.resize(n);
return WideToUtf8(buf);
}
}
std::lock_guard<std::mutex> lock(g_mutex);
const auto it = g_env.find(key);
return it == g_env.end() ? std::string() : it->second;
}
void Config::ReloadEnv() {
std::lock_guard<std::mutex> lock(g_mutex);
g_env.clear();
const std::wstring parentEnv = JoinPath(JoinPath(g_dir, L".."), L".env");
if (FileExists(parentEnv)) {
ParseDotEnv(parentEnv);
} else {
ParseDotEnv(JoinPath(g_dir, L".env"));
}
}
int Config::Port() {
const json config = GetJson("server.json", json::object());
const std::string fromEnv = Env("PDD_ASSISTANT_PORT");
if (!fromEnv.empty()) {
try {
return std::stoi(fromEnv);
} catch (const std::exception&) {
// 忽略非法值,回退到配置文件
}
}
const json portValue = config.is_object() ? config.value("port", json()) : json();
if (portValue.is_number()) return portValue.get<int>();
if (portValue.is_string()) {
try {
return std::stoi(portValue.get<std::string>());
} catch (const std::exception&) {
return 3456;
}
}
return 3456;
}
std::string Config::Host() {
const json config = GetJson("server.json", json::object());
const std::string fromEnv = Env("PDD_ASSISTANT_HOST");
if (!fromEnv.empty()) return fromEnv;
const json hostValue = config.is_object() ? config.value("host", json()) : json();
if (hostValue.is_string() && !hostValue.get<std::string>().empty()) return hostValue.get<std::string>();
return "127.0.0.1";
}
std::string Config::DailyPauseTime() {
const json config = GetJson("server.json", json::object());
const std::string fromEnv = Env("PDD_DAILY_PAUSE_TIME");
if (!fromEnv.empty()) return fromEnv;
const json v = config.is_object() ? config.value("dailyPauseTime", json()) : json();
if (v.is_string() && !v.get<std::string>().empty()) return v.get<std::string>();
return "07:50";
}
std::string Config::ControlToken() {
const json config = GetJson("server.json", json::object());
const std::string fromEnv = Env("PDD_CONTROL_TOKEN");
if (!fromEnv.empty()) return fromEnv;
const json v = config.is_object() ? config.value("controlToken", json()) : json();
return v.is_string() ? v.get<std::string>() : std::string();
}
std::string Config::DefaultReceiptShortageReply() {
return "已收到您发来的{total}张照片,规格是{expected}张,还差{gap}张,麻烦您补齐后我一并处理。";
}
std::string Config::DefaultReceiptOverflowReply() {
return "已收到您发来的{total}张照片,规格是{expected}张,多了{gap}张,我先按规格数量处理,您看多余的照片是否需要调整。";
}
std::string Config::DefaultAdjustReplaceReply() {
return "好的,已用您新发的照片替换第{index}张,当前共{total}张。";
}
std::string Config::DefaultAdjustDeleteReply() {
return "好的,已为您删除第{index}张,当前共{total}张。";
}
std::string Config::DefaultAdjustReplaceWords() {
return "替换,换成,换掉,换一张,换一下,换下,更换,改成,改为,换个";
}
std::string Config::DefaultAdjustDeleteWords() {
return "删掉,删除,去掉,不要,不想要,不需要,不用,取消,移除,删了";
}
std::string Config::DefaultAdjustResendWords() {
return "重新发,重发,再发一张,补发";
}
std::string Config::DefaultAdjustPointWords() {
return "这个,这张,那张,这幅,那幅,这张图,这个图,它";
}
std::string Config::DefaultAdjustNegativeWords() {
return "不要,不用,不需要,无需,别,勿";
}
json Config::LoadShops() {
json raw = GetJson("shops.json", json::array());
if (!raw.is_array()) raw = json::array();
json result = json::array();
int index = 0;
for (const json& item : raw) {
const json shop = NormalizeShop(item, index);
++index;
if (!shop.is_null()) result.push_back(shop);
}
if (!result.empty()) return result;
json fallback = json::object();
fallback["id"] = "default";
fallback["name"] = "默认店铺";
fallback["pluginToken"] = "";
json only = json::array();
only.push_back(fallback);
return only;
}
// ---------- 每店铺配置 ----------
bool Config::IsSafeShopId(const std::string& shopId) {
const std::string id = TrimShopId(shopId);
if (id.empty() || id.size() > 64) return false;
if (id.find("..") != std::string::npos) return false;
for (const char c : id) {
const bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
c == '-' || c == '_' || c == '.';
if (!ok) return false;
}
return true;
}
std::string Config::CurrentShop() {
return g_shop;
}
Config::ShopScope::ShopScope(const std::string& shopId) : previous_(g_shop) {
const std::string id = TrimShopId(shopId);
g_shop = IsSafeShopId(id) ? id : std::string();
}
Config::ShopScope::~ShopScope() {
g_shop = previous_;
}
void Config::EnsureShopLayout(const std::string& shopId) {
if (!IsSafeShopId(shopId)) return;
const std::wstring root = ShopRoot();
const std::wstring dir = JoinPath(root, Utf8ToWide(TrimShopId(shopId)));
::CreateDirectoryW(root.c_str(), nullptr);
::CreateDirectoryW(dir.c_str(), nullptr);
// 新店铺从全局模板复制一份,之后完全独立;已存在的文件不覆盖
static const char* const kTemplates[] = {
"products.json", "knowledge.json", "persona.json", "quick-replies.json",
"risk-intents.json", "manual-handoff-whitelist.json", "tone-examples.json",
"system-prompt.md", "reply-guidelines.md", "server.json", "mail.json", "faq.json"
};
for (const char* name : kTemplates) {
const std::wstring src = JoinPath(g_dir, Utf8ToWide(std::string(name)));
const std::wstring dst = JoinPath(dir, Utf8ToWide(std::string(name)));
if (!FileExists(src) || FileExists(dst)) continue;
try {
WriteFileUtf8At(dst, std::string(name), ReadFileUtf8(src));
} catch (const std::exception& error) {
Log::Error("初始化店铺配置失败 " + std::string(name) + ": " + error.what());
}
}
}
void Config::MigrateShops() {
for (const json& shop : LoadShops()) {
if (!shop.is_object()) continue;
EnsureShopLayout(shop.value("id", std::string()));
}
}
}
+94
View File
@@ -0,0 +1,94 @@
#pragma once
#include <string>
#include "Json.h"
namespace pddai {
// 配置读写:目录解析 + .env 覆盖 + 按 (大小, mtime) 判脏的热加载
class Config {
public:
struct InitResult {
std::wstring dir; // 规范化后的绝对路径
bool seeded = false; // 是否刚新建并写入默认配置
};
// cliDir 为空时按优先级探测:exeDir\config > %LOCALAPPDATA%\PddAI\config > exeDir\..\..\config
static InitResult Init(const std::wstring& cliDir = std::wstring());
static const std::wstring& Dir();
// 解析失败抛 std::runtime_error(对齐 Node:非 ENOENT 不回退)
static json GetJson(const std::string& fileName, const json& fallback);
static std::string GetText(const std::string& fileName, const std::string& fallback = "");
// 忽略店铺作用域,直接读 / 写全局配置(端口、监听地址这类与店铺无关的键)
static json GetJsonGlobal(const std::string& fileName, const json& fallback);
static std::string GetTextGlobal(const std::string& fileName, const std::string& fallback = "");
static void WriteTextGlobal(const std::string& fileName, const std::string& text);
// 每店铺配置作用域:作用域内 GetJson/GetText/WriteText 走 config/shops/<id>/,
// 读取时该店铺文件不存在则回落全局文件;server.json 会与全局合并(店铺优先)。
class ShopScope {
public:
explicit ShopScope(const std::string& shopId);
~ShopScope();
ShopScope(const ShopScope&) = delete;
ShopScope& operator=(const ShopScope&) = delete;
private:
std::string previous_;
};
static std::string CurrentShop();
static bool IsSafeShopId(const std::string& shopId);
// 首次使用时把全局模板复制到 shops/<id>/,已有文件不覆盖
static void EnsureShopLayout(const std::string& shopId);
static void MigrateShops();
// 店铺配置目录 config/shops/<id>,目录不存在时创建;shopId 非法时返回空
static std::wstring ShopDir(const std::string& shopId);
// 图片库目录:店铺配置 image-library.json 里指定了就用它,否则用 exe 目录下的 images
static std::wstring ImageLibraryDir(const std::string& shopId);
// 扫描图片库目录,并按 images.json 里的元数据合并名称/触发词/发送方式
static json ScanImageLibrary(const std::string& shopId);
// 配置文件的绝对路径,便于在资源管理器里打开
static std::wstring Path(const std::string& fileName);
// 覆盖写入 UTF-8 文本,并让该文件名的热加载缓存立即失效
static void WriteText(const std::string& fileName, const std::string& text);
// 进程环境变量优先,其次 .env
static std::string Env(const std::string& key);
static void ReloadEnv();
static int Port();
static std::string Host();
static std::string DailyPauseTime();
static std::string ControlToken();
// 复刻 loadShops + normalizeShop,无 shops.json 时回退默认店铺
static json LoadShops();
// 图片数量不符时的默认回复文案(支持 {total} {expected} {gap} 占位符)
static std::string DefaultReceiptShortageReply();
static std::string DefaultReceiptOverflowReply();
// 买家要求替换/删除第 N 张图时的默认确认文案(支持 {index} {total} {expected} {gap})
static std::string DefaultAdjustReplaceReply();
static std::string DefaultAdjustDeleteReply();
// 图片调整指令的默认识别词(逗号分隔,可在图片设置页修改)
static std::string DefaultAdjustReplaceWords();
static std::string DefaultAdjustDeleteWords();
static std::string DefaultAdjustResendWords();
static std::string DefaultAdjustPointWords();
static std::string DefaultAdjustNegativeWords();
};
}
+289
View File
@@ -0,0 +1,289 @@
#include "Http.h"
#include <windows.h>
#include <winhttp.h>
#include <stdexcept>
#include <string>
#include <vector>
#include "Json.h"
#include "Util.h"
namespace pddai {
namespace {
struct UrlParts {
bool https = false;
std::wstring host;
int port = 0;
std::wstring path;
};
std::runtime_error MakeError(const std::string& action, DWORD code) {
std::string msg = action;
if (code) msg += " 失败,Win32=" + std::to_string(code);
else msg += " 失败";
return std::runtime_error(msg);
}
// 等价于 JS 的 new URL(url)
UrlParts CrackUrl(const std::string& url) {
const std::wstring wide = Utf8ToWide(url);
URL_COMPONENTSW comp{};
comp.dwStructSize = sizeof(comp);
wchar_t scheme[32]{};
wchar_t host[512]{};
wchar_t user[256]{};
wchar_t pass[256]{};
wchar_t path[8192]{};
wchar_t extra[8192]{};
comp.lpszScheme = scheme;
comp.dwSchemeLength = 32;
comp.lpszHostName = host;
comp.dwHostNameLength = 512;
comp.lpszUserName = user;
comp.dwUserNameLength = 256;
comp.lpszPassword = pass;
comp.dwPasswordLength = 256;
comp.lpszUrlPath = path;
comp.dwUrlPathLength = 8192;
comp.lpszExtraInfo = extra;
comp.dwExtraInfoLength = 8192;
if (!::WinHttpCrackUrl(wide.c_str(), static_cast<DWORD>(wide.size()), 0, &comp)) {
throw std::runtime_error("无法解析地址:" + url);
}
UrlParts out;
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 out;
}
struct ProxyParts {
std::wstring hostPort;
std::wstring user;
std::wstring pass;
};
ProxyParts ParseProxy(const std::string& proxyUrl) {
ProxyParts out;
std::string rest = proxyUrl;
const size_t schemeEnd = rest.find("://");
if (schemeEnd != std::string::npos) rest = rest.substr(schemeEnd + 3);
const size_t slash = rest.find('/');
std::string authority = slash == std::string::npos ? rest : rest.substr(0, slash);
const size_t at = authority.rfind('@');
if (at != std::string::npos) {
const std::string userinfo = authority.substr(0, at);
authority = authority.substr(at + 1);
const size_t colon = userinfo.find(':');
if (colon == std::string::npos) {
out.user = Utf8ToWide(userinfo);
} else {
out.user = Utf8ToWide(userinfo.substr(0, colon));
out.pass = Utf8ToWide(userinfo.substr(colon + 1));
}
}
// 兼容 [ipv6]:port
if (!authority.empty() && authority[0] == '[') {
const size_t close = authority.find(']');
if (close != std::string::npos) {
out.hostPort = Utf8ToWide(authority.substr(0, close + 1));
const std::string tail = authority.substr(close + 1);
if (!tail.empty() && tail[0] == ':') out.hostPort += Utf8ToWide(tail);
} else {
out.hostPort = Utf8ToWide(authority);
}
} else {
out.hostPort = Utf8ToWide(authority);
}
return out;
}
class Session {
public:
Session(const std::string& proxyUrl, int timeoutMs) {
if (proxyUrl.empty()) {
// 对齐 Node fetch:无代理时直连,不使用系统代理
hSession_ = ::WinHttpOpen(L"PddAI/1.0", WINHTTP_ACCESS_TYPE_NO_PROXY,
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
} else {
const ProxyParts proxy = ParseProxy(proxyUrl);
hSession_ = ::WinHttpOpen(L"PddAI/1.0", WINHTTP_ACCESS_TYPE_NAMED_PROXY,
proxy.hostPort.empty() ? WINHTTP_NO_PROXY_NAME : proxy.hostPort.c_str(),
WINHTTP_NO_PROXY_BYPASS, 0);
proxyUser_ = proxy.user;
proxyPass_ = proxy.pass;
}
if (!hSession_) throw MakeError("WinHttpOpen", ::GetLastError());
if (timeoutMs > 0) {
::WinHttpSetTimeouts(hSession_, timeoutMs, timeoutMs, timeoutMs, timeoutMs);
}
}
~Session() {
if (hSession_) ::WinHttpCloseHandle(hSession_);
}
HINTERNET Get() const { return hSession_; }
const std::wstring& ProxyUser() const { return proxyUser_; }
const std::wstring& ProxyPass() const { return proxyPass_; }
private:
HINTERNET hSession_ = nullptr;
std::wstring proxyUser_;
std::wstring proxyPass_;
};
class Request {
public:
Request(HINTERNET hSession, const std::wstring& method, const UrlParts& url, int timeoutMs) {
hConnect_ = ::WinHttpConnect(hSession, url.host.c_str(), static_cast<INTERNET_PORT>(url.port), 0);
if (!hConnect_) throw MakeError("WinHttpConnect", ::GetLastError());
hRequest_ = ::WinHttpOpenRequest(hConnect_, method.c_str(), url.path.c_str(), nullptr,
WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES,
url.https ? WINHTTP_FLAG_SECURE : 0);
if (!hRequest_) throw MakeError("WinHttpOpenRequest", ::GetLastError());
if (timeoutMs > 0) {
::WinHttpSetTimeouts(hRequest_, timeoutMs, timeoutMs, timeoutMs, timeoutMs);
}
if (url.https) {
DWORD protocols = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
::WinHttpSetOption(hRequest_, WINHTTP_OPTION_SECURE_PROTOCOLS, &protocols, sizeof(protocols));
}
}
~Request() {
if (hRequest_) ::WinHttpCloseHandle(hRequest_);
if (hConnect_) ::WinHttpCloseHandle(hConnect_);
}
void SetProxyCredentials(const std::wstring& user, const std::wstring& pass) {
if (user.empty()) return;
::WinHttpSetCredentials(hRequest_, WINHTTP_AUTH_TARGET_PROXY, WINHTTP_AUTH_SCHEME_BASIC,
user.c_str(), pass.c_str(), nullptr);
}
void SetHeaders(const Http::Headers& headers) {
std::wstring block;
for (const auto& item : headers) {
if (item.first.empty()) continue;
block += Utf8ToWide(item.first) + L": " + Utf8ToWide(item.second) + L"\r\n";
}
if (block.empty()) return;
::WinHttpAddRequestHeaders(hRequest_, block.c_str(), static_cast<DWORD>(block.size()),
WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE);
}
void Send(const std::string& body) {
if (!::WinHttpSendRequest(hRequest_, WINHTTP_NO_ADDITIONAL_HEADERS, 0,
body.empty() ? WINHTTP_NO_REQUEST_DATA
: const_cast<char*>(body.data()),
static_cast<DWORD>(body.size()), static_cast<DWORD>(body.size()), 0)) {
throw MakeError("WinHttpSendRequest", ::GetLastError());
}
if (!::WinHttpReceiveResponse(hRequest_, nullptr)) {
throw MakeError("WinHttpReceiveResponse", ::GetLastError());
}
}
int Status() const {
DWORD status = 0;
DWORD len = sizeof(status);
::WinHttpQueryHeaders(hRequest_, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX, &status, &len, WINHTTP_NO_HEADER_INDEX);
return static_cast<int>(status);
}
std::string Body() {
std::string out;
for (;;) {
DWORD available = 0;
if (!::WinHttpQueryDataAvailable(hRequest_, &available) || available == 0) break;
std::vector<char> buffer(available);
DWORD read = 0;
if (!::WinHttpReadData(hRequest_, buffer.data(), available, &read) || read == 0) break;
out.append(buffer.data(), read);
}
return out;
}
private:
HINTERNET hConnect_ = nullptr;
HINTERNET hRequest_ = nullptr;
};
HttpResponse ParseResponse(int status, const std::string& body) {
HttpResponse out;
out.status = status;
json parsed = json::parse(body, nullptr, false);
if (parsed.is_discarded()) {
out.data = json::object();
out.data["raw"] = body;
} else {
out.data = parsed;
}
return out;
}
HttpResponse RequestInternal(const std::wstring& method, const std::string& url,
const Http::Headers& headers, const std::string& body, int timeoutMs,
const std::string& proxyUrl) {
const UrlParts parts = CrackUrl(url);
Session session(proxyUrl, timeoutMs);
Request request(session.Get(), method, parts, timeoutMs);
request.SetProxyCredentials(session.ProxyUser(), session.ProxyPass());
Http::Headers all = headers;
if (!body.empty()) {
bool hasContentType = false;
for (const auto& item : all) {
if (LowerAscii(item.first) == "content-type") hasContentType = true;
}
if (!hasContentType) all.emplace(all.begin(), std::make_pair("Content-Type", "application/json"));
}
request.SetHeaders(all);
request.Send(body);
return ParseResponse(request.Status(), request.Body());
}
} // namespace
HttpResponse Http::PostJson(const std::string& url, const Headers& headers, const json& body,
int timeoutMs, const std::string& proxyUrl) {
return RequestInternal(L"POST", url, headers, body.dump(), timeoutMs, proxyUrl);
}
HttpResponse Http::GetJson(const std::string& url, const Headers& headers, int timeoutMs,
const std::string& proxyUrl) {
return RequestInternal(L"GET", url, headers, std::string(), timeoutMs, proxyUrl);
}
std::string Http::MaskProxyUrl(const std::string& proxyUrl) {
if (proxyUrl.empty()) return "";
const size_t at = proxyUrl.rfind('@');
if (at != std::string::npos) {
const size_t schemeEnd = proxyUrl.find("://");
const size_t start = schemeEnd == std::string::npos ? 0 : schemeEnd + 3;
if (at > start) {
return proxyUrl.substr(0, start) + "***:***@" + proxyUrl.substr(at + 1);
}
}
return proxyUrl;
}
}
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include <string>
#include <utility>
#include <vector>
#include "Json.h"
namespace pddai {
// 对齐 server/index.js 的 postJson/getJson:
// data 解析失败时退化为 {"raw": "<响应原文>"}
struct HttpResponse {
int status = 0;
json data;
};
class Http {
public:
using Headers = std::vector<std::pair<std::string, std::string>>;
// 失败时抛 std::runtime_error
static HttpResponse PostJson(const std::string& url, const Headers& headers, const json& body,
int timeoutMs, const std::string& proxyUrl);
static HttpResponse GetJson(const std::string& url, const Headers& headers, int timeoutMs,
const std::string& proxyUrl);
// 供日志脱敏:与 index.js maskProxyUrl 等价
static std::string MaskProxyUrl(const std::string& proxyUrl);
};
}
+9
View File
@@ -0,0 +1,9 @@
#pragma once
// 隔离 nlohmann/json 单头,避免它被拖进每个编译单元。
// 用 ordered_json:Node 的对象属性顺序对外可见(控制页/日志/提示词),必须保序。
#include "json.hpp"
namespace pddai {
using json = nlohmann::ordered_json;
}
+73
View File
@@ -0,0 +1,73 @@
#include "Log.h"
#include <windows.h>
#include <shlobj.h>
#include <cstdio>
#include <deque>
#include <mutex>
#include <share.h>
#include "Util.h"
namespace pddai {
namespace {
std::mutex g_mutex;
std::deque<Log::Entry> g_buffer;
constexpr size_t kMaxBuffer = 2000;
FILE* g_file = nullptr;
const char* LevelName(Log::Level level) {
switch (level) {
case Log::Level::Info: return "INFO";
case Log::Level::Warn: return "WARN";
case Log::Level::Error: return "ERR ";
default: return "???";
}
}
}
void Log::Init() {
std::lock_guard<std::mutex> lock(g_mutex);
if (g_file) return;
// 日志跟数据目录走:默认在 exe 目录下的 data,exe 目录只读时回落用户目录
const std::wstring dir = DataDir();
::CreateDirectoryW(dir.c_str(), nullptr);
// 用二进制追加模式写入,内容已经是 UTF-8,避免 ccs= 编码模式的兼容问题。
// _SH_DENYNO 让日志在进程运行中也能被外部读取,排查时不必先结束进程
g_file = _wfsopen((dir + L"\\pddai.log").c_str(), L"ab", _SH_DENYNO);
}
void Log::Write(Level level, const std::string& message) {
SYSTEMTIME st{};
::GetLocalTime(&st);
char ts[32];
std::snprintf(ts, sizeof(ts), "%02d:%02d:%02d.%03d", st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
FILETIME ft{};
::GetSystemTimeAsFileTime(&ft);
const long long timeMs = (static_cast<long long>(ft.dwHighDateTime) << 32 | ft.dwLowDateTime) / 10000;
std::lock_guard<std::mutex> lock(g_mutex);
g_buffer.push_back({timeMs, level, message});
if (g_buffer.size() > kMaxBuffer) g_buffer.pop_front();
const std::string line = std::string("[") + ts + "] " + LevelName(level) + " " + message + "\n";
if (g_file) {
std::fputs(line.c_str(), g_file);
std::fflush(g_file);
}
std::fputs(line.c_str(), stdout);
std::fflush(stdout);
}
std::vector<Log::Entry> Log::Recent(size_t maxCount) {
std::lock_guard<std::mutex> lock(g_mutex);
const size_t n = maxCount < g_buffer.size() ? maxCount : g_buffer.size();
return std::vector<Entry>(g_buffer.end() - static_cast<long long>(n), g_buffer.end());
}
}
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include <string>
#include <vector>
namespace pddai {
class Log {
public:
enum class Level { Info, Warn, Error };
static void Init();
static void Write(Level level, const std::string& message);
static void Info(const std::string& m) { Write(Level::Info, m); }
static void Warn(const std::string& m) { Write(Level::Warn, m); }
static void Error(const std::string& m) { Write(Level::Error, m); }
// 环形缓冲,供 UI 的日志页读取
struct Entry {
long long timeMs;
Level level;
std::string text;
};
static std::vector<Entry> Recent(size_t maxCount = 500);
};
}
File diff suppressed because it is too large Load Diff
+21
View File
@@ -0,0 +1,21 @@
#pragma once
#include "Json.h"
#include <string>
namespace pddai {
// 回复流水线的本地部分:归一化 / 快捷回复 / 高危 / 人工接手 / 降级回复 / modelContext。
// 契约与 server/index.js 的 handleReply 一致。
class Pipeline {
public:
// payload 已通过鉴权;shop 至少含 id / name
static json Run(const json& payload, const json& shop);
// 用模型判断买家最新一句是不是「替换/删除图片」的指令,只返回意图,不动任何文件。
// 返回 {ok, intent: replace|delete|none, index, target, confidence, reason}
static json ClassifyImageAdjustment(const json& context);
};
}
+36
View File
@@ -0,0 +1,36 @@
#include "Resources.h"
#include <windows.h>
namespace pddai {
namespace {
bool LoadResourceRaw(int resourceId, LPCWSTR type, const void*& data, DWORD& size) {
HRSRC hRsrc = ::FindResourceW(nullptr, MAKEINTRESOURCE(resourceId), type);
if (!hRsrc) return false;
HGLOBAL hGlobal = ::LoadResource(nullptr, hRsrc);
if (!hGlobal) return false;
data = ::LockResource(hGlobal);
size = ::SizeofResource(nullptr, hRsrc);
return data != nullptr;
}
}
std::string LoadTextResource(int resourceId) {
const void* data = nullptr;
DWORD size = 0;
if (!LoadResourceRaw(resourceId, RT_RCDATA, data, size)) return {};
return std::string(static_cast<const char*>(data), static_cast<size_t>(size));
}
std::vector<unsigned char> LoadBinaryResource(int resourceId) {
const void* data = nullptr;
DWORD size = 0;
if (!LoadResourceRaw(resourceId, RT_RCDATA, data, size)) return {};
const auto* p = static_cast<const unsigned char*>(data);
return std::vector<unsigned char>(p, p + size);
}
}
+12
View File
@@ -0,0 +1,12 @@
#pragma once
#include <string>
#include <vector>
namespace pddai {
// 从 EXE 的 RCDATA 资源读取嵌入内容(前端页面 / 注入脚本)
std::string LoadTextResource(int resourceId);
std::vector<unsigned char> LoadBinaryResource(int resourceId);
}
File diff suppressed because it is too large Load Diff
+37
View File
@@ -0,0 +1,37 @@
#pragma once
#include <functional>
#include <map>
#include <string>
#include <vector>
namespace pddai {
// 内置本地 HTTP 服务:契约与 server/index.js 对齐,插件可零改动接入
class Server {
public:
struct Status {
bool running = false;
std::string host;
int port = 0;
std::string error;
};
static bool Start(const std::string& host, int port);
static void Stop();
static Status GetStatus();
// 复刻 getLanUrls:IPv4、非回环
static std::vector<std::string> LanUrls(int port);
// 各店铺的暂停状态,供桌面 UI 的店铺页展示
static std::map<std::string, bool> PausedShopIds();
// 各店铺插件当前模式(auto / debug),供桌面 UI 的选项卡圆点区分
static std::map<std::string, std::string> ShopModes();
// 监听状态变化(手机控制页切换、定时暂停)时回调,供桌面 UI 刷新
static void SetStateListener(std::function<void()> listener);
};
}
+644
View File
@@ -0,0 +1,644 @@
#include "Smtp.h"
#define SECURITY_WIN32
// winsock2.h 必须先于 windows.h,否则 winsock.h 会被间接引入导致重定义
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <schannel.h>
#include <sspi.h>
#include <wincrypt.h>
#include <algorithm>
#include <cstring>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
#include "Config.h"
#include "Json.h"
#include "Util.h"
namespace pddai {
namespace {
// ---------------- JSON 取值 ----------------
const json& Member(const json& obj, const char* key) {
static const json empty = json();
if (!obj.is_object()) return empty;
const auto it = obj.find(key);
return it == obj.end() ? empty : *it;
}
// JS 的 String(value)
std::string ScalarStr(const json& v) {
if (v.is_string()) return v.get<std::string>();
if (v.is_null()) return "";
if (v.is_boolean()) return v.get<bool>() ? "true" : "false";
if (v.is_number_integer()) return std::to_string(v.get<long long>());
if (v.is_number_unsigned()) return std::to_string(v.get<unsigned long long>());
if (v.is_number_float()) {
char buf[64];
std::snprintf(buf, sizeof(buf), "%.17g", v.get<double>());
return std::string(buf);
}
return "";
}
std::string Str(const json& obj, const char* key) { return ScalarStr(Member(obj, key)); }
bool IsTrue(const json& value) { return value.is_boolean() && value.get<bool>(); }
// ---------------- TLS(Schannel) ----------------
class TlsChannel {
public:
TlsChannel() = default;
~TlsChannel() {
if (ctxValid_) ::DeleteSecurityContext(&ctx_);
if (credValid_) ::FreeCredentialsHandle(&cred_);
}
TlsChannel(const TlsChannel&) = delete;
TlsChannel& operator=(const TlsChannel&) = delete;
void Handshake(SOCKET sock, const std::string& serverName, bool rejectUnauthorized) {
sock_ = sock;
SCHANNEL_CRED cred{};
cred.dwVersion = SCHANNEL_CRED_VERSION;
cred.dwFlags = SCH_CRED_NO_DEFAULT_CREDS |
(rejectUnauthorized ? SCH_CRED_AUTO_CRED_VALIDATION : SCH_CRED_MANUAL_CRED_VALIDATION);
cred.grbitEnabledProtocols = SP_PROT_TLS1_2_CLIENT;
TimeStamp ts{};
SECURITY_STATUS ss = ::AcquireCredentialsHandleW(nullptr, const_cast<LPWSTR>(UNISP_NAME_W),
SECPKG_CRED_OUTBOUND, nullptr, &cred, nullptr,
nullptr, &cred_, &ts);
if (ss != SEC_E_OK) {
if (ss == SEC_E_SECPKG_NOT_FOUND) {
throw std::runtime_error("系统不支持 Schannel,无法建立 TLS 连接");
}
throw std::runtime_error("AcquireCredentialsHandle 失败,SSPI=0x" +
std::to_string(static_cast<unsigned>(ss)));
}
credValid_ = true;
std::wstring name = Utf8ToWide(serverName);
std::string input;
bool first = true;
for (;;) {
SecBuffer outBuffer{};
outBuffer.BufferType = SECBUFFER_TOKEN;
outBuffer.pvBuffer = nullptr;
outBuffer.cbBuffer = 0;
SecBufferDesc outDesc{};
outDesc.ulVersion = SECBUFFER_VERSION;
outDesc.cBuffers = 1;
outDesc.pBuffers = &outBuffer;
SecBuffer inBuffers[2]{};
SecBufferDesc inDesc{};
inDesc.ulVersion = SECBUFFER_VERSION;
inDesc.cBuffers = 2;
inDesc.pBuffers = inBuffers;
inBuffers[0].BufferType = SECBUFFER_TOKEN;
inBuffers[0].pvBuffer = input.empty() ? nullptr : input.data();
inBuffers[0].cbBuffer = static_cast<unsigned long>(input.size());
inBuffers[1].BufferType = SECBUFFER_EMPTY;
inBuffers[1].pvBuffer = nullptr;
inBuffers[1].cbBuffer = 0;
ULONG attrs = 0;
ss = ::InitializeSecurityContextW(
&cred_, first ? nullptr : &ctx_, name.empty() ? nullptr : name.data(),
ISC_REQ_STREAM | ISC_REQ_CONFIDENTIALITY | ISC_REQ_EXTENDED_ERROR |
ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_USE_SUPPLIED_CREDS,
0, 0, first ? nullptr : &inDesc, 0, first ? &ctx_ : nullptr, &outDesc, &attrs, &ts);
if (FAILED(ss) && ss != SEC_I_CONTINUE_NEEDED && ss != SEC_I_INCOMPLETE_CREDENTIALS) {
if (outBuffer.pvBuffer) ::FreeContextBuffer(outBuffer.pvBuffer);
throw std::runtime_error("TLS 握手失败,SSPI=0x" + std::to_string(static_cast<unsigned>(ss)));
}
ctxValid_ = true;
if (outBuffer.pvBuffer && outBuffer.cbBuffer) {
SendRaw(static_cast<const char*>(outBuffer.pvBuffer), outBuffer.cbBuffer);
::FreeContextBuffer(outBuffer.pvBuffer);
outBuffer.pvBuffer = nullptr;
}
if (ss == SEC_E_OK) {
// 握手可能夹带应用数据
std::string extra;
for (int i = 0; i < 2; ++i) {
if (inBuffers[i].BufferType == SECBUFFER_EXTRA && inBuffers[i].cbBuffer) {
extra.assign(static_cast<const char*>(inBuffers[i].pvBuffer), inBuffers[i].cbBuffer);
}
}
enc_ = extra;
break;
}
std::string chunk;
if (!RecvRaw(chunk, 8192)) {
throw std::runtime_error("TLS 握手失败:连接被关闭");
}
input += chunk;
first = false;
}
if (::QueryContextAttributesW(&ctx_, SECPKG_ATTR_STREAM_SIZES, &sizes_) != SEC_E_OK) {
throw std::runtime_error("QueryContextAttributes(SECPKG_ATTR_STREAM_SIZES) 失败");
}
}
bool WriteAll(const char* data, size_t len) {
size_t offset = 0;
while (offset < len) {
const size_t chunk = std::min<size_t>(len - offset, sizes_.cbMaximumMessage);
std::vector<char> header(sizes_.cbHeader);
std::vector<char> trailer(sizes_.cbTrailer);
SecBuffer buffers[4]{};
buffers[0].cbBuffer = sizes_.cbHeader;
buffers[0].BufferType = SECBUFFER_STREAM_HEADER;
buffers[0].pvBuffer = header.data();
buffers[1].cbBuffer = static_cast<unsigned long>(chunk);
buffers[1].BufferType = SECBUFFER_DATA;
buffers[1].pvBuffer = const_cast<char*>(data + offset);
buffers[2].cbBuffer = sizes_.cbTrailer;
buffers[2].BufferType = SECBUFFER_STREAM_TRAILER;
buffers[2].pvBuffer = trailer.data();
buffers[3].cbBuffer = 0;
buffers[3].BufferType = SECBUFFER_EMPTY;
buffers[3].pvBuffer = nullptr;
SecBufferDesc desc{};
desc.ulVersion = SECBUFFER_VERSION;
desc.cBuffers = 4;
desc.pBuffers = buffers;
const SECURITY_STATUS ss = ::EncryptMessage(&ctx_, 0, &desc, 0);
if (ss != SEC_E_OK) return false;
if (!SendRaw(header.data(), buffers[0].cbBuffer)) return false;
if (!SendRaw(data + offset, buffers[1].cbBuffer)) return false;
if (!SendRaw(trailer.data(), buffers[2].cbBuffer)) return false;
offset += chunk;
}
return true;
}
// 返回 0 表示对端关闭或出错
int Read(char* buffer, int want) {
while (plain_.empty()) {
if (!FillPlain()) return 0;
}
const size_t take = std::min<size_t>(want, plain_.size());
std::memcpy(buffer, plain_.data(), take);
plain_.erase(0, take);
return static_cast<int>(take);
}
private:
bool SendRaw(const char* data, size_t len) {
size_t sent = 0;
while (sent < len) {
const int n = ::send(sock_, data + sent, static_cast<int>(len - sent), 0);
if (n <= 0) return false;
sent += static_cast<size_t>(n);
}
return true;
}
bool RecvRaw(std::string& out, size_t maxBytes) {
std::vector<char> buffer(maxBytes);
const int n = ::recv(sock_, buffer.data(), static_cast<int>(buffer.size()), 0);
if (n <= 0) return false;
out.assign(buffer.data(), static_cast<size_t>(n));
return true;
}
bool FillPlain() {
for (;;) {
if (enc_.empty()) {
std::string chunk;
if (!RecvRaw(chunk, 8192)) return false;
enc_ += chunk;
}
SecBuffer buffers[4]{};
buffers[0].cbBuffer = static_cast<unsigned long>(enc_.size());
buffers[0].BufferType = SECBUFFER_DATA;
buffers[0].pvBuffer = enc_.empty() ? nullptr : enc_.data();
buffers[1].cbBuffer = 0;
buffers[1].BufferType = SECBUFFER_EMPTY;
buffers[2].cbBuffer = 0;
buffers[2].BufferType = SECBUFFER_EMPTY;
buffers[3].cbBuffer = 0;
buffers[3].BufferType = SECBUFFER_EMPTY;
SecBufferDesc desc{};
desc.ulVersion = SECBUFFER_VERSION;
desc.cBuffers = 4;
desc.pBuffers = buffers;
const SECURITY_STATUS ss = ::DecryptMessage(&ctx_, &desc, 0, nullptr);
if (ss == SEC_E_INCOMPLETE_MESSAGE) {
std::string chunk;
if (!RecvRaw(chunk, 8192)) return false;
enc_ += chunk;
continue;
}
if (ss == SEC_I_CONTEXT_EXPIRED) return false;
if (ss != SEC_E_OK) return false;
std::string extra;
for (int i = 0; i < 4; ++i) {
if (buffers[i].BufferType == SECBUFFER_DATA && buffers[i].cbBuffer) {
plain_.assign(static_cast<const char*>(buffers[i].pvBuffer), buffers[i].cbBuffer);
} else if (buffers[i].BufferType == SECBUFFER_EXTRA && buffers[i].cbBuffer) {
extra.assign(static_cast<const char*>(buffers[i].pvBuffer), buffers[i].cbBuffer);
}
}
enc_ = extra;
return !plain_.empty();
}
}
SOCKET sock_ = INVALID_SOCKET;
CredHandle cred_{};
CtxtHandle ctx_{};
bool credValid_ = false;
bool ctxValid_ = false;
SecPkgContext_StreamSizes sizes_{};
std::string enc_;
std::string plain_;
};
// ---------------- 连接封装 ----------------
class Stream {
public:
~Stream() {
if (sock_ != INVALID_SOCKET) ::closesocket(sock_);
tls_.reset();
}
void Connect(const std::string& host, int port, int timeoutMs) {
addrinfo hints{};
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
addrinfo* result = nullptr;
if (::getaddrinfo(host.c_str(), std::to_string(port).c_str(), &hints, &result) != 0 || !result) {
throw std::runtime_error("无法解析邮件服务器地址:" + host);
}
SOCKET sock = INVALID_SOCKET;
for (addrinfo* p = result; p; p = p->ai_next) {
sock = ::socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sock == INVALID_SOCKET) continue;
// 非阻塞 + select 实现连接超时
u_long mode = 1;
::ioctlsocket(sock, FIONBIO, &mode);
::connect(sock, p->ai_addr, static_cast<int>(p->ai_addrlen));
timeval tv{};
tv.tv_sec = timeoutMs / 1000;
tv.tv_usec = (timeoutMs % 1000) * 1000;
fd_set write{};
FD_ZERO(&write);
FD_SET(sock, &write);
if (::select(0, nullptr, &write, nullptr, &tv) <= 0) {
::closesocket(sock);
sock = INVALID_SOCKET;
continue;
}
mode = 0;
::ioctlsocket(sock, FIONBIO, &mode);
break;
}
::freeaddrinfo(result);
if (sock == INVALID_SOCKET) {
throw std::runtime_error("连接邮件服务器失败:" + host + ":" + std::to_string(port));
}
sock_ = sock;
const int recvTimeout = 30000;
::setsockopt(sock_, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&recvTimeout),
sizeof(recvTimeout));
const int sendTimeout = 30000;
::setsockopt(sock_, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char*>(&sendTimeout),
sizeof(sendTimeout));
}
void StartTls(const std::string& serverName, bool rejectUnauthorized) {
tls_ = std::make_unique<TlsChannel>();
tls_->Handshake(sock_, serverName, rejectUnauthorized);
}
void Write(const std::string& data) {
if (tls_) {
if (!tls_->WriteAll(data.data(), data.size())) {
throw std::runtime_error("SMTP 写入失败:TLS 加密错误");
}
return;
}
size_t sent = 0;
while (sent < data.size()) {
const int n = ::send(sock_, data.data() + sent, static_cast<int>(data.size() - sent), 0);
if (n <= 0) throw std::runtime_error("SMTP 写入失败:连接已断开");
sent += static_cast<size_t>(n);
}
}
// 返回 0 表示对端关闭
int Read(char* buffer, int want) {
if (tls_) return tls_->Read(buffer, want);
const int n = ::recv(sock_, buffer, want, 0);
return n > 0 ? n : 0;
}
private:
SOCKET sock_ = INVALID_SOCKET;
std::unique_ptr<TlsChannel> tls_;
};
struct WsaInit {
WsaInit() {
WSADATA data{};
::WSAStartup(MAKEWORD(2, 2), &data);
}
};
struct SmtpResponse {
int code = 0;
std::vector<std::string> lines;
};
class SmtpSession {
public:
SmtpSession(Stream& stream) : stream_(stream) {}
SmtpResponse Command(const std::string& line, const std::vector<int>& allowed, const std::string& action) {
stream_.Write(line + "\r\n");
const SmtpResponse response = ReadResponse();
if (std::find(allowed.begin(), allowed.end(), response.code) == allowed.end()) {
std::string joined;
for (size_t i = 0; i < response.lines.size(); ++i) {
if (i) joined += " | ";
joined += response.lines[i];
}
throw std::runtime_error("SMTP " + action + " 失败:" + joined);
}
return response;
}
SmtpResponse ReadResponse() {
SmtpResponse out;
for (;;) {
const size_t eol = buffer_.find("\r\n");
if (eol == std::string::npos) {
char chunk[4096];
const int n = stream_.Read(chunk, static_cast<int>(sizeof(chunk)));
if (n <= 0) {
if (out.lines.empty()) throw std::runtime_error("SMTP 读取失败:连接被关闭");
out.code = ParseCode(out.lines.back());
return out;
}
buffer_.append(chunk, static_cast<size_t>(n));
continue;
}
const std::string line = buffer_.substr(0, eol);
buffer_.erase(0, eol + 2);
out.lines.push_back(line);
// 与 index.js:1469 的 /^(\d{3})([ -])/ 一致,分隔符为空格时响应结束
if (line.size() >= 4 && IsThreeDigits(line) && line[3] == ' ') {
out.code = ParseCode(line);
return out;
}
}
}
private:
static bool IsThreeDigits(const std::string& line) {
return line[0] >= '0' && line[0] <= '9' && line[1] >= '0' && line[1] <= '9' &&
line[2] >= '0' && line[2] <= '9';
}
static int ParseCode(const std::string& line) {
if (line.size() < 3 || !IsThreeDigits(line)) return 0;
return (line[0] - '0') * 100 + (line[1] - '0') * 10 + (line[2] - '0');
}
Stream& stream_;
std::string buffer_;
};
// ---------------- MIME ----------------
std::string ExtractEmail(const std::string& value) {
const size_t begin = value.find('<');
const size_t end = value.find('>');
if (begin != std::string::npos && end != std::string::npos && end > begin) {
return Trim(value.substr(begin + 1, end - begin - 1));
}
return Trim(value);
}
std::string MimeHeader(const std::string& value) {
return "=?UTF-8?B?" + Base64Encode(value) + "?=";
}
std::string FormatAddress(const std::string& address, const std::string& displayName) {
const std::string email = ExtractEmail(address);
if (displayName.empty()) return email;
return MimeHeader(displayName) + " <" + email + ">";
}
std::string WrapBase64(const std::string& value) {
std::string out;
for (size_t i = 0; i < value.size(); i += 76) {
if (i) out += "\r\n";
out += value.substr(i, 76);
}
return out;
}
std::vector<std::string> NormalizeAddressList(const json& value) {
std::vector<std::string> out;
if (value.is_array()) {
for (const json& item : value) {
if (item.is_null()) continue;
const std::string text = ScalarStr(item);
if (!text.empty()) out.push_back(text);
}
return out;
}
if (value.is_null()) return out;
std::string raw;
if (value.is_string()) {
raw = value.get<std::string>();
} else if (value.is_number()) {
raw = ScalarStr(value);
} else {
return out;
}
size_t start = 0;
for (;;) {
const size_t comma = raw.find(',', start);
const std::string piece = Trim(comma == std::string::npos ? raw.substr(start) : raw.substr(start, comma - start));
if (!piece.empty()) out.push_back(piece);
if (comma == std::string::npos) break;
start = comma + 1;
}
return out;
}
std::string ComposeEmail(const json& config, const std::string& subject, const std::string& text,
const std::string& from, const std::vector<std::string>& to,
const std::vector<std::string>& cc) {
std::vector<std::string> headers;
headers.push_back("From: " + FormatAddress(from, Str(config, "senderName")));
std::string toHeader;
for (size_t i = 0; i < to.size(); ++i) {
if (i) toHeader += ", ";
toHeader += FormatAddress(to[i], "");
}
headers.push_back("To: " + toHeader);
if (!cc.empty()) {
std::string ccHeader;
for (size_t i = 0; i < cc.size(); ++i) {
if (i) ccHeader += ", ";
ccHeader += FormatAddress(cc[i], "");
}
headers.push_back("Cc: " + ccHeader);
}
headers.push_back("Subject: " + MimeHeader(subject));
headers.push_back("Date: " + Rfc2822NowUtc());
headers.push_back("MIME-Version: 1.0");
headers.push_back("Content-Type: text/plain; charset=UTF-8");
headers.push_back("Content-Transfer-Encoding: base64");
std::string head;
for (size_t i = 0; i < headers.size(); ++i) {
if (i) head += "\r\n";
head += headers[i];
}
return head + "\r\n\r\n" + WrapBase64(Base64Encode(text)) + "\r\n.\r\n";
}
std::string MailDomain(const json& config) {
const std::string helo = Str(config, "heloDomain");
if (!helo.empty()) return helo;
const std::string host = ComputerNameUtf8();
return host.empty() ? "localhost" : host;
}
} // namespace
void Smtp::Send(const json& config, const std::string& subject, const std::string& text) {
static const WsaInit wsa;
const std::string host = Trim(Str(config, "host"));
const bool secure = IsTrue(Member(config, "secure"));
const json portValue = Member(config, "port");
const double portNumber = portValue.is_number() ? portValue.get<double>() : 0.0;
const int port = static_cast<int>(portNumber > 0 ? portNumber : (secure ? 465 : 587));
const std::string user = Str(config, "user");
std::string password;
const std::string authCodeEnv = Str(config, "authCodeEnv");
if (!authCodeEnv.empty()) password = Config::Env(authCodeEnv);
if (password.empty()) {
const json authCode = Member(config, "authCode");
if (!authCode.is_null()) password = Str(config, "authCode");
}
if (password.empty()) {
const json pw = Member(config, "password");
if (!pw.is_null()) password = Str(config, "password");
}
if (password.empty()) password = Config::Env("PDD_MAIL_AUTH_CODE");
std::string from = Str(config, "from");
if (from.empty()) from = user;
const std::vector<std::string> to = NormalizeAddressList(Member(config, "to"));
const std::vector<std::string> cc = NormalizeAddressList(Member(config, "cc"));
std::vector<std::string> recipients = to;
recipients.insert(recipients.end(), cc.begin(), cc.end());
if (host.empty() || port <= 0 || from.empty() || recipients.empty()) {
throw std::runtime_error("邮件配置不完整:host/port/from/to 必填");
}
if (!user.empty() && password.empty()) {
throw std::runtime_error("邮件授权码为空,请配置环境变量 " +
(authCodeEnv.empty() ? std::string("PDD_MAIL_AUTH_CODE") : authCodeEnv) +
" 或 mail.json authCode");
}
const bool rejectUnauthorized = !(Member(config, "rejectUnauthorized") == json(false));
Stream stream;
stream.Connect(host, port, 15000);
if (secure) stream.StartTls(host, rejectUnauthorized);
SmtpSession session(stream);
const SmtpResponse greeting = session.ReadResponse();
if (greeting.code != 220) {
std::string joined;
for (size_t i = 0; i < greeting.lines.size(); ++i) {
if (i) joined += " | ";
joined += greeting.lines[i];
}
throw std::runtime_error("SMTP connect 失败:" + joined);
}
const std::string domain = MailDomain(config);
session.Command("EHLO " + domain, {250}, "EHLO " + domain);
if (!secure && !(Member(config, "startTls") == json(false))) {
session.Command("STARTTLS", {220}, "STARTTLS");
stream.StartTls(host, rejectUnauthorized);
session.Command("EHLO " + domain, {250}, "EHLO " + domain);
}
if (!user.empty()) {
session.Command("AUTH LOGIN", {334}, "AUTH LOGIN");
session.Command(Base64Encode(user), {334}, "AUTH LOGIN 用户名");
session.Command(Base64Encode(password), {235}, "AUTH LOGIN 密码");
}
session.Command("MAIL FROM:<" + ExtractEmail(from) + ">", {250}, "MAIL FROM");
for (const std::string& recipient : recipients) {
session.Command("RCPT TO:<" + ExtractEmail(recipient) + ">", {250, 251}, "RCPT TO");
}
session.Command("DATA", {354}, "DATA");
stream.Write(ComposeEmail(config, subject, text, from, to, cc));
const SmtpResponse dataResponse = session.ReadResponse();
if (dataResponse.code != 250) {
std::string joined;
for (size_t i = 0; i < dataResponse.lines.size(); ++i) {
if (i) joined += " | ";
joined += dataResponse.lines[i];
}
throw std::runtime_error("SMTP DATA body 失败:" + joined);
}
session.Command("QUIT", {221}, "QUIT");
}
}
+15
View File
@@ -0,0 +1,15 @@
#pragma once
#include <string>
#include "Json.h"
namespace pddai {
// 复刻 server/index.js 的 sendSmtpMail:失败抛 std::runtime_error(错误消息与 index.js:1413 一致)
class Smtp {
public:
static void Send(const json& config, const std::string& subject, const std::string& text);
};
}
+61
View File
@@ -0,0 +1,61 @@
#include "Stats.h"
#include <windows.h>
#include <mutex>
namespace pddai {
namespace {
std::mutex g_mutex;
Stats::Counters g_counters;
int g_dayKey = 0; // yyyymmdd,用于跨日归零
int LocalDayKey() {
SYSTEMTIME st{};
::GetLocalTime(&st);
return st.wYear * 10000 + st.wMonth * 100 + st.wDay;
}
void ResetIfNewDay() {
const int key = LocalDayKey();
if (g_dayKey != key) {
g_dayKey = key;
g_counters = Stats::Counters{};
}
}
} // namespace
void Stats::AddReply() {
std::lock_guard<std::mutex> lock(g_mutex);
ResetIfNewDay();
++g_counters.replies;
}
void Stats::AddManual() {
std::lock_guard<std::mutex> lock(g_mutex);
ResetIfNewDay();
++g_counters.manual;
}
void Stats::AddMail() {
std::lock_guard<std::mutex> lock(g_mutex);
ResetIfNewDay();
++g_counters.mails;
}
void Stats::AddModelFailure() {
std::lock_guard<std::mutex> lock(g_mutex);
ResetIfNewDay();
++g_counters.modelFailures;
}
Stats::Counters Stats::Get() {
std::lock_guard<std::mutex> lock(g_mutex);
ResetIfNewDay();
return g_counters;
}
}
+23
View File
@@ -0,0 +1,23 @@
#pragma once
namespace pddai {
// 今日运行统计,供桌面 UI 的状态页展示,跨本地日自动归零
class Stats {
public:
struct Counters {
long long replies = 0; // 成功回复数
long long manual = 0; // 转人工 / 高危拦截数
long long mails = 0; // 告警邮件发送成功数
long long modelFailures = 0; // 模型(含 Coze、分类器)调用失败数
};
static void AddReply();
static void AddManual();
static void AddMail();
static void AddModelFailure();
static Counters Get();
};
}
+330
View File
@@ -0,0 +1,330 @@
#include "Util.h"
#include <shlobj.h>
#include <wincrypt.h>
#include <cstdio>
#include <filesystem>
#include <string>
#include <vector>
namespace pddai {
std::wstring Utf8ToWide(std::string_view s) {
if (s.empty()) return {};
const int n = ::MultiByteToWideChar(CP_UTF8, 0, s.data(), static_cast<int>(s.size()), nullptr, 0);
if (n <= 0) return {};
std::wstring out(static_cast<size_t>(n), L'\0');
::MultiByteToWideChar(CP_UTF8, 0, s.data(), static_cast<int>(s.size()), out.data(), n);
return out;
}
std::string WideToUtf8(std::wstring_view s) {
if (s.empty()) return {};
const int n = ::WideCharToMultiByte(CP_UTF8, 0, s.data(), static_cast<int>(s.size()), nullptr, 0, nullptr, nullptr);
if (n <= 0) return {};
std::string out(static_cast<size_t>(n), '\0');
::WideCharToMultiByte(CP_UTF8, 0, s.data(), static_cast<int>(s.size()), out.data(), n, nullptr, nullptr);
return out;
}
std::string IsoNowUtc() {
SYSTEMTIME st{};
::GetSystemTime(&st);
char buf[32];
std::snprintf(buf, sizeof(buf), "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
return std::string(buf);
}
namespace {
bool AllDigits(std::string_view s) {
if (s.empty()) return false;
for (const char c : s) {
if (c < '0' || c > '9') return false;
}
return true;
}
}
std::string Trim(std::string_view s) {
size_t b = 0;
size_t e = s.size();
while (b < e && (s[b] == ' ' || s[b] == '\t' || s[b] == '\r' || s[b] == '\n')) ++b;
while (e > b && (s[e - 1] == ' ' || s[e - 1] == '\t' || s[e - 1] == '\r' || s[e - 1] == '\n')) --e;
return std::string(s.substr(b, e - b));
}
bool NextDailyTime(const std::string& hhmm, SYSTEMTIME& out) {
// 等价于 index.js 的 /^(\d{1,2}):(\d{2})$/
const std::string s = Trim(hhmm);
const size_t colon = s.find(':');
if (colon == std::string::npos || colon == 0 || colon > 2) return false;
if (s.size() - colon - 1 != 2) return false;
const std::string hourPart = s.substr(0, colon);
const std::string minutePart = s.substr(colon + 1);
if (!AllDigits(hourPart) || !AllDigits(minutePart)) return false;
const int hour = std::stoi(hourPart);
const int minute = std::stoi(minutePart);
if (hour < 0 || hour > 23 || minute < 0 || minute > 59) return false;
SYSTEMTIME now{};
::GetLocalTime(&now);
SYSTEMTIME next = now;
next.wHour = static_cast<WORD>(hour);
next.wMinute = static_cast<WORD>(minute);
next.wSecond = 0;
next.wMilliseconds = 0;
FILETIME ftNow{};
FILETIME ftNext{};
if (!::SystemTimeToFileTime(&now, &ftNow) || !::SystemTimeToFileTime(&next, &ftNext)) return false;
ULARGE_INTEGER a{};
a.HighPart = ftNow.dwHighDateTime;
a.LowPart = ftNow.dwLowDateTime;
ULARGE_INTEGER b{};
b.HighPart = ftNext.dwHighDateTime;
b.LowPart = ftNext.dwLowDateTime;
if (b.QuadPart <= a.QuadPart) {
// +1 天(100ns 单位)
b.QuadPart += 864000000000ULL;
FILETIME ftRolled{};
ftRolled.dwHighDateTime = b.HighPart;
ftRolled.dwLowDateTime = b.LowPart;
if (!::FileTimeToSystemTime(&ftRolled, &next)) return false;
}
out = next;
return true;
}
std::string FormatLocalDateTime(const SYSTEMTIME& st) {
char buf[32];
std::snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
return std::string(buf);
}
bool SafeTokenEqual(std::string_view a, std::string_view b) {
if (a.size() != b.size()) return false;
unsigned char diff = 0;
for (size_t i = 0; i < a.size(); ++i) {
diff |= static_cast<unsigned char>(a[i]) ^ static_cast<unsigned char>(b[i]);
}
return diff == 0;
}
std::string EscapeHtml(std::string_view value) {
std::string out;
out.reserve(value.size());
for (const char c : value) {
switch (c) {
case '&': out += "&amp;"; break;
case '<': out += "&lt;"; break;
case '>': out += "&gt;"; break;
case '"': out += "&quot;"; break;
case '\'': out += "&#39;"; break;
default: out += c; break;
}
}
return out;
}
std::wstring GetLocalAppDataDir() {
wchar_t path[MAX_PATH]{};
if (SUCCEEDED(::SHGetFolderPathW(nullptr, CSIDL_LOCAL_APPDATA, nullptr, 0, path))) {
return std::wstring(path);
}
return L".";
}
std::wstring ExeDir() {
wchar_t buf[MAX_PATH]{};
const DWORD n = ::GetModuleFileNameW(nullptr, buf, MAX_PATH);
const std::wstring full(buf, n);
const size_t slash = full.find_last_of(L"\\/");
return slash == std::wstring::npos ? std::wstring(L".") : full.substr(0, slash);
}
namespace {
bool WritableProbe(const std::wstring& dir) {
const std::wstring probe = dir + L"\\.pddai-write-test";
HANDLE h = ::CreateFileW(probe.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, nullptr);
if (h == INVALID_HANDLE_VALUE) return false;
::CloseHandle(h);
return true;
}
// 把旧位置的店铺浏览器数据搬到新数据目录,保住登录态。
// 同盘直接重命名;跨盘逐文件复制,复制失败就丢弃目标,最多重新登录一次。
void MigrateConsoles(const std::wstring& legacy, const std::wstring& target) {
const std::wstring from = legacy + L"\\consoles";
const std::wstring to = target + L"\\consoles";
if (::GetFileAttributesW(from.c_str()) == INVALID_FILE_ATTRIBUTES) return;
if (::GetFileAttributesW(to.c_str()) != INVALID_FILE_ATTRIBUTES) return;
if (::MoveFileExW(from.c_str(), to.c_str(), 0)) return;
std::error_code ec;
std::filesystem::copy(from, to,
std::filesystem::copy_options::recursive |
std::filesystem::copy_options::copy_symlinks |
std::filesystem::copy_options::skip_existing,
ec);
if (ec) std::filesystem::remove_all(to, ec); // 不完整的 profile 直接丢弃
}
std::wstring ResolveDataDir() {
std::wstring dir = ExeDir() + L"\\data";
::CreateDirectoryW(dir.c_str(), nullptr);
if (!WritableProbe(dir)) {
// exe 放在 Program Files 等只读位置时退回用户目录
dir = GetLocalAppDataDir() + L"\\PddAI";
::CreateDirectoryW(dir.c_str(), nullptr);
return dir;
}
// 首次切换到 exe\data:把旧的店铺登录态搬过来,避免重新登录
MigrateConsoles(GetLocalAppDataDir() + L"\\PddAI", dir);
return dir;
}
} // namespace
std::wstring DataDir() {
static const std::wstring dir = ResolveDataDir();
return dir;
}
std::string Base64Encode(const std::string& bytes) {
static const char* table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string out;
out.reserve(((bytes.size() + 2) / 3) * 4);
size_t i = 0;
while (i + 2 < bytes.size()) {
const unsigned char b0 = static_cast<unsigned char>(bytes[i]);
const unsigned char b1 = static_cast<unsigned char>(bytes[i + 1]);
const unsigned char b2 = static_cast<unsigned char>(bytes[i + 2]);
out += table[b0 >> 2];
out += table[((b0 & 0x03) << 4) | (b1 >> 4)];
out += table[((b1 & 0x0F) << 2) | (b2 >> 6)];
out += table[b2 & 0x3F];
i += 3;
}
const size_t rest = bytes.size() - i;
if (rest == 1) {
const unsigned char b0 = static_cast<unsigned char>(bytes[i]);
out += table[b0 >> 2];
out += table[(b0 & 0x03) << 4];
out += "==";
} else if (rest == 2) {
const unsigned char b0 = static_cast<unsigned char>(bytes[i]);
const unsigned char b1 = static_cast<unsigned char>(bytes[i + 1]);
out += table[b0 >> 2];
out += table[((b0 & 0x03) << 4) | (b1 >> 4)];
out += table[(b1 & 0x0F) << 2];
out += "=";
}
return out;
}
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)];
if (v < 0) continue;
accum = (accum << 6) | v;
bits += 6;
if (bits >= 8) {
bits -= 8;
out += static_cast<char>((accum >> bits) & 0xFF);
}
}
return out;
}
std::string Sha256Hex(const std::string& data) {
HCRYPTPROV prov = 0;
if (!::CryptAcquireContextW(&prov, nullptr, nullptr, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
return "";
}
HCRYPTHASH hash = 0;
if (!::CryptCreateHash(prov, CALG_SHA_256, 0, 0, &hash)) {
::CryptReleaseContext(prov, 0);
return "";
}
std::string out;
if (::CryptHashData(hash, reinterpret_cast<const BYTE*>(data.data()), static_cast<DWORD>(data.size()), 0)) {
BYTE digest[32]{};
DWORD len = sizeof(digest);
if (::CryptGetHashParam(hash, HP_HASHVAL, digest, &len, 0)) {
static const char* hex = "0123456789abcdef";
for (DWORD i = 0; i < len; ++i) {
out += hex[digest[i] >> 4];
out += hex[digest[i] & 0x0F];
}
}
}
::CryptDestroyHash(hash);
::CryptReleaseContext(prov, 0);
return out;
}
std::string Rfc2822NowUtc() {
SYSTEMTIME st{};
::GetSystemTime(&st);
static const char* days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
static const char* months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
FILETIME ft{};
::SystemTimeToFileTime(&st, &ft);
ULARGE_INTEGER uli;
uli.LowPart = ft.dwLowDateTime;
uli.HighPart = ft.dwHighDateTime;
// 1601-01-01 是星期一,JS getUTCDay 以周日为 0
const int wday = static_cast<int>(((uli.QuadPart / 864000000000ULL) + 1) % 7);
char buf[64];
std::snprintf(buf, sizeof(buf), "%s, %02d %s %04d %02d:%02d:%02d GMT",
days[wday], st.wDay, months[(st.wMonth - 1) % 12], st.wYear,
st.wHour, st.wMinute, st.wSecond);
return std::string(buf);
}
std::string ComputerNameUtf8() {
wchar_t name[MAX_COMPUTERNAME_LENGTH + 1]{};
DWORD len = static_cast<DWORD>(MAX_COMPUTERNAME_LENGTH + 1);
if (::GetComputerNameW(name, &len)) return WideToUtf8(std::wstring(name, len));
return "localhost";
}
void SleepMs(int ms) {
if (ms > 0) ::Sleep(static_cast<DWORD>(ms));
}
std::string LowerAscii(std::string_view s) {
std::string out(s);
for (char& c : out) {
if (c >= 'A' && c <= 'Z') c = static_cast<char>(c - 'A' + 'a');
}
return out;
}
}
+47
View File
@@ -0,0 +1,47 @@
#pragma once
#include <windows.h>
#include <string>
#include <string_view>
namespace pddai {
std::wstring Utf8ToWide(std::string_view s);
std::string WideToUtf8(std::wstring_view s);
// 复刻 Node 的 new Date().toISOString():2026-11-01T12:34:56.789Z
std::string IsoNowUtc();
// 复刻 getNextDailyTime:解析 "H:MM"/"HH:MM",返回本地时区的下一次触发时刻
bool NextDailyTime(const std::string& hhmm, SYSTEMTIME& out);
std::string FormatLocalDateTime(const SYSTEMTIME& st);
// 常量时间比较(先比长度)
bool SafeTokenEqual(std::string_view a, std::string_view b);
// 与 server/index.js escapeHtml 完全一致
std::string EscapeHtml(std::string_view value);
std::string Trim(std::string_view s);
std::wstring GetLocalAppDataDir();
// 程序所在目录
std::wstring ExeDir();
// 数据目录(WebView2 缓存、店铺登录态、日志):
// 优先 <exe 目录>\data(绿色分发);exe 目录不可写时回落到 %LOCALAPPDATA%\PddAI
std::wstring DataDir();
std::string Base64Encode(const std::string& bytes);
std::string Base64Decode(const std::string& text);
std::string Sha256Hex(const std::string& data);
// 复刻 JS 的 new Date().toUTCString():Mon, 02 Nov 2026 12:34:56 GMT
std::string Rfc2822NowUtc();
std::string ComputerNameUtf8();
void SleepMs(int ms);
std::string LowerAscii(std::string_view s);
}
File diff suppressed because it is too large Load Diff
+45
View File
@@ -0,0 +1,45 @@
#pragma once
#include <windows.h>
#include <wrl.h>
#include <string>
#include <vector>
#include "Json.h"
#include "WebView2.h"
namespace pddai {
// 内嵌客服台:每个店铺一份独立的 WebView2 Environment(独立 user data folder → 独立 cookie),
// Controller 的父窗口是主窗口,Bounds 由前端上报的内容区矩形决定。
// 之所以不用 iframe:iframe 拿不到 MAIN world 的原生 API 覆写时机,
// 也伪造不了 outerWidth/outerHeight 这组窗口级几何特征。
class WebConsole {
public:
// 打开并切换到该店铺的内嵌台;首次调用时异步创建 Environment 与 Controller。
// shopId 为空时取 shops.json 里的第一个店铺。
static bool Open(HWND owner, const std::string& shopId);
// 销毁某个店铺的 Controller 并释放它的配置目录占用
static void Close(const std::string& shopId);
static void CloseAll();
static bool IsOpen(); // 任一店铺已打开
static bool IsOpen(const std::string& shopId);
// 退出该店铺的拼多多登录:清除该配置目录下的 cookie 与站点数据后重新加载
static bool Logout(const std::string& shopId);
static std::vector<std::string> OpenShopIds();
// 前端上报内容区矩形(客户区 CSS 像素)。visible=false 时隐藏当前店铺。
static void SetLayout(const RECT& rect, bool visible);
// HTTP 线程调用:按 payload 里的 shopId 找到对应店铺,封送到 UI 线程执行真实输入
static bool DispatchInput(const json& payload, std::string& error);
// 由主窗口 WndProc 在 WM_APP_CONSOLE_INPUT 时调用(UI 线程)
static void HandleUiInputMessage(LPARAM lParam);
};
} // namespace pddai
+1881
View File
File diff suppressed because it is too large Load Diff
+21
View File
@@ -0,0 +1,21 @@
#pragma once
#define IDR_UI_HTML 101
#define IDR_INJECT_CONTENT_JS 102
#define IDR_INJECT_CONTENT_CSS 103
#define IDI_APP_ICON 104
#define IDR_EXT_MANIFEST 105
#define IDR_EXT_BACKGROUND 106
#define IDR_INJECT_STEALTH_JS 107
#define WM_APP_RESIZE (WM_APP + 1)
#define WM_APP_TRAY (WM_APP + 2)
#define WM_APP_LOG (WM_APP + 3)
#define WM_APP_POSTJSON (WM_APP + 4)
#define WM_APP_CONSOLE_INPUT (WM_APP + 5)
#define IDC_TRAY_OPEN 2001
#define IDC_TRAY_PAUSE 2002
#define IDC_TRAY_RESUME 2003
#define IDC_TRAY_OPEN_CONFIG 2004
#define IDC_TRAY_EXIT 2005
+9441
View File
File diff suppressed because it is too large Load Diff
+24765
View File
File diff suppressed because it is too large Load Diff
+2483
View File
File diff suppressed because it is too large Load Diff