how to get chat history from xmpp server smack library - android

I want to get chat history for one to one chat and group chat. after some research i came to know that i can do it by Message Archive Management . but it does not provide any example to get older message in to android client. i want to get older message chat history from server, but i dont know how to pull older messages from xmpp server. there are so many questions asked about this over here but didn't get any proper solution. what i have done till now is connection and sending message to other user. can anyone help me to get history of chat from xmpp server?
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword("user1", "password")
.setHost(getString(R.string.domain))
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setServiceName(getString(R.string.domain))
.setPort(5222)
.setDebuggerEnabled(true) // to view what's happening in detail
.build();
XMPPTCPConnection conn1 = new XMPPTCPConnection(config);
conn1.setUseStreamManagement(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
conn1.setUseStreamManagementResumption(true);
// ReconnectionManager.getInstanceFor(this.conn1).enableAutomaticReconnection();
conn1.setPacketReplyTimeout(10000);
try {
conn1.connect();
if(conn1.isConnected()) {
Log.w("app", "conn done");
}
conn1.login();
if(conn1.isAuthenticated()) {
Log.w("app", "Auth done");
}
}
catch (Exception e) {
Log.w("app", e.toString());
}
ChatManager chatmanager = ChatManager.getInstanceFor(conn1);
Chat newChat = chatmanager.createChat("user2#"+getString(R.string.domain));
try {
newChat.sendMessage("Test Msg from user1!!!");
}
catch (SmackException.NotConnectedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

I'd use Smack's MamManager. For example MamManager.queryArchive(Integer).

Related

how to implement smack for xmpp

I'm trying to have my android app to be able to send and receive xmpp message using smack but it does not work and the connect command does not return. I have seen several code example but Smack has new versions and the syntax has changed so I might be doing something wrong :
in my build.graddle file I use :
compile "org.igniterealtime.smack:smack-android-extensions:4.3.0"
compile "org.igniterealtime.smack:smack-tcp:4.3.0"
I'm trying to send a message from myaccount321#xabber.org to myaccount456#xabber.org
I'm trying to connect using hot-chilli.net (Idon't mind using some other server))
everything seems to go well until connection.connect() after which the script does not return without triggering any exception.
Please tell me what I'm doing wrong
TIA
public void sendxmpp(){
XMPPTCPConnectionConfiguration config = null;
try {
XMPPTCPConnectionConfiguration.Builder configbuilder = XMPPTCPConnectionConfiguration.builder();
configbuilder.setUsernameAndPassword("myaccount321","myaccount321pw");
DomainBareJid serviceName = JidCreate.domainBareFrom("hot-chilli.net");
configbuilder.setServiceName(serviceName);
configbuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
configbuilder.setHost("jabber.hot-chilli.net");
configbuilder.setPort(8222);
config=configbuilder.build();
AbstractXMPPConnection connection = new XMPPTCPConnection(config);
try {
connection.connect();
}
catch (SmackException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (XMPPException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
connection.login();
ChatManager chatManager = ChatManager.getInstanceFor(connection);
EntityBareJid jid = JidCreate.entityBareFrom("myaccount321pw#xabber.org");
Chat chat = chatManager.createChat(jid);
chat.sendMessage("Hello");
}
catch (Exception e) {
}
}
OK I got it, the connection process has to be done in its own thread.

Update and retrieve chat history in smack with openfire -Android

I am making a chat application with smack library and openfire as a server but everytime i exit the chat conversation activity between two users and come back, the whole chat gets erased. I have already enabled archive settings to store one to one messages in the server but i do not know how to implement it in the app.
I want to show chats history in recyclerview by the sender and the receiver in the recyclerview.
currently i have implemented this function which caused error
private void setChatHistory(String entityBareId) {
EntityBareJid jid = null;
try {
jid = JidCreate.entityBareFrom(entityBareId);
} catch (XmppStringprepException e) {
e.printStackTrace();
}
MamManager manager = MamManager.getInstanceFor(mConnection);
MamManager.MamQueryResult r = null;
try {
try {
r = manager.mostRecentPage(jid, 10);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotLoggedInException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
}
if (r.forwardedMessages.size() >= 1) //printing first of them
{
Message message = (Message) r.forwardedMessages.get(0).getForwardedStanza();
Log.i("mam", "message received" + message.getBody());
MessagesData data = new MessagesData("send",message.getBody());
mMessagesData.add(data);
mAdapter = new ConversationAdapter(mMessagesData);
recyclerView.setAdapter(mAdapter);
}
}
Error was
Attempt to read from field 'java.util.List org.jivesoftware.smackx.mam.MamManager$MamQueryResult.forwardedMessages' on a null object reference
At r.forwardedmessages.size()>=1.
Thanks in advance
If you want to keep history of conversation, you must save them in database. MAM just for fetching old conversation from server like when you uninstall or logout the app and decide to reinstall and get old messages.
For getting messages from server be sure you already enabled it, then forwarded messages shouldnt be null. here is a guide to enable it.

Function chatDidReceiveMessage not working Quickblox

I use this framework to create a messenger on Android and iOS.
In android I create a message and send it.
The server quickblox it comes !
I also see this message in the log of xcode... but no further response should not be, because the function - (void)chatDidReceiveMessage:(QBChatMessage *)message is break point.
What am I doing wrong?
Code for sending message(Android)
// create a message
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setProperty("save_to_history", "1"); // Save a message to history
chatMessage.setBody("Hi there");
chatMessage.setDateSent(new Date().getTime()/1000);
// attach a audio
QBAttachment attachment = new QBAttachment("audio");
attachment.setId(file.getId().toString());
chatMessage.addAttachment(attachment);
try {
currentChatRoom.sendMessage(chatMessage);
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
Code in log XCode
2015-12-13 16:05:27.638 Messenger[462:5623] [ChatService] Message RCV: <message xmlns="jabber:client" id="566d5efb1fecfa062778dcd9" to="6804658-31081#chat.quickblox.com/A9320123-BD0A-4C80-BD81-F729D036877A" type="groupchat" from="31081_56616b87a0eb4756f2000b6d#muc.chat.quickblox.com/6919398"><body>Hi there</body><extraParams xmlns="jabber:client"><attachment type="audio" id="3173128"/><date_sent>1450011927</date_sent><save_to_history>1</save_to_history><message_id>566d5efb1fecfa062778dcd9</message_id><dialog_id>56616b87a0eb4756f2000b6d</dialog_id></extraParams><delay xmlns="urn:xmpp:delay" stamp="2015-12-13T13:05:27Z"/></message>
I don't understand((
If I am right, you send messages to chat room (not private chat), and then you should use chatRoomDidReceiveMessage:fromDialogID: instead. I faced the same problem, described in chatDidReceiveMessage: not called post.

Retrieving offline messages using asmack

I'm new to asmack and openfire, looked a lot for a working answer to this but couldn't find it anywhere. How do I retrieve offline messages on Logging into my account on asmack?
I've used the following code:
configure(ProviderManager.getInstance()); //configuring providers before creating a connection
ConnectionConfiguration connConfig = new ConnectionConfiguration(HOST, PORT);
connConfig.setSendPresence(false);
connection = new XMPPConnection (connConfig);
try {
connection.connect();
} catch (XMPPException ex) {
setConnection(null);
}
try {
connection.login(username, password);
try {
OfflineMessageManager offlineManager = new OfflineMessageManager(
connection);
Iterator<org.jivesoftware.smack.packet.Message> it = offlineManager
.getMessages();
System.out.println(offlineManager.supportsFlexibleRetrieval());
System.out.println("Number of offline messages:: " + offlineManager.getMessageCount());
Map<String,ArrayList<Message>> offlineMsgs = new HashMap<String,ArrayList<Message>>();
while (it.hasNext()) {
org.jivesoftware.smack.packet.Message message = it.next();
System.out
.println("receive offline messages, the Received from [" + message.getFrom()
+ "] the message:" + message.getBody());
String fromUser = message.getFrom().split("/")[0];
if(offlineMsgs.containsKey(fromUser))
{
offlineMsgs.get(fromUser).add(message);
}else{
ArrayList<Message> temp = new ArrayList<Message>();
temp.add(message);
offlineMsgs.put(fromUser, temp);
}
}
// Deal with a collection of offline messages ...
offlineManager.deleteMessages();
} catch (Exception e) {
Log.e("CATCH","OFFLINE");
e.printStackTrace();
}
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
setConnection(connection);//Packet Listener
// Set the status to available
} catch (XMPPException ex) {
setConnection(null);
}
From what I've read, once a connection is established, Openfire automatically sends offline messages to the user. (if any) Which means that by just setting packet listeners after logging in, I should be able to retrieve the messages. However, this didn't work for me. Which's why I tried using OfflineMessageManager. It always shows 0 messages as the message count though. I even logged in to the mysql db which the server's using and checked the offline messages folder. The messages exist till the user logs in, which means that the messages are being sent but it isn't being retrieved by the app. I can't seem to find out how implement this. If anyone has a working solution, It'd be greatly appreciated.
i partially solved added a packet listener after login but the same problem persist when internet go down. in that case i intercept reconnectionSuccessful event and remove and add again the packet listener but the messages sent when the user was offline is lost .
Somebody have the best solution to solve it?
Send your presence afetr logging in to the XMPP server. You have forgot to add packetListener which listens for the upcoming offline messages.
Hope this works.

Login exception SASL authentication failed using mechanism DIGEST-MD5 asmack in android

I m try to connect with Xmpp server,But i m getting exception
Login exception SASL authentication failed using mechanism DIGEST-MD5
i use this code ,can any one help me,or code
try {
if (xmppConnection == null) {
ConnectionConfiguration config = new ConnectionConfiguration(
SERVER_HOST, SERVER_PORT, SERVICE_NAME);
xmppConnection = new XMPPConnection(config);
System.out.println("xmppConnection"+xmppConnection);
}
if (!xmppConnection.isConnected()) {
xmppConnection.connect();
System.out.println("Connecting");
}
System.out.println("facebook id get xmpp "+username);
if (!xmppConnection.isAuthenticated()) {
xmppConnection.login(username, "123");
System.out.println("User is authenticated ");
}
Presence presence = new Presence(Presence.Type.available);
xmppConnection.sendPacket(presence);
} catch (Exception e) {
System.out.println("Login exception "+e);
e.printStackTrace();
}
In the Openfire configuration it is machinename.domain.com
This SASL mechanism uses also the Xmpp Domain name for authentication, not only username and password. This is why authentication fails.
mean your username & password must be like:
username: abc111#domain.com (whatever your domain name)
password: abcabc111
for more detail check this conversation.
I am using below code in my, its working fine in here..
try {
ConnectionConfiguration connConfig = new ConnectionConfiguration("HOST_IP", Integer.parseInt("PORT_NO"));
XMPPConnection connection = new XMPPConnection(connConfig);
connection.connect();
try {
// Login
connection.login("USER_NAME", "PASSWORD");
// Set the status to available
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
xmppClient.setConnection(connection);
} catch (XMPPException ex) {
Log.w("XMPPClient", "[SettingsDialog] Failed to log in as " + username);
Log.w("XMPPClient", ex.toString());
xmppClient.setConnection(null);
}
} catch (XMPPException ex) {
Log.w("XMPPClient", "[SettingsDialog] Failed to connect to " + connection.getHost());
Log.w("XMPPClient", ex.toString());
xmppClient.setConnection(null);
}
And I have also added smack.jar file.
Please check below post, i think it might help you..
https://stackoverflow.com/a/6659403/1849482
And many users are getting this error in login. check below links for More Information..
http://community.igniterealtime.org/thread/44219
http://code.google.com/p/asmack/issues/detail?id=33
asmack uses Novell's Open LDAP DigestMD5SaslClient.java which does not support the escape of backslash ('\') and double-quote ('"') for SASL. According to XEP-0106, user name "user#company.com" should be encoded as "user\040company.com". Fully complying with SASL spec, it should be encoded as "user\\040company.com", but asmack didn't. If your XMPP server (e.g. Openfire) uses Java's SASL implementation, it will have a mismatch. Smack 3.x uses Java's SASL implementation, so it works fine. Smack 4.x is supposed to replace asmack, but I don't know if Smack 4.x uses Novell or Java SASL implementation.
BTW, this problem exists in iOS xmppframework as well.
If you are interested in my fix, I'll post it somewhere.
Here is the link to the revised DigestMD5SaslClient.java with the escape quoted string.

Categories

Resources