Search in sources :

Example 11 with Stanza

use of org.jivesoftware.smack.packet.Stanza in project xabber-android by redsolution.

the class NextMamManager method parseAndSaveMessageFromMamResult.

/**
 * PARSING
 */
private void parseAndSaveMessageFromMamResult(Realm realm, AccountJid account, Forwarded forwarded) {
    Stanza stanza = forwarded.getForwardedStanza();
    AccountItem accountItem = AccountManager.getInstance().getAccount(account);
    Jid user = stanza.getFrom().asBareJid();
    if (user.equals(account.getFullJid().asBareJid()))
        user = stanza.getTo().asBareJid();
    try {
        AbstractChat chat = MessageManager.getInstance().getOrCreateChat(account, UserJid.from(user));
        MessageItem messageItem = parseMessage(accountItem, account, chat.getUser(), forwarded, null);
        if (messageItem != null) {
            saveOrUpdateMessages(realm, Collections.singletonList(messageItem), true);
            updateLastMessageId(chat, realm);
        }
    } catch (UserJid.UserJidCreateException e) {
        LogManager.d(LOG_TAG, e.toString());
    }
}
Also used : MessageItem(com.xabber.android.data.database.messagerealm.MessageItem) AccountJid(com.xabber.android.data.entity.AccountJid) UserJid(com.xabber.android.data.entity.UserJid) Jid(org.jxmpp.jid.Jid) AccountItem(com.xabber.android.data.account.AccountItem) AbstractChat(com.xabber.android.data.message.AbstractChat) Stanza(org.jivesoftware.smack.packet.Stanza) UserJid(com.xabber.android.data.entity.UserJid)

Example 12 with Stanza

use of org.jivesoftware.smack.packet.Stanza in project xabber-android by redsolution.

the class NextMamManager method loadAllNewMessages.

private boolean loadAllNewMessages(Realm realm, AccountItem accountItem, String lastArchivedId) {
    if (accountItem.getLoadHistorySettings() != LoadHistorySettings.all || !isSupported(accountItem.getAccount()))
        return true;
    LogManager.d(LOG_TAG, "load new messages");
    List<Forwarded> messages = new ArrayList<>();
    boolean complete = false;
    String id = lastArchivedId;
    int pageLoaded = 0;
    // Request all new messages after last archived id
    while (!complete && id != null && pageLoaded < 2) {
        MamManager.MamQueryResult queryResult = requestMessagesFromId(accountItem, null, id);
        if (queryResult != null) {
            messages.addAll(queryResult.forwardedMessages);
            complete = queryResult.mamFin.isComplete();
            id = getNextId(queryResult);
            pageLoaded++;
        } else
            complete = true;
    }
    if (!messages.isEmpty()) {
        HashMap<String, ArrayList<Forwarded>> messagesByChat = new HashMap<>();
        List<MessageItem> parsedMessages = new ArrayList<>();
        List<AbstractChat> chatsNeedUpdateLastMessageId = new ArrayList<>();
        // Sort messages by chat to separate lists
        for (Forwarded forwarded : messages) {
            Stanza stanza = forwarded.getForwardedStanza();
            Jid user = stanza.getFrom().asBareJid();
            if (user.equals(accountItem.getAccount().getFullJid().asBareJid()))
                user = stanza.getTo().asBareJid();
            if (!messagesByChat.containsKey(user.toString())) {
                messagesByChat.put(user.toString(), new ArrayList<Forwarded>());
            }
            ArrayList<Forwarded> list = messagesByChat.get(user.toString());
            if (list != null)
                list.add(forwarded);
        }
        // parse message lists
        for (Map.Entry<String, ArrayList<Forwarded>> entry : messagesByChat.entrySet()) {
            ArrayList<Forwarded> list = entry.getValue();
            if (list != null) {
                try {
                    AbstractChat chat = MessageManager.getInstance().getOrCreateChat(accountItem.getAccount(), UserJid.from(entry.getKey()));
                    // sort messages in list by timestamp
                    Collections.sort(list, new Comparator<Forwarded>() {

                        @Override
                        public int compare(Forwarded o1, Forwarded o2) {
                            DelayInformation delayInformation1 = o1.getDelayInformation();
                            long time1 = delayInformation1.getStamp().getTime();
                            DelayInformation delayInformation2 = o2.getDelayInformation();
                            long time2 = delayInformation2.getStamp().getTime();
                            return Long.valueOf(time1).compareTo(time2);
                        }
                    });
                    // parse messages and set previous id
                    parsedMessages.addAll(parseMessage(accountItem, accountItem.getAccount(), chat.getUser(), list, chat.getLastMessageId()));
                    chatsNeedUpdateLastMessageId.add(chat);
                } catch (UserJid.UserJidCreateException e) {
                    LogManager.d(LOG_TAG, e.toString());
                    continue;
                }
            }
        }
        // save messages to Realm
        saveOrUpdateMessages(realm, parsedMessages);
        for (AbstractChat chat : chatsNeedUpdateLastMessageId) {
            updateLastMessageId(chat, realm);
        }
    }
    return complete;
}
Also used : MessageItem(com.xabber.android.data.database.messagerealm.MessageItem) AccountJid(com.xabber.android.data.entity.AccountJid) UserJid(com.xabber.android.data.entity.UserJid) Jid(org.jxmpp.jid.Jid) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) AbstractChat(com.xabber.android.data.message.AbstractChat) Stanza(org.jivesoftware.smack.packet.Stanza) ArrayList(java.util.ArrayList) UserJid(com.xabber.android.data.entity.UserJid) MamManager(org.jivesoftware.smackx.mam.MamManager) DelayInformation(org.jivesoftware.smackx.delay.packet.DelayInformation) Forwarded(org.jivesoftware.smackx.forward.packet.Forwarded) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 13 with Stanza

use of org.jivesoftware.smack.packet.Stanza in project xabber-android by redsolution.

the class UploadService method startWork.

private void startWork(AccountJid account, UserJid user, List<String> filePaths, CharSequence uploadServerUrl, String existMessageId) {
    // get account item
    AccountItem accountItem = AccountManager.getInstance().getAccount(account);
    if (accountItem == null) {
        publishError(null, "Account not found");
        return;
    }
    // get upload jid
    Jid uploadJid;
    try {
        uploadJid = JidCreate.bareFrom(uploadServerUrl);
    } catch (XmppStringprepException e) {
        publishError(null, "Wrong upload jid");
        return;
    }
    final String fileMessageId;
    if (existMessageId == null) {
        // create fileMessage with files
        List<File> files = new ArrayList<>();
        for (String filePath : filePaths) {
            files.add(new File(filePath));
        }
        fileMessageId = MessageManager.getInstance().createFileMessage(account, user, files);
    } else
        // use existing fileMessage
        fileMessageId = existMessageId;
    HashMap<String, String> uploadedFilesUrls = new HashMap<>();
    List<String> notUploadedFilesPaths = new ArrayList<>();
    List<File> notUploadedFiles = new ArrayList<>();
    List<String> errors = new ArrayList<>();
    for (String filePath : filePaths) {
        if (needStop) {
            stopWork(fileMessageId);
            return;
        }
        try {
            File uncompressedFile = new File(filePath);
            final File file;
            // compress file if image
            if (FileManager.fileIsImage(uncompressedFile) && SettingsManager.connectionCompressImage()) {
                file = ImageCompressor.compressImage(uncompressedFile, getCompressedDirPath());
                if (file == null)
                    throw new Exception("Compress image failed");
            } else
                file = uncompressedFile;
            // request slot
            Stanza slot = requestSlot(accountItem, file, uploadJid);
            if (!(slot instanceof Slot))
                throw new Exception("Could not request upload slot");
            // upload file
            Response response = uploadFileToSlot(account, (Slot) slot, file);
            if (response.isSuccessful())
                uploadedFilesUrls.put(filePath, ((Slot) slot).getGetUrl());
            else
                throw new Exception("Upload failed: " + response.message());
        } catch (Exception e) {
            notUploadedFilesPaths.add(filePath);
            notUploadedFiles.add(new File(filePath));
            errors.add(e.toString());
        }
        publishProgress(fileMessageId, uploadedFilesUrls.size(), filePaths.size());
    }
    removeTempDirectory();
    // check that files are uploaded
    if (uploadedFilesUrls.size() == 0) {
        setErrorForMessage(fileMessageId, generateErrorDescriptionForFiles(notUploadedFilesPaths, errors));
        publishError(fileMessageId, "Could not upload any files");
        return;
    }
    // save results to Realm and send message
    MessageManager.getInstance().updateFileMessage(account, user, fileMessageId, uploadedFilesUrls, notUploadedFilesPaths);
    publishCompleted(fileMessageId);
    // if some files have errors move its to separate message
    if (notUploadedFilesPaths.size() > 0) {
        String messageId = MessageManager.getInstance().createFileMessage(account, user, notUploadedFiles);
        setErrorForMessage(messageId, generateErrorDescriptionForFiles(notUploadedFilesPaths, errors));
    }
}
Also used : UserJid(com.xabber.android.data.entity.UserJid) AccountJid(com.xabber.android.data.entity.AccountJid) Jid(org.jxmpp.jid.Jid) AccountItem(com.xabber.android.data.account.AccountItem) HashMap(java.util.HashMap) Stanza(org.jivesoftware.smack.packet.Stanza) ArrayList(java.util.ArrayList) XmppStringprepException(org.jxmpp.stringprep.XmppStringprepException) SmackException(org.jivesoftware.smack.SmackException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) XmppStringprepException(org.jxmpp.stringprep.XmppStringprepException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) XMPPException(org.jivesoftware.smack.XMPPException) Response(okhttp3.Response) Slot(com.xabber.xmpp.httpfileupload.Slot) File(java.io.File)

Example 14 with Stanza

use of org.jivesoftware.smack.packet.Stanza in project xabber-android by redsolution.

the class AbstractChat method parseForwardedMessage.

public RealmList<ForwardId> parseForwardedMessage(boolean ui, Stanza packet, String parentMessageId) {
    List<Forwarded> forwarded = ReferencesManager.getForwardedFromReferences(packet);
    if (forwarded.isEmpty())
        forwarded = ForwardManager.getForwardedFromStanza(packet);
    if (forwarded.isEmpty())
        return null;
    RealmList<ForwardId> forwardedIds = new RealmList<>();
    for (Forwarded forward : forwarded) {
        Stanza stanza = forward.getForwardedStanza();
        DelayInformation delayInformation = forward.getDelayInformation();
        Date timestamp = delayInformation.getStamp();
        if (stanza instanceof Message) {
            forwardedIds.add(new ForwardId(parseInnerMessage(ui, (Message) stanza, timestamp, parentMessageId)));
        }
    }
    return forwardedIds;
}
Also used : RealmList(io.realm.RealmList) DelayInformation(org.jivesoftware.smackx.delay.packet.DelayInformation) Message(org.jivesoftware.smack.packet.Message) Stanza(org.jivesoftware.smack.packet.Stanza) Forwarded(org.jivesoftware.smackx.forward.packet.Forwarded) ForwardId(com.xabber.android.data.database.messagerealm.ForwardId) Date(java.util.Date)

Example 15 with Stanza

use of org.jivesoftware.smack.packet.Stanza in project Smack by igniterealtime.

the class AbstractXMPPConnection method firePacketInterceptors.

/**
 * Process interceptors. Interceptors may modify the stanza that is about to be sent.
 * Since the thread that requested to send the stanza will invoke all interceptors, it
 * is important that interceptors perform their work as soon as possible so that the
 * thread does not remain blocked for a long period.
 *
 * @param packet the stanza that is going to be sent to the server.
 * @return the, potentially modified stanza, after the interceptors are run.
 */
private Stanza firePacketInterceptors(Stanza packet) {
    List<StanzaListener> interceptorsToInvoke = new LinkedList<>();
    synchronized (interceptors) {
        for (InterceptorWrapper interceptorWrapper : interceptors.values()) {
            if (interceptorWrapper.filterMatches(packet)) {
                interceptorsToInvoke.add(interceptorWrapper.getInterceptor());
            }
        }
    }
    for (StanzaListener interceptor : interceptorsToInvoke) {
        try {
            interceptor.processStanza(packet);
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Packet interceptor threw exception", e);
        }
    }
    final Stanza stanzaAfterInterceptors;
    if (packet instanceof Message) {
        Message message = (Message) packet;
        stanzaAfterInterceptors = fireMessageOrPresenceInterceptors(message, messageInterceptors);
    } else if (packet instanceof Presence) {
        Presence presence = (Presence) packet;
        stanzaAfterInterceptors = fireMessageOrPresenceInterceptors(presence, presenceInterceptors);
    } else {
        // We do not (yet) support interceptors for IQ stanzas.
        assert packet instanceof IQ;
        stanzaAfterInterceptors = packet;
    }
    return stanzaAfterInterceptors;
}
Also used : Message(org.jivesoftware.smack.packet.Message) Stanza(org.jivesoftware.smack.packet.Stanza) IQ(org.jivesoftware.smack.packet.IQ) ErrorIQ(org.jivesoftware.smack.packet.ErrorIQ) Presence(org.jivesoftware.smack.packet.Presence) MessageOrPresence(org.jivesoftware.smack.packet.MessageOrPresence) LinkedList(java.util.LinkedList) SmackSaslException(org.jivesoftware.smack.SmackException.SmackSaslException) XMPPErrorException(org.jivesoftware.smack.XMPPException.XMPPErrorException) FailedNonzaException(org.jivesoftware.smack.XMPPException.FailedNonzaException) XmppStringprepException(org.jxmpp.stringprep.XmppStringprepException) NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) StreamErrorException(org.jivesoftware.smack.XMPPException.StreamErrorException) XmlPullParserException(org.jivesoftware.smack.xml.XmlPullParserException) NoResponseException(org.jivesoftware.smack.SmackException.NoResponseException) IOException(java.io.IOException) SecurityRequiredException(org.jivesoftware.smack.SmackException.SecurityRequiredException) SmackParsingException(org.jivesoftware.smack.parsing.SmackParsingException) NotLoggedInException(org.jivesoftware.smack.SmackException.NotLoggedInException) AlreadyLoggedInException(org.jivesoftware.smack.SmackException.AlreadyLoggedInException) SASLErrorException(org.jivesoftware.smack.sasl.SASLErrorException) AlreadyConnectedException(org.jivesoftware.smack.SmackException.AlreadyConnectedException) SmackWrappedException(org.jivesoftware.smack.SmackException.SmackWrappedException) SecurityRequiredByClientException(org.jivesoftware.smack.SmackException.SecurityRequiredByClientException) ResourceBindingNotOfferedException(org.jivesoftware.smack.SmackException.ResourceBindingNotOfferedException)

Aggregations

Stanza (org.jivesoftware.smack.packet.Stanza)101 StanzaListener (org.jivesoftware.smack.StanzaListener)24 Test (org.junit.Test)22 IQ (org.jivesoftware.smack.packet.IQ)20 Test (org.junit.jupiter.api.Test)18 XMPPConnection (org.jivesoftware.smack.XMPPConnection)14 Message (org.jivesoftware.smack.packet.Message)14 ArrayList (java.util.ArrayList)11 SmackException (org.jivesoftware.smack.SmackException)11 Jid (org.jxmpp.jid.Jid)11 IOException (java.io.IOException)9 NotConnectedException (org.jivesoftware.smack.SmackException.NotConnectedException)8 StanzaFilter (org.jivesoftware.smack.filter.StanzaFilter)8 Bytestream (org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream)7 DelayInformation (org.jivesoftware.smackx.delay.packet.DelayInformation)7 XMPPErrorException (org.jivesoftware.smack.XMPPException.XMPPErrorException)6 StanzaTypeFilter (org.jivesoftware.smack.filter.StanzaTypeFilter)6 Protocol (org.jivesoftware.util.Protocol)6 EntityFullJid (org.jxmpp.jid.EntityFullJid)6 LinkedList (java.util.LinkedList)5