electron-vue-exam-single/electron/main.js

209 lines
5.2 KiB
JavaScript

// 确保所有导入都使用 ES 模块语法
import { app, BrowserWindow, ipcMain } from 'electron';
import path from 'path';
import { fileURLToPath } from 'url';
import { checkDatabaseInitialized, initializeDatabase } from './db/index.js';
// 导入配置项服务
import {
fetchAllConfigs,
fetchConfigById,
saveConfig,
removeConfig,
getSystemConfig,
updateSystemConfig,
increaseQuestionBandVersion,
initAuthIpc
} from './service/configService.js';
// 定义 __dirname 和 __filename
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// 确保在应用最开始处添加单实例锁检查
// 尝试获取单实例锁
const gotTheLock = app.requestSingleInstanceLock();
// 如果获取锁失败,说明已有实例在运行,直接退出
if (!gotTheLock) {
app.quit();
} else {
// 设置第二个实例启动时的处理
app.on('second-instance', (event, commandLine, workingDirectory) => {
// 当用户尝试启动第二个实例时,聚焦到已有的主窗口
const mainWindow = BrowserWindow.getAllWindows()[0];
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
});
}
function createWindow() {
const mainWindow = new BrowserWindow({
fullscreen: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true
}
})
if (process.env.NODE_ENV === 'development') {
mainWindow.loadURL('http://localhost:5173/')
mainWindow.webContents.openDevTools()
} else {
mainWindow.loadFile(path.join(__dirname, '../dist/index.html'))
}
}
// Initalize app
app.whenReady().then(() => {
setupApp()
createWindow()
setupIpcMain()
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
// Check database initialization status
async function setupApp() {
try {
console.log('应用启动 - 检查数据库初始化状态...');
// 使用全局变量防止重复初始化检查
if (global.dbInitCheck) {
console.log('数据库初始化检查已完成');
return;
}
global.dbInitCheck = true;
const isInitialized = await checkDatabaseInitialized();
console.log('数据库初始化状态:', isInitialized);
// 只检查状态,不自动初始化
} catch (error) {
console.error('数据库检查过程中出错:', error);
}
}
// Setup IPC communication
function setupIpcMain() {
// 数据库相关
ipcMain.handle('check-database-initialized', async () => {
try {
return await checkDatabaseInitialized();
} catch (error) {
console.error('Failed to check database initialization:', error);
return false;
}
});
ipcMain.handle('initialize-database', async () => {
try {
return await initializeDatabase();
} catch (error) {
console.error('Failed to initialize database:', error);
return false;
}
});
// 系统相关
ipcMain.handle('system-get-config', async () => {
try {
return await getSystemConfig();
} catch (error) {
console.error('Failed to get system config:', error);
return null;
}
});
ipcMain.handle('system-update-config', async (event, config) => {
try {
return await updateSystemConfig(config);
} catch (error) {
console.error('Failed to update system config:', error);
return false;
}
});
ipcMain.handle('system-increase-question-band-version', async () => {
try {
return await increaseQuestionBandVersion();
} catch (error) {
console.error('Failed to increase question band version:', error);
return false;
}
});
// 初始化认证相关IPC
initAuthIpc(ipcMain);
// 配置项管理相关IPC
ipcMain.handle('config-fetch-all', async () => {
try {
return await fetchAllConfigs();
} catch (error) {
console.error('Failed to fetch all configs:', error);
throw error;
}
});
ipcMain.handle('config-fetch-by-id', async (event, id) => {
try {
return await fetchConfigById(id);
} catch (error) {
console.error(`Failed to fetch config by id ${id}:`, error);
throw error;
}
});
ipcMain.handle('config-save', async (event, { key, value }) => {
try {
await saveConfig(key, value);
return true;
} catch (error) {
console.error(`Failed to save config ${key}:`, error);
throw error;
}
});
ipcMain.handle('config-delete', async (event, id) => {
try {
await removeConfig(id);
return true;
} catch (error) {
console.error(`Failed to delete config ${id}:`, error);
throw error;
}
});
}
// 确保在 app.whenReady() 中调用 setupIpcMain()
app.whenReady().then(() => {
setupApp()
createWindow()
setupIpcMain()
});
// 删除下面这段重复的代码
// app.whenReady().then(() => {
// setupApp()
// createWindow()
// setupIpcMain()
// });
// 在应用退出前关闭所有数据库连接
app.on('will-quit', () => {
console.log('应用即将退出...');
// closeAllConnections();
});