diff --git a/server2.js b/server2.js
index d030f3d..795b478 100755
--- a/server2.js
+++ b/server2.js
@@ -13,18 +13,18 @@ const https = require("https");
// 强制 IPv4 的 https agent
const ipv4Agent = new https.Agent({
- family: 4, // 最关键:强制 IPv4
- keepAlive: true,
- maxSockets: 100,
- keepAliveMsecs: 10000,
+ family: 4, // 最关键:强制 IPv4
+ keepAlive: true,
+ maxSockets: 100,
+ keepAliveMsecs: 10000,
});
// 包一个强制 IPv4 的 fetch
const fetchIPv4 = (url, options = {}) => {
- return fetch(url, {
- ...options,
- agent: ipv4Agent, // 👈 加上 IPv4 专用 agent
- });
+ return fetch(url, {
+ ...options,
+ agent: ipv4Agent, // 👈 加上 IPv4 专用 agent
+ });
};
@@ -47,31 +47,31 @@ const accessTokenUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=clien
const mysql = require("mysql2/promise");
// 初始化数据库连接池
const pool = mysql.createPool({
- host: "1.95.137.212",
- user: "fastbee",
- password: "maibu520",
- database: "fastbee",
- waitForConnections: true,
- connectionLimit: 10,
+ host: "1.95.137.212",
+ user: "fastbee",
+ password: "maibu520",
+ database: "fastbee",
+ waitForConnections: true,
+ connectionLimit: 10,
});
// 允许大文件请求体
app.use(bodyParser.json({ limit: "500mb" }));
app.use(bodyParser.urlencoded({ limit: "500mb", extended: true }));
app.use(xmlparser({
- explicitArray: false, // 禁用默认的数组格式,和你后续xml2js配置一致
- trim: true // 去除字符串前后空格
+ explicitArray: false, // 禁用默认的数组格式,和你后续xml2js配置一致
+ trim: true // 去除字符串前后空格
}));
// Multer 上传目录
const upload = multer({
- dest: "uploads/",
- limits: { fileSize: 500 * 1024 * 1024 }, // 500MB
+ dest: "uploads/",
+ limits: { fileSize: 500 * 1024 * 1024 }, // 500MB
});
// Node <20 兼容 File
if (typeof File === "undefined") {
- globalThis.File = require("node:buffer").File;
+ globalThis.File = require("node:buffer").File;
}
// 启用 CORS
@@ -144,22 +144,20 @@ const client1 = new OpenAI({
});
-async function test1()
-{
- console.time("test");
- await client.chat.completions.create({
+async function test1() {
+ console.time("test");
+ await client.chat.completions.create({
model: "gpt-4.1", // 注意:这里必须是你在 Azure portal 里创建的“部署名称”
messages: [
{ role: "user", content: "ping" }
]
});
- console.timeEnd("test");
+ console.timeEnd("test");
}
-async function directCall()
-{
- console.time("directCall");
- await client1.chat.completions.create({ model:"gpt-5-mini", messages:[{ role: "user", content: "ping" }] });
- console.timeEnd("directCall");
+async function directCall() {
+ console.time("directCall");
+ await client1.chat.completions.create({ model: "gpt-5-mini", messages: [{ role: "user", content: "ping" }] });
+ console.timeEnd("directCall");
}
test1();
@@ -168,64 +166,64 @@ directCall();
// 获取 access_token
// getAccessToken();
async function getAccessToken() {
- const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`;
- const res = await axios.get(url);
- if (res.data.access_token) {
- console.log('✅ 获取 access_token 成功',res.data);
-
- return res.data.access_token;
- } else {
- throw new Error('❌ 获取 access_token 失败: ' + JSON.stringify(res.data));
- }
+ const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`;
+ const res = await axios.get(url);
+ if (res.data.access_token) {
+ console.log('✅ 获取 access_token 成功', res.data);
+
+ return res.data.access_token;
+ } else {
+ throw new Error('❌ 获取 access_token 失败: ' + JSON.stringify(res.data));
+ }
}
const WECHAT_OAUTH_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/access_token';
app.get('/wechat/oauth/access-token', async (req, res) => {
try {
- console.log(req.query)
- // 1. 接收并校验前端传递的 code 参数
- const { code } = req.query; // 从URL查询参数中获取 code
- if (!code) {
- return res.status(400).json({
- code: -1,
- message: '参数错误:缺少 code(微信授权临时票据)'
- });
- }
+ console.log(req.query)
+ // 1. 接收并校验前端传递的 code 参数
+ const { code } = req.query; // 从URL查询参数中获取 code
+ if (!code) {
+ return res.status(400).json({
+ code: -1,
+ message: '参数错误:缺少 code(微信授权临时票据)'
+ });
+ }
- // 3. 调用微信 OAuth2 接口,传递必要参数
- const response = await axios.get(WECHAT_OAUTH_TOKEN_URL, {
- params: {
- appid: "wx364b8ebf17fe45fe", // 你的微信appid
- secret: "9b7476020991a2c71f1416da7f011d31", // 你的微信secret
- code: code, // 前端传递的授权code
- grant_type: 'authorization_code' // 固定值
- }
- });
+ // 3. 调用微信 OAuth2 接口,传递必要参数
+ const response = await axios.get(WECHAT_OAUTH_TOKEN_URL, {
+ params: {
+ appid: "wx364b8ebf17fe45fe", // 你的微信appid
+ secret: "9b7476020991a2c71f1416da7f011d31", // 你的微信secret
+ code: code, // 前端传递的授权code
+ grant_type: 'authorization_code' // 固定值
+ }
+ });
- // 4. 处理微信返回的结果
- const wechatData = response.data;
+ // 4. 处理微信返回的结果
+ const wechatData = response.data;
- // 微信接口失败(返回 errcode 字段)
- if (wechatData.errcode) {
- throw new Error(`微信接口错误:${wechatData.errmsg}(错误码:${wechatData.errcode})`);
- }
+ // 微信接口失败(返回 errcode 字段)
+ if (wechatData.errcode) {
+ throw new Error(`微信接口错误:${wechatData.errmsg}(错误码:${wechatData.errcode})`);
+ }
- // 5. 成功响应:返回微信返回的所有信息(包含 access_token、openid 等)
- res.status(200).json({
- code: 0,
- message: '获取 OAuth2 access_token 成功',
- data: wechatData // 包含 access_token、expires_in、refresh_token、openid 等
- });
+ // 5. 成功响应:返回微信返回的所有信息(包含 access_token、openid 等)
+ res.status(200).json({
+ code: 0,
+ message: '获取 OAuth2 access_token 成功',
+ data: wechatData // 包含 access_token、expires_in、refresh_token、openid 等
+ });
- } catch (error) {
- // 异常处理:捕获网络错误、微信接口错误等
- console.error('获取 OAuth2 access_token 失败:', error.message);
- res.status(500).json({
- code: -3,
- message: '获取 access_token 失败:' + error.message
- });
- }
+ } catch (error) {
+ // 异常处理:捕获网络错误、微信接口错误等
+ console.error('获取 OAuth2 access_token 失败:', error.message);
+ res.status(500).json({
+ code: -3,
+ message: '获取 access_token 失败:' + error.message
+ });
+ }
});
/*菜单部分 */
@@ -261,9 +259,9 @@ async function createMenu() {
"name": "AI智能体",
// "url":`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx364b8ebf17fe45fe&redirect_uri= encodeURIComponent("https://ai.satabot.com/?from=weixin")&response_type=code&scope=snsapi_login&state=123#wechat_redirect`,
"url": "https://ai.satabot.com/middle.html"
-
+
},
-
+
]
},
{
@@ -299,91 +297,91 @@ async function createMenu() {
"name": "加入我们",
"url": "https://www.zhipin.com/gongsi/job/d1e30046e726d2d01nN72Ni4EFQ~.html?ka=all-jobs-hot"
},
- {
+ {
"type": "view",
"name": "运维招工",
- "url": "https://zp.satabot.com/#/pages/Wxpublic/Wxpublic?redirect=/pages/index/index"
-
+ "url": "https://zp.satabot.com/"
+
}
]
}
]
};
- const res = await axios.post(url, menuData);
- if (res.data.errcode === 0) {
- console.log('✅ 菜单创建成功');
- } else {
- console.error('❌ 菜单创建失败:', res.data);
- }
+ const res = await axios.post(url, menuData);
+ if (res.data.errcode === 0) {
+ console.log('✅ 菜单创建成功');
+ } else {
+ console.error('❌ 菜单创建失败:', res.data);
+ }
}
// ========== 查询菜单 ==========
async function getMenu() {
- const accessToken = await getAccessToken();
- const url = `https://api.weixin.qq.com/cgi-bin/menu/get?access_token=${accessToken}`;
- const res = await axios.get(url);
- return res.data;
+ const accessToken = await getAccessToken();
+ const url = `https://api.weixin.qq.com/cgi-bin/menu/get?access_token=${accessToken}`;
+ const res = await axios.get(url);
+ return res.data;
}
// ========== 删除菜单(可选)==========
async function deleteMenu() {
- const accessToken = await getAccessToken();
- const url = `https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=${accessToken}`;
- const res = await axios.get(url);
- return res.data;
+ const accessToken = await getAccessToken();
+ const url = `https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=${accessToken}`;
+ const res = await axios.get(url);
+ return res.data;
}
app.get('/createMenu', async (req, res) => {
- try {
- await createMenu();
- res.send('✅ 菜单创建成功!');
- } catch (err) {
- res.send('❌ 创建失败: ' + err.message);
- }
+ try {
+ await createMenu();
+ res.send('✅ 菜单创建成功!');
+ } catch (err) {
+ res.send('❌ 创建失败: ' + err.message);
+ }
});
app.get('/getMenu', async (req, res) => {
- try {
- const data = await getMenu();
- res.json(data);
- } catch (err) {
- res.send('❌ 查询失败: ' + err.message);
- }
+ try {
+ const data = await getMenu();
+ res.json(data);
+ } catch (err) {
+ res.send('❌ 查询失败: ' + err.message);
+ }
});
app.get('/deleteMenu', async (req, res) => {
- try {
- const data = await deleteMenu();
- res.json(data);
- } catch (err) {
- res.send('❌ 删除失败: ' + err.message);
- }
+ try {
+ const data = await deleteMenu();
+ res.json(data);
+ } catch (err) {
+ res.send('❌ 删除失败: ' + err.message);
+ }
});
app.post('/wechat', async (req, res) => {
- try {
- console.log("收到请求:", req.body);
- const xml = req.body;
- const message = xml.xml;
-
- // 修复语法错误:移除msgtype前的空格
- const msgType = message.msgtype;
- const fromUser = message.fromusername; // openid
- const toUser = message.tousername; // 公众号原始ID
-
- console.log("消息类型:", msgType);
- console.log("用户OpenID:", fromUser);
-
- // 菜单点击事件
- if (msgType === 'event' && message.event === 'CLICK') {
- const key = message.eventkey;
- console.log("菜单点击Key:", key);
-
- if (key === 'AI_INTELLIGENT') {
- try {
- const timestamp = Date.now();
- // 方案一:简单文本回复(推荐,避免超时)
- const reply = `
+ try {
+ console.log("收到请求:", req.body);
+ const xml = req.body;
+ const message = xml.xml;
+
+ // 修复语法错误:移除msgtype前的空格
+ const msgType = message.msgtype;
+ const fromUser = message.fromusername; // openid
+ const toUser = message.tousername; // 公众号原始ID
+
+ console.log("消息类型:", msgType);
+ console.log("用户OpenID:", fromUser);
+
+ // 菜单点击事件
+ if (msgType === 'event' && message.event === 'CLICK') {
+ const key = message.eventkey;
+ console.log("菜单点击Key:", key);
+
+ if (key === 'AI_INTELLIGENT') {
+ try {
+ const timestamp = Date.now();
+ // 方案一:简单文本回复(推荐,避免超时)
+ const reply = `
@@ -392,76 +390,76 @@ app.post('/wechat', async (req, res) => {
立即进入AI智能体]]>
`;
- res.send(reply);
- return;
-
- // 启动异步任务处理耗时操作
- setTimeout(async () => {
- try {
- const token = await getAccessToken();
- console.log("获取到Token:", token);
-
- // 获取用户信息
-
- const userRes = await axios.get('https://api.weixin.qq.com/sns/userinfo', {
- params: {
- access_token:token,
- fromUser,
- lang: 'zh_CN'
- }
- });
- console.log(userRes, 'user000000000000');
- // res.redirect('https://ai.satabot.com');
- const { nickname, errcode: userErrCode } = userRes.data;
- console.log(nickname, 'nickname');
- return;
- if (userErrCode) return res.status(500).send(`获取用户信息失败:${userErrCode}`);
- const userInfoRes = await axios.get(
- `https://api.weixin.qq.com/cgi-bin/user/info?access_token=${token}&openid=${fromUser}&lang=zh_CN`
- );
-
- const user = userInfoRes.data;
- console.log("用户信息:", user);
-
- // 使用客服消息接口发送详细回复
- if (user && user.nickname) {
- await sendCustomerServiceMessage(fromUser, `你好,${user.nickname}!欢迎使用AI智能体`);
- }
- } catch (err) {
- console.error("异步处理错误:", err);
- }
- }, 0);
-
- return;
-
- // 方案二:直接回复(如果能确保5秒内完成)
- /*
- const token = await getAccessToken();
- console.log("Token:", token);
-
- const userInfoRes = await axios.get(
- `https://api.weixin.qq.com/cgi-bin/user/info?access_token=${token}&openid=${fromUser}&lang=zh_CN`
- );
-
- const user = userInfoRes.data;
- console.log("用户信息:", user);
-
- const reply = `
-
-
-
- ${Date.now()}
-
-
-
- `;
- res.send(reply);
- return;
- */
- } catch (err) {
- console.error("处理AI_INTELLIGENT错误:", err);
- // 出错时返回标准回复
- const errorReply = `
+ res.send(reply);
+ return;
+
+ // 启动异步任务处理耗时操作
+ setTimeout(async () => {
+ try {
+ const token = await getAccessToken();
+ console.log("获取到Token:", token);
+
+ // 获取用户信息
+
+ const userRes = await axios.get('https://api.weixin.qq.com/sns/userinfo', {
+ params: {
+ access_token: token,
+ fromUser,
+ lang: 'zh_CN'
+ }
+ });
+ console.log(userRes, 'user000000000000');
+ // res.redirect('https://ai.satabot.com');
+ const { nickname, errcode: userErrCode } = userRes.data;
+ console.log(nickname, 'nickname');
+ return;
+ if (userErrCode) return res.status(500).send(`获取用户信息失败:${userErrCode}`);
+ const userInfoRes = await axios.get(
+ `https://api.weixin.qq.com/cgi-bin/user/info?access_token=${token}&openid=${fromUser}&lang=zh_CN`
+ );
+
+ const user = userInfoRes.data;
+ console.log("用户信息:", user);
+
+ // 使用客服消息接口发送详细回复
+ if (user && user.nickname) {
+ await sendCustomerServiceMessage(fromUser, `你好,${user.nickname}!欢迎使用AI智能体`);
+ }
+ } catch (err) {
+ console.error("异步处理错误:", err);
+ }
+ }, 0);
+
+ return;
+
+ // 方案二:直接回复(如果能确保5秒内完成)
+ /*
+ const token = await getAccessToken();
+ console.log("Token:", token);
+
+ const userInfoRes = await axios.get(
+ `https://api.weixin.qq.com/cgi-bin/user/info?access_token=${token}&openid=${fromUser}&lang=zh_CN`
+ );
+
+ const user = userInfoRes.data;
+ console.log("用户信息:", user);
+
+ const reply = `
+
+
+
+ ${Date.now()}
+
+
+
+ `;
+ res.send(reply);
+ return;
+ */
+ } catch (err) {
+ console.error("处理AI_INTELLIGENT错误:", err);
+ // 出错时返回标准回复
+ const errorReply = `
@@ -470,21 +468,120 @@ app.post('/wechat', async (req, res) => {
`;
- res.send(errorReply);
- return;
- }
- }
- }
-
- // 默认回复空串(表示不处理)
- res.send('');
-
- } catch (err) {
- console.error("服务器错误:", err);
- // 异常情况下回复空串
- res.send('');
+ res.send(errorReply);
+ return;
+ }
+ }
+ }
+
+ // 默认回复空串(表示不处理)
+ res.send('');
+
+ } catch (err) {
+ console.error("服务器错误:", err);
+ // 异常情况下回复空串
+ res.send('');
}
- });
+});
+
+app.get('/webCallback', async (req, res) => {
+ try {
+ // 获取 URL 中的 code 和 state 参数
+ const { code, state } = req.query;
+ if (!code) {
+ return res.status(400).send('授权失败:没有 code');
+ }
+
+ // 记录 extraParams
+ console.log('Extra Params:', state);
+
+ // 1️⃣ 用 code 换 access_token
+ const tokenRes = await axios.get('https://api.weixin.qq.com/sns/oauth2/access_token', {
+ params: {
+ appid: 'wx0eeb7556d60121db',
+ secret: 'a01456fbccf15adf57ea0d3c702d4e31',
+ code,
+ grant_type: 'authorization_code',
+ },
+ });
+
+ const { access_token, openid, unionid } = tokenRes.data;
+ console.log('Access Token Response:', tokenRes.data);
+
+ if (!access_token || !openid) {
+ return res.status(400).send('access_token 获取失败');
+ }
+
+ // 2️⃣ 用 access_token 和 openid 拉取用户信息
+ const userInfoRes = await axios.get('https://api.weixin.qq.com/sns/userinfo', {
+ params: {
+ access_token,
+ openid,
+ lang: 'zh_CN',
+ },
+ });
+
+ const userInfo = userInfoRes.data;
+ console.log('User Info Response:', userInfoRes.data);
+ const datalogin = {
+ sourceType: 1,
+ openId: openid,
+ phonenumber: '',
+ smsCode: '',
+ loginPlatForm: 2
+
+ }
+ console.log(datalogin, "data")
+ // 3️⃣ 发送用户信息到登录接口
+ try {
+ const loginRes = await axios.post('https://serviceri.satabot.com/login', datalogin, {
+ headers: {
+ 'Content-Type': 'application/json',
+ }
+ });
+ console.log('Login Response:', loginRes.data);
+ if (loginRes.data.code === 200) {
+ // 登录成功,设置 token 并跳转
+ const { token, userId, username } = loginRes.data;
+ res.cookie('Admin-Token', token, {
+ maxAge: 900000, httpOnly: true, sameSite: 'None', // 或 'Strict' / 'Lax',具体根据需要选择
+ });
+ res.cookie('userId', userId, {
+ maxAge: 900000, httpOnly: true, sameSite: 'None', // 或 'Strict' / 'Lax',具体根据需要选择
+ });
+
+ const encodedUserId = btoa(unescape(encodeURIComponent(userId)));
+ // 跳转到指定的页面
+ const t = Date.now();
+ // document.body.classList.add('fadeout');
+ if (state == "ai") {
+ res.redirect(`https://ai.satabot.com?userId=${encodedUserId}&headingimg=${userInfo.headimgurl}&nickname=${userInfo.nickname}&localtoken=${token}&t=${t}`);
+ // window.location.replace(`https://ai.satabot.com?userId=${encodedUserId}&headingimg=${userInfo.headimgurl}&nickname=${userInfo.nickname}&localtoken=${token}&t=${t}`);
+
+ } else {
+ const encodedToken = btoa(unescape(encodeURIComponent(token)));
+ const encodedUsername = btoa(unescape(encodeURIComponent(username)));
+ res.redirect(`http://ri.satabot.com/#/index?djjdbsjdwjhedbh=${encodedToken}&username=${encodedUsername}`);
+ }
+ // res.redirect(`https://ai.satabot.com?userId=${encodedUserId}&headingimg=${userInfo.headimgurl}&nickname=${userInfo.nickname}&localtoken=${token}&t=${t}`);
+
+ // res.redirect(`https://ai.satabot.com?userId=${encodedUserId}&headingimg=${userInfo.headimgurl}&nickname=${userInfo.nickname}&localtoken=${token}&t=${t}`);
+ // window.location.replace(`https://ai.satabot.com?userId=${encodedUserId}&headingimg=${userInfo.headimgurl}&nickname=${userInfo.nickname}&localtoken=${token}&t=${t}`);
+
+ } else {
+ return res.status(400).send('登录失败');
+ }
+ } catch (err) {
+ console.error('Login Error:', err);
+ return res.status(500).send('登录接口请求失败');
+ }
+
+ } catch (err) {
+ console.error('Error:', err.response?.data || err);
+ res.status(500).send('服务器错误');
+ }
+});
+
// app.post('/wechat', async (req, res) => {
@@ -493,7 +590,7 @@ app.post('/wechat', async (req, res) => {
// const xml = req.body;
// console.log(xml);
// const message = xml.xml;
-
+
// const msgType = message.msgtype;
// const fromUser = message.fromusername; // openid
@@ -555,153 +652,153 @@ app.post('/wechat', async (req, res) => {
// OAuth2 回调
app.get('/wechat/oauth/callback', async (req, res) => {
- try {
- const { code, state } = req.query;
- console.log(code,"code")
-
+ try {
+ const { code, state } = req.query;
+ console.log(code, "code")
- // 用 code 换取 access_token 和 openid
- const tokenResp = await axios.get(
- `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=${code}&grant_type=authorization_code`
- );
- const { access_token, openid } = tokenResp.data;
- // 拉取用户信息
- const userInfoResp = await axios.get(
- `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`
- );
- const user = userInfoResp.data;
+ // 用 code 换取 access_token 和 openid
+ const tokenResp = await axios.get(
+ `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=${code}&grant_type=authorization_code`
+ );
+ const { access_token, openid } = tokenResp.data;
- console.log(user, "获取到用户信息");
+ // 拉取用户信息
+ const userInfoResp = await axios.get(
+ `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`
+ );
+ const user = userInfoResp.data;
- // 你可以直接跳转到前端页面并带上用户信息
- res.redirect(`https://ai.satabot.com?nickname=${encodeURIComponent(user.nickname)}&openid=${openid}`);
- } catch (err) {
- console.error(err);
- res.send("获取用户信息失败");
- }
+ console.log(user, "获取到用户信息");
+
+ // 你可以直接跳转到前端页面并带上用户信息
+ res.redirect(`https://ai.satabot.com?nickname=${encodeURIComponent(user.nickname)}&openid=${openid}`);
+ } catch (err) {
+ console.error(err);
+ res.send("获取用户信息失败");
+ }
});
app.get("/test-db", async (req, res) => {
- try {
- await pool.query(
- "INSERT INTO ai_chat_messages (session_id, role, content) VALUES (?, 'user', ?)",
- ["sess1", "hello"]
- );
- res.send("OK");
- } catch (err) {
- console.error(err);
- res.send("FAIL");
- }
+ try {
+ await pool.query(
+ "INSERT INTO ai_chat_messages (session_id, role, content) VALUES (?, 'user', ?)",
+ ["sess1", "hello"]
+ );
+ res.send("OK");
+ } catch (err) {
+ console.error(err);
+ res.send("FAIL");
+ }
});
app.get("/wechat/userinfo", async (req, res) => {
- const { code } = req.query;
- if (!code) return res.status(400).send("缺少 code");
+ const { code } = req.query;
+ if (!code) return res.status(400).send("缺少 code");
- try {
- // 1. 用 code 换取 access_token 和 openid
- const tokenResp = await axios.get(
- `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=${code}&grant_type=authorization_code`
- );
- const { access_token, openid } = tokenResp.data;
+ try {
+ // 1. 用 code 换取 access_token 和 openid
+ const tokenResp = await axios.get(
+ `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=${code}&grant_type=authorization_code`
+ );
+ const { access_token, openid } = tokenResp.data;
- // 2. 拉取用户信息
- const userRes = await axios.get(
- `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`
- );
- const userInfo = userRes.data;
+ // 2. 拉取用户信息
+ const userRes = await axios.get(
+ `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`
+ );
+ const userInfo = userRes.data;
- // 3. 返回给前端
- res.json({ code: 0, data: userInfo });
- } catch (err) {
- console.error(err);
- res.status(500).send("获取用户信息失败");
- }
+ // 3. 返回给前端
+ res.json({ code: 0, data: userInfo });
+ } catch (err) {
+ console.error(err);
+ res.status(500).send("获取用户信息失败");
+ }
});
app.post("/user", async (req, res) => {
- try {
- const { userId } = req.body; // 从请求体里拿到 user_id
-
+ try {
+ const { userId } = req.body; // 从请求体里拿到 user_id
- if (!userId&&userId!="NaN") {
- res.json({
- code: 300,
- error: "http://ri.satabot.com/#/login?goRemote=1",
- msg:"未找到该用户"
+
+ if (!userId && userId != "NaN") {
+ res.json({
+ code: 300,
+ error: "http://ri.satabot.com/#/login?goRemote=1",
+ msg: "未找到该用户"
});
- return;
- }
+ return;
+ }
- // 查询 user_name
- const [rows] = await pool.query(
- "SELECT user_name FROM sys_user WHERE user_id = ?",
- [userId]
- );
+ // 查询 user_name
+ const [rows] = await pool.query(
+ "SELECT user_name FROM sys_user WHERE user_id = ?",
+ [userId]
+ );
- if (rows.length === 0) {
- res.json({
- code: 300,
- error: "http://ri.satabot.com/#/login?goRemote=1",
- msg:"未找到该用户"
+ if (rows.length === 0) {
+ res.json({
+ code: 300,
+ error: "http://ri.satabot.com/#/login?goRemote=1",
+ msg: "未找到该用户"
});
- return;
- }
+ return;
+ }
- res.json({ code:0,userId, userName: rows[0].user_name });
- } catch (err) {
- console.error(err);
- res.status(500).send("服务器错误");
- }
+ res.json({ code: 0, userId, userName: rows[0].user_name });
+ } catch (err) {
+ console.error(err);
+ res.status(500).send("服务器错误");
+ }
});
app.post("/getuserByopenid", async (req, res) => {
- try {
- const { userId } = req.body; // 从请求体里拿到 user_id
+ try {
+ const { userId } = req.body; // 从请求体里拿到 user_id
- if (!userId) {
- return res.status(400).send("缺少 user_id");
- }
-
- // 查询 user_name
- const [rows] = await pool.query(
- "SELECT * FROM sys_user WHERE open_id = ?",
- [userId]
- );
- if (rows.length > 0) {
- // 用户存在,直接返回
- res.json({ code: 0, msg: "找到该用户",userId:rows[0].user_id });
- return
- } else {
- // 用户不存在,插入新用户
- const [result] = await pool.query(
- "INSERT INTO sys_user (open_id,user_name,nick_name) VALUES (?,?,?)",
- [userId,userId,userId]
- );
- console.log(result,"udgwehvdh")
- res.json({code:0,msg:"新增该用户",userId:result.insertId});
- return ;
+ if (!userId) {
+ return res.status(400).send("缺少 user_id");
}
- } catch (err) {
- console.error(err);
- res.status(500).send("服务器错误");
- }
+
+ // 查询 user_name
+ const [rows] = await pool.query(
+ "SELECT * FROM sys_user WHERE open_id = ?",
+ [userId]
+ );
+ if (rows.length > 0) {
+ // 用户存在,直接返回
+ res.json({ code: 0, msg: "找到该用户", userId: rows[0].user_id });
+ return
+ } else {
+ // 用户不存在,插入新用户
+ const [result] = await pool.query(
+ "INSERT INTO sys_user (open_id,user_name,nick_name) VALUES (?,?,?)",
+ [userId, userId, userId]
+ );
+ console.log(result, "udgwehvdh")
+ res.json({ code: 0, msg: "新增该用户", userId: result.insertId });
+ return;
+ }
+ } catch (err) {
+ console.error(err);
+ res.status(500).send("服务器错误");
+ }
});
app.get('/wechat', (req, res) => {
- const { signature, timestamp, nonce, echostr } = req.query;
- console.log(req, "req");
- const arr = [TOKEN, timestamp, nonce].sort();
- const str = arr.join('');
- const hash = crypto.createHash('sha1').update(str).digest('hex');
- if (hash === signature) res.send(echostr);
- else res.send('验证失败');
+ const { signature, timestamp, nonce, echostr } = req.query;
+ console.log(req, "req");
+ const arr = [TOKEN, timestamp, nonce].sort();
+ const str = arr.join('');
+ const hash = crypto.createHash('sha1').update(str).digest('hex');
+ if (hash === signature) res.send(echostr);
+ else res.send('验证失败');
});
// 查询用户所有会话列表
@@ -710,18 +807,17 @@ app.get("/sessions", async (req, res) => {
console.log("收到的 userId:", req.query.userId);
try {
const userId = req.query.userId;
- if (!userId || userId == "NaN" || isNaN(Number(userId)))
- {
+ if (!userId || userId == "NaN" || isNaN(Number(userId))) {
console.log("userId:", req.query.userId);
res.json({
code: 300,
// error:'https://gsgg.com'
// error: "http://ri.satabot.com/#/dhhdghgbshwadhg"
- error: "http://ri.satabot.com/#/login?goRemote=1"
+ error: "http://ri.satabot.com/#/login?goRemote=1"
});
return;
- // return res.status(500).json({ code: 505, error: "http://1.95.137.212/#/login?redirect=%2Findex&goRemote=1" });
- // return res.redirect('http://1.95.137.212/#/login?redirect=%2Findex&goRemote=1');
+ // return res.status(500).json({ code: 505, error: "http://1.95.137.212/#/login?redirect=%2Findex&goRemote=1" });
+ // return res.redirect('http://1.95.137.212/#/login?redirect=%2Findex&goRemote=1');
}
// return;
@@ -737,18 +833,18 @@ app.get("/sessions", async (req, res) => {
// [userId]
// );
// const [rows] = await pool.query(`
- // SELECT m.session_id, m.title
- // FROM ai_chat_messages m
- // INNER JOIN (
- // SELECT session_id, MAX(created_at) AS last_time
- // FROM ai_chat_messages
- // WHERE user_id = ?
- // GROUP BY session_id
- // ) t ON m.session_id = t.session_id AND m.created_at = t.last_time
- // WHERE m.user_id = ?
- // ORDER BY t.last_time ASC
+ // SELECT m.session_id, m.title
+ // FROM ai_chat_messages m
+ // INNER JOIN (
+ // SELECT session_id, MAX(created_at) AS last_time
+ // FROM ai_chat_messages
+ // WHERE user_id = ?
+ // GROUP BY session_id
+ // ) t ON m.session_id = t.session_id AND m.created_at = t.last_time
+ // WHERE m.user_id = ?
+ // ORDER BY t.last_time ASC
// `, [userId, userId]);
- const [rows] = await pool.query(`
+ const [rows] = await pool.query(`
SELECT session_id, title
FROM ai_chat_messages
WHERE user_id = ?
@@ -758,16 +854,15 @@ app.get("/sessions", async (req, res) => {
ORDER BY MIN(created_at) ASC
`, [userId]);
-res.json({
- code: 0,
- sessions: rows.map(r => ({
- sessId: r.session_id,
- title: r.title
- }))
-});
- }
- catch (err)
- {
+ res.json({
+ code: 0,
+ sessions: rows.map(r => ({
+ sessId: r.session_id,
+ title: r.title
+ }))
+ });
+ }
+ catch (err) {
console.error("查询会话列表失败:", err);
res.status(500).json({ code: 1, error: err.message });
}
@@ -775,24 +870,22 @@ res.json({
// 查询会话历史
app.get("/history", async (req, res) => {
- try
- {
- if(!req.query?.sessionId || req.query?.sessionId == "NaN")
- {
+ try {
+ if (!req.query?.sessionId || req.query?.sessionId == "NaN") {
return res.status(400).json({ code: 1, error: "sessionId 必填" });
}
const { sessionId } = req.query;
// 查询数据库
const [rows] = await pool.query(
- "SELECT user_id, role, content, image_base64, created_at,title FROM ai_chat_messages WHERE session_id = ? ORDER BY id ASC",
- [sessionId]
+ "SELECT user_id, role, content, image_base64, created_at,title FROM ai_chat_messages WHERE session_id = ? ORDER BY id ASC",
+ [sessionId]
);
res.json({
- code: 0,
- sessionId,
- messages: rows,
+ code: 0,
+ sessionId,
+ messages: rows,
});
} catch (err) {
console.error("查询会话历史失败:", err);
@@ -802,13 +895,11 @@ app.get("/history", async (req, res) => {
// 删除指定会话及其消息
app.delete("/session", async (req, res) => {
- try
- {
+ try {
console.log("会话删除:", req.query);
-
+
// if (!sessionId || !userId)
- if (req.query?.userId == "NaN" || !req.query?.userId || !req.query?.sessionId || req.query?.sessionId == "NaN")
- {
+ if (req.query?.userId == "NaN" || !req.query?.userId || !req.query?.sessionId || req.query?.sessionId == "NaN") {
return res.status(400).json({ code: 1, error: "sessionId 和 userId 必填" });
}
@@ -835,8 +926,7 @@ app.delete("/session", async (req, res) => {
message: `会话 ${sessionId} 已删除`,
});
}
- catch (err)
- {
+ catch (err) {
console.error("删除会话失败:", err);
res.status(500).json({ code: 1, error: err.message });
}
@@ -844,13 +934,11 @@ app.delete("/session", async (req, res) => {
// 新建会话(实际上就是往消息表里插入一条记录)
app.post("/session", async (req, res) => {
- try
- {
- console.log("新建会话: ",req.body)
-
- if (req.body?.userId == "NaN" || !req.body?.userId || !req.body?.sessionId || req.body?.sessionId == "NaN")
- {
- console.log("=== userId: ",req.body?.userId)
+ try {
+ console.log("新建会话: ", req.body)
+
+ if (req.body?.userId == "NaN" || !req.body?.userId || !req.body?.sessionId || req.body?.sessionId == "NaN") {
+ console.log("=== userId: ", req.body?.userId)
return res.status(400).json({ code: 1, error: "userId 和 sessionId 必填" });
}
@@ -867,8 +955,7 @@ app.post("/session", async (req, res) => {
message: `会话 ${sessionId} 已创建`,
});
}
- catch (err)
- {
+ catch (err) {
console.error("创建会话失败:", err);
res.status(500).json({ code: 1, error: err.message });
}
@@ -883,39 +970,39 @@ const aiChatNum = new Map(); // userId -> number
const mutexes = new Map(); // userId -> Mutex
function getMutex(userId) {
- if (!mutexes.has(userId)) mutexes.set(userId, new Mutex());
- return mutexes.get(userId);
+ if (!mutexes.has(userId)) mutexes.set(userId, new Mutex());
+ return mutexes.get(userId);
}
-async function setQuota(userId,num) {
- const m = getMutex(userId);
- return await m.runExclusive(async () => {
- console.log("更新用户对话次数:", userId, num);
- aiChatNum.set(userId, num);
- });
+async function setQuota(userId, num) {
+ const m = getMutex(userId);
+ return await m.runExclusive(async () => {
+ console.log("更新用户对话次数:", userId, num);
+ aiChatNum.set(userId, num);
+ });
}
async function hasQuota(userId) {
- const m = getMutex(userId);
- return await m.runExclusive(async () => {
- return aiChatNum.has(userId);
- });
+ const m = getMutex(userId);
+ return await m.runExclusive(async () => {
+ return aiChatNum.has(userId);
+ });
}
async function getQuota(userId) {
- const m = getMutex(userId);
- return await m.runExclusive(async () => {
- console.log("获取用户对话次数:", userId, aiChatNum.get(userId));
- return aiChatNum.get(userId);
- });
+ const m = getMutex(userId);
+ return await m.runExclusive(async () => {
+ console.log("获取用户对话次数:", userId, aiChatNum.get(userId));
+ return aiChatNum.get(userId);
+ });
}
async function removeQuota(userId) {
- const m = getMutex(userId);
- return await m.runExclusive(async () => {
- aiChatNum.delete(userId);
- });
+ const m = getMutex(userId);
+ return await m.runExclusive(async () => {
+ aiChatNum.delete(userId);
+ });
}
// ====================== API ======================
@@ -928,18 +1015,17 @@ app.post("/refreshAiChatNum", async (req, res) => {
);
if (userRemainChatNum.length > 0) {
const quota = userRemainChatNum[0].ai_chat_num;
- console.log(userId,"刷新对话次数",quota);
- await setQuota(userId,quota);
+ console.log(userId, "刷新对话次数", quota);
+ await setQuota(userId, quota);
}
- } catch (error) {
- console.error("更新失败:", error);
- }
+ } catch (error) {
+ console.error("更新失败:", error);
+ }
})
app.post("/analyze", upload.single("file"), async (req, res) => {
- const { userId } = req.body;
- try
- {
+ const { userId } = req.body;
+ try {
const exists = await hasQuota(userId);
if (!exists) {
const [userRemainChatNum] = await pool.query(
@@ -951,13 +1037,13 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
if (quota <= 0 && quota !== -1) {
return res.status(400).json({ error: "对话次数已用完,请完成账号注册" });
}
- await setQuota(userId,quota);
+ await setQuota(userId, quota);
}
} else {
const quota = await getQuota(userId);
if (quota <= 0 && quota !== -1) {
return res.status(400).json({ error: "对话次数已用完,请完成账号注册" });
- }
+ }
}
const { requestId } = req.body;
@@ -974,22 +1060,20 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
console.time("analyze");
- const logBody = { ...req.body };
- if(req.body?.imageBase64)
- {
+ const logBody = { ...req.body };
+ if (req.body?.imageBase64) {
delete logBody.imageBase64;
}
console.log("analyze: ", logBody);
// console.log("analyze: ",req.body)
- if (!req.body?.userId || !req.body?.sessionId)
- {
+ if (!req.body?.userId || !req.body?.sessionId) {
console.log("缺少必要参数");
return res.status(400).json({ error: "缺少必要参数" });
}
- const { userPrompt, imageBase64, sessionId } = req.body;
- const [rows] = await pool.query(
- `
+ const { userPrompt, imageBase64, sessionId } = req.body;
+ const [rows] = await pool.query(
+ `
SELECT EXISTS(
SELECT 1
FROM ai_chat_messages
@@ -999,8 +1083,8 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
AND title != ''
) AS hasTitle
`,
- [sessionId, userId]
- );
+ [sessionId, userId]
+ );
const existingTitle = rows[0].hasTitle === 1; // true / false
console.log(existingTitle, rows?.[0], 9999, rows)
@@ -1019,26 +1103,24 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
role: row.role,
content: []
};
-
+
// 添加文本内容
- if (row.content)
- {
+ if (row.content) {
message.content.push({ type: "text", text: row.content });
}
-
+
// 添加图片内容
- if (row.image_base64)
- {
+ if (row.image_base64) {
message.content.push({
- type: "image_url",
- image_url: {
- url: row.image_base64.startsWith("data:")
- ? row.image_base64
- : `data:image/png;base64,${row.image_base64}`,
- }
+ type: "image_url",
+ image_url: {
+ url: row.image_base64.startsWith("data:")
+ ? row.image_base64
+ : `data:image/png;base64,${row.image_base64}`,
+ }
});
}
-
+
return message;
});
@@ -1065,17 +1147,17 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
{
role: "user",
content: [
- { type: "text", text: userPrompt || "请描述图片内容。" },
- imageBase64
- ? {
- type: "image_url",
- image_url: {
- url: imageBase64.startsWith("data:")
- ? imageBase64
- : `data:image/png;base64,${imageBase64}`,
- },
- }
- : null,
+ { type: "text", text: userPrompt || "请描述图片内容。" },
+ imageBase64
+ ? {
+ type: "image_url",
+ image_url: {
+ url: imageBase64.startsWith("data:")
+ ? imageBase64
+ : `data:image/png;base64,${imageBase64}`,
+ },
+ }
+ : null,
].filter(Boolean),
},
];
@@ -1097,8 +1179,7 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
});
res.socket.setNoDelay(true);
- for await (const chunk of completion)
- {
+ for await (const chunk of completion) {
if (stopFlags.get(requestId)) {
console.log("⛔ 图像分析被前端中断");
res.end();
@@ -1108,8 +1189,7 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
const delta = chunk.choices[0]?.delta?.content || "";
sceneText += delta;
- if (delta)
- {
+ if (delta) {
res.write(
`data: ${JSON.stringify({ type: "scene", content: delta })}\n\n`
);
@@ -1164,9 +1244,8 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
console.log("====== 开始深度思考... ======")
let llmText = "";
- for await (const chunk of llmStream)
- {
- if (stopFlags.get(requestId)) {
+ for await (const chunk of llmStream) {
+ if (stopFlags.get(requestId)) {
console.log("⛔ 深度分析被前端中断");
res.end();
stopFlags.delete(requestId);
@@ -1177,10 +1256,10 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
if (delta)
res.write(
- `data: ${JSON.stringify({ type: "llm", content: delta})}\n\n`
+ `data: ${JSON.stringify({ type: "llm", content: delta })}\n\n`
);
-
+
/* delta 很长,这会 人为拉长处理时间。 */
// if (delta)
// {
@@ -1191,61 +1270,58 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
// }
// }
}
-
-
- // 保存 LLM 输出到数据库
- /* 加标题需要异步,且在会话开始时就进行 */
- if (existingTitle) {
- console.log("uidh")
- await pool.query(
- "INSERT INTO ai_chat_messages (session_id, user_id, role, content) VALUES (?, ?, 'assistant', ?)",
- [sessId, userId || null, llmText]
- );
- } else {
- console.log("uidh1111")
- try
- {
- const titlePrompt = `请根据以下对话内容生成一个简短的标题(不超过15字):
+
+ // 保存 LLM 输出到数据库
+ /* 加标题需要异步,且在会话开始时就进行 */
+ if (existingTitle) {
+ console.log("uidh")
+ await pool.query(
+ "INSERT INTO ai_chat_messages (session_id, user_id, role, content) VALUES (?, ?, 'assistant', ?)",
+ [sessId, userId || null, llmText]
+ );
+ } else {
+ console.log("uidh1111")
+
+ try {
+ const titlePrompt = `请根据以下对话内容生成一个简短的标题(不超过15字):
用户问题: ${userPrompt}
AI回答: ${llmText}`;
- const titleResp = await client1.chat.completions.create({
- model: "gpt-5-mini",
- messages: [
- { role: "system", content: "你是标题生成助手,只返回标题,不要解释。" },
- { role: "user", content: titlePrompt }
- ]
- });
+ const titleResp = await client1.chat.completions.create({
+ model: "gpt-5-mini",
+ messages: [
+ { role: "system", content: "你是标题生成助手,只返回标题,不要解释。" },
+ { role: "user", content: titlePrompt }
+ ]
+ });
- const title = titleResp.choices[0]?.message?.content?.trim() || "未命名会话";
- res.write(
+ const title = titleResp.choices[0]?.message?.content?.trim() || "未命名会话";
+ res.write(
`data: ${JSON.stringify({ type: "title", content: title })}\n\n`
);
- console.log("生成的标题:", title);
+ console.log("生成的标题:", title);
- // 保存到数据库(建议你给 ai_chat_messages 表新增一列 title,或者单独建一张会话表)
- await pool.query(
- "INSERT INTO ai_chat_messages (session_id, user_id, role, content,title) VALUES (?, ?, 'assistant', ?,?)",
- [sessId, userId || null, llmText,title]
- );
- }
- catch (err)
- {
- console.error("生成标题失败:", err.message);
- }
+ // 保存到数据库(建议你给 ai_chat_messages 表新增一列 title,或者单独建一张会话表)
+ await pool.query(
+ "INSERT INTO ai_chat_messages (session_id, user_id, role, content,title) VALUES (?, ?, 'assistant', ?,?)",
+ [sessId, userId || null, llmText, title]
+ );
}
-
+ catch (err) {
+ console.error("生成标题失败:", err.message);
+ }
+ }
+
+
-
res.write("data: [DONE]\n\n");
res.end();
// 删除上传文件
- if (req.file && req.file.path)
- {
+ if (req.file && req.file.path) {
fs.unlinkSync(req.file.path);
}
console.log("====== 分析完成 ======");
@@ -1258,55 +1334,54 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
// await setQuota(userId,userChatNum);
// console.log(`用户剩余AI 对话次数: ${userChatNum}`);
// }
- }
- catch (err)
- {
+ }
+ catch (err) {
console.error("❌ 调用失败:", err.response?.data || err.message);
res.status(500).json({ code: 1, error: err.response?.data || err.message });
}
finally {
- let userChatNum = await getQuota(userId);
- if (userChatNum !== -1 && userChatNum !== undefined) {
- userChatNum = Math.max(0, userChatNum - 1); // 防止变成负数
- await setQuota(userId, userChatNum);
+ let userChatNum = await getQuota(userId);
+ if (userChatNum !== -1 && userChatNum !== undefined) {
+ userChatNum = Math.max(0, userChatNum - 1); // 防止变成负数
+ await setQuota(userId, userChatNum);
// 更新数据库
await pool.query(
"update sys_user set ai_chat_num = ? where user_id= ?",
[userChatNum, userId]
);
console.log("更新用户对话次数:", userId, userChatNum);
- }
+ }
- }
+ }
});
app.post("/stop", express.json(), (req, res) => {
- const { requestId } = req.body;
- console.log("🔴 收到停止信号:", requestId);
+ const { requestId } = req.body;
+ console.log("🔴 收到停止信号:", requestId);
stopFlags.set(requestId, true);
- console.log(stopFlags,"消息id");
- res.json({ ok: true });
+ console.log(stopFlags, "消息id");
+ res.json({ ok: true });
});
-app.post('/submit',async (req, res) => {
- const { company, scenes, needs, userId } = req.body;
+app.post('/submit', async (req, res) => {
+ const { company, scenes, needs, userId } = req.body;
- console.log("收到数据:", company, scenes, needs, userId);
+ console.log("收到数据:", company, scenes, needs, userId);
- if (!company || !needs || !userId) {
- return res.status(400).json({ message: "缺少必要字段" });
- }
+ if (!company || !needs || !userId) {
+ return res.status(400).json({ message: "缺少必要字段" });
+ }
- try {
- const sql =
- "INSERT INTO pv_form (company, scenes, needs, userId) VALUES (?, ?, ?, ?)";
+ try {
+ const sql =
+ "INSERT INTO pv_form (company, scenes, needs, userId) VALUES (?, ?, ?, ?)";
- await pool.query(sql, [company, scenes, needs, userId || null]);
+ await pool.query(sql, [company, scenes, needs, userId || null]);
- res.json({ code:200,message: "提交成功!" });
- } catch (err) {
- console.error("数据库插入失败:", err);
- res.status(500).json({ message: "数据库写入失败" });
- }
+ res.json({ code: 200, message: "提交成功!" });
+ } catch (err) {
+ console.error("数据库插入失败:", err);
+ res.status(500).json({ message: "数据库写入失败" });
+ }
});
@@ -1359,5 +1434,5 @@ app.use("/uploads", express.static("uploads"));
// 启动服务
app.listen(port, () => {
- console.log(`✅ 服务器运行:http://localhost:${port}`);
+ console.log(`✅ 服务器运行:http://localhost:${port}`);
});