main.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. const { app, BrowserWindow, dialog, Tray, Menu, shell } = require('electron');
  2. const { spawn } = require('child_process');
  3. const path = require('path');
  4. const http = require('http');
  5. const fs = require('fs');
  6. let mainWindow;
  7. let serverProcess;
  8. let tray = null;
  9. let serverErrorLogs = [];
  10. const PORT = 3000;
  11. // 保存日志到文件并打开
  12. function saveAndOpenErrorLog() {
  13. try {
  14. const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
  15. const logFileName = `new-api-crash-${timestamp}.log`;
  16. const logDir = app.getPath('logs');
  17. const logFilePath = path.join(logDir, logFileName);
  18. // 确保日志目录存在
  19. if (!fs.existsSync(logDir)) {
  20. fs.mkdirSync(logDir, { recursive: true });
  21. }
  22. // 写入日志
  23. const logContent = `New API 崩溃日志
  24. 生成时间: ${new Date().toLocaleString('zh-CN')}
  25. 平台: ${process.platform}
  26. 架构: ${process.arch}
  27. 应用版本: ${app.getVersion()}
  28. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  29. 完整错误日志:
  30. ${serverErrorLogs.join('\n')}
  31. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  32. 日志文件位置: ${logFilePath}
  33. `;
  34. fs.writeFileSync(logFilePath, logContent, 'utf8');
  35. // 打开日志文件
  36. shell.openPath(logFilePath).then((error) => {
  37. if (error) {
  38. console.error('Failed to open log file:', error);
  39. // 如果打开文件失败,至少显示文件位置
  40. shell.showItemInFolder(logFilePath);
  41. }
  42. });
  43. return logFilePath;
  44. } catch (err) {
  45. console.error('Failed to save error log:', err);
  46. return null;
  47. }
  48. }
  49. // 分析错误日志,识别常见错误并提供解决方案
  50. function analyzeError(errorLogs) {
  51. const allLogs = errorLogs.join('\n');
  52. // 检测端口占用错误
  53. if (allLogs.includes('failed to start HTTP server') ||
  54. allLogs.includes('bind: address already in use') ||
  55. allLogs.includes('listen tcp') && allLogs.includes('bind: address already in use')) {
  56. return {
  57. type: '端口被占用',
  58. title: '端口 ' + PORT + ' 被占用',
  59. message: '无法启动服务器,端口已被其他程序占用',
  60. solution: `可能的解决方案:\n\n1. 关闭占用端口 ${PORT} 的其他程序\n2. 检查是否已经运行了另一个 New API 实例\n3. 使用以下命令查找占用端口的进程:\n Mac/Linux: lsof -i :${PORT}\n Windows: netstat -ano | findstr :${PORT}\n4. 重启电脑以释放端口`
  61. };
  62. }
  63. // 检测数据库错误
  64. if (allLogs.includes('database is locked') ||
  65. allLogs.includes('unable to open database')) {
  66. return {
  67. type: '数据库错误',
  68. title: '数据库访问失败',
  69. message: '无法访问或锁定数据库文件',
  70. solution: '可能的解决方案:\n\n1. 确保没有其他 New API 实例正在运行\n2. 检查数据库文件权限\n3. 尝试删除数据库锁文件(.db-shm 和 .db-wal)\n4. 重启应用程序'
  71. };
  72. }
  73. // 检测权限错误
  74. if (allLogs.includes('permission denied') ||
  75. allLogs.includes('access denied')) {
  76. return {
  77. type: '权限错误',
  78. title: '权限不足',
  79. message: '程序没有足够的权限执行操作',
  80. solution: '可能的解决方案:\n\n1. 以管理员/root权限运行程序\n2. 检查数据目录的读写权限\n3. 检查可执行文件的权限\n4. 在 Mac 上,检查安全性与隐私设置'
  81. };
  82. }
  83. // 检测网络错误
  84. if (allLogs.includes('network is unreachable') ||
  85. allLogs.includes('no such host') ||
  86. allLogs.includes('connection refused')) {
  87. return {
  88. type: '网络错误',
  89. title: '网络连接失败',
  90. message: '无法建立网络连接',
  91. solution: '可能的解决方案:\n\n1. 检查网络连接是否正常\n2. 检查防火墙设置\n3. 检查代理配置\n4. 确认目标服务器地址正确'
  92. };
  93. }
  94. // 检测配置文件错误
  95. if (allLogs.includes('invalid configuration') ||
  96. allLogs.includes('failed to parse config') ||
  97. allLogs.includes('yaml') || allLogs.includes('json') && allLogs.includes('parse')) {
  98. return {
  99. type: '配置错误',
  100. title: '配置文件错误',
  101. message: '配置文件格式不正确或包含无效配置',
  102. solution: '可能的解决方案:\n\n1. 检查配置文件格式是否正确\n2. 恢复默认配置\n3. 删除配置文件让程序重新生成\n4. 查看文档了解正确的配置格式'
  103. };
  104. }
  105. // 检测内存不足
  106. if (allLogs.includes('out of memory') ||
  107. allLogs.includes('cannot allocate memory')) {
  108. return {
  109. type: '内存不足',
  110. title: '系统内存不足',
  111. message: '程序运行时内存不足',
  112. solution: '可能的解决方案:\n\n1. 关闭其他占用内存的程序\n2. 增加系统可用内存\n3. 重启电脑释放内存\n4. 检查是否存在内存泄漏'
  113. };
  114. }
  115. // 检测文件不存在错误
  116. if (allLogs.includes('no such file or directory') ||
  117. allLogs.includes('cannot find the file')) {
  118. return {
  119. type: '文件缺失',
  120. title: '找不到必需的文件',
  121. message: '缺少程序运行所需的文件',
  122. solution: '可能的解决方案:\n\n1. 重新安装应用程序\n2. 检查安装目录是否完整\n3. 确保所有依赖文件都存在\n4. 检查文件路径是否正确'
  123. };
  124. }
  125. return null;
  126. }
  127. function getBinaryPath() {
  128. const isDev = process.env.NODE_ENV === 'development';
  129. const platform = process.platform;
  130. if (isDev) {
  131. const binaryName = platform === 'win32' ? 'new-api.exe' : 'new-api';
  132. return path.join(__dirname, '..', binaryName);
  133. }
  134. let binaryName;
  135. switch (platform) {
  136. case 'win32':
  137. binaryName = 'new-api.exe';
  138. break;
  139. case 'darwin':
  140. binaryName = 'new-api';
  141. break;
  142. case 'linux':
  143. binaryName = 'new-api';
  144. break;
  145. default:
  146. binaryName = 'new-api';
  147. }
  148. return path.join(process.resourcesPath, 'bin', binaryName);
  149. }
  150. function startServer() {
  151. return new Promise((resolve, reject) => {
  152. const binaryPath = getBinaryPath();
  153. const isDev = process.env.NODE_ENV === 'development';
  154. console.log('Starting server from:', binaryPath);
  155. const env = { ...process.env, PORT: PORT.toString() };
  156. let dataDir;
  157. if (isDev) {
  158. dataDir = path.join(__dirname, '..', 'data');
  159. } else {
  160. const userDataPath = app.getPath('userData');
  161. dataDir = path.join(userDataPath, 'data');
  162. }
  163. if (!fs.existsSync(dataDir)) {
  164. fs.mkdirSync(dataDir, { recursive: true });
  165. }
  166. env.SQLITE_PATH = path.join(dataDir, 'new-api.db');
  167. const workingDir = isDev
  168. ? path.join(__dirname, '..')
  169. : process.resourcesPath;
  170. serverProcess = spawn(binaryPath, [], {
  171. env,
  172. cwd: workingDir
  173. });
  174. serverProcess.stdout.on('data', (data) => {
  175. console.log(`Server: ${data}`);
  176. });
  177. serverProcess.stderr.on('data', (data) => {
  178. const errorMsg = data.toString();
  179. console.error(`Server Error: ${errorMsg}`);
  180. serverErrorLogs.push(errorMsg);
  181. // 只保留最近的100条错误日志
  182. if (serverErrorLogs.length > 100) {
  183. serverErrorLogs.shift();
  184. }
  185. });
  186. serverProcess.on('error', (err) => {
  187. console.error('Failed to start server:', err);
  188. reject(err);
  189. });
  190. serverProcess.on('close', (code) => {
  191. console.log(`Server process exited with code ${code}`);
  192. // 如果退出代码不是0,说明服务器异常退出
  193. if (code !== 0 && code !== null) {
  194. const errorDetails = serverErrorLogs.length > 0
  195. ? serverErrorLogs.slice(-20).join('\n')
  196. : '没有捕获到错误日志';
  197. // 分析错误类型
  198. const knownError = analyzeError(serverErrorLogs);
  199. let dialogOptions;
  200. if (knownError) {
  201. // 识别到已知错误,显示友好的错误信息和解决方案
  202. dialogOptions = {
  203. type: 'error',
  204. title: knownError.title,
  205. message: knownError.message,
  206. detail: `${knownError.solution}\n\n━━━━━━━━━━━━━━━━━━━━━━\n\n退出代码: ${code}\n\n错误类型: ${knownError.type}\n\n最近的错误日志:\n${errorDetails}`,
  207. buttons: ['退出应用', '查看完整日志'],
  208. defaultId: 0,
  209. cancelId: 0
  210. };
  211. } else {
  212. // 未识别的错误,显示通用错误信息
  213. dialogOptions = {
  214. type: 'error',
  215. title: '服务器崩溃',
  216. message: '服务器进程异常退出',
  217. detail: `退出代码: ${code}\n\n最近的错误信息:\n${errorDetails}`,
  218. buttons: ['退出应用', '查看完整日志'],
  219. defaultId: 0,
  220. cancelId: 0
  221. };
  222. }
  223. dialog.showMessageBox(dialogOptions).then((result) => {
  224. if (result.response === 1) {
  225. // 用户选择查看详情,保存并打开日志文件
  226. const logPath = saveAndOpenErrorLog();
  227. // 显示确认对话框
  228. const confirmMessage = logPath
  229. ? `日志已保存到:\n${logPath}\n\n日志文件已在默认文本编辑器中打开。\n\n点击"退出"关闭应用程序。`
  230. : '日志保存失败,但已在控制台输出。\n\n点击"退出"关闭应用程序。';
  231. dialog.showMessageBox({
  232. type: 'info',
  233. title: '日志已保存',
  234. message: confirmMessage,
  235. buttons: ['退出'],
  236. defaultId: 0
  237. }).then(() => {
  238. app.isQuitting = true;
  239. app.quit();
  240. });
  241. // 同时在控制台输出
  242. console.log('=== 完整错误日志 ===');
  243. console.log(serverErrorLogs.join('\n'));
  244. } else {
  245. // 用户选择直接退出
  246. app.isQuitting = true;
  247. app.quit();
  248. }
  249. });
  250. } else {
  251. // 正常退出(code为0或null),直接关闭窗口
  252. if (mainWindow && !mainWindow.isDestroyed()) {
  253. mainWindow.close();
  254. }
  255. }
  256. });
  257. waitForServer(resolve, reject);
  258. });
  259. }
  260. function waitForServer(resolve, reject, retries = 30) {
  261. if (retries === 0) {
  262. reject(new Error('Server failed to start within timeout'));
  263. return;
  264. }
  265. const req = http.get(`http://localhost:${PORT}`, (res) => {
  266. console.log('Server is ready');
  267. resolve();
  268. });
  269. req.on('error', () => {
  270. setTimeout(() => waitForServer(resolve, reject, retries - 1), 1000);
  271. });
  272. req.end();
  273. }
  274. function createWindow() {
  275. mainWindow = new BrowserWindow({
  276. width: 1400,
  277. height: 900,
  278. webPreferences: {
  279. preload: path.join(__dirname, 'preload.js'),
  280. nodeIntegration: false,
  281. contextIsolation: true
  282. },
  283. title: 'New API',
  284. icon: path.join(__dirname, 'icon.png')
  285. });
  286. mainWindow.loadURL(`http://localhost:${PORT}`);
  287. if (process.env.NODE_ENV === 'development') {
  288. mainWindow.webContents.openDevTools();
  289. }
  290. // Close to tray instead of quitting
  291. mainWindow.on('close', (event) => {
  292. if (!app.isQuitting) {
  293. event.preventDefault();
  294. mainWindow.hide();
  295. if (process.platform === 'darwin') {
  296. app.dock.hide();
  297. }
  298. }
  299. });
  300. mainWindow.on('closed', () => {
  301. mainWindow = null;
  302. });
  303. }
  304. function createTray() {
  305. // Use template icon for macOS (black with transparency, auto-adapts to theme)
  306. // Use colored icon for Windows
  307. const trayIconPath = process.platform === 'darwin'
  308. ? path.join(__dirname, 'tray-iconTemplate.png')
  309. : path.join(__dirname, 'tray-icon-windows.png');
  310. tray = new Tray(trayIconPath);
  311. const contextMenu = Menu.buildFromTemplate([
  312. {
  313. label: 'Show New API',
  314. click: () => {
  315. if (mainWindow === null) {
  316. createWindow();
  317. } else {
  318. mainWindow.show();
  319. if (process.platform === 'darwin') {
  320. app.dock.show();
  321. }
  322. }
  323. }
  324. },
  325. { type: 'separator' },
  326. {
  327. label: 'Quit',
  328. click: () => {
  329. app.isQuitting = true;
  330. app.quit();
  331. }
  332. }
  333. ]);
  334. tray.setToolTip('New API');
  335. tray.setContextMenu(contextMenu);
  336. // On macOS, clicking the tray icon shows the window
  337. tray.on('click', () => {
  338. if (mainWindow === null) {
  339. createWindow();
  340. } else {
  341. mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show();
  342. if (mainWindow.isVisible() && process.platform === 'darwin') {
  343. app.dock.show();
  344. }
  345. }
  346. });
  347. }
  348. app.whenReady().then(async () => {
  349. try {
  350. await startServer();
  351. createTray();
  352. createWindow();
  353. } catch (err) {
  354. console.error('Failed to start application:', err);
  355. // 分析启动失败的错误
  356. const knownError = analyzeError(serverErrorLogs);
  357. if (knownError) {
  358. dialog.showMessageBox({
  359. type: 'error',
  360. title: knownError.title,
  361. message: `启动失败: ${knownError.message}`,
  362. detail: `${knownError.solution}\n\n━━━━━━━━━━━━━━━━━━━━━━\n\n错误信息: ${err.message}\n\n错误类型: ${knownError.type}`,
  363. buttons: ['退出', '查看完整日志'],
  364. defaultId: 0,
  365. cancelId: 0
  366. }).then((result) => {
  367. if (result.response === 1) {
  368. // 用户选择查看日志
  369. const logPath = saveAndOpenErrorLog();
  370. const confirmMessage = logPath
  371. ? `日志已保存到:\n${logPath}\n\n日志文件已在默认文本编辑器中打开。\n\n点击"退出"关闭应用程序。`
  372. : '日志保存失败,但已在控制台输出。\n\n点击"退出"关闭应用程序。';
  373. dialog.showMessageBox({
  374. type: 'info',
  375. title: '日志已保存',
  376. message: confirmMessage,
  377. buttons: ['退出'],
  378. defaultId: 0
  379. }).then(() => {
  380. app.quit();
  381. });
  382. console.log('=== 完整错误日志 ===');
  383. console.log(serverErrorLogs.join('\n'));
  384. } else {
  385. app.quit();
  386. }
  387. });
  388. } else {
  389. dialog.showMessageBox({
  390. type: 'error',
  391. title: '启动失败',
  392. message: '无法启动服务器',
  393. detail: `错误信息: ${err.message}\n\n请检查日志获取更多信息。`,
  394. buttons: ['退出', '查看完整日志'],
  395. defaultId: 0,
  396. cancelId: 0
  397. }).then((result) => {
  398. if (result.response === 1) {
  399. // 用户选择查看日志
  400. const logPath = saveAndOpenErrorLog();
  401. const confirmMessage = logPath
  402. ? `日志已保存到:\n${logPath}\n\n日志文件已在默认文本编辑器中打开。\n\n点击"退出"关闭应用程序。`
  403. : '日志保存失败,但已在控制台输出。\n\n点击"退出"关闭应用程序。';
  404. dialog.showMessageBox({
  405. type: 'info',
  406. title: '日志已保存',
  407. message: confirmMessage,
  408. buttons: ['退出'],
  409. defaultId: 0
  410. }).then(() => {
  411. app.quit();
  412. });
  413. console.log('=== 完整错误日志 ===');
  414. console.log(serverErrorLogs.join('\n'));
  415. } else {
  416. app.quit();
  417. }
  418. });
  419. }
  420. }
  421. });
  422. app.on('window-all-closed', () => {
  423. // Don't quit when window is closed, keep running in tray
  424. // Only quit when explicitly choosing Quit from tray menu
  425. });
  426. app.on('activate', () => {
  427. if (BrowserWindow.getAllWindows().length === 0) {
  428. createWindow();
  429. }
  430. });
  431. app.on('before-quit', (event) => {
  432. if (serverProcess) {
  433. event.preventDefault();
  434. console.log('Shutting down server...');
  435. serverProcess.kill('SIGTERM');
  436. setTimeout(() => {
  437. if (serverProcess) {
  438. serverProcess.kill('SIGKILL');
  439. }
  440. app.exit();
  441. }, 5000);
  442. serverProcess.on('close', () => {
  443. serverProcess = null;
  444. app.exit();
  445. });
  446. }
  447. });