Search in sources :

Example 21 with Message

use of eu.siacs.conversations.entities.Message in project Conversations by siacs.

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", "jabber:x:oob");
    final boolean isOob = oob != null && body != null && body.equals(oob.findChildContent("url"));
    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;
    boolean isProperlyAddressed = (to != null) && (!to.isBareJid() || account.countPresences() == 0);
    boolean isMucStatusMessage = from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
    if (packet.fromAccount(account)) {
        status = Message.STATUS_SEND;
        counterpart = to != null ? to : account.getJid();
    } else {
        status = Message.STATUS_RECEIVED;
        counterpart = from;
    }
    Invite invite = extractInvite(account, packet);
    if (invite != null && invite.execute(account)) {
        return;
    }
    if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), isTypeGroupChat, packet)) {
        mXmppConnectionService.updateConversationUi();
    }
    if ((body != null || pgpEncrypted != null || axolotlEncrypted != null) && !isMucStatusMessage) {
        Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.toBareJid(), isTypeGroupChat, false, query);
        final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
        if (serverMsgId == null) {
            serverMsgId = extractStanzaId(packet, isTypeGroupChat, conversation);
        }
        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);
            if (message == null) {
                return;
            }
            if (conversationMultiMode) {
                message.setTrueCounterpart(origin);
            }
        } 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);
        message.setOob(isOob);
        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 (Config.PARSE_REAL_JID_FROM_MUC_MAM) {
                trueCounterpart = getTrueCounterpart(query != null ? mucUserElement : null, 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()) {
            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);
                        replacedMessage.setEncryption(message.getEncryption());
                        if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
                            replacedMessage.markUnread();
                        }
                        mXmppConnectionService.updateMessage(replacedMessage, uuid);
                        mXmppConnectionService.getNotificationService().updateNotification(false);
                        if (mXmppConnectionService.confirmMessages() && (replacedMessage.trusted() || replacedMessage.getType() == Message.TYPE_PRIVATE) && remoteMsgId != null && !isForwarded && !isTypeGroupChat) {
                            sendMessageReceipts(account, packet);
                        }
                        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 && conversation.hasDuplicateMessage(message)) {
            Log.d(Config.LOGTAG, "skipping duplicate message from " + message.getCounterpart().toString() + " " + message.getBody());
            return;
        }
        if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
            conversation.prepend(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) {
            mXmppConnectionService.updateConversationUi();
        }
        if (mXmppConnectionService.confirmMessages() && (message.trusted() || message.getType() == Message.TYPE_PRIVATE) && remoteMsgId != null && !isForwarded && !isTypeGroupChat) {
            sendMessageReceipts(account, packet);
        }
        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() != Message.Decision.NEVER && manager.getAutoAcceptFileSize() > 0) {
            manager.createNewDownloadConnection(message);
        } else if (notify) {
            if (query == null) {
                mXmppConnectionService.getNotificationService().push(message);
            } else if (query.isCatchup()) {
                // mam catchup
                mXmppConnectionService.getNotificationService().pushFromBacklog(message);
            }
        }
    } else if (!packet.hasChild("body")) {
        //no body
        Conversation conversation = mXmppConnectionService.find(account, from.toBareJid());
        if (isTypeGroupChat) {
            if (packet.hasChild("subject")) {
                if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
                    conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
                    String subject = packet.findChildContent("subject");
                    conversation.getMucOptions().setSubject(subject);
                    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()) {
                        conversation.getMucOptions().updateUser(user);
                        mXmppConnectionService.getAvatarService().clear(conversation);
                        mXmppConnectionService.updateMucRosterUi();
                        mXmppConnectionService.updateConversationUi();
                        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);
                            }
                        }
                    }
                }
            }
        }
    }
    Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
    if (received == null) {
        received = packet.findChild("received", "urn:xmpp:receipts");
    }
    if (received != null && !packet.fromAccount(account)) {
        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) {
        if (packet.fromAccount(account)) {
            Conversation conversation = mXmppConnectionService.find(account, counterpart.toBareJid());
            if (conversation != null) {
                mXmppConnectionService.markRead(conversation);
            }
        } else {
            final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), displayed.getAttribute("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();
            }
        }
    }
    Element event = original.findChild("event", "http://jabber.org/protocol/pubsub#event");
    if (event != null) {
        parseEvent(event, original.getFrom(), account);
    }
    String nick = packet.findChildContent("nick", "http://jabber.org/protocol/nick");
    if (nick != null) {
        Contact contact = account.getRoster().getContact(from);
        contact.setPresenceName(nick);
    }
}
Also used : Jid(eu.siacs.conversations.xmpp.jid.Jid) XmppAxolotlMessage(eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage) Message(eu.siacs.conversations.entities.Message) Element(eu.siacs.conversations.xml.Element) Conversation(eu.siacs.conversations.entities.Conversation) Contact(eu.siacs.conversations.entities.Contact) MessagePacket(eu.siacs.conversations.xmpp.stanzas.MessagePacket) MucOptions(eu.siacs.conversations.entities.MucOptions) MessageArchiveService(eu.siacs.conversations.services.MessageArchiveService) Bookmark(eu.siacs.conversations.entities.Bookmark) HttpConnectionManager(eu.siacs.conversations.http.HttpConnectionManager)

Example 22 with Message

use of eu.siacs.conversations.entities.Message in project Conversations by siacs.

the class MessageParser method parseAxolotlChat.

private Message parseAxolotlChat(Element axolotlMessage, Jid from, Conversation conversation, int status) {
    AxolotlService service = conversation.getAccount().getAxolotlService();
    XmppAxolotlMessage xmppAxolotlMessage;
    try {
        xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlMessage, from.toBareJid());
    } catch (Exception e) {
        Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": invalid omemo message received " + e.getMessage());
        return null;
    }
    XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = service.processReceivingPayloadMessage(xmppAxolotlMessage);
    if (plaintextMessage != null) {
        Message finishedMessage = new Message(conversation, plaintextMessage.getPlaintext(), Message.ENCRYPTION_AXOLOTL, status);
        finishedMessage.setFingerprint(plaintextMessage.getFingerprint());
        Log.d(Config.LOGTAG, AxolotlService.getLogprefix(finishedMessage.getConversation().getAccount()) + " Received Message with session fingerprint: " + plaintextMessage.getFingerprint());
        return finishedMessage;
    } else {
        return null;
    }
}
Also used : AxolotlService(eu.siacs.conversations.crypto.axolotl.AxolotlService) XmppAxolotlMessage(eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage) Message(eu.siacs.conversations.entities.Message) XmppAxolotlMessage(eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage)

Example 23 with Message

use of eu.siacs.conversations.entities.Message in project Conversations by siacs.

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();
        contact.setPresenceName(packet.findChildContent("nick", "http://jabber.org/protocol/nick"));
        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", "urn:xmpp:idle:1");
        if (idle != null) {
            contact.flagInactive();
            String since = idle.getAttribute("since");
            try {
                contact.setLastseen(AbstractParser.parseTimestamp(since));
            } catch (NullPointerException | ParseException e) {
                contact.setLastseen(System.currentTimeMillis());
            }
        } else {
            contact.flagActive();
            contact.setLastseen(AbstractParser.parseTimestamp(packet));
        }
        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 (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);
            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(eu.siacs.conversations.generator.PresenceGenerator) Jid(eu.siacs.conversations.xmpp.jid.Jid) Message(eu.siacs.conversations.entities.Message) Element(eu.siacs.conversations.xml.Element) PgpEngine(eu.siacs.conversations.crypto.PgpEngine) Conversation(eu.siacs.conversations.entities.Conversation) Avatar(eu.siacs.conversations.xmpp.pep.Avatar) Contact(eu.siacs.conversations.entities.Contact) Presence(eu.siacs.conversations.entities.Presence) ParseException(java.text.ParseException)

Example 24 with Message

use of eu.siacs.conversations.entities.Message in project Conversations by siacs.

the class DatabaseBackend method getMessages.

public ArrayList<Message> getMessages(Conversation conversation, int limit, long timestamp) {
    ArrayList<Message> list = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor;
    if (timestamp == -1) {
        String[] selectionArgs = { conversation.getUuid() };
        cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION + "=?", selectionArgs, null, null, Message.TIME_SENT + " DESC", String.valueOf(limit));
    } else {
        String[] selectionArgs = { conversation.getUuid(), Long.toString(timestamp) };
        cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION + "=? and " + Message.TIME_SENT + "<?", selectionArgs, null, null, Message.TIME_SENT + " DESC", String.valueOf(limit));
    }
    if (cursor.getCount() > 0) {
        cursor.moveToLast();
        do {
            Message message = Message.fromCursor(cursor);
            if (message != null) {
                message.setConversation(conversation);
                list.add(message);
            }
        } while (cursor.moveToPrevious());
    }
    cursor.close();
    return list;
}
Also used : Message(eu.siacs.conversations.entities.Message) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor)

Example 25 with Message

use of eu.siacs.conversations.entities.Message in project Conversations by siacs.

the class NotificationService method buildSingleConversations.

private Builder buildSingleConversations(final ArrayList<Message> messages) {
    final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
    if (messages.size() >= 1) {
        final Conversation conversation = messages.get(0).getConversation();
        mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService().get(conversation, getPixel(64)));
        mBuilder.setContentTitle(conversation.getName());
        if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
            int count = messages.size();
            mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
        } else {
            Message message;
            if ((message = getImage(messages)) != null) {
                modifyForImage(mBuilder, message, messages);
            } else {
                modifyForTextOnly(mBuilder, messages);
            }
            RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
            NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(R.drawable.ic_send_text_offline, "Reply", createReplyIntent(conversation, false)).addRemoteInput(remoteInput).build();
            NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_send_text_offline, "Reply", createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
            mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                mBuilder.addAction(replyAction);
            }
            if ((message = getFirstDownloadableMessage(messages)) != null) {
                mBuilder.addAction(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? R.drawable.ic_file_download_white_24dp : R.drawable.ic_action_download, mXmppConnectionService.getResources().getString(R.string.download_x_file, UIHelper.getFileDescriptionString(mXmppConnectionService, message)), createDownloadIntent(message));
            }
            if ((message = getFirstLocationMessage(messages)) != null) {
                mBuilder.addAction(R.drawable.ic_room_white_24dp, mXmppConnectionService.getString(R.string.show_location), createShowLocationIntent(message));
            }
        }
        if (conversation.getMode() == Conversation.MODE_SINGLE) {
            Contact contact = conversation.getContact();
            Uri systemAccount = contact.getSystemAccount();
            if (systemAccount != null) {
                mBuilder.addPerson(systemAccount.toString());
            }
        }
        mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
        mBuilder.setSmallIcon(R.drawable.ic_notification);
        mBuilder.setDeleteIntent(createDeleteIntent(conversation));
        mBuilder.setContentIntent(createContentIntent(conversation));
    }
    return mBuilder;
}
Also used : RemoteInput(android.support.v4.app.RemoteInput) Message(eu.siacs.conversations.entities.Message) Builder(android.support.v4.app.NotificationCompat.Builder) NotificationCompat(android.support.v4.app.NotificationCompat) Conversation(eu.siacs.conversations.entities.Conversation) Uri(android.net.Uri) Contact(eu.siacs.conversations.entities.Contact)

Aggregations

Message (eu.siacs.conversations.entities.Message)39 XmppAxolotlMessage (eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage)16 Conversation (eu.siacs.conversations.entities.Conversation)12 Account (eu.siacs.conversations.entities.Account)9 Jid (eu.siacs.conversations.xmpp.jid.Jid)7 PendingIntent (android.app.PendingIntent)5 InvalidJidException (eu.siacs.conversations.xmpp.jid.InvalidJidException)5 MessagePacket (eu.siacs.conversations.xmpp.stanzas.MessagePacket)5 ArrayList (java.util.ArrayList)5 SuppressLint (android.annotation.SuppressLint)4 SpannableString (android.text.SpannableString)4 NotificationCompat (android.support.v4.app.NotificationCompat)3 StyleSpan (android.text.style.StyleSpan)3 View (android.view.View)3 TextView (android.widget.TextView)3 PgpEngine (eu.siacs.conversations.crypto.PgpEngine)3 Contact (eu.siacs.conversations.entities.Contact)3 Element (eu.siacs.conversations.xml.Element)3 Cursor (android.database.Cursor)2 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)2