-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.js
More file actions
298 lines (246 loc) · 8.94 KB
/
main.js
File metadata and controls
298 lines (246 loc) · 8.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
const { app, BrowserWindow, BrowserView, ipcMain, shell, Notification, Menu, dialog, net } = require('electron');
const path = require('path');
const fs = require('fs');
const pkg = require('./package.json');
const CONSTANTS = require('./src/constants');
const APP_VERSION = pkg.version;
let mainWindow;
let browserView;
let stopRequested = false;
function sendLog(msg, type = '') {
if (!mainWindow || mainWindow.isDestroyed()) return;
mainWindow.webContents.send('log', String(msg), type);
}
async function checkForUpdates() {
sendLog('[系統] 正在檢查更新...', 'info');
const fetchRelease = () => new Promise((resolve, reject) => {
const req = net.request({
method: 'GET',
url: CONSTANTS.URLS.GITHUB_API_LATEST,
headers: { 'User-Agent': 'TWSE-Auto-eVoting-App' },
});
req.on('response', (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => res.statusCode === 200 ? resolve(JSON.parse(data)) : reject(new Error(res.statusCode)));
});
req.on('error', reject);
req.end();
});
try {
const release = await fetchRelease();
const latestVersion = release.tag_name.replace('v', '');
if (!isNewerVersion(latestVersion, APP_VERSION)) {
sendLog(`[系統] 目前已是最新版本 v${APP_VERSION}`, 'info');
return;
}
sendLog(`[更新] 發現新版本 v${latestVersion}`, 'info');
const { response } = await dialog.showMessageBox(mainWindow, {
type: 'info',
title: '發現新版本',
message: `偵測到新版本 v${latestVersion}`,
detail: `建議前往 GitHub 下載最新版本 v${latestVersion} 以確保功能正常。\n目前版本: v${APP_VERSION}`,
buttons: ['前往下載', '稍後'],
defaultId: 0,
cancelId: 1,
});
if (response !== 0) return;
shell.openExternal(`${CONSTANTS.URLS.GITHUB_REPO}/releases/latest`);
} catch (err) {
sendLog(`[系統] 檢查更新失敗: ${err.message}`, 'error');
}
}
function isNewerVersion(latest, current) {
const l = latest.split('.').map(Number);
const c = current.split('.').map(Number);
for (let i = 0; i < 3; i++) {
if (l[i] > (c[i] || 0)) return true;
if (l[i] < (c[i] || 0)) return false;
}
return false;
}
// Mask Electron User-Agent
app.userAgentFallback = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36";
app.setAppUserModelId('股東會投票幫手');
function getConfig() {
const CONFIG_PATH = path.join(app.getPath('userData'), 'config.json');
const defaultConfig = { outputDir: '', ids: '', folderStructure: 'by_id', filenamePattern: '{id}_{code}' };
if (!fs.existsSync(CONFIG_PATH)) return defaultConfig;
try {
const data = fs.readFileSync(CONFIG_PATH, 'utf8');
const config = JSON.parse(data);
if (!config) return defaultConfig;
// Migrate old includeCompanyName if exists
if (config.filenamePattern === undefined && config.includeCompanyName !== undefined) {
config.filenamePattern = config.includeCompanyName ? '{id}_{code}_{name}' : '{id}_{code}';
delete config.includeCompanyName;
}
return { ...defaultConfig, ...config };
} catch (e) {
console.error('Failed to read config:', e);
return defaultConfig;
}
}
function saveConfig(config) {
const CONFIG_PATH = path.join(app.getPath('userData'), 'config.json');
try {
fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));
return true;
} catch (e) {
console.error('Failed to save config:', e);
return false;
}
}
const handleDevToolsShortcut = (targetWebContents) => (event, input) => {
if (input.type !== 'keyDown') return;
const isF12 = input.key === 'F12';
const isCtrlShiftI = input.key.toLowerCase() === 'i' && (input.control || input.meta) && input.shift;
if (isF12 || isCtrlShiftI) {
targetWebContents.toggleDevTools();
event.preventDefault();
}
};
function createBrowserView() {
if (!mainWindow || mainWindow.isDestroyed()) return;
browserView = new BrowserView({
webPreferences: { nodeIntegration: false, contextIsolation: true },
});
mainWindow.setBrowserView(browserView);
const updateBounds = () => {
if (!mainWindow || mainWindow.isDestroyed()) return;
const { width, height } = mainWindow.getContentBounds();
browserView.setBounds({ x: 450, y: 0, width: width - 450, height: height });
};
updateBounds();
mainWindow.on('resize', updateBounds);
browserView.webContents.on('before-input-event', handleDevToolsShortcut(browserView.webContents));
browserView.webContents.on('dom-ready', () => {
browserView.webContents.insertCSS('::-webkit-scrollbar { display: none; }');
});
browserView.webContents.loadURL(CONSTANTS.URLS.LOGIN);
}
function createWindow() {
mainWindow = new BrowserWindow({
width: 1000,
height: 850,
minWidth: 900,
minHeight: 850,
resizable: false,
show: true,
backgroundColor: '#1a1a2e',
paintWhenInitiallyHidden: false,
icon: path.join(__dirname, 'assets/icons/icon.png'),
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
spellcheck: false,
},
title: '股東會投票幫手',
});
mainWindow.loadFile(path.join(__dirname, 'src/renderer/index.html'));
mainWindow.webContents.on('before-input-event', handleDevToolsShortcut(mainWindow.webContents));
mainWindow.webContents.on('did-finish-load', () => {
checkForUpdates();
});
setTimeout(createBrowserView, 400);
app.on('select-client-certificate', (event, webContents, url, list, callback) => {
event.preventDefault();
if (list && list.length > 0) callback(list[0]);
});
}
app.whenReady().then(() => {
createWindow();
Menu.setApplicationMenu(null);
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
ipcMain.handle('get-app-version', () => APP_VERSION);
ipcMain.handle('start-voting', async (event, params) => {
const { ids, outputDir, folderStructure, filenamePattern } = params;
stopRequested = false;
const automation = require('./src/automation/main_flow');
const { calculateProgress } = require('./src/automation/utils');
let maxPercent = 0;
const sendProgress = (progress) => {
if (!mainWindow || mainWindow.isDestroyed()) return;
mainWindow.webContents.send('progress', JSON.parse(JSON.stringify(progress)));
const currentPercent = calculateProgress(progress);
if (currentPercent > maxPercent) {
maxPercent = currentPercent;
}
mainWindow.setTitle(`(${maxPercent}%) 股東會投票幫手`);
};
try {
const stats = await automation.run(
browserView.webContents,
ids,
sendLog,
sendProgress,
() => stopRequested,
outputDir,
folderStructure,
filenamePattern
);
if (!mainWindow || mainWindow.isDestroyed()) return { success: true };
mainWindow.setTitle('股東會投票幫手');
const msg = `累計投票: ${stats.voted},累計截圖: ${stats.screenshoted}`;
sendLog(`[系統] 完成。${msg}`);
if (!mainWindow.isFocused() && Notification.isSupported()) {
new Notification({
title: '投票完成',
body: msg,
icon: path.join(__dirname, 'assets/icons/icon.png'),
}).show();
}
return { success: true };
} catch (error) {
if (!mainWindow || mainWindow.isDestroyed()) return { success: false, error: error.message };
mainWindow.setTitle('股東會投票幫手');
if (!mainWindow.isFocused() && Notification.isSupported()) {
new Notification({
title: '投票錯誤',
body: error.message,
icon: path.join(__dirname, 'assets/icons/icon.png'),
}).show();
}
return { success: false, error: error.message };
}
});
ipcMain.handle('select-directory', async () => {
const result = await dialog.showOpenDialog(mainWindow, { properties: ['openDirectory'] });
return result.canceled ? null : result.filePaths[0];
});
ipcMain.handle('get-config', async () => getConfig());
ipcMain.handle('save-config', async (event, config) => saveConfig(config));
ipcMain.handle('open-about', async () => {
const aboutWindow = new BrowserWindow({
width: 400,
height: 450,
resizable: false,
autoHideMenuBar: true,
title: '關於股東會投票幫手',
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
},
});
aboutWindow.loadFile(path.join(__dirname, 'src/renderer/about.html'));
return { success: true };
});
ipcMain.handle('open-external', async (event, url) => {
await shell.openExternal(url);
return { success: true };
});
ipcMain.handle('stop-voting', () => {
stopRequested = true;
if (browserView && browserView.webContents && !browserView.webContents.isDestroyed()) {
browserView.webContents.stop();
}
return { success: true };
});