Credential should be scoped to a valid region when creating AWS-chime meeting - aws-serverless

let meetingId = null;
let meeting = null;
let clientId = 2017;
meetingId = uuid();
var region = await getNearestMediaRegion();
const chime = new AWS.Chime({ region: region });
chime.endpoint = new AWS.Endpoint('https://service.chime.aws.amazon.com');
meeting = await chime.createMeeting({
ClientRequestToken: meetingId,
MediaRegion: region,
ExternalMeetingId: meetingId,
}).promise();
const attendee = await chime.createAttendee({
MeetingId: meeting.Meeting.MeetingId,
ExternalUserId: `${uuid().substring(0, 8)}#${clientId}`,
})
.promise();
let res = { meeting, attendee };
I've created meeting using Amazon chime SDK in Serverless refer following example
example
OUTPUT:

Remove following line from your code:
chime.endpoint = new AWS.Endpoint('https://service.chime.aws.amazon.com');

Related

How to create a firebase cloud function that writes data to every 'user' node in firebase realtime database

I am attempting to write a firebase function that creates new data nodes for every user in the database, but i just can't seem to get it to work.
Database structure:
I wish to add additional days to the TimeSlots node, through this function
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var database = admin.database();
exports.addTimeNode = functions.database.ref('/message/{id}').onCreate((snapshot, context) =>
{
var root = firebase.database().ref();
var db = root.child('Users').child('Barbers');
db.once('value', function(snapshot)
{
snapshot.forEach(function(data)
{
//var reqStatus = data.val().request_status;
var uid = data.key;
root.child('User').child(uid).child(TimeSlots).once('value', function(userSnapshot)
{
var now = new Date().toDateString();
database.ref('/Users/Barbers/' + uid + '/TimeSlots/'+ now +'/9am').set({
availability: 'Available',
id: '01',
time: '09:00 AM'
});
database.ref('/Users/Barbers/' + uid + '/TimeSlots/'+ now +'/9:30am').set({
availability: 'Available',
id: '02',
time: '09:30 AM'
});
...
Maybe you can try this way:
By the way I am not a big fan of using snapshot.key instead I add the value of UID in the node itself with a child node named as id and it would stay below firstName node in your case. Won't take long for you too adjust your code to add ID there as well along with adding the first name.
const allBarbersSnapshot = await admin.database().ref(`/users/barbers/`).once('value').then(function (snapBarbers: any) {
snapBarbers.forEach((eachBarber: any) => {
const currentBarberId = eachBarber.val().id
admin.database().ref(`/users/barbers//${currentBarberId}/TimeSlots/${now}/${yourTimeVariableHere}`).update({ "availability": 'Available', "id": 1, "time": yourTimeVariableHere })
});
//Anything after above stuff is done goes here !!!
})
If you have any questions, drop a comment below ;)
PS: All the above code goes inside your Cloud Function

How to pull data from inside arrays in firestore

So I have a main field EmailFrom and inside it has arrays with some info of their own.
I am trying to pull this data from firestore but I am not sure how to go about it.
Here is how I am pulling data currently
var user = firebase.auth().currentUser.uid;
let cityRef = db.collection("Users").doc(user);
let getDoc = cityRef
.get()
.then((doc) => {
if (!doc.exists) {
console.log("No such document!");
} else {
console.log("Document data:", doc.data());
let z = 0;
for (z = 0; z < 5; z++) {
let data = doc.data();
let emailBody = data.EmailBody;
let emailsubject = data.EmailSubject;
let emailSubject = emailsubject[z];
let olddate = data.EmailDate;
let oldDate = olddate[z];
let emailDateYear = new Date(oldDate).getFullYear();
let emailDateMonth = new Date(oldDate).getMonth();
let emailDateDay = new Date(oldDate).getDate();
let emailfrom = data.EmailFrom;
let emailFrom = emailfrom[z];
console.log(olddate);
so basically I am trying to use the data.EmailFrom[arrayNumber] method to pull the data in my current setup but because this data is like further inside the array I am not sure how to access it. Tried searching online and cannot find much to help me on this one. Any help would be appreciated =]
The following should do the trick:
const data = doc.data();
const address = data.EmailFrom[0].value[0].address;

Reading data out of datastore with dialogflow

I'm doing a chatbot similar to helpdesk (Dialogflow - inline editor). I'm able to write to datastore but I`m facing some issues with read out of data, it is a basic operation of finding UserID but code is not kicking off -please help code below.
const Datastore = require('#google-cloud/datastore');
const datastore = new Datastore({
projectId: 'bot-datastore-mnddjv'
});
function write(agent) {
var name = agent.parameters.name;
var sur = agent.parameters.sur;
var uid = agent.parameters.uid;
const taskKey = datastore.key('Key');
const entity = {
key: taskKey,
data: {
name: name,
sur: sur,
uid: uid
}
};
return datastore.save(entity).then(() => {
console.log(`Saved ${entity.key.name}: ${entity.data.item_name}`);
agent.add(`Stored ${name},${sur}`); -----> That part is working
});
}
function read(agent){
const query = datastore.createQuery('Key').filter('name');
return datastore.runQuery(query).then(() =>{
const sortA = query.order('name');
const sortD = query.order('name',( {descending:true}));
agent.add("Scores: ",sortA); ----// This funcion is not working
});
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('Zapis', write);
intentMap.set('Odczyt', read);
agent.handleRequest(intentMap);
});
The issue seems to be in your usage of filter().
You need to use an operator like =, > etc. so if that condition is met the query will run.
Here is a sample code from the documentation.
const query = datastore
.createQuery('Task')
.filter('done', '=', false)
.filter('priority', '>=', 4)
.order('priority', {
descending: true,
});

How To Store DialogFlow all the Parameter Value On Realtime Firebase Database?

I am making a action for Google Home. It's about restaurant booking so I have to take some information from users like:
How many guests do you want to book the table for?
For which date?
For which time?
Then I have to store it on Firebase real time database. For the guests parameter it is writing the value to the database but the date and time parameters are not showing on database.
what will be code for storing both time and date with guests in database?
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
//initialize db connection
const admin = require('firebase-admin');
admin.initializeApp();
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
function createBooking(agent) {
let guests = agent.parameters.guests;
let time = new Date(agent.parameters.time);
let date = new Date(agent.parameters.date);
let bookingDate = new Date(date);
bookingDate.setHours(time.getHours());
bookingDate.setMinutes(time.getMinutes());
let now = new Date();
const guestsParam = agent.parameters.guests;
if (guests < 1){
agent.add('You need to reserve a table for at least one person. Please try again!');
} else if (bookingDate < now){
agent.add(`You can't make a reservation in the past. Please try again!`);
} else if (bookingDate.getFullYear() > now.getFullYear()) {
agent.add(`You can't make a reservation for ${bookingDate.getFullYear()} yet. Please choose a date in ${now.getFullYear()}.`);
} else {
let timezone = parseInt(agent.parameters.time.toString().slice(19,22));
bookingDate.setHours(bookingDate.getHours() + timezone);
agent.add(`You have successfully booked a table for ${guests} guests on ${bookingDate.toString().slice(0,21)}`);
agent.add('See you at the restaurant!');
}
return admin.database().ref('/guests').push({guests: guests}).then((snapshot) => {
console.log('database write successful: ' + snapshot.ref.toString());
});
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('restaurant.booking.create', createBooking);
// intentMap.set('your intent name here', yourFunctionHandler);
// intentMap.set('your intent name here', googleAssistantHandler);
agent.handleRequest(intentMap);
});
Well, the simple answer is that you don't see them in the database because you don't put them there.
The line
admin.database().ref('/guests').push({guests: guests})
Just stores a document with the guests. You don't do anything with bookingDate.

How to join data from multiple locations in your Firebase DB?

I have an index of notification ids associated with a user X. When I want to display these notifications I need to fetch them from the user X's notifications index which just contains the
a) id of the notification (nid)
b) status: "read/unread"
But I also need to go to
a) /notifcations/nid to get my notification data: text and fromUser
b) /users/fromUser to get the user data for that user
My question is about structure.
Did i structure my data properly and if so, how can I fetch all this information inside the Notification and when ready, present it to angular for displaying on the screen.
Here is my take on that below. Any critique (code/structure/anything) is welcome. Thanks.
P.S.
Also if I am replacing POJOs in firebaseArray with instances of Notification, how would that affect my DB when I say edit the notification and save it back to Firebase. How does AngularFire know what to save back?
/* Notifications */
.factory('Notifications', function(firebaseUrl, NotificationsFactory){
var ref = new Firebase(firebaseUrl);
return {
getNotificationsForUser : function(uid){
var userNotifRef = ref.child('users').child(uid).child('notifications');
return new NotificationsFactory(userNotifRef);
}
}
})
.factory('NotificationsFactory', function($firebaseArray, Notification) {
return $firebaseArray.extend({
$$added : function(snapshot, prevChild){ //called anytime a 'child_added' event occurs
return new Notification(snapshot);
}
})
})
.factory('Notification', function(firebaseUrl, $q, Users) {
var notifRef = (new Firebase(firebaseUrl)).child('notifications');
var usersRef = (new Firebase(firebaseUrl)).child('users');
var mainDeferred = $q.defer();
var notifDeferred = $q.defer();
var userDeferred = $q.defer();
var Notification = function(snapshot){
this.$id = snapshot.key();
this.status = snapshot.val().status;
this.message = null;
this.from = null;
this.to = null;
notifRef.child(this.$id).once('value', function(snap){ //change to on if expect notification to keep updating
var data = snap.val();
this.message = data.message;
this.from = data.from; //user id
this.to = data.to; //user id
notifDeferred.resolve();
});
notifDeferred.promise.then(function(){
this.from = Users.getUser(this.from);
this.to = Users.getUser(this.to);
this.from.$loaded().then(function(){
this.to.$loaded().then(function(){
mainDeferred.resolve();
})
})
})
};
Notification.prototype.ready = function(){
return mainDeferred.promise;
}
return Notification;
})

Resources