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