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