This repository has been archived by the owner on May 12, 2021. It is now read-only.
/
muxrpc-ipc.js
69 lines (64 loc) · 1.89 KB
/
muxrpc-ipc.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
var ipc = require('ipc')
var muxrpc = require('muxrpc')
var pull = require('pull-stream')
var pushable = require('pull-pushable')
var clientApi = {
navigate: 'async',
contextualToggleDevTools: 'async'
}
module.exports = function (window, sbot, params) {
// add rpc APIs to window
window.createRpc = function () {
// create rpc object
var rpc = window.rpc = muxrpc(clientApi, sbot.manifest(), serialize)(sbot)
rpc.authorized = { id: sbot.id, role: 'master' }
rpc.permissions({allow: null, deny: null})
function serialize (stream) { return stream }
// start the stream
window.rpcStream = rpc.createStream()
var ipcPush = pushable()
ipc.on('muxrpc-ssb', function (e, msg) {
if (e.sender == window.webContents) {
try {
if (typeof msg == 'string')
msg = JSON.parse(msg)
} catch (e) {
return
}
if (msg.bvalue) {
msg.value = new Buffer(msg.bvalue, 'base64')
delete msg.bvalue
}
ipcPush.push(msg)
}
})
pull(ipcPush, window.rpcStream, pull.drain(
function (msg) {
if (msg.value && Buffer.isBuffer(msg.value)) {
// convert buffers to base64
msg.bvalue = msg.value.toString('base64')
delete msg.value
}
window.webContents.send('muxrpc-ssb', JSON.stringify(msg))
},
function (err) { if (err) { console.error(err) } }
))
}
window.resetRpc = function () {
console.log('close rpc')
window.rpcStream.source(true)
window.rpc.close()
window.createRpc()
}
// setup default stream
window.createRpc()
// setup helper messages
ipc.on('fetch-manifest', function(e) {
if (e.sender == window.webContents)
e.returnValue = sbot.manifest()
});
ipc.on('fetch-params', function(e) {
if (e.sender == window.webContents)
e.returnValue = params
});
}