MessageParser.java

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