Repository navigation
Expand file tree
/
Copy pathelectron.js
More file actions
585 lines (495 loc) · 15.1 KB
/
Copy pathelectron.js
File metadata and controls
585 lines (495 loc) · 15.1 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
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
const electron = require('electron')
const { remote, app, BrowserWindow, Tray, Menu, MenuItem, ipcMain } = electron
const path = require('path')
const URL = require('url')
const fs = require('fs')
// const URL = require('URL')
// console.log(fs.readFileSync('./insert/trx.js').toString())
const isDev = process.mainModule.filename.indexOf('app.asar') === -1
// import { ipcMain } from 'electron'
// const { ebtMain } = require('electron-baidu-tongji')
// ebtMain(ipcMain)
// console.log(process.mainModule)
let icon = isDev
? 'static/icons/1024x1024.png'
: __dirname + '/static/icons/1024x1024.png'
let trayIcon = isDev
? 'static/icons/16x16.png'
: __dirname + '/static/icons/16x16.png'
let mainUrl = isPopup =>
isDev
? `http://localhost:8080/${isPopup ? '/#/popout' : ''}`
: URL.format({
pathname: path.join(__dirname, 'dist', 'index.html'),
protocol: 'file:',
slashes: true,
hash: isPopup ? '/popout' : null
})
const quit = () => {
if (global && global.appShared && global.appShared.savingData) {
setTimeout(() => {
quit()
}, 100)
} else {
if (global && global.appShared && global.appShared.QuitWatcher !== null)
global.appShared.QuitWatcher()
app.quit()
}
}
let tray, mainWindow
const setupMenu = () => {
const menu = new Menu()
mainWindow.setMenu(menu)
const template = [
{
label: 'Application',
submenu: [
{
label: 'About Application',
selector: 'orderFrontStandardAboutPanel:'
},
{ type: 'separator' },
{
label: 'Quit',
accelerator: 'Command+Q',
click: () => {
quit()
}
}
]
},
{
label: 'Edit',
submenu: [
{ label: 'Undo', accelerator: 'CmdOrCtrl+Z', selector: 'undo:' },
{ label: 'Redo', accelerator: 'Shift+CmdOrCtrl+Z', selector: 'redo:' },
{ type: 'separator' },
{ label: 'Cut', accelerator: 'CmdOrCtrl+X', selector: 'cut:' },
{ label: 'Copy', accelerator: 'CmdOrCtrl+C', selector: 'copy:' },
{ label: 'Paste', accelerator: 'CmdOrCtrl+V', selector: 'paste:' },
{
label: 'Select All',
accelerator: 'CmdOrCtrl+A',
selector: 'selectAll:'
}
]
}
]
Menu.setApplicationMenu(Menu.buildFromTemplate(template))
}
const restoreInstance = () => {
mainWindow.show()
if (mainWindow.isMinimized()) mainWindow.restore()
}
const activateInstance = e => {
if (e) e.preventDefault()
if (!mainWindow) return
restoreInstance()
}
const setupTray = () => {
tray = new Tray(trayIcon)
const contextMenu = Menu.buildFromTemplate([
{ label: '打开', type: 'normal', click: () => restoreInstance() },
{ label: '退出', type: 'normal', click: () => quit() }
])
tray.setToolTip('TokenPocket')
tray.setContextMenu(contextMenu)
tray.on('click', () => restoreInstance())
}
const createScatterInstance = () => {
app.setAsDefaultProtocolClient('TokenPocket')
const createMainWindow = (show, backgroundColor) =>
new BrowserWindow({
width: 1000,
height: 720,
frame: false,
radii: [5, 5, 5, 5],
icon,
resizable: true,
minWidth: 1000,
minHeight: 720,
titleBarStyle: 'hiddenInset',
backgroundColor,
show,
webPreferences: {
nodeIntegration: true,
webviewTag: true
}
})
mainWindow = createMainWindow(false, '#fff')
mainWindow.loadURL(mainUrl(false))
mainWindow.once('ready-to-show', () => {
mainWindow.show()
mainWindow.focus()
})
// mainWindow.openDevTools();
mainWindow.on('closed', () => (mainWindow = null))
mainWindow.on('close', () => quit())
setupTray()
setupMenu()
LowLevelWindowService.queuePopup()
}
app.on('ready', createScatterInstance)
app.on('activate', activateInstance)
app.on('window-all-closed', () => quit())
app.on('second-instance', (event, argv) => {
if (process.platform === 'win32' || process.platform === 'linux')
callDeepLink(argv.slice(1))
if (mainWindow) activateInstance()
})
app.on(
'certificate-error',
(event, webContents, url, error, certificate, callback) => {
const isLocal = URL.startsWith('https://127.0.0.1')
if (isLocal) {
event.preventDefault()
callback(true)
} else {
callback(false)
}
}
)
app.on('web-contents-created', (event, contents) => {
contents.on('will-navigate', (event, navigationUrl) => {
// Never navigate away from localhost.
if (navigationUrl.indexOf(mainUrl(false)) !== 0) event.preventDefault()
})
})
const callDeepLink = url => {
if (global.appShared.ApiWatcher !== null) global.appShared.ApiWatcher(url)
}
if (!app.requestSingleInstanceLock()) quit()
app.on('will-finish-launching', () => {
app.on('open-url', (e, url) => {
e.preventDefault()
callDeepLink(url)
})
})
const isMac = () => process.platform === 'darwin'
let waitingPopup
class LowLevelWindowService {
static getWindow(width = 800, height = 600) {
return new Promise(resolve => {
const win = new BrowserWindow({
backgroundColor: '#FFFFFF',
width,
height,
frame: false,
radii: [5, 5, 5, 5],
icon: 'assets/favicon.png',
show: false,
webPreferences: {
nodeIntegration: true
}
})
win.loadURL(mainUrl(true))
resolve(win)
// win.once('ready-to-show', () => resolve(win));
})
}
static async queuePopup() {
setTimeout(async () => {
waitingPopup = await this.getWindow(800, 600)
}, 100)
}
static async openPopOut(
onReady = () => {},
onClosed = () => {},
width = 800,
height = 600,
dontHide = false
) {
let win = waitingPopup
if (!win) win = await this.getWindow()
else waitingPopup = null
win.setSize(width, height)
// Getting the screen to display the popup based on
// where the user is at the time ( for dual monitors )
const mousePoint = electron.screen.getCursorScreenPoint()
const activeDisplay = electron.screen.getDisplayNearestPoint(mousePoint)
let {
width: screenWidth,
height: screenHeight
} = activeDisplay.workAreaSize
const leftBound = activeDisplay.bounds.x
let bounds = electron.screen.getPrimaryDisplay().bounds
let x = bounds.x + (leftBound + (bounds.width - width) / 2)
let y = bounds.y + (bounds.height - height) / 2
win.setPosition(Math.round(x), Math.round(y))
win.once('closed', async () => {
// This is a fix for MacOS systems which causes the
// main window to always pop up after popups closing.
if (!dontHide && isMac()) {
// mainWindow.hide();
Menu.sendActionToFirstResponder('hide:')
// mainWindow.show();
}
onClosed(win)
win = null
})
onReady(win)
this.queuePopup()
win.show()
win.setAlwaysOnTop(true, 'floating')
win.focus()
if (isMac()) {
app.dock.hide()
win.setAlwaysOnTop(false)
win.setVisibleOnAllWorkspaces(true)
win.setFullScreenable(false)
app.dock.show()
}
return win
}
}
const notifier = require('node-notifier')
class NotificationService {
static pushNotification(title, body) {
notifier.notify({
message: body,
title,
appID: 'com.get-scatter.server',
sound: false,
icon,
wait: false
})
}
}
require('babel-polyfill')
const Transport = require('@ledgerhq/hw-transport-node-hid')
const NodeMachineId = require('node-machine-id')
const http = require('http')
const https = require('https')
const WebSocket = require('ws')
const net = require('net')
class LowLevelSocketService {
constructor() {
this.rekeyPromise = null
this.openConnections = {}
this.websockets = []
this.ports = {}
}
async getNewKey(origin, id) {
return new Promise((resolve, reject) => {
this.rekeyPromise = { resolve, reject }
this.emit(origin, id, 'rekey')
return this.rekeyPromise
})
}
async emit(origin, id, path, data) {
const socket = this.openConnections[origin + id]
return this.emitSocket(socket, path, data)
}
async emitSocket(socket, path, data) {
if (!socket) return console.error('No socket found')
socket.send('42/scatter,' + JSON.stringify([path, data ? data : false]))
}
async initialize(_certs) {
const socketHandler = socket => {
let origin = null
socket.send('40')
socket.send('40/scatter')
socket.send(`42/scatter,["connected"]`)
const id = Math.round(Math.random() * 999999999).toString()
// Just logging errors for debugging purposes (dev only)
if (isDev)
socket.on('error', async request => console.log('error', request))
// Different clients send different message types for disconnect (ws vs socket.io)
socket.on('close', () => delete this.openConnections[origin + id])
socket.on('disconnect', () => delete this.openConnections[origin + id])
socket.on('message', msg => {
if (msg.indexOf('42/scatter') === -1) return false
const [type, request] = JSON.parse(msg.replace('42/scatter,', ''))
const killRequest = () =>
this.emitSocket(socket, 'api', { id: request.id, result: null })
if (!request.plugin || request.plugin.length > 100) return killRequest()
request.plugin = request.plugin.replace(/\s/g, '')
if (request.plugin.trim().toLowerCase() === 'Scatter') killRequest()
if (
request.data.hasOwnProperty('payload') &&
request.data.payload.origin.trim().toLowerCase() === 'Scatter'
)
killRequest()
let requestOrigin
if (request.data.hasOwnProperty('payload'))
requestOrigin = request.data.payload.origin
else requestOrigin = request.data.origin
if (!origin) origin = requestOrigin
else if (origin && requestOrigin !== origin)
return this.emitSocket(socket, 'api', {
id: request.id,
result: null
})
if (!this.openConnections.hasOwnProperty(origin + id))
this.openConnections[origin + id] = socket
switch (type) {
case 'pair':
return mainWindow.webContents.send('pair', { request, id })
case 'rekeyed':
return this.rekeyPromise.resolve(request)
case 'api':
return mainWindow.webContents.send('api', { request, id })
}
})
}
if (this.websockets.length) return this.websockets
await this.findOpenPorts()
mainWindow.webContents.send('ports', this.ports)
const requestHandler = (_, res) => {
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Request-Method', '*')
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET')
res.setHeader('Access-Control-Allow-Headers', '*')
res.setHeader('Content-Type', 'application/json')
res.end('scatter')
}
await Promise.all(
Object.keys(this.ports).map(async port => {
const server = this.ports[port]
? https.createServer(_certs, requestHandler)
: http.createServer(requestHandler)
this.websockets.push(new WebSocket.Server({ server }))
server.listen(port)
return true
})
)
this.websockets.map(ws => ws.on('connection', socketHandler))
return this.websockets
}
async close() {
this.websockets.map(ws => {
if (typeof ws.clients.map === 'function')
ws.clients.map(ws => ws.terminate())
})
return true
}
sendEvent(event, payload, origin) {
const sockets = Object.keys(this.openConnections)
.filter(x => x.indexOf(origin) === 0)
.map(x => this.openConnections[x])
sockets.map(x => this.emitSocket(x, 'event', { event, payload }))
return true
}
broadcastEvent(event, payload) {
Object.keys(this.openConnections).map(origin =>
this.sendEvent(event, payload, origin)
)
return true
}
async findOpenPorts() {
const isPortAvailable = (port = 0) => {
return new Promise(async resolve => {
const server = net.createServer()
server.once('error', err => resolve(err.code !== 'EADDRINUSE'))
server.once('listening', () => {
server.close()
resolve(true)
})
server.listen(port)
})
}
const findPort = async (delta = 0) => {
let port = 50005 + delta
while (!(await isPortAvailable(port))) port += 1500
return port
}
const http = await findPort()
const https = await findPort(1)
this.ports = { [http]: false, [https]: true }
return true
}
}
global.appShared = {
Transport,
QuitWatcher: null,
ApiWatcher: null,
LowLevelWindowService,
LowLevelSocketService: new LowLevelSocketService(),
NotificationService,
NodeMachineId,
savingData: false,
reloader: () => mainWindow.reload()
}
const secp256k1 = require('secp256k1')
let seed, key
ipcMain.on('key', (event, arg) => {
if (event.sender.history[0].indexOf('popout') > -1) return
if (arg === null) return (key = null)
if (key) return
key = Buffer.from(arg, 'base64')
})
ipcMain.on('seeding', (event, arg) => (seed = arg))
ipcMain.on('seed', (event, arg) => {
const { data, sig } = arg
// if (
// !isDev &&
// !secp256k1.verify(Buffer.from(data), Buffer.from(sig, 'base64'), key)
// ) {
// return event.sender.send('seed', null)
// }
event.sender.send('seed', seed)
})
let newwin
ipcMain.on('goGame', (event, arg) => {
// Menu.setApplicationMenu(null)
const js = fs.readFileSync(path.join(__dirname, './insert/trx.js')).toString()
newwin = new BrowserWindow({
title: arg.data.title,
width: 1200,
height: 720,
radii: [5, 5, 5, 5],
frame: false,
resizable: true,
titleBarStyle: 'hiddenInset',
webPreferences: {
nodeIntegration: true,
webviewTag: true
}
})
const webviewURL = isDev
? `http://localhost:8080/#/WebView`
: URL.format({
pathname: path.join(__dirname, 'dist', 'index.html'),
protocol: 'file:',
slashes: true,
hash: '/WebView'
})
newwin.loadURL(webviewURL) //new.html是新开窗口的渲染进程
newwin.webContents.on('dom-ready', () => {
// newwin.openDevTools()
newwin.webContents.send('INSERT_WEBVIEW_DATA', {
...arg,
js
})
})
newwin.on('closed', () => {
newwin = null
})
})
ipcMain.on('CLOSE_WEBVIEW', (evet, arg) => {
// console.log(newwin);
newwin.close()
})
// -------------------------------------------------------------
// CATCH ALL EXCEPTIONS AND CONSOLES
// We're throwing all exceptions and console up to the renderer console so they can be visible in running builds.
// -------------------------------------------------------------
process.on('uncaughtException', err => {
mainWindow.webContents.send('error', {
message: err.message,
file: err.fileName,
line: err.lineNumber
})
console.error('There was an uncaught error', err)
// process.exit(1) //mandatory (as per the Node docs)
})
const log = console.log
console.log = (...params) => {
mainWindow.webContents.send('console', params)
log(...params)
}
const logerr = console.error
console.error = (...params) => {
mainWindow.webContents.send('console', params)
logerr(...params)
}