1package eu.siacs.conversations.parser;
2
3import android.util.Log;
4import android.util.Pair;
5
6import net.java.otr4j.session.Session;
7import net.java.otr4j.session.SessionStatus;
8
9import eu.siacs.conversations.Config;
10import eu.siacs.conversations.entities.Account;
11import eu.siacs.conversations.entities.Contact;
12import eu.siacs.conversations.entities.Conversation;
13import eu.siacs.conversations.entities.Message;
14import eu.siacs.conversations.entities.MucOptions;
15import eu.siacs.conversations.http.HttpConnectionManager;
16import eu.siacs.conversations.services.MessageArchiveService;
17import eu.siacs.conversations.services.XmppConnectionService;
18import eu.siacs.conversations.utils.CryptoHelper;
19import eu.siacs.conversations.xml.Element;
20import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
21import eu.siacs.conversations.xmpp.chatstate.ChatState;
22import eu.siacs.conversations.xmpp.jid.Jid;
23import eu.siacs.conversations.xmpp.pep.Avatar;
24import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
25
26public class MessageParser extends AbstractParser implements
27 OnMessagePacketReceived {
28 public MessageParser(XmppConnectionService service) {
29 super(service);
30 }
31
32 private boolean extractChatState(Conversation conversation, final MessagePacket packet) {
33 ChatState state = ChatState.parse(packet);
34 if (state != null && conversation != null) {
35 final Account account = conversation.getAccount();
36 Jid from = packet.getFrom();
37 if (from.toBareJid().equals(account.getJid().toBareJid())) {
38 conversation.setOutgoingChatState(state);
39 return false;
40 } else {
41 return conversation.setIncomingChatState(state);
42 }
43 }
44 return false;
45 }
46
47 private Message parseOtrChat(String body, Jid from, String id, Conversation conversation) {
48 String presence;
49 if (from.isBareJid()) {
50 presence = "";
51 } else {
52 presence = from.getResourcepart();
53 }
54 if (body.matches("^\\?OTRv\\d{1,2}\\?.*")) {
55 conversation.endOtrIfNeeded();
56 }
57 if (!conversation.hasValidOtrSession()) {
58 conversation.startOtrSession(presence,false);
59 } else {
60 String foreignPresence = conversation.getOtrSession().getSessionID().getUserID();
61 if (!foreignPresence.equals(presence)) {
62 conversation.endOtrIfNeeded();
63 conversation.startOtrSession(presence, false);
64 }
65 }
66 try {
67 conversation.setLastReceivedOtrMessageId(id);
68 Session otrSession = conversation.getOtrSession();
69 SessionStatus before = otrSession.getSessionStatus();
70 body = otrSession.transformReceiving(body);
71 SessionStatus after = otrSession.getSessionStatus();
72 if ((before != after) && (after == SessionStatus.ENCRYPTED)) {
73 conversation.setNextEncryption(Message.ENCRYPTION_OTR);
74 mXmppConnectionService.onOtrSessionEstablished(conversation);
75 } else if ((before != after) && (after == SessionStatus.FINISHED)) {
76 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
77 conversation.resetOtrSession();
78 mXmppConnectionService.updateConversationUi();
79 }
80 if ((body == null) || (body.isEmpty())) {
81 return null;
82 }
83 if (body.startsWith(CryptoHelper.FILETRANSFER)) {
84 String key = body.substring(CryptoHelper.FILETRANSFER.length());
85 conversation.setSymmetricKey(CryptoHelper.hexToBytes(key));
86 return null;
87 }
88 Message finishedMessage = new Message(conversation, body, Message.ENCRYPTION_OTR, Message.STATUS_RECEIVED);
89 conversation.setLastReceivedOtrMessageId(null);
90 return finishedMessage;
91 } catch (Exception e) {
92 conversation.resetOtrSession();
93 return null;
94 }
95 }
96
97 private class Invite {
98 Jid jid;
99 String password;
100 Invite(Jid jid, String password) {
101 this.jid = jid;
102 this.password = password;
103 }
104 }
105
106 private Invite extractInvite(Element message) {
107 Element x = message.findChild("x", "http://jabber.org/protocol/muc#user");
108 if (x != null) {
109 Element invite = x.findChild("invite");
110 if (invite != null) {
111 Element pw = x.findChild("password");
112 return new Invite(message.getAttributeAsJid("from"), pw != null ? pw.getContent(): null);
113 }
114 } else {
115 x = message.findChild("x","jabber:x:conference");
116 if (x != null) {
117 return new Invite(x.getAttributeAsJid("jid"),x.getAttribute("password"));
118 }
119 }
120 return null;
121 }
122
123 private void parseEvent(final Element event, final Jid from, final Account account) {
124 Element items = event.findChild("items");
125 if (items == null) {
126 return;
127 }
128 String node = items.getAttribute("node");
129 if (node == null) {
130 return;
131 }
132 if (node.equals("urn:xmpp:avatar:metadata")) {
133 Avatar avatar = Avatar.parseMetadata(items);
134 if (avatar != null) {
135 avatar.owner = from;
136 if (mXmppConnectionService.getFileBackend().isAvatarCached(
137 avatar)) {
138 if (account.getJid().toBareJid().equals(from)) {
139 if (account.setAvatar(avatar.getFilename())) {
140 mXmppConnectionService.databaseBackend
141 .updateAccount(account);
142 }
143 mXmppConnectionService.getAvatarService().clear(
144 account);
145 mXmppConnectionService.updateConversationUi();
146 mXmppConnectionService.updateAccountUi();
147 } else {
148 Contact contact = account.getRoster().getContact(
149 from);
150 contact.setAvatar(avatar);
151 mXmppConnectionService.getAvatarService().clear(
152 contact);
153 mXmppConnectionService.updateConversationUi();
154 mXmppConnectionService.updateRosterUi();
155 }
156 } else {
157 mXmppConnectionService.fetchAvatar(account, avatar);
158 }
159 }
160 } else if (node.equals("http://jabber.org/protocol/nick")) {
161 Element item = items.findChild("item");
162 if (item != null) {
163 Element nick = item.findChild("nick",
164 "http://jabber.org/protocol/nick");
165 if (nick != null) {
166 if (from != null) {
167 Contact contact = account.getRoster().getContact(
168 from);
169 contact.setPresenceName(nick.getContent());
170 mXmppConnectionService.getAvatarService().clear(account);
171 mXmppConnectionService.updateConversationUi();
172 mXmppConnectionService.updateAccountUi();
173 }
174 }
175 }
176 }
177 }
178
179 @Override
180 public void onMessagePacketReceived(Account account, MessagePacket original) {
181 final MessagePacket packet;
182 Long timestamp = null;
183 final boolean isForwarded;
184 MessageArchiveService.Query query = null;
185 String serverMsgId = null;
186 if (original.fromServer(account)) {
187 Pair<MessagePacket, Long> f;
188 f = original.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
189 f = f == null ? original.getForwardedMessagePacket("sent", "urn:xmpp:carbons:2") : f;
190 f = f == null ? original.getForwardedMessagePacket("result", "urn:xmpp:mam:0") : f;
191 packet = f != null ? f.first : original;
192 timestamp = f != null ? f.second : null;
193 isForwarded = f != null;
194
195 Element fin = original.findChild("fin", "urn:xmpp:mam:0");
196 if (fin != null) {
197 mXmppConnectionService.getMessageArchiveService().processFin(fin);
198 return;
199 }
200
201 final Element result = original.findChild("result","urn:xmpp:mam:0");
202 if (result != null) {
203 query = mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
204 if (query != null) {
205 query.incrementTotalCount();
206 }
207 serverMsgId = result.getAttribute("id");
208 }
209 } else {
210 packet = original;
211 isForwarded = false;
212 }
213 if (timestamp == null) {
214 timestamp = AbstractParser.getTimestamp(packet, System.currentTimeMillis());
215 }
216 final String body = packet.getBody();
217 final String encrypted = packet.findChildContent("x", "jabber:x:encrypted");
218 int status;
219 final Jid to = packet.getTo();
220 final Jid from = packet.getFrom();
221 final Jid counterpart;
222 final String remoteMsgId = packet.getId();
223 boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
224 boolean properlyAddressed = !to.isBareJid() || account.countPresences() == 1;
225 if (packet.fromAccount(account)) {
226 status = Message.STATUS_SEND;
227 counterpart = to;
228 } else {
229 status = Message.STATUS_RECEIVED;
230 counterpart = from;
231 }
232
233 if (from == null || to == null) {
234 Log.d(Config.LOGTAG,"no to or from in: "+packet.toString());
235 return;
236 }
237
238 Invite invite = extractInvite(packet);
239 if (invite != null && invite.jid != null) {
240 Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, invite.jid, true,query);
241 if (!conversation.getMucOptions().online()) {
242 conversation.getMucOptions().setPassword(invite.password);
243 mXmppConnectionService.databaseBackend.updateConversation(conversation);
244 mXmppConnectionService.joinMuc(conversation);
245 mXmppConnectionService.updateConversationUi();
246 }
247 return;
248 }
249
250 if (extractChatState(mXmppConnectionService.find(account,from), packet)) {
251 mXmppConnectionService.updateConversationUi();
252 }
253
254 if (body != null || encrypted != null) {
255 Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.toBareJid(), isTypeGroupChat);
256 if (isTypeGroupChat) {
257 if (counterpart.getResourcepart().equals(conversation.getMucOptions().getActualNick())) {
258 status = Message.STATUS_SEND;
259 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, Message.STATUS_SEND_RECEIVED)) {
260 return;
261 } else if (remoteMsgId == null) {
262 Message message = conversation.findSentMessageWithBody(packet.getBody());
263 if (message != null) {
264 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_RECEIVED);
265 return;
266 }
267 }
268 } else {
269 status = Message.STATUS_RECEIVED;
270 }
271 }
272 Message message;
273 if (body != null && body.startsWith("?OTR")) {
274 if (!isForwarded && !isTypeGroupChat && properlyAddressed) {
275 message = parseOtrChat(body, from, remoteMsgId, conversation);
276 if (message == null) {
277 return;
278 }
279 } else {
280 message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
281 }
282 } else if (encrypted != null) {
283 message = new Message(conversation, encrypted, Message.ENCRYPTION_PGP, status);
284 } else {
285 message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
286 }
287 message.setCounterpart(counterpart);
288 message.setRemoteMsgId(remoteMsgId);
289 message.setServerMsgId(serverMsgId);
290 message.setTime(timestamp);
291 message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
292 if (conversation.getMode() == Conversation.MODE_MULTI) {
293 message.setTrueCounterpart(conversation.getMucOptions().getTrueCounterpart(counterpart.getResourcepart()));
294 if (!isTypeGroupChat) {
295 message.setType(Message.TYPE_PRIVATE);
296 }
297 }
298 updateLastseen(packet,account,true);
299 boolean checkForDuplicates = serverMsgId != null || (isTypeGroupChat && packet.hasChild("delay","urn:xmpp:delay"));
300 if (checkForDuplicates && conversation.hasDuplicateMessage(message)) {
301 Log.d(Config.LOGTAG,"skipping duplicate message from "+message.getCounterpart().toString()+" "+message.getBody());
302 return;
303 }
304 if (query != null) {
305 query.incrementMessageCount();
306 }
307 conversation.add(message);
308 if (serverMsgId == null) {
309 if (status == Message.STATUS_SEND) {
310 mXmppConnectionService.markRead(conversation);
311 account.activateGracePeriod();
312 } else {
313 message.markUnread();
314 }
315 }
316
317 if (mXmppConnectionService.confirmMessages() && remoteMsgId != null && !isForwarded) {
318 if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
319 MessagePacket receipt = mXmppConnectionService
320 .getMessageGenerator().received(account, packet, "urn:xmpp:chat-markers:0");
321 mXmppConnectionService.sendMessagePacket(account, receipt);
322 }
323 if (packet.hasChild("request", "urn:xmpp:receipts")) {
324 MessagePacket receipt = mXmppConnectionService
325 .getMessageGenerator().received(account, packet, "urn:xmpp:receipts");
326 mXmppConnectionService.sendMessagePacket(account, receipt);
327 }
328 }
329 if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().advancedStreamFeaturesLoaded()) {
330 if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
331 mXmppConnectionService.updateConversation(conversation);
332 }
333 }
334
335 if (message.getStatus() == Message.STATUS_RECEIVED
336 && conversation.getOtrSession() != null
337 && !conversation.getOtrSession().getSessionID().getUserID()
338 .equals(message.getCounterpart().getResourcepart())) {
339 conversation.endOtrIfNeeded();
340 }
341
342 if (message.getEncryption() == Message.ENCRYPTION_NONE
343 || mXmppConnectionService.saveEncryptedMessages()) {
344 mXmppConnectionService.databaseBackend.createMessage(message);
345 }
346 final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
347 if (message.trusted() && message.bodyContainsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
348 manager.createNewConnection(message);
349 } else if (!message.isRead()) {
350 mXmppConnectionService.getNotificationService().push(message);
351 }
352 mXmppConnectionService.updateConversationUi();
353 } else {
354 if (packet.hasChild("subject") && isTypeGroupChat) {
355 Conversation conversation = mXmppConnectionService.find(account, from.toBareJid());
356 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
357 conversation.setHasMessagesLeftOnServer(true);
358 conversation.getMucOptions().setSubject(packet.findChildContent("subject"));
359 mXmppConnectionService.updateConversationUi();
360 return;
361 }
362 }
363 }
364
365 Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
366 if (received == null) {
367 received = packet.findChild("received", "urn:xmpp:receipts");
368 }
369 if (received != null && !packet.fromAccount(account)) {
370 mXmppConnectionService.markMessage(account, from.toBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED);
371 }
372 Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
373 if (displayed != null) {
374 if (packet.fromAccount(account)) {
375 Conversation conversation = mXmppConnectionService.find(account,counterpart.toBareJid());
376 mXmppConnectionService.markRead(conversation);
377 } else {
378 updateLastseen(packet, account, true);
379 final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), displayed.getAttribute("id"), Message.STATUS_SEND_DISPLAYED);
380 Message message = displayedMessage == null ? null : displayedMessage.prev();
381 while (message != null
382 && message.getStatus() == Message.STATUS_SEND_RECEIVED
383 && message.getTimeSent() < displayedMessage.getTimeSent()) {
384 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
385 message = message.prev();
386 }
387 }
388 }
389
390 Element event = packet.findChild("event", "http://jabber.org/protocol/pubsub#event");
391 if (event != null) {
392 parseEvent(event, from, account);
393 }
394
395 String nick = packet.findChildContent("nick", "http://jabber.org/protocol/nick");
396 if (nick != null) {
397 Contact contact = account.getRoster().getContact(from);
398 contact.setPresenceName(nick);
399 }
400 }
401}