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