forked from crowbartools/Firebot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
383 lines (309 loc) · 12.7 KB
/
main.js
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
'use strict';
const path = require('path');
const url = require('url');
const logger = require('./lib/logwrapper');
logger.info("Starting Firebot...");
const electron = require('electron');
const {app, BrowserWindow, ipcMain, shell, dialog} = electron;
const windowStateKeeper = require('electron-window-state');
const GhReleases = require('electron-gh-releases');
const settings = require('./lib/common/settings-access').settings;
const dataAccess = require('./lib/common/data-access.js');
const backupManager = require("./lib/backupManager");
const apiServer = require('./api/apiServer.js');
const Effect = require('./lib/common/EffectType');
// These are defined globally for Custom Scripts.
// We will probably wnat to handle these differently but we shouldn't
// change anything until we are ready as changing this will break most scripts
global.EffectType = Effect.EffectType;
global.SCRIPTS_DIR = dataAccess.getPathInUserData('/user-settings/scripts/');
// uncaught exception - log the error
process.on('uncaughtException', logger.error); //eslint-disable-line no-console
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
// Interactive handler
let mixerConnect; //eslint-disable-line
// Handle Squirrel events for windows machines
if (process.platform === 'win32') {
let cp;
let updateDotExe;
let target;
let child;
switch (process.argv[1]) {
case '--squirrel-updated':
// cleanup from last instance
// use case-fallthrough to do normal installation
break;
case '--squirrel-install': //eslint-disable-line no-fallthrough
// Optional - do things such as:
// - Install desktop and start menu shortcuts
// - Add your .exe to the PATH
// - Write to the registry for things like file associations and explorer context menus
// Install shortcuts
cp = require('child_process');
updateDotExe = path.resolve(path.dirname(process.execPath), '..', 'update.exe');
target = path.basename(process.execPath);
child = cp.spawn(updateDotExe, ["--createShortcut", target], { detached: true });
child.on('close', app.quit);
return;
case '--squirrel-uninstall': {
// Undo anything you did in the --squirrel-install and --squirrel-updated handlers
//attempt to delete the user-settings folder
let rimraf = require('rimraf');
rimraf.sync(dataAccess.getPathInUserData("/user-settings"));
// Remove shortcuts
cp = require('child_process');
updateDotExe = path.resolve(path.dirname(process.execPath), '..', 'update.exe');
target = path.basename(process.execPath);
child = cp.spawn(updateDotExe, ["--removeShortcut", target], { detached: true });
child.on('close', app.quit);
return true;
}
case '--squirrel-obsolete':
// This is called on the outgoing version of your app before
// we update to the new version - it's the opposite of
// --squirrel-updated
app.quit();
return;
}
}
function createWindow () {
logger.info('Creating window...');
let mainWindowState = windowStateKeeper({
defaultWidth: 1285,
defaultHeight: 720
});
// Create the browser window.
mainWindow = new BrowserWindow({
x: mainWindowState.x,
y: mainWindowState.y,
width: mainWindowState.width,
height: mainWindowState.height,
minWidth: 300,
minHeight: 50,
icon: path.join(__dirname, './gui/images/logo.ico'),
show: false
});
// register listeners on the window, so we can update the state
// automatically (the listeners will be removed when the window is closed)
// and restore the maximized or full screen state
mainWindowState.manage(mainWindow);
// and load the index.html of the app.
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, './gui/app/index.html'),
protocol: 'file:',
slashes: true
}));
// wait for the main window's content to load, then show it
mainWindow.webContents.on('did-finish-load', () => {
// mainWindow.webContents.openDevTools();
mainWindow.show();
});
// Emitted when the window is closed.
mainWindow.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
global.renderWindow = null;
});
// Global var for main window.
global.renderWindow = mainWindow;
logger.on('logging', (transport, level, msg, meta) => {
if (renderWindow != null && renderWindow.isDestroyed() === false) {
renderWindow.webContents.send('logging', {
transport: transport,
level: level,
msg: msg,
meta: meta
});
}
});
let hotkeyManager = require('./lib/hotkeys/hotkey-manager');
hotkeyManager.refreshHotkeyCache();
}
async function createDefaultFoldersAndFiles() {
logger.info("Ensuring default folders and files exist...");
//create the root "firebot-data" folder in user-settings
dataAccess.createFirebotDataDir();
// Create the user-settings folder if it doesn't exist. It's required
// for the folders below that are within it
if (!dataAccess.userDataPathExistsSync("/user-settings/")) {
logger.info("Can't find the user-settings folder, creating one now...");
dataAccess.makeDirInUserDataSync("/user-settings");
}
if (!dataAccess.userDataPathExistsSync("/user-settings/hotkeys.json")) {
logger.info("Can't find the hotkeys file, creating the default one now...");
dataAccess.copyDefaultConfigToUserData("hotkeys.json", "/user-settings/");
}
// Create the scripts folder if it doesn't exist
if (!dataAccess.userDataPathExistsSync("/user-settings/scripts/")) {
logger.info("Can't find the scripts folder, creating one now...");
dataAccess.makeDirInUserDataSync("/user-settings/scripts");
}
// Create the backups folder if it doesn't exist
if (!dataAccess.userDataPathExistsSync("/backups/")) {
logger.info("Can't find the backup folder, creating one now...");
dataAccess.makeDirInUserDataSync("/backups");
}
// Create the clips folder if it doesn't exist
if (!dataAccess.userDataPathExistsSync("/clips/")) {
dataAccess.makeDirInUserDataSync("/clips");
}
// Update the port.js file
let port = settings.getWebSocketPort();
dataAccess.writeFileInWorkingDir(
'/resources/overlay/js/port.js',
`window.WEBSOCKET_PORT = ${port}`,
() => {
logger.info(`Set overlay port to: ${port}`);
});
// Create the controls folder if it doesn't exist.
if (!dataAccess.userDataPathExistsSync("/user-settings/controls")) {
logger.info("Can't find the controls folder, creating one now...");
dataAccess.makeDirInUserDataSync("/user-settings/controls");
}
// Create the logs folder if it doesn't exist.
if (!dataAccess.userDataPathExistsSync("/user-settings/logs")) {
logger.info("Can't find the logs folder, creating one now...");
dataAccess.makeDirInUserDataSync("/user-settings/logs");
}
// Create the chat folder if it doesn't exist.
if (!dataAccess.userDataPathExistsSync("/user-settings/chat")) {
logger.info("Can't find the chat folder, creating one now...");
dataAccess.makeDirInUserDataSync("/user-settings/chat");
}
// Create the chat folder if it doesn't exist.
if (!dataAccess.userDataPathExistsSync("/user-settings/live-events")) {
logger.info("Can't find the live-events folder, creating one now...");
dataAccess.makeDirInUserDataSync("/user-settings/live-events");
}
logger.info("Finished verifying default folders and files.");
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async function() {
await createDefaultFoldersAndFiles();
createWindow();
backupManager.onceADayBackUpCheck();
//start the REST api server
apiServer.start();
return true;
});
// Quit when all windows are closed.
app.on('window-all-closed', () => {
if (settings.backupOnExit()) {
backupManager.startBackup(false, app.quit);
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
} else if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
// When Quitting.
app.on('will-quit', () => {
let hotkeyManager = require('./lib/hotkeys/hotkey-manager');
// Unregister all shortcuts.
hotkeyManager.unregisterAllHotkeys();
});
// Run Updater
ipcMain.on('downloadUpdate', () => {
//back up first
if (settings.backupBeforeUpdates()) {
backupManager.startBackup();
}
// Download Update
let options = {
repo: 'firebottle/firebot',
currentVersion: app.getVersion()
};
let updater = new GhReleases(options);
updater.check((err, status) => {
logger.info('Should we download an update? ' + status);
// Download the update
updater.download();
if (err) {
logger.info(err);
}
});
// When an update has been downloaded
updater.on('update-downloaded', () => {
logger.info('Updated downloaded. Installing...');
//let the front end know and wait a few secs.
renderWindow.webContents.send('updateDownloaded');
setTimeout(function () {
// Restart the app and install the update
settings.setJustUpdated(true);
updater.install();
}, 3 * 1000);
});
// Access electrons autoUpdater
// eslint-disable-next-line no-unused-expressions
updater.autoUpdater;
});
// restarts the app
ipcMain.on('restartApp', () => {
app.relaunch({args: process.argv.slice(1).concat(['--relaunch'])});
app.exit(0);
});
// Opens the firebot root folder
ipcMain.on('openRootFolder', () => {
// We include "fakefile.txt" as a workaround to make it open into the 'root' folder instead
// of opening to the poarent folder with 'Firebot'folder selected.
let rootFolder = path.resolve(dataAccess.getUserDataPath() + path.sep + "user-settings");
shell.showItemInFolder(rootFolder);
});
// Get Import Folder Path
// This listens for an event from the render media.js file to open a dialog to get a filepath.
ipcMain.on('getImportFolderPath', (event, uniqueid) => {
let path = dialog.showOpenDialog({
title: "Select 'user-settings' folder",
buttonLabel: "Import 'user-settings'",
properties: ['openDirectory']
});
event.sender.send('gotImportFolderPath', {path: path, id: uniqueid});
});
// Get Get Backup Zip Path
// This listens for an event from the render media.js file to open a dialog to get a filepath.
ipcMain.on('getBackupZipPath', (event, uniqueid) => {
const backupsFolderPath = path.resolve(dataAccess.getUserDataPath() + path.sep + "backups" + path.sep);
let fs = require('fs');
let backupsFolderExists = false;
try {
backupsFolderExists = fs.existsSync(backupsFolderPath);
} catch (err) {
logger.warn("cannot check if backup folder exists", err);
}
let zipPath = dialog.showOpenDialog({
title: "Select backup zp",
buttonLabel: "Select Backup",
defaultPath: backupsFolderExists ? backupsFolderPath : undefined,
filters: [
{name: 'Zip', extensions: ['zip']}
]
});
event.sender.send('gotBackupZipPath', {path: zipPath, id: uniqueid});
});
// Opens the firebot backup folder
ipcMain.on('openBackupFolder', () => {
// We include "fakefile.txt" as a workaround to make it open into the 'root' folder instead
// of opening to the poarent folder with 'Firebot'folder selected.
let backupFolder = path.resolve(dataAccess.getUserDataPath() + path.sep + "backups" + path.sep + "fakescript.js");
shell.showItemInFolder(backupFolder);
});
ipcMain.on('startBackup', (event, manualActivation = false) => {
backupManager.startBackup(manualActivation, () => {
logger.info("backup complete");
renderWindow.webContents.send('backupComplete', manualActivation);
});
});
mixerConnect = require('./lib/common/mixer-interactive.js');