MessageParser.java

   1package eu.siacs.conversations.parser;
   2
   3import android.util.Log;
   4import android.util.Pair;
   5
   6import java.text.SimpleDateFormat;
   7import java.util.ArrayList;
   8import java.util.Arrays;
   9import java.util.Collections;
  10import java.util.Date;
  11import java.util.List;
  12import java.util.Locale;
  13import java.util.Map;
  14import java.util.Set;
  15import java.util.UUID;
  16
  17import eu.siacs.conversations.Config;
  18import eu.siacs.conversations.R;
  19import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  20import eu.siacs.conversations.crypto.axolotl.BrokenSessionException;
  21import eu.siacs.conversations.crypto.axolotl.NotEncryptedForThisDeviceException;
  22import eu.siacs.conversations.crypto.axolotl.OutdatedSenderException;
  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.Conversational;
  29import eu.siacs.conversations.entities.Message;
  30import eu.siacs.conversations.entities.MucOptions;
  31import eu.siacs.conversations.entities.ReadByMarker;
  32import eu.siacs.conversations.entities.ReceiptRequest;
  33import eu.siacs.conversations.entities.RtpSessionStatus;
  34import eu.siacs.conversations.http.HttpConnectionManager;
  35import eu.siacs.conversations.services.MessageArchiveService;
  36import eu.siacs.conversations.services.QuickConversationsService;
  37import eu.siacs.conversations.services.XmppConnectionService;
  38import eu.siacs.conversations.utils.CryptoHelper;
  39import eu.siacs.conversations.xml.Element;
  40import eu.siacs.conversations.xml.LocalizedContent;
  41import eu.siacs.conversations.xml.Namespace;
  42import eu.siacs.conversations.xmpp.InvalidJid;
  43import eu.siacs.conversations.xmpp.Jid;
  44import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
  45import eu.siacs.conversations.xmpp.chatstate.ChatState;
  46import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
  47import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
  48import eu.siacs.conversations.xmpp.pep.Avatar;
  49import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  50
  51public class MessageParser extends AbstractParser implements OnMessagePacketReceived {
  52
  53    private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
  54
  55    private static final List<String> JINGLE_MESSAGE_ELEMENT_NAMES = Arrays.asList("accept", "propose", "proceed", "reject", "retract");
  56
  57    public MessageParser(XmppConnectionService service) {
  58        super(service);
  59    }
  60
  61    private static String extractStanzaId(Element packet, boolean isTypeGroupChat, Conversation conversation) {
  62        final Jid by;
  63        final boolean safeToExtract;
  64        if (isTypeGroupChat) {
  65            by = conversation.getJid().asBareJid();
  66            safeToExtract = conversation.getMucOptions().hasFeature(Namespace.STANZA_IDS);
  67        } else {
  68            Account account = conversation.getAccount();
  69            by = account.getJid().asBareJid();
  70            safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
  71        }
  72        return safeToExtract ? extractStanzaId(packet, by) : null;
  73    }
  74
  75    private static String extractStanzaId(Account account, Element packet) {
  76        final boolean safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
  77        return safeToExtract ? extractStanzaId(packet, account.getJid().asBareJid()) : null;
  78    }
  79
  80    private static String extractStanzaId(Element packet, Jid by) {
  81        for (Element child : packet.getChildren()) {
  82            if (child.getName().equals("stanza-id")
  83                    && Namespace.STANZA_IDS.equals(child.getNamespace())
  84                    && by.equals(InvalidJid.getNullForInvalid(child.getAttributeAsJid("by")))) {
  85                return child.getAttribute("id");
  86            }
  87        }
  88        return null;
  89    }
  90
  91    private static Jid getTrueCounterpart(Element mucUserElement, Jid fallback) {
  92        final Element item = mucUserElement == null ? null : mucUserElement.findChild("item");
  93        Jid result = item == null ? null : InvalidJid.getNullForInvalid(item.getAttributeAsJid("jid"));
  94        return result != null ? result : fallback;
  95    }
  96
  97    private boolean extractChatState(Conversation c, final boolean isTypeGroupChat, final MessagePacket packet) {
  98        ChatState state = ChatState.parse(packet);
  99        if (state != null && c != null) {
 100            final Account account = c.getAccount();
 101            final Jid from = packet.getFrom();
 102            if (from.asBareJid().equals(account.getJid().asBareJid())) {
 103                c.setOutgoingChatState(state);
 104                if (state == ChatState.ACTIVE || state == ChatState.COMPOSING) {
 105                    if (c.getContact().isSelf()) {
 106                        return false;
 107                    }
 108                    mXmppConnectionService.markRead(c);
 109                    activateGracePeriod(account);
 110                }
 111                return false;
 112            } else {
 113                if (isTypeGroupChat) {
 114                    MucOptions.User user = c.getMucOptions().findUserByFullJid(from);
 115                    if (user != null) {
 116                        return user.setChatState(state);
 117                    } else {
 118                        return false;
 119                    }
 120                } else {
 121                    return c.setIncomingChatState(state);
 122                }
 123            }
 124        }
 125        return false;
 126    }
 127
 128    private Message parseAxolotlChat(Element axolotlMessage, Jid from, Conversation conversation, int status, final boolean checkedForDuplicates, boolean postpone) {
 129        final AxolotlService service = conversation.getAccount().getAxolotlService();
 130        final XmppAxolotlMessage xmppAxolotlMessage;
 131        try {
 132            xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlMessage, from.asBareJid());
 133        } catch (Exception e) {
 134            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": invalid omemo message received " + e.getMessage());
 135            return null;
 136        }
 137        if (xmppAxolotlMessage.hasPayload()) {
 138            final XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage;
 139            try {
 140                plaintextMessage = service.processReceivingPayloadMessage(xmppAxolotlMessage, postpone);
 141            } catch (BrokenSessionException e) {
 142                if (checkedForDuplicates) {
 143                    if (service.trustedOrPreviouslyResponded(from.asBareJid())) {
 144                        service.reportBrokenSessionException(e, postpone);
 145                        return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
 146                    } else {
 147                        Log.d(Config.LOGTAG, "ignoring broken session exception because contact was not trusted");
 148                        return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
 149                    }
 150                } else {
 151                    Log.d(Config.LOGTAG, "ignoring broken session exception because checkForDuplicates failed");
 152                    return null;
 153                }
 154            } catch (NotEncryptedForThisDeviceException e) {
 155                return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE, status);
 156            } catch (OutdatedSenderException e) {
 157                return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
 158            }
 159            if (plaintextMessage != null) {
 160                Message finishedMessage = new Message(conversation, plaintextMessage.getPlaintext(), Message.ENCRYPTION_AXOLOTL, status);
 161                finishedMessage.setFingerprint(plaintextMessage.getFingerprint());
 162                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(finishedMessage.getConversation().getAccount()) + " Received Message with session fingerprint: " + plaintextMessage.getFingerprint());
 163                return finishedMessage;
 164            }
 165        } else {
 166            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": received OMEMO key transport message");
 167            service.processReceivingKeyTransportMessage(xmppAxolotlMessage, postpone);
 168        }
 169        return null;
 170    }
 171
 172    private Invite extractInvite(Element message) {
 173        final Element mucUser = message.findChild("x", Namespace.MUC_USER);
 174        if (mucUser != null) {
 175            Element invite = mucUser.findChild("invite");
 176            if (invite != null) {
 177                String password = mucUser.findChildContent("password");
 178                Jid from = InvalidJid.getNullForInvalid(invite.getAttributeAsJid("from"));
 179                Jid room = InvalidJid.getNullForInvalid(message.getAttributeAsJid("from"));
 180                if (room == null) {
 181                    return null;
 182                }
 183                return new Invite(room, password, false, from);
 184            }
 185        }
 186        final Element conference = message.findChild("x", "jabber:x:conference");
 187        if (conference != null) {
 188            Jid from = InvalidJid.getNullForInvalid(message.getAttributeAsJid("from"));
 189            Jid room = InvalidJid.getNullForInvalid(conference.getAttributeAsJid("jid"));
 190            if (room == null) {
 191                return null;
 192            }
 193            return new Invite(room, conference.getAttribute("password"), true, from);
 194        }
 195        return null;
 196    }
 197
 198    private void parseEvent(final Element event, final Jid from, final Account account) {
 199        final Element items = event.findChild("items");
 200        final String node = items == null ? null : items.getAttribute("node");
 201        if ("urn:xmpp:avatar:metadata".equals(node)) {
 202            Avatar avatar = Avatar.parseMetadata(items);
 203            if (avatar != null) {
 204                avatar.owner = from.asBareJid();
 205                if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
 206                    if (account.getJid().asBareJid().equals(from)) {
 207                        if (account.setAvatar(avatar.getFilename())) {
 208                            mXmppConnectionService.databaseBackend.updateAccount(account);
 209                            mXmppConnectionService.notifyAccountAvatarHasChanged(account);
 210                        }
 211                        mXmppConnectionService.getAvatarService().clear(account);
 212                        mXmppConnectionService.updateConversationUi();
 213                        mXmppConnectionService.updateAccountUi();
 214                    } else {
 215                        final Contact contact = account.getRoster().getContact(from);
 216                        contact.setAvatar(avatar);
 217                        mXmppConnectionService.syncRoster(account);
 218                        mXmppConnectionService.getAvatarService().clear(contact);
 219                        mXmppConnectionService.updateConversationUi();
 220                        mXmppConnectionService.updateRosterUi();
 221                    }
 222                } else if (mXmppConnectionService.isDataSaverDisabled()) {
 223                    mXmppConnectionService.fetchAvatar(account, avatar);
 224                }
 225            }
 226        } else if (Namespace.NICK.equals(node)) {
 227            final Element i = items.findChild("item");
 228            final String nick = i == null ? null : i.findChildContent("nick", Namespace.NICK);
 229            if (nick != null) {
 230                setNick(account, from, nick);
 231            }
 232        } else if (AxolotlService.PEP_DEVICE_LIST.equals(node)) {
 233            Element item = items.findChild("item");
 234            Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
 235            Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received PEP device list " + deviceIds + " update from " + from + ", processing... ");
 236            AxolotlService axolotlService = account.getAxolotlService();
 237            axolotlService.registerDevices(from, deviceIds);
 238        } else if (Namespace.BOOKMARKS.equals(node) && account.getJid().asBareJid().equals(from)) {
 239            if (account.getXmppConnection().getFeatures().bookmarksConversion()) {
 240                final Element i = items.findChild("item");
 241                final Element storage = i == null ? null : i.findChild("storage", Namespace.BOOKMARKS);
 242                Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
 243                mXmppConnectionService.processBookmarksInitial(account, bookmarks, true);
 244                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": processing bookmark PEP event");
 245            } else {
 246                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring bookmark PEP event because bookmark conversion was not detected");
 247            }
 248        } else if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
 249            final Element item = items.findChild("item");
 250            final Element retract = items.findChild("retract");
 251            if (item != null) {
 252                final Bookmark bookmark = Bookmark.parseFromItem(item, account);
 253                if (bookmark != null) {
 254                    account.putBookmark(bookmark);
 255                    mXmppConnectionService.processModifiedBookmark(bookmark);
 256                    mXmppConnectionService.updateConversationUi();
 257                }
 258            }
 259            if (retract != null) {
 260                final Jid id = InvalidJid.getNullForInvalid(retract.getAttributeAsJid("id"));
 261                if (id != null) {
 262                    account.removeBookmark(id);
 263                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": deleted bookmark for " + id);
 264                    mXmppConnectionService.processDeletedBookmark(account, id);
 265                    mXmppConnectionService.updateConversationUi();
 266                }
 267            }
 268        } else {
 269            Log.d(Config.LOGTAG, account.getJid().asBareJid() + " received pubsub notification for node=" + node);
 270        }
 271    }
 272
 273    private void parseDeleteEvent(final Element event, final Jid from, final Account account) {
 274        final Element delete = event.findChild("delete");
 275        final String node = delete == null ? null : delete.getAttribute("node");
 276        if (Namespace.NICK.equals(node)) {
 277            Log.d(Config.LOGTAG, "parsing nick delete event from " + from);
 278            setNick(account, from, null);
 279        } else if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
 280            account.setBookmarks(Collections.emptyMap());
 281            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": deleted bookmarks node");
 282        }
 283    }
 284
 285    private void parsePurgeEvent(final Element event, final Jid from, final Account account) {
 286        final Element purge = event.findChild("purge");
 287        final String node = purge == null ? null : purge.getAttribute("node");
 288        if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
 289            account.setBookmarks(Collections.emptyMap());
 290            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": purged bookmarks");
 291        }
 292    }
 293
 294    private void setNick(Account account, Jid user, String nick) {
 295        if (user.asBareJid().equals(account.getJid().asBareJid())) {
 296            account.setDisplayName(nick);
 297            if (QuickConversationsService.isQuicksy()) {
 298                mXmppConnectionService.getAvatarService().clear(account);
 299            }
 300        } else {
 301            Contact contact = account.getRoster().getContact(user);
 302            if (contact.setPresenceName(nick)) {
 303                mXmppConnectionService.syncRoster(account);
 304                mXmppConnectionService.getAvatarService().clear(contact);
 305            }
 306        }
 307        mXmppConnectionService.updateConversationUi();
 308        mXmppConnectionService.updateAccountUi();
 309    }
 310
 311    private boolean handleErrorMessage(final Account account, final MessagePacket packet) {
 312        if (packet.getType() == MessagePacket.TYPE_ERROR) {
 313            if (packet.fromServer(account)) {
 314                final Pair<MessagePacket, Long> forwarded = packet.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
 315                if (forwarded != null) {
 316                    return handleErrorMessage(account, forwarded.first);
 317                }
 318            }
 319            final Jid from = packet.getFrom();
 320            final String id = packet.getId();
 321            if (from != null && id != null) {
 322                if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
 323                    final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
 324                    mXmppConnectionService.getJingleConnectionManager()
 325                            .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.FAILED);
 326                    return true;
 327                }
 328                if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROCEED_ID_PREFIX)) {
 329                    final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROCEED_ID_PREFIX.length());
 330                    final String message = extractErrorMessage(packet);
 331                    mXmppConnectionService.getJingleConnectionManager().failProceed(account, from, sessionId, message);
 332                    return true;
 333                }
 334                mXmppConnectionService.markMessage(account,
 335                        from.asBareJid(),
 336                        id,
 337                        Message.STATUS_SEND_FAILED,
 338                        extractErrorMessage(packet));
 339                final Element error = packet.findChild("error");
 340                final boolean pingWorthyError = error != null && (error.hasChild("not-acceptable") || error.hasChild("remote-server-timeout") || error.hasChild("remote-server-not-found"));
 341                if (pingWorthyError) {
 342                    Conversation conversation = mXmppConnectionService.find(account, from);
 343                    if (conversation != null && conversation.getMode() == Conversational.MODE_MULTI) {
 344                        if (conversation.getMucOptions().online()) {
 345                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received ping worthy error for seemingly online muc at " + from);
 346                            mXmppConnectionService.mucSelfPingAndRejoin(conversation);
 347                        }
 348                    }
 349                }
 350            }
 351            return true;
 352        }
 353        return false;
 354    }
 355
 356    @Override
 357    public void onMessagePacketReceived(Account account, MessagePacket original) {
 358        if (handleErrorMessage(account, original)) {
 359            return;
 360        }
 361        final MessagePacket packet;
 362        Long timestamp = null;
 363        boolean isCarbon = false;
 364        String serverMsgId = null;
 365        final Element fin = original.findChild("fin", MessageArchiveService.Version.MAM_0.namespace);
 366        if (fin != null) {
 367            mXmppConnectionService.getMessageArchiveService().processFinLegacy(fin, original.getFrom());
 368            return;
 369        }
 370        final Element result = MessageArchiveService.Version.findResult(original);
 371        final String queryId = result == null ? null : result.getAttribute("queryid");
 372        final MessageArchiveService.Query query = queryId == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(queryId);
 373        if (query != null && query.validFrom(original.getFrom())) {
 374            final Pair<MessagePacket, Long> f = original.getForwardedMessagePacket("result", query.version.namespace);
 375            if (f == null) {
 376                return;
 377            }
 378            timestamp = f.second;
 379            packet = f.first;
 380            serverMsgId = result.getAttribute("id");
 381            query.incrementMessageCount();
 382            if (handleErrorMessage(account, packet)) {
 383                return;
 384            }
 385        } else if (query != null) {
 386            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received mam result with invalid from (" + original.getFrom() + ") or queryId (" + queryId + ")");
 387            return;
 388        } else if (original.fromServer(account)) {
 389            Pair<MessagePacket, Long> f;
 390            f = original.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
 391            f = f == null ? original.getForwardedMessagePacket("sent", "urn:xmpp:carbons:2") : f;
 392            packet = f != null ? f.first : original;
 393            if (handleErrorMessage(account, packet)) {
 394                return;
 395            }
 396            timestamp = f != null ? f.second : null;
 397            isCarbon = f != null;
 398        } else {
 399            packet = original;
 400        }
 401
 402        if (timestamp == null) {
 403            timestamp = AbstractParser.parseTimestamp(original, AbstractParser.parseTimestamp(packet));
 404        }
 405        final LocalizedContent body = packet.getBody();
 406        final Element mucUserElement = packet.findChild("x", Namespace.MUC_USER);
 407        final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted");
 408        final Element replaceElement = packet.findChild("replace", "urn:xmpp:message-correct:0");
 409        final Element oob = packet.findChild("x", Namespace.OOB);
 410        final String oobUrl = oob != null ? oob.findChildContent("url") : null;
 411        final String replacementId = replaceElement == null ? null : replaceElement.getAttribute("id");
 412        final Element axolotlEncrypted = packet.findChildEnsureSingle(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
 413        int status;
 414        final Jid counterpart;
 415        final Jid to = packet.getTo();
 416        final Jid from = packet.getFrom();
 417        final Element originId = packet.findChild("origin-id", Namespace.STANZA_IDS);
 418        final String remoteMsgId;
 419        if (originId != null && originId.getAttribute("id") != null) {
 420            remoteMsgId = originId.getAttribute("id");
 421        } else {
 422            remoteMsgId = packet.getId();
 423        }
 424        boolean notify = false;
 425
 426        if (from == null || !InvalidJid.isValid(from) || !InvalidJid.isValid(to)) {
 427            Log.e(Config.LOGTAG, "encountered invalid message from='" + from + "' to='" + to + "'");
 428            return;
 429        }
 430
 431        boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
 432        if (query != null && !query.muc() && isTypeGroupChat) {
 433            Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": received groupchat (" + from + ") message on regular MAM request. skipping");
 434            return;
 435        }
 436        boolean isMucStatusMessage = InvalidJid.hasValidFrom(packet) && from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
 437        boolean selfAddressed;
 438        if (packet.fromAccount(account)) {
 439            status = Message.STATUS_SEND;
 440            selfAddressed = to == null || account.getJid().asBareJid().equals(to.asBareJid());
 441            if (selfAddressed) {
 442                counterpart = from;
 443            } else {
 444                counterpart = to != null ? to : account.getJid();
 445            }
 446        } else {
 447            status = Message.STATUS_RECEIVED;
 448            counterpart = from;
 449            selfAddressed = false;
 450        }
 451
 452        final Invite invite = extractInvite(packet);
 453        if (invite != null) {
 454            if (isTypeGroupChat) {
 455                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring invite to " + invite.jid + " because type=groupchat");
 456            } else if (invite.direct && (mucUserElement != null || invite.inviter == null || mXmppConnectionService.isMuc(account, invite.inviter))) {
 457                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring direct invite to " + invite.jid + " because it was received in MUC");
 458            } else {
 459                invite.execute(account);
 460                return;
 461            }
 462        }
 463
 464        if ((body != null || pgpEncrypted != null || (axolotlEncrypted != null && axolotlEncrypted.hasChild("payload")) || oobUrl != null) && !isMucStatusMessage) {
 465            final boolean conversationIsProbablyMuc = isTypeGroupChat || mucUserElement != null || account.getXmppConnection().getMucServersWithholdAccount().contains(counterpart.getDomain().toEscapedString());
 466            final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), conversationIsProbablyMuc, false, query, false);
 467            final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
 468
 469            if (serverMsgId == null) {
 470                serverMsgId = extractStanzaId(packet, isTypeGroupChat, conversation);
 471            }
 472
 473
 474            if (selfAddressed) {
 475                if (mXmppConnectionService.markMessage(conversation, remoteMsgId, Message.STATUS_SEND_RECEIVED, serverMsgId)) {
 476                    return;
 477                }
 478                status = Message.STATUS_RECEIVED;
 479                if (remoteMsgId != null && conversation.findMessageWithRemoteId(remoteMsgId, counterpart) != null) {
 480                    return;
 481                }
 482            }
 483
 484            if (isTypeGroupChat) {
 485                if (conversation.getMucOptions().isSelf(counterpart)) {
 486                    status = Message.STATUS_SEND_RECEIVED;
 487                    isCarbon = true; //not really carbon but received from another resource
 488                    if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status, serverMsgId, body)) {
 489                        return;
 490                    } else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
 491                        if (body != null) {
 492                            Message message = conversation.findSentMessageWithBody(body.content);
 493                            if (message != null) {
 494                                mXmppConnectionService.markMessage(message, status);
 495                                return;
 496                            }
 497                        }
 498                    }
 499                } else {
 500                    status = Message.STATUS_RECEIVED;
 501                }
 502            }
 503            final Message message;
 504            if (pgpEncrypted != null && Config.supportOpenPgp()) {
 505                message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status);
 506            } else if (axolotlEncrypted != null && Config.supportOmemo()) {
 507                Jid origin;
 508                Set<Jid> fallbacksBySourceId = Collections.emptySet();
 509                if (conversationMultiMode) {
 510                    final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
 511                    origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
 512                    if (origin == null) {
 513                        try {
 514                            fallbacksBySourceId = account.getAxolotlService().findCounterpartsBySourceId(XmppAxolotlMessage.parseSourceId(axolotlEncrypted));
 515                        } catch (IllegalArgumentException e) {
 516                            //ignoring
 517                        }
 518                    }
 519                    if (origin == null && fallbacksBySourceId.size() == 0) {
 520                        Log.d(Config.LOGTAG, "axolotl message in anonymous conference received and no possible fallbacks");
 521                        return;
 522                    }
 523                } else {
 524                    fallbacksBySourceId = Collections.emptySet();
 525                    origin = from;
 526                }
 527
 528                final boolean liveMessage = query == null && !isTypeGroupChat && mucUserElement == null;
 529                final boolean checkedForDuplicates = liveMessage || (serverMsgId != null && remoteMsgId != null && !conversation.possibleDuplicate(serverMsgId, remoteMsgId));
 530
 531                if (origin != null) {
 532                    message = parseAxolotlChat(axolotlEncrypted, origin, conversation, status, checkedForDuplicates, query != null);
 533                } else {
 534                    Message trial = null;
 535                    for (Jid fallback : fallbacksBySourceId) {
 536                        trial = parseAxolotlChat(axolotlEncrypted, fallback, conversation, status, checkedForDuplicates && fallbacksBySourceId.size() == 1, query != null);
 537                        if (trial != null) {
 538                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": decoded muc message using fallback");
 539                            origin = fallback;
 540                            break;
 541                        }
 542                    }
 543                    message = trial;
 544                }
 545                if (message == null) {
 546                    if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
 547                        mXmppConnectionService.updateConversationUi();
 548                    }
 549                    if (query != null && status == Message.STATUS_SEND && remoteMsgId != null) {
 550                        Message previouslySent = conversation.findSentMessageWithUuid(remoteMsgId);
 551                        if (previouslySent != null && previouslySent.getServerMsgId() == null && serverMsgId != null) {
 552                            previouslySent.setServerMsgId(serverMsgId);
 553                            mXmppConnectionService.databaseBackend.updateMessage(previouslySent, false);
 554                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": encountered previously sent OMEMO message without serverId. updating...");
 555                        }
 556                    }
 557                    return;
 558                }
 559                if (conversationMultiMode) {
 560                    message.setTrueCounterpart(origin);
 561                }
 562            } else if (body == null && oobUrl != null) {
 563                message = new Message(conversation, oobUrl, Message.ENCRYPTION_NONE, status);
 564                message.setOob(oobUrl);
 565                if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
 566                    message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 567                }
 568            } else {
 569                message = new Message(conversation, body.content, Message.ENCRYPTION_NONE, status);
 570                if (body.count > 1) {
 571                    message.setBodyLanguage(body.language);
 572                }
 573            }
 574
 575            message.setSubject(original.findChildContent("subject"));
 576            message.setCounterpart(counterpart);
 577            message.setRemoteMsgId(remoteMsgId);
 578            message.setServerMsgId(serverMsgId);
 579            message.setCarbon(isCarbon);
 580            message.setTime(timestamp);
 581            if (oobUrl != null) {
 582                message.setOob(oobUrl);
 583                if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
 584                    message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 585                }
 586            }
 587            message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
 588            if (conversationMultiMode) {
 589                message.setMucUser(conversation.getMucOptions().findUserByFullJid(counterpart));
 590                final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
 591                Jid trueCounterpart;
 592                if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
 593                    trueCounterpart = message.getTrueCounterpart();
 594                } else if (query != null && query.safeToExtractTrueCounterpart()) {
 595                    trueCounterpart = getTrueCounterpart(mucUserElement, fallback);
 596                } else {
 597                    trueCounterpart = fallback;
 598                }
 599                if (trueCounterpart != null && isTypeGroupChat) {
 600                    if (trueCounterpart.asBareJid().equals(account.getJid().asBareJid())) {
 601                        status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND;
 602                    } else {
 603                        status = Message.STATUS_RECEIVED;
 604                        message.setCarbon(false);
 605                    }
 606                }
 607                message.setStatus(status);
 608                message.setTrueCounterpart(trueCounterpart);
 609                if (!isTypeGroupChat) {
 610                    message.setType(Message.TYPE_PRIVATE);
 611                }
 612            } else {
 613                updateLastseen(account, from);
 614            }
 615
 616            if (replacementId != null && mXmppConnectionService.allowMessageCorrection()) {
 617                final Message replacedMessage = conversation.findMessageWithRemoteIdAndCounterpart(replacementId,
 618                        counterpart,
 619                        message.getStatus() == Message.STATUS_RECEIVED,
 620                        message.isCarbon());
 621                if (replacedMessage != null) {
 622                    final boolean fingerprintsMatch = replacedMessage.getFingerprint() == null
 623                            || replacedMessage.getFingerprint().equals(message.getFingerprint());
 624                    final boolean trueCountersMatch = replacedMessage.getTrueCounterpart() != null
 625                            && message.getTrueCounterpart() != null
 626                            && replacedMessage.getTrueCounterpart().asBareJid().equals(message.getTrueCounterpart().asBareJid());
 627                    final boolean mucUserMatches = query == null && replacedMessage.sameMucUser(message); //can not be checked when using mam
 628                    final boolean duplicate = conversation.hasDuplicateMessage(message);
 629                    if (fingerprintsMatch && (trueCountersMatch || !conversationMultiMode || mucUserMatches) && !duplicate) {
 630                        Log.d(Config.LOGTAG, "replaced message '" + replacedMessage.getBody() + "' with '" + message.getBody() + "'");
 631                        synchronized (replacedMessage) {
 632                            final String uuid = replacedMessage.getUuid();
 633                            replacedMessage.setUuid(UUID.randomUUID().toString());
 634                            replacedMessage.setBody(message.getBody());
 635                            replacedMessage.putEdited(replacedMessage.getRemoteMsgId(), replacedMessage.getServerMsgId());
 636                            replacedMessage.setRemoteMsgId(remoteMsgId);
 637                            if (replacedMessage.getServerMsgId() == null || message.getServerMsgId() != null) {
 638                                replacedMessage.setServerMsgId(message.getServerMsgId());
 639                            }
 640                            replacedMessage.setEncryption(message.getEncryption());
 641                            if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
 642                                replacedMessage.markUnread();
 643                            }
 644                            extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
 645                            mXmppConnectionService.updateMessage(replacedMessage, uuid);
 646                            if (mXmppConnectionService.confirmMessages()
 647                                    && replacedMessage.getStatus() == Message.STATUS_RECEIVED
 648                                    && (replacedMessage.trusted() || replacedMessage.isPrivateMessage()) //TODO do we really want to send receipts for all PMs?
 649                                    && remoteMsgId != null
 650                                    && !selfAddressed
 651                                    && !isTypeGroupChat) {
 652                                processMessageReceipts(account, packet, remoteMsgId, query);
 653                            }
 654                            if (replacedMessage.getEncryption() == Message.ENCRYPTION_PGP) {
 655                                conversation.getAccount().getPgpDecryptionService().discard(replacedMessage);
 656                                conversation.getAccount().getPgpDecryptionService().decrypt(replacedMessage, false);
 657                            }
 658                        }
 659                        mXmppConnectionService.getNotificationService().updateNotification();
 660                        return;
 661                    } else {
 662                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received message correction but verification didn't check out");
 663                    }
 664                }
 665            }
 666
 667            long deletionDate = mXmppConnectionService.getAutomaticMessageDeletionDate();
 668            if (deletionDate != 0 && message.getTimeSent() < deletionDate) {
 669                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping message from " + message.getCounterpart().toString() + " because it was sent prior to our deletion date");
 670                return;
 671            }
 672
 673            boolean checkForDuplicates = (isTypeGroupChat && packet.hasChild("delay", "urn:xmpp:delay"))
 674                    || message.isPrivateMessage()
 675                    || message.getServerMsgId() != null
 676                    || (query == null && mXmppConnectionService.getMessageArchiveService().isCatchupInProgress(conversation));
 677            if (checkForDuplicates) {
 678                final Message duplicate = conversation.findDuplicateMessage(message);
 679                if (duplicate != null) {
 680                    final boolean serverMsgIdUpdated;
 681                    if (duplicate.getStatus() != Message.STATUS_RECEIVED
 682                            && duplicate.getUuid().equals(message.getRemoteMsgId())
 683                            && duplicate.getServerMsgId() == null
 684                            && message.getServerMsgId() != null) {
 685                        duplicate.setServerMsgId(message.getServerMsgId());
 686                        if (mXmppConnectionService.databaseBackend.updateMessage(duplicate, false)) {
 687                            serverMsgIdUpdated = true;
 688                        } else {
 689                            serverMsgIdUpdated = false;
 690                            Log.e(Config.LOGTAG, "failed to update message");
 691                        }
 692                    } else {
 693                        serverMsgIdUpdated = false;
 694                    }
 695                    Log.d(Config.LOGTAG, "skipping duplicate message with " + message.getCounterpart() + ". serverMsgIdUpdated=" + serverMsgIdUpdated);
 696                    return;
 697                }
 698            }
 699
 700            if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
 701                conversation.prepend(query.getActualInThisQuery(), message);
 702            } else {
 703                conversation.add(message);
 704            }
 705            if (query != null) {
 706                query.incrementActualMessageCount();
 707            }
 708
 709            if (query == null || query.isCatchup()) { //either no mam or catchup
 710                if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
 711                    mXmppConnectionService.markRead(conversation);
 712                    if (query == null) {
 713                        activateGracePeriod(account);
 714                    }
 715                } else {
 716                    message.markUnread();
 717                    notify = true;
 718                }
 719            }
 720
 721            if (message.getEncryption() == Message.ENCRYPTION_PGP) {
 722                notify = conversation.getAccount().getPgpDecryptionService().decrypt(message, notify);
 723            } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE || message.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
 724                notify = false;
 725            }
 726
 727            if (query == null) {
 728                extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
 729                mXmppConnectionService.updateConversationUi();
 730            }
 731
 732            if (mXmppConnectionService.confirmMessages()
 733                    && message.getStatus() == Message.STATUS_RECEIVED
 734                    && (message.trusted() || message.isPrivateMessage())
 735                    && remoteMsgId != null
 736                    && !selfAddressed
 737                    && !isTypeGroupChat) {
 738                processMessageReceipts(account, packet, remoteMsgId, query);
 739            }
 740
 741            mXmppConnectionService.databaseBackend.createMessage(message);
 742            final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
 743            if (message.trusted() && message.treatAsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
 744                manager.createNewDownloadConnection(message);
 745            } else if (notify) {
 746                if (query != null && query.isCatchup()) {
 747                    mXmppConnectionService.getNotificationService().pushFromBacklog(message);
 748                } else {
 749                    mXmppConnectionService.getNotificationService().push(message);
 750                }
 751            }
 752        } else if (!packet.hasChild("body")) { //no body
 753
 754            final Conversation conversation = mXmppConnectionService.find(account, from.asBareJid());
 755            if (axolotlEncrypted != null) {
 756                Jid origin;
 757                if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
 758                    final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
 759                    origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
 760                    if (origin == null) {
 761                        Log.d(Config.LOGTAG, "omemo key transport message in anonymous conference received");
 762                        return;
 763                    }
 764                } else if (isTypeGroupChat) {
 765                    return;
 766                } else {
 767                    origin = from;
 768                }
 769                try {
 770                    final XmppAxolotlMessage xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlEncrypted, origin.asBareJid());
 771                    account.getAxolotlService().processReceivingKeyTransportMessage(xmppAxolotlMessage, query != null);
 772                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": omemo key transport message received from " + origin);
 773                } catch (Exception e) {
 774                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": invalid omemo key transport message received " + e.getMessage());
 775                    return;
 776                }
 777            }
 778
 779            if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
 780                mXmppConnectionService.updateConversationUi();
 781            }
 782
 783            if (isTypeGroupChat) {
 784                if (packet.hasChild("subject")) { //TODO usually we would want to check for lack of body; however some servers do set a body :(
 785                    if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
 786                        conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
 787                        final LocalizedContent subject = packet.findInternationalizedChildContentInDefaultNamespace("subject");
 788                        if (subject != null && conversation.getMucOptions().setSubject(subject.content)) {
 789                            mXmppConnectionService.updateConversation(conversation);
 790                        }
 791                        mXmppConnectionService.updateConversationUi();
 792                        return;
 793                    }
 794                }
 795            }
 796            if (conversation != null && mucUserElement != null && InvalidJid.hasValidFrom(packet) && from.isBareJid()) {
 797                for (Element child : mucUserElement.getChildren()) {
 798                    if ("status".equals(child.getName())) {
 799                        try {
 800                            int code = Integer.parseInt(child.getAttribute("code"));
 801                            if ((code >= 170 && code <= 174) || (code >= 102 && code <= 104)) {
 802                                mXmppConnectionService.fetchConferenceConfiguration(conversation);
 803                                break;
 804                            }
 805                        } catch (Exception e) {
 806                            //ignored
 807                        }
 808                    } else if ("item".equals(child.getName())) {
 809                        MucOptions.User user = AbstractParser.parseItem(conversation, child);
 810                        Log.d(Config.LOGTAG, account.getJid() + ": changing affiliation for "
 811                                + user.getRealJid() + " to " + user.getAffiliation() + " in "
 812                                + conversation.getJid().asBareJid());
 813                        if (!user.realJidMatchesAccount()) {
 814                            boolean isNew = conversation.getMucOptions().updateUser(user);
 815                            mXmppConnectionService.getAvatarService().clear(conversation);
 816                            mXmppConnectionService.updateMucRosterUi();
 817                            mXmppConnectionService.updateConversationUi();
 818                            Contact contact = user.getContact();
 819                            if (!user.getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
 820                                Jid jid = user.getRealJid();
 821                                List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
 822                                if (cryptoTargets.remove(user.getRealJid())) {
 823                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
 824                                    conversation.setAcceptedCryptoTargets(cryptoTargets);
 825                                    mXmppConnectionService.updateConversation(conversation);
 826                                }
 827                            } else if (isNew
 828                                    && user.getRealJid() != null
 829                                    && conversation.getMucOptions().isPrivateAndNonAnonymous()
 830                                    && (contact == null || !contact.mutualPresenceSubscription())
 831                                    && account.getAxolotlService().hasEmptyDeviceList(user.getRealJid())) {
 832                                account.getAxolotlService().fetchDeviceIds(user.getRealJid());
 833                            }
 834                        }
 835                    }
 836                }
 837            }
 838            if (!isTypeGroupChat) {
 839                for (Element child : packet.getChildren()) {
 840                    if (Namespace.JINGLE_MESSAGE.equals(child.getNamespace()) && JINGLE_MESSAGE_ELEMENT_NAMES.contains(child.getName())) {
 841                        final String action = child.getName();
 842                        final String sessionId = child.getAttribute("id");
 843                        if (sessionId == null) {
 844                            break;
 845                        }
 846                        if (query == null) {
 847                            if (serverMsgId == null) {
 848                                serverMsgId = extractStanzaId(account, packet);
 849                            }
 850                            mXmppConnectionService.getJingleConnectionManager().deliverMessage(account, packet.getTo(), packet.getFrom(), child, remoteMsgId, serverMsgId, timestamp);
 851                            if (!account.getJid().asBareJid().equals(from.asBareJid()) && remoteMsgId != null) {
 852                                processMessageReceipts(account, packet, remoteMsgId, query);
 853                            }
 854                        } else if (query.isCatchup()) {
 855                            if ("propose".equals(action)) {
 856                                final Element description = child.findChild("description");
 857                                final String namespace = description == null ? null : description.getNamespace();
 858                                if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
 859                                    final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
 860                                    final Message preExistingMessage = c.findRtpSession(sessionId, status);
 861                                    if (preExistingMessage != null) {
 862                                        preExistingMessage.setServerMsgId(serverMsgId);
 863                                        mXmppConnectionService.updateMessage(preExistingMessage);
 864                                        break;
 865                                    }
 866                                    final Message message = new Message(
 867                                            c,
 868                                            status,
 869                                            Message.TYPE_RTP_SESSION,
 870                                            sessionId
 871                                    );
 872                                    message.setServerMsgId(serverMsgId);
 873                                    message.setTime(timestamp);
 874                                    message.setBody(new RtpSessionStatus(false, 0).toString());
 875                                    c.add(message);
 876                                    mXmppConnectionService.databaseBackend.createMessage(message);
 877                                }
 878                            } else if ("proceed".equals(action)) {
 879                                //status needs to be flipped to find the original propose
 880                                final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
 881                                final int s = packet.fromAccount(account) ? Message.STATUS_RECEIVED : Message.STATUS_SEND;
 882                                final Message message = c.findRtpSession(sessionId, s);
 883                                if (message != null) {
 884                                    message.setBody(new RtpSessionStatus(true, 0).toString());
 885                                    if (serverMsgId != null) {
 886                                        message.setServerMsgId(serverMsgId);
 887                                    }
 888                                    message.setTime(timestamp);
 889                                    mXmppConnectionService.updateMessage(message, true);
 890                                } else {
 891                                    Log.d(Config.LOGTAG, "unable to find original rtp session message for received propose");
 892                                }
 893
 894                            }
 895                        } else {
 896                            //MAM reloads (non catchups
 897                            if ("propose".equals(action)) {
 898                                final Element description = child.findChild("description");
 899                                final String namespace = description == null ? null : description.getNamespace();
 900                                if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
 901                                    final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
 902                                    final Message preExistingMessage = c.findRtpSession(sessionId, status);
 903                                    if (preExistingMessage != null) {
 904                                        preExistingMessage.setServerMsgId(serverMsgId);
 905                                        mXmppConnectionService.updateMessage(preExistingMessage);
 906                                        break;
 907                                    }
 908                                    final Message message = new Message(
 909                                            c,
 910                                            status,
 911                                            Message.TYPE_RTP_SESSION,
 912                                            sessionId
 913                                    );
 914                                    message.setServerMsgId(serverMsgId);
 915                                    message.setTime(timestamp);
 916                                    message.setBody(new RtpSessionStatus(true, 0).toString());
 917                                    if (query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
 918                                        c.prepend(query.getActualInThisQuery(), message);
 919                                    } else {
 920                                        c.add(message);
 921                                    }
 922                                    query.incrementActualMessageCount();
 923                                    mXmppConnectionService.databaseBackend.createMessage(message);
 924                                }
 925                            }
 926                        }
 927                        break;
 928                    }
 929                }
 930            }
 931        }
 932
 933        Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
 934        if (received == null) {
 935            received = packet.findChild("received", "urn:xmpp:receipts");
 936        }
 937        if (received != null) {
 938            String id = received.getAttribute("id");
 939            if (packet.fromAccount(account)) {
 940                if (query != null && id != null && packet.getTo() != null) {
 941                    query.removePendingReceiptRequest(new ReceiptRequest(packet.getTo(), id));
 942                }
 943            } else if (id != null) {
 944                if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
 945                    final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
 946                    mXmppConnectionService.getJingleConnectionManager()
 947                            .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.DISCOVERED);
 948                } else {
 949                    mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_RECEIVED);
 950                }
 951            }
 952        }
 953        Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
 954        if (displayed != null) {
 955            final String id = displayed.getAttribute("id");
 956            final Jid sender = InvalidJid.getNullForInvalid(displayed.getAttributeAsJid("sender"));
 957            if (packet.fromAccount(account) && !selfAddressed) {
 958                dismissNotification(account, counterpart, query, id);
 959                if (query == null) {
 960                    activateGracePeriod(account);
 961                }
 962            } else if (isTypeGroupChat) {
 963                final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
 964                final Message message;
 965                if (conversation != null && id != null) {
 966                    if (sender != null) {
 967                        message = conversation.findMessageWithRemoteId(id, sender);
 968                    } else {
 969                        message = conversation.findMessageWithServerMsgId(id);
 970                    }
 971                } else {
 972                    message = null;
 973                }
 974                if (message != null) {
 975                    final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
 976                    final Jid trueJid = getTrueCounterpart((query != null && query.safeToExtractTrueCounterpart()) ? mucUserElement : null, fallback);
 977                    final boolean trueJidMatchesAccount = account.getJid().asBareJid().equals(trueJid == null ? null : trueJid.asBareJid());
 978                    if (trueJidMatchesAccount || conversation.getMucOptions().isSelf(counterpart)) {
 979                        if (!message.isRead() && (query == null || query.isCatchup())) { //checking if message is unread fixes race conditions with reflections
 980                            mXmppConnectionService.markRead(conversation);
 981                        }
 982                    } else if (!counterpart.isBareJid() && trueJid != null) {
 983                        final ReadByMarker readByMarker = ReadByMarker.from(counterpart, trueJid);
 984                        if (message.addReadByMarker(readByMarker)) {
 985                            mXmppConnectionService.updateMessage(message, false);
 986                        }
 987                    }
 988                }
 989            } else {
 990                final Message displayedMessage = mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_DISPLAYED);
 991                Message message = displayedMessage == null ? null : displayedMessage.prev();
 992                while (message != null
 993                        && message.getStatus() == Message.STATUS_SEND_RECEIVED
 994                        && message.getTimeSent() < displayedMessage.getTimeSent()) {
 995                    mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
 996                    message = message.prev();
 997                }
 998                if (displayedMessage != null && selfAddressed) {
 999                    dismissNotification(account, counterpart, query, id);
1000                }
1001            }
1002        }
1003
1004        final Element event = original.findChild("event", "http://jabber.org/protocol/pubsub#event");
1005        if (event != null && InvalidJid.hasValidFrom(original) && original.getFrom().isBareJid()) {
1006            if (event.hasChild("items")) {
1007                parseEvent(event, original.getFrom(), account);
1008            } else if (event.hasChild("delete")) {
1009                parseDeleteEvent(event, original.getFrom(), account);
1010            } else if (event.hasChild("purge")) {
1011                parsePurgeEvent(event, original.getFrom(), account);
1012            }
1013        }
1014
1015        final String nick = packet.findChildContent("nick", Namespace.NICK);
1016        if (nick != null && InvalidJid.hasValidFrom(original)) {
1017            if (mXmppConnectionService.isMuc(account, from)) {
1018                return;
1019            }
1020            final Contact contact = account.getRoster().getContact(from);
1021            if (contact.setPresenceName(nick)) {
1022                mXmppConnectionService.syncRoster(account);
1023                mXmppConnectionService.getAvatarService().clear(contact);
1024            }
1025        }
1026    }
1027
1028    private void dismissNotification(Account account, Jid counterpart, MessageArchiveService.Query query, final String id) {
1029        final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
1030        if (conversation != null && (query == null || query.isCatchup())) {
1031            final String displayableId = conversation.findMostRecentRemoteDisplayableId();
1032            if (displayableId != null && displayableId.equals(id)) {
1033                mXmppConnectionService.markRead(conversation);
1034            } else {
1035                Log.w(Config.LOGTAG, account.getJid().asBareJid() + ": received dismissing display marker that did not match our last id in that conversation");
1036            }
1037        }
1038    }
1039
1040    private void processMessageReceipts(final Account account, final MessagePacket packet, final String remoteMsgId, MessageArchiveService.Query query) {
1041        final boolean markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
1042        final boolean request = packet.hasChild("request", "urn:xmpp:receipts");
1043        if (query == null) {
1044            final ArrayList<String> receiptsNamespaces = new ArrayList<>();
1045            if (markable) {
1046                receiptsNamespaces.add("urn:xmpp:chat-markers:0");
1047            }
1048            if (request) {
1049                receiptsNamespaces.add("urn:xmpp:receipts");
1050            }
1051            if (receiptsNamespaces.size() > 0) {
1052                final MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
1053                        packet.getFrom(),
1054                        remoteMsgId,
1055                        receiptsNamespaces,
1056                        packet.getType());
1057                mXmppConnectionService.sendMessagePacket(account, receipt);
1058            }
1059        } else if (query.isCatchup()) {
1060            if (request) {
1061                query.addPendingReceiptRequest(new ReceiptRequest(packet.getFrom(), remoteMsgId));
1062            }
1063        }
1064    }
1065
1066    private void activateGracePeriod(Account account) {
1067        long duration = mXmppConnectionService.getLongPreference("grace_period_length", R.integer.grace_period) * 1000;
1068        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": activating grace period till " + TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
1069        account.activateGracePeriod(duration);
1070    }
1071
1072    private class Invite {
1073        final Jid jid;
1074        final String password;
1075        final boolean direct;
1076        final Jid inviter;
1077
1078        Invite(Jid jid, String password, boolean direct, Jid inviter) {
1079            this.jid = jid;
1080            this.password = password;
1081            this.direct = direct;
1082            this.inviter = inviter;
1083        }
1084
1085        public boolean execute(Account account) {
1086            if (jid != null) {
1087                Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true, false);
1088                if (conversation.getMucOptions().online()) {
1089                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received invite to " + jid + " but muc is considered to be online");
1090                    mXmppConnectionService.mucSelfPingAndRejoin(conversation);
1091                } else {
1092                    conversation.getMucOptions().setPassword(password);
1093                    mXmppConnectionService.databaseBackend.updateConversation(conversation);
1094                    final Contact contact = inviter != null ? account.getRoster().getContactFromContactList(inviter) : null;
1095                    mXmppConnectionService.joinMuc(conversation, contact != null && contact.mutualPresenceSubscription());
1096                    mXmppConnectionService.updateConversationUi();
1097                }
1098                return true;
1099            }
1100            return false;
1101        }
1102    }
1103}