main.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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. const userDataPath = app.getPath('userData');
  193. const dataDir = path.join(userDataPath, 'data');
  194. // 设置环境变量供 preload.js 使用
  195. process.env.ELECTRON_DATA_DIR = dataDir;
  196. if (isDev) {
  197. // 开发模式:假设开发者手动启动了 Go 后端和前端开发服务器
  198. // 只需要等待前端开发服务器就绪
  199. console.log('Development mode: skipping server startup');
  200. console.log('Please make sure you have started:');
  201. console.log(' 1. Go backend: go run main.go (port 3000)');
  202. console.log(' 2. Frontend dev server: cd web && bun dev (port 5173)');
  203. console.log('');
  204. console.log('Checking if servers are running...');
  205. // First check if both servers are accessible
  206. checkServerAvailability(DEV_FRONTEND_PORT)
  207. .then(() => {
  208. console.log('✓ Frontend dev server is accessible on port 5173');
  209. resolve();
  210. })
  211. .catch((err) => {
  212. console.error(`✗ Cannot connect to frontend dev server on port ${DEV_FRONTEND_PORT}`);
  213. console.error('Please make sure the frontend dev server is running:');
  214. console.error(' cd web && bun dev');
  215. reject(err);
  216. });
  217. return;
  218. }
  219. // 生产模式:启动二进制服务器
  220. const env = { ...process.env, PORT: PORT.toString() };
  221. if (!fs.existsSync(dataDir)) {
  222. fs.mkdirSync(dataDir, { recursive: true });
  223. }
  224. env.SQLITE_PATH = path.join(dataDir, 'new-api.db');
  225. console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
  226. console.log('📁 您的数据存储位置:');
  227. console.log(' ' + dataDir);
  228. console.log(' 💡 备份提示:复制此目录即可备份所有数据');
  229. console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
  230. const binaryPath = getBinaryPath();
  231. const workingDir = process.resourcesPath;
  232. console.log('Starting server from:', binaryPath);
  233. serverProcess = spawn(binaryPath, [], {
  234. env,
  235. cwd: workingDir
  236. });
  237. serverProcess.stdout.on('data', (data) => {
  238. console.log(`Server: ${data}`);
  239. });
  240. serverProcess.stderr.on('data', (data) => {
  241. const errorMsg = data.toString();
  242. console.error(`Server Error: ${errorMsg}`);
  243. serverErrorLogs.push(errorMsg);
  244. // 只保留最近的100条错误日志
  245. if (serverErrorLogs.length > 100) {
  246. serverErrorLogs.shift();
  247. }
  248. });
  249. serverProcess.on('error', (err) => {
  250. console.error('Failed to start server:', err);
  251. reject(err);
  252. });
  253. serverProcess.on('close', (code) => {
  254. console.log(`Server process exited with code ${code}`);
  255. // 如果退出代码不是0,说明服务器异常退出
  256. if (code !== 0 && code !== null) {
  257. const errorDetails = serverErrorLogs.length > 0
  258. ? serverErrorLogs.slice(-20).join('\n')
  259. : '没有捕获到错误日志';
  260. // 分析错误类型
  261. const knownError = analyzeError(serverErrorLogs);
  262. let dialogOptions;
  263. if (knownError) {
  264. // 识别到已知错误,显示友好的错误信息和解决方案
  265. dialogOptions = {
  266. type: 'error',
  267. title: knownError.title,
  268. message: knownError.message,
  269. detail: `${knownError.solution}\n\n━━━━━━━━━━━━━━━━━━━━━━\n\n退出代码: ${code}\n\n错误类型: ${knownError.type}\n\n最近的错误日志:\n${errorDetails}`,
  270. buttons: ['退出应用', '查看完整日志'],
  271. defaultId: 0,
  272. cancelId: 0
  273. };
  274. } else {
  275. // 未识别的错误,显示通用错误信息
  276. dialogOptions = {
  277. type: 'error',
  278. title: '服务器崩溃',
  279. message: '服务器进程异常退出',
  280. detail: `退出代码: ${code}\n\n最近的错误信息:\n${errorDetails}`,
  281. buttons: ['退出应用', '查看完整日志'],
  282. defaultId: 0,
  283. cancelId: 0
  284. };
  285. }
  286. dialog.showMessageBox(dialogOptions).then((result) => {
  287. if (result.response === 1) {
  288. // 用户选择查看详情,保存并打开日志文件
  289. const logPath = saveAndOpenErrorLog();
  290. // 显示确认对话框
  291. const confirmMessage = logPath
  292. ? `日志已保存到:\n${logPath}\n\n日志文件已在默认文本编辑器中打开。\n\n点击"退出"关闭应用程序。`
  293. : '日志保存失败,但已在控制台输出。\n\n点击"退出"关闭应用程序。';
  294. dialog.showMessageBox({
  295. type: 'info',
  296. title: '日志已保存',
  297. message: confirmMessage,
  298. buttons: ['退出'],
  299. defaultId: 0
  300. }).then(() => {
  301. app.isQuitting = true;
  302. app.quit();
  303. });
  304. // 同时在控制台输出
  305. console.log('=== 完整错误日志 ===');
  306. console.log(serverErrorLogs.join('\n'));
  307. } else {
  308. // 用户选择直接退出
  309. app.isQuitting = true;
  310. app.quit();
  311. }
  312. });
  313. } else {
  314. // 正常退出(code为0或null),直接关闭窗口
  315. if (mainWindow && !mainWindow.isDestroyed()) {
  316. mainWindow.close();
  317. }
  318. }
  319. });
  320. checkServerAvailability(PORT)
  321. .then(() => {
  322. console.log('✓ Backend server is accessible on port 3000');
  323. resolve();
  324. })
  325. .catch((err) => {
  326. console.error('✗ Failed to connect to backend server');
  327. reject(err);
  328. });
  329. });
  330. }
  331. function createWindow() {
  332. const isDev = process.env.NODE_ENV === 'development';
  333. const loadPort = isDev ? DEV_FRONTEND_PORT : PORT;
  334. mainWindow = new BrowserWindow({
  335. width: 1080,
  336. height: 720,
  337. webPreferences: {
  338. preload: path.join(__dirname, 'preload.js'),
  339. nodeIntegration: false,
  340. contextIsolation: true
  341. },
  342. title: 'New API',
  343. icon: path.join(__dirname, 'icon.png')
  344. });
  345. mainWindow.loadURL(`http://127.0.0.1:${loadPort}`);
  346. console.log(`Loading from: http://127.0.0.1:${loadPort}`);
  347. if (isDev) {
  348. mainWindow.webContents.openDevTools();
  349. }
  350. // Close to tray instead of quitting
  351. mainWindow.on('close', (event) => {
  352. if (!app.isQuitting) {
  353. event.preventDefault();
  354. mainWindow.hide();
  355. if (process.platform === 'darwin') {
  356. app.dock.hide();
  357. }
  358. }
  359. });
  360. mainWindow.on('closed', () => {
  361. mainWindow = null;
  362. });
  363. }
  364. function createTray() {
  365. // Use template icon for macOS (black with transparency, auto-adapts to theme)
  366. // Use colored icon for Windows
  367. const trayIconPath = process.platform === 'darwin'
  368. ? path.join(__dirname, 'tray-iconTemplate.png')
  369. : path.join(__dirname, 'tray-icon-windows.png');
  370. tray = new Tray(trayIconPath);
  371. const contextMenu = Menu.buildFromTemplate([
  372. {
  373. label: 'Show New API',
  374. click: () => {
  375. if (mainWindow === null) {
  376. createWindow();
  377. } else {
  378. mainWindow.show();
  379. if (process.platform === 'darwin') {
  380. app.dock.show();
  381. }
  382. }
  383. }
  384. },
  385. { type: 'separator' },
  386. {
  387. label: 'Quit',
  388. click: () => {
  389. app.isQuitting = true;
  390. app.quit();
  391. }
  392. }
  393. ]);
  394. tray.setToolTip('New API');
  395. tray.setContextMenu(contextMenu);
  396. // On macOS, clicking the tray icon shows the window
  397. tray.on('click', () => {
  398. if (mainWindow === null) {
  399. createWindow();
  400. } else {
  401. mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show();
  402. if (mainWindow.isVisible() && process.platform === 'darwin') {
  403. app.dock.show();
  404. }
  405. }
  406. });
  407. }
  408. app.whenReady().then(async () => {
  409. try {
  410. await startServer();
  411. createTray();
  412. createWindow();
  413. } catch (err) {
  414. console.error('Failed to start application:', err);
  415. // 分析启动失败的错误
  416. const knownError = analyzeError(serverErrorLogs);
  417. if (knownError) {
  418. dialog.showMessageBox({
  419. type: 'error',
  420. title: knownError.title,
  421. message: `启动失败: ${knownError.message}`,
  422. detail: `${knownError.solution}\n\n━━━━━━━━━━━━━━━━━━━━━━\n\n错误信息: ${err.message}\n\n错误类型: ${knownError.type}`,
  423. buttons: ['退出', '查看完整日志'],
  424. defaultId: 0,
  425. cancelId: 0
  426. }).then((result) => {
  427. if (result.response === 1) {
  428. // 用户选择查看日志
  429. const logPath = saveAndOpenErrorLog();
  430. const confirmMessage = logPath
  431. ? `日志已保存到:\n${logPath}\n\n日志文件已在默认文本编辑器中打开。\n\n点击"退出"关闭应用程序。`
  432. : '日志保存失败,但已在控制台输出。\n\n点击"退出"关闭应用程序。';
  433. dialog.showMessageBox({
  434. type: 'info',
  435. title: '日志已保存',
  436. message: confirmMessage,
  437. buttons: ['退出'],
  438. defaultId: 0
  439. }).then(() => {
  440. app.quit();
  441. });
  442. console.log('=== 完整错误日志 ===');
  443. console.log(serverErrorLogs.join('\n'));
  444. } else {
  445. app.quit();
  446. }
  447. });
  448. } else {
  449. dialog.showMessageBox({
  450. type: 'error',
  451. title: '启动失败',
  452. message: '无法启动服务器',
  453. detail: `错误信息: ${err.message}\n\n请检查日志获取更多信息。`,
  454. buttons: ['退出', '查看完整日志'],
  455. defaultId: 0,
  456. cancelId: 0
  457. }).then((result) => {
  458. if (result.response === 1) {
  459. // 用户选择查看日志
  460. const logPath = saveAndOpenErrorLog();
  461. const confirmMessage = logPath
  462. ? `日志已保存到:\n${logPath}\n\n日志文件已在默认文本编辑器中打开。\n\n点击"退出"关闭应用程序。`
  463. : '日志保存失败,但已在控制台输出。\n\n点击"退出"关闭应用程序。';
  464. dialog.showMessageBox({
  465. type: 'info',
  466. title: '日志已保存',
  467. message: confirmMessage,
  468. buttons: ['退出'],
  469. defaultId: 0
  470. }).then(() => {
  471. app.quit();
  472. });
  473. console.log('=== 完整错误日志 ===');
  474. console.log(serverErrorLogs.join('\n'));
  475. } else {
  476. app.quit();
  477. }
  478. });
  479. }
  480. }
  481. });
  482. app.on('window-all-closed', () => {
  483. // Don't quit when window is closed, keep running in tray
  484. // Only quit when explicitly choosing Quit from tray menu
  485. });
  486. app.on('activate', () => {
  487. if (BrowserWindow.getAllWindows().length === 0) {
  488. createWindow();
  489. }
  490. });
  491. app.on('before-quit', (event) => {
  492. if (serverProcess) {
  493. event.preventDefault();
  494. console.log('Shutting down server...');
  495. serverProcess.kill('SIGTERM');
  496. setTimeout(() => {
  497. if (serverProcess) {
  498. serverProcess.kill('SIGKILL');
  499. }
  500. app.exit();
  501. }, 5000);
  502. serverProcess.on('close', () => {
  503. serverProcess = null;
  504. app.exit();
  505. });
  506. }
  507. });