1package eu.siacs.conversations.parser;
2
3import android.util.Log;
4
5import net.java.otr4j.session.Session;
6import net.java.otr4j.session.SessionStatus;
7
8import eu.siacs.conversations.Config;
9import eu.siacs.conversations.entities.Account;
10import eu.siacs.conversations.entities.Contact;
11import eu.siacs.conversations.entities.Conversation;
12import eu.siacs.conversations.entities.Message;
13import eu.siacs.conversations.services.MessageArchiveService;
14import eu.siacs.conversations.services.XmppConnectionService;
15import eu.siacs.conversations.utils.CryptoHelper;
16import eu.siacs.conversations.xml.Element;
17import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
18import eu.siacs.conversations.xmpp.jid.Jid;
19import eu.siacs.conversations.xmpp.pep.Avatar;
20import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
21
22public class MessageParser extends AbstractParser implements
23 OnMessagePacketReceived {
24 public MessageParser(XmppConnectionService service) {
25 super(service);
26 }
27
28 private Message parseChat(MessagePacket packet, Account account) {
29 final Jid jid = packet.getFrom();
30 if (jid == null) {
31 return null;
32 }
33 Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid.toBareJid(), false);
34 updateLastseen(packet, account, true);
35 String pgpBody = getPgpBody(packet);
36 Message finishedMessage;
37 if (pgpBody != null) {
38 finishedMessage = new Message(conversation,
39 pgpBody, Message.ENCRYPTION_PGP, Message.STATUS_RECEIVED);
40 } else {
41 finishedMessage = new Message(conversation,
42 packet.getBody(), Message.ENCRYPTION_NONE,
43 Message.STATUS_RECEIVED);
44 }
45 finishedMessage.setRemoteMsgId(packet.getId());
46 finishedMessage.markable = isMarkable(packet);
47 if (conversation.getMode() == Conversation.MODE_MULTI
48 && !jid.isBareJid()) {
49 finishedMessage.setType(Message.TYPE_PRIVATE);
50 finishedMessage.setTrueCounterpart(conversation.getMucOptions()
51 .getTrueCounterpart(jid.getResourcepart()));
52 if (conversation.hasDuplicateMessage(finishedMessage)) {
53 return null;
54 }
55
56 }
57 finishedMessage.setCounterpart(jid);
58 finishedMessage.setTime(getTimestamp(packet));
59 return finishedMessage;
60 }
61
62 private Message parseOtrChat(MessagePacket packet, Account account) {
63 final Jid to = packet.getTo();
64 final Jid from = packet.getFrom();
65 if (to == null || from == null) {
66 return null;
67 }
68 boolean properlyAddressed = !to.isBareJid() || account.countPresences() == 1;
69 Conversation conversation = mXmppConnectionService
70 .findOrCreateConversation(account, from.toBareJid(), false);
71 String presence;
72 if (from.isBareJid()) {
73 presence = "";
74 } else {
75 presence = from.getResourcepart();
76 }
77 updateLastseen(packet, account, true);
78 String body = packet.getBody();
79 if (body.matches("^\\?OTRv\\d*\\?")) {
80 conversation.endOtrIfNeeded();
81 }
82 if (!conversation.hasValidOtrSession()) {
83 if (properlyAddressed) {
84 conversation.startOtrSession(presence,false);
85 } else {
86 return null;
87 }
88 } else {
89 String foreignPresence = conversation.getOtrSession()
90 .getSessionID().getUserID();
91 if (!foreignPresence.equals(presence)) {
92 conversation.endOtrIfNeeded();
93 if (properlyAddressed) {
94 conversation.startOtrSession(presence, false);
95 } else {
96 return null;
97 }
98 }
99 }
100 try {
101 Session otrSession = conversation.getOtrSession();
102 SessionStatus before = otrSession.getSessionStatus();
103 body = otrSession.transformReceiving(body);
104 SessionStatus after = otrSession.getSessionStatus();
105 if ((before != after) && (after == SessionStatus.ENCRYPTED)) {
106 mXmppConnectionService.onOtrSessionEstablished(conversation);
107 } else if ((before != after) && (after == SessionStatus.FINISHED)) {
108 conversation.resetOtrSession();
109 mXmppConnectionService.updateConversationUi();
110 }
111 if ((body == null) || (body.isEmpty())) {
112 return null;
113 }
114 if (body.startsWith(CryptoHelper.FILETRANSFER)) {
115 String key = body.substring(CryptoHelper.FILETRANSFER.length());
116 conversation.setSymmetricKey(CryptoHelper.hexToBytes(key));
117 return null;
118 }
119 Message finishedMessage = new Message(conversation, body, Message.ENCRYPTION_OTR,
120 Message.STATUS_RECEIVED);
121 finishedMessage.setTime(getTimestamp(packet));
122 finishedMessage.setRemoteMsgId(packet.getId());
123 finishedMessage.markable = isMarkable(packet);
124 finishedMessage.setCounterpart(from);
125 return finishedMessage;
126 } catch (Exception e) {
127 conversation.resetOtrSession();
128 return null;
129 }
130 }
131
132 private Message parseGroupchat(MessagePacket packet, Account account) {
133 int status;
134 final Jid from = packet.getFrom();
135 if (from == null) {
136 return null;
137 }
138 if (mXmppConnectionService.find(account.pendingConferenceLeaves,
139 account, from.toBareJid()) != null) {
140 return null;
141 }
142 Conversation conversation = mXmppConnectionService
143 .findOrCreateConversation(account, from.toBareJid(), true);
144 if (packet.hasChild("subject")) {
145 conversation.getMucOptions().setSubject(
146 packet.findChild("subject").getContent());
147 mXmppConnectionService.updateConversationUi();
148 return null;
149 }
150 if (from.isBareJid()) {
151 return null;
152 }
153 if (from.getResourcepart().equals(conversation.getMucOptions().getActualNick())) {
154 if (mXmppConnectionService.markMessage(conversation,
155 packet.getId(), Message.STATUS_SEND)) {
156 return null;
157 } else if (packet.getId() == null) {
158 Message message = conversation.findSentMessageWithBody(packet.getBody());
159 if (message != null) {
160 mXmppConnectionService.markMessage(message,Message.STATUS_SEND_RECEIVED);
161 return null;
162 } else {
163 status = Message.STATUS_SEND;
164 }
165 } else {
166 status = Message.STATUS_SEND;
167 }
168 } else {
169 status = Message.STATUS_RECEIVED;
170 }
171 String pgpBody = getPgpBody(packet);
172 Message finishedMessage;
173 if (pgpBody == null) {
174 finishedMessage = new Message(conversation,
175 packet.getBody(), Message.ENCRYPTION_NONE, status);
176 } else {
177 finishedMessage = new Message(conversation, pgpBody,
178 Message.ENCRYPTION_PGP, status);
179 }
180 finishedMessage.setRemoteMsgId(packet.getId());
181 finishedMessage.markable = isMarkable(packet);
182 finishedMessage.setCounterpart(from);
183 if (status == Message.STATUS_RECEIVED) {
184 finishedMessage.setTrueCounterpart(conversation.getMucOptions()
185 .getTrueCounterpart(from.getResourcepart()));
186 }
187 if (packet.hasChild("delay")
188 && conversation.hasDuplicateMessage(finishedMessage)) {
189 return null;
190 }
191 finishedMessage.setTime(getTimestamp(packet));
192 return finishedMessage;
193 }
194
195 private Message parseCarbonMessage(final MessagePacket packet, final Account account) {
196 int status;
197 final Jid fullJid;
198 Element forwarded;
199 if (packet.hasChild("received", "urn:xmpp:carbons:2")) {
200 forwarded = packet.findChild("received", "urn:xmpp:carbons:2")
201 .findChild("forwarded", "urn:xmpp:forward:0");
202 status = Message.STATUS_RECEIVED;
203 } else if (packet.hasChild("sent", "urn:xmpp:carbons:2")) {
204 forwarded = packet.findChild("sent", "urn:xmpp:carbons:2")
205 .findChild("forwarded", "urn:xmpp:forward:0");
206 status = Message.STATUS_SEND;
207 } else {
208 return null;
209 }
210 if (forwarded == null) {
211 return null;
212 }
213 Element message = forwarded.findChild("message");
214 if (message == null) {
215 return null;
216 }
217 if (!message.hasChild("body")) {
218 if (status == Message.STATUS_RECEIVED
219 && message.getAttribute("from") != null) {
220 parseNonMessage(message, account);
221 } else if (status == Message.STATUS_SEND
222 && message.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
223 final Jid to = message.getAttributeAsJid("to");
224 if (to != null) {
225 final Conversation conversation = mXmppConnectionService.find(
226 mXmppConnectionService.getConversations(), account,
227 to.toBareJid());
228 if (conversation != null) {
229 mXmppConnectionService.markRead(conversation);
230 }
231 }
232 }
233 return null;
234 }
235 if (status == Message.STATUS_RECEIVED) {
236 fullJid = message.getAttributeAsJid("from");
237 if (fullJid == null) {
238 return null;
239 } else {
240 updateLastseen(message, account, true);
241 }
242 } else {
243 fullJid = message.getAttributeAsJid("to");
244 if (fullJid == null) {
245 return null;
246 }
247 }
248 if (message.hasChild("x","http://jabber.org/protocol/muc#user")
249 && "chat".equals(message.getAttribute("type"))) {
250 return null;
251 }
252 Conversation conversation = mXmppConnectionService
253 .findOrCreateConversation(account, fullJid.toBareJid(), false);
254 String pgpBody = getPgpBody(message);
255 Message finishedMessage;
256 if (pgpBody != null) {
257 finishedMessage = new Message(conversation, pgpBody,
258 Message.ENCRYPTION_PGP, status);
259 } else {
260 String body = message.findChild("body").getContent();
261 finishedMessage = new Message(conversation, body,
262 Message.ENCRYPTION_NONE, status);
263 }
264 finishedMessage.setTime(getTimestamp(message));
265 finishedMessage.setRemoteMsgId(message.getAttribute("id"));
266 finishedMessage.markable = isMarkable(message);
267 finishedMessage.setCounterpart(fullJid);
268 if (conversation.getMode() == Conversation.MODE_MULTI
269 && !fullJid.isBareJid()) {
270 finishedMessage.setType(Message.TYPE_PRIVATE);
271 finishedMessage.setTrueCounterpart(conversation.getMucOptions()
272 .getTrueCounterpart(fullJid.getResourcepart()));
273 if (conversation.hasDuplicateMessage(finishedMessage)) {
274 return null;
275 }
276 }
277 return finishedMessage;
278 }
279
280 private Message parseMamMessage(MessagePacket packet, final Account account) {
281 final Element result = packet.findChild("result","urn:xmpp:mam:0");
282 if (result == null ) {
283 return null;
284 }
285 final MessageArchiveService.Query query = this.mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
286 if (query!=null) {
287 query.incrementTotalCount();
288 }
289 final Element forwarded = result.findChild("forwarded","urn:xmpp:forward:0");
290 if (forwarded == null) {
291 return null;
292 }
293 final Element message = forwarded.findChild("message");
294 if (message == null) {
295 return null;
296 }
297 final Element body = message.findChild("body");
298 if (body == null || message.hasChild("private","urn:xmpp:carbons:2") || message.hasChild("no-copy","urn:xmpp:hints")) {
299 return null;
300 }
301 int encryption;
302 String content = getPgpBody(message);
303 if (content != null) {
304 encryption = Message.ENCRYPTION_PGP;
305 } else {
306 encryption = Message.ENCRYPTION_NONE;
307 content = body.getContent();
308 }
309 if (content == null) {
310 return null;
311 }
312 final long timestamp = getTimestamp(forwarded);
313 final Jid to = message.getAttributeAsJid("to");
314 final Jid from = message.getAttributeAsJid("from");
315 Jid counterpart;
316 int status;
317 Conversation conversation;
318 if (from!=null && to != null && from.toBareJid().equals(account.getJid().toBareJid())) {
319 status = Message.STATUS_SEND;
320 conversation = this.mXmppConnectionService.findOrCreateConversation(account,to.toBareJid(),false,query);
321 counterpart = to;
322 } else if (from !=null && to != null) {
323 status = Message.STATUS_RECEIVED;
324 conversation = this.mXmppConnectionService.findOrCreateConversation(account,from.toBareJid(),false,query);
325 counterpart = from;
326 } else {
327 return null;
328 }
329 Message finishedMessage = new Message(conversation,content,encryption,status);
330 finishedMessage.setTime(timestamp);
331 finishedMessage.setCounterpart(counterpart);
332 finishedMessage.setRemoteMsgId(message.getAttribute("id"));
333 finishedMessage.setServerMsgId(result.getAttribute("id"));
334 if (conversation.hasDuplicateMessage(finishedMessage)) {
335 return null;
336 }
337 if (query!=null) {
338 query.incrementMessageCount();
339 }
340 return finishedMessage;
341 }
342
343 private void parseError(final MessagePacket packet, final Account account) {
344 final Jid from = packet.getFrom();
345 mXmppConnectionService.markMessage(account, from.toBareJid(),
346 packet.getId(), Message.STATUS_SEND_FAILED);
347 }
348
349 private void parseNonMessage(Element packet, Account account) {
350 final Jid from = packet.getAttributeAsJid("from");
351 Element invite = extractInvite(packet);
352 if (invite != null) {
353 Conversation conversation = mXmppConnectionService.findOrCreateConversation(account,from, true);
354 if (!conversation.getMucOptions().online()) {
355 Element password = invite.findChild("password");
356 conversation.getMucOptions().setPassword(password == null ? null : password.getContent());
357 mXmppConnectionService.databaseBackend.updateConversation(conversation);
358 mXmppConnectionService.joinMuc(conversation);
359 mXmppConnectionService.updateConversationUi();
360 }
361 }
362 if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
363 Element event = packet.findChild("event",
364 "http://jabber.org/protocol/pubsub#event");
365 parseEvent(event, from, account);
366 } else if (from != null
367 && packet.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
368 String id = packet
369 .findChild("displayed", "urn:xmpp:chat-markers:0")
370 .getAttribute("id");
371 updateLastseen(packet, account, true);
372 mXmppConnectionService.markMessage(account, from.toBareJid(),
373 id, Message.STATUS_SEND_DISPLAYED);
374 } else if (from != null
375 && packet.hasChild("received", "urn:xmpp:chat-markers:0")) {
376 String id = packet.findChild("received", "urn:xmpp:chat-markers:0")
377 .getAttribute("id");
378 updateLastseen(packet, account, false);
379 mXmppConnectionService.markMessage(account, from.toBareJid(),
380 id, Message.STATUS_SEND_RECEIVED);
381 } else if (from != null
382 && packet.hasChild("received", "urn:xmpp:receipts")) {
383 String id = packet.findChild("received", "urn:xmpp:receipts")
384 .getAttribute("id");
385 updateLastseen(packet, account, false);
386 mXmppConnectionService.markMessage(account, from.toBareJid(),
387 id, Message.STATUS_SEND_RECEIVED);
388 }
389 }
390
391 private Element extractInvite(Element message) {
392 Element x = message.findChild("x","http://jabber.org/protocol/muc#user");
393 if (x == null) {
394 x = message.findChild("x","jabber:x:conference");
395 }
396 if (x != null && x.hasChild("invite")) {
397 return x;
398 } else {
399 return null;
400 }
401 }
402
403 private void parseEvent(final Element event, final Jid from, final Account account) {
404 Element items = event.findChild("items");
405 if (items == null) {
406 return;
407 }
408 String node = items.getAttribute("node");
409 if (node == null) {
410 return;
411 }
412 if (node.equals("urn:xmpp:avatar:metadata")) {
413 Avatar avatar = Avatar.parseMetadata(items);
414 if (avatar != null) {
415 avatar.owner = from;
416 if (mXmppConnectionService.getFileBackend().isAvatarCached(
417 avatar)) {
418 if (account.getJid().toBareJid().equals(from)) {
419 if (account.setAvatar(avatar.getFilename())) {
420 mXmppConnectionService.databaseBackend
421 .updateAccount(account);
422 }
423 mXmppConnectionService.getAvatarService().clear(
424 account);
425 mXmppConnectionService.updateConversationUi();
426 mXmppConnectionService.updateAccountUi();
427 } else {
428 Contact contact = account.getRoster().getContact(
429 from);
430 contact.setAvatar(avatar.getFilename());
431 mXmppConnectionService.getAvatarService().clear(
432 contact);
433 mXmppConnectionService.updateConversationUi();
434 mXmppConnectionService.updateRosterUi();
435 }
436 } else {
437 mXmppConnectionService.fetchAvatar(account, avatar);
438 }
439 }
440 } else if (node.equals("http://jabber.org/protocol/nick")) {
441 Element item = items.findChild("item");
442 if (item != null) {
443 Element nick = item.findChild("nick",
444 "http://jabber.org/protocol/nick");
445 if (nick != null) {
446 if (from != null) {
447 Contact contact = account.getRoster().getContact(
448 from);
449 contact.setPresenceName(nick.getContent());
450 mXmppConnectionService.getAvatarService().clear(account);
451 mXmppConnectionService.updateConversationUi();
452 mXmppConnectionService.updateAccountUi();
453 }
454 }
455 }
456 }
457 }
458
459 private String getPgpBody(Element message) {
460 Element child = message.findChild("x", "jabber:x:encrypted");
461 if (child == null) {
462 return null;
463 } else {
464 return child.getContent();
465 }
466 }
467
468 private boolean isMarkable(Element message) {
469 return message.hasChild("markable", "urn:xmpp:chat-markers:0");
470 }
471
472 @Override
473 public void onMessagePacketReceived(Account account, MessagePacket packet) {
474 Message message = null;
475 this.parseNick(packet, account);
476 if ((packet.getType() == MessagePacket.TYPE_CHAT || packet.getType() == MessagePacket.TYPE_NORMAL)) {
477 if ((packet.getBody() != null)
478 && (packet.getBody().startsWith("?OTR"))) {
479 message = this.parseOtrChat(packet, account);
480 if (message != null) {
481 message.markUnread();
482 }
483 } else if (packet.hasChild("body") && extractInvite(packet) == null) {
484 message = this.parseChat(packet, account);
485 if (message != null) {
486 message.markUnread();
487 }
488 } else if (packet.hasChild("received", "urn:xmpp:carbons:2")
489 || (packet.hasChild("sent", "urn:xmpp:carbons:2"))) {
490 message = this.parseCarbonMessage(packet, account);
491 if (message != null) {
492 if (message.getStatus() == Message.STATUS_SEND) {
493 account.activateGracePeriod();
494 mXmppConnectionService.markRead(message.getConversation());
495 } else {
496 message.markUnread();
497 }
498 }
499 } else if (packet.hasChild("result","urn:xmpp:mam:0")) {
500 message = parseMamMessage(packet, account);
501 if (message != null) {
502 Conversation conversation = message.getConversation();
503 conversation.add(message);
504 mXmppConnectionService.databaseBackend.createMessage(message);
505 }
506 return;
507 } else if (packet.hasChild("fin","urn:xmpp:mam:0")) {
508 Element fin = packet.findChild("fin","urn:xmpp:mam:0");
509 mXmppConnectionService.getMessageArchiveService().processFin(fin);
510 } else {
511 parseNonMessage(packet, account);
512 }
513 } else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
514 message = this.parseGroupchat(packet, account);
515 if (message != null) {
516 if (message.getStatus() == Message.STATUS_RECEIVED) {
517 message.markUnread();
518 } else {
519 mXmppConnectionService.markRead(message.getConversation());
520 account.activateGracePeriod();
521 }
522 }
523 } else if (packet.getType() == MessagePacket.TYPE_ERROR) {
524 this.parseError(packet, account);
525 return;
526 } else if (packet.getType() == MessagePacket.TYPE_HEADLINE) {
527 this.parseHeadline(packet, account);
528 return;
529 }
530 if ((message == null) || (message.getBody() == null)) {
531 return;
532 }
533 if ((mXmppConnectionService.confirmMessages())
534 && ((packet.getId() != null))) {
535 if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
536 MessagePacket receipt = mXmppConnectionService
537 .getMessageGenerator().received(account, packet,
538 "urn:xmpp:chat-markers:0");
539 mXmppConnectionService.sendMessagePacket(account, receipt);
540 }
541 if (packet.hasChild("request", "urn:xmpp:receipts")) {
542 MessagePacket receipt = mXmppConnectionService
543 .getMessageGenerator().received(account, packet,
544 "urn:xmpp:receipts");
545 mXmppConnectionService.sendMessagePacket(account, receipt);
546 }
547 }
548 Conversation conversation = message.getConversation();
549 conversation.add(message);
550 if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().advancedStreamFeaturesLoaded()) {
551 if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
552 mXmppConnectionService.updateConversation(conversation);
553 }
554 }
555
556 if (message.getStatus() == Message.STATUS_RECEIVED
557 && conversation.getOtrSession() != null
558 && !conversation.getOtrSession().getSessionID().getUserID()
559 .equals(message.getCounterpart().getResourcepart())) {
560 conversation.endOtrIfNeeded();
561 }
562
563 if (packet.getType() != MessagePacket.TYPE_ERROR) {
564 if (message.getEncryption() == Message.ENCRYPTION_NONE
565 || mXmppConnectionService.saveEncryptedMessages()) {
566 mXmppConnectionService.databaseBackend.createMessage(message);
567 }
568 }
569 if (message.trusted() && message.bodyContainsDownloadable()) {
570 this.mXmppConnectionService.getHttpConnectionManager()
571 .createNewConnection(message);
572 } else if (!message.isRead()) {
573 mXmppConnectionService.getNotificationService().push(message);
574 }
575 mXmppConnectionService.updateConversationUi();
576 }
577
578 private void parseHeadline(MessagePacket packet, Account account) {
579 if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
580 Element event = packet.findChild("event",
581 "http://jabber.org/protocol/pubsub#event");
582 parseEvent(event, packet.getFrom(), account);
583 }
584 }
585
586 private void parseNick(MessagePacket packet, Account account) {
587 Element nick = packet.findChild("nick",
588 "http://jabber.org/protocol/nick");
589 if (nick != null) {
590 if (packet.getFrom() != null) {
591 Contact contact = account.getRoster().getContact(
592 packet.getFrom());
593 contact.setPresenceName(nick.getContent());
594 }
595 }
596 }
597}