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