-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
313 lines (274 loc) · 8.74 KB
/
app.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
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
const express = require('express')
const fs = require('fs')
const { exec } = require('child_process')
const execa = require('execa')
const websocket = require('ws')
const find = require('find-process')
const fetch = require('node-fetch')
const ping = require('ping')
var systemSettings
var status = {
captureDevice: false,
stream: false
}
function apply(settings) {
// Save AP SSID and passphrase
console.log('Saving AP settings...')
const apSettings = 'interface=wlan0\n' +
'driver=nl80211\n' +
'ssid=' + settings['ap-ssid'] + '\n' +
'hw_mode=g\n' +
'hw_mode=g\n' +
'channel=8\n' +
'wmm_enabled=0\n' +
'macaddr_acl=0\n' +
'auth_algs=1\n' +
'ignore_broadcast_ssid=0\n' +
'wpa=2\n' +
'wpa_passphrase=' + settings['ap-passphrase'] + '\n' +
'wpa_key_mgmt=WPA-PSK\n' +
'wpa_pairwise=CCMP TKIP\n' +
'rsn_pairwise=CCMP\n' +
'country_code=US\n' +
'ieee80211n=1\n' +
'ieee80211d=1'
fs.writeFile('/etc/hostapd/hostapd.conf', apSettings, (err) => {
if (err) {
console.log(err)
return
}
})
// Save Client SSID and passphrase
console.log('Saving client settings...')
const clientSettings = 'country=US\n' +
'ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n' +
'update_config=1\n' +
'network={\n' +
' ssid="' + settings['client-ssid'] + '"\n' +
' psk="' + settings['client-passphrase'] + '"\n' +
' id_str="AP1"\n' +
'}'
fs.writeFile('/etc/wpa_supplicant/wpa_supplicant.conf', clientSettings, (err) => {
if (err) {
console.log(err)
return
}
})
// Save server address and stream key
console.log('Saving server settings...')
const serverSettings = '["-hide_banner","-re","-f","v4l2","-i","/dev/video0","-c:v","h264_omx","-an","-f","flv","rtmp://' + settings['server-address'] + '/live/' + settings['stream-key'] + '"]'
// Concatonate all the settings and save them
let newSettings = Object.assign(settings, { "stream-params": serverSettings })
fs.writeFile('/sonostreamer/system_settings.json', JSON.stringify(newSettings), (err) => {
if (err) {
console.log(err)
return
}
})
console.log('System settings successfully saved')
exec('sudo autohotspot')
return
}
async function configureInputDevice() {
fs.readFile('/sonostreamer/system_settings.json', (err, data) => {
if (err) {
console.log(err)
return
}
systemSettings = JSON.parse(data)
if (systemSettings['video-source'] == 'Composite (RCA)') {
exec('v4l2-ctl', ["-d", "/dev/video0", "-i", "0"])
console.log('Success - Composite')
} else if (systemSettings['video-source'] == 'S-video') {
exec('v4l2-ctl', ["-d", "/dev/video0", "-i", "1"])
console.log('Success - S-video')
} else if (systemSettings['video-source'] == 'HDMI') {
exec('v4l2-ctl', ["-d", "/dev/video0", "-i", "0"])
console.log('Success - HDMI')
} else {
console.log('Failure')
}
})
return
}
function checkCaptureDevice() {
const path = '/dev/video0'
try {
if (fs.existsSync(path)) {
//console.log('Capture device detected')
status.captureDevice = true
} else if (!fs.existsSync(path)) {
//console.log('Capture device NOT detected')
status.captureDevice = false
}
} catch(err) {
console.error(err)
status.captureDevice = false
}
}
function checkStreamStatus() {
//console.log('check stream status')
find('name', 'ffmpeg', true)
.then(function(list) {
//console.log('ffmpeg processes running: ' + list.length)
if(list.length == 0) {
status.stream = false
} else {
status.stream = true
}
})
.catch(err => {
'find ffmpeg error'
status.stream = false
})
}
function checkConnection() {
ping.sys.probe('jaffamd.com', (isAlive) => {
status.internet = isAlive
})
}
// Timed function to send status of capture device and stream once per second via websocket
function sendStatus(websocket) {
checkCaptureDevice()
checkStreamStatus()
checkConnection()
//console.log('Status to send: ' + JSON.stringify(status))
websocket.send(JSON.stringify(status))
setTimeout(sendStatus, 1000, websocket)
}
const app = express()
// Serve static files
app.use(express.static('public'))
// Use the JSON middleware to parse POST data
app.use(express.json())
// Load stream parameters and configure the input device
configureInputDevice()
// -------------------------------------------------------------------------------------
// Define local functions to allow user interaction endpoints to trigger system commands
// -------------------------------------------------------------------------------------
// --------------------------------------------
// Define routes for user-interaction endpoints
// --------------------------------------------
// Site root
app.get('/', (req, res) => {
res.sendFile(__dirname + ('/index.html'))
})
// Start livestream
app.get('/stream/start', (req, res) => {
// Make sure the input device is properly configured
configureInputDevice()
// Start the livestream (requires async process)
startLivestream()
res.json({ message: 'Stream started' })
})
async function startLivestream() {
const {stdout} = await execa('ffmpeg', JSON.parse(systemSettings['stream-params']))
console.log(stdout)
}
// Stop livestream
app.get('/stream/stop', (req, res) => {
exec('sudo killall ffmpeg')
res.json({ message: 'Stream stopped' })
})
// Reboot system
app.get('/system/reboot', (req, res) => {
res.json({ message: 'Rebooting system...' })
exec('sudo reboot now')
})
// Shutdown system
app.get('/system/shutdown', (req, res) => {
res.json({ message: 'Shutting down system...' })
exec('sudo shutdown now')
})
// Check streaming status
app.get('/system/checkstream', (req, res) => {
if(checkStreamStatus()) {
//console.log('Currently streaming')
} else {
//console.log('Currently NOT streaming')
}
})
// Check capture device status
app.get('/system/checkcapturedevice', (req, res) => {
if(checkCaptureDevice()) {
//console.log('Capture device connected')
} else {
//console.log('Capture device NOT connected')
}
})
// ---------------
// Manage settings
// ---------------
// Route to html page for settings management
app.get('/settings', (req, res) => {
res.sendFile(__dirname + '/settings.html')
})
// Route to request file in which system settings are saved
app.get('/system/settings', (req, res) => {
res.sendFile(__dirname + '/system_settings.json')
})
// Route to change system settings from form
app.post('/system/settings', (req, res) => {
try {
apply(req.body)
} catch (err) {
console.log('Error saving settings')
console.log(err)
res.json({ message: 'There was an error while saving your settings' })
return
}
res.json({ message: 'Settings saved successfully' })
})
// ---------------------
// Manage system updates
// ---------------------
// Route to manage updating system files (automated-ish future updates)
app.get('/system/checkupdate', (req, res) => {
// Retrieve the package.json file from the master GitHub repo online and extract the version number
fetch('https://raw.githubusercontent.com/jaffamd/sonostreamer/master/package.json', { method: 'get' })
.then(data => data.json())
.then((json) => {
let remoteVersion = json.version
// Retrieve the local version number from the local package.json file
fs.readFile('/sonostreamer/package.json', (err, data) => {
if(err) {
console.log(err)
res.send(err)
}
localVersion = JSON.parse(data).version
console.log('Local version: ' + localVersion)
console.log('Remote version: ' + remoteVersion)
if (localVersion == remoteVersion) {
res.json({msg: 'uptodate'})
} else {
res.json({msg: 'updateneeded'})
}
})
})
})
app.get('/system/update', (req, res) => {
exec('sudo ./systemupdate &', (error, stdout, stderr) => {
if (wsserver) {
if (error) {
wsserver.send(`Error: ${error}`)
}
if (stderr) {
wsserver.send(`STDERR: ${stderr}`)
}
wsserver.send(`STDOUT: ${stdout}`)
}
})
})
app.listen(80, () => console.log('Sonostreamer client started at ' + new Date().toISOString().replace('T', ' ').substr(0, 19)))
// -------------------------
// WebSockets Implementation
// -------------------------
const wsserver = new websocket.Server({ port: 8080 })
wsserver.on('connection', websocket => {
console.log('Connected to client')
// When a client connects (e.g. a user opens the webpage or connects via the mobile app), start running the sendStatus function once per second
setTimeout(sendStatus, 1000, websocket)
websocket.on('message', message => {
//console.log(`Received message from client => ${message}`)
})
})