MessageParser.java

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