Search in sources :

Example 61 with Element

use of de.pixart.messenger.xml.Element in project Pix-Art-Messenger by kriztan.

the class MessageParser method onMessagePacketReceived.

@Override
public void onMessagePacketReceived(Account account, MessagePacket original) {
    if (handleErrorMessage(account, original)) {
        return;
    }
    final MessagePacket packet;
    Long timestamp = null;
    final boolean isForwarded;
    boolean isCarbon = false;
    String serverMsgId = null;
    final Element fin = original.findChild("fin", Namespace.MAM_LEGACY);
    if (fin != null) {
        mXmppConnectionService.getMessageArchiveService().processFinLegacy(fin, original.getFrom());
        return;
    }
    final boolean mamLegacy = original.hasChild("result", Namespace.MAM_LEGACY);
    final Element result = original.findChild("result", mamLegacy ? Namespace.MAM_LEGACY : Namespace.MAM);
    final MessageArchiveService.Query query = result == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
    if (query != null && query.validFrom(original.getFrom())) {
        Pair<MessagePacket, Long> f = original.getForwardedMessagePacket("result", mamLegacy ? Namespace.MAM_LEGACY : Namespace.MAM);
        if (f == null) {
            return;
        }
        timestamp = f.second;
        packet = f.first;
        isForwarded = true;
        serverMsgId = result.getAttribute("id");
        query.incrementMessageCount();
    } else if (query != null) {
        Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": received mam result from invalid sender");
        return;
    } else if (original.fromServer(account)) {
        Pair<MessagePacket, Long> f;
        f = original.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
        f = f == null ? original.getForwardedMessagePacket("sent", "urn:xmpp:carbons:2") : f;
        packet = f != null ? f.first : original;
        if (handleErrorMessage(account, packet)) {
            return;
        }
        timestamp = f != null ? f.second : null;
        isCarbon = f != null;
        isForwarded = isCarbon;
    } else {
        packet = original;
        isForwarded = false;
    }
    if (timestamp == null) {
        timestamp = AbstractParser.parseTimestamp(original, AbstractParser.parseTimestamp(packet));
    }
    final String body = packet.getBody();
    final Element mucUserElement = packet.findChild("x", "http://jabber.org/protocol/muc#user");
    final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted");
    final Element replaceElement = packet.findChild("replace", "urn:xmpp:message-correct:0");
    final Element oob = packet.findChild("x", Namespace.OOB);
    final String oobUrl = oob != null ? oob.findChildContent("url") : null;
    final String replacementId = replaceElement == null ? null : replaceElement.getAttribute("id");
    final Element axolotlEncrypted = packet.findChild(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
    int status;
    final Jid counterpart;
    final Jid to = packet.getTo();
    final Jid from = packet.getFrom();
    final Element originId = packet.findChild("origin-id", Namespace.STANZA_IDS);
    final String remoteMsgId;
    if (originId != null && originId.getAttribute("id") != null) {
        remoteMsgId = originId.getAttribute("id");
    } else {
        remoteMsgId = packet.getId();
    }
    boolean notify = false;
    if (from == null) {
        Log.d(Config.LOGTAG, "no from in: " + packet.toString());
        return;
    }
    boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
    if (query != null && !query.muc() && isTypeGroupChat) {
        Log.e(Config.LOGTAG, account.getJid().toBareJid() + ": received groupchat (" + from + ") message on regular MAM request. skipping");
        return;
    }
    boolean isProperlyAddressed = (to != null) && (!to.isBareJid() || account.countPresences() == 0);
    boolean isMucStatusMessage = from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
    boolean selfAddressed;
    if (packet.fromAccount(account)) {
        status = Message.STATUS_SEND;
        selfAddressed = to == null || account.getJid().toBareJid().equals(to.toBareJid());
        if (selfAddressed) {
            counterpart = from;
        } else {
            counterpart = to != null ? to : account.getJid();
        }
    } else {
        status = Message.STATUS_RECEIVED;
        counterpart = from;
        selfAddressed = false;
    }
    Invite invite = extractInvite(account, packet);
    if (invite != null && invite.execute(account)) {
        return;
    }
    if ((body != null || pgpEncrypted != null || (axolotlEncrypted != null && axolotlEncrypted.hasChild("payload")) || oobUrl != null) && !isMucStatusMessage) {
        final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.toBareJid(), isTypeGroupChat, false, query, false);
        final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
        if (serverMsgId == null) {
            serverMsgId = extractStanzaId(packet, isTypeGroupChat, conversation);
        }
        if (selfAddressed) {
            if (mXmppConnectionService.markMessage(conversation, remoteMsgId, Message.STATUS_SEND_RECEIVED, serverMsgId)) {
                return;
            }
            status = Message.STATUS_RECEIVED;
            if (remoteMsgId != null && conversation.findMessageWithRemoteId(remoteMsgId, counterpart) != null) {
                return;
            }
        }
        if (isTypeGroupChat) {
            if (conversation.getMucOptions().isSelf(counterpart)) {
                status = Message.STATUS_SEND_RECEIVED;
                // not really carbon but received from another resource
                isCarbon = true;
                if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status, serverMsgId)) {
                    return;
                } else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
                    Message message = conversation.findSentMessageWithBody(packet.getBody());
                    if (message != null) {
                        mXmppConnectionService.markMessage(message, status);
                        return;
                    }
                }
            } else {
                status = Message.STATUS_RECEIVED;
            }
        }
        final Message message;
        if (body != null && body.startsWith("?OTR") && Config.supportOtr()) {
            if (!isForwarded && !isTypeGroupChat && isProperlyAddressed && !conversationMultiMode) {
                message = parseOtrChat(body, from, remoteMsgId, conversation);
                if (message == null) {
                    return;
                }
            } else {
                Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ignoring OTR message from " + from + " isForwarded=" + Boolean.toString(isForwarded) + ", isProperlyAddressed=" + Boolean.valueOf(isProperlyAddressed));
                message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
            }
        } else if (pgpEncrypted != null && Config.supportOpenPgp()) {
            message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status);
        } else if (axolotlEncrypted != null && Config.supportOmemo()) {
            Jid origin;
            if (conversationMultiMode) {
                final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
                origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
                if (origin == null) {
                    Log.d(Config.LOGTAG, "axolotl message in non anonymous conference received");
                    return;
                }
            } else {
                origin = from;
            }
            message = parseAxolotlChat(axolotlEncrypted, origin, conversation, status, query != null);
            if (message == null) {
                if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), isTypeGroupChat, packet)) {
                    mXmppConnectionService.updateConversationUi();
                }
                if (query != null && status == Message.STATUS_SEND && remoteMsgId != null) {
                    Message previouslySent = conversation.findSentMessageWithUuid(remoteMsgId);
                    if (previouslySent != null && previouslySent.getServerMsgId() == null && serverMsgId != null) {
                        previouslySent.setServerMsgId(serverMsgId);
                        mXmppConnectionService.databaseBackend.updateMessage(previouslySent);
                        Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": encountered previously sent OMEMO message without serverId. updating...");
                    }
                }
                return;
            }
            if (conversationMultiMode) {
                message.setTrueCounterpart(origin);
            }
        } else if (body == null && oobUrl != null) {
            message = new Message(conversation, oobUrl, Message.ENCRYPTION_NONE, status);
            message.setOob(true);
            if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
                message.setEncryption(Message.ENCRYPTION_DECRYPTED);
            }
        } else {
            message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
        }
        message.setCounterpart(counterpart);
        message.setRemoteMsgId(remoteMsgId);
        message.setServerMsgId(serverMsgId);
        message.setCarbon(isCarbon);
        message.setTime(timestamp);
        if (body != null && body.equals(oobUrl)) {
            message.setOob(true);
            if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
                message.setEncryption(Message.ENCRYPTION_DECRYPTED);
            }
        }
        message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
        if (conversationMultiMode) {
            final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
            Jid trueCounterpart;
            if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
                trueCounterpart = message.getTrueCounterpart();
            } else if (query != null && query.safeToExtractTrueCounterpart()) {
                trueCounterpart = getTrueCounterpart(mucUserElement, fallback);
            } else {
                trueCounterpart = fallback;
            }
            if (trueCounterpart != null && trueCounterpart.toBareJid().equals(account.getJid().toBareJid())) {
                status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND;
            }
            message.setStatus(status);
            message.setTrueCounterpart(trueCounterpart);
            if (!isTypeGroupChat) {
                message.setType(Message.TYPE_PRIVATE);
            }
        } else {
            updateLastseen(account, from);
        }
        if (replacementId != null && mXmppConnectionService.allowMessageCorrection()) {
            final Message replacedMessage = conversation.findMessageWithRemoteIdAndCounterpart(replacementId, counterpart, message.getStatus() == Message.STATUS_RECEIVED, message.isCarbon());
            if (replacedMessage != null) {
                final boolean fingerprintsMatch = replacedMessage.getFingerprint() == null || replacedMessage.getFingerprint().equals(message.getFingerprint());
                final boolean trueCountersMatch = replacedMessage.getTrueCounterpart() != null && replacedMessage.getTrueCounterpart().equals(message.getTrueCounterpart());
                final boolean duplicate = conversation.hasDuplicateMessage(message);
                if (fingerprintsMatch && (trueCountersMatch || !conversationMultiMode) && !duplicate) {
                    Log.d(Config.LOGTAG, "replaced message '" + replacedMessage.getBody() + "' with '" + message.getBody() + "'");
                    synchronized (replacedMessage) {
                        final String uuid = replacedMessage.getUuid();
                        replacedMessage.setUuid(UUID.randomUUID().toString());
                        replacedMessage.setBody(message.getBody());
                        replacedMessage.setEdited(replacedMessage.getRemoteMsgId());
                        replacedMessage.setRemoteMsgId(remoteMsgId);
                        if (replacedMessage.getServerMsgId() == null || message.getServerMsgId() != null) {
                            replacedMessage.setServerMsgId(message.getServerMsgId());
                        }
                        replacedMessage.setEncryption(message.getEncryption());
                        if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
                            replacedMessage.markUnread();
                        }
                        extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), isTypeGroupChat, packet);
                        mXmppConnectionService.updateMessage(replacedMessage, uuid);
                        mXmppConnectionService.getNotificationService().updateNotification(false);
                        if (mXmppConnectionService.confirmMessages() && replacedMessage.getStatus() == Message.STATUS_RECEIVED && (replacedMessage.trusted() || replacedMessage.getType() == Message.TYPE_PRIVATE) && remoteMsgId != null && !selfAddressed && !isTypeGroupChat) {
                            processMessageReceipts(account, packet, query);
                        }
                        if (replacedMessage.getEncryption() == Message.ENCRYPTION_PGP) {
                            conversation.getAccount().getPgpDecryptionService().discard(replacedMessage);
                            conversation.getAccount().getPgpDecryptionService().decrypt(replacedMessage, false);
                        }
                    }
                    return;
                } else {
                    Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": received message correction but verification didn't check out");
                }
            }
        }
        long deletionDate = mXmppConnectionService.getAutomaticMessageDeletionDate();
        if (deletionDate != 0 && message.getTimeSent() < deletionDate) {
            Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": skipping message from " + message.getCounterpart().toString() + " because it was sent prior to our deletion date");
            return;
        }
        boolean checkForDuplicates = (isTypeGroupChat && packet.hasChild("delay", "urn:xmpp:delay")) || message.getType() == Message.TYPE_PRIVATE || message.getServerMsgId() != null;
        if (checkForDuplicates) {
            final Message duplicate = conversation.findDuplicateMessage(message);
            if (duplicate != null) {
                final boolean serverMsgIdUpdated;
                if (duplicate.getStatus() != Message.STATUS_RECEIVED && duplicate.getUuid().equals(message.getRemoteMsgId()) && duplicate.getServerMsgId() == null && message.getServerMsgId() != null) {
                    duplicate.setServerMsgId(message.getServerMsgId());
                    mXmppConnectionService.databaseBackend.updateMessage(message);
                    serverMsgIdUpdated = true;
                } else {
                    serverMsgIdUpdated = false;
                }
                Log.d(Config.LOGTAG, "skipping duplicate message with " + message.getCounterpart() + ". serverMsgIdUpdated=" + Boolean.toString(serverMsgIdUpdated));
                return;
            }
        }
        if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
            conversation.prepend(query.getActualInThisQuery(), message);
        } else {
            conversation.add(message);
        }
        if (query != null) {
            query.incrementActualMessageCount();
        }
        if (query == null || query.isCatchup()) {
            // either no mam or catchup
            if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
                mXmppConnectionService.markRead(conversation);
                if (query == null) {
                    activateGracePeriod(account);
                }
            } else {
                message.markUnread();
                notify = true;
            }
        }
        if (message.getEncryption() == Message.ENCRYPTION_PGP) {
            notify = conversation.getAccount().getPgpDecryptionService().decrypt(message, notify);
        }
        if (query == null) {
            extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), isTypeGroupChat, packet);
            mXmppConnectionService.updateConversationUi();
        }
        if (mXmppConnectionService.confirmMessages() && message.getStatus() == Message.STATUS_RECEIVED && (message.trusted() || message.getType() == Message.TYPE_PRIVATE) && remoteMsgId != null && !selfAddressed && !isTypeGroupChat) {
            processMessageReceipts(account, packet, query);
        }
        if (message.getStatus() == Message.STATUS_RECEIVED && conversation.getOtrSession() != null && !conversation.getOtrSession().getSessionID().getUserID().equals(message.getCounterpart().getResourcepart())) {
            conversation.endOtrIfNeeded();
        }
        mXmppConnectionService.databaseBackend.createMessage(message);
        final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
        if (message.trusted() && message.treatAsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
            manager.createNewDownloadConnection(message);
        } else if (notify) {
            if (query != null && query.isCatchup()) {
                mXmppConnectionService.getNotificationService().pushFromBacklog(message);
            } else {
                mXmppConnectionService.getNotificationService().push(message);
            }
        }
    } else if (!packet.hasChild("body")) {
        // no body
        final Conversation conversation = mXmppConnectionService.find(account, from.toBareJid());
        if (axolotlEncrypted != null) {
            Jid origin;
            if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
                final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
                origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
                if (origin == null) {
                    Log.d(Config.LOGTAG, "omemo key transport message in non anonymous conference received");
                    return;
                }
            } else if (isTypeGroupChat) {
                return;
            } else {
                origin = from;
            }
            try {
                final XmppAxolotlMessage xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlEncrypted, origin.toBareJid());
                account.getAxolotlService().processReceivingKeyTransportMessage(xmppAxolotlMessage, query != null);
                Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": omemo key transport message received from " + origin);
            } catch (Exception e) {
                Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": invalid omemo key transport message received " + e.getMessage());
                return;
            }
        }
        if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), isTypeGroupChat, packet)) {
            mXmppConnectionService.updateConversationUi();
        }
        if (isTypeGroupChat) {
            if (packet.hasChild("subject")) {
                if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
                    conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
                    String subject = packet.findInternationalizedChildContent("subject");
                    if (conversation.getMucOptions().setSubject(subject)) {
                        mXmppConnectionService.updateConversation(conversation);
                    }
                    final Bookmark bookmark = conversation.getBookmark();
                    if (bookmark != null && bookmark.getBookmarkName() == null) {
                        if (bookmark.setBookmarkName(subject)) {
                            mXmppConnectionService.pushBookmarks(account);
                        }
                    }
                    mXmppConnectionService.updateConversationUi();
                    return;
                }
            }
        }
        if (conversation != null && mucUserElement != null && from.isBareJid()) {
            for (Element child : mucUserElement.getChildren()) {
                if ("status".equals(child.getName())) {
                    try {
                        int code = Integer.parseInt(child.getAttribute("code"));
                        if ((code >= 170 && code <= 174) || (code >= 102 && code <= 104)) {
                            mXmppConnectionService.fetchConferenceConfiguration(conversation);
                            break;
                        }
                    } catch (Exception e) {
                    // ignored
                    }
                } else if ("item".equals(child.getName())) {
                    MucOptions.User user = AbstractParser.parseItem(conversation, child);
                    Log.d(Config.LOGTAG, account.getJid() + ": changing affiliation for " + user.getRealJid() + " to " + user.getAffiliation() + " in " + conversation.getJid().toBareJid());
                    if (!user.realJidMatchesAccount()) {
                        boolean isNew = conversation.getMucOptions().updateUser(user);
                        mXmppConnectionService.getAvatarService().clear(conversation);
                        mXmppConnectionService.updateMucRosterUi();
                        mXmppConnectionService.updateConversationUi();
                        Contact contact = user.getContact();
                        if (!user.getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
                            Jid jid = user.getRealJid();
                            List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
                            if (cryptoTargets.remove(user.getRealJid())) {
                                Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
                                conversation.setAcceptedCryptoTargets(cryptoTargets);
                                mXmppConnectionService.updateConversation(conversation);
                            }
                        } else if (isNew && user.getRealJid() != null && conversation.getMucOptions().isPrivateAndNonAnonymous() && (contact == null || !contact.mutualPresenceSubscription()) && account.getAxolotlService().hasEmptyDeviceList(user.getRealJid())) {
                            account.getAxolotlService().fetchDeviceIds(user.getRealJid());
                        }
                    }
                }
            }
        }
    }
    Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
    if (received == null) {
        received = packet.findChild("received", "urn:xmpp:receipts");
    }
    if (received != null) {
        String id = received.getAttribute("id");
        if (packet.fromAccount(account)) {
            if (query != null && id != null && packet.getTo() != null) {
                query.pendingReceiptRequests.remove(new ReceiptRequest(packet.getTo(), id));
            }
        } else {
            mXmppConnectionService.markMessage(account, from.toBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED);
        }
    }
    Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
    if (displayed != null) {
        final String id = displayed.getAttribute("id");
        final Jid sender = displayed.getAttributeAsJid("sender");
        if (packet.fromAccount(account) && !selfAddressed) {
            dismissNotification(account, counterpart, query);
        } else if (isTypeGroupChat) {
            Conversation conversation = mXmppConnectionService.find(account, counterpart.toBareJid());
            if (conversation != null && id != null && sender != null) {
                Message message = conversation.findMessageWithRemoteId(id, sender);
                if (message != null) {
                    final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
                    final Jid trueJid = getTrueCounterpart((query != null && query.safeToExtractTrueCounterpart()) ? mucUserElement : null, fallback);
                    final boolean trueJidMatchesAccount = account.getJid().toBareJid().equals(trueJid == null ? null : trueJid.toBareJid());
                    if (trueJidMatchesAccount || conversation.getMucOptions().isSelf(counterpart)) {
                        if (!message.isRead() && (query == null || query.isCatchup())) {
                            // checking if message is unread fixes race conditions with reflections
                            mXmppConnectionService.markRead(conversation);
                        }
                    } else if (!counterpart.isBareJid() && trueJid != null) {
                        ReadByMarker readByMarker = ReadByMarker.from(counterpart, trueJid);
                        if (message.addReadByMarker(readByMarker)) {
                            Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": added read by (" + readByMarker.getRealJid() + ") to message '" + message.getBody() + "'");
                            mXmppConnectionService.updateMessage(message);
                            mXmppConnectionService.markMessage(account, from.toBareJid(), id, Message.STATUS_SEND_DISPLAYED);
                        }
                    }
                }
            }
        } else {
            final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), id, Message.STATUS_SEND_DISPLAYED);
            Message message = displayedMessage == null ? null : displayedMessage.prev();
            while (message != null && message.getStatus() == Message.STATUS_SEND_RECEIVED && message.getTimeSent() < displayedMessage.getTimeSent()) {
                mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
                message = message.prev();
            }
            if (displayedMessage != null && selfAddressed) {
                dismissNotification(account, counterpart, query);
            }
        }
    }
    Element event = original.findChild("event", "http://jabber.org/protocol/pubsub#event");
    if (event != null) {
        parseEvent(event, original.getFrom(), account);
    }
    final String nick = packet.findChildContent("nick", Namespace.NICK);
    if (nick != null) {
        Contact contact = account.getRoster().getContact(from);
        if (contact.setPresenceName(nick)) {
            mXmppConnectionService.getAvatarService().clear(contact);
        }
    }
}
Also used : Jid(de.pixart.messenger.xmpp.jid.Jid) XmppAxolotlMessage(de.pixart.messenger.crypto.axolotl.XmppAxolotlMessage) Message(de.pixart.messenger.entities.Message) ReadByMarker(de.pixart.messenger.entities.ReadByMarker) Element(de.pixart.messenger.xml.Element) Conversation(de.pixart.messenger.entities.Conversation) XmppAxolotlMessage(de.pixart.messenger.crypto.axolotl.XmppAxolotlMessage) Contact(de.pixart.messenger.entities.Contact) MessagePacket(de.pixart.messenger.xmpp.stanzas.MessagePacket) MucOptions(de.pixart.messenger.entities.MucOptions) MessageArchiveService(de.pixart.messenger.services.MessageArchiveService) Bookmark(de.pixart.messenger.entities.Bookmark) HttpConnectionManager(de.pixart.messenger.http.HttpConnectionManager) ReceiptRequest(de.pixart.messenger.entities.ReceiptRequest)

Example 62 with Element

use of de.pixart.messenger.xml.Element in project Pix-Art-Messenger by kriztan.

the class MessageParser method extractInvite.

private Invite extractInvite(Account account, Element message) {
    Element x = message.findChild("x", "http://jabber.org/protocol/muc#user");
    if (x != null) {
        Element invite = x.findChild("invite");
        if (invite != null) {
            Element pw = x.findChild("password");
            Jid from = invite.getAttributeAsJid("from");
            Contact contact = from == null ? null : account.getRoster().getContact(from);
            return new Invite(message.getAttributeAsJid("from"), pw != null ? pw.getContent() : null, contact);
        }
    } else {
        x = message.findChild("x", "jabber:x:conference");
        if (x != null) {
            Jid from = message.getAttributeAsJid("from");
            Contact contact = from == null ? null : account.getRoster().getContact(from);
            return new Invite(x.getAttributeAsJid("jid"), x.getAttribute("password"), contact);
        }
    }
    return null;
}
Also used : Jid(de.pixart.messenger.xmpp.jid.Jid) Element(de.pixart.messenger.xml.Element) Contact(de.pixart.messenger.entities.Contact)

Example 63 with Element

use of de.pixart.messenger.xml.Element in project Pix-Art-Messenger by kriztan.

the class MessageParser method parseEvent.

private void parseEvent(final Element event, final Jid from, final Account account) {
    Element items = event.findChild("items");
    String node = items == null ? null : items.getAttribute("node");
    if ("urn:xmpp:avatar:metadata".equals(node)) {
        Avatar avatar = Avatar.parseMetadata(items);
        if (avatar != null) {
            avatar.owner = from.toBareJid();
            if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
                if (account.getJid().toBareJid().equals(from)) {
                    if (account.setAvatar(avatar.getFilename())) {
                        mXmppConnectionService.databaseBackend.updateAccount(account);
                    }
                    mXmppConnectionService.getAvatarService().clear(account);
                    mXmppConnectionService.updateConversationUi();
                    mXmppConnectionService.updateAccountUi();
                } else {
                    Contact contact = account.getRoster().getContact(from);
                    contact.setAvatar(avatar);
                    mXmppConnectionService.getAvatarService().clear(contact);
                    mXmppConnectionService.updateConversationUi();
                    mXmppConnectionService.updateRosterUi();
                }
            } else if (mXmppConnectionService.isDataSaverDisabled()) {
                mXmppConnectionService.fetchAvatar(account, avatar);
            }
        }
    } else if ("http://jabber.org/protocol/nick".equals(node)) {
        final Element i = items.findChild("item");
        final String nick = i == null ? null : i.findChildContent("nick", Namespace.NICK);
        if (nick != null) {
            Contact contact = account.getRoster().getContact(from);
            if (contact.setPresenceName(nick)) {
                mXmppConnectionService.getAvatarService().clear(contact);
            }
            mXmppConnectionService.updateConversationUi();
            mXmppConnectionService.updateAccountUi();
        }
    } else if (AxolotlService.PEP_DEVICE_LIST.equals(node)) {
        Element item = items.findChild("item");
        Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
        Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received PEP device list " + deviceIds + " update from " + from + ", processing... ");
        AxolotlService axolotlService = account.getAxolotlService();
        axolotlService.registerDevices(from, deviceIds);
        mXmppConnectionService.updateAccountUi();
    }
}
Also used : AxolotlService(de.pixart.messenger.crypto.axolotl.AxolotlService) Element(de.pixart.messenger.xml.Element) Avatar(de.pixart.messenger.xmpp.pep.Avatar) Contact(de.pixart.messenger.entities.Contact)

Example 64 with Element

use of de.pixart.messenger.xml.Element in project Pix-Art-Messenger by kriztan.

the class PresenceParser method parseContactPresence.

public void parseContactPresence(final PresencePacket packet, final Account account) {
    final PresenceGenerator mPresenceGenerator = mXmppConnectionService.getPresenceGenerator();
    final Jid from = packet.getFrom();
    if (from == null || from.equals(account.getJid())) {
        return;
    }
    final String type = packet.getAttribute("type");
    final Contact contact = account.getRoster().getContact(from);
    if (type == null) {
        final String resource = from.isBareJid() ? "" : from.getResourcepart();
        if (contact.setPresenceName(packet.findChildContent("nick", Namespace.NICK))) {
            mXmppConnectionService.getAvatarService().clear(contact);
        }
        Avatar avatar = Avatar.parsePresence(packet.findChild("x", "vcard-temp:x:update"));
        if (avatar != null && (!contact.isSelf() || account.getAvatar() == null)) {
            avatar.owner = from.toBareJid();
            if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
                if (avatar.owner.equals(account.getJid().toBareJid())) {
                    account.setAvatar(avatar.getFilename());
                    mXmppConnectionService.databaseBackend.updateAccount(account);
                    mXmppConnectionService.getAvatarService().clear(account);
                    mXmppConnectionService.updateConversationUi();
                    mXmppConnectionService.updateAccountUi();
                } else if (contact.setAvatar(avatar)) {
                    mXmppConnectionService.getAvatarService().clear(contact);
                    mXmppConnectionService.updateConversationUi();
                    mXmppConnectionService.updateRosterUi();
                }
            } else if (mXmppConnectionService.isDataSaverDisabled()) {
                mXmppConnectionService.fetchAvatar(account, avatar);
            }
        }
        int sizeBefore = contact.getPresences().size();
        final String show = packet.findChildContent("show");
        final Element caps = packet.findChild("c", "http://jabber.org/protocol/caps");
        final String message = packet.findChildContent("status");
        final Presence presence = Presence.parse(show, caps, message);
        contact.updatePresence(resource, presence);
        if (presence.hasCaps()) {
            mXmppConnectionService.fetchCaps(account, from, presence);
        }
        final Element idle = packet.findChild("idle", Namespace.IDLE);
        if (idle != null) {
            try {
                final String since = idle.getAttribute("since");
                contact.setLastseen(AbstractParser.parseTimestamp(since));
                contact.flagInactive();
            } catch (Throwable throwable) {
                if (contact.setLastseen(AbstractParser.parseTimestamp(packet))) {
                    contact.flagActive();
                }
            }
        } else {
            if (contact.setLastseen(AbstractParser.parseTimestamp(packet))) {
                contact.flagActive();
            }
        }
        PgpEngine pgp = mXmppConnectionService.getPgpEngine();
        Element x = packet.findChild("x", "jabber:x:signed");
        if (pgp != null && x != null) {
            Element status = packet.findChild("status");
            String msg = status != null ? status.getContent() : "";
            contact.setPgpKeyId(pgp.fetchKeyId(account, msg, x.getContent()));
        }
        boolean online = sizeBefore < contact.getPresences().size();
        mXmppConnectionService.onContactStatusChanged.onContactStatusChanged(contact, online);
    } else if (type.equals("unavailable")) {
        if (contact.setLastseen(AbstractParser.parseTimestamp(packet, 0L, true))) {
            contact.flagInactive();
        }
        if (from.isBareJid()) {
            contact.clearPresences();
        } else {
            contact.removePresence(from.getResourcepart());
        }
        mXmppConnectionService.onContactStatusChanged.onContactStatusChanged(contact, false);
    } else if (type.equals("subscribe")) {
        if (contact.getOption(Contact.Options.PREEMPTIVE_GRANT)) {
            mXmppConnectionService.sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
        } else {
            contact.setOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
            final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, contact.getJid().toBareJid(), false, false);
            final String statusMessage = packet.findChildContent("status");
            if (statusMessage != null && !statusMessage.isEmpty() && conversation.countMessages() == 0) {
                conversation.add(new Message(conversation, statusMessage, Message.ENCRYPTION_NONE, Message.STATUS_RECEIVED));
            }
        }
    }
    mXmppConnectionService.updateRosterUi();
}
Also used : PresenceGenerator(de.pixart.messenger.generator.PresenceGenerator) Jid(de.pixart.messenger.xmpp.jid.Jid) Message(de.pixart.messenger.entities.Message) Element(de.pixart.messenger.xml.Element) PgpEngine(de.pixart.messenger.crypto.PgpEngine) Conversation(de.pixart.messenger.entities.Conversation) Avatar(de.pixart.messenger.xmpp.pep.Avatar) Contact(de.pixart.messenger.entities.Contact) Presence(de.pixart.messenger.entities.Presence)

Example 65 with Element

use of de.pixart.messenger.xml.Element in project Pix-Art-Messenger by kriztan.

the class JingleConnection method init.

public void init(Account account, JinglePacket packet) {
    this.mJingleStatus = JINGLE_STATUS_INITIATED;
    Conversation conversation = this.mXmppConnectionService.findOrCreateConversation(account, packet.getFrom().toBareJid(), false, true);
    this.message = new Message(conversation, "", Message.ENCRYPTION_NONE);
    this.message.setStatus(Message.STATUS_RECEIVED);
    this.mStatus = Transferable.STATUS_OFFER;
    this.message.setTransferable(this);
    final Jid from = packet.getFrom();
    this.message.setCounterpart(from);
    this.account = account;
    this.initiator = packet.getFrom();
    this.responder = this.account.getJid();
    this.sessionId = packet.getSessionId();
    Content content = packet.getJingleContent();
    this.contentCreator = content.getAttribute("creator");
    this.contentName = content.getAttribute("name");
    this.transportId = content.getTransportId();
    this.mergeCandidates(JingleCandidate.parse(content.socks5transport().getChildren()));
    this.ftVersion = content.getVersion();
    if (ftVersion == null) {
        this.sendCancel();
        this.fail();
        return;
    }
    this.fileOffer = content.getFileOffer(this.ftVersion);
    mXmppConnectionService.sendIqPacket(account, packet.generateResponse(IqPacket.TYPE.RESULT), null);
    if (fileOffer != null) {
        Element encrypted = fileOffer.findChild("encrypted", AxolotlService.PEP_PREFIX);
        if (encrypted != null) {
            this.mXmppAxolotlMessage = XmppAxolotlMessage.fromElement(encrypted, packet.getFrom().toBareJid());
        }
        Element fileSize = fileOffer.findChild("size");
        Element fileNameElement = fileOffer.findChild("name");
        if (fileNameElement != null) {
            String[] filename = fileNameElement.getContent().toLowerCase(Locale.US).toLowerCase().split("\\.");
            String filename_new = fileDateFormat.format(new Date(message.getTimeSent())) + "_" + message.getUuid().substring(0, 4);
            String extension = filename[filename.length - 1];
            if (VALID_IMAGE_EXTENSIONS.contains(extension)) {
                message.setType(Message.TYPE_IMAGE);
                message.setRelativeFilePath(filename_new + "." + extension);
            } else if (VALID_CRYPTO_EXTENSIONS.contains(filename[filename.length - 1])) {
                if (filename.length == 3) {
                    extension = filename[filename.length - 2];
                    if (VALID_IMAGE_EXTENSIONS.contains(extension)) {
                        message.setType(Message.TYPE_IMAGE);
                        message.setRelativeFilePath(filename_new + "." + extension);
                    } else {
                        message.setType(Message.TYPE_FILE);
                    }
                    if (filename[filename.length - 1].equals("otr")) {
                        message.setEncryption(Message.ENCRYPTION_OTR);
                    } else {
                        message.setEncryption(Message.ENCRYPTION_PGP);
                    }
                }
            } else {
                message.setType(Message.TYPE_FILE);
            }
            if (message.getType() == Message.TYPE_FILE) {
                String suffix = "";
                if (!fileNameElement.getContent().isEmpty()) {
                    String[] parts = fileNameElement.getContent().split("/");
                    suffix = parts[parts.length - 1];
                    if (message.getEncryption() == Message.ENCRYPTION_OTR && suffix.endsWith(".otr")) {
                        suffix = suffix.substring(0, suffix.length() - 4);
                    } else if (message.getEncryption() == Message.ENCRYPTION_PGP && (suffix.endsWith(".pgp") || suffix.endsWith(".gpg"))) {
                        suffix = suffix.substring(0, suffix.length() - 4);
                    }
                }
                message.setRelativeFilePath(filename_new + "_" + suffix);
            }
            long size = Long.parseLong(fileSize.getContent());
            message.setBody(Long.toString(size));
            conversation.add(message);
            mJingleConnectionManager.updateConversationUi(true);
            if (mJingleConnectionManager.hasStoragePermission() && size < this.mJingleConnectionManager.getAutoAcceptFileSize() && mXmppConnectionService.isDataSaverDisabled()) {
                Log.d(Config.LOGTAG, "auto accepting file from " + packet.getFrom());
                this.acceptedAutomatically = true;
                this.sendAccept();
            } else {
                message.markUnread();
                Log.d(Config.LOGTAG, "not auto accepting new file offer with size: " + size + " allowed size:" + this.mJingleConnectionManager.getAutoAcceptFileSize());
                this.mXmppConnectionService.getNotificationService().push(message);
            }
            this.file = this.mXmppConnectionService.getFileBackend().getFile(message, false);
            if (mXmppAxolotlMessage != null) {
                XmppAxolotlMessage.XmppAxolotlKeyTransportMessage transportMessage = account.getAxolotlService().processReceivingKeyTransportMessage(mXmppAxolotlMessage, false);
                if (transportMessage != null) {
                    message.setEncryption(Message.ENCRYPTION_AXOLOTL);
                    this.file.setKey(transportMessage.getKey());
                    this.file.setIv(transportMessage.getIv());
                    message.setFingerprint(transportMessage.getFingerprint());
                } else {
                    Log.d(Config.LOGTAG, "could not process KeyTransportMessage");
                }
            } else if (message.getEncryption() == Message.ENCRYPTION_OTR) {
                byte[] key = conversation.getSymmetricKey();
                if (key == null) {
                    this.sendCancel();
                    this.fail();
                    return;
                } else {
                    this.file.setKeyAndIv(key);
                }
            }
            this.file.setExpectedSize(size);
            message.resetFileParams();
            Log.d(Config.LOGTAG, "receiving file: expecting size of " + this.file.getExpectedSize());
        } else {
            this.sendCancel();
            this.fail();
        }
    } else {
        this.sendCancel();
        this.fail();
    }
}
Also used : XmppAxolotlMessage(de.pixart.messenger.crypto.axolotl.XmppAxolotlMessage) Message(de.pixart.messenger.entities.Message) Jid(de.pixart.messenger.xmpp.jid.Jid) Content(de.pixart.messenger.xmpp.jingle.stanzas.Content) Element(de.pixart.messenger.xml.Element) Conversation(de.pixart.messenger.entities.Conversation) XmppAxolotlMessage(de.pixart.messenger.crypto.axolotl.XmppAxolotlMessage) Date(java.util.Date)

Aggregations

Element (de.pixart.messenger.xml.Element)100 IqPacket (de.pixart.messenger.xmpp.stanzas.IqPacket)48 Account (de.pixart.messenger.entities.Account)23 Jid (de.pixart.messenger.xmpp.jid.Jid)19 OnIqPacketReceived (de.pixart.messenger.xmpp.OnIqPacketReceived)17 Contact (de.pixart.messenger.entities.Contact)9 MessagePacket (de.pixart.messenger.xmpp.stanzas.MessagePacket)8 ArrayList (java.util.ArrayList)7 Conversation (de.pixart.messenger.entities.Conversation)6 IOException (java.io.IOException)6 Data (de.pixart.messenger.xmpp.forms.Data)5 Avatar (de.pixart.messenger.xmpp.pep.Avatar)5 HashSet (java.util.HashSet)5 AxolotlService (de.pixart.messenger.crypto.axolotl.AxolotlService)4 MucOptions (de.pixart.messenger.entities.MucOptions)4 ECPublicKey (org.whispersystems.libsignal.ecc.ECPublicKey)4 PreKeyBundle (org.whispersystems.libsignal.state.PreKeyBundle)4 Pair (android.util.Pair)3 Bookmark (de.pixart.messenger.entities.Bookmark)3 Message (de.pixart.messenger.entities.Message)3