forked from DannyNoam/casinocoin-wallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
electron.ts
368 lines (325 loc) · 10.4 KB
/
electron.ts
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
import {
app, BrowserWindow, screen,
autoUpdater, ipcMain, dialog,
Menu, MenuItem, powerMonitor
} from 'electron';
import * as path from 'path';
import * as fs from 'fs';
import * as os from 'os';
// this is required to check if the app is running in development mode.
import * as isDev from 'electron-is-dev';
import * as notifier from 'electron-notification-desktop';
let win, serve;
const args = process.argv.slice(1);
serve = args.some(val => val === '--serve');
const version = app.getVersion();
const platform = os.platform() + '_' + os.arch();
const globalTS: any = global;
globalTS.vars = {};
// set app id
app.setAppUserModelId("org.stoxum.desktop.wallet");
// set property for exit dialog
let showExitPrompt = true;
let savedBeforeQuit = false;
globalTS.vars.exitFromRenderer = false;
globalTS.vars.exitFromLogin = false;
// define auto update url
let updaterFeedURL = 'https://download.stoxum.org/update/' + platform + '/' + version;
if (version.indexOf("beta") !== -1) {
updaterFeedURL = updaterFeedURL + '/' + 'beta';
}
console.log('Update URL: ' + updaterFeedURL);
// if in development add electron reload
if (serve) {
require('electron-reload')(__dirname, {
electron: require('${__dirname}/../../node_modules/electron')
});
}
/* Handling squirrel.windows events on windows
only required if you have build the windows with target squirrel. For NSIS target you don't need it. */
if (require('electron-squirrel-startup')) {
showExitPrompt = false;
savedBeforeQuit = true;
globalTS.vars.exitFromRenderer = true;
globalTS.vars.exitFromLogin = true;
app.quit();
}
// Funtion to check the current OS. As of now there is no proper method to add auto-updates to linux platform.
function isWindowsOrmacOS() {
return process.platform === 'darwin' || process.platform === 'win32';
}
function appUpdater() {
autoUpdater.setFeedURL(updaterFeedURL);
/* Log whats happening
TODO send autoUpdater events to renderer so that we could console log it in developer tools
You could alsoe use nslog or other logging to see what's happening */
autoUpdater.on('error', err => console.log(err));
autoUpdater.on('checking-for-update', () => console.log('checking-for-update'));
autoUpdater.on('update-available', () => console.log('update-available'));
autoUpdater.on('update-not-available', () => console.log('update-not-available'));
// Ask the user if update is available
autoUpdater.on('update-downloaded', (event, releaseNotes, releaseName) => {
let message = app.getName() + ' ' + releaseName + ' is now available. It will be installed the next time you restart the application.';
if (releaseNotes) {
const splitNotes = releaseNotes.split(/[^\r]\n/);
message += '\n\nRelease notes:\n';
splitNotes.forEach(notes => {
message += notes + '\n\n';
});
}
// Ask user to update the app
dialog.showMessageBox({
type: 'question',
buttons: ['Install and Relaunch', 'Later'],
defaultId: 0,
message: 'A new version of ' + app.getName() + ' has been downloaded',
detail: message
}, response => {
if (response === 0) {
showExitPrompt = false;
savedBeforeQuit = true;
globalTS.vars.exitFromRenderer = true;
globalTS.vars.exitFromLogin = true;
setTimeout(() => autoUpdater.quitAndInstall(), 1);
}
});
});
// init for updates
autoUpdater.checkForUpdates();
}
// set the default userData directory
const defaultSTMPath = path.join(app.getPath('home'), '.stoxum');
if (!fs.existsSync(defaultSTMPath)) {
fs.mkdirSync(defaultSTMPath);
}
app.setPath('userData', defaultSTMPath);
// configure loggging
const winston = require('winston');
if (serve) {
globalTS.loglevel = 'debug';
} else {
globalTS.loglevel = 'info';
}
var logFolder = path.join(app.getPath("userData"), "logs");
if (!fs.existsSync(logFolder)) {
fs.mkdirSync(logFolder);
}
let logFilename = new Date().toISOString().replace(/:/g, '.') + '.log';
let logFile = path.join(logFolder, logFilename)
function customFileFormatter(options) {
// Return string will be passed to logger.
return new Date().toISOString() + ' [' + options.level.toUpperCase() + '] ' + (undefined !== options.message ? options.message : '') +
(options.meta && Object.keys(options.meta).length ? '\n\t' + JSON.stringify(options.meta) : '');
}
winston.add(winston.transports.File,
{
filename: logFile,
level: globalTS.loglevel,
maxsize: 100000000,
json: false,
formatter: customFileFormatter
}
);
winston.remove(winston.transports.Console);
winston.level = globalTS.loglevel;
globalTS.logger = winston;
// configure backup path
let backupFolder = path.join(app.getPath("userData"), "backup");
if (!fs.existsSync(backupFolder)) {
fs.mkdirSync(backupFolder);
}
globalTS.vars.backupPath = backupFolder;
// create window
function createWindow() {
const electronScreen = screen;
const size = electronScreen.getPrimaryDisplay().workAreaSize;
const minimalWidth = Math.min(size.width, 1024);
const minimalHeight = Math.min(size.height, 720);
// Create the browser window.
win = new BrowserWindow({
width: minimalWidth,
minWidth: minimalWidth,
height: minimalHeight,
minHeight: minimalHeight,
icon: __dirname + '/favicon.ico',
show: false,
darkTheme: true
});
// and load the index.html of the app.
win.loadURL('file://' + __dirname + '/index.html');
const page = win.webContents;
// Run the auto updater
page.once('did-frame-finish-load', () => {
const checkOS = isWindowsOrmacOS();
if (checkOS && !isDev) {
// Initate auto-updates on macOs and windows
appUpdater();
}
});
// Open the DevTools.
if (serve) {
win.webContents.openDevTools();
}
powerMonitor.on('suspend', () => {
winston.log("debug", "### Electron -> The system is going to sleep ###");
// send message to save and logout wallet
if (win !== null) {
win.webContents.send('action', 'save-wallet');
}
});
powerMonitor.on('resume', () => {
winston.log("debug", "### Electron -> The system is resuming after sleep ###");
if (win === null) {
createWindow();
} else {
win.reload();
win.show();
}
});
//push notification using electron-notification-desktop
ipcMain.on('push-notification', (event, arg) => {
const notification = notifier.notify(arg.title, {
message: arg.body,
icon: path.join(__dirname, 'assets/brand/stoxum-icon-256x256.png'),
duration: 4
});
notification.on('close', function (event) {
notification.hide();
event.preventDefault();
});
});
// Emitted when the window is closed.
win.on('close', (e) => {
// console.log("close - showExitPrompt: " + showExitPrompt + " exitFromLogin: " + globalTS.vars.exitFromLogin + " savedBeforeQuit: " + savedBeforeQuit);
if (globalTS.vars.exitFromLogin && showExitPrompt) {
// Prevent the window from closing
e.preventDefault()
globalTS.vars.exitFromLogin = false;
showExitPrompt = false;
savedBeforeQuit = true;
win.close();
} else if (!globalTS.vars.exitFromRenderer) {
if (showExitPrompt) {
e.preventDefault() // Prevents the window from closing
dialog.showMessageBox({
type: 'question',
buttons: ['Yes', 'No'],
title: 'Confirm',
message: 'Are you sure you want to close the wallet?'
}, function (response) {
if (response === 0) { // Runs the following if 'Yes' is clicked
// on next win.on('close') the app will be finally closed
showExitPrompt = false;
savedBeforeQuit = true;
win.close();
}
});
}
} else {
if (showExitPrompt) {
e.preventDefault() // Prevents the window from closing
dialog.showMessageBox({
type: 'question',
buttons: ['Yes', 'No'],
title: 'Confirm',
message: 'Are you sure you want to close the wallet?'
}, function (response) {
if (response === 0) { // Runs the following if 'Yes' is clicked
// on next win.on('close') the app will be finally closed
showExitPrompt = false;
win.close();
}
});
} else if (!savedBeforeQuit) {
// Prevent the window from closing
e.preventDefault();
if (win != null) {
ipcMain.on('wallet-closed', (event, arg) => {
savedBeforeQuit = true;
win.close();
});
// save and close wallet
win.webContents.send('action', 'quit-wallet');
} else {
win.close();
}
}
}
});
win.on('closed', (e) => {
win = null;
});
// Disable menu bar
win.setMenu(null);
// show the windows
win.once('ready-to-show', () => {
showExitPrompt = true;
savedBeforeQuit = false;
globalTS.vars.exitFromRenderer = false;
globalTS.vars.exitFromLogin = false;
win.show();
});
// Create the Application's main menu
const template: Electron.MenuItemConstructorOptions[] = [{
label: 'Stoxum Wallet',
submenu: [
{
label: 'Cut',
accelerator: 'Command+X',
role: 'cut'
},
{
label: 'Copy',
accelerator: 'Command+C',
role: 'copy'
},
{
label: 'Paste',
accelerator: 'Command+V',
role: 'paste'
},
{
type: 'separator'
},
{
label: 'Quit',
accelerator: 'Command+Q',
click: function () { app.quit(); }
}
]
}];
let menu = Menu.buildFromTemplate(template);
if (process.platform == 'darwin') {
Menu.setApplicationMenu(menu);
}
}
try {
// 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', createWindow);
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
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 (win === null) {
createWindow();
} else {
win.show();
}
});
app.on('before-quit', () => {
console.log("before-quit");
});
} catch (e) {
// Catch Error
// throw e;
console.log(e);
}