2

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??

Yashwanth Babu
  • 919
  • 9
  • 30

1 Answers1

3

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);
    });
ArtOfCode
  • 5,702
  • 5
  • 37
  • 56
Yashwanth Babu
  • 919
  • 9
  • 30
  • hello i'm getting error "Uncaught TypeError: Cannot read property 'query' of undefined". can you help? – gaurang Jan 18 '18 at 07:46
  • @gaurang At which line are you getting the error? Can you please paste the error traceback? – Yashwanth Babu Jan 18 '18 at 20:18
  • at connection.mam.query(Strophe.getBareJidFromJid(connection.jid), q); line and error is "Uncaught TypeError: Cannot read property 'query' of undefined. i have asked https://stackoverflow.com/questions/48317459/uncaught-typeerror-cannot-read-property-query-of-undefined-in-mam-using-strop?noredirect=1#48317459 and https://github.com/strophe/strophejs-plugin-mam/issues/8 – gaurang Jan 19 '18 at 04:38