main.js 19 KB

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