git ssb

1+

mixmix / scuttle-shell



Tree: de92553986e36c8aa555fb0a529a98913b109777

Files: de92553986e36c8aa555fb0a529a98913b109777 / host-app.js

2518 bytesRaw
1
2const nativeMessage = require('chrome-native-messaging')
3const { spawn } = require('child_process')
4const path = require('path')
5const fs = require('fs')
6const config = require('ssb-config/inject')(process.env.ssb_appname)
7
8const pathToSecret = path.join(config.path, 'secret')
9
10const input = new nativeMessage.Input()
11const transform = new nativeMessage.Transform((msg, push, done) => {
12 getReplyFor(msg, data => {
13 push(data)
14 done()
15 })
16})
17const output = new nativeMessage.Output()
18
19const getConfig = () => {
20 try {
21 let secret = fs.readFileSync(pathToSecret, "utf8")
22 let keys = JSON.parse(secret.replace(/#[^\n]*/g, ''))
23 let manifest = JSON.parse(fs.readFileSync(path.join(config.path, 'manifest.json')))
24 let remote = "ws://localhost:8989~shs:" + keys.id.substring(1, keys.id.indexOf('.'))
25 return { type: 'config', keys: keys, manifest: manifest, remote: remote, secret: secret }
26 } catch (n) {
27 return { type: 'exception', msg: n.message }
28 }
29}
30
31const startServer = (cb) => {
32 output.write({ type: "debug", msg: `starting scuttlebutt` })
33
34 var scriptPath = path.join(__dirname, 'server.js')
35 var child = spawn(process.execPath, [scriptPath])
36
37 child.stdout.on('data', (data) => {
38 output.write({ type: 'debug', msg: `stdout: ${data}` })
39 })
40
41 child.stderr.on('data', (data) => {
42 output.write({ type: 'error', msg: `stderr: ${data}` })
43 })
44
45 child.on('close', (code) => {
46 output.write({ type: 'debug', msg: `child process exited with code ${code}` })
47 })
48
49 output.write(getConfig())
50}
51
52const getReplyFor = (msg, cb) => {
53 output.write({ type: "debug", msg: `trying to get reply for ${msg.cmd}` })
54 switch (msg.cmd) {
55 case 'start-server':
56 startServer(cb)
57 break
58 case 'stop-server': {
59 clearInterval(timer)
60 cb({ type: 'shutdown', msg: 'stopping server' })
61 process.exit(1)
62 }
63 case 'get-config': {
64 let secretRaw = fs.readFileSync(pathToSecret)
65 let keys = JSON.parse(secret.replace(/#[^\n]*/g, ''))
66 let manifest = JSON.parse(fs.readFileSync(path.join(config.path, 'manifest.json')))
67 let remote = "ws://localhost:8989~shs:" + keys.id.substring(1, keys.id.indexOf('.'))
68
69 cb({ type: 'config', keys, manifest, remote })
70 }
71 }
72}
73
74var timer = setInterval(function () {
75 output.write({ type: "ping", time: new Date().toISOString() })
76}, 120000)
77
78input.on('end', function () {
79 clearInterval(timer)
80})
81
82process.stdin
83 .pipe(input)
84 .pipe(transform)
85 .pipe(output)
86 .pipe(process.stdout)
87

Built with git-ssb-web