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(mXmppConnectionService, presence,
79 false);
80 } else {
81 return null;
82 }
83 } else {
84 String foreignPresence = conversation.getOtrSession()
85 .getSessionID().getUserID();
86 if (!foreignPresence.equals(presence)) {
87 conversation.endOtrIfNeeded();
88 if (properlyAddressed) {
89 conversation.startOtrSession(mXmppConnectionService,
90 presence, false);
91 } else {
92 return null;
93 }
94 }
95 }
96 try {
97 Session otrSession = conversation.getOtrSession();
98 SessionStatus before = otrSession.getSessionStatus();
99 body = otrSession.transformReceiving(body);
100 SessionStatus after = otrSession.getSessionStatus();
101 if ((before != after) && (after == SessionStatus.ENCRYPTED)) {
102 mXmppConnectionService.onOtrSessionEstablished(conversation);
103 } else if ((before != after) && (after == SessionStatus.FINISHED)) {
104 conversation.resetOtrSession();
105 mXmppConnectionService.updateConversationUi();
106 }
107 if ((body == null) || (body.isEmpty())) {
108 return null;
109 }
110 if (body.startsWith(CryptoHelper.FILETRANSFER)) {
111 String key = body.substring(CryptoHelper.FILETRANSFER.length());
112 conversation.setSymmetricKey(CryptoHelper.hexToBytes(key));
113 return null;
114 }
115 conversation
116 .setLatestMarkableMessageId(getMarkableMessageId(packet));
117 Message finishedMessage = new Message(conversation,
118 packet.getFrom(), body, Message.ENCRYPTION_OTR,
119 Message.STATUS_RECEIVED);
120 finishedMessage.setTime(getTimestamp(packet));
121 finishedMessage.setRemoteMsgId(packet.getId());
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 String[] fromParts = packet.getFrom().split("/");
136 if (mXmppConnectionService.find(account.pendingConferenceLeaves,
137 account, fromParts[0]) != null) {
138 return null;
139 }
140 Conversation conversation = mXmppConnectionService
141 .findOrCreateConversation(account, fromParts[0], true);
142 if (packet.hasChild("subject")) {
143 conversation.getMucOptions().setSubject(
144 packet.findChild("subject").getContent());
145 mXmppConnectionService.updateConversationUi();
146 return null;
147 }
148 if ((fromParts.length == 1)) {
149 return null;
150 }
151 String counterPart = fromParts[1];
152 if (counterPart.equals(conversation.getMucOptions().getActualNick())) {
153 if (mXmppConnectionService.markMessage(conversation,
154 packet.getId(), Message.STATUS_SEND)) {
155 return null;
156 } else {
157 status = Message.STATUS_SEND;
158 }
159 } else {
160 status = Message.STATUS_RECEIVED;
161 }
162 String pgpBody = getPgpBody(packet);
163 conversation.setLatestMarkableMessageId(getMarkableMessageId(packet));
164 Message finishedMessage;
165 if (pgpBody == null) {
166 finishedMessage = new Message(conversation, counterPart,
167 packet.getBody(), Message.ENCRYPTION_NONE, status);
168 } else {
169 finishedMessage = new Message(conversation, counterPart, pgpBody,
170 Message.ENCRYPTION_PGP, status);
171 }
172 finishedMessage.setRemoteMsgId(packet.getId());
173 if (status == Message.STATUS_RECEIVED) {
174 finishedMessage.setTrueCounterpart(conversation.getMucOptions()
175 .getTrueCounterpart(counterPart));
176 }
177 if (packet.hasChild("delay")
178 && conversation.hasDuplicateMessage(finishedMessage)) {
179 return null;
180 }
181 finishedMessage.setTime(getTimestamp(packet));
182 return finishedMessage;
183 }
184
185 private Message parseCarbonMessage(MessagePacket packet, Account account) {
186 int status;
187 String fullJid;
188 Element forwarded;
189 if (packet.hasChild("received")) {
190 forwarded = packet.findChild("received").findChild("forwarded");
191 status = Message.STATUS_RECEIVED;
192 } else if (packet.hasChild("sent")) {
193 forwarded = packet.findChild("sent").findChild("forwarded");
194 status = Message.STATUS_SEND;
195 } else {
196 return null;
197 }
198 if (forwarded == null) {
199 return null;
200 }
201 Element message = forwarded.findChild("message");
202 if ((message == null) || (!message.hasChild("body"))) {
203 if (status == Message.STATUS_RECEIVED
204 && message.getAttribute("from") != null) {
205 parseNonMessage(message, account);
206 }
207 return null;
208 }
209 if (status == Message.STATUS_RECEIVED) {
210 fullJid = message.getAttribute("from");
211 if (fullJid == null) {
212 return null;
213 } else {
214 updateLastseen(message, account, true);
215 }
216 } else {
217 fullJid = message.getAttribute("to");
218 if (fullJid == null) {
219 return null;
220 }
221 }
222 String[] parts = fullJid.split("/");
223 Conversation conversation = mXmppConnectionService
224 .findOrCreateConversation(account, parts[0], false);
225 conversation.setLatestMarkableMessageId(getMarkableMessageId(packet));
226
227 String pgpBody = getPgpBody(message);
228 Message finishedMessage;
229 if (pgpBody != null) {
230 finishedMessage = new Message(conversation, fullJid, pgpBody,
231 Message.ENCRYPTION_PGP, status);
232 } else {
233 String body = message.findChild("body").getContent();
234 finishedMessage = new Message(conversation, fullJid, body,
235 Message.ENCRYPTION_NONE, status);
236 }
237 finishedMessage.setTime(getTimestamp(message));
238 finishedMessage.setRemoteMsgId(message.getAttribute("id"));
239 if (conversation.getMode() == Conversation.MODE_MULTI
240 && parts.length >= 2) {
241 finishedMessage.setType(Message.TYPE_PRIVATE);
242 finishedMessage.setPresence(parts[1]);
243 finishedMessage.setTrueCounterpart(conversation.getMucOptions()
244 .getTrueCounterpart(parts[1]));
245 if (conversation.hasDuplicateMessage(finishedMessage)) {
246 return null;
247 }
248 }
249
250 return finishedMessage;
251 }
252
253 private void parseError(MessagePacket packet, Account account) {
254 String[] fromParts = packet.getFrom().split("/");
255 mXmppConnectionService.markMessage(account, fromParts[0],
256 packet.getId(), Message.STATUS_SEND_FAILED);
257 }
258
259 private void parseNonMessage(Element packet, Account account) {
260 if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
261 Element event = packet.findChild("event",
262 "http://jabber.org/protocol/pubsub#event");
263 parseEvent(event, packet.getAttribute("from"), account);
264 } else if (packet.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
265 String id = packet
266 .findChild("displayed", "urn:xmpp:chat-markers:0")
267 .getAttribute("id");
268 String[] fromParts = packet.getAttribute("from").split("/");
269 updateLastseen(packet, account, true);
270 mXmppConnectionService.markMessage(account, fromParts[0], id,
271 Message.STATUS_SEND_DISPLAYED);
272 } else if (packet.hasChild("received", "urn:xmpp:chat-markers:0")) {
273 String id = packet.findChild("received", "urn:xmpp:chat-markers:0")
274 .getAttribute("id");
275 String[] fromParts = packet.getAttribute("from").split("/");
276 updateLastseen(packet, account, false);
277 mXmppConnectionService.markMessage(account, fromParts[0], id,
278 Message.STATUS_SEND_RECEIVED);
279 } else if (packet.hasChild("x", "http://jabber.org/protocol/muc#user")) {
280 Element x = packet.findChild("x",
281 "http://jabber.org/protocol/muc#user");
282 if (x.hasChild("invite")) {
283 Conversation conversation = mXmppConnectionService
284 .findOrCreateConversation(account,
285 packet.getAttribute("from"), true);
286 if (!conversation.getMucOptions().online()) {
287 if (x.hasChild("password")) {
288 Element password = x.findChild("password");
289 conversation.getMucOptions().setPassword(
290 password.getContent());
291 }
292 mXmppConnectionService.joinMuc(conversation);
293 mXmppConnectionService.updateConversationUi();
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 String password = x.getAttribute("password");
300 if (jid != null) {
301 Conversation conversation = mXmppConnectionService
302 .findOrCreateConversation(account, jid, true);
303 if (!conversation.getMucOptions().online()) {
304 if (password != null) {
305 conversation.getMucOptions().setPassword(password);
306 }
307 mXmppConnectionService.joinMuc(conversation);
308 mXmppConnectionService.updateConversationUi();
309 }
310 }
311 }
312 }
313
314 private void parseEvent(Element event, String from, Account account) {
315 Element items = event.findChild("items");
316 String node = items.getAttribute("node");
317 if (node != null) {
318 if (node.equals("urn:xmpp:avatar:metadata")) {
319 Avatar avatar = Avatar.parseMetadata(items);
320 if (avatar != null) {
321 avatar.owner = from;
322 if (mXmppConnectionService.getFileBackend().isAvatarCached(
323 avatar)) {
324 if (account.getJid().equals(from)) {
325 if (account.setAvatar(avatar.getFilename())) {
326 mXmppConnectionService.databaseBackend
327 .updateAccount(account);
328 }
329 } else {
330 Contact contact = account.getRoster().getContact(
331 from);
332 contact.setAvatar(avatar.getFilename());
333 }
334 } else {
335 mXmppConnectionService.fetchAvatar(account, avatar);
336 }
337 }
338 } else if (node.equals("http://jabber.org/protocol/nick")) {
339 Element item = items.findChild("item");
340 if (item != null) {
341 Element nick = item.findChild("nick",
342 "http://jabber.org/protocol/nick");
343 if (nick != null) {
344 if (from != null) {
345 Contact contact = account.getRoster().getContact(
346 from);
347 contact.setPresenceName(nick.getContent());
348 }
349 }
350 }
351 }
352 }
353 }
354
355 private String getPgpBody(Element message) {
356 Element child = message.findChild("x", "jabber:x:encrypted");
357 if (child == null) {
358 return null;
359 } else {
360 return child.getContent();
361 }
362 }
363
364 private String getMarkableMessageId(Element message) {
365 if (message.hasChild("markable", "urn:xmpp:chat-markers:0")) {
366 return message.getAttribute("id");
367 } else {
368 return null;
369 }
370 }
371
372 @Override
373 public void onMessagePacketReceived(Account account, MessagePacket packet) {
374 Message message = null;
375 boolean notify = true;
376 if (mXmppConnectionService.getPreferences().getBoolean(
377 "notification_grace_period_after_carbon_received", true)) {
378 notify = (SystemClock.elapsedRealtime() - lastCarbonMessageReceived) > (Config.CARBON_GRACE_PERIOD * 1000);
379 }
380
381 this.parseNick(packet, account);
382
383 if ((packet.getType() == MessagePacket.TYPE_CHAT || packet.getType() == MessagePacket.TYPE_NORMAL)) {
384 if ((packet.getBody() != null)
385 && (packet.getBody().startsWith("?OTR"))) {
386 message = this.parseOtrChat(packet, account);
387 if (message != null) {
388 message.markUnread();
389 }
390 } else if (packet.hasChild("body")) {
391 message = this.parseChat(packet, account);
392 if (message != null) {
393 message.markUnread();
394 }
395 } else if (packet.hasChild("received") || (packet.hasChild("sent"))) {
396 message = this.parseCarbonMessage(packet, account);
397 if (message != null) {
398 if (message.getStatus() == Message.STATUS_SEND) {
399 lastCarbonMessageReceived = SystemClock
400 .elapsedRealtime();
401 notify = false;
402 message.getConversation().markRead();
403 } else {
404 message.markUnread();
405 }
406 }
407 } else {
408 parseNonMessage(packet, account);
409 }
410 } else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
411 message = this.parseGroupchat(packet, account);
412 if (message != null) {
413 if (message.getStatus() == Message.STATUS_RECEIVED) {
414 message.markUnread();
415 } else {
416 message.getConversation().markRead();
417 lastCarbonMessageReceived = SystemClock.elapsedRealtime();
418 notify = false;
419 }
420 }
421 } else if (packet.getType() == MessagePacket.TYPE_ERROR) {
422 this.parseError(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 if (message.getEncryption() == Message.ENCRYPTION_NONE
450 || mXmppConnectionService.saveEncryptedMessages()) {
451 mXmppConnectionService.databaseBackend.createMessage(message);
452 }
453 }
454 notify = notify && !conversation.isMuted();
455 mXmppConnectionService.notifyUi(conversation, notify);
456 }
457
458 private void parseHeadline(MessagePacket packet, Account account) {
459 if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
460 Element event = packet.findChild("event",
461 "http://jabber.org/protocol/pubsub#event");
462 parseEvent(event, packet.getFrom(), account);
463 }
464 }
465
466 private void parseNick(MessagePacket packet, Account account) {
467 Element nick = packet.findChild("nick",
468 "http://jabber.org/protocol/nick");
469 if (nick != null) {
470 if (packet.getFrom() != null) {
471 Contact contact = account.getRoster().getContact(
472 packet.getFrom());
473 contact.setPresenceName(nick.getContent());
474 }
475 }
476 }
477}