Mute/kick channel web application (ARI) - javascript

So I currently have two functions which are called when I add a call to a bridge, and two functions within that get called automatically, so am trying to use JQuery so they only get called when a button is clicked, and then I can work from there in the server side of things.
Issue being at the moment an error gets thrown up saying $ isnt defined.
JQuery does work I have another file am calling which is all JQuery and handles my socket.io client side.
$("#mute").click(function () {
alert("Handler for .click() called.");
channel.mute({
channelId : 111
},
function (err) {});
});
$("#kick").click(function () {
alert("Handler for .click() called.");
channel.hangup({
channelId : 111
},
function (err) {});
});
As anyone any experience using both or even have any suggestion as to how I can do this.
Full code listing(Server side);
var ari = require('ari-client');
var util = require('util');
var chanArr = [];
var test;
var mute;
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
//ARI client
ari.connect('http://localhost:8088', 'asterisk', 'asterisk', clientLoaded);
function clientLoaded(err, client) {
if (err) {
throw err;
}
// find or create a holding bridges
var bridge = null;
client.bridges.list(function (err, bridges) {
if (err) {
throw err;
}
bridge = bridges.filter(function (candidate) {
return candidate.bridge_type === 'mixing';
})[0];
if (bridge) {
console.log(util.format('Using bridge %s', bridge.id));
} else {
client.bridges.create({
type : 'mixing'
}, function (err, newBridge) {
if (err) {
throw err;
}
bridge = newBridge;
console.log(util.format('Created bridge %s', bridge.id));
});
}
});
// handler for StasisStart event
function stasisStart(event, channel) {
console.log(util.format(
'Channel %s just entered our application, adding it to bridge %s',
channel.name,
bridge.id));
channel.answer(function (err) {
if (err) {
throw err;
}
bridge.addChannel({
channel : channel.id
}, function (err) {
var id = chanArr.push(channel.name)
console.log("Value: " + test);
test = channel.name;
updateSip);
if (err) {
throw err;
}
//If else statement to start music for first user entering channel, music will stop once more than 1 enters the channel.
if (chanArr.length <= 1) {
bridge.startMoh(function (err) {
if (err) {
throw err;
}
});
} else if (chanArr.length === 2) {
bridge.stopMoh(function (err) {
if (err) {
throw err;
}
});
} else {}
});
});
$("#mute").click(function () {
alert("Handler for .click() called.");
channel.mute({
channelId : 111
},
function (err) {});
});
$("#kick").click(function () {
alert("Handler for .click() called.");
channel.hangup({
channelId : 111
},
}
// handler for StasisEnd event
function stasisEnd(event, channel) {
console.log(util.format(
'Channel %s just left our application', channel.name));
console.log(channel.name);
var index = chanArr.indexOf(channel.name);
chanArr.splice(index, 1);
updateSip();
}
client.on('StasisStart', stasisStart);
client.on('StasisEnd', stasisEnd);
client.start('bridge-hold');
}
//Socket.io logic here
server.listen(3009, function () {
console.log('listening on *:3009');
});
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendfile(__dirname + "/testPage.html");
});
io.sockets.on('connection', function (data) {
updateSip();
});
io.sockets.on('muting', function (data) {
mute = data;
console.log("client side:" + mute);
});
function updateSip() {
console.log("Value: " + test);
io.sockets.emit('sip', chanArr);
}

This is how am kicking channels from the bridge.
Am currently working on a Mute & Unmute function, but am having some troubles but this is how I kicked users via the web application
For example.
Client Side
When kick button is clicked emit the data found in TD to the server side
$(document).on('click', '.kick', function () {
var hangup = $(this).closest('td').siblings(':first-child').text();
socket.emit('hangup', hangup);
});
Server Side
Store the data received from client side into a var and then call the stasis function.
io.sockets.on('connection', function (socket) {
updateSip();
socket.on('hangup', function (data) {
hangup(data);
});
});
Stasis function
Kick the channel which you have just passed from client to server side using ARI client commands, user will be kicked and will show in stasis application.
function hangup(hangval) {
console.log("Kicked:" + hangval);
client.channels.hangup
({
channelId : hangval
},
function (err) {
if (err) {
throw err;
}
});
}
Hope this helps.

Related

How to check if the db connection is success or not in node js and mysql

I'm using mysql connection pool to create connection. The code looks like the following.
var pool = mysql.createPool(connectionProps);
by accessing pool, I'll get the an Object, even if the connection is not Successful. I checked it with starting and stopping mysql.
What I want is that, I need to check connection is successful or not as follows.
if(pool){ // mysql is started && connected successfully.
console.log('Connection Success');
doSomething();
}else{
console.log('Cant connect to db, Check ur db connection');
}
I want something like this. So how can we do this with the mysql pool Object. Can someone please help me?
Thanks n Regards
Commonly you would do something like select something arbitrary from the db, and catch an error if that failed. Example from the docs.
const pool = mysql.createPool(connectionProps);
pool.query('SELECT 1 + 1 AS solution', (error, results, fields) => {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
var pool = mysql.createPool(config.db);
exports.connection = {
query: function () {
var queryArgs = Array.prototype.slice.call(arguments),
events = [],
eventNameIndex = {};
pool.getConnection(function (err, conn) {
if (err) {
if (eventNameIndex.error) {
eventNameIndex.error();
}
}
if (conn) {
var q = conn.query.apply(conn, queryArgs);
q.on('end', function () {
conn.release();
});
events.forEach(function (args) {
q.on.apply(q, args);
});
}
});
return {
on: function (eventName, callback) {
events.push(Array.prototype.slice.call(arguments));
eventNameIndex[eventName] = callback;
return this;
}
};
}
};
And require to use it like:
db.connection.query("SELECT * FROM `table` WHERE `id` = ? ", row_id)
.on('result', function (row) {
setData(row);
})
.on('error', function (err) {
callback({error: true, err: err});
});

Callback isn't called

I use the following code and it seems that the callback (Which start with Im HERE) is not called, any idea why?
console.log("im starting");
process.start(function() {
//this line doesnt called
console.log("im HERE");
server.listen(app.get('port'), function(err) {
if (err) {
console.error(err);
} else {
console.log(' listen to: ' + app.get('port'));
}
});
});
the method start are called and finish ...any idea what it can be ?
before ive added the process.start the code look like following:
And this works OK, now I need to add this process.start and when it finish to do the server.listen
module.exports = (function() {
server.listen(app.get('port'), function(err) {
if (err) {
console.error(err);
} else {
console.log('listen ' + app.get('port'));
}
});
}());
UPDATE
This is the code of process start
exports.start = function () {
Validator.validateJson(function (err) {
console.log(err);
process.exit(1);
});
plugin.parse().then(function (conf) {
require.cache.pe.configObj = conf;
}, function (err) {
console.log(err);
});
envHandler.eventE.on('AppP', function () {
console.log('User port ' + require.cache.per);
});
var run= function () {
return Promise.all([
childPro.create(path.join(value)),
childPro.findAndUpdateUser()
]).spread(function (cmd,updatedAppEnv) {
return Promise.all([childProc.executeChildProcess('exec', cmd, updatedAppEnv), Promise.delay(50).then(function (results) {
return inter.ProcessRun(val);
})]);
})
}();
}
I use promise lib like bluebird if its matter in this case
It's a bit unclear where you want to call the callback. In short, change the start function to accept a callback parameter and call callback() when you are done (or pass it at end as argument to then).
exports.start = function (callback) {
Validator.validateJson(function (err) {
console.log(err);
process.exit(1);
});
plugin.parse().then(function (configObj) {
if (typeof require.cache.persist === 'undefined') {
require.cache.persist = {};
}
require.cache.persist.configObj = configObj;
}, function (err) {
console.log(err);
});
envHandler.eventEmitterIns.on('AppPortDef', function () {
console.log('User port ' + require.cache.persist.port);
});
var run= function () {
return Promise.all([
childPro.create(path.join(value)),
childPro.findAndUpdateUser()
]).spread(function (cmd,updatedAppEnv) {
return Promise.all([childProc.executeChildProcess('exec', cmd, updatedAppEnv), Promise.delay(50).then(function (results) {
return inter.ProcessRun(val);
})]);
})
}();
run.then(callback);
}

Calling async function befrore server start to listen

I've node app and I want to call to function before the server is start,my questions are:
what is the recommended why to do it ?
does that can have an issue (that I call to some async function before the server is up)
Btw I use bluebird
This is my code
//This is the function which I want to call before
process.beforeProc();
//Before I start the following server
http.createServer(app).listen(app.get('port'), function (err) {
if (err) {
console.error(err);
} else {
console.log('listening on port ' + app.get('port'));
}
});
**UPDATE**
The preProcess look like following
exports.beforeProc= function () {
run.validate(function (err) {
console.log(err);
process.exit(1);
});
Parser.parse().then(function (con) {
//Cache the path values to serve new requests
if (typeof require.cache.persist === 'undefined') {
require.cache.persist = {};
}
require.cache.persist.con = con;
}, function (err) {
console.log(err);
});
.....
I don't have 50 rep so I made an answer:
Does process.beforeProc() have a callback?
If so you can do it like this:
process.beforeProc(function() {
// Once the beforeProc loaded it will return the callback, so whats
// in here
http.createServer(app).listen(app.get('port'), function (err) {
if (err) {
console.error(err);
} else {
console.log('listening on port ' + app.get('port'));
}
});
});

Control when ARI function is called using JQuery/socket.io

So I currently have two functions which are called when I add a call to a bridge, and two functions within that get called automatically, so am trying to use JQuery so they only get called when a button is clicked, and then I can work from there in the server side of things.
It may have be an issue with using both ARI client and socket.io together, am not too sure am still learning as am going along.
Issue being at the moment an error gets thrown up saying $ isnt defined.
JQuery does work I have another file am calling which is all JQuery and handles my socket.io client side.
$("#mute").click(function () {
alert("Handler for .click() called.");
channel.mute({
channelId : 111
},
function (err) {});
});
$("#kick").click(function () {
alert("Handler for .click() called.");
channel.hangup({
channelId : 111
},
function (err) {});
});
As anyone any experience using both or even have any suggestion as to how I can do this.
Full code listing;
var ari = require('ari-client');
var util = require('util');
var chanArr = [];
var test;
var mute;
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
//ARI client
ari.connect('http://localhost:8088', 'asterisk', 'asterisk', clientLoaded);
function clientLoaded(err, client) {
if (err) {
throw err;
}
// find or create a holding bridges
var bridge = null;
client.bridges.list(function (err, bridges) {
if (err) {
throw err;
}
bridge = bridges.filter(function (candidate) {
return candidate.bridge_type === 'mixing';
})[0];
if (bridge) {
console.log(util.format('Using bridge %s', bridge.id));
} else {
client.bridges.create({
type : 'mixing'
}, function (err, newBridge) {
if (err) {
throw err;
}
bridge = newBridge;
console.log(util.format('Created bridge %s', bridge.id));
});
}
});
// handler for StasisStart event
function stasisStart(event, channel) {
console.log(util.format(
'Channel %s just entered our application, adding it to bridge %s',
channel.name,
bridge.id));
channel.answer(function (err) {
if (err) {
throw err;
}
bridge.addChannel({
channel : channel.id
}, function (err) {
var id = chanArr.push(channel.name)
console.log("Value: " + test);
test = channel.name;
updateSip);
if (err) {
throw err;
}
//If else statement to start music for first user entering channel, music will stop once more than 1 enters the channel.
if (chanArr.length <= 1) {
bridge.startMoh(function (err) {
if (err) {
throw err;
}
});
} else if (chanArr.length === 2) {
bridge.stopMoh(function (err) {
if (err) {
throw err;
}
});
} else {}
});
});
$("#mute").click(function () {
alert("Handler for .click() called.");
channel.mute({
channelId : 111
},
function (err) {});
});
$("#kick").click(function () {
alert("Handler for .click() called.");
channel.hangup({
channelId : 111
},
}
// handler for StasisEnd event
function stasisEnd(event, channel) {
console.log(util.format(
'Channel %s just left our application', channel.name));
console.log(channel.name);
var index = chanArr.indexOf(channel.name);
chanArr.splice(index, 1);
updateSip();
}
client.on('StasisStart', stasisStart);
client.on('StasisEnd', stasisEnd);
client.start('bridge-hold');
}
//Socket.io logic here
server.listen(3009, function () {
console.log('listening on *:3009');
});
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendfile(__dirname + "/testPage.html");
});
io.sockets.on('connection', function (data) {
updateSip();
});
io.sockets.on('muting', function (data) {
mute = data;
console.log("client side:" + mute);
});
function updateSip() {
console.log("Value: " + test);
io.sockets.emit('sip', chanArr);
}
The error saying $ isnt defined would be jQuery not being available. If we could see more of the code as its structured on the page, why it is not available would be more clear.

Issue with Implementing callback in node.js code

I have this node.js function process() which is supposed to return a value when called. I am facing issue with creating a callback for my process(). The value should return from process() only after it gets response back from ec2.runInstances(params, function(err, data) call.
------------- Snippet from app.js (express.js)--------------------
var createEngine = require('./ec2_create.js');
app.get('/create', function (req, res) {
res.render('create', {
status: createEngine.process()
});
});
------------------------Code snippet from ec2_create.js -----------------------
function process(callback) {
var status = null;
// Create the instance
ec2.runInstances(params, function (err, data) {
if (err) {
//console.log("Could not create instance", err);
status = "Could not create instance: " + err;
} else {
var instanceId = data.Instances[0].InstanceId;
//console.log("Created instance", instanceId);
status = "Created instance: " + instanceId;
}
});
callback(status);
};
module.exports.process = process;
Try as follows
function ec2process(callback){
var status = null;
// Create the instance
ec2.runInstances(params, function(err, data) {
if (err) {
//console.log("Could not create instance", err);
status = "Could not create instance: " + err;
}
else{
var instanceId = data.Instances[0].InstanceId;
//console.log("Created instance", instanceId);
status = "Created instance: " + instanceId;
}
callback(status); // Callback moved
});
};
exports.
process = ec2process
since your process method expects a callback function and does not return a value, you could call it rather like this:
app.get('/create', function (req, res) {
createEngine.process(function(status){
//you're inside the callback and therefor have the status value
res.render('create', {
status: status
});
}):
});
You should move the code which calls the callback into the callback for runInstances:
function process(callback) {
var status = null;
// Create the instance
ec2.runInstances(params, function (err, data) {
if (err) {
//console.log("Could not create instance", err);
status = "Could not create instance: " + err;
} else {
var instanceId = data.Instances[0].InstanceId;
//console.log("Created instance", instanceId);
status = "Created instance: " + instanceId;
}
callback(status);
});
};

Categories