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