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