MessageParser.java

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