This repository has been archived by the owner on Nov 17, 2023. It is now read-only.
/
main.js
363 lines (322 loc) · 10.5 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
/**
* This module executes inside of electron's main process. You can start
* electron renderer process from here and communicate with the other processes
* through IPC.
*
* When running `npm run build` or `npm run build-main`, this file is compiled to
* `/dist/main.js` using webpack. This gives us some performance wins.
*/
import { app, BrowserWindow, session } from 'electron'
import isDev from 'electron-is-dev'
import installExtension, {
REACT_DEVELOPER_TOOLS,
REDUX_DEVTOOLS,
} from 'electron-devtools-installer'
import get from 'lodash.get'
import path from 'path'
import os from 'os'
import fs from 'fs'
import bip21 from 'bip21'
import config from 'config'
import { mainLog } from '@zap/utils/log'
import appRootPath from '@zap/utils/appRootPath'
import themes from '@zap/renderer/themes'
import ZapMenuBuilder from './menuBuilder'
import ZapController from './controller'
import createBackupService from './walletBackup/service'
import ZapUpdater from './updater'
import ZapMigrator from './migrator'
import fetchSettings from './utils/fetchSettings'
// Set the Electron userDir to a temporary directory if the ELECTRON_USER_DIR_TEMP env var is set.
// This provides an easy way to run the app with a completely fresh environment, useful for e2e tests.
if (process.env.ELECTRON_USER_DIR_TEMP) {
const folder = fs.mkdtempSync(path.join(os.tmpdir(), 'zap-'))
mainLog.info('Using temporary directory %s for userData', folder)
app.setPath('userData', folder)
}
// By default, run the app in development mode.
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = 'development'
}
// Set up references to application helpers and controllers.
let zap
let updater
let menuBuilder
let mainWindow
let protocolUrl
// Set up a couple of timers to track the app startup progress.
mainLog.time('Time until app is ready')
/**
* Handler for open-link events.
*/
const handleOpenUrl = (urlToOpen = '') => {
// If we already have the mainWindow, handle the link right away.
if (mainWindow) {
mainLog.debug('handleOpenUrl: %s', urlToOpen)
const type = urlToOpen.split(':')[0]
switch (type) {
case 'bitcoin':
handleBitcoinLink(urlToOpen)
break
case 'lightning':
handleLightningLink(urlToOpen)
break
case 'lndconnect':
handleLndconnectLink(urlToOpen)
break
}
}
// Otherwise, defer until the winow content has fully loaded.
// See mainWindow.webContents.on('did-finish-load') below.
else {
protocolUrl = urlToOpen
}
}
/**
* Handler for lndconnect: links
*/
const handleBitcoinLink = input => {
try {
const decoded = bip21.decode(input)
zap.sendMessage('bitcoinPaymentUri', decoded)
mainWindow.show()
} catch (e) {
mainLog.warn('Unable to process bitcoin uri: %s', e)
}
}
/**
* Handler for lightning: links
*/
const handleLightningLink = input => {
const payReq = input.split(':')[1]
zap.sendMessage('lightningPaymentUri', { payReq })
mainWindow.show()
}
/**
* Handler for lndconnect: links
*/
const handleLndconnectLink = input => {
try {
zap.sendMessage('lndconnectUri', input)
mainWindow.show()
} catch (e) {
mainLog.warn('Unable to process lndconnect uri: %s', e)
}
}
/**
* Helper method to fetch a a settings property value.'
*/
const getSetting = (store, key) => {
const setting = store.find(s => s.key === key)
return setting && setting.hasOwnProperty('value') ? setting.value : null
}
/**
* If we are not able to get a single instnace lock, quit immediately.
*/
const singleInstanceLock = app.requestSingleInstanceLock()
if (!singleInstanceLock) {
mainLog.error('Unable to get single instance lock. It looks like you already have Zap open?')
app.quit()
}
app.on('will-finish-launching', () => {
app.on('open-url', (event, urlToOpen) => {
mainLog.trace('app.open-url')
event.preventDefault()
handleOpenUrl(urlToOpen)
})
})
/**
* Initialize Zap as soon as electron is ready.
*/
app.on('ready', async () => {
mainLog.trace('app.ready')
mainLog.timeEnd('Time until app is ready')
// Get the users preference so that we can:
// - set the background colour of the window to avoid unwanted flicker.
// - Initialise the Language menu with the users locale selected by default.
// - Enable autoupdates based on user preferences.
let autoupdate = {}
let theme = {}
let locale = null
if (!process.env.DISABLE_INIT) {
try {
const settings = await fetchSettings()
const currentConfig = getSetting(settings, 'config') || {}
const themeKey = currentConfig.theme || config.theme
locale = currentConfig.locale || config.locale
autoupdate = currentConfig.autoupdate || config.autoupdate
theme = themes[themeKey]
} catch (e) {
mainLog.warn('Unable to determine user settings: %s', e.message)
}
}
// Create a new browser window.
mainWindow = new BrowserWindow({
show: false,
useContentSize: true,
titleBarStyle: 'hidden',
width: 900,
height: 680,
minWidth: 900,
minHeight: 425,
backgroundColor: get(theme, 'colors.primaryColor', '#242633'),
icon: isDev
? path.resolve('resources', 'icon.png')
: path.resolve(appRootPath(), 'resources', 'icon.png'),
webPreferences: {
nodeIntegration: false,
contextIsolation: false,
nodeIntegrationInWorker: true,
preload: isDev
? path.resolve(__dirname, '..', 'dist', 'preload.js')
: path.resolve(__dirname, 'preload.js'),
},
})
// Initialise the migrator and run any pending migrations.
if (!process.env.DISABLE_INIT) {
const migrator = new ZapMigrator()
await migrator.up()
}
// Initialise the updater.
updater = new ZapUpdater(mainWindow, autoupdate)
// Initialise the application.
zap = new ZapController(mainWindow)
zap.init({ theme: theme ? theme.name : undefined })
// initialize backup system
createBackupService(mainWindow)
// Initialise the application menus.
menuBuilder = new ZapMenuBuilder(mainWindow)
menuBuilder.buildMenu(locale)
/**
* Add application event listener:
* - Stop gRPC and kill lnd process before the app windows are closed and the app quits.
*/
app.on('before-quit', event => {
mainLog.trace('app.before-quit')
if (mainWindow && !mainWindow.forceClose) {
event.preventDefault()
mainWindow.forceClose = true
zap.terminate()
}
})
app.on('will-quit', () => {
mainLog.trace('app.will-quit')
})
app.on('quit', () => {
mainLog.trace('app.quit')
})
/**
* On OS X it's common to re-open a window in the app when the dock icon is clicked.
*/
app.on('activate', () => {
mainLog.trace('app.activate')
mainWindow.show()
})
app.on('window-all-closed', () => {
mainLog.trace('app.window-all-closed')
if (os.platform() !== 'darwin' || mainWindow.forceClose) {
app.quit()
}
})
/**
* Someone tried to run a second instance, we should focus our window.
*/
app.on('second-instance', (event, commandLine) => {
mainLog.trace('app.second-instance')
if (os.platform() !== 'darwin') {
const urlToOpen = commandLine && commandLine.slice(1)[0]
if (urlToOpen) {
handleOpenUrl(urlToOpen)
}
}
if (mainWindow) {
if (mainWindow.isMinimized()) {
mainWindow.restore()
}
mainWindow.focus()
}
})
// When the window is closed, just hide it unless we are force closing.
mainWindow.on('close', event => {
mainLog.trace('mainWindow.close')
if (os.platform() === 'darwin' && !mainWindow.forceClose) {
event.preventDefault()
if (mainWindow.isFullScreen()) {
mainWindow.once('leave-full-screen', () => {
mainWindow.hide()
})
mainWindow.setFullScreen(false)
} else {
mainWindow.hide()
}
}
})
// Dereference the window object.
mainWindow.on('closed', () => {
mainLog.trace('mainWindow.closed')
mainWindow = null
updater.mainWindow = null
zap.mainWindow = null
menuBuilder.mainWindow = null
})
// Once the app has finished loading, handle any deferred protocol urls.
mainWindow.webContents.on('did-finish-load', () => {
mainLog.trace('webContents.did-finish-load')
// Check to see if we have a protocol link to handle from app startup time.
// On the mac, `protocolUrl` will be set as a result of us trying to process the link from the `open-url` handler.
// On windows/linux the link will be passed to electron as the first process argument.
const urlToOpen = protocolUrl || process.argv.slice(1)[0]
if (urlToOpen) {
handleOpenUrl(urlToOpen)
protocolUrl = null
}
})
/**
* In production mode, enable source map support.
*/
if (process.env.NODE_ENV === 'production') {
const sourceMapSupport = require('source-map-support') // eslint-disable-line global-require
sourceMapSupport.install()
}
/**
* In development mode or when DEBUG_PROD is set, enable debugging tools.
*/
if (process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD) {
installExtension(REACT_DEVELOPER_TOOLS)
.then(name => mainLog.debug(`Added Extension: ${name}`))
.catch(err => mainLog.warn(`An error occurred when installing REACT_DEVELOPER_TOOLS: ${err}`))
installExtension(REDUX_DEVTOOLS)
.then(name => mainLog.debug(`Added Extension: ${name}`))
.catch(err => mainLog.warn(`An error occurred when installing REDUX_DEVTOOLS: ${err}`))
mainWindow.webContents.once('dom-ready', () => {
mainLog.trace('webContents.dom-ready')
mainWindow.openDevTools()
})
}
// HACK: patch webrequest to fix devtools incompatibility with electron 2.x.
// See https://github.com/electron/electron/issues/13008#issuecomment-400261941
session.defaultSession.webRequest.onBeforeRequest({}, (details, callback) => {
if (details.url.indexOf('7accc8730b0f99b5e7c0702ea89d1fa7c17bfe33') === -1) {
callback({ cancel: false })
} else {
callback({
redirectURL: details.url.replace(
'7accc8730b0f99b5e7c0702ea89d1fa7c17bfe33',
'57c9d07b416b5a2ea23d28247300e4af36329bdc'
),
})
}
})
})
// ------------------------------------
// Helpers
// ------------------------------------
/**
* Add application event listeners:
* - lightning: Open zap payment form when bitcoin url is opened
* - lightning: Open zap payment form when lightning url is opened
* - lndconnect: Populate onboarding connection details form when lndconnect url is opened
*/
app.setAsDefaultProtocolClient('bitcoin')
app.setAsDefaultProtocolClient('lightning')
app.setAsDefaultProtocolClient('lndconnect')