Update chat with MySQL on JavaScript event - javascript

I'm trying to make a chat system where anyone can go into the chat and send a message. The messages are stored in a MySQL database and my code looks like this at the moment ...
<script>
$('input[type=text]').on('keydown', function(e) {
if(e.which == 13) {
e.preventDefault();
$.ajax({
url: "php/chat.class.php",
data: { steamid: "<?php echo $steamprofile['steamid']?>", message: document.getElementById("chatMessage").value },
type: "GET",
context: document.body
}).done(function() {
alert("Message sent");
// This is when the chat should update for everyone
}).error(function() {
document.getElementById('chat-box').innerHTML += '<span class="text-muted"><i>Could not send chat message at this time.</i></span>';
});
}
});
Basically, it inserts a new row into the MySQL table once you press enter.
As it is a chat for everyone, I need the chat to update for every user when anyone sends a message.
I know how to display all the messages and who sent them, but I need it to update whenever someone sends a message, for everyone.
I've done research but I can't find anything useful unfortunately and now I'm clueless.
I've thought of updating the chat every x seconds, but I want to make the chat as smooth and fast as possible and wondering what the best solution would be.
Have a good day

So that is a read operation, and hence what you are trying is a write operation. Either you can do a continuous lookup to the server with a interval/timeout/ or initiate a rest call when last call was finished (success/error/timeout whatever). but better approach for this will be initiating a WebSocket Client and create and set up WebSocket Server in your backend and design it properly, so if it get any message from any client it will send that to all other client or something optimizer/ or something in schedule

Consider using a realtime database like Firebase https://firebase.google.com/docs/database/web/start and on your client side you can listen to messages being added using something like:
commentsRef.on('child_added', function(data) {
addCommentElement(postElement, data.key, data.val().text, data.val().author);
});
With firebase you can create a serverless chat application.

Related

Teams proactive messages and Graph API token

I'm trying to build a bot that sends proactive user recommendations regularly. They look similar to this one:
I have it all working in terms of user data coming from the backend, but I also want to add some additional things coming from the Graph API - one of which is the profile picture.
I've setup an Azure Bot Channel, got the Graph auth sample running, but I still can't figure how to mix the proactive messages with the OAuthPrompt dialog.
If I make the user sign in upon app registration, can I reliably get the graph token and use it in my proactive message handler? Note that these messages are going to be sent on a weekly basis. I'm afraid that the token is going to expire.
Has anyone done something similar?
If you just need the bot to make a call to Graph and retrieve user data, you can use Application Permissions to do this without having the user log in. First, you will need to enable the permissions in Azure Active Directory>App registrations>API permissions. The particular ones you need here is User.Read.All (or User.ReadWrite.All if you might want it to have write access for other use cases). There are also separate permissions for Group and Contact if you need that.
For the bot, you first need to get the token. There's a whole reference article here (which includes the app permissions as described above). The client ID and secret are the values for your application. So in javascript I do something like
var identityUrl = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
var formData = `client_id=${clientId}&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret=${clientSecret}&grant_type=client_credentials`
try {
var idResponse = await request({
url: identityUrl,
method: 'POST',
headers: {'Content-Type': 'application/x-www-urlencoded;charset=UTF-8'},
form: formData
});
var token = JSON.parse(idResponse).access_token;
} catch (err) {
await step.context.sendActivity(`Sorry, something went wrong. Please try again later.`);
console.log(err.message);
return step.endDialog();
}
I've got a lot going on where I'm making an actual call to graph, but my http call looks like this:
var userResponse = await request({
url: usersUrl + queryString,
method: 'GET',
headers: {'Authorization':`Bearer ${token}`, 'ConsistencyLevel':'eventual'}
});
userResponse = JSON.parse(userResponse);
Now in your case you're calling the Get Photo endpoint, which I haven't done, but should be basically the same as the above. Here is a link for the Get photo documentation. So now, you bot should be able to authenticate and grab the picture before sending the proactive message, without any need for the user to ever give any credentials.

XMPP chat architecture

I am currently connecting to an external XMPP server (not mine). Since I couldn't find any XMPP PHP client which suits my needs, I have developed my own simple client (XMPP PHP). The client opens a socket connection to the server and that is where the XML exchange happens, and that part works well.
The main reason for developing this package was to integrate it within a corporate app. I have done so and can successfully send messages back and forth.
Even though my end goal is to have an open websocket connection, currently the program works by polling the server in 2s interval (I am using a simple 1on1 communication, no chat rooms or similar):
receiveMessages: function () {
this.poll = setInterval(function () {
Ext.Ajax.request({
url : 'index.php',
method : 'post',
params : {
method: 'receiveMessages',
},
scope : this,
callback: function (options, success, response) {
...
}
});
}, this.pollTimer);
}
And on the PHP side:
public function receiveMessages()
{
$messages = $this->client->getMessages();
if ($messages) {
foreach ($messages as $message) {
$message = $this->xml2array($message);
$conversation = $this->conversationExists($message['#attributes']['from']);
if ($conversation == null) {
$preparedConversation = array(
...
);
$conversation = $this->_save($preparedConversation ...);
}
$message = array(
...
);
$response = $this->_save($message ...);
return array(
'success' => true,
'response' => $response,
);
}
}
}
Upon success, this method updates frontend with the received message, as well as saves the message to the DB. DB is organized in a way that one User can have many Conversations and one Conversation can have many Messages.
What I fail to understand though is how should everything be structured in order to function like some of the real chat clients (Facebook or other messengers), because this way I can't get the "concurrency" I want. If I log in with my account on 2 different places, each of them will poll the server every 2s, and it is basically a race condition, first one to get the message will display it.
If I think about it, one way to do it properly would be to implement websockets to server, and have frontend wait for DB changes, however I think this may create much read overhead on DB. Can someone give me some advice on how to do this?

How can I use PHP & NodeJS for realtime notifications?

I need to be able to get realtime notifications once a PHP script has finished, Im using jQuery, PHP, AJAX, nodeJS.
I send some stuff via AJAX to the PHP script, I need to be able to notify the user when this script starts (simple) but I need to be able to use nodeJS to notify when it’s finished.
AJAX Script
$(document).ready(function($) {
$('.rules-table').on('click', '.runRule', function(event) {
event.preventDefault();
/* Act on the event */
var ruleID = $(this).parents('tr').attr('id');
$.ajax({
url: '/ajax/run-rule.php',
type: 'POST',
dataType: 'json',
data: {
ruleID: ruleID
},
})
.done(function(data) {
console.log(data);
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
});
Sends to a PHP script which does a load of processing (could take a while)
so I need to access NodeJS from here to notify the user it's running, then notify when it's finished. How can i?
When Ajax makes request to php at the starting store sessionid and request id to any database like redis and Use NodeJs with Socket.io for sending real time notifications. In your PHP code create a function like below where $data is the information and $requestId is the id of the ajax request. And in your nodeJs code get the session id regarding that requestId and emit the message to be diplayed.
public static function sendSocketMessage($data, $requestId) {
$url = 'http://' . url . ':3000/publish?salt=<some_salt>';
$curl = new \skeeks\yii2\curl\Curl();
$curl->setOption(CURLOPT_POSTFIELDS, json_encode(array(
'id' => $requestId,
'message' => $data,
)));
$curl->setOption(CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
));
return $curl->post($url);
}
The best way to go is to implement a messaging service in nodeJS. Basicaly a messaging service is a service where client can subscribe to some sort of events. Also another client can push events to the service (so this event can be delivered to subscribed client).
It's quite standard these days. Most online messaging services works that way (Pusher, Pubnub, etc) so by implementing this model in your node app, you'll be able later to outsource the realtime part to a 3rd-party service.
The delivering can be done using socket.io (which already implement a subscribing and room pattern). The publishing can be any endpoint (a socket.io special message, a REST endpoint, whatever express can handle out of the box).

How to get last conversations in xmpp chat server using javascript

I am new to XMPP. I have created a xmpp chat application using javascript. As of now, i am able to send and receive messages from or to the users using the following code.
jQuery.xmpp.connect({
url: url,
jid: sessionUserId,
password: password
onConnect: function ()
console.log("Xmpp Connected");
jQuery.xmpp.setPresence(null);
},
onPresence: function (presence) {
},
onMessage: function (message) {
}
});
Now I need to get last 20 conversations between two users.I had referred history in this link, and i have no idea how to use it. How can we do that. Please help me. Thanks in advance!

Strophe Message Sent Acknowledgment Issue

I have implemented OPENFIRE with XMPP + BOSH on my Web based client interface.
When i am sending the message ,i check whether connection is live or not.If it is not live i create new connection and then send.
Sometimes it happens that client send a message and it is not get delivered to server(not opposite client).
So for that i need a strong thing that should inform client that this message didn't reach to server,please send again.
try { // sleep(2000);
Gab.connection.send(message); >
**var request = $msg({
to: jid,
"type": "get",
id: mid
}).c('get', {
'xmlns': Strophe.NS.DISCO_INFO,
'id': mid
});**
console.log(request); >
} catch (err) {
alert("Internet Disconnected ! Click ok to Reconnect SEND");
window.top.location.reload(1);
}
On above code i call message send().After that i call function as mentioned in "XMPP:xep-0184" doc.
but no response i received.
Thank you in advance.
Not sure what a "strong thing" is, but when someone is disconnected in Strophe, you should get errors from the script and it will update the Strophe.Status connection state. Strophe sends a post every 60 secs (unless otherwise specified). In your code it appears you're trying to check support.
You should look for "Strophe.Status.CONNECTED" or "Strophe.Status.ATTACHED" prior to sending if that's your concern. You can also write a handler to manage the errors.
In XEP 0184, you must include:
<request xmlns='urn:xmpp:receipts'/>
So your msg should look like (note, you must include an id per XEP 0184):
$msg({
to: tojid,
from: fromjid,
type: "chat",
id: "sometrackingid"}).c('body').t("bodytxt").up().c("request", {
xmlns: "urn:xmpp:receipts"});
You will then need to modify you message handler or create a separate handler to manage the receipts.

Categories