MessageParser.java

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