Search in sources :

Example 1 with FileApi

use of com.fanap.podchat.networking.api.FileApi in project pod-chat-android-sdk by FanapSoft.

the class PodUploader method uploadImageToPodSpace.

private static Subscription uploadImageToPodSpace(String uniqueId, String threadHashCode, String fileServer, String token, int tokenIssuer, String xC, String yC, String hC, String wC, IPodUploadFileToPodSpace listener, String mimeType, File file, long fileSize) throws FileNotFoundException {
    int width = 0;
    int height = 0;
    String nWidth = "0";
    String nHeight = "0";
    try {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(file.getAbsolutePath(), options);
        width = options.outWidth;
        height = options.outHeight;
        nWidth = !Util.isNullOrEmpty(wC) ? wC : String.valueOf(width);
        nHeight = !Util.isNullOrEmpty(hC) ? hC : String.valueOf(height);
    } catch (Exception e) {
        throw new FileNotFoundException("Invalid image!");
    }
    listener.onUploadStarted(mimeType, file, fileSize);
    RetrofitHelperFileServer retrofitHelperFileServer = new RetrofitHelperFileServer(fileServer);
    FileApi fileApi = retrofitHelperFileServer.getService(FileApi.class);
    RequestBody namePart = RequestBody.create(MediaType.parse("multipart/form-data"), file.getName());
    RequestBody hashGroupPart = RequestBody.create(MediaType.parse("multipart/form-data"), threadHashCode);
    RequestBody xCPart = RequestBody.create(MediaType.parse("multipart/form-data"), !Util.isNullOrEmpty(xC) ? xC : "0");
    RequestBody yCPart = RequestBody.create(MediaType.parse("multipart/form-data"), !Util.isNullOrEmpty(yC) ? yC : "0");
    RequestBody hCPart = RequestBody.create(MediaType.parse("multipart/form-data"), nWidth);
    RequestBody wCPart = RequestBody.create(MediaType.parse("multipart/form-data"), nHeight);
    ProgressRequestBody requestFile = new ProgressRequestBody(file, mimeType, uniqueId, new ProgressRequestBody.UploadCallbacks() {

        @Override
        public void onProgress(String uniqueId, int progress, int totalBytesSent, int totalBytesToSend) {
            if (progress < 95)
                listener.onProgressUpdate(progress, totalBytesSent, totalBytesToSend);
        }
    });
    MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
    Observable<Response<UploadToPodSpaceResponse>> uploadObservable = fileApi.uploadImageToPodSpace(filePart, token, tokenIssuer, namePart, hashGroupPart, xCPart, yCPart, wCPart, hCPart);
    int finalWidth = width;
    int finalHeight = height;
    String finalNWidth = nWidth;
    String finalNHeight = nHeight;
    return uploadObservable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).doOnError(error -> listener.onFailure(error.getMessage(), error)).subscribe(response -> {
        if (response.isSuccessful() && response.body() != null) {
            if (response.body().isHasError()) {
                listener.onFailure(response.body().getMessage(), new PodChatException(response.body().getMessage(), uniqueId, token));
                return;
            }
            listener.onProgressUpdate(100, (int) fileSize, 0);
            listener.onSuccess(response.body().getUploadToPodSpaceResult(), file, mimeType, fileSize, finalWidth, finalHeight, Integer.parseInt(finalNWidth), Integer.parseInt(finalNHeight));
        } else {
            try {
                if (response.errorBody() != null) {
                    listener.onFailure(response.errorBody().string(), new PodChatException(response.errorBody().string(), uniqueId, token));
                } else {
                    listener.onFailure(response.message(), new PodChatException(response.message(), uniqueId, token));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }, error -> listener.onFailure(error.getMessage(), error));
}
Also used : Context(android.content.Context) PodChatException(com.fanap.podchat.util.PodChatException) RetrofitHelperFileServer(com.fanap.podchat.networking.retrofithelper.RetrofitHelperFileServer) Uri(android.net.Uri) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) BitmapFactory(android.graphics.BitmapFactory) NonNull(android.support.annotation.NonNull) ResultFile(com.fanap.podchat.model.ResultFile) Response(retrofit2.Response) FileUpload(com.fanap.podchat.mainmodel.FileUpload) ChatConstant(com.fanap.podchat.util.ChatConstant) ChatResponse(com.fanap.podchat.model.ChatResponse) RequestBody(okhttp3.RequestBody) Observable(rx.Observable) Schedulers(rx.schedulers.Schedulers) FilePick(com.fanap.podchat.util.FilePick) Log(android.util.Log) MediaType(okhttp3.MediaType) TAG(com.fanap.podchat.chat.Chat.TAG) IOException(java.io.IOException) ProgressRequestBody(com.fanap.podchat.networking.ProgressRequestBody) FileApi(com.fanap.podchat.networking.api.FileApi) Util(com.fanap.podchat.util.Util) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) ResultImageFile(com.fanap.podchat.model.ResultImageFile) FileImageUpload(com.fanap.podchat.model.FileImageUpload) MultipartBody(okhttp3.MultipartBody) Subscription(rx.Subscription) UploadingQueueCache(com.fanap.podchat.cachemodel.queue.UploadingQueueCache) FileUtils(com.fanap.podchat.util.FileUtils) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) PodChatException(com.fanap.podchat.util.PodChatException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) RetrofitHelperFileServer(com.fanap.podchat.networking.retrofithelper.RetrofitHelperFileServer) Response(retrofit2.Response) ChatResponse(com.fanap.podchat.model.ChatResponse) PodChatException(com.fanap.podchat.util.PodChatException) MultipartBody(okhttp3.MultipartBody) BitmapFactory(android.graphics.BitmapFactory) ProgressRequestBody(com.fanap.podchat.networking.ProgressRequestBody) FileApi(com.fanap.podchat.networking.api.FileApi) RequestBody(okhttp3.RequestBody) ProgressRequestBody(com.fanap.podchat.networking.ProgressRequestBody)

Example 2 with FileApi

use of com.fanap.podchat.networking.api.FileApi in project pod-chat-android-sdk by FanapSoft.

the class PodUploader method uploadImageToChatServer.

public static Subscription uploadImageToChatServer(String uniqueId, @NonNull Uri fileUri, Context context, String fileServer, String token, int tokenIssuer, IPodUploadImage listener) throws Exception {
    if (fileUri.getPath() == null)
        throw new NullPointerException("Invalid file uri!");
    String mimeType = FileUtils.getMimeType(fileUri, context);
    String path = FilePick.getSmartFilePath(context, fileUri);
    if (path == null)
        throw new NullPointerException("Invalid path!");
    File file = new File(path);
    if (!file.exists() || !file.isFile())
        throw new FileNotFoundException("Invalid file!");
    long fileSize = 0;
    try {
        fileSize = file.length();
    } catch (Exception x) {
        Log.e(TAG, "File length exception: " + x.getMessage());
    }
    listener.onUploadStarted(mimeType, file, fileSize);
    RetrofitHelperFileServer retrofitHelperFileServer = new RetrofitHelperFileServer(fileServer);
    FileApi fileApi = retrofitHelperFileServer.getService(FileApi.class);
    RequestBody namePart = RequestBody.create(MediaType.parse("multipart/form-data"), file.getName());
    ProgressRequestBody requestFile = new ProgressRequestBody(file, mimeType, uniqueId, new ProgressRequestBody.UploadCallbacks() {

        @Override
        public void onProgress(String uniqueId, int progress, int totalBytesSent, int totalBytesToSend) {
            listener.onProgressUpdate(progress, totalBytesSent, totalBytesToSend);
        }
    });
    MultipartBody.Part filePart = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
    Observable<Response<FileImageUpload>> uploadObservable = fileApi.sendImageFile(filePart, token, tokenIssuer, namePart);
    long finalFileSize = fileSize;
    return uploadObservable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).doOnError(error -> listener.onFailure(uniqueId + " - " + error.getMessage(), error)).subscribe(response -> {
        if (response.isSuccessful() && response.body() != null) {
            if (response.body().isHasError()) {
                listener.onFailure(uniqueId + " - " + response.body().getMessage() + " - " + response.body().getReferenceNumber(), new PodChatException(uniqueId + " - " + response.body().getMessage() + " - " + response.body().getReferenceNumber(), uniqueId, token));
            } else {
                listener.onSuccess(response.body(), file, mimeType, finalFileSize);
            }
        } else {
            if (response.body() != null) {
                listener.onFailure(uniqueId + " - " + response.body().getMessage() + " - " + response.body().getReferenceNumber(), new PodChatException(uniqueId + " - " + response.body().getMessage() + " - " + response.body().getReferenceNumber(), uniqueId, token));
            } else {
                listener.onFailure(uniqueId + " - " + response.message(), new PodChatException(uniqueId + " - " + response.message(), uniqueId, token));
            }
        }
    });
}
Also used : Context(android.content.Context) PodChatException(com.fanap.podchat.util.PodChatException) RetrofitHelperFileServer(com.fanap.podchat.networking.retrofithelper.RetrofitHelperFileServer) Uri(android.net.Uri) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) BitmapFactory(android.graphics.BitmapFactory) NonNull(android.support.annotation.NonNull) ResultFile(com.fanap.podchat.model.ResultFile) Response(retrofit2.Response) FileUpload(com.fanap.podchat.mainmodel.FileUpload) ChatConstant(com.fanap.podchat.util.ChatConstant) ChatResponse(com.fanap.podchat.model.ChatResponse) RequestBody(okhttp3.RequestBody) Observable(rx.Observable) Schedulers(rx.schedulers.Schedulers) FilePick(com.fanap.podchat.util.FilePick) Log(android.util.Log) MediaType(okhttp3.MediaType) TAG(com.fanap.podchat.chat.Chat.TAG) IOException(java.io.IOException) ProgressRequestBody(com.fanap.podchat.networking.ProgressRequestBody) FileApi(com.fanap.podchat.networking.api.FileApi) Util(com.fanap.podchat.util.Util) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) ResultImageFile(com.fanap.podchat.model.ResultImageFile) FileImageUpload(com.fanap.podchat.model.FileImageUpload) MultipartBody(okhttp3.MultipartBody) Subscription(rx.Subscription) UploadingQueueCache(com.fanap.podchat.cachemodel.queue.UploadingQueueCache) FileUtils(com.fanap.podchat.util.FileUtils) FileNotFoundException(java.io.FileNotFoundException) PodChatException(com.fanap.podchat.util.PodChatException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) RetrofitHelperFileServer(com.fanap.podchat.networking.retrofithelper.RetrofitHelperFileServer) Response(retrofit2.Response) ChatResponse(com.fanap.podchat.model.ChatResponse) PodChatException(com.fanap.podchat.util.PodChatException) MultipartBody(okhttp3.MultipartBody) ResultFile(com.fanap.podchat.model.ResultFile) File(java.io.File) ResultImageFile(com.fanap.podchat.model.ResultImageFile) ProgressRequestBody(com.fanap.podchat.networking.ProgressRequestBody) FileApi(com.fanap.podchat.networking.api.FileApi) RequestBody(okhttp3.RequestBody) ProgressRequestBody(com.fanap.podchat.networking.ProgressRequestBody)

Example 3 with FileApi

use of com.fanap.podchat.networking.api.FileApi in project pod-chat-android-sdk by FanapSoft.

the class PodDownloader method downloadFileFromPodSpace.

public static Call downloadFileFromPodSpace(ProgressHandler.IDownloadFile progressHandler, String token, int tokenIssuer, String fileHash, String fileServer, String fileName, File destinationFolder, IDownloaderError downloaderErrorInterface) {
    Retrofit retrofit = ProgressResponseBody.getDownloadRetrofit(fileServer, progressHandler);
    FileApi api = retrofit.create(FileApi.class);
    Call<ResponseBody> call = api.downloadPodSpaceFile(fileHash, token, tokenIssuer);
    final String[] downloadTempPath = new String[1];
    call.enqueue(new Callback<ResponseBody>() {

        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            new Thread(() -> {
                InputStream inputStream = null;
                OutputStream outputStream = null;
                File downloadTempFile = null;
                try {
                    if (!destinationFolder.exists()) {
                        boolean createFolder = destinationFolder.mkdirs();
                    }
                    downloadTempFile = new File(destinationFolder, fileName);
                    if (!downloadTempFile.exists()) {
                        boolean fileCreationResult = downloadTempFile.createNewFile();
                        if (!fileCreationResult) {
                            downloaderErrorInterface.errorOnWritingToFile();
                            return;
                        }
                    }
                    // keep path for cancel handling
                    downloadTempPath[0] = downloadTempFile.getPath();
                    if (response.body() != null && response.isSuccessful()) {
                        byte[] byteReader = new byte[4096];
                        inputStream = response.body().byteStream();
                        outputStream = new BufferedOutputStream(new FileOutputStream(downloadTempFile));
                        while (true) {
                            int read = inputStream.read(byteReader);
                            if (read == -1) {
                                // download finished
                                Log.i(TAG, "File has been downloaded");
                                MediaType mediaType = response.body().contentType();
                                String type = null;
                                String subType = "";
                                if (mediaType != null) {
                                    type = mediaType.type();
                                    subType = mediaType.subtype();
                                }
                                File downloadedFile = new File(destinationFolder, fileName + "." + subType);
                                boolean savingSuccess = downloadTempFile.renameTo(downloadedFile);
                                if (savingSuccess) {
                                    ChatResponse<ResultDownloadFile> chatResponse = generatePodSpaceDownloadResult(fileHash, downloadedFile);
                                    progressHandler.onFileReady(chatResponse);
                                // 
                                } else {
                                    downloaderErrorInterface.errorOnWritingToFile();
                                }
                                break;
                            }
                            outputStream.write(byteReader, 0, read);
                            outputStream.flush();
                        }
                    } else {
                        if (response.errorBody() != null) {
                            downloaderErrorInterface.errorUnknownException(response.errorBody().string());
                        } else {
                            downloaderErrorInterface.errorUnknownException(response.message());
                        }
                    }
                } catch (Exception e) {
                    if (call.isCanceled()) {
                        handleCancelDownload(downloadTempFile);
                        return;
                    }
                    Log.e(TAG, e.getMessage());
                    downloaderErrorInterface.errorUnknownException(e.getMessage());
                } finally {
                    try {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                        if (outputStream != null) {
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e(TAG, e.getMessage());
                        downloaderErrorInterface.errorUnknownException(e.getMessage());
                    }
                }
            }).start();
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            if (call.isCanceled()) {
                handleCancelDownload(new File(downloadTempPath[0]));
                return;
            }
            Log.d(TAG, "ERROR " + t.getMessage());
            call.cancel();
            downloaderErrorInterface.errorUnknownException(t.getMessage());
        }
    });
    return call;
}
Also used : InputStream(java.io.InputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) IOException(java.io.IOException) CursorIndexOutOfBoundsException(android.database.CursorIndexOutOfBoundsException) ProgressResponseBody(com.fanap.podchat.networking.ProgressResponseBody) ResponseBody(okhttp3.ResponseBody) Retrofit(retrofit2.Retrofit) FileOutputStream(java.io.FileOutputStream) MediaType(okhttp3.MediaType) ResultDownloadFile(com.fanap.podchat.chat.file_manager.download_file.model.ResultDownloadFile) ResultDownloadFile(com.fanap.podchat.chat.file_manager.download_file.model.ResultDownloadFile) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) FileApi(com.fanap.podchat.networking.api.FileApi)

Example 4 with FileApi

use of com.fanap.podchat.networking.api.FileApi in project pod-chat-android-sdk by FanapSoft.

the class ChatCore method mainUploadImageFileMsg.

private void mainUploadImageFileMsg(LFileUpload fileUpload) {
    JsonObject jsonLog = new JsonObject();
    String description = fileUpload.getDescription();
    jsonLog.addProperty("description", description);
    ProgressHandler.sendFileMessage handler = fileUpload.getHandler();
    Integer messageType = fileUpload.getMessageType();
    jsonLog.addProperty("messageType", messageType);
    long threadId = fileUpload.getThreadId();
    jsonLog.addProperty("threadId", threadId);
    String uniqueId = fileUpload.getUniqueId();
    jsonLog.addProperty("uniqueId", uniqueId);
    String systemMetaData = fileUpload.getSystemMetaData();
    jsonLog.addProperty("systemMetaData", systemMetaData);
    long messageId = fileUpload.getMessageId();
    jsonLog.addProperty("messageId", messageId);
    String mimeType = fileUpload.getMimeType();
    jsonLog.addProperty("mimeType", mimeType);
    String methodName = fileUpload.getMethodName();
    jsonLog.addProperty("methodName", methodName);
    long fileSize = fileUpload.getFileSize();
    jsonLog.addProperty("fileSize", fileSize);
    String center = fileUpload.getCenter();
    jsonLog.addProperty("center", center);
    File file = fileUpload.getFile();
    if (chatReady) {
        if (fileServer != null) {
            RetrofitHelperFileServer retrofitHelperFileServer = new RetrofitHelperFileServer(getFileServer());
            FileApi fileApi = retrofitHelperFileServer.getService(FileApi.class);
            try {
                showLog("UPLOAD_FILE_TO_SERVER", getJsonForLog(jsonLog));
            } catch (Exception e) {
                showErrorLog(e.getMessage());
            }
            ProgressRequestBody requestFile = new ProgressRequestBody(file, mimeType, uniqueId, new ProgressRequestBody.UploadCallbacks() {

                @Override
                public void onProgress(String uniqueId, int progress, int totalBytesSent, int totalBytesToSend) {
                    Log.i(TAG, "on progress");
                    if (handler != null) {
                        handler.onProgressUpdate(uniqueId, progress, totalBytesSent, totalBytesToSend);
                        if (log)
                            Log.i(TAG, "uniqueId " + uniqueId + " bytesSent " + progress);
                    } else {
                        if (log)
                            Log.i(TAG, "Handler is null");
                    }
                }

                @Override
                public void onError() {
                    if (log)
                        Log.i(TAG, "Error on upload");
                }

                @Override
                public void onFinish() {
                    if (log)
                        Log.i(TAG, "Finish upload");
                }
            });
            MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
            RequestBody name = RequestBody.create(MediaType.parse("text/plain"), file.getName());
            Observable<Response<FileImageUpload>> uploadObservable = fileApi.sendImageFile(body, getToken(), TOKEN_ISSUER, name);
            Subscription subscribe = uploadObservable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(fileUploadResponse -> {
                if (fileUploadResponse.body() != null && fileUploadResponse.isSuccessful()) {
                    boolean hasError = fileUploadResponse.body().isHasError();
                    if (hasError) {
                        String errorMessage = fileUploadResponse.body().getMessage();
                        int errorCode = fileUploadResponse.body().getErrorCode();
                        String jsonError = captureError(errorMessage, errorCode, uniqueId);
                        // listenerManager.callOnLogEvent(jsonError);
                        ErrorOutPut error = new ErrorOutPut(true, errorMessage, errorCode, uniqueId);
                        if (handler != null) {
                            handler.onError(jsonError, error);
                        }
                    } else {
                        // remove from Uploading Queue
                        removeFromUploadQueue(uniqueId);
                        ResultImageFile result = fileUploadResponse.body().getResult();
                        long imageId = result.getId();
                        String hashCode = result.getHashCode();
                        ChatResponse<ResultImageFile> chatResponse = new ChatResponse<>();
                        ResultImageFile resultImageFile = new ResultImageFile();
                        chatResponse.setUniqueId(uniqueId);
                        resultImageFile.setId(result.getId());
                        resultImageFile.setHashCode(result.getHashCode());
                        resultImageFile.setName(result.getName());
                        resultImageFile.setHeight(result.getHeight());
                        resultImageFile.setWidth(result.getWidth());
                        resultImageFile.setActualHeight(result.getActualHeight());
                        resultImageFile.setActualWidth(result.getActualWidth());
                        chatResponse.setResult(resultImageFile);
                        String imageJson = gson.toJson(chatResponse);
                        listenerManager.callOnUploadImageFile(imageJson, chatResponse);
                        if (handler != null) {
                            handler.onFinishImage(imageJson, chatResponse);
                        }
                        showLog("RECEIVE_UPLOAD_IMAGE", imageJson);
                        // if (log) Log.i(TAG, "RECEIVE_UPLOAD_IMAGE");
                        // listenerManager.callOnLogEvent(imageJson);
                        String metaJson;
                        if (!Util.isNullOrEmpty(methodName) && methodName.equals(ChatConstant.METHOD_LOCATION_MSG)) {
                            metaJson = createImageMetadata(file, hashCode, imageId, result.getActualHeight(), result.getActualWidth(), mimeType, fileSize, null, true, center);
                        } else {
                            metaJson = createImageMetadata(file, hashCode, imageId, result.getActualHeight(), result.getActualWidth(), mimeType, fileSize, null, false, null);
                        }
                        // 
                        JsonObject js = new JsonObject();
                        js.addProperty("metadata", metaJson);
                        js.addProperty("uniqueId", uniqueId);
                        // send to handler
                        if (handler != null) {
                            handler.onFinishImage(imageJson, chatResponse);
                        }
                        if (isReplyMessage(methodName)) {
                            showLog("SEND_REPLY_FILE_MESSAGE", getJsonForLog(js));
                            mainReplyMessage(description, threadId, messageId, systemMetaData, messageType, metaJson, uniqueId, null);
                        // if (log) Log.i(TAG, "SEND_REPLY_FILE_MESSAGE");
                        // listenerManager.callOnLogEvent(metaJson);
                        } else {
                            sendTextMessageWithFile(description, threadId, metaJson, systemMetaData, uniqueId, typeCode, messageType);
                        }
                    // listenerManager.callOnLogEvent(metaJson);
                    }
                }
            }, throwable -> {
                try {
                    String jsonError = captureError(throwable.getMessage(), ChatConstant.ERROR_CODE_UNKNOWN_EXCEPTION, uniqueId);
                    ErrorOutPut error = new ErrorOutPut(true, throwable.getMessage(), ChatConstant.ERROR_CODE_UNKNOWN_EXCEPTION, uniqueId);
                    if (log)
                        Log.e(TAG, jsonError);
                    if (handler != null) {
                        handler.onError(jsonError, error);
                    }
                } catch (Exception e) {
                    showErrorLog(e.getMessage());
                    onUnknownException(uniqueId, e);
                }
            });
            /*
                 * Cancel Upload request
                 * */
            initCancelUpload(uniqueId, subscribe);
        } else {
            if (log)
                Log.e(TAG, "FileServer url Is null");
        }
    } else {
        captureError(ChatConstant.ERROR_CHAT_READY, ChatConstant.ERROR_CODE_CHAT_READY, uniqueId);
    }
}
Also used : JsonObject(com.google.gson.JsonObject) RetrofitHelperFileServer(com.fanap.podchat.networking.retrofithelper.RetrofitHelperFileServer) ResultImageFile(com.fanap.podchat.model.ResultImageFile) ChatResponse(com.fanap.podchat.model.ChatResponse) ErrorOutPut(com.fanap.podchat.model.ErrorOutPut) Subscription(rx.Subscription) ProgressRequestBody(com.fanap.podchat.networking.ProgressRequestBody) FileApi(com.fanap.podchat.networking.api.FileApi) RequestBody(okhttp3.RequestBody) ProgressRequestBody(com.fanap.podchat.networking.ProgressRequestBody) ProgressHandler(com.fanap.podchat.ProgressHandler) JSONException(org.json.JSONException) SentryException(io.sentry.core.protocol.SentryException) IOException(java.io.IOException) JsonSyntaxException(com.google.gson.JsonSyntaxException) PodChatException(com.fanap.podchat.util.PodChatException) RoomIntegrityException(com.fanap.podchat.persistance.RoomIntegrityException) ChatResponse(com.fanap.podchat.model.ChatResponse) Response(retrofit2.Response) MultipartBody(okhttp3.MultipartBody) MetaDataFile(com.fanap.podchat.model.MetaDataFile) RequestUploadFile(com.fanap.podchat.requestobject.RequestUploadFile) ResultDownloadFile(com.fanap.podchat.chat.file_manager.download_file.model.ResultDownloadFile) ResultFile(com.fanap.podchat.model.ResultFile) RequestGetPodSpaceFile(com.fanap.podchat.requestobject.RequestGetPodSpaceFile) RequestGetFile(com.fanap.podchat.requestobject.RequestGetFile) RequestCreateThreadWithFile(com.fanap.podchat.requestobject.RequestCreateThreadWithFile) File(java.io.File) ResultImageFile(com.fanap.podchat.model.ResultImageFile)

Example 5 with FileApi

use of com.fanap.podchat.networking.api.FileApi in project pod-chat-android-sdk by FanapSoft.

the class ChatCore method mainUploadFileMessage.

private void mainUploadFileMessage(LFileUpload lFileUpload) {
    JsonObject jsonLog = new JsonObject();
    String description = lFileUpload.getDescription();
    jsonLog.addProperty("description", description);
    Integer messageType = lFileUpload.getMessageType();
    jsonLog.addProperty("messageType", messageType);
    long threadId = lFileUpload.getThreadId();
    jsonLog.addProperty("threadId", threadId);
    String uniqueId = lFileUpload.getUniqueId();
    jsonLog.addProperty("uniqueId", uniqueId);
    String systemMetadata = lFileUpload.getSystemMetaData();
    jsonLog.addProperty("systemMetadata", systemMetadata);
    long messageId = lFileUpload.getMessageId();
    jsonLog.addProperty("messageId", messageId);
    String mimeType = lFileUpload.getMimeType();
    jsonLog.addProperty("mimeType", mimeType);
    File file = lFileUpload.getFile();
    ProgressHandler.sendFileMessage handler = lFileUpload.getHandler();
    long file_size = lFileUpload.getFileSize();
    jsonLog.addProperty("file_size", file_size);
    String methodName = lFileUpload.getMethodName();
    jsonLog.addProperty("methodName", methodName);
    jsonLog.addProperty("name", file.getName());
    showLog("UPLOADING_FILE_TO_SERVER", getJsonForLog(jsonLog));
    if (chatReady) {
        if (getFileServer() != null) {
            RetrofitHelperFileServer retrofitHelperFileServer = new RetrofitHelperFileServer(getFileServer());
            FileApi fileApi = retrofitHelperFileServer.getService(FileApi.class);
            RequestBody name = RequestBody.create(MediaType.parse("multipart/form-data"), file.getName());
            ProgressRequestBody requestFile = new ProgressRequestBody(file, mimeType, uniqueId, new ProgressRequestBody.UploadCallbacks() {

                @Override
                public void onProgress(String uniqueId, int progress, int totalBytesSent, int totalBytesToSend) {
                    if (handler != null)
                        handler.onProgressUpdate(uniqueId, progress, totalBytesSent, totalBytesToSend);
                }
            });
            MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
            Observable<Response<FileUpload>> uploadObservable = fileApi.sendFile(body, getToken(), TOKEN_ISSUER, name);
            Subscription subscription = uploadObservable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(fileUploadResponse -> {
                if (fileUploadResponse.isSuccessful() && fileUploadResponse.body() != null) {
                    boolean error = fileUploadResponse.body().isHasError();
                    if (error) {
                        String errorMessage = fileUploadResponse.body().getMessage();
                        if (log)
                            Log.e(TAG, errorMessage);
                        if (handler != null) {
                            String jsonError = captureError(ChatConstant.ERROR_UPLOAD_FILE, ChatConstant.ERROR_CODE_UPLOAD_FILE, uniqueId);
                            ErrorOutPut errorOutPut = new ErrorOutPut(true, ChatConstant.ERROR_UPLOAD_FILE, ChatConstant.ERROR_CODE_UPLOAD_FILE, uniqueId);
                            handler.onError(jsonError, errorOutPut);
                        }
                    } else {
                        // remove from Uploading Queue
                        removeFromUploadQueue(uniqueId);
                        ResultFile result = fileUploadResponse.body().getResult();
                        if (result != null) {
                            long fileId = result.getId();
                            String hashCode = result.getHashCode();
                            ChatResponse<ResultFile> chatResponse = new ChatResponse<>();
                            chatResponse.setResult(result);
                            chatResponse.setUniqueId(uniqueId);
                            result.setSize(file_size);
                            String json = gson.toJson(chatResponse);
                            showLog("FILE_UPLOADED_TO_SERVER", json);
                            listenerManager.callOnUploadFile(json, chatResponse);
                            if (handler != null) {
                                handler.onFinishFile(json, chatResponse);
                            }
                            String jsonMeta = createFileMetadata(file, hashCode, fileId, mimeType, file_size, "");
                            if (!Util.isNullOrEmpty(methodName) && methodName.equals(ChatConstant.METHOD_REPLY_MSG)) {
                                showLog("SEND_REPLY_FILE_MESSAGE", jsonMeta);
                                mainReplyMessage(description, threadId, messageId, systemMetadata, messageType, jsonMeta, uniqueId, null);
                            } else {
                                sendTextMessageWithFile(description, threadId, jsonMeta, systemMetadata, uniqueId, typeCode, messageType);
                            }
                        }
                    }
                }
            }, throwable -> {
                if (log)
                    Log.e(TAG, throwable.getMessage());
            });
            /*
                 * Cancel Uploading progress
                 * */
            initCancelUpload(uniqueId, subscription);
        } else {
            if (log)
                Log.e(TAG, "FileServer url Is null");
        }
    } else {
        captureError(ChatConstant.ERROR_CHAT_READY, ChatConstant.ERROR_CODE_CHAT_READY, uniqueId);
    // listenerManager.callOnLogEvent(jsonError);
    }
}
Also used : ProgressHandler(com.fanap.podchat.ProgressHandler) JsonObject(com.google.gson.JsonObject) ResultFile(com.fanap.podchat.model.ResultFile) RetrofitHelperFileServer(com.fanap.podchat.networking.retrofithelper.RetrofitHelperFileServer) ChatResponse(com.fanap.podchat.model.ChatResponse) Response(retrofit2.Response) MultipartBody(okhttp3.MultipartBody) ChatResponse(com.fanap.podchat.model.ChatResponse) ErrorOutPut(com.fanap.podchat.model.ErrorOutPut) Subscription(rx.Subscription) MetaDataFile(com.fanap.podchat.model.MetaDataFile) RequestUploadFile(com.fanap.podchat.requestobject.RequestUploadFile) ResultDownloadFile(com.fanap.podchat.chat.file_manager.download_file.model.ResultDownloadFile) ResultFile(com.fanap.podchat.model.ResultFile) RequestGetPodSpaceFile(com.fanap.podchat.requestobject.RequestGetPodSpaceFile) RequestGetFile(com.fanap.podchat.requestobject.RequestGetFile) RequestCreateThreadWithFile(com.fanap.podchat.requestobject.RequestCreateThreadWithFile) File(java.io.File) ResultImageFile(com.fanap.podchat.model.ResultImageFile) ProgressRequestBody(com.fanap.podchat.networking.ProgressRequestBody) FileApi(com.fanap.podchat.networking.api.FileApi) RequestBody(okhttp3.RequestBody) ProgressRequestBody(com.fanap.podchat.networking.ProgressRequestBody)

Aggregations

FileApi (com.fanap.podchat.networking.api.FileApi)11 File (java.io.File)11 IOException (java.io.IOException)10 MediaType (okhttp3.MediaType)9 ChatResponse (com.fanap.podchat.model.ChatResponse)8 ResultFile (com.fanap.podchat.model.ResultFile)8 ResultImageFile (com.fanap.podchat.model.ResultImageFile)8 ProgressRequestBody (com.fanap.podchat.networking.ProgressRequestBody)8 RetrofitHelperFileServer (com.fanap.podchat.networking.retrofithelper.RetrofitHelperFileServer)8 MultipartBody (okhttp3.MultipartBody)8 RequestBody (okhttp3.RequestBody)8 Response (retrofit2.Response)8 Subscription (rx.Subscription)8 PodChatException (com.fanap.podchat.util.PodChatException)7 Context (android.content.Context)6 BitmapFactory (android.graphics.BitmapFactory)6 Uri (android.net.Uri)6 NonNull (android.support.annotation.NonNull)6 Log (android.util.Log)6 UploadingQueueCache (com.fanap.podchat.cachemodel.queue.UploadingQueueCache)6