Get twilio call status at client side javascript - twilio-api

I am working twilio client JavaScript. I successfully placed a voice call to specific number but i want to know whether or not call is cancelled, unanswered and other status
if(Twilio) {
Twilio.Device.setup(token);
Twilio.Device.ready((device:any) => {
console.log('Twilio.Device Ready!');
});
Twilio.Device.error((error:any) => {
console.log('Twilio.Device Error: ' + error.message);
// setShowInCallMenu(!showInCallMenu);
setIsCallConnected(false);
});
Twilio.Device.connect((conn:any) => {
console.log('Successfully established call!');
setIsCallConnected(true);
setStartTimestamp(moment());
handleRecording(true);
});
Twilio.Device.disconnect((conn:any) => {
console.log('Call ended.');
setIsCallConnected(false);
handleRecording(false);
//toggleCaller()
onNativeCallback(
{
'code':4001,
'message':'Call Ended'
}
);
});
}
webhook doesn't solve this problem all. I need the status of the call. another way would be make a separate call to callSid endpoint and get information about call but in that case it wont gave details like whether call is not answered or cancelled

Related

How to display API data using fetch on Dialogflow GUI

I want to display data from OMDB API on Dialogflow GUI but it's not happening. Data is being displayed fine on Google Cloud Console.
function infoHandler(agent){
let movieName = agent.parameters.movie;
agent.add(`The information for ${movieName} is as follow`);
fetch('http://www.omdbapi.com/?apikey=e255decd%20&s='+ movieName)
.then(result => result.json())
.then((json) => {
let id = json.Search[0].imdbID;
fetch('http://www.omdbapi.com/?apikey=e255decd%20&i=' + id)
.then(result => result.json())
.then((json) => {
agent.add(json.Title + json.Plot + json.imdbRatinng);
return;
}).catch((ex) => {
console.log(ex);
});
})
.catch((e) => {console.log(e);});
The issue is that fetch() causes an asynchronous operation. However, there is nothing that indicates to the Dialogflow handler dispatcher that it is asynchronous and that it should wait for it to complete before sending back a reply. To do that, you'd need to return a Promise.
Fortunately the then/catch chain that you have that are built off the fetch() return a Promise. So all you need to do is return the Promise that they have. This is as simple, in your case, by placing a return before the fetch() call. So it would look something like this:
return fetch('http://www.omdbapi.com/?apikey=e255decd%20&s='+ movieName)
// Other lines remain the same

Google Action Webhook Inline Editor Returns Before the API call

This is my first Google Action project. I have a simple slot after the invocation. User enters the value on prompt and slot invokes the webhook and make a call to API using the user input. All works fine. However the webhook returns to users even before the API call finish processing and returns the value (line 1 conv.add). I do see in the logs that everything from API is logged fine after the webhook returns to user. Below is the code I am using. I am using inline editor. What am I missing? Thanks for help in advance.
const { conversation } = require('#assistant/conversation');
const functions = require('firebase-functions');
var https = require('https');
const fetch = require('node-fetch');
const app = conversation({debug: true});
app.handle('SearchData', conv => {
const body = JSON.stringify({
val: "this is my body"
});
// prepare the header
var postheaders = {
'Content-Type' : 'application/json',
'Auth' : 'MyAuthCreds'
};
fetch('https://host.domain.com/data', {
method: 'post',
body: body,
headers: postheaders,
})
.then(res => res.json())
.then(d => {
console.log(d);
var profile = d;//JSON.parse(d);
console.log(d.entries);
console.log("Length: "+ d.entries.length);
if(d.entries.length > 0)
{
console.log("Data found");
conv.add("Data found"); //line 1
}
else
{
console.log("no data found");
conv.add("no data found"); //line 1
}
})
.catch(function (err) {
// POST failed...
console.log(err);
});
});
exports.ActionsOnGoogleFulfillment = functions.https.onRequest(app);
Your issue is that your handler is making API calls which are asynchronous, but the Assistant Conversation library doesn't know that you're doing so. So as soon as the handler finishes, it tries to send back a response, but your asynchronous responses (the stuff in the then() blocks) haven't executed yet.
To address this, you need to return a Promise object so the library knows to wait till the Promise is fulfilled before it returns.
Fortunately, in your case, this should be pretty straightforward. fetch and all the .then() blocks return a Promise. So all you need to do is add a return statement in front of the call to fetch. So something like this:
return fetch('https://host.domain.com/data', {

Call recursive function in Observable not working in ionic3

I have one function in my app getServerData() which I call from home page and passing Token as param in my API calling in this function.
if Token is valid API will return data otherwise it will return unauthorised access with token expired error at that time I am calling same function with new generated token form another API but some how recursive function calling not working in Observable.
Check below code for more detail :
/**
* Get Search result from server.
*/
getServerData(searchText: string): Observable<any> {
let self = this;
return Observable.create(function(observer) {
self.getToken().then((token) => {
console.log('Token : ', token);
self.httpPlugin.get(self.url + searchText, {}, {}).then((response) => {
console.log("Response Success : " + JSON.stringify(response));
observer.next(jsonResponse);
}).catch(error => {
if (error.status == 403) {
//Call Same method Again
self.getServerData(searchText);
} else {
console.log("Error : " + error);
console.log("Error " + JSON.stringify(error));
observer.error(error);
}
});
}).catch((error) => {
observer.error(error);
console.log("Error : " + error);
})
});
}
While calling same function no code execution done.
Edit based on comment:
I am subscribe like below:
this.subscription = this.api.getServerData(this.searchString.toUpperCase()).subscribe((response: any) => {
console.log("back with data :-",response);
}, error => {
console.log("InLine Error : ",error);
});
Not able to understand whats going wrong or Am I doing some mistake in calling function from Observable().
Guide me on this.
Thanks in advance!
It's not good practice to use promise in observable. Use Obserable.fromPromise and also use mergeMap. What will happen if you will use. Whenever any error will come Observable will throw error and you will able to catch. I will suggest to use Subject rather than creating your own observable and also remember one thing that don't subscribe in your service.
Hope it will help
Finally after lots of research I found solution of my issue.
1st thing was I need to update my rxjx library as my installed version of rxjx was 5.5.2 so I upgraded it to latest one 5.5.11.
2nd thing was I am calling Observable without subscribe() to that Observable so it will never return so I updated my recursive call from error block from where I call its subscriber() like below.
getSearchData(){
this.subscription = this.api.getServerData(this.searchString.toUpperCase()).subscribe((response: any) => {
console.log("back with data :-",response);
}, error => {
if (response.status == 403) {
this.getSearchData();
}else{
console.log("InLine Error : ",response);
this.showAlert('Error', 'Something went wrong. please try again.');
}
});
}
By doing above 2 things I am able to solve my issue.
Thanks all for your quick reply on my issue.
Hope this will help someone who is facing same issue like me.

Handling JWT token expiration in a React based application?

We are in the process of building a web based application, using React and making use of a REST based server. The question that came up is how to best manage a previously authenticated connection becoming unauthenticated and whether there are any React or React/Redux design patterns for this?
Previous designs had used sessions, but since the REST server is meant to be stateless, the current REST server design will probably look at follows:
POST /auth/authenticate --> Authenticate and provides a token
DELETE /auth/token --> Invalidates the token, black-list token
PUT /auth/token --> Renews token, if still valid
GET /auth/token --> Indicates if token is still valid
On the client side the current draft design is to wrap the fetch function with our own function for dealing with checking the response state and then either calling a client side service for invalidating state and redirecting to login page or doing the same thing with Redux. We are also looking to add an interval timer to check the token we have and then automatically do the same thing if the 'exp' field is present and past.
The function we have at this point is (it does not take care of revalidation of token, at this point, to prevent an activate 'session' expiring):
function handleFetchResponse(fetchResponse) {
let newResponse;
try {
return fetchResponse.then((response) => {
newResponse = response;
const contentType = response.headers.get('content-type');
if (contentType && contentType.indexOf("application/json") !== -1) {
return response.json();
} else if (response.status === 200) {
return response.blob();
} else {
if (response.status === 401) {
forceLogout();
}
throw new RequestError(response.statusText, response.status);
}
}).then((responseBody) => {
if (newResponse.status === 401) {
forceLogout();
return;
} else if (newResponse.status !== 200) {
if (responseBody) {
throw new RequestError(
responseBody.details ||
newResponse.statusText,
newResponse.status
);
}
throw new RequestError(newResponse.statusText, newResponse.status);
}
return responseBody;
});
} catch (error) {
console.error('handleFetchResponse:error', error);
return Promise.resolve(err)
.then((err) => {
throw err;
})
}
}
It would be called via:
return handleFetchResponse( fetch(...) );
Is this an acceptable design or are they ways to improve on this?

How can I send a success status to browser from nodejs/express?

I've written the following piece of code in my nodeJS/Expressjs server:
app.post('/settings', function(req, res){
var myData = {
a: req.param('a')
,b: req.param('b')
,c: req.param('c')
,d: req.param('d')
}
var outputFilename = 'config.json';
fs.writeFile(outputFilename, JSON.stringify(myData, null, 4), function(err) {
if(err) {
console.log(err);
} else {
console.log("Config file as been overwriten");
}
});
});
This allows me to get the submitted form data and write it to a JSON file.
This works perfectly. But the client remains in some kind of posting state and eventually times out. So I need to send some kind of success state or success header back to the client.
How should I do this?
Thank you in advance!
Express Update 2015:
Use this instead:
res.sendStatus(200)
This has been deprecated:
res.send(200)
Just wanted to add, that you can send json via the res.json() helper.
res.json({ok:true}); // status 200 is default
res.json(500, {error:"internal server error"}); // status 500
Update 2015:
res.json(status, obj) has been deprecated in favor of res.status(status).json(obj)
res.status(500).json({error: "Internal server error"});
In express 4 you should do:
res.status(200).json({status:"ok"})
instead of the deprecated:
res.json(200,{status:"ok"})
Jup, you need to send an answer back, the simplest would be
res.send(200);
Inside the callback handler of writeFile.
The 200 is a HTTP status code, so you could even vary that in case of failure:
if (err) {
res.send(500);
} else {
res.send(200);
}