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 mXmppConnectionService.joinMuc(conversation);
292 mXmppConnectionService.updateConversationUi();
293 }
294 }
295
296 } else if (packet.hasChild("x", "jabber:x:conference")) {
297 Element x = packet.findChild("x", "jabber:x:conference");
298 String jid = x.getAttribute("jid");
299 if (jid != null) {
300 Conversation conversation = mXmppConnectionService
301 .findOrCreateConversation(account, jid, true);
302 if (!conversation.getMucOptions().online()) {
303 mXmppConnectionService.joinMuc(conversation);
304 mXmppConnectionService.updateConversationUi();
305 }
306 }
307 }
308 }
309
310 private void parseEvent(Element event, String from, Account account) {
311 Element items = event.findChild("items");
312 String node = items.getAttribute("node");
313 if (node != null) {
314 if (node.equals("urn:xmpp:avatar:metadata")) {
315 Avatar avatar = Avatar.parseMetadata(items);
316 if (avatar != null) {
317 avatar.owner = from;
318 if (mXmppConnectionService.getFileBackend().isAvatarCached(
319 avatar)) {
320 if (account.getJid().equals(from)) {
321 if (account.setAvatar(avatar.getFilename())) {
322 mXmppConnectionService.databaseBackend
323 .updateAccount(account);
324 }
325 } else {
326 Contact contact = account.getRoster().getContact(
327 from);
328 contact.setAvatar(avatar.getFilename());
329 }
330 } else {
331 mXmppConnectionService.fetchAvatar(account, avatar);
332 }
333 }
334 } else if (node.equals("http://jabber.org/protocol/nick")) {
335 Element item = items.findChild("item");
336 if (item != null) {
337 Element nick = item.findChild("nick",
338 "http://jabber.org/protocol/nick");
339 if (nick != null) {
340 if (from != null) {
341 Contact contact = account.getRoster().getContact(
342 from);
343 contact.setPresenceName(nick.getContent());
344 }
345 }
346 }
347 }
348 }
349 }
350
351 private String getPgpBody(Element message) {
352 Element child = message.findChild("x", "jabber:x:encrypted");
353 if (child == null) {
354 return null;
355 } else {
356 return child.getContent();
357 }
358 }
359
360 private String getMarkableMessageId(Element message) {
361 if (message.hasChild("markable", "urn:xmpp:chat-markers:0")) {
362 return message.getAttribute("id");
363 } else {
364 return null;
365 }
366 }
367
368 @Override
369 public void onMessagePacketReceived(Account account, MessagePacket packet) {
370 Message message = null;
371 boolean notify = true;
372 if (mXmppConnectionService.getPreferences().getBoolean(
373 "notification_grace_period_after_carbon_received", true)) {
374 notify = (SystemClock.elapsedRealtime() - lastCarbonMessageReceived) > (Config.CARBON_GRACE_PERIOD * 1000);
375 }
376
377 this.parseNick(packet, account);
378
379 if ((packet.getType() == MessagePacket.TYPE_CHAT)) {
380 if ((packet.getBody() != null)
381 && (packet.getBody().startsWith("?OTR"))) {
382 message = this.parseOtrChat(packet, account);
383 if (message != null) {
384 message.markUnread();
385 }
386 } else if (packet.hasChild("body")) {
387 message = this.parseChat(packet, account);
388 if (message != null) {
389 message.markUnread();
390 }
391 } else if (packet.hasChild("received") || (packet.hasChild("sent"))) {
392 message = this.parseCarbonMessage(packet, account);
393 if (message != null) {
394 if (message.getStatus() == Message.STATUS_SEND) {
395 lastCarbonMessageReceived = SystemClock
396 .elapsedRealtime();
397 notify = false;
398 message.getConversation().markRead();
399 } else {
400 message.markUnread();
401 }
402 }
403 } else {
404 parseNormal(packet, account);
405 }
406
407 } else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
408 message = this.parseGroupchat(packet, account);
409 if (message != null) {
410 if (message.getStatus() == Message.STATUS_RECEIVED) {
411 message.markUnread();
412 } else {
413 message.getConversation().markRead();
414 lastCarbonMessageReceived = SystemClock.elapsedRealtime();
415 notify = false;
416 }
417 }
418 } else if (packet.getType() == MessagePacket.TYPE_ERROR) {
419 this.parseError(packet, account);
420 return;
421 } else if (packet.getType() == MessagePacket.TYPE_NORMAL) {
422 this.parseNormal(packet, account);
423 return;
424 } else if (packet.getType() == MessagePacket.TYPE_HEADLINE) {
425 this.parseHeadline(packet, account);
426 return;
427 }
428 if ((message == null) || (message.getBody() == null)) {
429 return;
430 }
431 if ((mXmppConnectionService.confirmMessages())
432 && ((packet.getId() != null))) {
433 if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
434 MessagePacket receipt = mXmppConnectionService
435 .getMessageGenerator().received(account, packet,
436 "urn:xmpp:chat-markers:0");
437 mXmppConnectionService.sendMessagePacket(account, receipt);
438 }
439 if (packet.hasChild("request", "urn:xmpp:receipts")) {
440 MessagePacket receipt = mXmppConnectionService
441 .getMessageGenerator().received(account, packet,
442 "urn:xmpp:receipts");
443 mXmppConnectionService.sendMessagePacket(account, receipt);
444 }
445 }
446 Conversation conversation = message.getConversation();
447 conversation.getMessages().add(message);
448 if (packet.getType() != MessagePacket.TYPE_ERROR) {
449 mXmppConnectionService.databaseBackend.createMessage(message);
450 }
451 notify = notify && !conversation.isMuted();
452 mXmppConnectionService.notifyUi(conversation, notify);
453 }
454
455 private void parseHeadline(MessagePacket packet, Account account) {
456 if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
457 Element event = packet.findChild("event",
458 "http://jabber.org/protocol/pubsub#event");
459 parseEvent(event, packet.getFrom(), account);
460 }
461 }
462
463 private void parseNick(MessagePacket packet, Account account) {
464 Element nick = packet.findChild("nick",
465 "http://jabber.org/protocol/nick");
466 if (nick != null) {
467 if (packet.getFrom() != null) {
468 Contact contact = account.getRoster().getContact(
469 packet.getFrom());
470 contact.setPresenceName(nick.getContent());
471 }
472 }
473 }
474}