Search in sources :

Example 1 with Slot

use of com.xabber.xmpp.httpfileupload.Slot in project xabber-android by redsolution.

the class HttpFileUploadManager method uploadFile.

public void uploadFile(final String account, final String user, final String filePath) {
    final String uploadServerUrl = uploadServers.get(account);
    if (uploadServerUrl == null) {
        return;
    }
    final File file = new File(filePath);
    final Request httpFileUpload = new Request();
    httpFileUpload.setFilename(file.getName());
    httpFileUpload.setSize(String.valueOf(file.length()));
    httpFileUpload.setTo(uploadServerUrl);
    try {
        ConnectionManager.getInstance().sendRequest(account, httpFileUpload, new OnResponseListener() {

            @Override
            public void onReceived(final String account, String packetId, IQ iq) {
                if (!httpFileUpload.getStanzaId().equals(packetId) || !(iq instanceof Slot)) {
                    return;
                }
                uploadFileToSlot(account, (Slot) iq);
            }

            private void uploadFileToSlot(final String account, final Slot slot) {
                AsyncHttpClient client = new AsyncHttpClient();
                client.setLoggingEnabled(SettingsManager.debugLog());
                client.setResponseTimeout(60 * 1000);
                FileEntity fileEntity = new FileEntity(file, ContentType.DEFAULT_BINARY);
                LogManager.i(this, "fileEntity.getContentLength() " + fileEntity.getContentLength());
                client.put(Application.getInstance(), slot.getPutUrl(), fileEntity, CONTENT_TYPE, new AsyncHttpResponseHandler() {

                    MessageItem fileMessage;

                    @Override
                    public void onStart() {
                        super.onStart();
                        LogManager.i(this, "uploadFileToSlot onStart");
                        fileMessage = MessageManager.getInstance().createFileMessage(account, user, file);
                    }

                    @Override
                    public void onSuccess(int i, Header[] headers, byte[] bytes) {
                        LogManager.i(this, "uploadFileToSlot onSuccess " + i);
                        MessageManager.getInstance().replaceMessage(account, user, fileMessage, slot.getGetUrl());
                        if (FileManager.fileIsImage(file)) {
                            saveImageToCache(slot.getGetUrl(), file);
                        }
                    }

                    @Override
                    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                        LogManager.i(this, "uploadFileToSlot onFailure " + i);
                        MessageManager.getInstance().updateMessageWithError(account, user, fileMessage, file.getName());
                    }

                    @Override
                    public void onRetry(int retryNo) {
                        super.onRetry(retryNo);
                        LogManager.i(this, "uploadFileToSlot onRetry " + retryNo);
                    }

                    @Override
                    public void onCancel() {
                        super.onCancel();
                        LogManager.i(this, "uploadFileToSlot onCancel");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        LogManager.i(this, "uploadFileToSlot onFinish");
                    }
                });
            }

            @Override
            public void onError(String account, String packetId, IQ iq) {
                LogManager.i(this, "On HTTP file upload slot error");
                Application.getInstance().onError(R.string.http_file_upload_slot_error);
            }

            @Override
            public void onTimeout(String account, String packetId) {
            }

            @Override
            public void onDisconnect(String account, String packetId) {
            }
        });
    } catch (NetworkException e) {
        e.printStackTrace();
    }
}
Also used : MessageItem(com.xabber.android.data.message.MessageItem) FileEntity(cz.msebera.android.httpclient.entity.FileEntity) Request(com.xabber.xmpp.httpfileupload.Request) IQ(org.jivesoftware.smack.packet.IQ) AsyncHttpResponseHandler(com.loopj.android.http.AsyncHttpResponseHandler) OnResponseListener(com.xabber.android.data.connection.OnResponseListener) Slot(com.xabber.xmpp.httpfileupload.Slot) File(java.io.File) NetworkException(com.xabber.android.data.NetworkException) AsyncHttpClient(com.loopj.android.http.AsyncHttpClient)

Example 2 with Slot

use of com.xabber.xmpp.httpfileupload.Slot 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 3 with Slot

use of com.xabber.xmpp.httpfileupload.Slot in project xabber-android by redsolution.

the class HttpFileUploadManager method uploadFile.

public void uploadFile(final AccountJid account, final UserJid user, final String filePath) {
    final Jid uploadServerUrl = uploadServers.get(account);
    if (uploadServerUrl == null) {
        return;
    }
    AccountItem accountItem = AccountManager.getInstance().getAccount(account);
    if (accountItem == null) {
        return;
    }
    final File file = new File(filePath);
    final com.xabber.xmpp.httpfileupload.Request httpFileUpload = new com.xabber.xmpp.httpfileupload.Request();
    httpFileUpload.setFilename(file.getName());
    httpFileUpload.setSize(String.valueOf(file.length()));
    httpFileUpload.setTo(uploadServerUrl);
    try {
        accountItem.getConnection().sendIqWithResponseCallback(httpFileUpload, new StanzaListener() {

            @Override
            public void processStanza(Stanza packet) throws SmackException.NotConnectedException, InterruptedException {
                if (!(packet instanceof Slot)) {
                    return;
                }
                uploadFileToSlot(account, (Slot) packet);
            }

            private void uploadFileToSlot(final AccountJid account, final Slot slot) {
                SSLSocketFactory sslSocketFactory = null;
                MemorizingTrustManager mtm = CertificateManager.getInstance().getNewFileUploadManager(account);
                final SSLContext sslContext;
                try {
                    sslContext = SSLContext.getInstance("SSL");
                    sslContext.init(null, new X509TrustManager[] { mtm }, new java.security.SecureRandom());
                    sslSocketFactory = sslContext.getSocketFactory();
                } catch (NoSuchAlgorithmException | KeyManagementException e) {
                    return;
                }
                OkHttpClient client = new OkHttpClient().newBuilder().sslSocketFactory(sslSocketFactory).hostnameVerifier(mtm.wrapHostnameVerifier(new org.apache.http.conn.ssl.StrictHostnameVerifier())).writeTimeout(5, TimeUnit.MINUTES).connectTimeout(5, TimeUnit.MINUTES).readTimeout(5, TimeUnit.MINUTES).build();
                Request request = new Request.Builder().url(slot.getPutUrl()).put(RequestBody.create(CONTENT_TYPE, file)).build();
                final String fileMessageId;
                fileMessageId = MessageManager.getInstance().createFileMessage(account, user, file);
                LogManager.i(HttpFileUploadManager.this, "starting upload file to " + slot.getPutUrl() + " size " + file.length());
                client.newCall(request).enqueue(new Callback() {

                    @Override
                    public void onFailure(Call call, IOException e) {
                        LogManager.i(HttpFileUploadManager.this, "onFailure " + e.getMessage());
                        MessageManager.getInstance().updateMessageWithError(fileMessageId, e.toString());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        LogManager.i(HttpFileUploadManager.this, "onResponse " + response.isSuccessful() + " " + response.body().string());
                        if (response.isSuccessful()) {
                            MessageManager.getInstance().updateFileMessage(account, user, fileMessageId, slot.getGetUrl());
                        } else {
                            MessageManager.getInstance().updateMessageWithError(fileMessageId, response.message());
                        }
                    }
                });
            }
        }, new ExceptionCallback() {

            @Override
            public void processException(Exception exception) {
                LogManager.i(this, "On HTTP file upload slot error");
                LogManager.exception(this, exception);
                Application.getInstance().onError(R.string.http_file_upload_slot_error);
            }
        });
    } catch (SmackException.NotConnectedException | InterruptedException e) {
        LogManager.exception(this, e);
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) AccountItem(com.xabber.android.data.account.AccountItem) StanzaListener(org.jivesoftware.smack.StanzaListener) AccountJid(com.xabber.android.data.entity.AccountJid) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Call(okhttp3.Call) UserJid(com.xabber.android.data.entity.UserJid) AccountJid(com.xabber.android.data.entity.AccountJid) DomainBareJid(org.jxmpp.jid.DomainBareJid) Jid(org.jxmpp.jid.Jid) Stanza(org.jivesoftware.smack.packet.Stanza) Request(okhttp3.Request) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) ExceptionCallback(org.jivesoftware.smack.ExceptionCallback) SmackException(org.jivesoftware.smack.SmackException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) XMPPException(org.jivesoftware.smack.XMPPException) MemorizingTrustManager(de.duenndns.ssl.MemorizingTrustManager) Response(okhttp3.Response) Callback(okhttp3.Callback) ExceptionCallback(org.jivesoftware.smack.ExceptionCallback) X509TrustManager(javax.net.ssl.X509TrustManager) Slot(com.xabber.xmpp.httpfileupload.Slot) File(java.io.File)

Aggregations

Slot (com.xabber.xmpp.httpfileupload.Slot)3 File (java.io.File)3 AccountItem (com.xabber.android.data.account.AccountItem)2 AccountJid (com.xabber.android.data.entity.AccountJid)2 UserJid (com.xabber.android.data.entity.UserJid)2 IOException (java.io.IOException)2 KeyManagementException (java.security.KeyManagementException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 Response (okhttp3.Response)2 SmackException (org.jivesoftware.smack.SmackException)2 XMPPException (org.jivesoftware.smack.XMPPException)2 Stanza (org.jivesoftware.smack.packet.Stanza)2 Jid (org.jxmpp.jid.Jid)2 AsyncHttpClient (com.loopj.android.http.AsyncHttpClient)1 AsyncHttpResponseHandler (com.loopj.android.http.AsyncHttpResponseHandler)1 NetworkException (com.xabber.android.data.NetworkException)1 OnResponseListener (com.xabber.android.data.connection.OnResponseListener)1 MessageItem (com.xabber.android.data.message.MessageItem)1 Request (com.xabber.xmpp.httpfileupload.Request)1 FileEntity (cz.msebera.android.httpclient.entity.FileEntity)1