mirror of
https://github.com/margrop/wrong-notebook.git
synced 2026-12-05 11:09:49 +08:00
342 lines
13 KiB
JavaScript
342 lines
13 KiB
JavaScript
/**
|
||
* 错题本桌面壳(Electron)
|
||
*
|
||
* - 启动时用 Electron 自带的 Node(ELECTRON_RUN_AS_NODE)运行 resources/server/launcher.js,
|
||
* 服务只监听 127.0.0.1,端口被占用时自动顺延
|
||
* - 数据目录为系统的应用数据目录(userData/data),卸载或升级不会删除
|
||
* - 全新安装还没有管理员时,直接打开一次性初始化链接设置管理员账号
|
||
* - 外部链接用系统浏览器打开;退出时结束服务进程
|
||
*/
|
||
const { app, BrowserWindow, Menu, shell, dialog, session } = require('electron');
|
||
const fs = require('node:fs');
|
||
const net = require('node:net');
|
||
const path = require('node:path');
|
||
const { spawn, spawnSync } = require('node:child_process');
|
||
const { isSameOrigin, isSafeExternalUrl } = require('./url-policy');
|
||
const { cleanServerEnv, isAllowedPermission, isIgnorableLoadFailure } = require('./runtime-policy');
|
||
|
||
// 系统全局代理或代理软件残留配置会劫持回环地址,导致内置服务窗口白屏或 502;固定直连本机
|
||
app.commandLine.appendSwitch('proxy-bypass-list', '127.0.0.1;localhost;<local>');
|
||
|
||
const PREFERRED_PORT = 39300;
|
||
const HOST = '127.0.0.1';
|
||
|
||
const serverRoot = app.isPackaged
|
||
? path.join(process.resourcesPath, 'server')
|
||
: path.join(__dirname, 'server');
|
||
|
||
let win = null;
|
||
let server = null;
|
||
let baseUrl = '';
|
||
let dataDir = '';
|
||
let quitting = false;
|
||
/** spawn 失败(ENOENT/EACCES 等)时记录,让 waitForHealthy 立即报错而不是等满 180 秒 */
|
||
let serverError = null;
|
||
/** 退出流程正在等待服务进程结束;再次 before-quit 时只阻止退出,不重复启动等待 */
|
||
let shutdownPromise = null;
|
||
let exitConfirmed = false;
|
||
|
||
function findFreePort(port, attempts = 50) {
|
||
return new Promise((resolve, reject) => {
|
||
const probe = net.createServer();
|
||
probe.unref();
|
||
probe.once('error', () => {
|
||
if (attempts <= 1) reject(new Error('没有可用端口'));
|
||
else resolve(findFreePort(port + 1, attempts - 1));
|
||
});
|
||
probe.listen(port, HOST, () => probe.close(() => resolve(port)));
|
||
});
|
||
}
|
||
|
||
async function waitForHealthy(url, timeoutMs) {
|
||
const deadline = Date.now() + timeoutMs;
|
||
while (Date.now() < deadline) {
|
||
if (serverError) throw new Error(`服务进程启动失败:${serverError.message}`);
|
||
if (!server || server.exitCode !== null) throw new Error('服务进程已退出');
|
||
try {
|
||
const res = await fetch(`${url}/api/health`);
|
||
if (res.ok) return;
|
||
} catch {
|
||
// 服务尚未监听
|
||
}
|
||
await new Promise((r) => setTimeout(r, 500));
|
||
}
|
||
throw new Error('等待服务启动超时');
|
||
}
|
||
|
||
async function startServer() {
|
||
dataDir = path.join(app.getPath('userData'), 'data');
|
||
const logDir = path.join(dataDir, 'logs');
|
||
fs.mkdirSync(logDir, { recursive: true });
|
||
const logFile = path.join(logDir, 'server.log');
|
||
const log = fs.createWriteStream(logFile, { flags: 'a' });
|
||
log.write(`\n===== ${new Date().toISOString()} v${app.getVersion()} =====\n`);
|
||
|
||
const port = await findFreePort(PREFERRED_PORT);
|
||
baseUrl = `http://${HOST}:${port}`;
|
||
server = spawn(nodeExecutable(), [
|
||
path.join(serverRoot, 'launcher.js'),
|
||
'--port', String(port),
|
||
'--host', HOST,
|
||
'--data-dir', dataDir,
|
||
], {
|
||
cwd: serverRoot,
|
||
env: {
|
||
...cleanServerEnv(process.env),
|
||
ELECTRON_RUN_AS_NODE: '1',
|
||
NEXTAUTH_URL: baseUrl,
|
||
WN_PLATFORM: 'desktop',
|
||
},
|
||
stdio: ['ignore', 'pipe', 'pipe'],
|
||
windowsHide: true,
|
||
});
|
||
server.stdout.pipe(log);
|
||
server.stderr.pipe(log);
|
||
server.on('error', (error) => {
|
||
serverError = error;
|
||
log.write(`[desktop] 服务进程启动失败:${error.message}\n`);
|
||
});
|
||
server.on('exit', (code) => {
|
||
log.write(`[desktop] 服务进程退出,退出码 ${code}\n`);
|
||
if (!quitting) {
|
||
dialog.showErrorBox('小马错题本服务已停止', `服务进程意外退出(退出码 ${code})。\n日志:${logFile}`);
|
||
app.quit();
|
||
}
|
||
});
|
||
|
||
try {
|
||
await waitForHealthy(baseUrl, 180_000);
|
||
} catch (error) {
|
||
throw new Error(`${error.message}\n日志:${logFile}`);
|
||
}
|
||
}
|
||
|
||
/** macOS 上用主程序跑 Node 会在程序坞多出一个图标,改用不显示图标的 Helper 程序 */
|
||
function nodeExecutable() {
|
||
if (process.platform !== 'darwin' || !app.isPackaged) return process.execPath;
|
||
const name = `${path.basename(process.execPath)} Helper`;
|
||
const helper = path.join(path.dirname(process.execPath), '..', 'Frameworks', `${name}.app`, 'Contents', 'MacOS', name);
|
||
return fs.existsSync(helper) ? helper : process.execPath;
|
||
}
|
||
|
||
/**
|
||
* 启动后打开的地址:服务端在全新安装(还没有管理员)时把一次性初始化令牌写到配置目录,
|
||
* 有令牌就直接打开初始化页;创建管理员后令牌被删除,之后打开首页
|
||
*/
|
||
function startUrl() {
|
||
let token = '';
|
||
try {
|
||
token = fs.readFileSync(path.join(dataDir, 'config', 'setup-token'), 'utf8').trim();
|
||
} catch {
|
||
// 没有令牌:已经创建过管理员
|
||
}
|
||
return /^[\w-]{16,128}$/.test(token) ? `${baseUrl}/initialize?token=${token}` : baseUrl;
|
||
}
|
||
|
||
/**
|
||
* 结束服务进程并等待其退出:Windows 下 launcher 派生的 prisma/seed 子进程需要 taskkill /T /F 清理,
|
||
* 避免孤儿进程占用端口、锁住 SQLite WAL 或让升级/卸载报文件被占用。
|
||
*/
|
||
function shutdownServer(timeoutMs = 5000) {
|
||
if (!server || server.exitCode !== null || serverError) return Promise.resolve();
|
||
const child = server;
|
||
return new Promise((resolve) => {
|
||
let settled = false;
|
||
let forceTimer = null;
|
||
const finish = () => {
|
||
if (settled) return;
|
||
settled = true;
|
||
clearTimeout(forceTimer);
|
||
resolve();
|
||
};
|
||
child.once('exit', finish);
|
||
try {
|
||
child.kill();
|
||
} catch {
|
||
// 进程已退出
|
||
}
|
||
forceTimer = setTimeout(() => {
|
||
if (settled || child.exitCode !== null) return;
|
||
try {
|
||
if (process.platform === 'win32') {
|
||
spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true });
|
||
} else {
|
||
child.kill('SIGKILL');
|
||
}
|
||
} catch {
|
||
// 进程已不存在
|
||
}
|
||
// 强杀后再等最多 1 秒;仍未退出则放行主进程,避免永久挂起
|
||
setTimeout(finish, 1000);
|
||
}, timeoutMs);
|
||
});
|
||
}
|
||
|
||
const LOADING_HTML = `<!doctype html><meta charset="utf-8"><title>小马错题本</title>
|
||
<style>body{margin:0;height:100vh;display:flex;align-items:center;justify-content:center;
|
||
font-family:system-ui,sans-serif;color:#555;background:#fafafa}
|
||
@media(prefers-color-scheme:dark){body{background:#1f1f1f;color:#ccc}}</style>
|
||
<p>小马错题本正在启动,首次运行需要初始化数据库,请稍候…</p>`;
|
||
|
||
let recoveryPromptOpen = false;
|
||
|
||
/** 渲染进程崩溃或主帧加载失败时提示并可一键重载;同时只保留一个对话框 */
|
||
function offerReload(contents, title, detail) {
|
||
if (quitting || !contents || contents.isDestroyed() || recoveryPromptOpen) return;
|
||
recoveryPromptOpen = true;
|
||
const owner = BrowserWindow.fromWebContents(contents) || undefined;
|
||
const options = {
|
||
type: 'error',
|
||
title,
|
||
message: title,
|
||
detail,
|
||
buttons: ['重新加载', '退出'],
|
||
defaultId: 0,
|
||
cancelId: 1,
|
||
noLink: true,
|
||
};
|
||
const prompted = owner ? dialog.showMessageBox(owner, options) : dialog.showMessageBox(options);
|
||
prompted.then(({ response }) => {
|
||
recoveryPromptOpen = false;
|
||
if (response === 0 && !contents.isDestroyed()) contents.reload();
|
||
else app.quit();
|
||
}).catch(() => {
|
||
recoveryPromptOpen = false;
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 主窗口与站内新窗口共用的导航处理:外链交给系统浏览器,右键菜单提供复制/粘贴/打开链接。
|
||
* 站内子窗口同样注册,避免打印预览等窗口直接导航到外网。
|
||
*/
|
||
function attachNavigationHandlers(contents) {
|
||
contents.setWindowOpenHandler(({ url }) => {
|
||
if (isSameOrigin(url, baseUrl)) {
|
||
return {
|
||
action: 'allow',
|
||
overrideBrowserWindowOptions: {
|
||
autoHideMenuBar: true,
|
||
webPreferences: { contextIsolation: true, sandbox: true },
|
||
},
|
||
};
|
||
}
|
||
if (isSafeExternalUrl(url)) shell.openExternal(url);
|
||
return { action: 'deny' };
|
||
});
|
||
contents.on('will-navigate', (event, url) => {
|
||
// data: 只用于服务就绪前的加载过渡页;启动地址确定后不再放行
|
||
if (isSameOrigin(url, baseUrl) || (!baseUrl && url.startsWith('data:'))) return;
|
||
event.preventDefault();
|
||
if (isSafeExternalUrl(url)) shell.openExternal(url);
|
||
});
|
||
contents.on('did-create-window', (child) => {
|
||
if (child && child.webContents) attachNavigationHandlers(child.webContents);
|
||
});
|
||
contents.on('render-process-gone', (event, details) => {
|
||
if (quitting || (details && details.reason === 'clean-exit')) return;
|
||
const reason = (details && details.reason) || 'unknown';
|
||
offerReload(contents, '页面进程异常退出', `渲染进程已退出(${reason}),可重新加载页面。`);
|
||
});
|
||
contents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => {
|
||
if (!isMainFrame || quitting || isIgnorableLoadFailure(errorCode)) return;
|
||
offerReload(
|
||
contents,
|
||
'页面加载失败',
|
||
`${errorDescription || '加载失败'}(${errorCode})\n${validatedURL || ''}`,
|
||
);
|
||
});
|
||
contents.on('context-menu', (event, params) => {
|
||
const template = [];
|
||
if (params.selectionText) template.push({ role: 'copy', label: '复制' });
|
||
if (params.isEditable) {
|
||
template.push({ role: 'cut', label: '剪切' }, { role: 'paste', label: '粘贴' });
|
||
}
|
||
template.push({ role: 'selectAll', label: '全选' });
|
||
if (params.linkURL && isSafeExternalUrl(params.linkURL)) {
|
||
template.push({ type: 'separator' }, {
|
||
label: '在浏览器中打开',
|
||
click: () => shell.openExternal(params.linkURL),
|
||
});
|
||
}
|
||
Menu.buildFromTemplate(template).popup({ window: BrowserWindow.fromWebContents(contents) || undefined });
|
||
});
|
||
}
|
||
|
||
/** 渲染进程默认自动批准所有权限请求;这里只放行同源页面的剪贴板与音视频 */
|
||
function configureSession() {
|
||
session.defaultSession.setPermissionRequestHandler((contents, permission, callback, details) => {
|
||
const url = (details && details.requestingUrl) || (contents && contents.getURL()) || '';
|
||
callback(isAllowedPermission(url, baseUrl, permission));
|
||
});
|
||
}
|
||
|
||
function createWindow() {
|
||
win = new BrowserWindow({
|
||
width: 1280,
|
||
height: 860,
|
||
minWidth: 360,
|
||
minHeight: 560,
|
||
title: '小马错题本',
|
||
icon: path.join(__dirname, 'icon.png'),
|
||
autoHideMenuBar: true,
|
||
show: false,
|
||
webPreferences: { contextIsolation: true, sandbox: true },
|
||
});
|
||
win.once('ready-to-show', () => win.show());
|
||
win.on('closed', () => { win = null; });
|
||
attachNavigationHandlers(win.webContents);
|
||
// 服务已就绪时统一走 startUrl:全新安装期间关窗再重开仍进入一次性初始化页
|
||
if (baseUrl) win.loadURL(startUrl());
|
||
else win.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(LOADING_HTML)}`);
|
||
}
|
||
|
||
async function boot() {
|
||
// macOS 保留默认菜单以支持复制粘贴等快捷键;其他平台隐藏菜单栏
|
||
if (process.platform !== 'darwin') Menu.setApplicationMenu(null);
|
||
configureSession();
|
||
createWindow();
|
||
try {
|
||
await startServer();
|
||
} catch (error) {
|
||
// 启动期间用户已关闭窗口(window-all-closed 触发退出)时不再误弹启动失败
|
||
if (quitting) return;
|
||
dialog.showErrorBox('小马错题本启动失败', String(error.message || error));
|
||
quitting = true;
|
||
app.quit();
|
||
return;
|
||
}
|
||
if (win) win.loadURL(startUrl());
|
||
}
|
||
|
||
if (!app.requestSingleInstanceLock()) {
|
||
app.quit();
|
||
} else {
|
||
app.on('second-instance', () => {
|
||
// 冷启动瞬间连续启动时可能早于 app.whenReady,此时创建窗口会抛异常
|
||
if (!app.isReady()) return;
|
||
if (!win) createWindow();
|
||
else {
|
||
if (win.isMinimized()) win.restore();
|
||
win.focus();
|
||
}
|
||
});
|
||
app.whenReady().then(boot);
|
||
app.on('activate', () => {
|
||
if (!win && baseUrl) createWindow();
|
||
});
|
||
app.on('window-all-closed', () => {
|
||
if (process.platform !== 'darwin') app.quit();
|
||
});
|
||
app.on('before-quit', (event) => {
|
||
quitting = true;
|
||
// 服务已退出或已经确认过退出:放行
|
||
if (exitConfirmed || !server || server.exitCode !== null) return;
|
||
event.preventDefault();
|
||
if (shutdownPromise) return;
|
||
shutdownPromise = shutdownServer().then(() => {
|
||
exitConfirmed = true;
|
||
app.quit();
|
||
});
|
||
});
|
||
}
|