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 if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
352 Element event = packet.findChild("event",
353 "http://jabber.org/protocol/pubsub#event");
354 parseEvent(event, from, account);
355 } else if (from != null
356 && packet.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
357 String id = packet
358 .findChild("displayed", "urn:xmpp:chat-markers:0")
359 .getAttribute("id");
360 updateLastseen(packet, account, true);
361 mXmppConnectionService.markMessage(account, from.toBareJid(),
362 id, Message.STATUS_SEND_DISPLAYED);
363 } else if (from != null
364 && packet.hasChild("received", "urn:xmpp:chat-markers:0")) {
365 String id = packet.findChild("received", "urn:xmpp:chat-markers:0")
366 .getAttribute("id");
367 updateLastseen(packet, account, false);
368 mXmppConnectionService.markMessage(account, from.toBareJid(),
369 id, Message.STATUS_SEND_RECEIVED);
370 } else if (from != null
371 && packet.hasChild("received", "urn:xmpp:receipts")) {
372 String id = packet.findChild("received", "urn:xmpp:receipts")
373 .getAttribute("id");
374 updateLastseen(packet, account, false);
375 mXmppConnectionService.markMessage(account, from.toBareJid(),
376 id, Message.STATUS_SEND_RECEIVED);
377 } else if (packet.hasChild("x", "http://jabber.org/protocol/muc#user")) {
378 Element x = packet.findChild("x",
379 "http://jabber.org/protocol/muc#user");
380 if (x.hasChild("invite")) {
381 Conversation conversation = mXmppConnectionService
382 .findOrCreateConversation(account,
383 packet.getAttributeAsJid("from"), true);
384 if (!conversation.getMucOptions().online()) {
385 if (x.hasChild("password")) {
386 Element password = x.findChild("password");
387 conversation.getMucOptions().setPassword(
388 password.getContent());
389 mXmppConnectionService.databaseBackend
390 .updateConversation(conversation);
391 }
392 mXmppConnectionService.joinMuc(conversation);
393 mXmppConnectionService.updateConversationUi();
394 }
395 }
396 } else if (packet.hasChild("x", "jabber:x:conference")) {
397 Element x = packet.findChild("x", "jabber:x:conference");
398 Jid jid = x.getAttributeAsJid("jid");
399 String password = x.getAttribute("password");
400 if (jid != null) {
401 Conversation conversation = mXmppConnectionService
402 .findOrCreateConversation(account, jid, true);
403 if (!conversation.getMucOptions().online()) {
404 if (password != null) {
405 conversation.getMucOptions().setPassword(password);
406 mXmppConnectionService.databaseBackend
407 .updateConversation(conversation);
408 }
409 mXmppConnectionService.joinMuc(conversation);
410 mXmppConnectionService.updateConversationUi();
411 }
412 }
413 }
414 }
415
416 private void parseEvent(final Element event, final Jid from, final Account account) {
417 Element items = event.findChild("items");
418 if (items == null) {
419 return;
420 }
421 String node = items.getAttribute("node");
422 if (node == null) {
423 return;
424 }
425 if (node.equals("urn:xmpp:avatar:metadata")) {
426 Avatar avatar = Avatar.parseMetadata(items);
427 if (avatar != null) {
428 avatar.owner = from;
429 if (mXmppConnectionService.getFileBackend().isAvatarCached(
430 avatar)) {
431 if (account.getJid().toBareJid().equals(from)) {
432 if (account.setAvatar(avatar.getFilename())) {
433 mXmppConnectionService.databaseBackend
434 .updateAccount(account);
435 }
436 mXmppConnectionService.getAvatarService().clear(
437 account);
438 mXmppConnectionService.updateConversationUi();
439 mXmppConnectionService.updateAccountUi();
440 } else {
441 Contact contact = account.getRoster().getContact(
442 from);
443 contact.setAvatar(avatar.getFilename());
444 mXmppConnectionService.getAvatarService().clear(
445 contact);
446 mXmppConnectionService.updateConversationUi();
447 mXmppConnectionService.updateRosterUi();
448 }
449 } else {
450 mXmppConnectionService.fetchAvatar(account, avatar);
451 }
452 }
453 } else if (node.equals("http://jabber.org/protocol/nick")) {
454 Element item = items.findChild("item");
455 if (item != null) {
456 Element nick = item.findChild("nick",
457 "http://jabber.org/protocol/nick");
458 if (nick != null) {
459 if (from != null) {
460 Contact contact = account.getRoster().getContact(
461 from);
462 contact.setPresenceName(nick.getContent());
463 mXmppConnectionService.getAvatarService().clear(account);
464 mXmppConnectionService.updateConversationUi();
465 mXmppConnectionService.updateAccountUi();
466 }
467 }
468 }
469 }
470 }
471
472 private String getPgpBody(Element message) {
473 Element child = message.findChild("x", "jabber:x:encrypted");
474 if (child == null) {
475 return null;
476 } else {
477 return child.getContent();
478 }
479 }
480
481 private boolean isMarkable(Element message) {
482 return message.hasChild("markable", "urn:xmpp:chat-markers:0");
483 }
484
485 @Override
486 public void onMessagePacketReceived(Account account, MessagePacket packet) {
487 Message message = null;
488 this.parseNick(packet, account);
489 if ((packet.getType() == MessagePacket.TYPE_CHAT || packet.getType() == MessagePacket.TYPE_NORMAL)) {
490 if ((packet.getBody() != null)
491 && (packet.getBody().startsWith("?OTR"))) {
492 message = this.parseOtrChat(packet, account);
493 if (message != null) {
494 message.markUnread();
495 }
496 } else if (packet.hasChild("body")) {
497 message = this.parseChat(packet, account);
498 if (message != null) {
499 message.markUnread();
500 }
501 } else if (packet.hasChild("received", "urn:xmpp:carbons:2")
502 || (packet.hasChild("sent", "urn:xmpp:carbons:2"))) {
503 message = this.parseCarbonMessage(packet, account);
504 if (message != null) {
505 if (message.getStatus() == Message.STATUS_SEND) {
506 account.activateGracePeriod();
507 mXmppConnectionService.markRead(message.getConversation());
508 } else {
509 message.markUnread();
510 }
511 }
512 } else if (packet.hasChild("result","urn:xmpp:mam:0")) {
513 message = parseMamMessage(packet, account);
514 if (message != null) {
515 Conversation conversation = message.getConversation();
516 conversation.add(message);
517 mXmppConnectionService.databaseBackend.createMessage(message);
518 }
519 return;
520 } else if (packet.hasChild("fin","urn:xmpp:mam:0")) {
521 Element fin = packet.findChild("fin","urn:xmpp:mam:0");
522 mXmppConnectionService.getMessageArchiveService().processFin(fin);
523 } else {
524 parseNonMessage(packet, account);
525 }
526 } else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
527 message = this.parseGroupchat(packet, account);
528 if (message != null) {
529 if (message.getStatus() == Message.STATUS_RECEIVED) {
530 message.markUnread();
531 } else {
532 mXmppConnectionService.markRead(message.getConversation());
533 account.activateGracePeriod();
534 }
535 }
536 } else if (packet.getType() == MessagePacket.TYPE_ERROR) {
537 this.parseError(packet, account);
538 return;
539 } else if (packet.getType() == MessagePacket.TYPE_HEADLINE) {
540 this.parseHeadline(packet, account);
541 return;
542 }
543 if ((message == null) || (message.getBody() == null)) {
544 return;
545 }
546 if ((mXmppConnectionService.confirmMessages())
547 && ((packet.getId() != null))) {
548 if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
549 MessagePacket receipt = mXmppConnectionService
550 .getMessageGenerator().received(account, packet,
551 "urn:xmpp:chat-markers:0");
552 mXmppConnectionService.sendMessagePacket(account, receipt);
553 }
554 if (packet.hasChild("request", "urn:xmpp:receipts")) {
555 MessagePacket receipt = mXmppConnectionService
556 .getMessageGenerator().received(account, packet,
557 "urn:xmpp:receipts");
558 mXmppConnectionService.sendMessagePacket(account, receipt);
559 }
560 }
561 Conversation conversation = message.getConversation();
562 conversation.add(message);
563 if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().advancedStreamFeaturesLoaded()) {
564 if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
565 mXmppConnectionService.updateConversation(conversation);
566 }
567 }
568
569 if (message.getStatus() == Message.STATUS_RECEIVED
570 && conversation.getOtrSession() != null
571 && !conversation.getOtrSession().getSessionID().getUserID()
572 .equals(message.getCounterpart().getResourcepart())) {
573 conversation.endOtrIfNeeded();
574 }
575
576 if (packet.getType() != MessagePacket.TYPE_ERROR) {
577 if (message.getEncryption() == Message.ENCRYPTION_NONE
578 || mXmppConnectionService.saveEncryptedMessages()) {
579 mXmppConnectionService.databaseBackend.createMessage(message);
580 }
581 }
582 if (message.trusted() && message.bodyContainsDownloadable()) {
583 this.mXmppConnectionService.getHttpConnectionManager()
584 .createNewConnection(message);
585 } else if (!message.isRead()) {
586 mXmppConnectionService.getNotificationService().push(message);
587 }
588 mXmppConnectionService.updateConversationUi();
589 }
590
591 private void parseHeadline(MessagePacket packet, Account account) {
592 if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
593 Element event = packet.findChild("event",
594 "http://jabber.org/protocol/pubsub#event");
595 parseEvent(event, packet.getFrom(), account);
596 }
597 }
598
599 private void parseNick(MessagePacket packet, Account account) {
600 Element nick = packet.findChild("nick",
601 "http://jabber.org/protocol/nick");
602 if (nick != null) {
603 if (packet.getFrom() != null) {
604 Contact contact = account.getRoster().getContact(
605 packet.getFrom());
606 contact.setPresenceName(nick.getContent());
607 }
608 }
609 }
610}