1package eu.siacs.conversations.parser;
2
3import android.os.Build;
4import android.text.Html;
5import android.util.Log;
6import android.util.Pair;
7
8import net.java.otr4j.session.Session;
9import net.java.otr4j.session.SessionStatus;
10
11import java.text.SimpleDateFormat;
12import java.util.ArrayList;
13import java.util.Arrays;
14import java.util.Date;
15import java.util.List;
16import java.util.Set;
17import java.util.UUID;
18
19import eu.siacs.conversations.Config;
20import eu.siacs.conversations.R;
21import eu.siacs.conversations.crypto.OtrService;
22import eu.siacs.conversations.crypto.axolotl.AxolotlService;
23import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
24import eu.siacs.conversations.entities.Account;
25import eu.siacs.conversations.entities.Bookmark;
26import eu.siacs.conversations.entities.Contact;
27import eu.siacs.conversations.entities.Conversation;
28import eu.siacs.conversations.entities.Message;
29import eu.siacs.conversations.entities.MucOptions;
30import eu.siacs.conversations.entities.Presence;
31import eu.siacs.conversations.entities.ServiceDiscoveryResult;
32import eu.siacs.conversations.http.HttpConnectionManager;
33import eu.siacs.conversations.services.MessageArchiveService;
34import eu.siacs.conversations.services.XmppConnectionService;
35import eu.siacs.conversations.utils.CryptoHelper;
36import eu.siacs.conversations.xml.Namespace;
37import eu.siacs.conversations.xml.Element;
38import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
39import eu.siacs.conversations.xmpp.chatstate.ChatState;
40import eu.siacs.conversations.xmpp.jid.Jid;
41import eu.siacs.conversations.xmpp.pep.Avatar;
42import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
43
44public class MessageParser extends AbstractParser implements OnMessagePacketReceived {
45
46 private static final List<String> CLIENTS_SENDING_HTML_IN_OTR = Arrays.asList("Pidgin","Adium","Trillian");
47
48 public MessageParser(XmppConnectionService service) {
49 super(service);
50 }
51
52 private boolean extractChatState(Conversation c, final boolean isTypeGroupChat, final MessagePacket packet) {
53 ChatState state = ChatState.parse(packet);
54 if (state != null && c != null) {
55 final Account account = c.getAccount();
56 Jid from = packet.getFrom();
57 if (from.toBareJid().equals(account.getJid().toBareJid())) {
58 c.setOutgoingChatState(state);
59 if (state == ChatState.ACTIVE || state == ChatState.COMPOSING) {
60 mXmppConnectionService.markRead(c);
61 activateGracePeriod(account);
62 }
63 return false;
64 } else {
65 if (isTypeGroupChat) {
66 MucOptions.User user = c.getMucOptions().findUserByFullJid(from);
67 if (user != null) {
68 return user.setChatState(state);
69 } else {
70 return false;
71 }
72 } else {
73 return c.setIncomingChatState(state);
74 }
75 }
76 }
77 return false;
78 }
79
80 private Message parseOtrChat(String body, Jid from, String id, Conversation conversation) {
81 String presence;
82 if (from.isBareJid()) {
83 presence = "";
84 } else {
85 presence = from.getResourcepart();
86 }
87 if (body.matches("^\\?OTRv\\d{1,2}\\?.*")) {
88 conversation.endOtrIfNeeded();
89 }
90 if (!conversation.hasValidOtrSession()) {
91 conversation.startOtrSession(presence,false);
92 } else {
93 String foreignPresence = conversation.getOtrSession().getSessionID().getUserID();
94 if (!foreignPresence.equals(presence)) {
95 conversation.endOtrIfNeeded();
96 conversation.startOtrSession(presence, false);
97 }
98 }
99 try {
100 conversation.setLastReceivedOtrMessageId(id);
101 Session otrSession = conversation.getOtrSession();
102 body = otrSession.transformReceiving(body);
103 SessionStatus status = otrSession.getSessionStatus();
104 if (body == null && status == SessionStatus.ENCRYPTED) {
105 mXmppConnectionService.onOtrSessionEstablished(conversation);
106 return null;
107 } else if (body == null && status == SessionStatus.FINISHED) {
108 conversation.resetOtrSession();
109 mXmppConnectionService.updateConversationUi();
110 return null;
111 } else if (body == null || (body.isEmpty())) {
112 return null;
113 }
114 if (body.startsWith(CryptoHelper.FILETRANSFER)) {
115 String key = body.substring(CryptoHelper.FILETRANSFER.length());
116 conversation.setSymmetricKey(CryptoHelper.hexToBytes(key));
117 return null;
118 }
119 if (clientMightSendHtml(conversation.getAccount(), from)) {
120 Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": received OTR message from bad behaving client. escaping HTML…");
121 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
122 body = Html.fromHtml(body,Html.FROM_HTML_MODE_LEGACY).toString();
123 } else {
124 body = Html.fromHtml(body).toString();
125 }
126 }
127
128 final OtrService otrService = conversation.getAccount().getOtrService();
129 Message finishedMessage = new Message(conversation, body, Message.ENCRYPTION_OTR, Message.STATUS_RECEIVED);
130 finishedMessage.setFingerprint(otrService.getFingerprint(otrSession.getRemotePublicKey()));
131 conversation.setLastReceivedOtrMessageId(null);
132
133 return finishedMessage;
134 } catch (Exception e) {
135 conversation.resetOtrSession();
136 return null;
137 }
138 }
139
140 private static boolean clientMightSendHtml(Account account, Jid from) {
141 String resource = from.getResourcepart();
142 if (resource == null) {
143 return false;
144 }
145 Presence presence = account.getRoster().getContact(from).getPresences().getPresences().get(resource);
146 ServiceDiscoveryResult disco = presence == null ? null : presence.getServiceDiscoveryResult();
147 if (disco == null) {
148 return false;
149 }
150 return hasIdentityKnowForSendingHtml(disco.getIdentities());
151 }
152
153 private static boolean hasIdentityKnowForSendingHtml(List<ServiceDiscoveryResult.Identity> identities) {
154 for(ServiceDiscoveryResult.Identity identity : identities) {
155 if (identity.getName() != null) {
156 if (CLIENTS_SENDING_HTML_IN_OTR.contains(identity.getName())) {
157 return true;
158 }
159 }
160 }
161 return false;
162 }
163
164 private Message parseAxolotlChat(Element axolotlMessage, Jid from, Conversation conversation, int status) {
165 AxolotlService service = conversation.getAccount().getAxolotlService();
166 XmppAxolotlMessage xmppAxolotlMessage;
167 try {
168 xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlMessage, from.toBareJid());
169 } catch (Exception e) {
170 Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": invalid omemo message received "+e.getMessage());
171 return null;
172 }
173 XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = service.processReceivingPayloadMessage(xmppAxolotlMessage);
174 if(plaintextMessage != null) {
175 Message finishedMessage = new Message(conversation, plaintextMessage.getPlaintext(), Message.ENCRYPTION_AXOLOTL, status);
176 finishedMessage.setFingerprint(plaintextMessage.getFingerprint());
177 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(finishedMessage.getConversation().getAccount())+" Received Message with session fingerprint: "+plaintextMessage.getFingerprint());
178 return finishedMessage;
179 } else {
180 return null;
181 }
182 }
183
184 private class Invite {
185 final Jid jid;
186 final String password;
187 final Contact inviter;
188 Invite(Jid jid, String password, Contact inviter) {
189 this.jid = jid;
190 this.password = password;
191 this.inviter = inviter;
192 }
193
194 public boolean execute(Account account) {
195 if (jid != null) {
196 Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true, false);
197 if (!conversation.getMucOptions().online()) {
198 conversation.getMucOptions().setPassword(password);
199 mXmppConnectionService.databaseBackend.updateConversation(conversation);
200 mXmppConnectionService.joinMuc(conversation, inviter != null && inviter.mutualPresenceSubscription());
201 mXmppConnectionService.updateConversationUi();
202 }
203 return true;
204 }
205 return false;
206 }
207 }
208
209 private Invite extractInvite(Account account, Element message) {
210 Element x = message.findChild("x", "http://jabber.org/protocol/muc#user");
211 if (x != null) {
212 Element invite = x.findChild("invite");
213 if (invite != null) {
214 Element pw = x.findChild("password");
215 Jid from = invite.getAttributeAsJid("from");
216 Contact contact = from == null ? null : account.getRoster().getContact(from);
217 return new Invite(message.getAttributeAsJid("from"), pw != null ? pw.getContent(): null, contact);
218 }
219 } else {
220 x = message.findChild("x","jabber:x:conference");
221 if (x != null) {
222 Jid from = message.getAttributeAsJid("from");
223 Contact contact = from == null ? null : account.getRoster().getContact(from);
224 return new Invite(x.getAttributeAsJid("jid"),x.getAttribute("password"),contact);
225 }
226 }
227 return null;
228 }
229
230 private static String extractStanzaId(Element packet, boolean isTypeGroupChat, Conversation conversation) {
231 final Jid by;
232 final boolean safeToExtract;
233 if (isTypeGroupChat) {
234 by = conversation.getJid().toBareJid();
235 safeToExtract = conversation.getMucOptions().hasFeature(Namespace.STANZA_IDS);
236 } else {
237 Account account = conversation.getAccount();
238 by = account.getJid().toBareJid();
239 safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
240 }
241 return safeToExtract ? extractStanzaId(packet, by) : null;
242 }
243
244 private static String extractStanzaId(Element packet, Jid by) {
245 for(Element child : packet.getChildren()) {
246 if (child.getName().equals("stanza-id")
247 && Namespace.STANZA_IDS.equals(child.getNamespace())
248 && by.equals(child.getAttributeAsJid("by"))) {
249 return child.getAttribute("id");
250 }
251 }
252 return null;
253 }
254
255 private void parseEvent(final Element event, final Jid from, final Account account) {
256 Element items = event.findChild("items");
257 String node = items == null ? null : items.getAttribute("node");
258 if ("urn:xmpp:avatar:metadata".equals(node)) {
259 Avatar avatar = Avatar.parseMetadata(items);
260 if (avatar != null) {
261 avatar.owner = from.toBareJid();
262 if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
263 if (account.getJid().toBareJid().equals(from)) {
264 if (account.setAvatar(avatar.getFilename())) {
265 mXmppConnectionService.databaseBackend.updateAccount(account);
266 }
267 mXmppConnectionService.getAvatarService().clear(account);
268 mXmppConnectionService.updateConversationUi();
269 mXmppConnectionService.updateAccountUi();
270 } else {
271 Contact contact = account.getRoster().getContact(from);
272 contact.setAvatar(avatar);
273 mXmppConnectionService.getAvatarService().clear(contact);
274 mXmppConnectionService.updateConversationUi();
275 mXmppConnectionService.updateRosterUi();
276 }
277 } else if (mXmppConnectionService.isDataSaverDisabled()) {
278 mXmppConnectionService.fetchAvatar(account, avatar);
279 }
280 }
281 } else if ("http://jabber.org/protocol/nick".equals(node)) {
282 Element i = items.findChild("item");
283 Element nick = i == null ? null : i.findChild("nick", "http://jabber.org/protocol/nick");
284 if (nick != null && nick.getContent() != null) {
285 Contact contact = account.getRoster().getContact(from);
286 contact.setPresenceName(nick.getContent());
287 mXmppConnectionService.getAvatarService().clear(account);
288 mXmppConnectionService.updateConversationUi();
289 mXmppConnectionService.updateAccountUi();
290 }
291 } else if (AxolotlService.PEP_DEVICE_LIST.equals(node)) {
292
293 Element item = items.findChild("item");
294 Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
295 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Received PEP device list ("+deviceIds+") update from "+ from + ", processing...");
296 AxolotlService axolotlService = account.getAxolotlService();
297 axolotlService.registerDevices(from, deviceIds);
298 mXmppConnectionService.updateAccountUi();
299 }
300 }
301
302 private boolean handleErrorMessage(Account account, MessagePacket packet) {
303 if (packet.getType() == MessagePacket.TYPE_ERROR) {
304 Jid from = packet.getFrom();
305 if (from != null) {
306 Message message = mXmppConnectionService.markMessage(account,
307 from.toBareJid(),
308 packet.getId(),
309 Message.STATUS_SEND_FAILED,
310 extractErrorMessage(packet));
311 if (message != null) {
312 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
313 message.getConversation().endOtrIfNeeded();
314 }
315 }
316 }
317 return true;
318 }
319 return false;
320 }
321
322 @Override
323 public void onMessagePacketReceived(Account account, MessagePacket original) {
324 if (handleErrorMessage(account, original)) {
325 return;
326 }
327 final MessagePacket packet;
328 Long timestamp = null;
329 final boolean isForwarded;
330 boolean isCarbon = false;
331 String serverMsgId = null;
332 final Element fin = original.findChild("fin", Namespace.MAM_LEGACY);
333 if (fin != null) {
334 mXmppConnectionService.getMessageArchiveService().processFinLegacy(fin,original.getFrom());
335 return;
336 }
337 final boolean mamLegacy = original.hasChild("result", Namespace.MAM_LEGACY);
338 final Element result = original.findChild("result",mamLegacy ? Namespace.MAM_LEGACY : Namespace.MAM);
339 final MessageArchiveService.Query query = result == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
340 if (query != null && query.validFrom(original.getFrom())) {
341 Pair<MessagePacket, Long> f = original.getForwardedMessagePacket("result", mamLegacy ? Namespace.MAM_LEGACY : Namespace.MAM);
342 if (f == null) {
343 return;
344 }
345 timestamp = f.second;
346 packet = f.first;
347 isForwarded = true;
348 serverMsgId = result.getAttribute("id");
349 query.incrementMessageCount();
350 } else if (query != null) {
351 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received mam result from invalid sender");
352 return;
353 } else if (original.fromServer(account)) {
354 Pair<MessagePacket, Long> f;
355 f = original.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
356 f = f == null ? original.getForwardedMessagePacket("sent", "urn:xmpp:carbons:2") : f;
357 packet = f != null ? f.first : original;
358 if (handleErrorMessage(account, packet)) {
359 return;
360 }
361 timestamp = f != null ? f.second : null;
362 isCarbon = f != null;
363 isForwarded = isCarbon;
364 } else {
365 packet = original;
366 isForwarded = false;
367 }
368
369 if (timestamp == null) {
370 timestamp = AbstractParser.parseTimestamp(original,AbstractParser.parseTimestamp(packet));
371 }
372 final String body = packet.getBody();
373 final Element mucUserElement = packet.findChild("x", "http://jabber.org/protocol/muc#user");
374 final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted");
375 final Element replaceElement = packet.findChild("replace", "urn:xmpp:message-correct:0");
376 final Element oob = packet.findChild("x", Namespace.OOB);
377 final String oobUrl = oob != null ? oob.findChildContent("url") : null;
378 final String replacementId = replaceElement == null ? null : replaceElement.getAttribute("id");
379 final Element axolotlEncrypted = packet.findChild(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
380 int status;
381 final Jid counterpart;
382 final Jid to = packet.getTo();
383 final Jid from = packet.getFrom();
384 final Element originId = packet.findChild("origin-id",Namespace.STANZA_IDS);
385 final String remoteMsgId;
386 if (originId != null && originId.getAttribute("id") != null) {
387 remoteMsgId = originId.getAttribute("id");
388 } else {
389 remoteMsgId = packet.getId();
390 }
391 boolean notify = false;
392
393 if (from == null) {
394 Log.d(Config.LOGTAG,"no from in: "+packet.toString());
395 return;
396 }
397
398 boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
399 boolean isProperlyAddressed = (to != null ) && (!to.isBareJid() || account.countPresences() == 0);
400 boolean isMucStatusMessage = from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
401 if (packet.fromAccount(account)) {
402 status = Message.STATUS_SEND;
403 counterpart = to != null ? to : account.getJid();
404 } else {
405 status = Message.STATUS_RECEIVED;
406 counterpart = from;
407 }
408
409 Invite invite = extractInvite(account, packet);
410 if (invite != null && invite.execute(account)) {
411 return;
412 }
413
414 if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), isTypeGroupChat, packet)) {
415 mXmppConnectionService.updateConversationUi();
416 }
417
418 if ((body != null || pgpEncrypted != null || axolotlEncrypted != null || oobUrl != null) && !isMucStatusMessage) {
419 final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.toBareJid(), isTypeGroupChat, false, query, false);
420 final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
421
422 if (serverMsgId == null) {
423 serverMsgId = extractStanzaId(packet, isTypeGroupChat, conversation);
424 }
425
426 if (isTypeGroupChat) {
427 if (conversation.getMucOptions().isSelf(counterpart)) {
428 status = Message.STATUS_SEND_RECEIVED;
429 isCarbon = true; //not really carbon but received from another resource
430 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status, serverMsgId)) {
431 return;
432 } else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
433 Message message = conversation.findSentMessageWithBody(packet.getBody());
434 if (message != null) {
435 mXmppConnectionService.markMessage(message, status);
436 return;
437 }
438 }
439 } else {
440 status = Message.STATUS_RECEIVED;
441 }
442 }
443 final Message message;
444 if (body != null && body.startsWith("?OTR") && Config.supportOtr()) {
445 if (!isForwarded && !isTypeGroupChat && isProperlyAddressed && !conversationMultiMode) {
446 message = parseOtrChat(body, from, remoteMsgId, conversation);
447 if (message == null) {
448 return;
449 }
450 } else {
451 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": ignoring OTR message from "+from+" isForwarded="+Boolean.toString(isForwarded)+", isProperlyAddressed="+Boolean.valueOf(isProperlyAddressed));
452 message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
453 }
454 } else if (pgpEncrypted != null && Config.supportOpenPgp()) {
455 message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status);
456 } else if (axolotlEncrypted != null && Config.supportOmemo()) {
457 Jid origin;
458 if (conversationMultiMode) {
459 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
460 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
461 if (origin == null) {
462 Log.d(Config.LOGTAG, "axolotl message in non anonymous conference received");
463 return;
464 }
465 } else {
466 origin = from;
467 }
468 message = parseAxolotlChat(axolotlEncrypted, origin, conversation, status);
469 if (message == null) {
470 return;
471 }
472 if (conversationMultiMode) {
473 message.setTrueCounterpart(origin);
474 }
475 } else if (body == null && oobUrl != null) {
476 message = new Message(conversation, oobUrl, Message.ENCRYPTION_NONE, status);
477 message.setOob(true);
478 if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
479 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
480 }
481 } else {
482 message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
483 }
484
485 message.setCounterpart(counterpart);
486 message.setRemoteMsgId(remoteMsgId);
487 message.setServerMsgId(serverMsgId);
488 message.setCarbon(isCarbon);
489 message.setTime(timestamp);
490 if (body != null && body.equals(oobUrl)) {
491 message.setOob(true);
492 if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
493 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
494 }
495 }
496 message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
497 if (conversationMultiMode) {
498 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
499 Jid trueCounterpart;
500 if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
501 trueCounterpart = message.getTrueCounterpart();
502 } else if (Config.PARSE_REAL_JID_FROM_MUC_MAM) {
503 trueCounterpart = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
504 } else {
505 trueCounterpart = fallback;
506 }
507 if (trueCounterpart != null && trueCounterpart.toBareJid().equals(account.getJid().toBareJid())) {
508 status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND;
509 }
510 message.setStatus(status);
511 message.setTrueCounterpart(trueCounterpart);
512 if (!isTypeGroupChat) {
513 message.setType(Message.TYPE_PRIVATE);
514 }
515 } else {
516 updateLastseen(account, from);
517 }
518
519 if (replacementId != null && mXmppConnectionService.allowMessageCorrection()) {
520 Message replacedMessage = conversation.findMessageWithRemoteIdAndCounterpart(replacementId,
521 counterpart,
522 message.getStatus() == Message.STATUS_RECEIVED,
523 message.isCarbon());
524 if (replacedMessage != null) {
525 final boolean fingerprintsMatch = replacedMessage.getFingerprint() == null
526 || replacedMessage.getFingerprint().equals(message.getFingerprint());
527 final boolean trueCountersMatch = replacedMessage.getTrueCounterpart() != null
528 && replacedMessage.getTrueCounterpart().equals(message.getTrueCounterpart());
529 final boolean duplicate = conversation.hasDuplicateMessage(message);
530 if (fingerprintsMatch && (trueCountersMatch || !conversationMultiMode) && !duplicate) {
531 Log.d(Config.LOGTAG, "replaced message '" + replacedMessage.getBody() + "' with '" + message.getBody() + "'");
532 synchronized (replacedMessage) {
533 final String uuid = replacedMessage.getUuid();
534 replacedMessage.setUuid(UUID.randomUUID().toString());
535 replacedMessage.setBody(message.getBody());
536 replacedMessage.setEdited(replacedMessage.getRemoteMsgId());
537 replacedMessage.setRemoteMsgId(remoteMsgId);
538 replacedMessage.setEncryption(message.getEncryption());
539 if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
540 replacedMessage.markUnread();
541 }
542 mXmppConnectionService.updateMessage(replacedMessage, uuid);
543 mXmppConnectionService.getNotificationService().updateNotification(false);
544 if (mXmppConnectionService.confirmMessages()
545 && (replacedMessage.trusted() || replacedMessage.getType() == Message.TYPE_PRIVATE)
546 && remoteMsgId != null
547 && !isForwarded
548 && !isTypeGroupChat) {
549 sendMessageReceipts(account, packet);
550 }
551 if (replacedMessage.getEncryption() == Message.ENCRYPTION_PGP) {
552 conversation.getAccount().getPgpDecryptionService().discard(replacedMessage);
553 conversation.getAccount().getPgpDecryptionService().decrypt(replacedMessage, false);
554 }
555 }
556 return;
557 } else {
558 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received message correction but verification didn't check out");
559 }
560 }
561 }
562
563 long deletionDate = mXmppConnectionService.getAutomaticMessageDeletionDate();
564 if (deletionDate != 0 && message.getTimeSent() < deletionDate) {
565 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping message from "+message.getCounterpart().toString()+" because it was sent prior to our deletion date");
566 return;
567 }
568
569 boolean checkForDuplicates = (isTypeGroupChat && packet.hasChild("delay","urn:xmpp:delay"))
570 || message.getType() == Message.TYPE_PRIVATE
571 || message.getServerMsgId() != null;
572 if (checkForDuplicates && conversation.hasDuplicateMessage(message)) {
573 Log.d(Config.LOGTAG,"skipping duplicate message from "+message.getCounterpart().toString()+" "+message.getBody());
574 return;
575 }
576
577 if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
578 conversation.prepend(message);
579 } else {
580 conversation.add(message);
581 }
582 if (query != null) {
583 query.incrementActualMessageCount();
584 }
585
586 if (query == null || query.isCatchup()) { //either no mam or catchup
587 if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
588 mXmppConnectionService.markRead(conversation);
589 if (query == null) {
590 activateGracePeriod(account);
591 }
592 } else {
593 message.markUnread();
594 notify = true;
595 }
596 }
597
598 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
599 notify = conversation.getAccount().getPgpDecryptionService().decrypt(message, notify);
600 }
601
602 if (query == null) {
603 mXmppConnectionService.updateConversationUi();
604 }
605
606 if (mXmppConnectionService.confirmMessages()
607 && (message.trusted() || message.getType() == Message.TYPE_PRIVATE)
608 && remoteMsgId != null
609 && !isForwarded
610 && !isTypeGroupChat) {
611 sendMessageReceipts(account, packet);
612 }
613
614 if (message.getStatus() == Message.STATUS_RECEIVED
615 && conversation.getOtrSession() != null
616 && !conversation.getOtrSession().getSessionID().getUserID()
617 .equals(message.getCounterpart().getResourcepart())) {
618 conversation.endOtrIfNeeded();
619 }
620
621 mXmppConnectionService.databaseBackend.createMessage(message);
622 final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
623 if (message.trusted() && message.treatAsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
624 manager.createNewDownloadConnection(message);
625 } else if (notify) {
626 if (query != null && query.isCatchup()) {
627 mXmppConnectionService.getNotificationService().pushFromBacklog(message);
628 } else {
629 mXmppConnectionService.getNotificationService().push(message);
630 }
631 }
632 } else if (!packet.hasChild("body")){ //no body
633 final Conversation conversation = mXmppConnectionService.find(account, from.toBareJid());
634 if (isTypeGroupChat) {
635 if (packet.hasChild("subject")) {
636 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
637 conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
638 String subject = packet.findChildContent("subject");
639 conversation.getMucOptions().setSubject(subject);
640 final Bookmark bookmark = conversation.getBookmark();
641 if (bookmark != null && bookmark.getBookmarkName() == null) {
642 if (bookmark.setBookmarkName(subject)) {
643 mXmppConnectionService.pushBookmarks(account);
644 }
645 }
646 mXmppConnectionService.updateConversationUi();
647 return;
648 }
649 }
650 }
651 if (conversation != null && mucUserElement != null && from.isBareJid()) {
652 for (Element child : mucUserElement.getChildren()) {
653 if ("status".equals(child.getName())) {
654 try {
655 int code = Integer.parseInt(child.getAttribute("code"));
656 if ((code >= 170 && code <= 174) || (code >= 102 && code <= 104)) {
657 mXmppConnectionService.fetchConferenceConfiguration(conversation);
658 break;
659 }
660 } catch (Exception e) {
661 //ignored
662 }
663 } else if ("item".equals(child.getName())) {
664 MucOptions.User user = AbstractParser.parseItem(conversation,child);
665 Log.d(Config.LOGTAG,account.getJid()+": changing affiliation for "
666 +user.getRealJid()+" to "+user.getAffiliation()+" in "
667 +conversation.getJid().toBareJid());
668 if (!user.realJidMatchesAccount()) {
669 conversation.getMucOptions().updateUser(user);
670 mXmppConnectionService.getAvatarService().clear(conversation);
671 mXmppConnectionService.updateMucRosterUi();
672 mXmppConnectionService.updateConversationUi();
673 if (!user.getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
674 Jid jid = user.getRealJid();
675 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
676 if (cryptoTargets.remove(user.getRealJid())) {
677 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": removed "+jid+" from crypto targets of "+conversation.getName());
678 conversation.setAcceptedCryptoTargets(cryptoTargets);
679 mXmppConnectionService.updateConversation(conversation);
680 }
681 }
682 }
683 }
684 }
685 }
686 }
687
688
689
690 Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
691 if (received == null) {
692 received = packet.findChild("received", "urn:xmpp:receipts");
693 }
694 if (received != null && !packet.fromAccount(account)) {
695 mXmppConnectionService.markMessage(account, from.toBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED);
696 }
697 Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
698 if (displayed != null) {
699 if (packet.fromAccount(account)) {
700 Conversation conversation = mXmppConnectionService.find(account,counterpart.toBareJid());
701 if (conversation != null && (query == null || query.isCatchup())) {
702 mXmppConnectionService.markRead(conversation);
703 }
704 } else {
705 final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), displayed.getAttribute("id"), Message.STATUS_SEND_DISPLAYED);
706 Message message = displayedMessage == null ? null : displayedMessage.prev();
707 while (message != null
708 && message.getStatus() == Message.STATUS_SEND_RECEIVED
709 && message.getTimeSent() < displayedMessage.getTimeSent()) {
710 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
711 message = message.prev();
712 }
713 }
714 }
715
716 Element event = original.findChild("event", "http://jabber.org/protocol/pubsub#event");
717 if (event != null) {
718 parseEvent(event, original.getFrom(), account);
719 }
720
721 String nick = packet.findChildContent("nick", "http://jabber.org/protocol/nick");
722 if (nick != null) {
723 Contact contact = account.getRoster().getContact(from);
724 contact.setPresenceName(nick);
725 }
726 }
727
728 private static Jid getTrueCounterpart(Element mucUserElement, Jid fallback) {
729 final Element item = mucUserElement == null ? null : mucUserElement.findChild("item");
730 Jid result = item == null ? null : item.getAttributeAsJid("jid");
731 return result != null ? result : fallback;
732 }
733
734 private void sendMessageReceipts(Account account, MessagePacket packet) {
735 ArrayList<String> receiptsNamespaces = new ArrayList<>();
736 if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
737 receiptsNamespaces.add("urn:xmpp:chat-markers:0");
738 }
739 if (packet.hasChild("request", "urn:xmpp:receipts")) {
740 receiptsNamespaces.add("urn:xmpp:receipts");
741 }
742 if (receiptsNamespaces.size() > 0) {
743 MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
744 packet,
745 receiptsNamespaces,
746 packet.getType());
747 mXmppConnectionService.sendMessagePacket(account, receipt);
748 }
749 }
750
751 private static SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss");
752
753 private void activateGracePeriod(Account account) {
754
755 long duration;
756 long defaultValue = mXmppConnectionService.getResources().getInteger(R.integer.grace_period);
757 try {
758 duration = Long.parseLong(mXmppConnectionService.getPreferences().getString("grace_period_length", String.valueOf(defaultValue))) * 1000;
759 } catch (NumberFormatException e) {
760 duration = defaultValue * 1000;
761 }
762 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": activating grace period ("+duration+") till "+TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
763 account.activateGracePeriod(duration);
764 }
765}