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            }
 781            if (conversationMultiMode) {
 782                message.setMucUser(conversation.getMucOptions().findUserByFullJid(counterpart));
 783                final Element occupantId = packet.findChild("occupant-id", "urn:xmpp:occupant-id:0");
 784                if (occupantId != null) message.setOccupantId(occupantId.getAttribute("id"));
 785                final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
 786                Jid trueCounterpart;
 787                if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
 788                    trueCounterpart = message.getTrueCounterpart();
 789                } else if (query != null && query.safeToExtractTrueCounterpart()) {
 790                    trueCounterpart = getTrueCounterpart(mucUserElement, fallback);
 791                } else {
 792                    trueCounterpart = fallback;
 793                }
 794                if (trueCounterpart != null && isTypeGroupChat) {
 795                    if (trueCounterpart.asBareJid().equals(account.getJid().asBareJid())) {
 796                        status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND;
 797                    } else {
 798                        status = Message.STATUS_RECEIVED;
 799                        message.setCarbon(false);
 800                    }
 801                }
 802                message.setStatus(status);
 803                message.setTrueCounterpart(trueCounterpart);
 804                if (!isTypeGroupChat) {
 805                    message.setType(Message.TYPE_PRIVATE);
 806                }
 807            } else {
 808                updateLastseen(account, from);
 809            }
 810
 811            if (replacementId != null && mXmppConnectionService.allowMessageCorrection()) {
 812                final Message replacedMessage = conversation.findMessageWithRemoteIdAndCounterpart(replacementId, counterpart);
 813                if (replacedMessage != null) {
 814                    final boolean fingerprintsMatch = replacedMessage.getFingerprint() == null
 815                            || replacedMessage.getFingerprint().equals(message.getFingerprint());
 816                    final boolean trueCountersMatch = replacedMessage.getTrueCounterpart() != null
 817                            && message.getTrueCounterpart() != null
 818                            && replacedMessage.getTrueCounterpart().asBareJid().equals(message.getTrueCounterpart().asBareJid());
 819                    final boolean mucUserMatches = query == null && replacedMessage.sameMucUser(message);
 820                    final boolean duplicate = conversation.hasDuplicateMessage(message);
 821                    if (fingerprintsMatch && (trueCountersMatch || !conversationMultiMode || mucUserMatches || counterpart.isBareJid()) && !duplicate) {
 822                        Log.d(Config.LOGTAG, "replaced message '" + replacedMessage.getBody() + "' with '" + message.getBody() + "'");
 823                        synchronized (replacedMessage) {
 824                            final String uuid = replacedMessage.getUuid();
 825                            replacedMessage.setUuid(UUID.randomUUID().toString());
 826                            replacedMessage.setBody(message.getBody());
 827                            replacedMessage.setSubject(message.getSubject());
 828                            replacedMessage.setThread(message.getThread());
 829                            replacedMessage.putEdited(replacedMessage.getRemoteMsgId(), replacedMessage.getServerMsgId());
 830                            replacedMessage.setRemoteMsgId(remoteMsgId);
 831                            if (replaceElement != null && !replaceElement.getName().equals("replace")) {
 832                                mXmppConnectionService.getFileBackend().deleteFile(replacedMessage);
 833                                mXmppConnectionService.evictPreview(message.getUuid());
 834                                List<Element> thumbs = replacedMessage.getFileParams() != null ? replacedMessage.getFileParams().getThumbnails() : null;
 835                                if (thumbs != null && !thumbs.isEmpty()) {
 836                                    for (Element thumb : thumbs) {
 837                                        Uri uri = Uri.parse(thumb.getAttribute("uri"));
 838                                        if (uri.getScheme().equals("cid")) {
 839                                            Cid cid = BobTransfer.cid(uri);
 840                                            if (cid == null) continue;
 841                                            DownloadableFile f = mXmppConnectionService.getFileForCid(cid);
 842                                            if (f != null) {
 843                                                mXmppConnectionService.evictPreview(f);
 844                                                f.delete();
 845                                            }
 846                                        }
 847                                    }
 848                                }
 849                                replacedMessage.clearPayloads();
 850                                replacedMessage.setFileParams(null);
 851                                replacedMessage.addPayload(replaceElement);
 852                            }
 853                            if (replacedMessage.getServerMsgId() == null || message.getServerMsgId() != null) {
 854                                replacedMessage.setServerMsgId(message.getServerMsgId());
 855                            }
 856                            replacedMessage.setEncryption(message.getEncryption());
 857                            if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
 858                                replacedMessage.markUnread();
 859                            }
 860                            extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
 861                            mXmppConnectionService.updateMessage(replacedMessage, uuid);
 862                            if (mXmppConnectionService.confirmMessages()
 863                                    && replacedMessage.getStatus() == Message.STATUS_RECEIVED
 864                                    && (replacedMessage.trusted() || replacedMessage.isPrivateMessage()) //TODO do we really want to send receipts for all PMs?
 865                                    && remoteMsgId != null
 866                                    && !selfAddressed
 867                                    && !isTypeGroupChat) {
 868                                processMessageReceipts(account, packet, remoteMsgId, query);
 869                            }
 870                            if (replacedMessage.getEncryption() == Message.ENCRYPTION_PGP) {
 871                                conversation.getAccount().getPgpDecryptionService().discard(replacedMessage);
 872                                conversation.getAccount().getPgpDecryptionService().decrypt(replacedMessage, false);
 873                            }
 874                        }
 875                        mXmppConnectionService.getNotificationService().updateNotification();
 876                        return;
 877                    } else {
 878                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received message correction but verification didn't check out");
 879                    }
 880                } else if (message.getBody() == null || message.getBody().equals("") || message.getBody().equals(" ")) {
 881                    return;
 882                }
 883                if (replaceElement != null && !replaceElement.getName().equals("replace")) return;
 884            }
 885
 886            boolean checkForDuplicates = (isTypeGroupChat && packet.hasChild("delay", "urn:xmpp:delay"))
 887                    || message.isPrivateMessage()
 888                    || message.getServerMsgId() != null
 889                    || (query == null && mXmppConnectionService.getMessageArchiveService().isCatchupInProgress(conversation));
 890            if (checkForDuplicates) {
 891                final Message duplicate = conversation.findDuplicateMessage(message);
 892                if (duplicate != null) {
 893                    final boolean serverMsgIdUpdated;
 894                    if (duplicate.getStatus() != Message.STATUS_RECEIVED
 895                            && duplicate.getUuid().equals(message.getRemoteMsgId())
 896                            && duplicate.getServerMsgId() == null
 897                            && message.getServerMsgId() != null) {
 898                        duplicate.setServerMsgId(message.getServerMsgId());
 899                        if (mXmppConnectionService.databaseBackend.updateMessage(duplicate, false)) {
 900                            serverMsgIdUpdated = true;
 901                        } else {
 902                            serverMsgIdUpdated = false;
 903                            Log.e(Config.LOGTAG, "failed to update message");
 904                        }
 905                    } else {
 906                        serverMsgIdUpdated = false;
 907                    }
 908                    Log.d(Config.LOGTAG, "skipping duplicate message with " + message.getCounterpart() + ". serverMsgIdUpdated=" + serverMsgIdUpdated);
 909                    return;
 910                }
 911            }
 912
 913            if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
 914                conversation.prepend(query.getActualInThisQuery(), message);
 915            } else {
 916                conversation.add(message);
 917            }
 918            if (query != null) {
 919                query.incrementActualMessageCount();
 920            }
 921
 922            if (query == null || query.isCatchup()) { //either no mam or catchup
 923                if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
 924                    mXmppConnectionService.markRead(conversation);
 925                    if (query == null) {
 926                        activateGracePeriod(account);
 927                    }
 928                } else {
 929                    message.markUnread();
 930                    notify = true;
 931                }
 932            }
 933
 934            if (message.getEncryption() == Message.ENCRYPTION_PGP) {
 935                notify = conversation.getAccount().getPgpDecryptionService().decrypt(message, notify);
 936            } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE || message.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
 937                notify = false;
 938            }
 939
 940            if (query == null) {
 941                extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
 942                mXmppConnectionService.updateConversationUi();
 943            }
 944
 945            if (mXmppConnectionService.confirmMessages()
 946                    && message.getStatus() == Message.STATUS_RECEIVED
 947                    && (message.trusted() || message.isPrivateMessage())
 948                    && remoteMsgId != null
 949                    && !selfAddressed
 950                    && !isTypeGroupChat) {
 951                processMessageReceipts(account, packet, remoteMsgId, query);
 952            }
 953
 954            if (message.getFileParams() != null) {
 955                for (Cid cid : message.getFileParams().getCids()) {
 956                    File f = mXmppConnectionService.getFileForCid(cid);
 957                    if (f != null && f.canRead()) {
 958                        message.setRelativeFilePath(f.getAbsolutePath());
 959                        mXmppConnectionService.getFileBackend().updateFileParams(message, null, false);
 960                        break;
 961                    }
 962                }
 963            }
 964
 965            mXmppConnectionService.databaseBackend.createMessage(message);
 966
 967            final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
 968            if (message.getRelativeFilePath() == null && message.trusted() && message.treatAsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
 969                if (message.getOob() != null && "cid".equalsIgnoreCase(message.getOob().getScheme())) {
 970                    try {
 971                        BobTransfer transfer = new BobTransfer.ForMessage(message, mXmppConnectionService);
 972                        message.setTransferable(transfer);
 973                        transfer.start();
 974                    } catch (URISyntaxException e) {
 975                        Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
 976                    }
 977                } else {
 978                    manager.createNewDownloadConnection(message);
 979                }
 980            } else if (notify) {
 981                if (query != null && query.isCatchup()) {
 982                    mXmppConnectionService.getNotificationService().pushFromBacklog(message);
 983                } else {
 984                    mXmppConnectionService.getNotificationService().push(message);
 985                }
 986            }
 987        } else if (!packet.hasChild("body")) { //no body
 988
 989            final Conversation conversation = mXmppConnectionService.find(account, from.asBareJid());
 990            if (axolotlEncrypted != null) {
 991                Jid origin;
 992                if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
 993                    final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
 994                    origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
 995                    if (origin == null) {
 996                        Log.d(Config.LOGTAG, "omemo key transport message in anonymous conference received");
 997                        return;
 998                    }
 999                } else if (isTypeGroupChat) {
1000                    return;
1001                } else {
1002                    origin = from;
1003                }
1004                try {
1005                    final XmppAxolotlMessage xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlEncrypted, origin.asBareJid());
1006                    account.getAxolotlService().processReceivingKeyTransportMessage(xmppAxolotlMessage, query != null);
1007                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": omemo key transport message received from " + origin);
1008                } catch (Exception e) {
1009                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": invalid omemo key transport message received " + e.getMessage());
1010                    return;
1011                }
1012            }
1013
1014            if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
1015                mXmppConnectionService.updateConversationUi();
1016            }
1017
1018            if (isTypeGroupChat) {
1019                if (packet.hasChild("subject") && !packet.hasChild("thread")) { // We already know it has no body per above
1020                    if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
1021                        conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
1022                        final LocalizedContent subject = packet.findInternationalizedChildContentInDefaultNamespace("subject");
1023                        if (subject != null && conversation.getMucOptions().setSubject(subject.content)) {
1024                            mXmppConnectionService.updateConversation(conversation);
1025                        }
1026                        mXmppConnectionService.updateConversationUi();
1027                        return;
1028                    }
1029                }
1030            }
1031            if (conversation != null && mucUserElement != null && InvalidJid.hasValidFrom(packet) && from.isBareJid()) {
1032                for (Element child : mucUserElement.getChildren()) {
1033                    if ("status".equals(child.getName())) {
1034                        try {
1035                            int code = Integer.parseInt(child.getAttribute("code"));
1036                            if ((code >= 170 && code <= 174) || (code >= 102 && code <= 104)) {
1037                                mXmppConnectionService.fetchConferenceConfiguration(conversation);
1038                                break;
1039                            }
1040                        } catch (Exception e) {
1041                            //ignored
1042                        }
1043                    } else if ("item".equals(child.getName())) {
1044                        MucOptions.User user = AbstractParser.parseItem(conversation, child);
1045                        Log.d(Config.LOGTAG, account.getJid() + ": changing affiliation for "
1046                                + user.getRealJid() + " to " + user.getAffiliation() + " in "
1047                                + conversation.getJid().asBareJid());
1048                        if (!user.realJidMatchesAccount()) {
1049                            boolean isNew = conversation.getMucOptions().updateUser(user);
1050                            mXmppConnectionService.getAvatarService().clear(conversation);
1051                            mXmppConnectionService.updateMucRosterUi();
1052                            mXmppConnectionService.updateConversationUi();
1053                            Contact contact = user.getContact();
1054                            if (!user.getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
1055                                Jid jid = user.getRealJid();
1056                                List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
1057                                if (cryptoTargets.remove(user.getRealJid())) {
1058                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
1059                                    conversation.setAcceptedCryptoTargets(cryptoTargets);
1060                                    mXmppConnectionService.updateConversation(conversation);
1061                                }
1062                            } else if (isNew
1063                                    && user.getRealJid() != null
1064                                    && conversation.getMucOptions().isPrivateAndNonAnonymous()
1065                                    && (contact == null || !contact.mutualPresenceSubscription())
1066                                    && account.getAxolotlService().hasEmptyDeviceList(user.getRealJid())) {
1067                                account.getAxolotlService().fetchDeviceIds(user.getRealJid());
1068                            }
1069                        }
1070                    }
1071                }
1072            }
1073            if (!isTypeGroupChat) {
1074                for (Element child : packet.getChildren()) {
1075                    if (Namespace.JINGLE_MESSAGE.equals(child.getNamespace()) && JINGLE_MESSAGE_ELEMENT_NAMES.contains(child.getName())) {
1076                        final String action = child.getName();
1077                        final String sessionId = child.getAttribute("id");
1078                        if (sessionId == null) {
1079                            break;
1080                        }
1081                        if (query == null && offlineMessagesRetrieved) {
1082                            if (serverMsgId == null) {
1083                                serverMsgId = extractStanzaId(account, packet);
1084                            }
1085                            mXmppConnectionService
1086                                    .getJingleConnectionManager()
1087                                    .deliverMessage(
1088                                            account,
1089                                            packet.getTo(),
1090                                            packet.getFrom(),
1091                                            child,
1092                                            remoteMsgId,
1093                                            serverMsgId,
1094                                            timestamp);
1095                            final Contact contact = account.getRoster().getContact(from);
1096                            if (mXmppConnectionService.confirmMessages()
1097                                    && !contact.isSelf()
1098                                    && remoteMsgId != null
1099                                    && contact.showInContactList()) {
1100                                processMessageReceipts(account, packet, remoteMsgId, null);
1101                            }
1102                        } else if ((query != null && query.isCatchup()) || !offlineMessagesRetrieved) {
1103                            if ("propose".equals(action)) {
1104                                final Element description = child.findChild("description");
1105                                final String namespace =
1106                                        description == null ? null : description.getNamespace();
1107                                if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
1108                                    final Conversation c =
1109                                            mXmppConnectionService.findOrCreateConversation(
1110                                                    account, counterpart.asBareJid(), false, false);
1111                                    final Message preExistingMessage =
1112                                            c.findRtpSession(sessionId, status);
1113                                    if (preExistingMessage != null) {
1114                                        preExistingMessage.setServerMsgId(serverMsgId);
1115                                        mXmppConnectionService.updateMessage(preExistingMessage);
1116                                        break;
1117                                    }
1118                                    final Message message =
1119                                            new Message(
1120                                                    c, status, Message.TYPE_RTP_SESSION, sessionId);
1121                                    message.setServerMsgId(serverMsgId);
1122                                    message.setTime(timestamp);
1123                                    message.setBody(new RtpSessionStatus(false, 0).toString());
1124                                    c.add(message);
1125                                    mXmppConnectionService.databaseBackend.createMessage(message);
1126                                }
1127                            } else if ("proceed".equals(action)) {
1128                                // status needs to be flipped to find the original propose
1129                                final Conversation c =
1130                                        mXmppConnectionService.findOrCreateConversation(
1131                                                account, counterpart.asBareJid(), false, false);
1132                                final int s =
1133                                        packet.fromAccount(account)
1134                                                ? Message.STATUS_RECEIVED
1135                                                : Message.STATUS_SEND;
1136                                final Message message = c.findRtpSession(sessionId, s);
1137                                if (message != null) {
1138                                    message.setBody(new RtpSessionStatus(true, 0).toString());
1139                                    if (serverMsgId != null) {
1140                                        message.setServerMsgId(serverMsgId);
1141                                    }
1142                                    message.setTime(timestamp);
1143                                    mXmppConnectionService.updateMessage(message, true);
1144                                } else {
1145                                    Log.d(
1146                                            Config.LOGTAG,
1147                                            "unable to find original rtp session message for received propose");
1148                                }
1149
1150                            } else if ("finish".equals(action)) {
1151                                Log.d(
1152                                        Config.LOGTAG,
1153                                        "received JMI 'finish' during MAM catch-up. Can be used to update success/failure and duration");
1154                            }
1155                        } else {
1156                            //MAM reloads (non catchups
1157                            if ("propose".equals(action)) {
1158                                final Element description = child.findChild("description");
1159                                final String namespace = description == null ? null : description.getNamespace();
1160                                if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
1161                                    final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
1162                                    final Message preExistingMessage = c.findRtpSession(sessionId, status);
1163                                    if (preExistingMessage != null) {
1164                                        preExistingMessage.setServerMsgId(serverMsgId);
1165                                        mXmppConnectionService.updateMessage(preExistingMessage);
1166                                        break;
1167                                    }
1168                                    final Message message = new Message(
1169                                            c,
1170                                            status,
1171                                            Message.TYPE_RTP_SESSION,
1172                                            sessionId
1173                                    );
1174                                    message.setServerMsgId(serverMsgId);
1175                                    message.setTime(timestamp);
1176                                    message.setBody(new RtpSessionStatus(true, 0).toString());
1177                                    if (query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
1178                                        c.prepend(query.getActualInThisQuery(), message);
1179                                    } else {
1180                                        c.add(message);
1181                                    }
1182                                    query.incrementActualMessageCount();
1183                                    mXmppConnectionService.databaseBackend.createMessage(message);
1184                                }
1185                            }
1186                        }
1187                        break;
1188                    }
1189                }
1190            }
1191        }
1192
1193        Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
1194        if (received == null) {
1195            received = packet.findChild("received", "urn:xmpp:receipts");
1196        }
1197        if (received != null) {
1198            String id = received.getAttribute("id");
1199            if (packet.fromAccount(account)) {
1200                if (query != null && id != null && packet.getTo() != null) {
1201                    query.removePendingReceiptRequest(new ReceiptRequest(packet.getTo(), id));
1202                }
1203            } else if (id != null) {
1204                if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
1205                    final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
1206                    mXmppConnectionService.getJingleConnectionManager()
1207                            .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.DISCOVERED);
1208                } else {
1209                    mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_RECEIVED);
1210                }
1211            }
1212        }
1213        final Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
1214        if (displayed != null) {
1215            final String id = displayed.getAttribute("id");
1216            final Jid sender = InvalidJid.getNullForInvalid(displayed.getAttributeAsJid("sender"));
1217            if (packet.fromAccount(account) && !selfAddressed) {
1218                final Conversation c =
1219                        mXmppConnectionService.find(account, counterpart.asBareJid());
1220                final Message message =
1221                        (c == null || id == null) ? null : c.findReceivedWithRemoteId(id);
1222                if (message != null && (query == null || query.isCatchup())) {
1223                    mXmppConnectionService.markReadUpTo(c, message);
1224                }
1225                if (query == null) {
1226                    activateGracePeriod(account);
1227                }
1228            } else if (isTypeGroupChat) {
1229                final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
1230                final Message message;
1231                if (conversation != null && id != null) {
1232                    if (sender != null) {
1233                        message = conversation.findMessageWithRemoteId(id, sender);
1234                    } else {
1235                        message = conversation.findMessageWithServerMsgId(id);
1236                    }
1237                } else {
1238                    message = null;
1239                }
1240                if (message != null) {
1241                    final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
1242                    final Jid trueJid = getTrueCounterpart((query != null && query.safeToExtractTrueCounterpart()) ? mucUserElement : null, fallback);
1243                    final boolean trueJidMatchesAccount = account.getJid().asBareJid().equals(trueJid == null ? null : trueJid.asBareJid());
1244                    if (trueJidMatchesAccount || conversation.getMucOptions().isSelf(counterpart)) {
1245                        if (!message.isRead() && (query == null || query.isCatchup())) { //checking if message is unread fixes race conditions with reflections
1246                            mXmppConnectionService.markReadUpTo(conversation, message);
1247                        }
1248                    } else if (!counterpart.isBareJid() && trueJid != null) {
1249                        final ReadByMarker readByMarker = ReadByMarker.from(counterpart, trueJid);
1250                        if (message.addReadByMarker(readByMarker)) {
1251                            final var mucOptions = conversation.getMucOptions();
1252                            final var everyone = ImmutableSet.copyOf(mucOptions.getMembers(false));
1253                            final var readyBy = message.getReadyByTrue();
1254                            final var mStatus = message.getStatus();
1255                            if (mucOptions.isPrivateAndNonAnonymous()
1256                                    && (mStatus == Message.STATUS_SEND_RECEIVED
1257                                            || mStatus == Message.STATUS_SEND)
1258                                    && readyBy.containsAll(everyone)) {
1259                                message.setStatus(Message.STATUS_SEND_DISPLAYED);
1260                            }
1261                            mXmppConnectionService.updateMessage(message, false);
1262                        }
1263                    }
1264                }
1265            } else {
1266                final Message displayedMessage = mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_DISPLAYED);
1267                Message message = displayedMessage == null ? null : displayedMessage.prev();
1268                while (message != null
1269                        && message.getStatus() == Message.STATUS_SEND_RECEIVED
1270                        && message.getTimeSent() < displayedMessage.getTimeSent()) {
1271                    mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
1272                    message = message.prev();
1273                }
1274                if (displayedMessage != null && selfAddressed) {
1275                    dismissNotification(account, counterpart, query, id);
1276                }
1277            }
1278        }
1279
1280        final Element event = original.findChild("event", "http://jabber.org/protocol/pubsub#event");
1281        if (event != null && InvalidJid.hasValidFrom(original) && original.getFrom().isBareJid()) {
1282            if (event.hasChild("items")) {
1283                parseEvent(event, original.getFrom(), account);
1284            } else if (event.hasChild("delete")) {
1285                parseDeleteEvent(event, original.getFrom(), account);
1286            } else if (event.hasChild("purge")) {
1287                parsePurgeEvent(event, original.getFrom(), account);
1288            }
1289        }
1290
1291        final String nick = packet.findChildContent("nick", Namespace.NICK);
1292        if (nick != null && InvalidJid.hasValidFrom(original)) {
1293            if (mXmppConnectionService.isMuc(account, from)) {
1294                return;
1295            }
1296            final Contact contact = account.getRoster().getContact(from);
1297            if (contact.setPresenceName(nick)) {
1298                mXmppConnectionService.syncRoster(account);
1299                mXmppConnectionService.getAvatarService().clear(contact);
1300            }
1301        }
1302    }
1303
1304    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) {
1305        final var extension = original.getExtension(clazz);
1306        final var forwarded = extension == null ? null : extension.getExtension(Forwarded.class);
1307        if (forwarded == null) {
1308            return null;
1309        }
1310        final Long timestamp = AbstractParser.parseTimestamp(forwarded, null);
1311        final var forwardedMessage = forwarded.getMessage();
1312        if (forwardedMessage == null) {
1313            return null;
1314        }
1315        return new Pair<>(forwardedMessage,timestamp);
1316    }
1317
1318    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) {
1319        final Element wrapper = original.findChild(name, namespace);
1320        final var forwardedElement = wrapper == null ? null : wrapper.findChild("forwarded",Namespace.FORWARD);
1321        if (forwardedElement instanceof Forwarded forwarded) {
1322            final Long timestamp = AbstractParser.parseTimestamp(forwarded, null);
1323            final var forwardedMessage = forwarded.getMessage();
1324            if (forwardedMessage == null) {
1325                return null;
1326            }
1327            return new Pair<>(forwardedMessage,timestamp);
1328        }
1329        return null;
1330    }
1331
1332    private void dismissNotification(Account account, Jid counterpart, MessageArchiveService.Query query, final String id) {
1333        final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
1334        if (conversation != null && (query == null || query.isCatchup())) {
1335            final String displayableId = conversation.findMostRecentRemoteDisplayableId();
1336            if (displayableId != null && displayableId.equals(id)) {
1337                mXmppConnectionService.markRead(conversation);
1338            } else {
1339                Log.w(Config.LOGTAG, account.getJid().asBareJid() + ": received dismissing display marker that did not match our last id in that conversation");
1340            }
1341        }
1342    }
1343
1344    private void processMessageReceipts(final Account account, final im.conversations.android.xmpp.model.stanza.Message packet, final String remoteMsgId, MessageArchiveService.Query query) {
1345        final boolean markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
1346        final boolean request = packet.hasChild("request", "urn:xmpp:receipts");
1347        if (query == null) {
1348            final ArrayList<String> receiptsNamespaces = new ArrayList<>();
1349            if (markable) {
1350                receiptsNamespaces.add("urn:xmpp:chat-markers:0");
1351            }
1352            if (request) {
1353                receiptsNamespaces.add("urn:xmpp:receipts");
1354            }
1355            if (receiptsNamespaces.size() > 0) {
1356                final var receipt = mXmppConnectionService.getMessageGenerator().received(account,
1357                        packet.getFrom(),
1358                        remoteMsgId,
1359                        receiptsNamespaces,
1360                        packet.getType());
1361                mXmppConnectionService.sendMessagePacket(account, receipt);
1362            }
1363        } else if (query.isCatchup()) {
1364            if (request) {
1365                query.addPendingReceiptRequest(new ReceiptRequest(packet.getFrom(), remoteMsgId));
1366            }
1367        }
1368    }
1369
1370    private void activateGracePeriod(Account account) {
1371        long duration = mXmppConnectionService.getLongPreference("grace_period_length", R.integer.grace_period) * 1000;
1372        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": activating grace period till " + TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
1373        account.activateGracePeriod(duration);
1374    }
1375
1376    private class Invite {
1377        final Jid jid;
1378        final String password;
1379        final boolean direct;
1380        final Jid inviter;
1381
1382        Invite(Jid jid, String password, boolean direct, Jid inviter) {
1383            this.jid = jid;
1384            this.password = password;
1385            this.direct = direct;
1386            this.inviter = inviter;
1387        }
1388
1389        public boolean execute(final Account account) {
1390            if (this.jid == null) {
1391                return false;
1392            }
1393            final Contact contact = this.inviter != null ? account.getRoster().getContact(this.inviter) : null;
1394            if (contact != null && contact.isBlocked()) {
1395                Log.d(Config.LOGTAG,account.getJid().asBareJid()+": ignore invite from "+contact.getJid()+" because contact is blocked");
1396                return false;
1397            }
1398            final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true, false);
1399            conversation.setAttribute("inviter", inviter.toEscapedString());
1400            if (conversation.getMucOptions().online()) {
1401                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received invite to " + jid + " but muc is considered to be online");
1402                mXmppConnectionService.mucSelfPingAndRejoin(conversation);
1403            } else {
1404                conversation.getMucOptions().setPassword(password);
1405                mXmppConnectionService.databaseBackend.updateConversation(conversation);
1406                mXmppConnectionService.joinMuc(conversation, contact != null && contact.showInContactList());
1407                mXmppConnectionService.updateConversationUi();
1408            }
1409            return true;
1410        }
1411    }
1412}