/
SnipsLogger.js
executable file
·460 lines (407 loc) · 19 KB
/
SnipsLogger.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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/* global window */
/* global Paho */
import React, { Component } from 'react'
import eventFunctions from './eventFunctions'
import Crunker from 'crunker'
import SnipsMqttServer from './SnipsMqttServer'
export default class SnipsLogger extends SnipsMqttServer {
constructor(props) {
super(props);
this.eventFunctions = eventFunctions;
this.eventCallbackFunctions = this.addCallbacks(this.props.eventCallbackFunctions);
this.siteId = props.siteId ? props.siteId : 'site'+parseInt(Math.random()*100000000,10);
this.state={sites:{},messages:[],session:{},audioListening:{},hotwordListening:{},showLogMessages:{},sessionStatus:{},sessionStatusText:{}};
this.audioBuffers={};
this.lastSessionId={};
this.getSession = this.getSession.bind(this);
this.saveSession = this.saveSession.bind(this);
this.updateSession = this.updateSession.bind(this);
this.logAudioBuffer = this.logAudioBuffer.bind(this);
this.updateSessionStatus = this.updateSessionStatus.bind(this);
this.addCallbacks = this.addCallbacks.bind(this);
this.findEventCallbackFunctions = this.findEventCallbackFunctions.bind(this);
this.onMessageArrived = this.onMessageArrived.bind(this);
this.isConnected = this.isConnected.bind(this);
this.reset = this.reset.bind(this);
this.mqttConnect.bind(this)() ;
}
reset() {
this.setState({sites:{},messages:[],session:{},audioListening:{},hotwordListening:{},showLogMessages:{},sessionStatus:{},sessionStatusText:{} });
this.audioBuffers={};
this.lastSessionId={};
};
addCallbacks(eventCallbackFunctions,oneOff = false) {
let that = this;
this.eventCallbackFunctions = Array.isArray(this.eventCallbackFunctions) ? this.eventCallbackFunctions : [];
if (eventCallbackFunctions) {
Object.keys(eventCallbackFunctions).map(function(key,loopKey) {
let value = eventCallbackFunctions[key];
if (typeof value === "function") {
that.eventCallbackFunctions.push({subscription:key,callBack:value, oneOff: oneOff,id:parseInt(Math.random()*100000000,10)});
}
});
}
return this.eventCallbackFunctions;
};
findEventCallbackFunctions(subscriptionKey) {
let that = this;
let ret=[];
this.eventCallbackFunctions.map(function(value,vkey) {
if (value.subscription === subscriptionKey) {
ret.push(value);
return;
}
});
return ret;
};
generateUuid() {
//// return uuid of form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
var uuid = '', ii;
for (ii = 0; ii < 32; ii += 1) {
switch (ii) {
case 8:
case 20:
uuid += '-';
uuid += (Math.random() * 16 | 0).toString(16);
break;
case 12:
uuid += '-';
uuid += '4';
break;
case 16:
uuid += '-';
uuid += (Math.random() * 4 | 8).toString(16);
break;
default:
uuid += (Math.random() * 16 | 0).toString(16);
}
}
return uuid;
};
onMessageArrived(message) {
let that = this;
let parts = message.destinationName ? message.destinationName.split("/") : [];
if (parts.length > 0 && parts[0] === "hermes") {
if (parts.length > 1 && parts[1] === "audioServer") {
var audio = message.payloadBytes;
if (parts.length > 3) {
let siteId = parts[2];
let action = parts[3];
let id = parts.length > 4 ? parts[4] : ''; //this.generateUuid() ;
if (action === "playBytes") {
} else if (action === "playFinished") {
} else if (action === "audioFrame") {
this.appendAudioBuffer(siteId,audio);
}
let functionKey ='hermes/audioServer/#/'+action;
// hooks and callbacks
// if (action !== "audioFrame") console.log(['LOGGER AUDIO CALLBACK',functionKey,that.eventFunctions[functionKey]]);
if (this.eventFunctions.hasOwnProperty(functionKey)) {
let p = that.eventFunctions[functionKey].bind(that)(audio);
p.then(function(session) {
//if (action !== "audioFrame") console.log(['LOGGER AUDIO CALLBACK COMPLETE',functionKey,session]);
let callbacks = that.findEventCallbackFunctions(functionKey);
//if (action !== "audioFrame") console.log(['LOGGER AUDIO CALLBACKS',callbacks]);
if (callbacks) {
callbacks.map(function(value,ckey) {
//if (action !== "audioFrame") console.log(['LOGGER AUDIO CALLBACK ONE',value,ckey]);
let session = that.getSession(siteId,null);
value.callBack.bind(that)(message.destinationName,siteId,id,session,audio);
});
}
}).catch(function(e) {
console.log(e);
});
}
let sessionId = this.lastSessionId[siteId];
let messages = this.state.messages;
if (action !== "audioFrame" && (!this.props.siteId || (this.props.siteId && this.props.siteId === siteId ))) {
messages.push({sessionId:sessionId,payload: <div style={{backgroundColor:'lightgrey'}}><hr/></div> ,text:message.destinationName});
this.setState({messages:messages});
}
}
} else {
let payload = {};
try {
payload = JSON.parse(message.payloadString);
} catch (e) {
}
// special case for hotword parameter in url
let functionKey = message.destinationName;
if (parts.length > 3 && parts[0] === "hermes" && parts[1] === "hotword" && parts[3] === "detected") {
functionKey = 'hermes/hotword/#/detected'
// special case for intent parameter in hermes/intent
} else if (parts.length > 1 && parts[0] === "hermes" && parts[1] === "intent") {
functionKey = 'hermes/intent/#';
}
if (this.eventFunctions.hasOwnProperty(functionKey)) {
let p = that.eventFunctions[functionKey].bind(that)(payload);
p.then(function(session) {
let callbacks = that.findEventCallbackFunctions(functionKey);
if (callbacks) {
callbacks.map(function(value,ckey) {
value.callBack.bind(that)(payload,message);
if (value.oneOff) {
// remove this callback
let breakLoop = false;
that.eventCallbackFunctions.map(function(tvalue,vkey) {
if (value.id === tvalue.id && !breakLoop) {
that.eventCallbackFunctions.splice(vkey,1);
breakLoop = true;
}
return;
});
}
});
}
}).catch(function(e) {
console.log(e);
});
}
let messages = this.state.messages;
let thisState = {}
if (payload.siteId) {
if (payload.sessionId) {
thisState = this.getSession(payload.siteId,payload.sessionId);
}
}
messages.push({sessionId:thisState.sessionId,payload: <div style={{backgroundColor:'lightgrey'}}><hr/><div style={{backgroundColor:'lightblue'}}><pre>{JSON.stringify(payload,undefined,4)}</pre></div><hr/><div style={{backgroundColor:'lightgreen'}}><pre>{JSON.stringify(thisState,undefined,4)}</pre></div><hr/></div> ,text:message.destinationName});
this.setState({messages:messages});
// console.log(['LOGGER MESSAGE',message.destinationName,message,JSON.parse(JSON.stringify(this.state.sites))]);
}
}
};
cleanSlots(slots) {
let final={};
if (slots) {
slots.map(function(slot) {
final[slot.slotName] = {type:slot.value.kind,value:slot.value.value}
return;
});
}
return final;
};
/**
* Get a session for a given siteId and sessionId
*
*/
// that.lastSessionId[payload.siteId]
getSession(siteIdIn,sessionIdIn) {
let siteId = null;
let sessionId = null;
let that = this;
function findOrCreateSession(siteId,sessionId) {
if (siteId && siteId.length > 0 && sessionId && sessionId.length > 0) {
if (that.state.sites && that.state.sites.hasOwnProperty(siteId) && that.state.sites[siteId].hasOwnProperty(sessionId) && that.state.sites[siteId][sessionId]) {
return that.state.sites[siteId][sessionId];
} else {
// fallback, create a new session
let sites = that.state.sites ? that.state.sites : {};
let sessions = that.state.sessions ? that.state.sessions : {};
if (!sites.hasOwnProperty(siteId)) sites[siteId] = {};
let newSession={createtimestamp: new Date().getTime(),siteId:siteId,sessionId:sessionId};
if (!sites[siteId].hasOwnProperty(sessionId)) sites[siteId][sessionId]=newSession;
sessions[sessionId] = siteId;
that.setState({sites:sites,sessions:sessions});
return sites[siteId][sessionId];
}
} else {
console.log(['CANNOT FIND OR CREATE SESSION MISSING SITE OR SESSION ID',siteId,sessionId]);
}
};
if (siteIdIn && siteIdIn.length>0) {
if (sessionIdIn && sessionIdIn.length>0) {
// have site and session id
siteId = siteIdIn;
sessionId = sessionIdIn;
} else {
// have siteId
siteId = siteIdIn;
sessionId = this.lastSessionId[siteId];
}
} else {
if (sessionIdIn && sessionIdIn.length>0) {
// have sessionId
sessionId = sessionIdIn;
siteId = this.state.sessions[sessionId];
} else {
// have no ids
console.log(['FAILED TO CAPTURE MESSAGE WITH NO SITE OR SESSION ID']);
return null;
}
}
return findOrCreateSession(siteId,sessionId);
};
/**
* Lookup session, use callback to make changes and restore session to state
*/
updateSession(payload,callback) {
let siteId = payload && payload.siteId && payload.siteId.length > 0 ? payload.siteId : null;
let sessionId = payload && payload.sessionId && payload.sessionId.length > 0 ? payload.sessionId : null;
let session = this.getSession(siteId,sessionId);
if (session) {
let result = callback(session)
this.saveSession(session.siteId,session.sessionId,result);
}
};
saveSession(siteIdIn,sessionIdIn,session) {
let sessionId = sessionIdIn && sessionIdIn.length > 0 ? sessionIdIn : 'unknownSession';
// ensure siteId
let siteId=siteIdIn;
if (!siteIdIn ||siteIdIn.length === 0) {
siteId = this.state.sessions[sessionId];
}
if (siteId && siteId.length>0) {
let sites = this.state.sites;
sites[siteId][sessionId] = session;
this.setState({sites:sites});
this.setLogData();
}
};
setLogData() {
if (this.props.setLogData) this.props.setLogData(this.state.sites,this.state.messages,this.state.sessionStatus,this.state.sessionStatusText,this.state.hotwordListening,this.state.audioListening);
};
updateSessionStatus(siteKey,session) {
let that = this;
let sessionStatus=0;
let sessionKey = session.sessionId;
if (that.state.hotwordListening[siteKey]) sessionStatus=1;
if (that.state.audioListening[siteKey]) sessionStatus=2;
if (session.queued) sessionStatus=3;
if (session.started) sessionStatus=4;
if (session.intents && session.asr && session.intents.length < session.asr.length) sessionStatus=5;
if (session.intents && session.asr && session.intents.length === session.asr.length) sessionStatus=6;
if (session.ended) sessionStatus=7;
if (session.success) sessionStatus=8;
let statusTexts=['starting','hotword','listening','queued','started','transcribed','interpreted','ended','success'];
let statusText= statusTexts[sessionStatus];
let allSessionsStatus = that.state.sessionStatus;
let allSessionsStatusText = that.state.sessionStatusText;
allSessionsStatus[sessionKey] = sessionStatus;
allSessionsStatusText[sessionKey] = statusText;
that.setState({sessionStatus:allSessionsStatus,sessionStatusText:allSessionsStatusText});
};
/**
* Get or create an audio buffer for the siteId
*/
getAudioBuffer(siteId) {
if (siteId) {
if (this.audioBuffers.hasOwnProperty(siteId)) {
return this.audioBuffers[siteId];
} else {
this.audioBuffers[siteId] = [];
return this.audioBuffers[siteId];
}
}
};
/**
* Get or create an audio buffer for the siteId
*/
appendAudioBuffer(siteId,buffer) {
if (this.props.logAudio === true && siteId) {
if (this.state.audioListening[siteId]) {
let currentBuffer = this.getAudioBuffer(siteId);
currentBuffer.push(buffer);
}
}
};
/**
* Get or create an audio buffer for the siteId
*/
resetAudioBuffer(siteId) {
this.audioBuffers[siteId] = [];
};
logAudioBuffer(payload) {
let that = this;
let promises = [];
let siteId = payload.siteId;
if (this.props.logAudio === true) {
try {
// save to sites/sessions
let audioContext = window.AudioContext || window.webkitAudioContext;
let context = new audioContext();
let audioBuffer = this.getAudioBuffer(siteId);
// memory overload protection
// if (audioBuffer.length> 350) return;
audioBuffer.map(function(bytes,key) {
let p = new Promise(function(resolve,reject) {
var buffer = new Uint8Array( bytes.length );
if (bytes.length > 0) {
buffer.set( new Uint8Array(bytes), 0 );
try {
context.decodeAudioData(buffer.buffer, function(audioBuffer) {
resolve(audioBuffer);
});
} catch (e) {
// trash buffer
reject();
}
}
});
promises.push(p);
return;
})
} catch (e) {
console.log(['ERROR',e]);
}
Promise.all(promises).then(function(allBuffers) {
let merger = new Crunker();
try {
let output = merger.export(merger.concatAudio(allBuffers), "audio/wav");
that.updateSession(payload,function(session) {
if (!session.audio) session.audio=[];
that.blobToDataUrl(output.blob).then(function(dataUrl) {
session.audio.push(dataUrl);
// start again
that.resetAudioBuffer(siteId);
that.setLogData();
});
return session;
});
} catch (e) {
console.log(e.message);
}
});
}
};
blobToDataUrl(blob) {
return new Promise((fulfill, reject) => {
let reader = new FileReader();
reader.onerror = reject;
reader.onload = (e) => fulfill(reader.result);
reader.readAsDataURL(blob);
})
}
sendMqtt(destination,payload) {
//if (!destination.startsWith('hermes/audioServer')) console.log(['SESSION SEND MQTT LOGGER',destination,payload])
if (this.state.connected) {
let message = new Paho.MQTT.Message(JSON.stringify(payload));
message.destinationName = destination;
this.mqttClient.send(message);
}
};
sendAudioMqtt(destination,payload) {
if (this.state.connected) {
let message = new Paho.MQTT.Message(payload);
message.destinationName = destination;
this.mqttClient.send(message);
}
};
/**
* Send Mqtt message to speak text
*/
say(siteId,text) {
let that = this;
if (that.state && that.state.connected) {
let currentSession = that.getSession(siteId,null);
let payload = {siteId:siteId,text:text};
if (currentSession) payload.sessionId = currentSession.sessionId;
let message = new Paho.MQTT.Message(JSON.stringify(payload));
message.destinationName = "hermes/tts/say";
that.mqttClient.send(message);
}
};
isConnected() {
return this.state.connected;
};
}