setting parameter in firebase functions - firebase

Hi i am using below code in index.js. Here i want to set one value in "Default welcome intent" and i want to take in "Test Intent". How to do this. I want to pass this value in background and i want to use it
"use strict";
exports.__esModule = true;
var functions = require("firebase-functions");
var gApp = require("actions-on-google");
var WebhookClient = require('dialogflow-fulfillment').WebhookClient;
var _a = require('dialogflow-fulfillment'), Card = _a.Card, Suggestion = _a.Suggestion;
var app = gApp.dialogflow({ debug: true });
process.env.DEBUG = 'dialogflow:debug';
//exports.dialogflowSample = functions.https.onRequest((request, response) =>
//{
app.intent('Default Welcome Intent', function (conv, input) {
conv.ask("Welcome to my dialogFlow agent!");
});
app.intent('Test Intent', function (conv, input) {
conv.ask('<speak>Testing the application' + ("<say-as >" + input + "</say-as></speak>"));
conv.ask('<speak>Testing the application' + "<say-as >" + qNo + "</say-as></speak>");
});
exports.dialogflowSample = functions.https.onRequest(app);
//});

Related

How to disable automatically signin after create new user in Firebase?

The admin can only add a new user. My problem is when I created a new user, it automatically signin that user then it signouts the admin.
FYI. I didn't use the Admin SDK. Firebase
My code:
var password = $('#row' + x + 'cell1').val();
var fname = $('#row' + x + 'cell2').val();
var email = teacherID + "#gmail.com";
console.log(email + password);
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
//Add to users table
var pushedUser = firebase.database().ref('users/' + user.uid).set({ role: "Teacher",
fullname: fname });
//Add name and default dp to the Authorization table
user.updateProfile({
displayName: fname,
photoURL: "default_dp",
});
var $rowFirst = $("table:first").find("tr:first");
var $rowNext = $('#tblCSVaccounts tr').eq(x);
//get all td's in row
var $tdsFirst = $rowFirst.find("td");
// loop all td
$.each($tdsFirst, function(i, el) {
//get value of each td
var txtEntity = $(this).find("input").val();
var $rowNext = $('#tblCSVaccounts tr').eq(x);
var $tdsNext = $rowNext.find("td:eq(" + i + ")");
$.each($tdsNext, function(i, el) {
//get value of each td
var txtValue = $(this).find("input").val();
//Update in database
const mySection = $('#sectionUpload').val();
var pushedRef = firebase.database().ref('Teachers/' + user.uid).update({ [txtEntity]: txtValue });
$('#alert-success').removeClass('hide');
});
});
}, function(error) {
// An error happened.
var errorCode = error.code;
var errorMessage = error.message;
});
you can use firebase.auth().onAuthStateChanged(...)
hope its help you, guy!

Firebase Cloud Functions - return undefined

This is the code that I am using to fetch the senderName and messageText from my database. In my logs, I am getting an error saying "Function returned undefined, expected Promise or value". I am using this function to send notifications to the recevier of the message. The notification is being sent appropriately.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPushNotification = functions.database.ref('/messages/{messageId}').onWrite(event => {
var db = admin.database();
var messageText;
var senderName;
var receiverId;
var senderId;
var messageId = event.params.messageId;
var messageTextRef = db.ref('/messages/' + messageId + '/text');
var senderIdRef = db.ref('/messages/' + messageId + '/fromId');
var receiverIdRef = db.ref('/messages/' + messageId + '/toId');
messageTextRef.once("value", function(data) {
messageText = data.val();
senderIdRef.once("value", function(data) {
senderId = data.val();
receiverIdRef.once("value", function(data) {
receiverId = data.val();
var senderNameRef = db.ref('/users/' + senderId + '/name');
senderNameRef.once("value", function(data) {
senderName = data.val();
console.log(senderName);
console.log(messageText);
const payload = {
notification : {
title: String(senderName),
body: String(messageText),
badge: "1",
sound: 'default',
}
};
return admin.database().ref('fcmToken').once('value').then(allToken => {
if (allToken.val()) {
const token = Object.keys(allToken.val());
return admin.messaging().sendToTopic(receiverId, payload).then(response => {
});
};
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
});
});
You have a monster function there. If you return the outermost Promise when you are getting all the database values that should fix the issue, and also ensure that your function is not stopped before all computation is complete. In your case this is on line ~25:
...
return messageTextRef.once("value", function(data) {
...

Firebase Request Timeout Feature [duplicate]

I'm trying to create a cloud function for firebase that remove a user depending on the delay value and insert back the after the number of delay.
exports.delayqueue = functions.database.ref('/queues/{queueid}/members/{memberid}').onWrite(event => {
var members = event.data.ref.parent;
var user = event.data;
var queueid = members.parent;
var userid = event.params.memberid;
var delayfor = user.child('delay').val();
var name = user.child('name').val();
if(delayfor != 0){
members.child(event.params.memberid).remove();
join(userid,queueid,delayfor,name);
return;
}else{
return;
}
});
function join(userid,queueid,delayfor,name){
setTimeout(function(){
var ref = db.ref("queues/queueid/members/userid");
ref.set({
name: name,
timestamp: Date.now(),
delay : 0
});
}, delayfor*1000);
};
But it's not working can someone help?
You'll need to wrap your setTimeout in a Promise:
exports.delayqueue = functions.database.ref('/queues/{queueid}/members/{memberid}').onWrite(event => {
var members = event.data.ref.parent;
var user = event.data;
var queueid = members.parent;
var userid = event.params.memberid;
var delayfor = user.child('delay').val();
var name = user.child('name').val();
if (delayfor !== 0){
members.child(event.params.memberid).remove();
return join(userid,queueid,delayfor,name);
} else {
return;
}
});
function join(userid,queueid,delayfor,name){
return new Promise((resolve, reject) => {
setTimeout(function(){
var ref = db.ref("queues/queueid/members/userid");
ref.set({
name: name,
timestamp: Date.now(),
delay : 0
}).then(resolve, reject);
}, delayfor*1000);
});
};
Note that the time spent waiting for setTimeout is billed as function execution time and is also subject to the function timeout. If you're only delaying a few seconds, that might be okay, but if the delay is expected to be minutes this solution isn't going to be viable or cost-effective.

Firebase infinite loop insert my item on child_added/set

I got an infinite loop inserting an item to my Firebase, so when I click on my post form, it inserts my item until I kill the process. Can you help me how to solve it?
PS : I'm using VueJS
var usersRef = new Firebase('https://xxxxxxxxxxxxxxxxxx.firebaseio.com/userslist/');
var vm = new Vue({
el: '#list1',
data: function () {
return{
// Initialisation du tableau de users
users: [],
sortKey: 'id',
reverse: 1,
nextKey: null
};
},
ready: function () {
// this works
//this.sortKey = 'name';
},
methods: {
updateUsers: function () {
},
removeUser: function (item) {
usersRef.child(item.id).remove();
},
addItem: function (e) {
e.preventDefault();
// get form data as Json
var jsonData = ConvertFormToJSON('form_add');
//console.log(jsonData);//test ok
//get the last item id and save it to next key
usersRef.limitToLast(1).on('child_added', function (snapshot) {
var lastKey = parseInt(snapshot.key());
this.nextKey = lastKey + 1;
console.log('nextKey ' + nextKey);//test ok
//
// save data to firebase
usersRef.child(this.nextKey).set(jsonData, function (snap) {
//console.log('add success');//test
//Notification par Jquery
var itemAdded = snap.val();
$.notify(itemAdded.firstname + " " + itemAdded.name + " à été ajouté", "success", {position: "top right"});
this.pendingKey = 0;
});
});
},
// Tri des colonnes
sortBy: function (_sortKey) {
this.reverse = (this.reverse == -1) ? 1 : -1;
this.sortKey = _sortKey;
console.log("SortKey " + this.sortKey);
}
}
});
usersRef.on('child_added', function (snapshot) {
var item = snapshot.val();
item.id = snapshot.key();
console.log('id ' + item.id);
vm.users.push(item);
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
thanks for your help
OK I've found a solution :
//get the last item id and save it to next key
var _nextKey = this.nextKey;
usersRef.limitToLast(1).on('child_added', function (snapshot) {
var lastKey = parseInt(snapshot.key());
_nextKey = lastKey + 1;
});
this.nextKey = _nextKey;
console.log('nextKey ' + this.nextKey);//test ok
// save data to firebase
usersRef.child(this.nextKey).set(jsonData, function (snap) {
//console.log('add success');//test
//Notification par Jquery
var itemAdded = snap.val();
$.notify(itemAdded.firstname + " " + itemAdded.name + " à été ajouté", "success", {position: "top right"});
});
May it help someone!

What is wrong with my download of a zip file from an ASP ApiController with AngularJS?

I'm trying to do the following:
The user fill a form and send it in .JSON to the server
With the form, the server generate some .CSV files and put them all together in a .ZIP file.
The server send the .ZIP file and the user download it.
After some research I have wrote this code:
My Controller:
[HttpPost]
[Route("routeToMyAPI")]
public HttpResponseMessage Process(Form form)
{
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(<streamToMyGeneratedZipFile>)
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "fileName.zip"
};
return result;
}
My Service:
angular.module('app')
.factory('MyService', function ($http) {
return {
Process: function (form) {
var req = $http.post('rest/example/process', form);
return req;
}
};
});
My Controller:
this.submit = function () {
var Form = {};
var formPost = MyService.Process(Form);
formPost.then(function (data) {
var a = document.createElement('a');
var blob = new Blob([data], { 'type': "application/octet-stream" });
a.href = URL.createObjectURL(blob);
a.download = "fileName.zip";
a.click();
}, function (error) {
alert('An error occured !');
});
};
I have parts 1 & 2 working, but I don't have find the way to call my ASP API to download the .ZIP file.
When I call the submit method of my Controller, I have a fileName.zip who is downloaded on my PC but when I try to open it Windows says to me that it's not a valid archive.
What did I do wrong ? I'm a rookie in angularjs and ASP so any help will be welcomed.
Thanks in advance.
Several issues with your code:
After ZipArchive does its work, the position of the stream will be at the end. So you must reset it to the beginning like this before sending it:
zipStream.Position = 0;
Since you're setting the content type and file name of the file on the server already, just parse it on the client side.
var headers = data.headers(); //$http resolves to data, status, headers, config
var regex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var match = regex.exec(headers["content-disposition"]);
var fileName = match[1] || "myZipFile.zip";
fileName = fileName.replace(/\"/g, ""); //replace trailing and leading slashes
var contentType = headers["content-type"] || "application/octet-stream";
IE will not allow you to open blobs directly. You must use msSaveOrOpenBlob or msSaveBlob.
var blob = new Blob([data.data], { type: contentType });
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
var a = document.createElement('a');
var objectUrl = URL.createObjectURL(blob);
a.href = URL.createObjectURL(blob);
a.download = match[1];
a.click();
}
One last thing: the previous code won't work on firefox because firefox doesn't support clic(). Thanks to this thread this can be solved by adding this little snippet of code:
HTMLElement.prototype.click = function() {
var evt = this.ownerDocument.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
}

Resources