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, false);
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 Conversation conversation = mXmppConnectionService
249 .findOrCreateConversation(account, fullJid.toBareJid(), false);
250 String pgpBody = getPgpBody(message);
251 Message finishedMessage;
252 if (pgpBody != null) {
253 finishedMessage = new Message(conversation, pgpBody,
254 Message.ENCRYPTION_PGP, status);
255 } else {
256 String body = message.findChild("body").getContent();
257 finishedMessage = new Message(conversation, body,
258 Message.ENCRYPTION_NONE, status);
259 }
260 finishedMessage.setTime(getTimestamp(message));
261 finishedMessage.setRemoteMsgId(message.getAttribute("id"));
262 finishedMessage.markable = isMarkable(message);
263 finishedMessage.setCounterpart(fullJid);
264 if (conversation.getMode() == Conversation.MODE_MULTI
265 && !fullJid.isBareJid()) {
266 finishedMessage.setType(Message.TYPE_PRIVATE);
267 finishedMessage.setTrueCounterpart(conversation.getMucOptions()
268 .getTrueCounterpart(fullJid.getResourcepart()));
269 if (conversation.hasDuplicateMessage(finishedMessage)) {
270 return null;
271 }
272 }
273 return finishedMessage;
274 }
275
276 private Message parseMamMessage(MessagePacket packet, final Account account) {
277 final Element result = packet.findChild("result","urn:xmpp:mam:0");
278 if (result == null ) {
279 return null;
280 }
281 final Element forwarded = result.findChild("forwarded","urn:xmpp:forward:0");
282 if (forwarded == null) {
283 return null;
284 }
285 final Element message = forwarded.findChild("message");
286 if (message == null) {
287 return null;
288 }
289 final Element body = message.findChild("body");
290 if (body == null || message.hasChild("private","urn:xmpp:carbons:2") || message.hasChild("no-copy","urn:xmpp:hints")) {
291 return null;
292 }
293 int encryption;
294 String content = getPgpBody(message);
295 if (content != null) {
296 encryption = Message.ENCRYPTION_PGP;
297 } else {
298 encryption = Message.ENCRYPTION_NONE;
299 content = body.getContent();
300 }
301 if (content == null) {
302 return null;
303 }
304 final long timestamp = getTimestamp(forwarded);
305 final Jid to = message.getAttributeAsJid("to");
306 final Jid from = message.getAttributeAsJid("from");
307 final MessageArchiveService.Query query = this.mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
308 Jid counterpart;
309 int status;
310 Conversation conversation;
311 if (from!=null && to != null && from.toBareJid().equals(account.getJid().toBareJid())) {
312 status = Message.STATUS_SEND;
313 conversation = this.mXmppConnectionService.findOrCreateConversation(account,to.toBareJid(),false,query);
314 counterpart = to;
315 } else if (from !=null && to != null) {
316 status = Message.STATUS_RECEIVED;
317 conversation = this.mXmppConnectionService.findOrCreateConversation(account,from.toBareJid(),false,query);
318 counterpart = from;
319 } else {
320 return null;
321 }
322 Message finishedMessage = new Message(conversation,content,encryption,status);
323 finishedMessage.setTime(timestamp);
324 finishedMessage.setCounterpart(counterpart);
325 finishedMessage.setRemoteMsgId(message.getAttribute("id"));
326 finishedMessage.setServerMsgId(result.getAttribute("id"));
327 if (query!=null) {
328 query.incrementCount();
329 }
330 return finishedMessage;
331 }
332
333 private void parseError(final MessagePacket packet, final Account account) {
334 final Jid from = packet.getFrom();
335 mXmppConnectionService.markMessage(account, from.toBareJid(),
336 packet.getId(), Message.STATUS_SEND_FAILED);
337 }
338
339 private void parseNonMessage(Element packet, Account account) {
340 final Jid from = packet.getAttributeAsJid("from");
341 if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
342 Element event = packet.findChild("event",
343 "http://jabber.org/protocol/pubsub#event");
344 parseEvent(event, from, account);
345 } else if (from != null
346 && packet.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
347 String id = packet
348 .findChild("displayed", "urn:xmpp:chat-markers:0")
349 .getAttribute("id");
350 updateLastseen(packet, account, true);
351 mXmppConnectionService.markMessage(account, from.toBareJid(),
352 id, Message.STATUS_SEND_DISPLAYED);
353 } else if (from != null
354 && packet.hasChild("received", "urn:xmpp:chat-markers:0")) {
355 String id = packet.findChild("received", "urn:xmpp:chat-markers:0")
356 .getAttribute("id");
357 updateLastseen(packet, account, false);
358 mXmppConnectionService.markMessage(account, from.toBareJid(),
359 id, Message.STATUS_SEND_RECEIVED);
360 } else if (from != null
361 && packet.hasChild("received", "urn:xmpp:receipts")) {
362 String id = packet.findChild("received", "urn:xmpp:receipts")
363 .getAttribute("id");
364 updateLastseen(packet, account, false);
365 mXmppConnectionService.markMessage(account, from.toBareJid(),
366 id, Message.STATUS_SEND_RECEIVED);
367 } else if (packet.hasChild("x", "http://jabber.org/protocol/muc#user")) {
368 Element x = packet.findChild("x",
369 "http://jabber.org/protocol/muc#user");
370 if (x.hasChild("invite")) {
371 Conversation conversation = mXmppConnectionService
372 .findOrCreateConversation(account,
373 packet.getAttributeAsJid("from"), true);
374 if (!conversation.getMucOptions().online()) {
375 if (x.hasChild("password")) {
376 Element password = x.findChild("password");
377 conversation.getMucOptions().setPassword(
378 password.getContent());
379 mXmppConnectionService.databaseBackend
380 .updateConversation(conversation);
381 }
382 mXmppConnectionService.joinMuc(conversation);
383 mXmppConnectionService.updateConversationUi();
384 }
385 }
386 } else if (packet.hasChild("x", "jabber:x:conference")) {
387 Element x = packet.findChild("x", "jabber:x:conference");
388 Jid jid = x.getAttributeAsJid("jid");
389 String password = x.getAttribute("password");
390 if (jid != null) {
391 Conversation conversation = mXmppConnectionService
392 .findOrCreateConversation(account, jid, true);
393 if (!conversation.getMucOptions().online()) {
394 if (password != null) {
395 conversation.getMucOptions().setPassword(password);
396 mXmppConnectionService.databaseBackend
397 .updateConversation(conversation);
398 }
399 mXmppConnectionService.joinMuc(conversation);
400 mXmppConnectionService.updateConversationUi();
401 }
402 }
403 }
404 }
405
406 private void parseEvent(final Element event, final Jid from, final Account account) {
407 Element items = event.findChild("items");
408 if (items == null) {
409 return;
410 }
411 String node = items.getAttribute("node");
412 if (node == null) {
413 return;
414 }
415 if (node.equals("urn:xmpp:avatar:metadata")) {
416 Avatar avatar = Avatar.parseMetadata(items);
417 if (avatar != null) {
418 avatar.owner = from;
419 if (mXmppConnectionService.getFileBackend().isAvatarCached(
420 avatar)) {
421 if (account.getJid().toBareJid().equals(from)) {
422 if (account.setAvatar(avatar.getFilename())) {
423 mXmppConnectionService.databaseBackend
424 .updateAccount(account);
425 }
426 mXmppConnectionService.getAvatarService().clear(
427 account);
428 mXmppConnectionService.updateConversationUi();
429 mXmppConnectionService.updateAccountUi();
430 } else {
431 Contact contact = account.getRoster().getContact(
432 from);
433 contact.setAvatar(avatar.getFilename());
434 mXmppConnectionService.getAvatarService().clear(
435 contact);
436 mXmppConnectionService.updateConversationUi();
437 mXmppConnectionService.updateRosterUi();
438 }
439 } else {
440 mXmppConnectionService.fetchAvatar(account, avatar);
441 }
442 }
443 } else if (node.equals("http://jabber.org/protocol/nick")) {
444 Element item = items.findChild("item");
445 if (item != null) {
446 Element nick = item.findChild("nick",
447 "http://jabber.org/protocol/nick");
448 if (nick != null) {
449 if (from != null) {
450 Contact contact = account.getRoster().getContact(
451 from);
452 contact.setPresenceName(nick.getContent());
453 mXmppConnectionService.getAvatarService().clear(account);
454 mXmppConnectionService.updateConversationUi();
455 mXmppConnectionService.updateAccountUi();
456 }
457 }
458 }
459 }
460 }
461
462 private String getPgpBody(Element message) {
463 Element child = message.findChild("x", "jabber:x:encrypted");
464 if (child == null) {
465 return null;
466 } else {
467 return child.getContent();
468 }
469 }
470
471 private boolean isMarkable(Element message) {
472 return message.hasChild("markable", "urn:xmpp:chat-markers:0");
473 }
474
475 @Override
476 public void onMessagePacketReceived(Account account, MessagePacket packet) {
477 Message message = null;
478 this.parseNick(packet, account);
479
480 if ((packet.getType() == MessagePacket.TYPE_CHAT || packet.getType() == MessagePacket.TYPE_NORMAL)) {
481 if ((packet.getBody() != null)
482 && (packet.getBody().startsWith("?OTR"))) {
483 message = this.parseOtrChat(packet, account);
484 if (message != null) {
485 message.markUnread();
486 }
487 } else if (packet.hasChild("body")
488 && !(packet.hasChild("x",
489 "http://jabber.org/protocol/muc#user"))) {
490 message = this.parseChat(packet, account);
491 if (message != null) {
492 message.markUnread();
493 }
494 } else if (packet.hasChild("received", "urn:xmpp:carbons:2")
495 || (packet.hasChild("sent", "urn:xmpp:carbons:2"))) {
496 message = this.parseCarbonMessage(packet, account);
497 if (message != null) {
498 if (message.getStatus() == Message.STATUS_SEND) {
499 account.activateGracePeriod();
500 mXmppConnectionService.markRead(
501 message.getConversation(), false);
502 } else {
503 message.markUnread();
504 }
505 }
506 } else if (packet.hasChild("result","urn:xmpp:mam:0")) {
507 message = parseMamMessage(packet, account);
508 if (message != null) {
509 Conversation conversation = message.getConversation();
510 conversation.add(message);
511 mXmppConnectionService.databaseBackend.createMessage(message);
512 }
513 return;
514 } else if (packet.hasChild("fin","urn:xmpp:mam:0")) {
515 Element fin = packet.findChild("fin","urn:xmpp:mam:0");
516 mXmppConnectionService.getMessageArchiveService().processFin(fin);
517 } else {
518 parseNonMessage(packet, account);
519 }
520 } else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
521 message = this.parseGroupchat(packet, account);
522 if (message != null) {
523 if (message.getStatus() == Message.STATUS_RECEIVED) {
524 message.markUnread();
525 } else {
526 mXmppConnectionService.markRead(message.getConversation(),
527 false);
528 account.activateGracePeriod();
529 }
530 }
531 } else if (packet.getType() == MessagePacket.TYPE_ERROR) {
532 this.parseError(packet, account);
533 return;
534 } else if (packet.getType() == MessagePacket.TYPE_HEADLINE) {
535 this.parseHeadline(packet, account);
536 return;
537 }
538 if ((message == null) || (message.getBody() == null)) {
539 return;
540 }
541 if ((mXmppConnectionService.confirmMessages())
542 && ((packet.getId() != null))) {
543 if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
544 MessagePacket receipt = mXmppConnectionService
545 .getMessageGenerator().received(account, packet,
546 "urn:xmpp:chat-markers:0");
547 mXmppConnectionService.sendMessagePacket(account, receipt);
548 }
549 if (packet.hasChild("request", "urn:xmpp:receipts")) {
550 MessagePacket receipt = mXmppConnectionService
551 .getMessageGenerator().received(account, packet,
552 "urn:xmpp:receipts");
553 mXmppConnectionService.sendMessagePacket(account, receipt);
554 }
555 }
556 Conversation conversation = message.getConversation();
557 conversation.add(message);
558 if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().advancedStreamFeaturesLoaded()) {
559 if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
560 mXmppConnectionService.updateConversation(conversation);
561 }
562 }
563
564 if (message.getStatus() == Message.STATUS_RECEIVED
565 && conversation.getOtrSession() != null
566 && !conversation.getOtrSession().getSessionID().getUserID()
567 .equals(message.getCounterpart().getResourcepart())) {
568 conversation.endOtrIfNeeded();
569 }
570
571 if (packet.getType() != MessagePacket.TYPE_ERROR) {
572 if (message.getEncryption() == Message.ENCRYPTION_NONE
573 || mXmppConnectionService.saveEncryptedMessages()) {
574 mXmppConnectionService.databaseBackend.createMessage(message);
575 }
576 }
577 if (message.trusted() && message.bodyContainsDownloadable()) {
578 this.mXmppConnectionService.getHttpConnectionManager()
579 .createNewConnection(message);
580 } else if (!message.isRead()) {
581 mXmppConnectionService.getNotificationService().push(message);
582 }
583 mXmppConnectionService.updateConversationUi();
584 }
585
586 private void parseHeadline(MessagePacket packet, Account account) {
587 if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
588 Element event = packet.findChild("event",
589 "http://jabber.org/protocol/pubsub#event");
590 parseEvent(event, packet.getFrom(), account);
591 }
592 }
593
594 private void parseNick(MessagePacket packet, Account account) {
595 Element nick = packet.findChild("nick",
596 "http://jabber.org/protocol/nick");
597 if (nick != null) {
598 if (packet.getFrom() != null) {
599 Contact contact = account.getRoster().getContact(
600 packet.getFrom());
601 contact.setPresenceName(nick.getContent());
602 }
603 }
604 }
605}