This.localStream is null - chat

I'm trying to develop and application that allow to a medic and a patient be able to communicate using an Api called connectycube, the chat and video call work, the problem is with to mute sound and video. I have implemented the buttons to mute sound and video, all this using jQuery dialogs, the first time I mute audio or video works, but when I close the dialog finishing the session and then I open the dialog with a new session, to mute audio and video do not work anymore and the message in the console is This.localStream is null
My Source Code:
const CREDENTIALS = {
appId: 'xxxxx',
authKey: 'xxxxx',
authSecret: 'xxxxx'
};
ConnectyCube.init(CREDENTIALS);
//This is a button in a main jquery dialog, this is the beginning of all
{
text: 'VideoCall',
click: function () {
$('#dv_progess').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.createSession().then((session) => {
$('#dv_progess').dialog('close');
signup_user();
$('#dv_videocall').dialog('option', 'position', {my: 'right top', at: 'right top', of: window}).dialog('open');
}).catch((error) => {
console.log('Error=>' + JSON.stringify(error));
$('#dv_progess').dialog('close');
$('#dv_message').html('Error=>' + JSON.stringify(error)).dialog('open');
});
}
},
function signup_user() {
var login = 'P' + $('#hd_idusr').val();
/*Buscar si existe usuario registrado en la API*/
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.users.get({login: login}).then((result) => {
console.log('User Exists:' + result.user.id);
$('#dv_progress').dialog('close');
chat();
}).catch((error) => {
$('#dv_progress').dialog('close');
console.log('User not exists [' + error.info.message + ']');
var password = $('#txt_birthdate').val().replace(/-/g, '') + '*';
var email = $('#hd_email').val();
email = email ? email : login + '#email.com';
const userProfile = {
login: login,
password: password,
full_name: $('#txt_names').val(),
email: email
};
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.users.signup(userProfile).then((data) => {
console.log('ok=>' + data.user.id);
$('#dv_progress').dialog('close');
chat();
}).catch((error) => {
console.log('Error=>' + JSON.stringify(error));
$('#dv_progress').dialog('close');
$('#dv_messages').html('Error=>' + JSON.stringify(error)).dialog('open');
});
});
}
function chat() {
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
var login_patient = 'P' + $('#hd_idusr').val();
ConnectyCube.users.get({login: login_patient}).then((result) => {
$('#dv_progress').dialog('close');
var id_patient = result.user.id;
$('#hd_idpatient').val(id_patient);
const userCredentials = {
login: 'S' + $('#txt_medic').attr('data-id-user'),
password: $('#txt_medic').attr('data-psw')
};
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.createSession(userCredentials).then((session) => {
$('#dv_progress').dialog('close');
console.log(JSON.stringify(session));
console.log('Medic Created session');
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.login(userCredentials).then((user) => {
var id_professional = user.id;
console.log('Medic login succesful=>' + id_professional);
$('#hd_idprofessional').val(id_professional);
const chatCredentials = {
userId: id_professional,
password: $('#txt_medic').attr('data-psw')
};
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.chat.connect(chatCredentials).then(() => {
$('#dv_progress').dialog('close');
console.log('Medic Connected to chat');
console.log('Id Paciente:' + id_patient);
const dialogParams = {
type: 3,
occupants_ids: [id_patient]
};
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.chat.dialog.create(dialogParams).then(dialog => {
$('#dv_progress').dialog('close');
console.log(JSON.stringify(dialog));
console.log('Dialog Created:' + dialog._id);
$('#hd_iddialog').val(dialog._id);
$('#dv_messagearea').prop('contenteditable', true);
$('#btn_sendmsg,#btn_startvideocall,#btn_finishvideocall').prop('disabled', false);
}).catch(error => {
console.log('Error=>' + JSON.stringify(error));
$('#dv_progress').dialog('close');
$('#dv_messages').html('Error=>' + JSON.stringify(error)).dialog('open');
});
}).catch((error) => {
console.log('Error:' + JSON.stringify(error));
$('#dv_progress').dialog('close');
$('#dv_messages').html('Error:' + JSON.stringify(error)).dialog('open');
});
}).catch((error) => {
console.log('Error:' + JSON.stringify(error));
$('#dv_progress').dialog('close');
$('#dv_messages').html('Error:' + JSON.stringify(error)).dialog('open');
});
}).catch((error) => {
console.log('Error=>' + JSON.stringify(error));
$('#dv_progress').dialog('close');
$('#dv_messages').html('Error=>' + JSON.stringify(error)).dialog('open');
});
/*Fin Login Medico*/
}).catch((error) => {
console.log('Error=>' + JSON.stringify(error));
$('#dv_progress').dialog('close');
$('#dv_messages').html('Error=>' + JSON.stringify(error)).dialog('open');
});
}
function onMessage(userId, message) {
console.log('[ConnectyCube.chat.onMessageListener] callback:', userId, message);
var dv_message = $('#dv_messageschat');
dv_message.append('<div><b>Patient:</b>' + message.body + '</div>');
dv_message.scrollTop(dv_message[0].scrollHeight);
}
function isTyPing(isTyping, userId, dialogId) {
console.log("[ConnectyCube.chat.onMessageTypingListener] callback:", isTyping, userId, dialogId);
}
function sendMessage() {
ConnectyCube.chat.sendIsStopTypingStatus($('#hd_idpatient').val());
var mensaje = $('#dv_messagearea').text();
const message = {
type: 'chat',
body: mensaje,
extension: {
save_to_history: 1,
dialog_id: $('#hd_iddialog').val()
},
markable: 1
};
message.id = ConnectyCube.chat.send($('#hd_idpatient').val(), message);
var dv_message = $('#dv_messageschat');
dv_message.append('<div><b>Yo:</b>' + mensaje + '</div>');
dv_message.scrollTop(dv_message[0].scrollHeight);
$('#dv_messagearea').html('');
}
$('#dv_messagearea').keypress(function (e) {
ConnectyCube.chat.sendIsTypingStatus($('#hd_idpatient').val());
setTimeout(function () {
ConnectyCube.chat.sendIsStopTypingStatus($('#hd_idpatient').val());
}, 1000);
if (e.keyCode == 13) {
sendMessage();
return false;
}
});
function startVideo() {
const calleesIds = [$('#hd_idprofessional').val(), $('#hd_idpatient').val()]; /*User's ids*/
const sessionType = ConnectyCube.videochat.CallType.VIDEO;
const additionalOptions = {};
const session = ConnectyCube.videochat.createNewSession(calleesIds, sessionType, additionalOptions);
const mediaParams = {
audio: true,
video: true,
options: {
muted: true,
mirror: true
}
};
session.getUserMedia(mediaParams).then((localStream) => {
console.log(JSON.stringify(localStream));
session.attachMediaStream('vd_video1', localStream);
/*Iniciar la llamada*/
const extension = {};
session.call(extension, (error) => {
console.log(JSON.stringify(error));
});
$('#btn_finishvideocall').on('click', {x: session}, finishCall);
}).catch((error) => {
console.log(JSON.stringify(error));
});
}
function finishCall(e) {
const extension = {};
e.data.x.stop(extension);
/*Clean local stream*/
var videoElem1 = document.getElementById('vd_video1'),
stream1 = videoElem1.srcObject;
if (stream1 != null) {
var tracks = stream1.getTracks();
tracks.forEach(function (track) {
track.stop();
});
videoElem1.srcObject = null;
}
/*Clean remote stream*/
var videoElem2 = document.getElementById('vd_video2'),
stream2 = videoElem2.srcObject;
if (stream2 != null) {
var tracks = stream2.getTracks();
tracks.forEach(function (track) {
track.stop();
});
videoElem2.srcObject = null;
}
}
$('#dv_controllsvideocall').find('button').prop('disabled', true);
$('#btn_mutesound,#btn_mutevideo').hide();
function setSound(e) {
const session = e.data.x;
if (e.data.y == 'mute') {
$('#btn_mutesound').show();
$('#btn_unmutesound').hide();
session.mute('audio');
console.log('muted audio');
} else {
$('#btn_mutesound').hide();
$('#btn_unmutesound').show();
session.unmute('audio');
console.log('unmuted audio');
}
}
function setVideo(e) {
const session = e.data.x;
if (e.data.y == 'mute') {
$('#btn_mutevideo').show();
$('#btn_unmutevideo').hide();
session.mute('video');
console.log('muted video');
} else {
$('#btn_mutevideo').hide();
$('#btn_unmutevideo').show();
session.unmute('video');
console.log('unmuted video');
}
}
function acceptedCall(session, userId, extension) {
console.log('Accepted call');
$('#dv_controllsvideocall').find('button').prop('disabled', false);
}
function setStream(session, userID, remoteStream) {
console.log('stream assigned');
session.attachMediaStream('vd_video2', remoteStream);
$('#btn_mutesound').on('click', {x: session, y: 'unmute'}, setSound);
$('#btn_unmutesound').on('click', {x: session, y: 'mute'}, setSound);
$('#btn_mutevideo').on('click', {x: session, y: 'unmute'}, setVideo);
$('#btn_unmutevideo').on('click', {x: session, y: 'mute'}, setVideo);
}
function onStopCall(session, userId, extension) {
console.log('Finished Call');
}
ConnectyCube.chat.onMessageListener = onMessage;
ConnectyCube.chat.onMessageTypingListener = isTyPing;
ConnectyCube.videochat.onAcceptCallListener = acceptedCall;
ConnectyCube.videochat.onRemoteStreamListener = setStream;
ConnectyCube.videochat.onStopCallListener = onStopCall;
$('#btn_sendmsg').click(function () {
sendMessage();
});
$('#btn_startvideocall').click(function () {
startVideo();
});
$('#btn_exitvideocall').click(function () {
$('#dv_videocall').dialog('close');
});
/*Dialog for video call*/
$('#dv_videocall').dialog({
autoOpen: false,
resizable: false,
height: 600,
width: 220,
modal: false,
close: function () {
$(this).find('input').val('');
$('#dv_messagearea').prop('contenteditable', false).html('');
$('#dv_messageschat').html('');
$('#btn_sendmsg,#btn_startvideocall,#btn_finishvideocall').prop('disabled', true);
$('#dv_controllsvideocall').find('button').prop('disabled', true);
if (ConnectyCube.chat.isConnected) {
$('#btn_finishvideocall').trigger('click');
ConnectyCube.chat.disconnect();
ConnectyCube.logout().catch((error) => {
console.log('logout=>' + JSON.stringify(error));
});
ConnectyCube.destroySession().catch((error) => {
console.log('destroySession=>' + JSON.stringify(error));
});
}
}
});
$(window).bind('beforeunload', function () {
if (ConnectyCube.chat.isConnected) {
$('#btn_finishvideocall').trigger('click');
ConnectyCube.chat.disconnect();
ConnectyCube.logout().catch((error) => {
console.log('logout=>' + JSON.stringify(error));
});
ConnectyCube.destroySession().catch((error) => {
console.log('destroySession=>' + JSON.stringify(error));
});
}
});
I think the problem is in the function finishCall() when I clean the video tag and I don't know if that is the right way to free the resources. Despite this the chat and video call still work.
If someone has experience please help me, becasue I didn't found any solution, thanks in advance.

Related

I have problems with the connection of dialogflow cx and firestore database

can someone help me with dialogflow cx webhooks and add data to Firestore, this is my index.js code but it does not store in the database. Thanks
Hello, can someone help me with dialogflow cx webhooks and add data to Firestore, this is my index.js code but it does not store in the database. Thanks
const Firestore = require('#google-cloud/firestore');
const PROJECTID = 'ia-proyecto';
const firestore = new Firestore({
projectId: PROJECTID,
timestampsInSnapshots: true,
});
exports.db_datos_personales = (req, res) => {
function replaceAll(string, search, replace) {
return string.split(search).join(replace);
}
console.log('Dialogflow Request body: ' + JSON.stringify(req.body));
let tag = req.body.fulfillmentInfo.tag;
console.log('Tag: ' + tag);
console.log('Session Info Parameters: ' + JSON.stringify(req.body.sessionInfo.parameters));
//
if (tag === 'nombre') {
const COLLECTION_NAME = 'Datos_Personales';
let Nombre_Usuario = replaceAll(JSON.stringify(req.body.sessionInfo.parameters['nombre_usuario']), '"', '');
let Ciudad_Usuario = replaceAll(JSON.stringify(req.body.sessionInfo.parameters['ciudad_usuario']), '"', '');
console.log('Nombre usuario: ' + Nombre_Usuario);
console.log('Ciudad usuario: ' + Ciudad_Usuario);
const data = {
Nombre_Usuario: Nombre_Usuario,
Ciudad_Usuario: Ciudad_Usuario,
};
console.log(JSON.stringify(data));
var answer = 'Welcome to the Cloud Audio family, '+ Nombre_Usuario +'! Enjoy our services.';
return firestore.collection(COLLECTION_NAME)
.set(data)
.then(doc => {
return res.status(200).send({
fulfillmentResponse: {
messages: [{
text: {
text: [answer]
}
}]
}
});
}).catch(err => {
console.error(err);
return res.status(404).send({ error: 'unable to store', err });
});
//
} else if (tag === 'pregunta') {
const COLLECTION_NAME = 'Pregunta_Usuario';
let pregunta_usuario = replaceAll(JSON.stringify(req.body.sessionInfo.parameters['pregunta_usuario']), '"', '');
console.log('Pregunta Usuario: ' + pregunta_usuario);
const data = {
pregunta_usuario: pregunta_usuario
};
console.log(JSON.stringify(data));
var answer = 'Your plan has been changed to the '+ pregunta_usuario + ' service.';
return firestore.collection(COLLECTION_NAME)
.doc(phone_number)
.update(data)
.then(doc => {
return res.status(200).send({
fulfillmentResponse: {
messages: [{
text: {
text: [answer]
}
}]
}
});
}).catch(err => {
console.error(err);
return res.status(404).send({ error: 'unable to update field', err });
});
}
};
I hope to have a solution, since I was more than a week and I can't find anything.

Problem with facebook login from the facebook application

I also encounter a problem with a project, login with facebook works on absolutely any browser, even those on mobile, but in the integrated browser in the facebook application it doesn't work, it just doesn't connect me, it sends me back to login ... can you help me with a piece of advice please? Thank you.
I used this script:
<script>
(function(){
var body = $('body');
var socialLoginErrorElm = $('#loginError');
var loginModal = $('#loginModal');
body.on('social-login:error', function(e, error) {
socialLoginErrorElm.removeClass('hide').html('<div class="alert alert-danger">' + error + '</div>');
loginModal.removeClass("logging-in");
});
window.loginWithFb = function(){
FB.login(function(response) {
if (response.authResponse) {
if(response.authResponse.grantedScopes.split(',').indexOf('email') < 0) {
//If email permission not granted
body.trigger('social-login:error', (__('fbNoEmailError')));
return;
}
FB.api('/me', {fields: 'id,name,email'}, function(response) {
console.log('Logged in as ' + response.name + '.');
//Dual check email - needed to if check if the user has a verified email ID
if(!response.email) {
body.trigger('social-login:error', (__('fbNoEmailError')));
return;
}
body.trigger('loggedIn:fb');
});
} else {
body.trigger('social-login:error', (__('fbPermissionError')));
}
}, {
scope: 'email',
auth_type: 'rerequest',
'return_scopes': true
});
}
var body = $('body');
body.on('click', '[data-action="loginWithFB"]', function(e){
loginWithFb();
e.preventDefault();
});
body.on('loggedIn', function(){
loginModal.modal('hide');
});
body.on('loggedIn:fb', function(){
if(!User.isLoggedIn()) {
$.get(BASE_PATH + '/login/fb').success(function(response){
User.setData(response.user);
}).fail(function(jqXHR, textStatus, errorThrown){
body.trigger('social-login:error', jqXHR.responseText);
}).always(function(){
loginModal.removeClass("logging-in");
});
}
});
body.on('prompt-login', function(e, message){
loginModal.find('.login-prompt-message').html(message);
loginModal.modal('show');
});
})();
function showNewPointsAlert(addedPoints) {
var alertOptions = {
title: "+"+ addedPoints +" " + __('points'),
text: __('earnedNewPointsMessage'),
imageUrl: "{{LeaderboardHelpers::getPointsIcon()}}",
confirmButtonText: __('earnedNewPointsOkayBtnText'),
allowEscapeKey: true,
allowOutsideClick: true,
customClass: 'new-points-alert'
}
#if(!empty($mainBtnColor))
alertOptions.confirmButtonColor = '{{{$mainBtnColor}}}';
#endif
swal(alertOptions);
}
$('body').on('user-activity-recorded', function() {
$.get('{{route('getMyPoints')}}').success(function(response) {
if(response && response.points) {
var oldPoints = parseInt(User.data.points);
var newPoints = parseInt(response.points);
User.data.points = newPoints;
User.setData(User.data);
if(oldPoints != newPoints) {
var animateClass = 'animated bounceIn';
$('#headerUserMenu').removeClass(animateClass).addClass(animateClass);
var addedPoints = parseInt(newPoints) - parseInt(oldPoints);
#if(MyConfig::isTrue('leaderboard.showNewPointsAlert'))
showNewPointsAlert(addedPoints);
#endif
}
}
}).fail(function() {
});
});
</script>

How to fix "_filePath.includes is not a function. ( In '_filePath.includes('&'), '_filePath.includes' is undefined)" in React Native?

I am trying to upload an image to Firebase Storage, however, ref.putfile() leads to the error in the tittle
I didn't find any appropriate resource related to this error
This is where I get image from user:
openPicker = () => {
// More info on all the options is below in the API Reference... just some common use cases shown here
const options = {
title: 'Fotoğraf Seç',
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
const source = { uri: response.uri}
this.setState({
imageMessageSrc: source
});
this.uploadImage();
}
});
}
Then I try to uploadImage to firebase
uploadImage = () => {
console.log("Here");
const filename = this.randIDGenerator// Generate unique name
firebase
.storage()
.ref(`${firebase.auth().currentUser.uid}/sentPictures/${filename}`)
.putFile(this.state.imageMessageSrc)
.then(() => {
console.log("Here1");
})
.catch((error) => {
console.log(error);
})
When I delete putFile, error is gone, but obviously nothing happens to database.
Problem is related to the difference between filePath and fileUri. So, the solution is as below:
openPicker = () => {
const options = {
title: 'Fotoğraf Seç',
storageOptions: {
skipBackup: true,
path: 'images',
allowsEditing: true,
},
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ',response.customButton);
}
else {
var path = '';
if (Platform.OS == 'ios')
path = response.uri.toString();
else {
path = response.path.toString();
}
const image= {
image: response.uri.toString(),
path: path
};
this.uploadImage(image);
}
});
}
uploadImage = (image) => {
firebase.storage().ref(uploadUrl).putFile(image.path);
}
I realized that Firebase Storage putFile function doesn't work with image uri, instead it should be supplied with filePath. I used uri of this image to directly show image on the screen even before upload.

Callback is not a function NODEJS

I am trying learn nodejs and stumble upon this error
callback(null, removed);
TypeError: callback is not a function
It is a Steam trade bot, so when it send me an offer, I accept it but after that it crashes. What is wrong?
exports.removeOweNoTitle = (user, callback) => {
let file = 'data/users/' + user + '.json';
if(fs.existsSync(file)) {
let read = fs.createReadStream(file);
let data = "";
read.on('data', (chunk) => {
data += chunk;
});
read.on('end', () => {
let json;
try {
json = JSON.parse(data);
} catch(error) {
return callback(error);
}
let owe = {};
if(json.owe)
owe = json.owe;
else {
callback(null, 0);
return;
}
let removed = 0;
for(let game in owe) {
if(owe[game]) {
removed += owe[game];
owe[game] = 0;
}
}
let write = fs.createWriteStream(file, {flags: 'w'});
exports.clearNotifications(user, () => {
write.write(JSON.stringify(json), (error) => {
if(error)
return callback(error);
write.end();
});
return;
});
write.write(JSON.stringify(json), (error) => {
if(error)
return callback(error);
write.end();
});
write.on("finish", (callback, error) => {
callback(null, removed); //tady nebyl deklarován callback chyběl
});
});
} else {
generateUserFile(user);
callback(new Error('User\'s file is not defined!'), null);
}
}

Append firebase JWT in Ember-simple-auth

I am trying to do authorization in my Ember App(2.10). My workflow is
user hit the button of Facebook login then
i'm using torii to get the access token /my user database is on firebase/
Then i send token to firebase.auth with facebook provider. It returns JWT token.
Problem is i got the JWT token and now i have to login to my emberapp. I am trying to customize torii authenticator here. How can i implement this in ember app. Below is my authenticator:
authenticate() {
return this._super(...arguments).then((torii) => {
const serverTokenEndpoint = this.get('serverTokenEndpoint');
return this.get('ajax').request(serverTokenEndpoint, {
type: 'POST',
data: {
'type': torii.provider,
'client_id': this.client,
'token': torii.authorizationCode
}
}).then((token) => {
var provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives Facebook Access Token.
// JWT-token=result.user.Cd
// JWT-token.iat at=result.user.ea.Sa
// JWT-token-refresh = result.user.refreshToken
console.log(result)
// token = result.user.Cd;
// const expiresAt = this._absolutizeExpirationTime(result.user.ea.Sa);
token = Ember.assign(token, { 'expires_at': result.user.ea.Sa });
// this._scheduleAccessTokenRefresh(result.user.ea.Sa, expiresAt, result.user.refreshToken, torii);
return Ember.assign(token, {'torii': torii});
});
});
});
}
Check out this guide in the ESA repo. It covers torii and Github auth but the general concepts are the same for your use case.
#marcoow I did try this and it authenticate but when token is expired i can not refresh token.Seems it is not the right approach, How can i refresh token using firebase
export default ToriiAuthenticator.extend({
torii: Ember.inject.service(),
ajax: Ember.inject.service(),
refreshAccessTokens: true,
rejectWithResponse: false,
restore(data) {
return new RSVP.Promise((resolve, reject) => {
const now = (new Date()).getTime();
const refreshAccessTokens = this.get('refreshAccessTokens');
if (!isEmpty(data['expires_at']) && data['expires_at'] < now) {
// if (refreshAccessTokens) {
this._refreshAccessToken(data['expires_in'], data['refresh_token']).then(() => {
resolve();
}).catch(function(error) {
reject();
});
// } else {
// reject();
// }
} else {
if (!this._validate(data)) {
reject();
} else {
this._scheduleAccessTokenRefresh(data['expires_in'], data['expires_at'], data['refresh_token']);
resolve(data);
}
}
});
},
authenticate() {
return new Ember.RSVP.Promise((resolve, reject) => {
var provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithPopup(provider).then((result) => {
var expires_in = this._absolutizeExpirationTime(result.user.ea.Sa);
var expiresAt = result.user.ea.Sa;
result = Ember.assign(result, { 'expires_at': expiresAt, 'expires_in': expires_in, 'access_token': result.user.Cd, 'refresh_token': result.refresh_token });
resolve(result)
});
// const useResponse = this.get('rejectWithResponse');
// const provider = new firebase.auth.FacebookAuthProvider();
// firebase.auth().signInWithPopup(provider).then((result) => {
// let expires_in = result.user.ea.Sa;
// const expiresAt = this._absolutizeExpirationTime(expires_in);
// this._scheduleAccessTokenRefresh(expires_in, expiresAt, result.refresh_token);
// if (!isEmpty(expiresAt)) {
// result = Ember.assign(result, { 'expires_at': expiresAt, 'expires_in': expires_in, 'access_token': result.user.Cd, 'refresh_token': result.refresh_token });
// }
// // resolve(result);
// }, (response) => {
// Ember.run(null, reject, useResponse ? response : response.responseJSON);
// }).catch(function(error) {
// console.log(error);
// });
});
},
invalidate(data) {
const serverTokenRevocationEndpoint = this.get('serverTokenRevocationEndpoint');
return new RSVP.Promise((resolve) => {
if (isEmpty(serverTokenRevocationEndpoint)) {
resolve();
} else {
if (!Ember.isEmpty(data.access_token)) {
delete data.access_token;
firebase.auth().signOut();
resolve();
}
}
});
},
_scheduleAccessTokenRefresh(expiresIn, expiresAt, refreshToken) {
console.log('sched')
const refreshAccessTokens = this.get('_refreshAccessTokens');
if (refreshAccessTokens) {
const now = (new Date()).getTime();
if (isEmpty(expiresAt) && !isEmpty(expiresIn)) {
expiresAt = new Date(now + expiresIn * 1000).getTime();
}
const offset = this.get('tokenRefreshOffset');
if (!isEmpty(refreshToken) && !isEmpty(expiresAt) && expiresAt > now - offset) {
run.cancel(this._refreshTokenTimeout);
delete this._refreshTokenTimeout;
if (!testing) {
this._refreshTokenTimeout = run.later(this, this._refreshAccessToken, expiresIn, refreshToken, expiresAt - now - offset);
}
}
}
},
_refreshAccessToken(expiresIn, refreshToken) {
console.log('refresh');
const data = { 'grant_type': 'refresh_token', 'refresh_token': refreshToken };
firebase.auth().currentUser.getToken(/ forceRefresh / true).then((response) => {
return new RSVP.Promise((resolve, reject) => {
// firebase.auth().currentUser.getToken(true).then((response) => {
expiresIn = response.user.ea.Sa || expiresIn;
refreshToken = response.refresh_token || refreshToken;
const expiresAt = this._absolutizeExpirationTime(expiresIn);
const data = assign(response, { 'expires_in': expiresIn, 'expires_at': expiresAt, 'refresh_token': refreshToken });
this._scheduleAccessTokenRefresh(expiresIn, null, refreshToken);
this.trigger('sessionDataUpdated', data);
resolve(data);
}, (response) => {
warn(`Access token could not be refreshed - server responded with ${response.responseJSON}.`);
reject();
});
});
},
_absolutizeExpirationTime(expiresIn) {
if (!isEmpty(expiresIn)) {
return new Date((new Date().getTime()) + expiresIn * 1000).getTime();
}
},
_validate(data) {
return !isEmpty(data['access_token']);
}
});