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