pay.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. // 支付处理模块
  2. const fs = require('fs');
  3. const path = require('path');
  4. const { promisify } = require('util');
  5. const { getDatabase } = require('./sql');
  6. const copyFile = promisify(fs.copyFile);
  7. const mkdir = promisify(fs.mkdir);
  8. const access = promisify(fs.access);
  9. const readdir = promisify(fs.readdir);
  10. const stat = promisify(fs.stat);
  11. // 用户数据根目录
  12. const USERS_DIR = path.join(__dirname, 'users');
  13. // 商店资源目录
  14. const STORE_DIR = path.join(__dirname, 'market_data');
  15. // 购买记录文件
  16. const PURCHASE_RECORDS_FILE = path.join(__dirname, 'purchase-records.json');
  17. // 确保目录存在
  18. async function ensureDir(dirPath) {
  19. try {
  20. await access(dirPath);
  21. } catch (error) {
  22. await mkdir(dirPath, { recursive: true });
  23. }
  24. }
  25. // 读取购买记录
  26. async function getPurchaseRecords() {
  27. try {
  28. const data = await fs.promises.readFile(PURCHASE_RECORDS_FILE, 'utf-8');
  29. return JSON.parse(data);
  30. } catch (error) {
  31. // 如果文件不存在,返回空对象
  32. return {};
  33. }
  34. }
  35. // 保存购买记录
  36. async function savePurchaseRecords(records) {
  37. await fs.promises.writeFile(PURCHASE_RECORDS_FILE, JSON.stringify(records, null, 2), 'utf-8');
  38. }
  39. // 检查用户是否已购买过该资源
  40. async function hasUserPurchased(username, resourcePath) {
  41. const records = await getPurchaseRecords();
  42. const normalizedUsername = username.toLowerCase();
  43. const userPurchases = records[normalizedUsername] || [];
  44. return userPurchases.includes(resourcePath);
  45. }
  46. // 记录用户购买
  47. async function recordPurchase(username, resourcePath) {
  48. const records = await getPurchaseRecords();
  49. const normalizedUsername = username.toLowerCase();
  50. if (!records[normalizedUsername]) {
  51. records[normalizedUsername] = [];
  52. }
  53. // 如果还没有记录,则添加
  54. if (!records[normalizedUsername].includes(resourcePath)) {
  55. records[normalizedUsername].push(resourcePath);
  56. await savePurchaseRecords(records);
  57. console.log(`[Pay] 已记录购买: ${normalizedUsername} -> ${resourcePath}`);
  58. }
  59. }
  60. // 获取用户网盘目录
  61. function getUserDiskDir(username) {
  62. const normalizedUsername = username.toLowerCase();
  63. return path.join(USERS_DIR, normalizedUsername, 'disk_data');
  64. }
  65. // 递归复制目录
  66. async function copyDirectory(src, dest) {
  67. console.log(`[Pay] [copyDirectory] 创建目标目录: ${dest}`);
  68. await ensureDir(dest);
  69. console.log(`[Pay] [copyDirectory] 读取源目录: ${src}`);
  70. const entries = await readdir(src);
  71. console.log(`[Pay] [copyDirectory] 找到 ${entries.length} 个项目`);
  72. for (let i = 0; i < entries.length; i++) {
  73. const entry = entries[i];
  74. const srcPath = path.join(src, entry);
  75. const destPath = path.join(dest, entry);
  76. console.log(`[Pay] [copyDirectory] [${i + 1}/${entries.length}] 处理: ${entry}`);
  77. try {
  78. const stats = await stat(srcPath);
  79. if (stats.isDirectory()) {
  80. console.log(`[Pay] [copyDirectory] 类型: 目录,递归复制`);
  81. await copyDirectory(srcPath, destPath);
  82. console.log(`[Pay] [copyDirectory] ✓ 目录复制完成: ${entry}`);
  83. } else {
  84. console.log(`[Pay] [copyDirectory] 类型: 文件,大小: ${stats.size} 字节`);
  85. await copyFile(srcPath, destPath);
  86. console.log(`[Pay] [copyDirectory] ✓ 文件复制完成: ${entry}`);
  87. }
  88. } catch (entryError) {
  89. console.error(`[Pay] [copyDirectory] ✗ 处理失败: ${entry}`, entryError);
  90. throw entryError;
  91. }
  92. }
  93. console.log(`[Pay] [copyDirectory] ✓ 目录复制完成: ${src} -> ${dest}`);
  94. }
  95. // 处理购买请求
  96. async function handlePurchaseRequest(req, res) {
  97. let body = '';
  98. req.on('data', chunk => {
  99. body += chunk.toString();
  100. });
  101. req.on('end', async () => {
  102. try {
  103. console.log('\n========== [Pay] 收到购买请求 ==========');
  104. console.log('[Pay] 原始请求体:', body);
  105. const data = JSON.parse(body);
  106. const { username, resourcePath, categoryDir, itemName, price, points } = data;
  107. // 兼容 price 和 points 两种参数名
  108. const finalPrice = price !== undefined ? price : (points !== undefined ? points : 0);
  109. console.log('[Pay] 解析后的参数:');
  110. console.log(' - username:', username);
  111. console.log(' - resourcePath:', resourcePath);
  112. console.log(' - categoryDir:', categoryDir);
  113. console.log(' - itemName:', itemName);
  114. console.log(' - price:', price);
  115. console.log(' - points:', points);
  116. console.log(' - finalPrice:', finalPrice);
  117. if (!username) {
  118. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  119. res.end(JSON.stringify({
  120. success: false,
  121. message: '缺少用户名参数'
  122. }));
  123. return;
  124. }
  125. if (!resourcePath || !categoryDir) {
  126. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  127. res.end(JSON.stringify({
  128. success: false,
  129. message: '缺少资源路径参数'
  130. }));
  131. return;
  132. }
  133. // 构建源路径(商店资源路径)
  134. // resourcePath 格式为 "categoryDir/itemName",例如 "charactor/player_0001"
  135. let sourcePath;
  136. if (resourcePath && resourcePath.includes('/')) {
  137. // resourcePath 已经包含分类目录
  138. sourcePath = path.join(STORE_DIR, resourcePath);
  139. } else if (categoryDir && resourcePath) {
  140. // resourcePath 只是资源名称,需要拼接分类目录
  141. sourcePath = path.join(STORE_DIR, categoryDir, resourcePath);
  142. } else {
  143. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  144. res.end(JSON.stringify({
  145. success: false,
  146. message: '资源路径格式错误'
  147. }));
  148. return;
  149. }
  150. console.log(`[Pay] 构建源路径: STORE_DIR=${STORE_DIR}, resourcePath=${resourcePath}, categoryDir=${categoryDir}, sourcePath=${sourcePath}`);
  151. // 检查源文件/文件夹是否存在
  152. try {
  153. await access(sourcePath);
  154. } catch (error) {
  155. console.error(`[Pay] 资源不存在: ${sourcePath}`, error);
  156. res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
  157. res.end(JSON.stringify({
  158. success: false,
  159. message: `资源不存在: ${sourcePath}`
  160. }));
  161. return;
  162. }
  163. // 获取用户网盘目录
  164. console.log('[Pay] 步骤1: 获取用户网盘目录');
  165. const userDiskDir = getUserDiskDir(username);
  166. console.log('[Pay] 用户网盘目录:', userDiskDir);
  167. console.log('[Pay] 步骤2: 确保用户网盘目录存在');
  168. await ensureDir(userDiskDir);
  169. console.log('[Pay] ✓ 用户网盘目录已存在或已创建');
  170. // 目标路径(用户网盘根目录)
  171. // resourcePath 格式为 "categoryDir/itemName",例如 "角色/player_0001"
  172. // 只取最后一级目录名(资源名),直接放到根目录
  173. const resourceName = itemName || path.basename(resourcePath);
  174. // 生成唯一的文件名(如果已存在,自动添加(1)、(2)等后缀)
  175. console.log('[Pay] 步骤3: 生成唯一的目标路径');
  176. let finalResourceName = resourceName;
  177. let destPath = path.join(userDiskDir, finalResourceName);
  178. let counter = 0;
  179. // 检查目标路径是否已存在,如果存在则生成新名称
  180. while (true) {
  181. try {
  182. await access(destPath);
  183. // 文件/文件夹已存在,生成新名称
  184. counter++;
  185. // 检查是否是文件夹(没有扩展名)还是文件
  186. const parsed = path.parse(resourceName);
  187. if (parsed.ext) {
  188. // 是文件,保留扩展名
  189. finalResourceName = `${parsed.name}(${counter})${parsed.ext}`;
  190. } else {
  191. // 是文件夹,直接添加后缀
  192. finalResourceName = `${resourceName}(${counter})`;
  193. }
  194. destPath = path.join(userDiskDir, finalResourceName);
  195. console.log(`[Pay] 名称冲突,尝试新名称: ${finalResourceName}`);
  196. } catch (error) {
  197. // 文件/文件夹不存在,可以使用这个名称
  198. console.log(`[Pay] ✓ 找到可用名称: ${finalResourceName}`);
  199. break;
  200. }
  201. }
  202. console.log(`[Pay] 最终资源名称: ${finalResourceName}`);
  203. console.log(`[Pay] 最终目标路径: ${destPath}`);
  204. // 检查并扣除用户点数
  205. console.log('[Pay] 步骤4: 检查并扣除用户点数');
  206. if (finalPrice && finalPrice > 0) {
  207. const db = await getDatabase();
  208. const currentPoints = db.getUserPoints(username);
  209. console.log(`[Pay] 当前点数: ${currentPoints}, 需要点数: ${finalPrice}`);
  210. if (currentPoints < finalPrice) {
  211. console.log('[Pay] ✗ 点数不足');
  212. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  213. res.end(JSON.stringify({
  214. success: false,
  215. message: '点数不足'
  216. }));
  217. return;
  218. }
  219. // 扣除点数
  220. const deducted = db.deductPoints(username, finalPrice);
  221. if (!deducted) {
  222. console.log('[Pay] ✗ 扣除点数失败');
  223. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  224. res.end(JSON.stringify({
  225. success: false,
  226. message: '扣除点数失败'
  227. }));
  228. return;
  229. }
  230. console.log(`[Pay] ✓ 用户 ${username} 扣除 ${finalPrice} 点数成功`);
  231. } else {
  232. console.log('[Pay] 免费资源,跳过点数检查');
  233. }
  234. // 复制文件/文件夹到用户网盘
  235. console.log('[Pay] 步骤5: 检查源路径类型');
  236. const sourceStats = await stat(sourcePath);
  237. console.log(`[Pay] 源路径类型: ${sourceStats.isDirectory() ? '目录' : '文件'}`);
  238. console.log(`[Pay] 源路径大小: ${sourceStats.size} 字节`);
  239. try {
  240. if (sourceStats.isDirectory()) {
  241. // 复制文件夹
  242. console.log('[Pay] 步骤6: 开始复制文件夹');
  243. console.log(`[Pay] 源文件夹: ${sourcePath}`);
  244. console.log(`[Pay] 目标文件夹: ${destPath}`);
  245. // 先确保目标目录的父目录存在
  246. const destParentDir = path.dirname(destPath);
  247. console.log(`[Pay] 确保父目录存在: ${destParentDir}`);
  248. await ensureDir(destParentDir);
  249. console.log(`[Pay] ✓ 父目录已存在或已创建`);
  250. console.log(`[Pay] 开始递归复制...`);
  251. await copyDirectory(sourcePath, destPath);
  252. console.log(`[Pay] ✓ 文件夹复制完成`);
  253. // 验证复制是否成功
  254. console.log('[Pay] 步骤9: 验证复制结果');
  255. try {
  256. const destStats = await stat(destPath);
  257. console.log(`[Pay] ✓ 目标文件夹存在: ${destPath}`);
  258. console.log(`[Pay] 目标文件夹类型: ${destStats.isDirectory() ? '目录' : '文件'}`);
  259. // 检查文件夹内容
  260. const destFiles = await readdir(destPath);
  261. console.log(`[Pay] 目标文件夹包含 ${destFiles.length} 个项目`);
  262. if (destFiles.length > 0) {
  263. console.log(`[Pay] 前5个项目: ${destFiles.slice(0, 5).join(', ')}`);
  264. }
  265. } catch (verifyError) {
  266. console.error(`[Pay] ✗ 验证失败,目标文件夹不存在: ${destPath}`);
  267. console.error(`[Pay] 错误详情:`, verifyError);
  268. throw new Error('复制失败:目标文件夹未创建');
  269. }
  270. } else {
  271. // 复制文件
  272. console.log('[Pay] 步骤6: 开始复制文件');
  273. const destParentDir = path.dirname(destPath);
  274. console.log(`[Pay] 确保父目录存在: ${destParentDir}`);
  275. await ensureDir(destParentDir);
  276. console.log(`[Pay] ✓ 父目录已存在或已创建`);
  277. console.log(`[Pay] 源文件: ${sourcePath}`);
  278. console.log(`[Pay] 目标文件: ${destPath}`);
  279. console.log(`[Pay] 开始复制文件...`);
  280. await copyFile(sourcePath, destPath);
  281. console.log(`[Pay] ✓ 文件复制完成`);
  282. // 验证复制是否成功
  283. console.log('[Pay] 步骤7: 验证复制结果');
  284. try {
  285. const destStats = await stat(destPath);
  286. console.log(`[Pay] ✓ 目标文件存在: ${destPath}`);
  287. console.log(`[Pay] 目标文件大小: ${destStats.size} 字节`);
  288. } catch (verifyError) {
  289. console.error(`[Pay] ✗ 验证失败,目标文件不存在: ${destPath}`);
  290. console.error(`[Pay] 错误详情:`, verifyError);
  291. throw new Error('复制失败:目标文件未创建');
  292. }
  293. }
  294. } catch (copyError) {
  295. console.error(`[Pay] ✗ 复制过程出错:`);
  296. console.error(`[Pay] 错误类型: ${copyError.constructor.name}`);
  297. console.error(`[Pay] 错误消息: ${copyError.message}`);
  298. console.error(`[Pay] 错误堆栈:`, copyError.stack);
  299. throw copyError;
  300. }
  301. // 记录购买(即使文件被删除,购买记录也会保留)
  302. console.log('[Pay] 步骤8: 记录购买');
  303. await recordPurchase(username, resourcePath);
  304. console.log(`[Pay] ✓ 购买记录已保存`);
  305. // 返回成功
  306. console.log('[Pay] 步骤9: 返回成功响应');
  307. console.log(`[Pay] ✓ 购买成功!资源已添加到用户网盘`);
  308. console.log(`[Pay] 用户名: ${username}`);
  309. console.log(`[Pay] 资源路径: ${resourcePath}`);
  310. console.log(`[Pay] 目标路径: ${destPath}`);
  311. console.log('========== [Pay] 购买请求处理完成 ==========\n');
  312. res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
  313. res.end(JSON.stringify({
  314. success: true,
  315. message: '购买成功,文件已添加到网盘',
  316. itemName: itemName,
  317. price: finalPrice,
  318. destPath: destPath
  319. }));
  320. } catch (error) {
  321. console.error('\n========== [Pay] 购买请求处理失败 ==========');
  322. console.error('[Pay] 错误类型:', error.constructor.name);
  323. console.error('[Pay] 错误消息:', error.message);
  324. console.error('[Pay] 错误堆栈:', error.stack);
  325. console.error('========== [Pay] 错误信息结束 ==========\n');
  326. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  327. res.end(JSON.stringify({
  328. success: false,
  329. message: '购买失败: ' + error.message
  330. }));
  331. }
  332. });
  333. }
  334. // 检查资源是否已存在于用户网盘根目录或购买记录中
  335. async function checkResourceExists(username, resourcePath) {
  336. try {
  337. // 首先检查购买记录(即使文件被删除,购买记录仍然保留)
  338. const hasPurchased = await hasUserPurchased(username, resourcePath);
  339. if (hasPurchased) {
  340. console.log(`[Pay] 资源在购买记录中: ${username} -> ${resourcePath}`);
  341. return true; // 已购买过,即使文件不存在也返回true
  342. }
  343. // 然后检查文件是否存在
  344. const userDiskDir = getUserDiskDir(username);
  345. // 只使用资源名,检查根目录
  346. const resourceName = path.basename(resourcePath);
  347. const destPath = path.join(userDiskDir, resourceName);
  348. try {
  349. await access(destPath);
  350. return true; // 资源已存在
  351. } catch (error) {
  352. return false; // 资源不存在
  353. }
  354. } catch (error) {
  355. console.error(`[Pay] 检查资源是否存在失败:`, error);
  356. return false;
  357. }
  358. }
  359. // 处理检查资源是否存在的请求
  360. async function handleCheckResourceRequest(req, res) {
  361. const parsedUrl = require('url').parse(req.url, true);
  362. const { username, resourcePath } = parsedUrl.query;
  363. if (!username || !resourcePath) {
  364. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  365. res.end(JSON.stringify({
  366. success: false,
  367. message: '缺少参数'
  368. }));
  369. return;
  370. }
  371. try {
  372. const exists = await checkResourceExists(username, resourcePath);
  373. res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
  374. res.end(JSON.stringify({
  375. success: true,
  376. exists: exists
  377. }));
  378. } catch (error) {
  379. console.error('[Pay] 检查资源失败:', error);
  380. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  381. res.end(JSON.stringify({
  382. success: false,
  383. message: '检查失败: ' + error.message
  384. }));
  385. }
  386. }
  387. // 获取用户购买记录(包含资源详细信息)
  388. async function getUserPurchaseHistory(username) {
  389. try {
  390. const records = await getPurchaseRecords();
  391. const normalizedUsername = username.toLowerCase();
  392. const userPurchases = records[normalizedUsername] || [];
  393. // 获取资源详细信息
  394. const StoreManager = require('./store/store');
  395. const storeManager = new StoreManager();
  396. const purchaseHistory = [];
  397. for (const resourcePath of userPurchases) {
  398. try {
  399. // resourcePath 格式为 "分类/资源名",例如 "角色/player_0001"
  400. const parts = resourcePath.split('/');
  401. if (parts.length === 2) {
  402. const [categoryDir, resourceName] = parts;
  403. const resourcePath_full = path.join(STORE_DIR, resourcePath);
  404. // 检查资源是否存在
  405. try {
  406. await access(resourcePath_full);
  407. // 获取预览图
  408. const previewInfo = await storeManager.getFirstFrame(resourcePath_full);
  409. // 获取资源价格
  410. const price = await storeManager.getResourcePrice(resourcePath);
  411. purchaseHistory.push({
  412. name: resourceName,
  413. category: categoryDir,
  414. path: resourcePath,
  415. previewUrl: previewInfo.hasPreview
  416. ? `/api/store/preview?category=${encodeURIComponent(categoryDir)}&folder=${encodeURIComponent(resourceName)}&file=${encodeURIComponent(previewInfo.previewFile)}`
  417. : null,
  418. points: price
  419. });
  420. } catch (error) {
  421. // 资源文件不存在,但仍然显示在购买记录中(可能被删除)
  422. purchaseHistory.push({
  423. name: resourceName,
  424. category: categoryDir,
  425. path: resourcePath,
  426. previewUrl: null,
  427. points: 0,
  428. deleted: true // 标记为已删除
  429. });
  430. }
  431. }
  432. } catch (error) {
  433. console.error(`[Pay] 获取购买记录资源信息失败: ${resourcePath}`, error);
  434. }
  435. }
  436. return purchaseHistory;
  437. } catch (error) {
  438. console.error('[Pay] 获取购买记录失败:', error);
  439. return [];
  440. }
  441. }
  442. // 处理获取购买记录请求
  443. async function handleGetPurchaseHistory(req, res) {
  444. try {
  445. const url = new URL(req.url, `http://${req.headers.host}`);
  446. const username = url.searchParams.get('username');
  447. if (!username) {
  448. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  449. res.end(JSON.stringify({
  450. success: false,
  451. message: '缺少用户名参数'
  452. }));
  453. return;
  454. }
  455. const history = await getUserPurchaseHistory(username);
  456. res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
  457. res.end(JSON.stringify({
  458. success: true,
  459. history: history
  460. }));
  461. } catch (error) {
  462. console.error('[Pay] 获取购买记录失败:', error);
  463. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  464. res.end(JSON.stringify({
  465. success: false,
  466. message: '获取购买记录失败: ' + error.message
  467. }));
  468. }
  469. }
  470. module.exports = {
  471. handlePurchaseRequest,
  472. checkResourceExists,
  473. handleCheckResourceRequest,
  474. handleGetPurchaseHistory
  475. };