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.XmppConnectionService;
14import eu.siacs.conversations.utils.CryptoHelper;
15import eu.siacs.conversations.xml.Element;
16import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
17import eu.siacs.conversations.xmpp.jid.InvalidJidException;
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 boolean properlyAddressed = (!packet.getTo().isBareJid())
64 || (account.countPresences() == 1);
65 final Jid from = packet.getFrom();
66 if (from == null) {
67 return null;
68 }
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 void parseError(final MessagePacket packet, final Account account) {
277 final Jid from = packet.getFrom();
278 mXmppConnectionService.markMessage(account, from.toBareJid(),
279 packet.getId(), Message.STATUS_SEND_FAILED);
280 }
281
282 private void parseNonMessage(Element packet, Account account) {
283 final Jid from = packet.getAttributeAsJid("from");
284 if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
285 Element event = packet.findChild("event",
286 "http://jabber.org/protocol/pubsub#event");
287 parseEvent(event, from, account);
288 } else if (from != null
289 && packet.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
290 String id = packet
291 .findChild("displayed", "urn:xmpp:chat-markers:0")
292 .getAttribute("id");
293 updateLastseen(packet, account, true);
294 mXmppConnectionService.markMessage(account, from.toBareJid(),
295 id, Message.STATUS_SEND_DISPLAYED);
296 } else if (from != null
297 && packet.hasChild("received", "urn:xmpp:chat-markers:0")) {
298 String id = packet.findChild("received", "urn:xmpp:chat-markers:0")
299 .getAttribute("id");
300 updateLastseen(packet, account, false);
301 mXmppConnectionService.markMessage(account, from.toBareJid(),
302 id, Message.STATUS_SEND_RECEIVED);
303 } else if (from != null
304 && packet.hasChild("received", "urn:xmpp:receipts")) {
305 String id = packet.findChild("received", "urn:xmpp:receipts")
306 .getAttribute("id");
307 updateLastseen(packet, account, false);
308 mXmppConnectionService.markMessage(account, from.toBareJid(),
309 id, Message.STATUS_SEND_RECEIVED);
310 } else if (packet.hasChild("x", "http://jabber.org/protocol/muc#user")) {
311 Element x = packet.findChild("x",
312 "http://jabber.org/protocol/muc#user");
313 if (x.hasChild("invite")) {
314 Conversation conversation = mXmppConnectionService
315 .findOrCreateConversation(account,
316 packet.getAttributeAsJid("from"), true);
317 if (!conversation.getMucOptions().online()) {
318 if (x.hasChild("password")) {
319 Element password = x.findChild("password");
320 conversation.getMucOptions().setPassword(
321 password.getContent());
322 mXmppConnectionService.databaseBackend
323 .updateConversation(conversation);
324 }
325 mXmppConnectionService.joinMuc(conversation);
326 mXmppConnectionService.updateConversationUi();
327 }
328 }
329 } else if (packet.hasChild("x", "jabber:x:conference")) {
330 Element x = packet.findChild("x", "jabber:x:conference");
331 Jid jid = x.getAttributeAsJid("jid");
332 String password = x.getAttribute("password");
333 if (jid != null) {
334 Conversation conversation = mXmppConnectionService
335 .findOrCreateConversation(account, jid, true);
336 if (!conversation.getMucOptions().online()) {
337 if (password != null) {
338 conversation.getMucOptions().setPassword(password);
339 mXmppConnectionService.databaseBackend
340 .updateConversation(conversation);
341 }
342 mXmppConnectionService.joinMuc(conversation);
343 mXmppConnectionService.updateConversationUi();
344 }
345 }
346 }
347 }
348
349 private void parseEvent(final Element event, final Jid from, final Account account) {
350 Element items = event.findChild("items");
351 if (items == null) {
352 return;
353 }
354 String node = items.getAttribute("node");
355 if (node == null) {
356 return;
357 }
358 if (node.equals("urn:xmpp:avatar:metadata")) {
359 Avatar avatar = Avatar.parseMetadata(items);
360 if (avatar != null) {
361 avatar.owner = from;
362 if (mXmppConnectionService.getFileBackend().isAvatarCached(
363 avatar)) {
364 if (account.getJid().toBareJid().equals(from)) {
365 if (account.setAvatar(avatar.getFilename())) {
366 mXmppConnectionService.databaseBackend
367 .updateAccount(account);
368 }
369 mXmppConnectionService.getAvatarService().clear(
370 account);
371 mXmppConnectionService.updateConversationUi();
372 mXmppConnectionService.updateAccountUi();
373 } else {
374 Contact contact = account.getRoster().getContact(
375 from);
376 contact.setAvatar(avatar.getFilename());
377 mXmppConnectionService.getAvatarService().clear(
378 contact);
379 mXmppConnectionService.updateConversationUi();
380 mXmppConnectionService.updateRosterUi();
381 }
382 } else {
383 mXmppConnectionService.fetchAvatar(account, avatar);
384 }
385 }
386 } else if (node.equals("http://jabber.org/protocol/nick")) {
387 Element item = items.findChild("item");
388 if (item != null) {
389 Element nick = item.findChild("nick",
390 "http://jabber.org/protocol/nick");
391 if (nick != null) {
392 if (from != null) {
393 Contact contact = account.getRoster().getContact(
394 from);
395 contact.setPresenceName(nick.getContent());
396 mXmppConnectionService.getAvatarService().clear(account);
397 mXmppConnectionService.updateConversationUi();
398 mXmppConnectionService.updateAccountUi();
399 }
400 }
401 }
402 }
403 }
404
405 private String getPgpBody(Element message) {
406 Element child = message.findChild("x", "jabber:x:encrypted");
407 if (child == null) {
408 return null;
409 } else {
410 return child.getContent();
411 }
412 }
413
414 private boolean isMarkable(Element message) {
415 return message.hasChild("markable", "urn:xmpp:chat-markers:0");
416 }
417
418 @Override
419 public void onMessagePacketReceived(Account account, MessagePacket packet) {
420 Message message = null;
421 this.parseNick(packet, account);
422
423 if ((packet.getType() == MessagePacket.TYPE_CHAT || packet.getType() == MessagePacket.TYPE_NORMAL)) {
424 if ((packet.getBody() != null)
425 && (packet.getBody().startsWith("?OTR"))) {
426 message = this.parseOtrChat(packet, account);
427 if (message != null) {
428 message.markUnread();
429 }
430 } else if (packet.hasChild("body")
431 && !(packet.hasChild("x",
432 "http://jabber.org/protocol/muc#user"))) {
433 message = this.parseChat(packet, account);
434 if (message != null) {
435 message.markUnread();
436 }
437 } else if (packet.hasChild("received", "urn:xmpp:carbons:2")
438 || (packet.hasChild("sent", "urn:xmpp:carbons:2"))) {
439 message = this.parseCarbonMessage(packet, account);
440 if (message != null) {
441 if (message.getStatus() == Message.STATUS_SEND) {
442 account.activateGracePeriod();
443 mXmppConnectionService.markRead(
444 message.getConversation(), false);
445 } else {
446 message.markUnread();
447 }
448 }
449 } else {
450 parseNonMessage(packet, account);
451 }
452 } else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
453 message = this.parseGroupchat(packet, account);
454 if (message != null) {
455 if (message.getStatus() == Message.STATUS_RECEIVED) {
456 message.markUnread();
457 } else {
458 mXmppConnectionService.markRead(message.getConversation(),
459 false);
460 account.activateGracePeriod();
461 }
462 }
463 } else if (packet.getType() == MessagePacket.TYPE_ERROR) {
464 this.parseError(packet, account);
465 return;
466 } else if (packet.getType() == MessagePacket.TYPE_HEADLINE) {
467 this.parseHeadline(packet, account);
468 return;
469 }
470 if ((message == null) || (message.getBody() == null)) {
471 return;
472 }
473 if ((mXmppConnectionService.confirmMessages())
474 && ((packet.getId() != null))) {
475 if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
476 MessagePacket receipt = mXmppConnectionService
477 .getMessageGenerator().received(account, packet,
478 "urn:xmpp:chat-markers:0");
479 mXmppConnectionService.sendMessagePacket(account, receipt);
480 }
481 if (packet.hasChild("request", "urn:xmpp:receipts")) {
482 MessagePacket receipt = mXmppConnectionService
483 .getMessageGenerator().received(account, packet,
484 "urn:xmpp:receipts");
485 mXmppConnectionService.sendMessagePacket(account, receipt);
486 }
487 }
488 Conversation conversation = message.getConversation();
489 conversation.add(message);
490
491 if (message.getStatus() == Message.STATUS_RECEIVED
492 && conversation.getOtrSession() != null
493 && !conversation.getOtrSession().getSessionID().getUserID()
494 .equals(message.getCounterpart().getResourcepart())) {
495 Log.d(Config.LOGTAG, "ending because of reasons");
496 conversation.endOtrIfNeeded();
497 }
498
499 if (packet.getType() != MessagePacket.TYPE_ERROR) {
500 if (message.getEncryption() == Message.ENCRYPTION_NONE
501 || mXmppConnectionService.saveEncryptedMessages()) {
502 mXmppConnectionService.databaseBackend.createMessage(message);
503 }
504 }
505 if (message.trusted() && message.bodyContainsDownloadable()) {
506 this.mXmppConnectionService.getHttpConnectionManager()
507 .createNewConnection(message);
508 } else {
509 mXmppConnectionService.getNotificationService().push(message);
510 }
511 mXmppConnectionService.updateConversationUi();
512 }
513
514 private void parseHeadline(MessagePacket packet, Account account) {
515 if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
516 Element event = packet.findChild("event",
517 "http://jabber.org/protocol/pubsub#event");
518 parseEvent(event, packet.getFrom(), account);
519 }
520 }
521
522 private void parseNick(MessagePacket packet, Account account) {
523 Element nick = packet.findChild("nick",
524 "http://jabber.org/protocol/nick");
525 if (nick != null) {
526 if (packet.getFrom() != null) {
527 Contact contact = account.getRoster().getContact(
528 packet.getFrom());
529 contact.setPresenceName(nick.getContent());
530 }
531 }
532 }
533}