MessageParser.java

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