MessageParser.java

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