Shinobi/libs/dataPort.js

66 lines
2.2 KiB
JavaScript
Raw Normal View History

const { createWebSocketServer } = require('./basic/websocketTools.js')
module.exports = function(s,config,lang,app,io){
const {
triggerEvent,
} = require('./events/utils.js')(s,config,lang)
s.dataPortTokens = {}
const theWebSocket = createWebSocketServer()
2023-12-14 00:59:52 +00:00
s.dataPortServer = theWebSocket;
function setClientKillTimerIfNotAuthenticatedInTime(client){
client.killTimer = setTimeout(function(){
client.terminate()
},10000)
}
function clearKillTimer(client){
clearTimeout(client.killTimer)
}
theWebSocket.on('connection',(client) => {
// client.send(someDataToSendAsStringOrBinary)
setClientKillTimerIfNotAuthenticatedInTime(client)
function onAuthenticate(data){
clearKillTimer(client)
2021-12-21 20:03:56 +00:00
if(data in s.dataPortTokens){
client.removeListener('message', onAuthenticate);
client.on('message', onAuthenticatedData)
delete(s.dataPortTokens[data]);
}else{
client.terminate()
}
}
function onAuthenticatedData(jsonData){
const data = JSON.parse(jsonData);
switch(data.f){
case'trigger':
triggerEvent(data)
break;
case's.tx':
s.tx(data.data,data.to)
break;
case'debugLog':
s.debugLog(data.data)
break;
2021-11-17 20:10:25 +00:00
default:
2023-10-04 22:38:16 +00:00
console.log(`No Data Port Handler!`)
console.log(`here's what we got :`)
2021-11-17 20:10:25 +00:00
console.log(data)
break;
}
s.onDataPortMessageExtensions.forEach(function(extender){
extender(data)
})
}
client.on('message', onAuthenticate)
client.on('close', () => {
clearTimeout(client.killTimer)
})
client.on('disconnect', () => {
clearTimeout(client.killTimer)
})
})
s.onHttpRequestUpgrade('/dataPort',(request, socket, head) => {
theWebSocket.handleUpgrade(request, socket, head, function done(ws) {
theWebSocket.emit('connection', ws, request)
})
})
}