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