So, im making a project for a subject, and i have a file (weather.js) that publishes two variables, one in local/temperature and another in local/time. I'm making a file that subscribes to both of them and operates with the values (blinds.js), but it mixes them. I send temperature and the hour at the same time, and in the subscriber it gives the 1st value to the temperature local variable (inside blinds.js) and then to the time local variable. What can i do?
Here's the weather.js file.
//Variables
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://localhost:1884')
var topic_temp = 'local/temperature'
var topic_time = 'local/time'
//Publisher (topic)
client.on('connect',() => {
setInterval(() => {
console.log('--------------------');
//creating random temperatures between -5 and 5
var temperature = Math.floor((Math.random() * 30) + 5);
var msg1 = temperature.toString();
//sending the temperature values
client.publish(topic_temp,msg1);
console.log('Temperature is ' + msg1 + 'ºC');
//Console log sent message
console.log('Temperature sent!');
setTimeout(function(){
//creating random time value 24h format
var time = Math.floor((Math.random() * 24));
var msg2 = time.toString();
//sending time value
client.publish(topic_time,msg2);
console.log('Time is ' + msg2 + 'h');
//Console log sent message
console.log('Time sent!');
console.log('--------------------');
}, 3000);
},15000)
})
And this is the blinds.js file.
//Variables
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://localhost:1884')
var topic_sub1 = 'local/temperature'
var msg1 = false;
var topic_sub2 = 'local/time'
msg2 = false;
var topic_post = 'appliances/blinds'
var blinds = false;
//Subscribing to the topic_sub1
client.on('connect',() => {
client.subscribe(topic_sub1)
})
//Receiving temp messages
client.on('message',(topic_sub1,temperature) => {
if (msg2 == false) {
msg1 = true;
temp = temperature.toString();
console.log('--------------------');
console.log(temp + 'ºC');
}
})
//Subscribing to the topic_sub2
client.on('connect',() => {
client.subscribe(topic_sub2)
})
//Receiving time messages
client.on('message',(topic_sub2,times) => {
if (msg1) {
msg2 = true;
time = times.toString();
console.log(time + 'h');
console.log('--------------------');
blind();
}
})
//blinds function
function blind() {
if (temp > 28 || time < 9) {
blinds = true;
console.log('Blinds are CLOSED');
}else if (temp > 28 || time > 19){
blinds = true;
console.log('Blinds are CLOSED');
}else{
blinds = false;
console.log('Blinds are OPEN');
}
//sending the temperature values
client.publish(topic_post,blinds.toString());
msg2 = false;
msg1 = false;
}
You can't add multiple client.on('message') listeners, there can only be one.
So just add an if statement in the callback to check what topic the message arrived on.
client.on('message', (topic, message) => {
if (topic == topic_sub1) {
//handle temp
} else if ( topic == topic_sub2) {
//handle time
}
})
Related
What is working
I created a node https/websocket server using WebSocket-Node. Here a snippet on how I add key/cert :
import WebSockerServer from "websocket";
import fs from "fs";
const httpsSignalServer = https.createServer(
{
key: fs.readFileSync("./server.private.key"),
cert: fs.readFileSync("./server.crt"),
},
(req, res) => {
console.log("signal server : we have received a request");
}
);
const signalWebsocket = new WebSockerServer.server({
httpServer: httpsSignalServer,
});
signalWebsocket.on("request", (request) => onRequest(request));
httpsSignalServer.listen(8080, () => console.log("My signal server is listening"));
I have a React html web page that sends data to server above with WebSocket web api via wss :
new WebSocket("wss://192.168.230.138:8081");
My react app runs in an https server. So far everything works.
What is not working
The problem is my little node websocket client. I am still using WebSocket-Node. The client documentation shows a tlsOptions to be given to the constructor.
Client code snippet:
var WebSocketClient = require("websocket").client;
var fs = require("fs");
const tlsOptions = {
key: "./server.private.key",
cert: "./server.crt",
};
var client = new WebSocketClient({
key: fs.readFileSync(tlsOptions.key),
cert: fs.readFileSync(tlsOptions.cert),
});
.
.
.
client.connect("wss://localhost:8080/", "");
The client returns the message :
Error: unable to verify the first certificate
Is there anyone out there who knows how to do the client setup with the tlsOptions?
Thank you
I wrote a perfectly functional simple chat script which is using secured connection. I added a couple of simple chat commands to enable or disable the chat from entering commands in chat.You could use this if you like or parts of it or even just see how I did it. Hope you find some use for it.
var maxLength = 100; // chars per chat
const port = 1441;
var JoinLeaveMsg = 1
var fs = require('fs');
const HTTPS = require('https');
const WebSocket = require('ws');
const server = new HTTPS.createServer({
cert: fs.readFileSync('C:/Certbot/live/MyDomain.com/cert.pem'),
key: fs.readFileSync('C:/Certbot/live/MyDomain.com/privkey.pem')
});
const wss = new WebSocket.Server({ server })
wss.on('connection', function connection(ws) {
const now = new Date();
const tDate = now.toDateString();
const date = new Date(now);
const currentDate = date.toLocaleTimeString();
console.log(tDate + ' - ' + currentDate + " - New User Connected");
ws.send(JSON.stringify(
{
name: "welcome",
message: "wanna chat?"
}
));
ws.on('message', function(message){
message = JSON.parse(message);
const createDOMPurify = require('dompurify');
const { JSDOM } = require('jsdom');
const window = new JSDOM('').window;
const DOMPurify = createDOMPurify(window);
// START CONNECT
if(message.type == "name"){
// START CHECKS FOR DOUBLE LOGIN
var dirty = message.data;
const ConnectingUser = DOMPurify.sanitize(dirty);
if (ConnectingUser != ''){
wss.clients.forEach(function e(client) {
var ConnectedUser = client.personName;
if(ConnectedUser == ConnectingUser) {
client.send(JSON.stringify(
{
name: "***Server***",
message: "***We do not allow double logins!"
}
));
client.send(JSON.stringify(
{
name: "***Server***",
message: "🔴 Disconnected..."
}
));
client.close();
}
});
}
// END CHECKS FOR DOUBLE LOGIN
ws.personName = ConnectingUser;
memberJoinedChatMsg(ws, ConnectingUser);
return;
}
// START INPUT DATA
if(message.type == "message"){
var ConnectedUser = ws.personName;
if (ConnectedUser != ''){
var dirty = message.message;
const Message = DOMPurify.sanitize(dirty);
var string = Message;
var temp = string.split(" ");
var CommandOne = temp[0];
var CommandTwo = temp[1];
var CommandThree = temp.slice(2).join(" ");
// lets process the messages and send to users
if((Message) != "") {
// START COMMANDS
// Do join/leave msg disable--------------------------------------------------------------------
if((CommandOne) == "/jpenable" || (CommandOne) == "!jpenable"){
JoinLeaveMsg = "1";
Msg ='***Join/Part message has been Enabled!';
sendMsgToAll(Msg)
MessageString ="";
}
// Do join/leave msg enable--------------------------------------------------------------------
if((CommandOne) == "/jpdisable" || (CommandOne) == "!jpdisable"){
JoinLeaveMsg = "0";
Msg ='***Join/Part message has been Disabled!';
sendMsgToAll(Msg)
MessageString ="";
}
// END COMMANDS
if ((Message).length < maxLength) {
wss.clients.forEach(function e(client) {
client.send(JSON.stringify(
{
name: ConnectedUser,
message: Message
}
));
console.log("Sent: "+ConnectedUser+" "+Message);
});
}else{
wss.clients.forEach(function e(client) {
if(client === ws)
client.send(JSON.stringify(
{
name: '***Server***',
message: "*** Your message exceeds "+maxLength+" characters!"
}
));
});
};
}else{
// dont process if empty line entered
};
}
}
// END INPUT DATA
})
ws.on('close', function(message) {
if(ws.personName){
memberLeftChatMsg(ws);
}
ws.close();
//console.log("Client Disconnected");
});
// END CONNECT
})
server.listen(port, function() {
console.log(`Server is listening on ${port}!`)
})
// FUNCTIONS
// complete Send Message To All
function sendMsgToAll(Msg){
wss.clients.forEach(function e(client) {
client.send(JSON.stringify(
{
name: "Server",
message: Msg
}
));
});
};
// complete
function memberJoinedChatMsg(ws, ConnectingUser) {
if(JoinLeaveMsg != "0"){
wss.clients.forEach(function e(client) {
client.send(JSON.stringify(
{
name: "***Server***",
message: "🟢 <<b>"+ConnectingUser+"</b>> has entered chat!"
}
));
});
}
};
// complete
function memberLeftChatMsg(ws) {
if(JoinLeaveMsg != "0"){
wss.clients.forEach(function e(client) {
client.send(JSON.stringify(
{
name: "***Server***",
message: "🔴 <<b>"+ws.personName+"</b>> has left chat!"
}
));
});
}
};
I also have Dompurify installed using npm to help prevent entities being posted. Remember to open the port in your firewall or change the port number in the script. If you need the client side script including the html, .css let me know, I can upload those too :)
CLIENT SCRIPT:
(function() {
const sendBtn = document.querySelector('#send');
const messages = document.querySelector('#messages');
const messageBox = document.querySelector('#messageBox');
var ws;
var text = "Server: Server Offline!";
var sName = name;
function updateChat(element) {
var name = element[0];
var message = element[1];
const now = new Date();
const tDate = now.toDateString();
const date = new Date(now);
const currentDate = date.toLocaleTimeString();
if(sName == name){
$('.responsive-html5-chat' + ' div.messages').append( '<div class="message"><div class="myMessage"><p>' + message + "</p><date>" + name + " " + currentDate + "</date></div></div>" );
}else{
$('.responsive-html5-chat' + ' div.messages').append( '<div class="message"><div class="fromThem"><p>' + message + "</p><date>" + currentDate + " " + name + "</date></div></div>" );
}
setTimeout(function () { $('.responsive-html5-chat' + ' > span').addClass("spinner"); }, 100);
setTimeout(function () { $('.responsive-html5-chat' + ' > span').removeClass("spinner"); }, 2000);
$(".messages").scrollTop(function() { return this.scrollHeight; });
}
function responsiveChat(element) {
$(element).html('<form class="chat"><span></span><div class="messages"></div><input type="text" id="msg" placeholder="Your message" autocomplete="off"><input id="send" type="submit" value="Send"></form>');
}
responsiveChat('.responsive-html5-chat');
function init() {
if (ws) {
ws.onerror = ws.onopen = ws.onclose = null;
ws.close();
}
ws = new WebSocket('wss://MyDomain.com:1441');
ws.onopen = function() {
if(name) {
ws.send(JSON.stringify({
type: "name",
data: name
}));
}else{
const dat = ['', 'Please Login to chat!'];
updateChat(dat);
ws = null;
return ;
}
}
// START RECIEVED FROM SERVER
ws.onmessage = function(event){
var json = JSON.parse(event.data);
var Name = json.name;
var Message = json.message;
if(name) {
if (Name === "***Server***"){
const dat = ['***Server***', Message];
updateChat(dat);
}else if(Name === "welcome" && name != '') {
Message = 'Hi ' + name + ' ' + Message;
const dat = ['', Message];
updateChat(dat);
}else{
const dat = [Name, Message];
updateChat(dat);
}
}
}
// END RECIEVED FROM SERVER
ws.onclose = function(event) {
if (event.wasClean) {
ws = null;
} else {
const dat = ['', 'Server Offline!'];
updateChat(dat);
ws = null;
}
};
}
// START SEND TO SERVER
send.onclick = function (event){
event.preventDefault();
if(name) {
if (!ws) {
const dat = ['', 'You are not connected... :('];
updateChat(dat);
ws = null;
return ;
}
var messages = document.getElementById("msg").value;
document.getElementById("msg").value = ''; // empty msg box
ws.send(JSON.stringify({
type: "message",
data: name,
message: messages
}));
}else{
const dat = ['', 'Please Login to chat!'];
updateChat(dat);
ws = null;
return ;
}
};
init();
})();
I am developing an office 365 word web addin, wherein I need to upload the currently opened document to my server. For which I am trying to get the file data using following code.
The method getSliceAsync() is returning only first slice of data.
On debugging it gives "Addin Error: Sorry, we had to restart because this addin wasn't responding" while getting second slice.
I am using this link for reference : [https://learn.microsoft.com/en-us/office/dev/add-ins/word/get-the-whole-document-from-an-add-in-for-word][1]
Here is my code:
Office.context.document.getFileAsync(Office.FileType.Compressed, { sliceSize: 65536 }, function (result) {
if (result.status == "succeeded") {
// If the getFileAsync call succeeded, then result.value will return a valid File Object
var myFile = result.value;
var filename1 = myFile.name;
console.log(filename1);
var sliceCount = myFile.sliceCount;
var slicesReceived = 0, isAllSlicesSuccess = true, docdataSlices = [];
// document.getElementById("result").innerText = "File size:" + myFile.size + "#Slices: " + sliceCount;
console.log(" File size:" + myFile.size + " #Slices: " + sliceCount, "");
makeProgress(20);
// Iterate over the file slices
for (var i = 0; i < sliceCount && isAllSlicesSuccess; i++) {
var diffPercent = ((i / sliceCount) * 100);
myFile.getSliceAsync(i, function (sliceResult) {
if (sliceResult.status == "succeeded") {
if (!isAllSlicesSuccess) { // Some slice has failed to get, no need to continue
console.log("Error", "One slice failed to get");
return;
console.log(sliceResult);
}
console.log('sliceResult', sliceResult);
console.log("Success", "i: " + i);
console.log("++slicesReceived ",slicesReceived );
console.log(" sliceCount",sliceCount );
console.log("++slicesReceived == sliceCount",slicesReceived == sliceCount);
// One chunk was got, store it in a temporal array
// ++slicesReceived;
// or you can do something with the chunk, such as sent it to a third party server
docdataSlices[sliceResult.value.index] = sliceResult.value.data;
if (++slicesReceived == sliceCount) {
getAllSlicesTime = Date.now();
var performance = (getAllSlicesTime - startTime) / 1000.0;
console.log("Success", "All slices has been get, Seconds: " + performance);
// All slices have been received
myFile.closeAsync(function (closeRes) {
if (closeRes.status == "succeeded") {
console.log("Close Success", "Success");
// DUClick();
}
else {
console.log("Close Error", closeRes.error.message);
}
});
onGetAllSlicesSucceeded(docdataSlices, false);
}
}
else {
isAllSlicesSuccess = false;
myFile.closeAsync(function (closeRes) {
if (closeRes.status == "succeeded") {
console.log("Close Success", "Success");
// DUClick();
}
else {
console.log("Close Error", closeRes.error.message);
}
});
console.log("Get Slice Error:", sliceResult.error.message);
}
});
}
}
else {
getFileTime = Date.now();
var performance = (getFileTime - startTime) / 1000.0;
console.log('Get File Error:', "Seconds: " + performance + " " + result.error.message);
}
});
Please suggest! Thanks in advance!
[1]: https://learn.microsoft.com/en-us/office/dev/add-ins/word/get-the-whole-document-from-an-add-in-for-word
I currently have a javascript application that plays a couple of videos and asks a series of questions, based on the wait time in each question.
However, after a new video is triggered (2th video), my code skips the first question and I can't really find out why. Any ideas? Thank you.
Settings.js
var settings = {
'appname': 'ExperimentX',
'masterpassword': 'xxxx'
};
var videos = [
{
'video': 'movie 1.mp4',
'questions': [
{
'text': `
blabla
`,
'wait': 2 * 60 + 51
},
{
'text': 'How sad are you right now',
'wait': 1 * 60 + 57
},
{
'text': '',
'wait': 57
}
]
},
{
'video': 'movie 2.mp4',
'questions': [
{
'text': 'How happy are you right now',
'wait': 2
},
{
'text': 'How sad are you right now',
'wait': 5
}
]
}
}
And the real JS code:
// -- base settings
identifier = new Date().getTime();
videos_path = 'videos/';
// -- create elements
var player = videojs('video');
var slider = $('#ex1');
// -- variables
var debug = true;
var timer = null;
var questions = [];
var currquestion = 0;
var currvideo = 0;
function log(msg){
if (debug)
console.log(msg);
}
function checkForLocalStorage(){
var result = false;
try {
result = (typeof window.localStorage == 'undefined');
} catch (err){
result = false;
}
return result;
}
function save(key, value){
log('Saving ' + key + ' -> ' + value);
var sessionObject = localStorage.getItem( identifier );
sessionObject = (null == sessionObject) ? {} : JSON.parse(sessionObject);
sessionObject[key] = value;
localStorage.setItem(identifier, JSON.stringify(sessionObject));
}
function toDate(ms){
var d = new Date(0);
d.setUTCSeconds(ms / 1000);
return d.toLocaleString();
}
function loadAll(){
var result = [];
log('Loading from localstorage:');
for (var i = 0; i < localStorage.length; i++){
var key = localStorage.key(i);
var obj = JSON.parse( localStorage.getItem(key) );
obj['timestamp'] = toDate(key);
log(obj);
result.push( obj );
}
return result;
}
function refreshVideoCount(){
log('Refreshing video counter');
$('#currvideoCounter').text( currvideo +1 );
$('#totalvideoCounter').text( videos.length );
}
function showEnd(){
log('Showing end page');
$('#ending').removeClass('hidden');
$('#videoPlayer').addClass('hidden');
$('#menuEnd').addClass('active');
$('#menuVideos').removeClass('active');
}
function showQuestion(){
console.log('Showing question, currquestion ' + currquestion + ' currvideo ' + currvideo);
clearTimeout(timer);
$('#modalTitle').html( questions[currquestion]['text'] );
$('#modalQuestion').modal('show');
$('#btnModal').on('click', function(){
log('btnModal clicked, saving answer');
save('V' + currvideo + ' Q' + currquestion, slider.slider('getValue'));
log('Refreshing slider');
slider.slider('refresh');
var next = (currquestion >= questions.length-1);
if (next == true){
log('currquestion is the last one, cycling to next video');
currvideo = currvideo +1;
currquestion = 0;
cycleVideos();
} else {
log('cycling to next question of this video');
currquestion = currquestion +1;
cycleQuestions();
}
});
}
function cycleQuestions(){
log('Resuming video');
var questionText = questions[currquestion]['text'];
var questionWait = questions[currquestion]['wait'];
player.play();
if (timer){
log('Clearing timer (cycleQuestions)');
clearTimeout(timer);
timer = null;
}
log('Setting new timer');
timer = setTimeout(function(){
log('Timer triggered, pausing player and showing question');
player.pause();
showQuestion();
}, questionWait * 1000);
}
function cycleVideos(){
log('Cycling to next video');
if (timer){
log('Clearing timer (cycleVideos)');
clearTimeout(timer);
timer = null;
}
if (currvideo > videos.length -1){
log('Video is the last one, showing end page');
player.pause();
player.exitFullscreen();
return showEnd();
}
log('Setting videofile and question variable');
videoFile = videos_path + videos[currvideo]['video'];
questions = videos[currvideo]['questions'];
refreshVideoCount();
log('Playing player');
player.src({ 'src' : videoFile });
player.play();
cycleQuestions();
}
function showOverview(){
log('Showing management page');
$('#intro').addClass('hidden');
$('#overview').removeClass('hidden');
var items = loadAll();
var content = '';
log('Generating table');
var table =
$('<table>')
.addClass('table')
.append('<thead><tr>');
for (var prop in items[0])
table.append('<th>' + prop + '</th>');
table
.append('</tr></thead>')
.append('<tbody>');
items.forEach(function(object){
// for every entry
var row = '<tr>';
for (var property in items[0]) {
if (object.hasOwnProperty(property)) {
// for every property
row = row.concat(
'<td>' + object[property] + '</td>'
);
}
}
row.concat('</tr>');
table.append(row);
});
table.append('</table>');
$('#overviewText').html(table);
$('#btnClear').on('click', function(){
log('Clearing storage');
if ( confirm('Do you really want to clear all results?') ){
localStorage.clear();
location.reload();
}
});
}
function showIntro(){
log('Showing intro page');
$('#menuIntro').addClass('active');
refreshVideoCount();
$('#intro').removeClass('hidden');
$('#introInput').keyup(function(event){
if(event.keyCode == 13)
$("#introBtn").click();
});
$('#introBtn').on('click', function(){
var name = $('#introInput').val();
var age = $('#introAge').val();
var gender = $('#introGender').val();
if (name.trim().length == 0)
return alert('You need to fill in your name.');
if (age.trim().length == 0)
return alert('You need to fill in your age.');
if (name === settings['masterpassword'])
return showOverview();
save('name', name);
save('age', age);
save('gender', gender);
$('#intro').addClass('hidden');
$('#videoPlayer').removeClass('hidden');
$('#menuIntro').removeClass('active');
$('#menuVideos').addClass('active');
slider.slider({});
player.requestFullscreen();
cycleVideos();
});
}
function disableRefresh(){
log('Disabling F5');
$(document).on("keydown", function(e){
if ((e.which || e.keyCode) == 116)
e.preventDefault();
});
}
// setup base stuff
checkForLocalStorage();
$('#logo').text( settings['appname'] );
$('#title').text( settings['appname'] );
disableRefresh();
// show intro page
showIntro( identifier );
My controller.js is as follows:
.controller('dashboardCtrl', function($scope,TestMethod,$cordovaSQLite) {
var dis_stime = [];
var dis_steps = [];
$scope.select = function() {
console.log("check1");
var lastSynced = localStorage.getItem('lastSynced');
if (lastSynced != undefined) {
console.log("check2");
// alert("lastSynced time is "+lastSynced);
// alert("query written");
try {
db = $cordovaSQLite.openDB({name:"health.db",location:'default'});
// alert("inside create");
} catch (error) {
alert(error);
}
lastSynced = lastSynced * 1000000;
startTime = lastSynced - (86400 * 1000000000);
for (var i = 1; i < (PERIOD +1); i++) {
$cordovaSQLite.execute(db,"SELECT SUM(stepcount) AS total FROM activity WHERE startTime BETWEEN ? AND ?", [startTime,lastSynced])
.then(function (resultSet)
{
dis_stime[i] = lastSynced;
dis_steps[i] = resultSet.rows.item(0).total;
alert("total is " + resultSet.rows.item(0).total);
// alert("Total is : " +resultSet.rows.item(0).total);
// alert("total entries" + resultSet.rows.length);
}, function(error) {
alert('SELECT error: ' + error.message);
});
lastSynced = startTime;
startTime = startTime - (86400 * 1000000000);
}
}
else
{
alert("Please sync the device to see the data");
}
alert("steps: "+dis_steps+" times: "+dis_stime);
$scope.labels = dis_stime;
$scope.series = ['steps'];
$scope.data = dis_steps;
}
})
I am fetching the data from sqlite plugin and then i want to display it on graph.
The problem is that the graph doesnt get loaded when select function is called.
where and how should i call the select function so that data is loaded when i open the page??
You have to inject the $cordovaSQLite service in your controller :
.controller('profile',['$scope','http','insert','$cordovaSQLite',
function($scope,$http,insert,$cordovaSQLite){
...
}]);
I am trying to retrieve the messages whenever Uses logs in and the page loads. Right now I can able to retrieve the messages whenever the User sends the message to other User i.e., with the onMessage function.
Here is my code:
var archive = [];
// Retrives the messages whenever User sends the messages to Other User.
// TODO: Should be better when User logins and page loads
var q = {
onMessage: function(message) {
try {
var id = message.querySelector('result').getAttribute('id');
var fwd = message.querySelector('forwarded');
var d = fwd.querySelector('delay').getAttribute('stamp');
var msg = fwd.querySelector('message');
var msg_data = {
id:id,
with: Strophe.getBareJidFromJid(msg.getAttribute('to')),
timestamp: (new Date(d)),
timestamp_orig: d,
from: Strophe.getBareJidFromJid(msg.getAttribute('from')),
to: Strophe.getBareJidFromJid(msg.getAttribute('to')),
type: msg.getAttribute('type'),
body: msg.getAttribute('body'),
message: Strophe.getText(msg.getElementsByTagName('body')[0]),
avatar:'images/default_avatar_image.png'
};
archive.val(archive.val() + msg_data.from + ":" + msg_data.message + "\n" + msg_data.to + ":" + msg_data.message + "\n");
archive.scrollTop(archive[0].scrollHeight - archive.height());
console.log('xmpp.history.message',msg_data.message);
} catch(err){
if(typeof(err) == 'TypeError'){
try {
console.log(err.stack)
} catch(err2){
console.log(err,err2);
}
}
}
return true;
},
onComplete: function(response) {
console.log('xmpp.history.end',{query:q,data:data,response:response});
}
};
console.log('xmpp.history.start',{query:q});
function onMessage(msg) {
// Calls whenever User receives the messages
// and shows the received message in messagebox
var fromJid = msg.getAttribute("from"),
bareFromJid = Strophe.getBareJidFromJid(fromJid),
type = msg.getAttribute("type"),
elems = msg.getElementsByTagName("body");
if (type == "chat" && elems.length > 0) {
var body = elems[0],
message = Strophe.getText(body);
showMessage(bareFromJid + ": " + message);
connection.mam.query(Strophe.getBareJidFromJid(connection.jid), q);
}
return true;
}
function send() {
// Calls whenever User sends the messages
// and shows the message in messagebox
var to = $('#to-jid').get(0).value,
myBareJid = Strophe.getBareJidFromJid(connection.jid);
message = $('#message').val(),
reply = $msg({to: to, type: 'chat'})
.c("body")
.t(message);
connection.send(reply.tree());
showMessage(myBareJid + ": " + message);
}
$(document).ready(function () {
connection = new Strophe.Connection(BOSH_SERVICE);
archive = $("#archive-messages");
archive.val("");
connection.rawInput = function (data) { log('RECV: ' + data); };
connection.rawOutput = function (data) { log('SEND: ' + data); };
Strophe.log = function (level, msg) { log('LOG: ' + msg); };
$("#send").bind('click', send);
});
So what happens in my code is whenever User receives the message, then all the messages be retrieved between those two Users.
How can I retrieve the messages in the chat box when I clicked on the particular User??
There were two issues in this. One is when I perform auto login with login() method when scripts loads, it at least takes 800ms to login and perform other actions. At this point I was facing the issue and also bit jQuery part.
Here is my code:
// Retrives the messages between two particular users.
var q = {
onMessage: function(message) {
try {
var id = message.querySelector('result').getAttribute('id');
var fwd = message.querySelector('forwarded');
var d = fwd.querySelector('delay').getAttribute('stamp');
var msg = fwd.querySelector('message');
var msg_data = {
id:id,
with: Strophe.getBareJidFromJid(msg.getAttribute('to')),
timestamp: (new Date(d)),
timestamp_orig: d,
from: Strophe.getBareJidFromJid(msg.getAttribute('from')),
to: Strophe.getBareJidFromJid(msg.getAttribute('to')),
type: msg.getAttribute('type'),
body: msg.getAttribute('body'),
message: Strophe.getText(msg.getElementsByTagName('body')[0])
};
var login_user = connection.jid.split('#')[0];
var username = msg_data.from.split('#')[0];
if(login_user == username) {
archive.val(archive.val() + "me:".capitalizeFirstLetter() + msg_data.message + "\n");
archive.scrollTop(archive[0].scrollHeight - archive.height());
}
else {
archive.val(archive.val() + username.capitalizeFirstLetter() + ":" + msg_data.message + "\n");
archive.scrollTop(archive[0].scrollHeight - archive.height());
}
console.log('xmpp.history.message',msg_data.message);
} catch(err){
if(typeof(err) == 'TypeError'){
try {
console.log(err.stack)
} catch(err2){
console.log(err,err2);
}
}
}
return true;
},
onComplete: function(response) {
console.log('xmpp.history.end',{query:q, response:response});
}
};
$("#to-jid").change(function() {
$("#archive-messages").val("");
var to = {"with": $(this).val()};
$.extend(q, to);
// It takes around 800ms to login. So after this timeout we have to retrieve the messages of particular User.
setTimeout(function(){
connection.mam.query(Strophe.getBareJidFromJid(connection.jid), q);
}, 1000);
});