-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
109 lines (83 loc) · 2.49 KB
/
index.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
const { app, ipcMain } = require('electron')
const secretStack = require('secret-stack')
const caps = require('ssb-caps')
const { promisify } = require('util')
const Menu = require('./electron/menu')
const UIWindow = require('./electron/window/ui-window')
const logger = require('./lib/log')
const log = logger.bind(null, 'main')
const buildConfig = require('./lib/build-config')
module.exports = function ahoy (url, opts = {}, cb) {
if (cb === undefined) return promisify(ahoy)(url, opts)
const {
title = 'hello_world',
plugins = [],
config: optConfig
} = opts
const config = buildConfig(title, plugins, optConfig)
if (!Array.isArray(plugins)) return cb(Error('ssb-ahoy: plugins must be an array'))
if (!isValidUrl(url)) return cb(Error('ssb-ahoy: expects a ui URL which starts with http: | https: | file:'))
const state = {
quitting: false
}
app.on('before-quit', () => {
state.quitting = true
log('quitting')
})
app.whenReady().then(() => {
// reply to ui-window calls for ssb config
ipcMain.handle('get-config', () => config)
Menu()
startSSB(plugins, config, (err, ssb) => {
if (err) return cb(Error(err, { cause: 'ssb-ahoy failed to start SSB stack' }))
config.manifest = ssb.getManifest()
// TODO write to path/manifest.json
launchUI(url, title, state, (err) => {
if (err) return cb(Error(err, { cause: 'ssb-ahoy failed launch UI' }))
cb(null, ssb)
})
})
})
}
function startSSB (plugins, config, cb) {
log('starting Server')
const stack = secretStack({ caps: config.caps || caps })
plugins.forEach(plugin => stack.use(plugin))
let ssb
try {
ssb = stack(config)
// need a way to check if is ready (that is db1 / db2 agnostic)
ssb.getManifest()
} catch (err) {
return cb(err)
}
cb(null, ssb)
}
function launchUI (url, title, state, cb) {
log('starting UI')
const uiWindow = UIWindow(url, { title })
uiWindow.setSheetOffset(40)
/* handle OSX minimizing */
uiWindow.on('close', ev => {
if (process.platform === 'darwin') {
if (!state.quitting) {
ev.preventDefault()
uiWindow.hide()
}
} else {
app.quit()
}
})
// OSX - reopen app when dock icon is clicked
app.on('activate', ev => uiWindow.show())
cb(null)
}
function isValidUrl (str) {
if (typeof str !== 'string') return false
const validStarts = [
'file:',
'http:',
'https:'
]
return validStarts.some(start => str.startsWith(start))
}