MessageParser.java

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