git ssb

1+

mixmix / scuttle-shell



Tree: 4933e4b778bdb7bc249725e152a78612fe6fcb5c

Files: 4933e4b778bdb7bc249725e152a78612fe6fcb5c / host-app.js

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

Built with git-ssb-web