Chat application using CFWebsocket - coldfusion

How can we develop a facebook like chat application using cfwebsocket. There is no description about how to send an user entered message to the server and how to send that message to a particular client from the server.
<script type="text/javascript">
function mymessagehandler(aevent, atoken)
{
console.log(aevent);
console.log(atoken);
var message = aevent.msg;
var txt=document.getElementById("myDiv");
txt.innerHTML = txt.innerHTML + message +"<br>";
}
</script>
<cfwebsocket name="mycfwebsocketobject" onmessage="mymessagehandler" subscribeto="stocks" >
<cfdiv id="myDiv"></cfdiv>
The above code just prints ok in the display. I am not sure how to pass my message inside the stocks object. Can anyone help on this? Thanks in advance
This is the stocks application that I am using
this.wschannels = [ {name="stocks", cfclistener="myChannelListener" }];

This is what I have did to make my chat application work
This is the chat application
<cfwebsocket name="ChatSocket" onOpen="openHandler" onMessage="msgHandler" onError="errHandler">
This is the script
function openHandler(){
//Subscribe to the channel, pass in headers for filtering later
ChatSocket.subscribe('chatChannel',{name: 'TheUserName', UserID: 'TheUserID', AccountID: 'AnUniqueID' });
}
// function to send the message. we can call this when the user clicks on send message
function publish(userID){
var msg = {
AccountID: "AnUniqueID",
publisher: userID,
id: userID,
message: document.getElementById("Name").value + " : " + document.getElementById("message").value
};
//When including headers, the "selector" is where you will filter who it goes to.
var headers = {
AccountID: "AnUniqueID",
publisher: userID,
id: userID
};
// we can save the chat history by an ajax call here
ChatSocket.publish('chatChannel',msg, headers);
}
// this is the receiving function
function msgHandler(message){
// if condition to display the message to the user who are sending and receiving
if(message.data !== undefined && message.data.message !== undefined && (message.data.id == '#session.userID#' || message.data.publisher == '#session.userID#')) {
var data = message.data.message;
console.log(data);
//showing the message
var txt=document.getElementById("myDiv");
txt.innerHTML+= data + "<br>";
}
}
function errHandler(err){
console.log('err');
console.log(err);
}

Related

Script to send a chat message based on an IF condition in Google Sheets

I'm trying to edit a script that was intended to send an email if column D is checked (true) but instead of sending an email, I now want it to send a chat. I've created a webhook for the chat group, and it is sort of working, but it's sending a message on EVERY edit made to the sheet.
I'm just a high school teacher way out of my depth here. If anyone can help me figure out how to fix the script, I'd be quite grateful.
When I associate my function with the on edit trigger it sends a chat for every action. If I use the on open trigger, it does nothing.
Screenshot of code
function myFunction() {
var WebWhooklink = "link to my group chat goes here"
var message = { text: "Student has returned"};
var payload = JSON.stringify(message);
var options = {
method: 'POST',
contentType: 'application/json',
payload: payload
};
var response = UrlFetchApp.fetch(WebWhooklink, options ).getContentText();
}
function onEdit() {
var s = SpreadsheetApp.getActiveSheet();
if( s.getName() == "Electronic Hall Pass" ) { //checks that we're on Sheet1 or not
var r = s.getActiveCell();
if( r.getColumn() == 1 ) { //checks that the cell being edited is in column A
var nextCell = r.offset(0, 1);
if( nextCell.getValue() === '' ) //checks if the adjacent cell is empty or not?
nextCell.setValue(new Date());
}
}
}
function onEdit2(e) {
if(e.value != "TRUE" ) return;
e.source.getActiveSheet().getRange(e.range.rowStart,e.range.columnStart+2).setValue(new Date());
}
You may try something like this that checks if the edit was made in Column D (the fourth column):
function onEdit(e){
if(e.range.getColumn()==4){
--> Put your function here
}
}
Thanks so much Martin! That fixed it!
function sendMailEdit(e){
if (e.range.columnStart != 4 || e.value != "TRUE") return;
let sName = e.source.getActiveSheet().getRange(e.range.rowStart,1).getValue();
var WebWhooklink = "webhook link to chat goes here"
var message = { text: "Student has returned"};
var payload = JSON.stringify(message);
var options = {
method: 'POST',
contentType: 'application/json',
payload: payload
};
var response = UrlFetchApp.fetch(WebWhooklink, options ).getContentText();
}

API Gateway -> Lambda -> DynamoDB using Cognito. HTTP POST-> Unable to read response but returns a code 200

Scenario:
I query an HTTP POST (using Authorizer as Header parameter from Cognito).
When I try to fetch/read the query response, it triggers the error event. However, in the browser, I can see how 2 HTTP POST responses with 200 code and one of them returning the valid response. For example: if I make the request via POST man I receive the data in 1 response in a good way.
Problem:
I am unable to print the result because it launches the error event with not valid response data.
Browser images:
https://i.postimg.cc/MTMsxZjw/Screenshot-1.png
https://i.postimg.cc/3RstwMgv/Screenshot-2.png
Lambda code:
'use strict';
var AWS = require('aws-sdk'),
documentClient = new AWS.DynamoDB.DocumentClient();
exports.handler = function index(event, context, callback){
var params = {
TableName : "data-table"
};
documentClient.scan(params, function(err, data){
if(err){
callback(err, null);
}else{
console.log(JSON.stringify(data.Items));
callback(null, data.Items);
}
});
}
Client side JS code:
function requestData(pickupLocation) {
$.ajax({
type: 'POST',
url: _config.api.invokeUrl,
headers: {
Authorization: authToken,
},
data: "{}",
cache: false,
success: completeRequest,
error: errorRequest
});
}
function completeRequest(response) {
alert("hello");
alert(response.d);
}
function errorRequest(response) {
alert("hello1");
alert(response.status + ' ' + response.statusText);
}
According to further clarification based on the comments, this looks like API gateway has CORS disabled or enabled with incorrect header value returns.
The solution is to re-enable CORS through API gateway and in the advanced options add Access-Control-Allow-Origin to the header response (if not already on by default).
If you're proxying the response, you need to follow a specific format as described here
'use strict';
console.log('Loading hello world function');
exports.handler = async (event) => {
let name = "you";
let city = 'World';
let time = 'day';
let day = '';
let responseCode = 200;
console.log("request: " + JSON.stringify(event));
// This is a simple illustration of app-specific logic to return the response.
// Although only 'event.queryStringParameters' are used here, other request data,
// such as 'event.headers', 'event.pathParameters', 'event.body', 'event.stageVariables',
// and 'event.requestContext' can be used to determine what response to return.
//
if (event.queryStringParameters && event.queryStringParameters.name) {
console.log("Received name: " + event.queryStringParameters.name);
name = event.queryStringParameters.name;
}
if (event.pathParameters && event.pathParameters.proxy) {
console.log("Received proxy: " + event.pathParameters.proxy);
city = event.pathParameters.proxy;
}
if (event.headers && event.headers['day']) {
console.log("Received day: " + event.headers.day);
day = event.headers.day;
}
if (event.body) {
let body = JSON.parse(event.body)
if (body.time)
time = body.time;
}
let greeting = `Good ${time}, ${name} of ${city}. `;
if (day) greeting += `Happy ${day}!`;
let responseBody = {
message: greeting,
input: event
};
// The output from a Lambda proxy integration must be
// of the following JSON object. The 'headers' property
// is for custom response headers in addition to standard
// ones. The 'body' property must be a JSON string. For
// base64-encoded payload, you must also set the 'isBase64Encoded'
// property to 'true'.
let response = {
statusCode: responseCode,
headers: {
"x-custom-header" : "my custom header value"
},
body: JSON.stringify(responseBody)
};
console.log("response: " + JSON.stringify(response))
return response;
};
If you are using chrome you probably need the cors plugin .

Unable to get work history/ email and other information

I have a list of user id's ( may or may not be my friends) I want to get ALL the public possible information about them.. However, I am only getting back Name, Id and Photo. Where am I going wrong?
FB.login(function(){
/* make the API call */
FB.api(
"/{event-id}/attending",
function (response) {
if (response && !response.error) {
var array = response.data;
array.forEach(function(eachUser){
//console.log(eachUser);
FB.api(
"/"+ eachUser.id,
function (response) {
if (response && !response.error) {
console.log(response);
}
}
);
});
}
}
);
}, {scope: 'user_events, user_education_history , user_about_me , user_work_history , user_location , user_website'}); //,age_range, bio , context , education
Even if it´s set to public, all the other data is only available if the user authorizes your App with the appropriate permission. So in the list of attending users, name/id/photo is the only data you can get.

cfwebsocket cannot find channels

I have just started a project at work using cfwebsockets. When I attempt to subscribe to the channel I set in the Application file <cfset this.wschannels = [{name="notify"}]> I get the following response in chrome:
Object {clientid: 540872586, ns: "coldfusion.websocket.channels", reqType: "subscribe", code: -1, type: "response"…}
clientid: 540872586
code: -1
msg: "Channel 'notify' doesn't exist or is not running."
ns: "coldfusion.websocket.channels"
reqType: "subscribe"
type: "response"
__proto__: Object
Why would it not be finding it? Here is more of my code for reference.
<cfwebsocket name="notify" onOpen="subscribeUser" onMessage="msgHandler" onError="errHandler">
<script>
function errHandler(err){
console.log(err);
}
function msgHandler(message){
var data = message.data;
if(data){
}
}
function subscribeUser(){
console.log(notify);
notify.subscribe("notify",{name: '#Session.Auth.FirstName#',UserID: '#Session.Auth.UserID#',LocationID: '#Session.Auth.LocationID#'});
}
function publish(txt, msgType){
var msg = {message: txt, UserID: '#Session.Auth.UserID#', type: msgType};
var headers = {selector: 'LocationID eq "#Session.Auth.LocationID#"'};
notify.publish('notify',msg, headers);
}
</script>

How to send an alert message to a special online user with firebase

I'm trying to make a "FourConnect"-game with javascript. I want, that there is a list from all online users. This list I've made with the example on the firebase site. Now I want that I can choose one online user and send them a invitation to play with me.
So I wrote a function, that all users expect of me have an additional div. When I click on the div this special user should get a confirm box to say okey or cancel. If the user clicks okey the play should begin.
I'll save the name and the id from the user. This already works.
My problem is, that I don't know how to send the request to the other user. I tried out many but always the confirm box is on my brwoser not on the browser of the other user.
I looked for solutions on the firebase page and in google but couldn't find anything which solves my problem.
The code I already have:
var name = prompt("Your name?", "Guest"),
currentStatus = "★ online";
// Get a reference to the presence data in Firebase.
var userListRef = new Firebase(connectFour.CONFIG.firebaseUrl);
// Generate a reference to a new location for my user with push.
var myUserRef = userListRef.push();
var gameId = myUserRef.name();
document.getElementById('labelGameId').innerHTML = gameId;
beginGame({id: gameId, name: name, status: currentStatus});
// Get a reference to my own presence status.
var connectedRef = new Firebase('http://presence.firebaseio-demo.com/.info/connected');
connectedRef.on("value", function(isOnline) {
if (isOnline.val()) {
// If we lose our internet connection, we want ourselves removed from the list.
myUserRef.onDisconnect().remove();
// Set our initial online status.
setUserStatus("★ online");
} else {
// We need to catch anytime we are marked as offline and then set the correct status. We
// could be marked as offline 1) on page load or 2) when we lose our internet connection
// temporarily.
setUserStatus(currentStatus);
}
});
//}
// A helper function to let us set our own state.
function setUserStatus(status) {
// Set our status in the list of online users.
currentStatus = status;
myUserRef.set({ name: name, status: status });
}
// Update our GUI to show someone"s online status.
userListRef.on("child_added", function(snapshot) {
var user = snapshot.val();
$("#output").append($("<div/>").attr("id", snapshot.name()));
$("#" + snapshot.name()).text(user.name + " is currently " + user.status);
if(snapshot.name() != myUserRef.name()){
var $invite = $('<div id="invite">invite</div>');
$("#output").append($invite);
$($invite).on('click', function(){
//startGame(user);
console.log('Gegner2: '+snapshot.name());
console.log('Genger2Name: '+user.name);
joinGame({id: snapshot.name(), name: user.name, status: user.status});
});
}
});
// Update our GUI to remove the status of a user who has left.
userListRef.on("child_removed", function(snapshot) {
$("#" + snapshot.name()).remove();
});
// Update our GUI to change a user"s status.
userListRef.on("child_changed", function(snapshot) {
var user = snapshot.val();
$("#" + snapshot.name()).text(user.name + " is currently " + user.status);
});
document.onIdle = function () {
setUserStatus("☆ idle");
}
document.onAway = function () {
setUserStatus("☄ away");
}
document.onBack = function (isIdle, isAway) {
setUserStatus("★ online");
}
setIdleTimeout(5000);
setAwayTimeout(10000);
function joinGame(opponent) {
console.log(opponent);
console.log(opponent.id);
var player2ID = opponent.id;
myUserRef = new Firebase(connectFour.CONFIG.firebaseUrl + opponent.id);
myUserRef.once('value', function(dataSnapshot){
if(dataSnapshot.val()){
beginGame({id: player2ID , name: opponent.name, status: opponent.status});
}else{
alert("game doesn't exist");
}
});
}
function beginGame(player) {
console.log(player);
console.log('Id spieler1: '+gameId);
});
With this code I can click on "invite" and then I will see the ID which the user had. I also wanted to send the ID to beginGame() but this doesn't really works.
My Firebase Structure:
games
-InmydEpSe5oZcLZUhfU
-InrLM6uxAsoOayOgFce
-name: "Barbara"
-status: "away"
In order to send a message to another user, you need that user to be monitoring a known location in your Firebase. Then when you want to send them a message, you simply modify that location in some way and they'll get a callback. Here's some pseudo code:
var root = new Firebase(...);
//On initialization start listening for messages
root.child("users/inbound-messages").on("child_added",
function(newMessageSnapshot) {
displaySomethingToTheUser(newMessageSnapshot.val());
newMessageSnapshot.ref().remove();
}
);
//Send a message to another user
root.child(otherUserId).child("inbound-messages").push("Hi other user!");
From what I understand. You want a chat window in the game so that users logged to communicate among themselves, okay?
Well, in its structure, you simply add something like:
-Games
    -rooms
     -charOfRoomSpecific
         - users
            
             + InmydEpSe5oZcLZUhfU
              -InrLM6uxAsoOayOgFce
                     name: "Barbara"
                     status "away"
         
       - messages
           + InmyBlaBlae5oZcLPKSu
           -InmyBlaBlae5oZcLPKSu2
                user: "Barbara"
                say: "Hello man, will gamer!"
     + charOfRoomSpecific2
     + charOfRoomSpecific3
     ...
So, for your users in the room can read the message simply:
FirebaseRef.child ("rooms/charOfYourRoomSpecific/messages");
And everyone who has access to this room will see in real time their conversations.