-
Notifications
You must be signed in to change notification settings - Fork 902
Expand file tree
/
Copy pathindex.js
More file actions
242 lines (213 loc) · 7.49 KB
/
Copy pathindex.js
File metadata and controls
242 lines (213 loc) · 7.49 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
// @ts-check
const { screen, BrowserWindow, ipcMain, app, session } = require('electron')
const { join } = require('path')
const { URL } = require('url')
const serve = require('electron-serve')
const i18n = require('i18next')
const openExternal = require('./open-external')
const logger = require('../common/logger')
const store = require('../common/store')
const { OPEN_WEBUI_LAUNCH: CONFIG_KEY } = require('../common/config-keys')
const dock = require('../utils/dock')
const { VERSION, ELECTRON_VERSION } = require('../common/consts')
const createToggler = require('../utils/create-toggler')
const { showDialog } = require('../dialogs')
const { getSecondsSinceAppStart } = require('../metrics/appStart')
const { performance } = require('perf_hooks')
const Countly = require('countly-sdk-nodejs')
const { analyticsKeys } = require('../analytics/keys')
const ipcMainEvents = require('../common/ipc-main-events')
const getCtx = require('../context')
const { STATUS } = require('../daemon/consts')
serve({ scheme: 'webui', directory: join(__dirname, '../../assets/webui') })
/**
*
* @returns {BrowserWindow}
*/
const createWindow = () => {
logger.info('[webui] creating window')
const dimensions = screen.getPrimaryDisplay()
const window = new BrowserWindow({
title: 'IPFS Desktop',
show: false,
autoHideMenuBar: true,
titleBarStyle: 'hiddenInset',
width: store.get('window.width', dimensions.size.width < 1440 ? dimensions.size.width : 1440),
height: store.get('window.height', dimensions.size.height < 900 ? dimensions.size.height : 900),
webPreferences: {
preload: join(__dirname, 'preload.js'),
webSecurity: false,
allowRunningInsecureContent: false,
nodeIntegration: process.env.NODE_ENV === 'test'
}
})
window.webContents.once('did-start-loading', (event) => {
const msg = '[web ui] loading'
const webContentLoad = logger.start(msg, { withAnalytics: analyticsKeys.WEB_UI_READY })
window.webContents.once('did-finish-load', () => {
webContentLoad.end()
})
window.webContents.once('did-fail-load', (_, errorCode, errorDescription) => {
webContentLoad.fail(`${msg}: ${errorDescription}, code: ${errorCode}`)
})
})
window.webContents.once('dom-ready', async (event) => {
const endTime = performance.now()
try {
const dur = getSecondsSinceAppStart(endTime)
logger.info(`[App] startup time - ${dur} seconds`)
Countly.add_event({
key: 'APP_START_TO_DOM_READY',
count: 1,
dur
})
} catch (err) {
logger.error(err)
}
})
// open devtools with: DEBUG=ipfs-desktop
if (process.env.DEBUG && process.env.DEBUG.match(/ipfs-desktop/)) {
window.webContents.openDevTools()
}
window.webContents.on('render-process-gone', (_, { reason, exitCode }) => {
logger.error(`[web ui] render-process-gone: ${reason}, code: ${exitCode}`)
})
window.webContents.on('unresponsive', async () => {
logger.error('[web ui] the webui became unresponsive')
const opt = showDialog({
title: i18n.t('unresponsiveWindowDialog.title'),
message: i18n.t('unresponsiveWindowDialog.message'),
buttons: [
i18n.t('unresponsiveWindowDialog.forceReload'),
i18n.t('unresponsiveWindowDialog.doNothing')
]
})
if (opt === 0) {
window.webContents.forcefullyCrashRenderer()
window.webContents.reload()
}
})
window.on('resize', () => {
const dim = window.getSize()
store.safeSet('window.width', dim[0])
store.safeSet('window.height', dim[1])
})
window.on('close', (event) => {
event.preventDefault()
window.hide()
dock.hide()
logger.info('[web ui] window hidden')
})
app.on('before-quit', () => {
logger.info('[web ui] app-quit requested')
// Makes sure the app quits even though we prevent
// the closing of this window.
window.removeAllListeners('close')
})
return window
}
module.exports = async function () {
logger.info('[webui] init...')
const ctx = getCtx()
if (store.get(CONFIG_KEY, null) === null) {
// First time running this. Enable opening ipfs-webui at app launch.
// This accounts for users on OSes who may have extensions for
// decluttering system menus/trays, and thus have no initial "way in" to
// Desktop upon install:
// https://github.com/ipfs-shipyard/ipfs-desktop/issues/1741
store.safeSet(CONFIG_KEY, true)
}
createToggler(CONFIG_KEY, async ({ newValue }) => {
store.safeSet(CONFIG_KEY, newValue)
return true
})
openExternal()
const window = createWindow()
ctx.setProp('webui', window)
let apiAddress = null
const url = new URL('/', 'webui://-')
url.hash = '/blank'
url.searchParams.set('deviceId', await ctx.getProp('countlyDeviceId'))
ctx.setProp('launchWebUI', async (path, { focus = true, forceRefresh = false } = {}) => {
if (window.isDestroyed()) {
logger.error(`[web ui] window is destroyed, not launching web ui with ${path}`)
return
}
if (forceRefresh) window.webContents.reload()
if (!path) {
logger.info('[web ui] launching web ui', { withAnalytics: analyticsKeys.FN_LAUNCH_WEB_UI })
} else {
logger.info(`[web ui] navigate to ${path}`, { withAnalytics: analyticsKeys.FN_LAUNCH_WEB_UI_WITH_PATH })
url.hash = path
window.webContents.loadURL(url.toString())
}
if (focus) {
window.show()
window.focus()
dock.show()
}
// load again: minimize visual jitter on windows
if (path) window.webContents.loadURL(url.toString())
})
function updateLanguage () {
url.searchParams.set('lng', store.get('language'))
}
const getIpfsd = ctx.getFn('getIpfsd')
let ipfsdStatus = null
ipcMain.on(ipcMainEvents.IPFSD, async (status) => {
const ipfsd = await getIpfsd(true)
ipfsdStatus = status
if (ipfsd && ipfsd.apiAddr !== apiAddress) {
apiAddress = ipfsd.apiAddr
url.searchParams.set('api', apiAddress.toString())
updateLanguage()
window.loadURL(url.toString())
}
})
// Set user agent
session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
details.requestHeaders['User-Agent'] = `ipfs-desktop/${VERSION} (Electron ${ELECTRON_VERSION})`
callback({ cancel: false, requestHeaders: details.requestHeaders }) // eslint-disable-line
})
const launchWebUI = ctx.getFn('launchWebUI')
const splashScreen = await ctx.getProp('splashScreen')
if (store.get(CONFIG_KEY)) {
// we're supposed to show the window on startup, display the splash screen
splashScreen.show()
} else {
// we don't need the splash screen, ignore it.
splashScreen.destroy()
}
let splashScreenTimeoutId = null
window.on('close', () => {
if (splashScreenTimeoutId) {
clearTimeout(splashScreenTimeoutId)
splashScreenTimeoutId = null
}
})
const handleSplashScreen = async () => {
if ([null, STATUS.STARTING_STARTED].includes(ipfsdStatus)) {
splashScreenTimeoutId = setTimeout(handleSplashScreen, 500)
return
}
await launchWebUI('/')
try {
splashScreen.destroy()
} catch (err) {
logger.error('[web ui] failed to hide splash screen')
logger.error(err)
}
}
return /** @type {Promise<void>} */(new Promise(resolve => {
if (store.get(CONFIG_KEY)) {
logger.info('[web ui] waiting for ipfsd to start')
window.once('ready-to-show', async () => {
logger.info('[web ui] window ready')
handleSplashScreen()
resolve()
})
}
updateLanguage()
window.loadURL(url.toString())
}))
}