forked from derogold/GoldWallet
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
364 lines (319 loc) · 11 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
const {app, dialog, Tray, Menu} = require('electron');
const path = require('path');
const fs = require('fs');
const url = require('url');
const https = require('https');
const platform = require('os').platform();
const crypto = require('crypto');
const Store = require('electron-store');
const settings = new Store({name: 'Settings'});
const log = require('electron-log');
const splash = require('@trodi/electron-splashscreen');
const config = require('./src/js/ws_config');
const IS_DEV = (process.argv[1] === 'dev' || process.argv[2] === 'dev');
const IS_DEBUG = IS_DEV || process.argv[1] === 'debug' || process.argv[2] === 'debug';
const LOG_LEVEL = IS_DEBUG ? 'debug' : 'warn';
log.transports.console.level = LOG_LEVEL;
log.transports.file.level = LOG_LEVEL;
log.transports.file.maxSize = 5 * 1024 * 1024;
const WALLETSHELL_VERSION = app.getVersion() || '0.3.6';
const SERVICE_FILENAME = (platform === 'win32' ? `${config.walletServiceBinaryFilename}.exe` : config.walletServiceBinaryFilename );
const SERVICE_OSDIR = (platform === 'win32' ? 'win' : (platform === 'darwin' ? 'osx' : 'lin'));
const DEFAULT_SERVICE_BIN = path.join(process.resourcesPath,'bin', SERVICE_OSDIR, SERVICE_FILENAME);
const DEFAULT_SETTINGS = {
service_bin: DEFAULT_SERVICE_BIN,
service_host: '127.0.0.1',
service_port: config.walletServiceRpcPort,
service_password: crypto.randomBytes(32).toString('hex'),
daemon_host: config.remoteNodeDefaultHost,
daemon_port: config.daemonDefaultRpcPort,
pubnodes_date: null,
pubnodes_data: config.remoteNodeListFallback,
pubnodes_custom: ['127.0.0.1:11898'],
tray_minimize: false,
tray_close: false,
darkmode: true,
service_config_format: config.walletServiceConfigFormat
};
const DEFAULT_SIZE = { width: 840, height: 680 };
app.prompExit = true;
app.prompShown = false;
app.needToExit = false;
app.setAppUserModelId(config.appId);
log.info(`Starting WalletShell ${WALLETSHELL_VERSION}`);
let trayIcon = path.join(__dirname,'src/assets/tray.png');
let trayIconHide = path.join(__dirname,'src/assets/trayon.png');
let win;
let tray;
function createWindow () {
// Create the browser window.
let darkmode = settings.get('darkmode', true);
let bgColor = darkmode ? '#000000' : '#02853E';
const winOpts = {
title: `${config.appName} ${config.appDescription}`,
icon: path.join(__dirname,'src/assets/walletshell_icon.png'),
frame: true,
width: DEFAULT_SIZE.width,
height: DEFAULT_SIZE.height,
minWidth: DEFAULT_SIZE.width,
minHeight: DEFAULT_SIZE.height,
show: false,
backgroundColor: bgColor,
center: true,
};
win = splash.initSplashScreen({
windowOpts: winOpts,
templateUrl: path.join(__dirname, "src/html/splash.html"),
delay: 0,
minVisible: 3000,
splashScreenOpts: {
width: 425,
height: 325,
transparent: true
},
});
let contextMenu = Menu.buildFromTemplate([
{ label: 'Minimize to tray', click: () => { win.hide(); }},
{ label: 'Quit', click: ()=> {
app.needToExit = true;
win.close();
}
}
]);
tray = new Tray(trayIcon);
tray.setPressedImage(trayIconHide);
tray.setTitle(config.appName);
tray.setToolTip(config.appSlogan);
tray.setContextMenu(contextMenu);
tray.on('click', () => {
if(settings.get('tray_minimize', false)){
if(win.isVisible()){
win.hide();
}else{
win.show();
}
}else{
if(win.isMinimized()){
win.restore();
win.focus();
}else{
win.minimize();
}
}
});
win.on('show', () => {
tray.setHighlightMode('always');
tray.setImage(trayIcon);
contextMenu = Menu.buildFromTemplate([
{ label: 'Minimize to tray', click: () => { win.hide();} },
{ label: 'Quit', click: ()=> {
app.needToExit = true;
win.close();
}
}
]);
tray.setContextMenu(contextMenu);
tray.setToolTip(config.appSlogan);
});
win.on('hide', () => {
tray.setHighlightMode('never');
tray.setImage(trayIconHide);
contextMenu = Menu.buildFromTemplate([
{ label: 'Restore', click: () => { win.show();} },
{ label: 'Quit', click: ()=> {
app.needToExit = true;
win.close();
}
}
]);
tray.setContextMenu(contextMenu);
});
win.on('minimize', (event) => {
if(settings.get('tray_minimize')){
event.preventDefault();
win.hide();
}
});
//load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, 'src/html/index.html'),
protocol: 'file:',
slashes: true
}));
// open devtools
if(IS_DEV ) win.webContents.openDevTools();
// show windosw
win.once('ready-to-show', () => {
//win.show();
win.setTitle(`${config.appName} ${config.appDescription}`);
tray.setToolTip(config.appSlogan);
});
win.on('close', (e) => {
if(settings.get('tray_close') && !app.needToExit){
e.preventDefault();
win.hide();
}else if(app.prompExit ){
e.preventDefault();
if(app.prompShown) return;
let msg = 'Are you sure want to exit?';
app.prompShown = true;
dialog.showMessageBox({
type: 'question',
buttons: ['Yes', 'No'],
title: 'Exit Confirmation',
message: msg
}, function (response) {
app.prompShown = false;
if (response === 0) {
app.prompExit = false;
win.webContents.send('cleanup','Clean it up, Dad!');
}else{
app.prompExit = true;
app.needToExit = false;
}
});
}
});
win.on('closed', () => {
win = null;
});
win.setMenu(null);
// misc handler
win.webContents.on('crashed', () => {
// todo: prompt to restart
log.debug('webcontent was crashed');
});
win.on('unresponsive', () => {
// todo: prompt to restart
log.debug('webcontent is unresponsive');
});
}
function storeNodeList(pnodes){
pnodes = pnodes || settings.get('pubnodes_data');
let validNodes = [];
if( pnodes.hasOwnProperty('nodes')){
pnodes.nodes.forEach(element => {
let item = `${element.url}:${element.port}`;
validNodes.push(item);
});
}
if(validNodes.length) settings.set('pubnodes_data', validNodes);
}
function doNodeListUpdate(){
try{
https.get(config.remoteNodeListUpdateUrl, (res) => {
var result = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
result += chunk;
});
res.on('end', () => {
try{
var pnodes = JSON.parse(result);
let today = new Date();
storeNodeList(pnodes);
log.debug('Public node list has been updated');
let mo = (today.getMonth()+1);
settings.set('pubnodes_date', `${today.getFullYear()}-${mo}-${today.getDate()}`);
}catch(e){
log.debug(`Failed to update public node list: ${e.message}`);
storeNodeList();
}
});
}).on('error', (e) => {
log.debug(`Failed to update public-node list: ${e.message}`);
});
}catch(e){
log.error(`Failed to update public-node list: ${e.code} - ${e.message}`);
}
}
function serviceBinCheck(){
if(!DEFAULT_SERVICE_BIN.startsWith('/tmp')){
return;
}
log.warn(`AppImage env, copying service bin file`);
let targetPath = path.join(app.getPath('userData'), SERVICE_FILENAME);
try{
fs.renameSync(targetPath, `${targetPath}.bak`, (err) => {
if(err) log.error(err);
});
}catch(_e){}
try{
fs.copyFile(DEFAULT_SERVICE_BIN, targetPath, (err) => {
if (err){
log.error(err);
return;
}
settings.set('service_bin', targetPath);
log.debug(`service binary copied to ${targetPath}`);
});
}catch(_e){}
}
function initSettings(){
Object.keys(DEFAULT_SETTINGS).forEach((k) => {
if(!settings.has(k) || settings.get(k) === null){
settings.set(k, DEFAULT_SETTINGS[k]);
}
});
settings.set('version', WALLETSHELL_VERSION);
serviceBinCheck();
}
const silock = app.requestSingleInstanceLock();
app.on('second-instance', () => {
if (win) {
if (!win.isVisible()) win.show();
if (win.isMinimized()) win.restore();
win.focus();
}
});
if (!silock) app.quit();
app.on('ready', () => {
initSettings();
if(IS_DEV || IS_DEBUG) log.warn(`Running in ${IS_DEV ? 'dev' : 'debug'} mode`);
global.wsession = {
debug: IS_DEBUG
};
if(config.remoteNodeListUpdateUrl){
let today = new Date();
let last_checked = new Date(settings.get('pubnodes_date'));
let diff_d = parseInt((today-last_checked)/(1000*60*60*24),10);
if(diff_d >= 1){
log.info('Performing daily public-node list update.');
doNodeListUpdate();
}else{
log.info('Public node list up to date, skipping update');
storeNodeList(false); // from local cache
}
}
createWindow();
// try to target center pos of primary display
let eScreen = require('electron').screen;
let primaryDisp = eScreen.getPrimaryDisplay();
let tx = Math.ceil((primaryDisp.workAreaSize.width - DEFAULT_SIZE.width)/2);
let ty = Math.ceil((primaryDisp.workAreaSize.height - (DEFAULT_SIZE.height))/2);
if(tx > 0 && ty > 0) win.setPosition(parseInt(tx, 10), parseInt(ty,10));
});
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (platform !== 'darwin') app.quit();
});
app.on('activate', () => {
// On macOS 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();
});
process.on('uncaughtException', function (e) {
log.error(`Uncaught exception: ${e.message}`);
process.exit(1);
});
process.on('beforeExit', (code) => {
log.debug(`beforeExit code: ${code}`);
});
process.on('exit', (code) => {
log.debug(`exit with code: ${code}`);
});
process.on('warning', (warning) => {
log.warn(`${warning.code}, ${warning.name}`);
});