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