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