1package eu.siacs.conversations.parser;
   2
   3import android.net.Uri;
   4import android.util.Log;
   5import android.util.Pair;
   6
   7import com.cheogram.android.BobTransfer;
   8import com.cheogram.android.WebxdcUpdate;
   9
  10import com.google.common.base.Strings;
  11import com.google.common.collect.ImmutableSet;
  12
  13import java.io.File;
  14import java.net.URISyntaxException;
  15import java.text.SimpleDateFormat;
  16import java.util.ArrayList;
  17import java.util.Arrays;
  18import java.util.Collections;
  19import java.util.Date;
  20import java.util.HashSet;
  21import java.util.HashMap;
  22import java.util.LinkedHashSet;
  23import java.util.List;
  24import java.util.Locale;
  25import java.util.Map;
  26import java.util.Set;
  27import java.util.UUID;
  28import java.util.function.Consumer;
  29import java.util.stream.Collectors;
  30
  31import io.ipfs.cid.Cid;
  32
  33import eu.siacs.conversations.AppSettings;
  34import eu.siacs.conversations.Config;
  35import eu.siacs.conversations.R;
  36import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  37import eu.siacs.conversations.crypto.axolotl.BrokenSessionException;
  38import eu.siacs.conversations.crypto.axolotl.NotEncryptedForThisDeviceException;
  39import eu.siacs.conversations.crypto.axolotl.OutdatedSenderException;
  40import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
  41import eu.siacs.conversations.entities.Account;
  42import eu.siacs.conversations.entities.Bookmark;
  43import eu.siacs.conversations.entities.Contact;
  44import eu.siacs.conversations.entities.Conversation;
  45import eu.siacs.conversations.entities.Conversational;
  46import eu.siacs.conversations.entities.DownloadableFile;
  47import eu.siacs.conversations.entities.Message;
  48import eu.siacs.conversations.entities.MucOptions;
  49import eu.siacs.conversations.entities.Reaction;
  50import eu.siacs.conversations.entities.ReadByMarker;
  51import eu.siacs.conversations.entities.ReceiptRequest;
  52import eu.siacs.conversations.entities.RtpSessionStatus;
  53import eu.siacs.conversations.http.HttpConnectionManager;
  54import eu.siacs.conversations.services.MessageArchiveService;
  55import eu.siacs.conversations.services.QuickConversationsService;
  56import eu.siacs.conversations.services.XmppConnectionService;
  57import eu.siacs.conversations.utils.CryptoHelper;
  58import eu.siacs.conversations.utils.Emoticons;
  59import eu.siacs.conversations.xml.Element;
  60import eu.siacs.conversations.xml.LocalizedContent;
  61import eu.siacs.conversations.xml.Namespace;
  62import eu.siacs.conversations.xmpp.InvalidJid;
  63import eu.siacs.conversations.xmpp.Jid;
  64import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
  65import eu.siacs.conversations.xmpp.chatstate.ChatState;
  66import eu.siacs.conversations.xmpp.forms.Data;
  67import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
  68import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
  69import eu.siacs.conversations.xmpp.pep.Avatar;
  70import im.conversations.android.xmpp.model.Extension;
  71import im.conversations.android.xmpp.model.carbons.Received;
  72import im.conversations.android.xmpp.model.carbons.Sent;
  73import im.conversations.android.xmpp.model.correction.Replace;
  74import im.conversations.android.xmpp.model.forward.Forwarded;
  75import im.conversations.android.xmpp.model.occupant.OccupantId;
  76import im.conversations.android.xmpp.model.reactions.Reactions;
  77
  78public class MessageParser extends AbstractParser implements Consumer<im.conversations.android.xmpp.model.stanza.Message> {
  79
  80    private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
  81
  82    private static final List<String> JINGLE_MESSAGE_ELEMENT_NAMES =
  83            Arrays.asList("accept", "propose", "proceed", "reject", "retract", "ringing", "finish");
  84
  85    public MessageParser(final XmppConnectionService service, final Account account) {
  86        super(service, account);
  87    }
  88
  89    private static String extractStanzaId(Element packet, boolean isTypeGroupChat, Conversation conversation) {
  90        final Jid by;
  91        final boolean safeToExtract;
  92        if (isTypeGroupChat) {
  93            by = conversation.getJid().asBareJid();
  94            safeToExtract = conversation.getMucOptions().hasFeature(Namespace.STANZA_IDS);
  95        } else {
  96            Account account = conversation.getAccount();
  97            by = account.getJid().asBareJid();
  98            safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
  99        }
 100        return safeToExtract ? extractStanzaId(packet, by) : null;
 101    }
 102
 103    private static String extractStanzaId(Account account, Element packet) {
 104        final boolean safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
 105        return safeToExtract ? extractStanzaId(packet, account.getJid().asBareJid()) : null;
 106    }
 107
 108    private static String extractStanzaId(Element packet, Jid by) {
 109        for (Element child : packet.getChildren()) {
 110            if (child.getName().equals("stanza-id")
 111                    && Namespace.STANZA_IDS.equals(child.getNamespace())
 112                    && by.equals(InvalidJid.getNullForInvalid(child.getAttributeAsJid("by")))) {
 113                return child.getAttribute("id");
 114            }
 115        }
 116        return null;
 117    }
 118
 119    private static Jid getTrueCounterpart(Element mucUserElement, Jid fallback) {
 120        final Element item = mucUserElement == null ? null : mucUserElement.findChild("item");
 121        Jid result = item == null ? null : InvalidJid.getNullForInvalid(item.getAttributeAsJid("jid"));
 122        return result != null ? result : fallback;
 123    }
 124
 125    private boolean extractChatState(Conversation c, final boolean isTypeGroupChat, final im.conversations.android.xmpp.model.stanza.Message packet) {
 126        ChatState state = ChatState.parse(packet);
 127        if (state != null && c != null) {
 128            final Account account = c.getAccount();
 129            final Jid from = packet.getFrom();
 130            if (from.asBareJid().equals(account.getJid().asBareJid())) {
 131                c.setOutgoingChatState(state);
 132                if (state == ChatState.ACTIVE || state == ChatState.COMPOSING) {
 133                    if (c.getContact().isSelf()) {
 134                        return false;
 135                    }
 136                    mXmppConnectionService.markRead(c);
 137                    activateGracePeriod(account);
 138                }
 139                return false;
 140            } else {
 141                if (isTypeGroupChat) {
 142                    MucOptions.User user = c.getMucOptions().findUserByFullJid(from);
 143                    if (user != null) {
 144                        return user.setChatState(state);
 145                    } else {
 146                        return false;
 147                    }
 148                } else {
 149                    return c.setIncomingChatState(state);
 150                }
 151            }
 152        }
 153        return false;
 154    }
 155
 156    private Message parseAxolotlChat(Element axolotlMessage, Jid from, Conversation conversation, int status, final boolean checkedForDuplicates, boolean postpone) {
 157        final AxolotlService service = conversation.getAccount().getAxolotlService();
 158        final XmppAxolotlMessage xmppAxolotlMessage;
 159        try {
 160            xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlMessage, from.asBareJid());
 161        } catch (Exception e) {
 162            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": invalid omemo message received " + e.getMessage());
 163            return null;
 164        }
 165        if (xmppAxolotlMessage.hasPayload()) {
 166            final XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage;
 167            try {
 168                plaintextMessage = service.processReceivingPayloadMessage(xmppAxolotlMessage, postpone);
 169            } catch (BrokenSessionException e) {
 170                if (checkedForDuplicates) {
 171                    if (service.trustedOrPreviouslyResponded(from.asBareJid())) {
 172                        service.reportBrokenSessionException(e, postpone);
 173                        return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
 174                    } else {
 175                        Log.d(Config.LOGTAG, "ignoring broken session exception because contact was not trusted");
 176                        return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
 177                    }
 178                } else {
 179                    Log.d(Config.LOGTAG, "ignoring broken session exception because checkForDuplicates failed");
 180                    return null;
 181                }
 182            } catch (NotEncryptedForThisDeviceException e) {
 183                return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE, status);
 184            } catch (OutdatedSenderException e) {
 185                return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
 186            }
 187            if (plaintextMessage != null) {
 188                Message finishedMessage = new Message(conversation, plaintextMessage.getPlaintext(), Message.ENCRYPTION_AXOLOTL, status);
 189                finishedMessage.setFingerprint(plaintextMessage.getFingerprint());
 190                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(finishedMessage.getConversation().getAccount()) + " Received Message with session fingerprint: " + plaintextMessage.getFingerprint());
 191                return finishedMessage;
 192            }
 193        } else {
 194            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": received OMEMO key transport message");
 195            service.processReceivingKeyTransportMessage(xmppAxolotlMessage, postpone);
 196        }
 197        return null;
 198    }
 199
 200    private Invite extractInvite(final Element message) {
 201        final Element mucUser = message.findChild("x", Namespace.MUC_USER);
 202        if (mucUser != null) {
 203            final Element invite = mucUser.findChild("invite");
 204            if (invite != null) {
 205                final String password = mucUser.findChildContent("password");
 206                final Jid from = InvalidJid.getNullForInvalid(invite.getAttributeAsJid("from"));
 207                final Jid to = InvalidJid.getNullForInvalid(invite.getAttributeAsJid("to"));
 208                if (to != null && from == null) {
 209                    Log.d(Config.LOGTAG,"do not parse outgoing mediated invite "+message);
 210                    return null;
 211                }
 212                final Jid room = InvalidJid.getNullForInvalid(message.getAttributeAsJid("from"));
 213                if (room == null) {
 214                    return null;
 215                }
 216                return new Invite(room, password, false, from);
 217            }
 218        }
 219        final Element conference = message.findChild("x", "jabber:x:conference");
 220        if (conference != null) {
 221            Jid from = InvalidJid.getNullForInvalid(message.getAttributeAsJid("from"));
 222            Jid room = InvalidJid.getNullForInvalid(conference.getAttributeAsJid("jid"));
 223            if (room == null) {
 224                return null;
 225            }
 226            return new Invite(room, conference.getAttribute("password"), true, from);
 227        }
 228        return null;
 229    }
 230
 231    private void parseEvent(final Element event, final Jid from, final Account account) {
 232        final Element items = event.findChild("items");
 233        final String node = items == null ? null : items.getAttribute("node");
 234        if ("urn:xmpp:avatar:metadata".equals(node)) {
 235            Avatar avatar = Avatar.parseMetadata(items);
 236            if (avatar != null) {
 237                avatar.owner = from.asBareJid();
 238                if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
 239                    if (account.getJid().asBareJid().equals(from)) {
 240                        if (account.setAvatar(avatar.getFilename())) {
 241                            mXmppConnectionService.databaseBackend.updateAccount(account);
 242                            mXmppConnectionService.notifyAccountAvatarHasChanged(account);
 243                        }
 244                        mXmppConnectionService.getAvatarService().clear(account);
 245                        mXmppConnectionService.updateConversationUi();
 246                        mXmppConnectionService.updateAccountUi();
 247                    } else {
 248                        final Contact contact = account.getRoster().getContact(from);
 249                        contact.setAvatar(avatar);
 250                        mXmppConnectionService.syncRoster(account);
 251                        mXmppConnectionService.getAvatarService().clear(contact);
 252                        mXmppConnectionService.updateConversationUi();
 253                        mXmppConnectionService.updateRosterUi(XmppConnectionService.UpdateRosterReason.AVATAR);
 254                    }
 255                } else if (mXmppConnectionService.isDataSaverDisabled()) {
 256                    mXmppConnectionService.fetchAvatar(account, avatar);
 257                }
 258            }
 259        } else if (Namespace.NICK.equals(node)) {
 260            final Element i = items.findChild("item");
 261            final String nick = i == null ? null : i.findChildContent("nick", Namespace.NICK);
 262            if (nick != null) {
 263                setNick(account, from, nick);
 264            }
 265        } else if (AxolotlService.PEP_DEVICE_LIST.equals(node)) {
 266            Element item = items.findChild("item");
 267            final Set<Integer> deviceIds = IqParser.deviceIds(item);
 268            Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received PEP device list " + deviceIds + " update from " + from + ", processing... ");
 269            final AxolotlService axolotlService = account.getAxolotlService();
 270            axolotlService.registerDevices(from, deviceIds);
 271        } else if (Namespace.BOOKMARKS.equals(node) && account.getJid().asBareJid().equals(from)) {
 272            final var connection = account.getXmppConnection();
 273            if (connection.getFeatures().bookmarksConversion()) {
 274                if (connection.getFeatures().bookmarks2()) {
 275                    Log.w(
 276                            Config.LOGTAG,
 277                            account.getJid().asBareJid()
 278                                    + ": received storage:bookmark notification even though we opted into bookmarks:1");
 279                }
 280                final Element i = items.findChild("item");
 281                final Element storage =
 282                        i == null ? null : i.findChild("storage", Namespace.BOOKMARKS);
 283                final Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
 284                mXmppConnectionService.processBookmarksInitial(account, bookmarks, true);
 285                Log.d(
 286                        Config.LOGTAG,
 287                        account.getJid().asBareJid() + ": processing bookmark PEP event");
 288            } else {
 289                Log.d(
 290                        Config.LOGTAG,
 291                        account.getJid().asBareJid()
 292                                + ": ignoring bookmark PEP event because bookmark conversion was not detected");
 293            }
 294        } else if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
 295            final Element item = items.findChild("item");
 296            final Element retract = items.findChild("retract");
 297            if (item != null) {
 298                final Bookmark bookmark = Bookmark.parseFromItem(item, account);
 299                if (bookmark != null) {
 300                    account.putBookmark(bookmark);
 301                    mXmppConnectionService.processModifiedBookmark(bookmark);
 302                    mXmppConnectionService.updateConversationUi();
 303                }
 304            }
 305            if (retract != null) {
 306                final Jid id = InvalidJid.getNullForInvalid(retract.getAttributeAsJid("id"));
 307                if (id != null) {
 308                    account.removeBookmark(id);
 309                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": deleted bookmark for " + id);
 310                    mXmppConnectionService.processDeletedBookmark(account, id);
 311                    mXmppConnectionService.updateConversationUi();
 312                }
 313            }
 314        } else if (Config.MESSAGE_DISPLAYED_SYNCHRONIZATION
 315                && Namespace.MDS_DISPLAYED.equals(node)
 316                && account.getJid().asBareJid().equals(from)) {
 317            final Element item = items.findChild("item");
 318            mXmppConnectionService.processMdsItem(account, item);
 319        } else {
 320            Log.d(
 321                    Config.LOGTAG,
 322                    account.getJid().asBareJid()
 323                            + " received pubsub notification for node="
 324                            + node);
 325        }
 326    }
 327
 328    private void parseDeleteEvent(final Element event, final Jid from, final Account account) {
 329        final Element delete = event.findChild("delete");
 330        final String node = delete == null ? null : delete.getAttribute("node");
 331        if (Namespace.NICK.equals(node)) {
 332            Log.d(Config.LOGTAG, "parsing nick delete event from " + from);
 333            setNick(account, from, null);
 334        } else if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
 335            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": deleted bookmarks node");
 336            deleteAllBookmarks(account);
 337        } else if (Namespace.AVATAR_METADATA.equals(node) && account.getJid().asBareJid().equals(from)) {
 338            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": deleted avatar metadata node");
 339        }
 340    }
 341
 342    private void parsePurgeEvent(final Element event, final Jid from, final Account account) {
 343        final Element purge = event.findChild("purge");
 344        final String node = purge == null ? null : purge.getAttribute("node");
 345        if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
 346            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": purged bookmarks");
 347            deleteAllBookmarks(account);
 348        }
 349    }
 350
 351    private void deleteAllBookmarks(final Account account) {
 352        final var previous = account.getBookmarkedJids();
 353        account.setBookmarks(Collections.emptyMap());
 354        mXmppConnectionService.processDeletedBookmarks(account, previous);
 355    }
 356
 357    private void setNick(final Account account, final Jid user, final String nick) {
 358        if (user.asBareJid().equals(account.getJid().asBareJid())) {
 359            account.setDisplayName(nick);
 360            if (QuickConversationsService.isQuicksy()) {
 361                mXmppConnectionService.getAvatarService().clear(account);
 362            }
 363            mXmppConnectionService.checkMucRequiresRename();
 364        } else {
 365            Contact contact = account.getRoster().getContact(user);
 366            if (contact.setPresenceName(nick)) {
 367                mXmppConnectionService.syncRoster(account);
 368                mXmppConnectionService.getAvatarService().clear(contact);
 369            }
 370        }
 371        mXmppConnectionService.updateConversationUi();
 372        mXmppConnectionService.updateAccountUi();
 373    }
 374
 375    private boolean handleErrorMessage(final Account account, final im.conversations.android.xmpp.model.stanza.Message packet) {
 376        if (packet.getType() == im.conversations.android.xmpp.model.stanza.Message.Type.ERROR) {
 377            if (packet.fromServer(account)) {
 378                final var forwarded = getForwardedMessagePacket(packet,"received", Namespace.CARBONS);
 379                if (forwarded != null) {
 380                    return handleErrorMessage(account, forwarded.first);
 381                }
 382            }
 383            final Jid from = packet.getFrom();
 384            final String id = packet.getId();
 385            if (from != null && id != null) {
 386                if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
 387                    final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
 388                    mXmppConnectionService.getJingleConnectionManager()
 389                            .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.FAILED);
 390                    return true;
 391                }
 392                if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROCEED_ID_PREFIX)) {
 393                    final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROCEED_ID_PREFIX.length());
 394                    final String message = extractErrorMessage(packet);
 395                    mXmppConnectionService.getJingleConnectionManager().failProceed(account, from, sessionId, message);
 396                    return true;
 397                }
 398                mXmppConnectionService.markMessage(account,
 399                        from.asBareJid(),
 400                        id,
 401                        Message.STATUS_SEND_FAILED,
 402                        extractErrorMessage(packet));
 403                final Element error = packet.findChild("error");
 404                final boolean pingWorthyError = error != null && (error.hasChild("not-acceptable") || error.hasChild("remote-server-timeout") || error.hasChild("remote-server-not-found"));
 405                if (pingWorthyError) {
 406                    Conversation conversation = mXmppConnectionService.find(account, from);
 407                    if (conversation != null && conversation.getMode() == Conversational.MODE_MULTI) {
 408                        if (conversation.getMucOptions().online()) {
 409                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received ping worthy error for seemingly online muc at " + from);
 410                            mXmppConnectionService.mucSelfPingAndRejoin(conversation);
 411                        }
 412                    }
 413                }
 414            }
 415            return true;
 416        }
 417        return false;
 418    }
 419
 420    @Override
 421    public void accept(final im.conversations.android.xmpp.model.stanza.Message original) {
 422        if (handleErrorMessage(account, original)) {
 423            return;
 424        }
 425        final im.conversations.android.xmpp.model.stanza.Message packet;
 426        Long timestamp = null;
 427        boolean isCarbon = false;
 428        String serverMsgId = null;
 429        final Element fin = original.findChild("fin", MessageArchiveService.Version.MAM_0.namespace);
 430        if (fin != null) {
 431            mXmppConnectionService.getMessageArchiveService().processFinLegacy(fin, original.getFrom());
 432            return;
 433        }
 434        final Element result = MessageArchiveService.Version.findResult(original);
 435        final String queryId = result == null ? null : result.getAttribute("queryid");
 436        final MessageArchiveService.Query query = queryId == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(queryId);
 437        final boolean offlineMessagesRetrieved = account.getXmppConnection().isOfflineMessagesRetrieved();
 438        if (query != null && query.validFrom(original.getFrom())) {
 439            final var f = getForwardedMessagePacket(original,"result", query.version.namespace);
 440            if (f == null) {
 441                return;
 442            }
 443            timestamp = f.second;
 444            packet = f.first;
 445            serverMsgId = result.getAttribute("id");
 446            query.incrementMessageCount();
 447            if (handleErrorMessage(account, packet)) {
 448                return;
 449            }
 450            final var contact = packet.getFrom() == null || packet.getFrom() instanceof InvalidJid ? null : account.getRoster().getContact(packet.getFrom());
 451            if (contact != null && contact.isBlocked()) {
 452                Log.d(Config.LOGTAG, "Got MAM result from blocked contact, ignoring...");
 453                return;
 454            }
 455        } else if (query != null) {
 456            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received mam result with invalid from (" + original.getFrom() + ") or queryId (" + queryId + ")");
 457            return;
 458        } else if (original.fromServer(account)
 459                && original.getType() != im.conversations.android.xmpp.model.stanza.Message.Type.GROUPCHAT) {
 460            Pair<im.conversations.android.xmpp.model.stanza.Message, Long> f;
 461            f = getForwardedMessagePacket(original, Received.class);
 462            f = f == null ? getForwardedMessagePacket(original, Sent.class) : f;
 463            packet = f != null ? f.first : original;
 464            if (handleErrorMessage(account, packet)) {
 465                return;
 466            }
 467            timestamp = f != null ? f.second : null;
 468            isCarbon = f != null;
 469        } else {
 470            packet = original;
 471        }
 472
 473        if (timestamp == null) {
 474            timestamp = AbstractParser.parseTimestamp(original, AbstractParser.parseTimestamp(packet));
 475        }
 476        final Element mucUserElement = packet.findChild("x", Namespace.MUC_USER);
 477        final boolean isTypeGroupChat = packet.getType() == im.conversations.android.xmpp.model.stanza.Message.Type.GROUPCHAT;
 478        final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted");
 479
 480        Element replaceElement = packet.findChild("replace", "urn:xmpp:message-correct:0");
 481        Set<Message.FileParams> attachments = new LinkedHashSet<>();
 482        for (Element child : packet.getChildren()) {
 483            // SIMS first so they get preference in the set
 484            if (child.getName().equals("reference") && child.getNamespace().equals("urn:xmpp:reference:0")) {
 485                if (child.findChild("media-sharing", "urn:xmpp:sims:1") != null) {
 486                    attachments.add(new Message.FileParams(child));
 487                }
 488            }
 489        }
 490        for (Element child : packet.getChildren()) {
 491            if (child.getName().equals("x") && child.getNamespace().equals(Namespace.OOB)) {
 492                attachments.add(new Message.FileParams(child));
 493            }
 494        }
 495        String replacementId = replaceElement == null ? null : replaceElement.getAttribute("id");
 496        if (replacementId == null) {
 497            final Element fasten = packet.findChild("apply-to", "urn:xmpp:fasten:0");
 498            if (fasten != null) {
 499                replaceElement = fasten.findChild("retract", "urn:xmpp:message-retract:0");
 500                if (replaceElement == null) replaceElement = fasten.findChild("moderated", "urn:xmpp:message-moderate:0");
 501            }
 502            if (replaceElement == null) replaceElement = packet.findChild("retract", "urn:xmpp:message-retract:1");
 503            if (replaceElement == null) replaceElement = packet.findChild("moderate", "urn:xmpp:message-moderate:1");
 504            if (replaceElement != null) {
 505                var reason = replaceElement.findChildContent("reason", "urn:xmpp:message-moderate:0");
 506                if (reason == null) reason = replaceElement.findChildContent("reason", "urn:xmpp:message-moderate:1");
 507                replacementId = (fasten == null ? replaceElement : fasten).getAttribute("id");
 508                packet.setBody(reason == null ? "" : reason);
 509            }
 510        }
 511        LocalizedContent body = packet.getBody();
 512
 513        final var reactions = packet.getExtension(Reactions.class);
 514
 515        final Element axolotlEncrypted = packet.findChildEnsureSingle(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
 516        int status;
 517        final Jid counterpart;
 518        final Jid to = packet.getTo();
 519        final Jid from = packet.getFrom();
 520        final Element originId = packet.findChild("origin-id", Namespace.STANZA_IDS);
 521        final String remoteMsgId;
 522        if (originId != null && originId.getAttribute("id") != null) {
 523            remoteMsgId = originId.getAttribute("id");
 524        } else {
 525            remoteMsgId = packet.getId();
 526        }
 527        boolean notify = false;
 528
 529        Element html = packet.findChild("html", "http://jabber.org/protocol/xhtml-im");
 530        if (html != null && html.findChild("body", "http://www.w3.org/1999/xhtml") == null) {
 531            html = null;
 532        }
 533
 534        if (from == null || !InvalidJid.isValid(from) || !InvalidJid.isValid(to)) {
 535            Log.e(Config.LOGTAG, "encountered invalid message from='" + from + "' to='" + to + "'");
 536            return;
 537        }
 538        if (query != null && !query.muc() && isTypeGroupChat) {
 539            Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": received groupchat (" + from + ") message on regular MAM request. skipping");
 540            return;
 541        }
 542        final Jid mucTrueCounterPart;
 543        final OccupantId occupant;
 544        if (isTypeGroupChat) {
 545            final Conversation conversation =
 546                    mXmppConnectionService.find(account, from.asBareJid());
 547            final Jid mucTrueCounterPartByPresence;
 548            if (conversation != null) {
 549                final var mucOptions = conversation.getMucOptions();
 550                occupant = mucOptions.occupantId() ? packet.getExtension(OccupantId.class) : null;
 551                final var user =
 552                        occupant == null ? null : mucOptions.findUserByOccupantId(occupant.getId(), from);
 553                mucTrueCounterPartByPresence = user == null ? null : user.getRealJid();
 554            } else {
 555                occupant = null;
 556                mucTrueCounterPartByPresence = null;
 557            }
 558            mucTrueCounterPart =
 559                    getTrueCounterpart(
 560                            (query != null && query.safeToExtractTrueCounterpart())
 561                                    ? mucUserElement
 562                                    : null,
 563                            mucTrueCounterPartByPresence);
 564        } else {
 565            mucTrueCounterPart = null;
 566            occupant = null;
 567        }
 568        boolean isMucStatusMessage = InvalidJid.hasValidFrom(packet) && from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
 569        boolean selfAddressed;
 570        if (packet.fromAccount(account)) {
 571            status = Message.STATUS_SEND;
 572            selfAddressed = to == null || account.getJid().asBareJid().equals(to.asBareJid());
 573            if (selfAddressed) {
 574                counterpart = from;
 575            } else {
 576                counterpart = to != null ? to : account.getJid();
 577            }
 578        } else {
 579            status = Message.STATUS_RECEIVED;
 580            counterpart = from;
 581            selfAddressed = false;
 582        }
 583
 584        final Invite invite = extractInvite(packet);
 585        if (invite != null) {
 586            if (invite.jid.asBareJid().equals(account.getJid().asBareJid())) {
 587                Log.d(Config.LOGTAG,account.getJid().asBareJid()+": ignore invite to "+invite.jid+" because it matches account");
 588            } else if (isTypeGroupChat) {
 589                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring invite to " + invite.jid + " because it was received as group chat");
 590            } else if (invite.direct && (mucUserElement != null || invite.inviter == null || mXmppConnectionService.isMuc(account, invite.inviter))) {
 591                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring direct invite to " + invite.jid + " because it was received in MUC");
 592            } else {
 593                invite.execute(account);
 594                return;
 595            }
 596        }
 597
 598        final boolean conversationIsProbablyMuc = isTypeGroupChat || mucUserElement != null || account.getXmppConnection().getMucServersWithholdAccount().contains(counterpart.getDomain().toEscapedString());
 599        final Element webxdc = packet.findChild("x", "urn:xmpp:webxdc:0");
 600        final Element thread = packet.findChild("thread");
 601        if (webxdc != null && thread != null) {
 602            final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), conversationIsProbablyMuc, false, query, false);
 603            Jid webxdcSender = counterpart.asBareJid();
 604            if (conversation.getMode() == Conversation.MODE_MULTI) {
 605                if(conversation.getMucOptions().nonanonymous()) {
 606                    webxdcSender = conversation.getMucOptions().getTrueCounterpart(counterpart);
 607                } else {
 608                    webxdcSender = counterpart;
 609                }
 610            }
 611            final var document = webxdc.findChildContent("document", "urn:xmpp:webxdc:0");
 612            final var summary = webxdc.findChildContent("summary", "urn:xmpp:webxdc:0");
 613            final var payload = webxdc.findChildContent("json", "urn:xmpp:json:0");
 614            if (document != null || summary != null || payload != null) {
 615                mXmppConnectionService.insertWebxdcUpdate(new WebxdcUpdate(
 616                    conversation,
 617                    remoteMsgId,
 618                    counterpart,
 619                    thread,
 620                    body == null ? null : body.content,
 621                    document,
 622                    summary,
 623                    payload
 624                ));
 625            }
 626
 627            final var realtime = webxdc.findChildContent("data", "urn:xmpp:webxdc:0");
 628            if (realtime != null) conversation.webxdcRealtimeData(thread, realtime);
 629
 630            mXmppConnectionService.updateConversationUi();
 631        }
 632
 633        // Basic visibility for voice requests
 634        if (body == null && html == null && pgpEncrypted == null && axolotlEncrypted == null && !isMucStatusMessage) {
 635            final Element formEl = packet.findChild("x", "jabber:x:data");
 636            if (formEl != null) {
 637                final Data form = Data.parse(formEl);
 638                final String role = form.getValue("muc#role");
 639                final String nick = form.getValue("muc#roomnick");
 640                if ("http://jabber.org/protocol/muc#request".equals(form.getFormType()) && "participant".equals(role)) {
 641                    body = new LocalizedContent("" + nick + " is requesting to speak", "en", 1);
 642                }
 643            }
 644        }
 645
 646        if (reactions == null && (body != null || pgpEncrypted != null || (axolotlEncrypted != null && axolotlEncrypted.hasChild("payload")) || !attachments.isEmpty() || html != null || (packet.hasChild("subject") && packet.hasChild("thread"))) && !isMucStatusMessage) {
 647            final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), conversationIsProbablyMuc, false, query, false);
 648            final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
 649
 650            if (serverMsgId == null) {
 651                serverMsgId = extractStanzaId(packet, isTypeGroupChat, conversation);
 652            }
 653
 654
 655            if (selfAddressed) {
 656                // don’t store serverMsgId on reflections for edits
 657                final var reflectedServerMsgId =
 658                        Strings.isNullOrEmpty(replacementId) ? serverMsgId : null;
 659                if (mXmppConnectionService.markMessage(
 660                        conversation,
 661                        remoteMsgId,
 662                        Message.STATUS_SEND_RECEIVED,
 663                        reflectedServerMsgId)) {
 664                    return;
 665                }
 666                status = Message.STATUS_RECEIVED;
 667                if (remoteMsgId != null && conversation.findMessageWithRemoteId(remoteMsgId, counterpart) != null) {
 668                    return;
 669                }
 670            }
 671
 672            if (isTypeGroupChat) {
 673                if (conversation.getMucOptions().isSelf(counterpart)) {
 674                    status = Message.STATUS_SEND_RECEIVED;
 675                    isCarbon = true; //not really carbon but received from another resource
 676                    // don’t store serverMsgId on reflections for edits
 677                    final var reflectedServerMsgId =
 678                            Strings.isNullOrEmpty(replacementId) ? serverMsgId : null;
 679                    if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status, reflectedServerMsgId, body, html, packet.findChildContent("subject"), packet.findChild("thread"), attachments)) {
 680                        return;
 681                    } else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
 682                        if (body != null) {
 683                            Message message = conversation.findSentMessageWithBody(body.content);
 684                            if (message != null) {
 685                                mXmppConnectionService.markMessage(message, status);
 686                                return;
 687                            }
 688                        }
 689                    }
 690                } else {
 691                    status = Message.STATUS_RECEIVED;
 692                }
 693            }
 694            final Message message;
 695            if (pgpEncrypted != null && Config.supportOpenPgp()) {
 696                message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status);
 697            } else if (axolotlEncrypted != null && Config.supportOmemo()) {
 698                Jid origin;
 699                Set<Jid> fallbacksBySourceId = Collections.emptySet();
 700                if (conversationMultiMode) {
 701                    final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
 702                    origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
 703                    if (origin == null) {
 704                        try {
 705                            fallbacksBySourceId = account.getAxolotlService().findCounterpartsBySourceId(XmppAxolotlMessage.parseSourceId(axolotlEncrypted));
 706                        } catch (IllegalArgumentException e) {
 707                            //ignoring
 708                        }
 709                    }
 710                    if (origin == null && fallbacksBySourceId.size() == 0) {
 711                        Log.d(Config.LOGTAG, "axolotl message in anonymous conference received and no possible fallbacks");
 712                        return;
 713                    }
 714                } else {
 715                    fallbacksBySourceId = Collections.emptySet();
 716                    origin = from;
 717                }
 718
 719                final boolean liveMessage = query == null && !isTypeGroupChat && mucUserElement == null;
 720                final boolean checkedForDuplicates = liveMessage || (serverMsgId != null && remoteMsgId != null && !conversation.possibleDuplicate(serverMsgId, remoteMsgId));
 721
 722                if (origin != null) {
 723                    message = parseAxolotlChat(axolotlEncrypted, origin, conversation, status, checkedForDuplicates, query != null);
 724                } else {
 725                    Message trial = null;
 726                    for (Jid fallback : fallbacksBySourceId) {
 727                        trial = parseAxolotlChat(axolotlEncrypted, fallback, conversation, status, checkedForDuplicates && fallbacksBySourceId.size() == 1, query != null);
 728                        if (trial != null) {
 729                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": decoded muc message using fallback");
 730                            origin = fallback;
 731                            break;
 732                        }
 733                    }
 734                    message = trial;
 735                }
 736                if (message == null) {
 737                    if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
 738                        mXmppConnectionService.updateConversationUi();
 739                    }
 740                    if (query != null && status == Message.STATUS_SEND && remoteMsgId != null) {
 741                        Message previouslySent = conversation.findSentMessageWithUuid(remoteMsgId);
 742                        if (previouslySent != null && previouslySent.getServerMsgId() == null && serverMsgId != null) {
 743                            previouslySent.setServerMsgId(serverMsgId);
 744                            mXmppConnectionService.databaseBackend.updateMessage(previouslySent, false);
 745                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": encountered previously sent OMEMO message without serverId. updating...");
 746                        }
 747                    }
 748                    return;
 749                }
 750                if (conversationMultiMode) {
 751                    message.setTrueCounterpart(origin);
 752                }
 753            } else if (body == null && !attachments.isEmpty()) {
 754                message = new Message(conversation, "", Message.ENCRYPTION_NONE, status);
 755            } else {
 756                message = new Message(conversation, body == null ? null : body.content, Message.ENCRYPTION_NONE, status);
 757                if (body != null && body.count > 1) {
 758                    message.setBodyLanguage(body.language);
 759                }
 760            }
 761
 762            Element addresses = packet.findChild("addresses", "http://jabber.org/protocol/address");
 763            if (status == Message.STATUS_RECEIVED && addresses != null) {
 764                for (Element address : addresses.getChildren()) {
 765                    if (!address.getName().equals("address") || !address.getNamespace().equals("http://jabber.org/protocol/address")) continue;
 766
 767                    if (address.getAttribute("type").equals("ofrom") && address.getAttribute("jid") != null) {
 768                        Jid ofrom = address.getAttributeAsJid("jid");
 769                        if (InvalidJid.isValid(ofrom) && ofrom.getDomain().equals(counterpart.getDomain()) &&
 770                            conversation.getAccount().getRoster().getContact(counterpart.getDomain()).getPresences().anySupport("http://jabber.org/protocol/address")) {
 771
 772                            message.setTrueCounterpart(ofrom);
 773                        }
 774                    }
 775                }
 776            }
 777
 778            if (html != null) message.addPayload(html);
 779            message.setSubject(packet.findChildContent("subject"));
 780            message.setCounterpart(counterpart);
 781            message.setRemoteMsgId(remoteMsgId);
 782            message.setServerMsgId(serverMsgId);
 783            message.setCarbon(isCarbon);
 784            message.setTime(timestamp);
 785            if (!attachments.isEmpty()) {
 786                message.setFileParams(attachments.iterator().next());
 787                if (CryptoHelper.isPgpEncryptedUrl(message.getFileParams().url)) {
 788                    message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 789                }
 790            }
 791            message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
 792            for (Element el : packet.getChildren()) {
 793                if ((el.getName().equals("query") && el.getNamespace().equals("http://jabber.org/protocol/disco#items") && el.getAttribute("node").equals("http://jabber.org/protocol/commands")) ||
 794                    (el.getName().equals("fallback") && el.getNamespace().equals("urn:xmpp:fallback:0"))) {
 795                    message.addPayload(el);
 796                }
 797                if (el.getName().equals("thread") && (el.getNamespace() == null || el.getNamespace().equals("jabber:client"))) {
 798                    el.setAttribute("xmlns", "jabber:client");
 799                    message.addPayload(el);
 800                }
 801                if (el.getName().equals("reply") && el.getNamespace() != null && el.getNamespace().equals("urn:xmpp:reply:0")) {
 802                    message.addPayload(el);
 803                    if (el.getAttribute("id") != null) {
 804                        for (final var parent : mXmppConnectionService.getMessageFuzzyIds(conversation, List.of(el.getAttribute("id"))).entrySet()) {
 805                            message.setInReplyTo(parent.getValue());
 806                        }
 807                    }
 808                }
 809                if (el.getName().equals("attention") && el.getNamespace() != null && el.getNamespace().equals("urn:xmpp:attention:0")) {
 810                    message.addPayload(el);
 811                }
 812                if (el.getName().equals("Description") && el.getNamespace() != null && el.getNamespace().equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#")) {
 813                    message.addPayload(el);
 814                }
 815            }
 816            if (conversationMultiMode) {
 817                final var mucOptions = conversation.getMucOptions();
 818                if (occupant != null) {
 819                    message.setOccupantId(occupant.getId());
 820                }
 821                message.setMucUser(mucOptions.findUserByFullJid(counterpart));
 822                final Jid fallback = mucOptions.getTrueCounterpart(counterpart);
 823                Jid trueCounterpart;
 824                if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
 825                    trueCounterpart = message.getTrueCounterpart();
 826                } else if (query != null && query.safeToExtractTrueCounterpart()) {
 827                    trueCounterpart = getTrueCounterpart(mucUserElement, fallback);
 828                } else {
 829                    trueCounterpart = fallback;
 830                }
 831                if (trueCounterpart != null && isTypeGroupChat) {
 832                    if (trueCounterpart.asBareJid().equals(account.getJid().asBareJid())) {
 833                        status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND;
 834                    } else {
 835                        status = Message.STATUS_RECEIVED;
 836                        message.setCarbon(false);
 837                    }
 838                }
 839                message.setStatus(status);
 840                message.setTrueCounterpart(trueCounterpart);
 841                if (!isTypeGroupChat) {
 842                    message.setType(Message.TYPE_PRIVATE);
 843                }
 844            } else {
 845                updateLastseen(account, from);
 846            }
 847
 848            if (replacementId != null && mXmppConnectionService.allowMessageCorrection()) {
 849                final Message replacedMessage = conversation.findMessageWithRemoteIdAndCounterpart(replacementId, counterpart);
 850                if (replacedMessage != null) {
 851                    final boolean fingerprintsMatch = replacedMessage.getFingerprint() == null
 852                            || replacedMessage.getFingerprint().equals(message.getFingerprint());
 853                    final boolean trueCountersMatch = replacedMessage.getTrueCounterpart() != null
 854                            && message.getTrueCounterpart() != null
 855                            && replacedMessage.getTrueCounterpart().asBareJid().equals(message.getTrueCounterpart().asBareJid());
 856                    final boolean occupantIdMatch =
 857                            replacedMessage.getOccupantId() != null
 858                                    && replacedMessage
 859                                            .getOccupantId()
 860                                            .equals(message.getOccupantId());
 861                    final boolean mucUserMatches = query == null && replacedMessage.sameMucUser(message); //can not be checked when using mam
 862                    final boolean duplicate = conversation.hasDuplicateMessage(message);
 863                    if (fingerprintsMatch && (trueCountersMatch || occupantIdMatch || !conversationMultiMode || mucUserMatches || counterpart.isBareJid()) && !duplicate) {
 864                        synchronized (replacedMessage) {
 865                            final String uuid = replacedMessage.getUuid();
 866                            replacedMessage.setUuid(UUID.randomUUID().toString());
 867                            replacedMessage.setBody(message.getBody());
 868                            replacedMessage.setSubject(message.getSubject());
 869                            replacedMessage.setThread(message.getThread());
 870                            replacedMessage.putEdited(replacedMessage.getRemoteMsgId(), replacedMessage.getServerMsgId());
 871                            replacedMessage.setRemoteMsgId(remoteMsgId);
 872                            if (replaceElement != null && !replaceElement.getName().equals("replace")) {
 873                                mXmppConnectionService.getFileBackend().deleteFile(replacedMessage);
 874                                mXmppConnectionService.evictPreview(message.getUuid());
 875                                List<Element> thumbs = replacedMessage.getFileParams() != null ? replacedMessage.getFileParams().getThumbnails() : null;
 876                                if (thumbs != null && !thumbs.isEmpty()) {
 877                                    for (Element thumb : thumbs) {
 878                                        Uri uri = Uri.parse(thumb.getAttribute("uri"));
 879                                        if (uri.getScheme().equals("cid")) {
 880                                            Cid cid = BobTransfer.cid(uri);
 881                                            if (cid == null) continue;
 882                                            DownloadableFile f = mXmppConnectionService.getFileForCid(cid);
 883                                            if (f != null) {
 884                                                mXmppConnectionService.evictPreview(f);
 885                                                f.delete();
 886                                            }
 887                                        }
 888                                    }
 889                                }
 890                                replacedMessage.clearPayloads();
 891                                replacedMessage.setFileParams(null);
 892                                replacedMessage.addPayload(replaceElement);
 893                            } else {
 894                                replacedMessage.clearPayloads();
 895                                for (final var p : message.getPayloads()) {
 896                                    replacedMessage.addPayload(p);
 897                                }
 898                            }
 899                            replacedMessage.setInReplyTo(message.getInReplyTo());
 900
 901                            // we store the IDs of the replacing message. This is essentially unused
 902                            // today (only the fact that there are _some_ edits causes the edit icon
 903                            // to appear)
 904                            replacedMessage.putEdited(
 905                                    message.getRemoteMsgId(), message.getServerMsgId());
 906
 907                            // we used to call
 908                            // `replacedMessage.setServerMsgId(message.getServerMsgId());` so during
 909                            // catchup we could start from the edit; not the original message
 910                            // however this caused problems for things like reactions that refer to
 911                            // the serverMsgId
 912
 913                            replacedMessage.setEncryption(message.getEncryption());
 914                            if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
 915                                replacedMessage.markUnread();
 916                            }
 917                            extractChatState(
 918                                    mXmppConnectionService.find(account, counterpart.asBareJid()),
 919                                    isTypeGroupChat,
 920                                    packet);
 921                            mXmppConnectionService.updateMessage(replacedMessage, uuid);
 922                            if (mXmppConnectionService.confirmMessages()
 923                                    && replacedMessage.getStatus() == Message.STATUS_RECEIVED
 924                                    && (replacedMessage.trusted() || replacedMessage.isPrivateMessage()) //TODO do we really want to send receipts for all PMs?
 925                                    && remoteMsgId != null
 926                                    && !selfAddressed
 927                                    && !isTypeGroupChat) {
 928                                processMessageReceipts(account, packet, remoteMsgId, query);
 929                            }
 930                            if (replacedMessage.getEncryption() == Message.ENCRYPTION_PGP) {
 931                                conversation.getAccount().getPgpDecryptionService().discard(replacedMessage);
 932                                conversation.getAccount().getPgpDecryptionService().decrypt(replacedMessage, false);
 933                            }
 934                        }
 935                        mXmppConnectionService.getNotificationService().updateNotification();
 936                        return;
 937                    } else {
 938                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received message correction but verification didn't check out");
 939                    }
 940                } else if (message.getBody() == null || message.getBody().equals("") || message.getBody().equals(" ")) {
 941                    return;
 942                }
 943                if (replaceElement != null && !replaceElement.getName().equals("replace")) return;
 944            }
 945
 946            boolean checkForDuplicates = (isTypeGroupChat && packet.hasChild("delay", "urn:xmpp:delay"))
 947                    || message.isPrivateMessage()
 948                    || message.getServerMsgId() != null
 949                    || (query == null && mXmppConnectionService.getMessageArchiveService().isCatchupInProgress(conversation));
 950            if (checkForDuplicates) {
 951                final Message duplicate = conversation.findDuplicateMessage(message);
 952                if (duplicate != null) {
 953                    final boolean serverMsgIdUpdated;
 954                    if (duplicate.getStatus() != Message.STATUS_RECEIVED
 955                            && duplicate.getUuid().equals(message.getRemoteMsgId())
 956                            && duplicate.getServerMsgId() == null
 957                            && message.getServerMsgId() != null) {
 958                        duplicate.setServerMsgId(message.getServerMsgId());
 959                        if (mXmppConnectionService.databaseBackend.updateMessage(duplicate, false)) {
 960                            serverMsgIdUpdated = true;
 961                        } else {
 962                            serverMsgIdUpdated = false;
 963                            Log.e(Config.LOGTAG, "failed to update message");
 964                        }
 965                    } else {
 966                        serverMsgIdUpdated = false;
 967                    }
 968                    Log.d(Config.LOGTAG, "skipping duplicate message with " + message.getCounterpart() + ". serverMsgIdUpdated=" + serverMsgIdUpdated);
 969                    return;
 970                }
 971            }
 972
 973            if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
 974                conversation.prepend(query.getActualInThisQuery(), message);
 975            } else {
 976                conversation.add(message);
 977            }
 978            if (query != null) {
 979                query.incrementActualMessageCount();
 980            }
 981
 982            if (query == null || query.isCatchup()) { //either no mam or catchup
 983                if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
 984                    mXmppConnectionService.markRead(conversation);
 985                    if (query == null) {
 986                        activateGracePeriod(account);
 987                    }
 988                } else {
 989                    message.markUnread();
 990                    notify = true;
 991                }
 992            }
 993
 994            if (message.getEncryption() == Message.ENCRYPTION_PGP) {
 995                notify = conversation.getAccount().getPgpDecryptionService().decrypt(message, notify);
 996            } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE || message.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
 997                notify = false;
 998            }
 999
1000            if (query == null) {
1001                extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
1002                mXmppConnectionService.updateConversationUi();
1003            }
1004
1005            if (mXmppConnectionService.confirmMessages()
1006                    && message.getStatus() == Message.STATUS_RECEIVED
1007                    && (message.trusted() || message.isPrivateMessage())
1008                    && remoteMsgId != null
1009                    && !selfAddressed
1010                    && !isTypeGroupChat) {
1011                processMessageReceipts(account, packet, remoteMsgId, query);
1012            }
1013
1014            if (message.getFileParams() != null) {
1015                for (Cid cid : message.getFileParams().getCids()) {
1016                    File f = mXmppConnectionService.getFileForCid(cid);
1017                    if (f != null && f.canRead()) {
1018                        message.setRelativeFilePath(f.getAbsolutePath());
1019                        mXmppConnectionService.getFileBackend().updateFileParams(message, null, false);
1020                        break;
1021                    }
1022                }
1023            }
1024
1025            mXmppConnectionService.databaseBackend.createMessage(message);
1026
1027            final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
1028            if (message.getRelativeFilePath() == null && message.trusted() && message.treatAsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
1029                if (message.getOob() != null && "cid".equalsIgnoreCase(message.getOob().getScheme())) {
1030                    try {
1031                        BobTransfer transfer = new BobTransfer.ForMessage(message, mXmppConnectionService);
1032                        message.setTransferable(transfer);
1033                        transfer.start();
1034                    } catch (URISyntaxException e) {
1035                        Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
1036                    }
1037                } else {
1038                    manager.createNewDownloadConnection(message);
1039                }
1040            } else if (notify) {
1041                if (query != null && query.isCatchup()) {
1042                    mXmppConnectionService.getNotificationService().pushFromBacklog(message);
1043                } else {
1044                    mXmppConnectionService.getNotificationService().push(message);
1045                }
1046            }
1047        } else if (!packet.hasChild("body")) { //no body
1048
1049            final Conversation conversation = mXmppConnectionService.find(account, from.asBareJid());
1050            if (axolotlEncrypted != null) {
1051                Jid origin;
1052                if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
1053                    final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
1054                    origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
1055                    if (origin == null) {
1056                        Log.d(Config.LOGTAG, "omemo key transport message in anonymous conference received");
1057                        return;
1058                    }
1059                } else if (isTypeGroupChat) {
1060                    return;
1061                } else {
1062                    origin = from;
1063                }
1064                try {
1065                    final XmppAxolotlMessage xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlEncrypted, origin.asBareJid());
1066                    account.getAxolotlService().processReceivingKeyTransportMessage(xmppAxolotlMessage, query != null);
1067                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": omemo key transport message received from " + origin);
1068                } catch (Exception e) {
1069                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": invalid omemo key transport message received " + e.getMessage());
1070                    return;
1071                }
1072            }
1073
1074            if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
1075                mXmppConnectionService.updateConversationUi();
1076            }
1077
1078            if (isTypeGroupChat) {
1079                if (packet.hasChild("subject") && !packet.hasChild("thread")) { // We already know it has no body per above
1080                    if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
1081                        conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
1082                        final LocalizedContent subject = packet.findInternationalizedChildContentInDefaultNamespace("subject");
1083                        if (subject != null && conversation.getMucOptions().setSubject(subject.content)) {
1084                            mXmppConnectionService.updateConversation(conversation);
1085                        }
1086                        mXmppConnectionService.updateConversationUi();
1087                        return;
1088                    }
1089                }
1090            }
1091            if (conversation != null && mucUserElement != null && InvalidJid.hasValidFrom(packet) && from.isBareJid()) {
1092                for (Element child : mucUserElement.getChildren()) {
1093                    if ("status".equals(child.getName())) {
1094                        try {
1095                            int code = Integer.parseInt(child.getAttribute("code"));
1096                            if ((code >= 170 && code <= 174) || (code >= 102 && code <= 104)) {
1097                                mXmppConnectionService.fetchConferenceConfiguration(conversation);
1098                                break;
1099                            }
1100                        } catch (Exception e) {
1101                            //ignored
1102                        }
1103                    } else if ("item".equals(child.getName())) {
1104                        MucOptions.User user = AbstractParser.parseItem(conversation, child);
1105                        Log.d(Config.LOGTAG, account.getJid() + ": changing affiliation for "
1106                                + user.getRealJid() + " to " + user.getAffiliation() + " in "
1107                                + conversation.getJid().asBareJid());
1108                        if (!user.realJidMatchesAccount()) {
1109                            boolean isNew = conversation.getMucOptions().updateUser(user);
1110                            mXmppConnectionService.getAvatarService().clear(conversation);
1111                            mXmppConnectionService.updateMucRosterUi();
1112                            mXmppConnectionService.updateConversationUi();
1113                            Contact contact = user.getContact();
1114                            if (!user.getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
1115                                Jid jid = user.getRealJid();
1116                                List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
1117                                if (cryptoTargets.remove(user.getRealJid())) {
1118                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
1119                                    conversation.setAcceptedCryptoTargets(cryptoTargets);
1120                                    mXmppConnectionService.updateConversation(conversation);
1121                                }
1122                            } else if (isNew
1123                                    && user.getRealJid() != null
1124                                    && conversation.getMucOptions().isPrivateAndNonAnonymous()
1125                                    && (contact == null || !contact.mutualPresenceSubscription())
1126                                    && account.getAxolotlService().hasEmptyDeviceList(user.getRealJid())) {
1127                                account.getAxolotlService().fetchDeviceIds(user.getRealJid());
1128                            }
1129                        }
1130                    }
1131                }
1132            }
1133            if (!isTypeGroupChat) {
1134                for (Element child : packet.getChildren()) {
1135                    if (Namespace.JINGLE_MESSAGE.equals(child.getNamespace()) && JINGLE_MESSAGE_ELEMENT_NAMES.contains(child.getName())) {
1136                        final String action = child.getName();
1137                        final String sessionId = child.getAttribute("id");
1138                        if (sessionId == null) {
1139                            break;
1140                        }
1141                        if (query == null && offlineMessagesRetrieved) {
1142                            if (serverMsgId == null) {
1143                                serverMsgId = extractStanzaId(account, packet);
1144                            }
1145                            mXmppConnectionService
1146                                    .getJingleConnectionManager()
1147                                    .deliverMessage(
1148                                            account,
1149                                            packet.getTo(),
1150                                            packet.getFrom(),
1151                                            child,
1152                                            remoteMsgId,
1153                                            serverMsgId,
1154                                            timestamp);
1155                            final Contact contact = account.getRoster().getContact(from);
1156                            // this is the same condition that is found in JingleRtpConnection for
1157                            // the 'ringing' response. Responding with delivery receipts predates
1158                            // the 'ringing' spec'd
1159                            final boolean sendReceipts =
1160                                    contact.showInContactList()
1161                                            || Config.JINGLE_MESSAGE_INIT_STRICT_OFFLINE_CHECK;
1162                            if (remoteMsgId != null && !contact.isSelf() && sendReceipts) {
1163                                processMessageReceipts(account, packet, remoteMsgId, null);
1164                            }
1165                        } else if ((query != null && query.isCatchup()) || !offlineMessagesRetrieved) {
1166                            if ("propose".equals(action)) {
1167                                final Element description = child.findChild("description");
1168                                final String namespace =
1169                                        description == null ? null : description.getNamespace();
1170                                if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
1171                                    final Conversation c =
1172                                            mXmppConnectionService.findOrCreateConversation(
1173                                                    account, counterpart.asBareJid(), false, false);
1174                                    final Message preExistingMessage =
1175                                            c.findRtpSession(sessionId, status);
1176                                    if (preExistingMessage != null) {
1177                                        preExistingMessage.setServerMsgId(serverMsgId);
1178                                        mXmppConnectionService.updateMessage(preExistingMessage);
1179                                        break;
1180                                    }
1181                                    final Message message =
1182                                            new Message(
1183                                                    c, status, Message.TYPE_RTP_SESSION, sessionId);
1184                                    message.setServerMsgId(serverMsgId);
1185                                    message.setTime(timestamp);
1186                                    message.setBody(new RtpSessionStatus(false, 0).toString());
1187                                    message.markUnread();
1188                                    c.add(message);
1189                                    mXmppConnectionService.getNotificationService().possiblyMissedCall(c.getUuid() + sessionId, message);
1190                                    query.incrementActualMessageCount();
1191                                    mXmppConnectionService.databaseBackend.createMessage(message);
1192                                }
1193                            } else if ("proceed".equals(action)) {
1194                                // status needs to be flipped to find the original propose
1195                                final Conversation c =
1196                                        mXmppConnectionService.findOrCreateConversation(
1197                                                account, counterpart.asBareJid(), false, false);
1198                                final int s =
1199                                        packet.fromAccount(account)
1200                                                ? Message.STATUS_RECEIVED
1201                                                : Message.STATUS_SEND;
1202                                final Message message = c.findRtpSession(sessionId, s);
1203                                if (message != null) {
1204                                    message.setBody(new RtpSessionStatus(true, 0).toString());
1205                                    if (serverMsgId != null) {
1206                                        message.setServerMsgId(serverMsgId);
1207                                    }
1208                                    message.setTime(timestamp);
1209                                    message.markRead();
1210                                    mXmppConnectionService.getNotificationService().possiblyMissedCall(c.getUuid() + sessionId, message);
1211                                    query.incrementActualMessageCount();
1212                                    mXmppConnectionService.updateMessage(message, true);
1213                                } else {
1214                                    Log.d(
1215                                            Config.LOGTAG,
1216                                            "unable to find original rtp session message for received propose");
1217                                }
1218
1219                            } else if ("finish".equals(action)) {
1220                                Log.d(
1221                                        Config.LOGTAG,
1222                                        "received JMI 'finish' during MAM catch-up. Can be used to update success/failure and duration");
1223                            }
1224                        } else {
1225                            //MAM reloads (non catchups
1226                            if ("propose".equals(action)) {
1227                                final Element description = child.findChild("description");
1228                                final String namespace = description == null ? null : description.getNamespace();
1229                                if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
1230                                    final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
1231                                    final Message preExistingMessage = c.findRtpSession(sessionId, status);
1232                                    if (preExistingMessage != null) {
1233                                        preExistingMessage.setServerMsgId(serverMsgId);
1234                                        mXmppConnectionService.updateMessage(preExistingMessage);
1235                                        break;
1236                                    }
1237                                    final Message message = new Message(
1238                                            c,
1239                                            status,
1240                                            Message.TYPE_RTP_SESSION,
1241                                            sessionId
1242                                    );
1243                                    message.setServerMsgId(serverMsgId);
1244                                    message.setTime(timestamp);
1245                                    message.setBody(new RtpSessionStatus(true, 0).toString());
1246                                    if (query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
1247                                        c.prepend(query.getActualInThisQuery(), message);
1248                                    } else {
1249                                        c.add(message);
1250                                    }
1251                                    query.incrementActualMessageCount();
1252                                    mXmppConnectionService.databaseBackend.createMessage(message);
1253                                }
1254                            }
1255                        }
1256                        break;
1257                    }
1258                }
1259            }
1260        }
1261
1262        Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
1263        if (received == null) {
1264            received = packet.findChild("received", "urn:xmpp:receipts");
1265        }
1266        if (received != null) {
1267            String id = received.getAttribute("id");
1268            if (packet.fromAccount(account)) {
1269                if (query != null && id != null && packet.getTo() != null) {
1270                    query.removePendingReceiptRequest(new ReceiptRequest(packet.getTo(), id));
1271                }
1272            } else if (id != null) {
1273                if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
1274                    final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
1275                    mXmppConnectionService.getJingleConnectionManager()
1276                            .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.DISCOVERED);
1277                } else {
1278                    mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_RECEIVED);
1279                }
1280            }
1281        }
1282        final Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
1283        if (displayed != null) {
1284            final String id = displayed.getAttribute("id");
1285            // TODO we don’t even use 'sender' any more. Remove this!
1286            final Jid sender = InvalidJid.getNullForInvalid(displayed.getAttributeAsJid("sender"));
1287            if (packet.fromAccount(account) && !selfAddressed) {
1288                final Conversation c =
1289                        mXmppConnectionService.find(account, counterpart.asBareJid());
1290                final Message message =
1291                        (c == null || id == null) ? null : c.findReceivedWithRemoteId(id);
1292                if (message != null && (query == null || query.isCatchup())) {
1293                    mXmppConnectionService.markReadUpTo(c, message);
1294                }
1295                if (query == null) {
1296                    activateGracePeriod(account);
1297                }
1298            } else if (isTypeGroupChat) {
1299                final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
1300                final Message message;
1301                if (conversation != null && id != null) {
1302                    if (sender != null) {
1303                        message = conversation.findMessageWithRemoteId(id, sender);
1304                    } else {
1305                        message = conversation.findMessageWithServerMsgId(id);
1306                    }
1307                } else {
1308                    message = null;
1309                }
1310                if (message != null) {
1311                    // TODO use occupantId to extract true counterpart from presence
1312                    final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
1313                    // TODO try to externalize mucTrueCounterpart
1314                    final Jid trueJid = getTrueCounterpart((query != null && query.safeToExtractTrueCounterpart()) ? mucUserElement : null, fallback);
1315                    final boolean trueJidMatchesAccount = account.getJid().asBareJid().equals(trueJid == null ? null : trueJid.asBareJid());
1316                    if (trueJidMatchesAccount || conversation.getMucOptions().isSelf(counterpart)) {
1317                        if (!message.isRead() && (query == null || query.isCatchup())) { //checking if message is unread fixes race conditions with reflections
1318                            mXmppConnectionService.markReadUpTo(conversation, message);
1319                        }
1320                    } else if (!counterpart.isBareJid() && trueJid != null) {
1321                        final ReadByMarker readByMarker = ReadByMarker.from(counterpart, trueJid);
1322                        if (message.addReadByMarker(readByMarker)) {
1323                            final var mucOptions = conversation.getMucOptions();
1324                            final var everyone = ImmutableSet.copyOf(mucOptions.getMembers(false));
1325                            final var readyBy = message.getReadyByTrue();
1326                            final var mStatus = message.getStatus();
1327                            if (mucOptions.isPrivateAndNonAnonymous()
1328                                    && (mStatus == Message.STATUS_SEND_RECEIVED
1329                                            || mStatus == Message.STATUS_SEND)
1330                                    && readyBy.containsAll(everyone)) {
1331                                message.setStatus(Message.STATUS_SEND_DISPLAYED);
1332                            }
1333                            mXmppConnectionService.updateMessage(message, false);
1334                        }
1335                    }
1336                }
1337            } else {
1338                final Message displayedMessage = mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_DISPLAYED);
1339                Message message = displayedMessage == null ? null : displayedMessage.prev();
1340                while (message != null
1341                        && message.getStatus() == Message.STATUS_SEND_RECEIVED
1342                        && message.getTimeSent() < displayedMessage.getTimeSent()) {
1343                    mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
1344                    message = message.prev();
1345                }
1346                if (displayedMessage != null && selfAddressed) {
1347                    dismissNotification(account, counterpart, query, id);
1348                }
1349            }
1350        }
1351
1352        if (reactions != null) {
1353            final String reactingTo = reactions.getId();
1354            final Conversation conversation =
1355                    mXmppConnectionService.find(account, counterpart.asBareJid());
1356
1357            if (conversation != null && reactingTo != null) {
1358                if (isTypeGroupChat && conversation.getMode() == Conversational.MODE_MULTI) {
1359                    final var mucOptions = conversation.getMucOptions();
1360                    final var occupantId = occupant == null ? null : occupant.getId();
1361                    if (occupantId != null) {
1362                        final boolean isReceived = !mucOptions.isSelf(occupantId);
1363                        final Message message;
1364                        final var inMemoryMessage =
1365                                conversation.findMessageWithServerMsgId(reactingTo);
1366                        if (inMemoryMessage != null) {
1367                            message = inMemoryMessage;
1368                        } else {
1369                            message =
1370                                    mXmppConnectionService.databaseBackend
1371                                            .getMessageWithServerMsgId(conversation, reactingTo);
1372                        }
1373                        if (message != null) {
1374                            final var newReactions = new HashSet<>(reactions.getReactions());
1375                            newReactions.removeAll(message.getReactions().stream().filter(r -> occupantId.equals(r.occupantId)).map(r -> r.reaction).collect(Collectors.toList()));
1376                            final var combinedReactions =
1377                                    Reaction.withOccupantId(
1378                                            message.getReactions(),
1379                                            reactions.getReactions(),
1380                                            isReceived,
1381                                            counterpart,
1382                                            null,
1383                                            occupantId,
1384                                            message.getRemoteMsgId());
1385                            message.setReactions(combinedReactions);
1386                            mXmppConnectionService.updateMessage(message, false);
1387                            if (isReceived) mXmppConnectionService.getNotificationService().push(message, counterpart, occupantId, newReactions);
1388                        } else {
1389                            Log.d(Config.LOGTAG, "message with id " + reactingTo + " not found");
1390                        }
1391                    } else {
1392                        Log.d(
1393                                Config.LOGTAG,
1394                                "received reaction in channel w/o occupant ids. ignoring");
1395                    }
1396                } else if (conversation.getMode() == Conversational.MODE_SINGLE) {
1397                    final Message message;
1398                    final var inMemoryMessage =
1399                            conversation.findMessageWithUuidOrRemoteId(reactingTo);
1400                    if (inMemoryMessage != null) {
1401                        message = inMemoryMessage;
1402                    } else {
1403                        message =
1404                                mXmppConnectionService.databaseBackend.getMessageWithUuidOrRemoteId(
1405                                        conversation, reactingTo);
1406                    }
1407                    final boolean isReceived;
1408                    final Jid reactionFrom;
1409                    if (packet.fromAccount(account)) {
1410                        isReceived = false;
1411                        reactionFrom = account.getJid().asBareJid();
1412                    } else {
1413                        isReceived = true;
1414                        reactionFrom = counterpart;
1415                    }
1416                    packet.fromAccount(account);
1417                    if (message != null) {
1418                        final var newReactions = new HashSet<>(reactions.getReactions());
1419                        newReactions.removeAll(message.getReactions().stream().filter(r -> reactionFrom.equals(r.from)).map(r -> r.reaction).collect(Collectors.toList()));
1420                        final var combinedReactions =
1421                                Reaction.withFrom(
1422                                        message.getReactions(),
1423                                        reactions.getReactions(),
1424                                        isReceived,
1425                                        reactionFrom,
1426                                        message.getRemoteMsgId());
1427                        message.setReactions(combinedReactions);
1428                        mXmppConnectionService.updateMessage(message, false);
1429                        if (status < Message.STATUS_SEND) mXmppConnectionService.getNotificationService().push(message, counterpart, null, newReactions);
1430                    } else {
1431                        Log.d(Config.LOGTAG, "message with id " + reactingTo + " not found");
1432                    }
1433                }
1434            }
1435        }
1436
1437        final Element event = original.findChild("event", "http://jabber.org/protocol/pubsub#event");
1438        if (event != null && InvalidJid.hasValidFrom(original) && original.getFrom().isBareJid()) {
1439            if (event.hasChild("items")) {
1440                parseEvent(event, original.getFrom(), account);
1441            } else if (event.hasChild("delete")) {
1442                parseDeleteEvent(event, original.getFrom(), account);
1443            } else if (event.hasChild("purge")) {
1444                parsePurgeEvent(event, original.getFrom(), account);
1445            }
1446        }
1447
1448        final String nick = packet.findChildContent("nick", Namespace.NICK);
1449        if (nick != null && InvalidJid.hasValidFrom(original)) {
1450            if (mXmppConnectionService.isMuc(account, from)) {
1451                return;
1452            }
1453            final Contact contact = account.getRoster().getContact(from);
1454            if (contact.setPresenceName(nick)) {
1455                mXmppConnectionService.syncRoster(account);
1456                mXmppConnectionService.getAvatarService().clear(contact);
1457            }
1458        }
1459    }
1460
1461    private static Pair<im.conversations.android.xmpp.model.stanza.Message,Long> getForwardedMessagePacket(final im.conversations.android.xmpp.model.stanza.Message original, Class<? extends Extension> clazz) {
1462        final var extension = original.getExtension(clazz);
1463        final var forwarded = extension == null ? null : extension.getExtension(Forwarded.class);
1464        if (forwarded == null) {
1465            return null;
1466        }
1467        final Long timestamp = AbstractParser.parseTimestamp(forwarded, null);
1468        final var forwardedMessage = forwarded.getMessage();
1469        if (forwardedMessage == null) {
1470            return null;
1471        }
1472        return new Pair<>(forwardedMessage,timestamp);
1473    }
1474
1475    private static Pair<im.conversations.android.xmpp.model.stanza.Message,Long> getForwardedMessagePacket(final im.conversations.android.xmpp.model.stanza.Message original, final String name, final String namespace) {
1476        final Element wrapper = original.findChild(name, namespace);
1477        final var forwardedElement = wrapper == null ? null : wrapper.findChild("forwarded",Namespace.FORWARD);
1478        if (forwardedElement instanceof Forwarded forwarded) {
1479            final Long timestamp = AbstractParser.parseTimestamp(forwarded, null);
1480            final var forwardedMessage = forwarded.getMessage();
1481            if (forwardedMessage == null) {
1482                return null;
1483            }
1484            return new Pair<>(forwardedMessage,timestamp);
1485        }
1486        return null;
1487    }
1488
1489    private void dismissNotification(Account account, Jid counterpart, MessageArchiveService.Query query, final String id) {
1490        final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
1491        if (conversation != null && (query == null || query.isCatchup())) {
1492            final String displayableId = conversation.findMostRecentRemoteDisplayableId();
1493            if (displayableId != null && displayableId.equals(id)) {
1494                mXmppConnectionService.markRead(conversation);
1495            } else {
1496                Log.w(Config.LOGTAG, account.getJid().asBareJid() + ": received dismissing display marker that did not match our last id in that conversation");
1497            }
1498        }
1499    }
1500
1501    private void processMessageReceipts(final Account account, final im.conversations.android.xmpp.model.stanza.Message packet, final String remoteMsgId, MessageArchiveService.Query query) {
1502        final boolean markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
1503        final boolean request = packet.hasChild("request", "urn:xmpp:receipts");
1504        if (query == null) {
1505            final ArrayList<String> receiptsNamespaces = new ArrayList<>();
1506            if (markable) {
1507                receiptsNamespaces.add("urn:xmpp:chat-markers:0");
1508            }
1509            if (request) {
1510                receiptsNamespaces.add("urn:xmpp:receipts");
1511            }
1512            if (receiptsNamespaces.size() > 0) {
1513                final var receipt = mXmppConnectionService.getMessageGenerator().received(account,
1514                        packet.getFrom(),
1515                        remoteMsgId,
1516                        receiptsNamespaces,
1517                        packet.getType());
1518                mXmppConnectionService.sendMessagePacket(account, receipt);
1519            }
1520        } else if (query.isCatchup()) {
1521            if (request) {
1522                query.addPendingReceiptRequest(new ReceiptRequest(packet.getFrom(), remoteMsgId));
1523            }
1524        }
1525    }
1526
1527    private void activateGracePeriod(Account account) {
1528        long duration = mXmppConnectionService.getLongPreference("grace_period_length", R.integer.grace_period) * 1000;
1529        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": activating grace period till " + TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
1530        account.activateGracePeriod(duration);
1531    }
1532
1533    private class Invite {
1534        final Jid jid;
1535        final String password;
1536        final boolean direct;
1537        final Jid inviter;
1538
1539        Invite(Jid jid, String password, boolean direct, Jid inviter) {
1540            this.jid = jid;
1541            this.password = password;
1542            this.direct = direct;
1543            this.inviter = inviter;
1544        }
1545
1546        public boolean execute(final Account account) {
1547            if (this.jid == null) {
1548                return false;
1549            }
1550            final Contact contact = this.inviter != null ? account.getRoster().getContact(this.inviter) : null;
1551            if (contact != null && contact.isBlocked()) {
1552                Log.d(Config.LOGTAG,account.getJid().asBareJid()+": ignore invite from "+contact.getJid()+" because contact is blocked");
1553                return false;
1554            }
1555            final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true, false);
1556            conversation.setAttribute("inviter", inviter.toEscapedString());
1557            if (conversation.getMucOptions().online()) {
1558                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received invite to " + jid + " but muc is considered to be online");
1559                mXmppConnectionService.mucSelfPingAndRejoin(conversation);
1560            } else {
1561                conversation.getMucOptions().setPassword(password);
1562                mXmppConnectionService.databaseBackend.updateConversation(conversation);
1563                mXmppConnectionService.joinMuc(conversation, contact != null && contact.showInContactList());
1564                mXmppConnectionService.updateConversationUi();
1565            }
1566            return true;
1567        }
1568    }
1569
1570    private static int parseInt(String value) {
1571        try {
1572            return Integer.parseInt(value);
1573        } catch (NumberFormatException e) {
1574            return 0;
1575        }
1576    }
1577}