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