-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
264 lines (227 loc) · 8.63 KB
/
Copy pathmain.js
File metadata and controls
264 lines (227 loc) · 8.63 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
const { app, BrowserWindow, session, ipcMain, desktopCapturer, shell } = require('electron');
const { autoUpdater } = require('electron-updater');
const path = require('path');
const url = require('url');
let win;
let splash;
const imageToDataUrl = (image) => {
if (!image || image.isEmpty()) {
return null;
}
try {
return image.toDataURL();
} catch (error) {
console.error('[Electron main] Failed to convert nativeImage to data URL', error);
return null;
}
};
function registerDesktopCapturerHandler() {
ipcMain.handle('desktop-capturer-get-sources', async (_event, options = {}) => {
const {
types = ['screen', 'window'],
thumbnailSize = { width: 480, height: 270 },
fetchWindowIcons = true,
} = options ?? {};
try {
const sources = await desktopCapturer.getSources({
types,
thumbnailSize,
fetchWindowIcons,
});
return sources.map((source) => ({
id: source.id,
name: source.name,
type: source.id.startsWith('screen:') ? 'screen' : 'window',
displayId: source.display_id ?? null,
thumbnail: imageToDataUrl(source.thumbnail),
appIcon: imageToDataUrl(source.appIcon),
}));
} catch (error) {
console.error('[Electron main] Failed to fetch screen sources', error);
throw error;
}
});
}
function createSplashWindow() {
splash = new BrowserWindow({
width: 500,
height: 400,
transparent: true,
frame: false,
alwaysOnTop: true,
icon: path.join(__dirname, 'public/logo/logo-icon.svg'),
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
},
});
splash.loadFile(path.join(__dirname, 'splash.html'));
splash.setResizable(false);
// Для дебага (раскомментируй если нужно)
// splash.webContents.openDevTools();
}
function createWindow() {
win = new BrowserWindow({
width: 1200,
height: 800,
icon: path.join(__dirname, 'public/logo/logo-icon.svg'),
show: false, // Не показываем сразу, покажем после загрузки
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js'),
},
autoHideMenuBar: true, // Hide the menu bar
});
// Обработка внешних ссылок (target="_blank")
win.webContents.setWindowOpenHandler(({ url }) => {
if (url.startsWith('http:') || url.startsWith('https:')) {
shell.openExternal(url);
return { action: 'deny' };
}
return { action: 'allow' };
});
// Обработка навигации внутри окна
win.webContents.on('will-navigate', (event, navigationUrl) => {
// Разрешаем навигацию только по локальным путям или dev-server
const isDev = process.argv.includes('--dev');
const isLocal = isDev
? navigationUrl.startsWith('http://localhost:4200')
: navigationUrl.startsWith('file://');
if (!isLocal && (navigationUrl.startsWith('http:') || navigationUrl.startsWith('https:'))) {
event.preventDefault();
shell.openExternal(navigationUrl);
}
});
// Check if we are in development mode
const isDev = process.argv.includes('--dev');
if (isDev) {
win.loadURL('http://localhost:4200');
win.webContents.openDevTools();
} else {
// Path to the Angular build output
win.loadFile(path.join(__dirname, 'dist/frontend/browser/index.html'));
}
// Показываем основное окно когда оно готово
win.once('ready-to-show', () => {
setTimeout(() => {
if (splash && !splash.isDestroyed()) {
splash.close();
}
win.show();
}, 500);
});
win.on('closed', () => {
win = null;
});
// Check for updates
if (!isDev) {
autoUpdater.checkForUpdatesAndNotify();
}
}
// Настройка перехвата запросов для работы Cookies и CORS в Electron
function setupSessionInterceptors() {
const filter = {
urls: ['http://localhost:3000/*'] // URL вашего API
};
// 1. Подмена Origin для обхода CORS на бэкенде (backend ожидает localhost:4200 или пусто)
// Это нужно, так как файл с диска (file://) отправляет Origin: file://
session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
details.requestHeaders['Origin'] = 'http://localhost:4200';
// Добавляем секретный заголовок для защиты от CSRF
details.requestHeaders['X-App-Source'] = 'twine-client';
callback({ requestHeaders: details.requestHeaders });
});
// 2. Исправление Cookies (SameSite)
// Electron считает file:// и localhost разными сайтами, поэтому SameSite=Lax куки не отправляются.
// Мы принудительно меняем их на SameSite=None; Secure
session.defaultSession.webRequest.onHeadersReceived(filter, (details, callback) => {
if (details.responseHeaders) {
// Копируем заголовки, чтобы можно было изменять
const newHeaders = { ...details.responseHeaders };
// Обработка Set-Cookie
// Заголовки могут приходить в разном регистре (Set-Cookie или set-cookie)
const setCookieKey = Object.keys(newHeaders).find(k => k.toLowerCase() === 'set-cookie');
if (setCookieKey) {
newHeaders[setCookieKey] = newHeaders[setCookieKey].map(cookie => {
// Удаляем существующие атрибуты SameSite, чтобы не дублировать
let newCookie = cookie.replace(/; SameSite=Lax/gi, '');
newCookie = newCookie.replace(/; SameSite=Strict/gi, '');
newCookie = newCookie.replace(/; SameSite=None/gi, '');
newCookie = newCookie.replace(/; Secure/gi, ''); // Удаляем Secure чтобы добавить его гарантированно
// Добавляем нужные для Cross-Origin (Electron File -> Localhost)
// Localhost считается Secure контекстом, поэтому Secure флаг допустим даже на http
return newCookie + '; SameSite=None; Secure';
});
}
callback({ responseHeaders: newHeaders });
} else {
callback({ responseHeaders: details.responseHeaders });
}
});
}
app.on('ready', () => {
registerDesktopCapturerHandler();
setupSessionInterceptors();
createSplashWindow();
// Создаем основное окно после небольшой задержки
setTimeout(() => {
createWindow();
}, 1000);
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (win === null) {
createWindow();
}
});
// Auto-updater events
autoUpdater.on('checking-for-update', () => {
console.log('Checking for update...');
if (splash && !splash.isDestroyed()) {
splash.webContents.send('checking-for-update');
}
});
autoUpdater.on('update-available', (info) => {
console.log('Update available.');
if (splash && !splash.isDestroyed()) {
splash.webContents.send('update-available', info);
}
});
autoUpdater.on('update-not-available', (info) => {
console.log('Update not available.');
if (splash && !splash.isDestroyed()) {
splash.webContents.send('update-not-available', info);
}
});
autoUpdater.on('error', (err) => {
console.log('Error in auto-updater. ' + err);
if (splash && !splash.isDestroyed()) {
// Не показываем ошибку пользователю, просто продолжаем загрузку
// как будто обновлений нет
splash.webContents.send('update-not-available');
}
});
autoUpdater.on('download-progress', (progressObj) => {
let log_message = 'Download speed: ' + progressObj.bytesPerSecond;
log_message = log_message + ' - Downloaded ' + progressObj.percent + '%';
log_message = log_message + ' (' + progressObj.transferred + '/' + progressObj.total + ')';
console.log(log_message);
if (splash && !splash.isDestroyed()) {
splash.webContents.send('download-progress', progressObj);
}
});
autoUpdater.on('update-downloaded', (info) => {
console.log('Update downloaded');
if (splash && !splash.isDestroyed()) {
splash.webContents.send('update-downloaded', info);
}
// Устанавливаем обновление после небольшой задержки
setTimeout(() => {
autoUpdater.quitAndInstall();
}, 2000);
});