Search in sources :

Example 1 with ResultDownloadFile

use of com.fanap.podchat.chat.file_manager.download_file.model.ResultDownloadFile in project pod-chat-android-sdk by FanapSoft.

the class ChatCore method getFile.

/**
 * @param request         fileId and hashCode of desired file
 * @param progressHandler callbacks for downloading progress.
 * @return uniqueId of request.
 */
public String getFile(RequestGetFile request, ProgressHandler.IDownloadFile progressHandler) {
    String uniqueId = generateUniqueId();
    String url = getFile(request.getFileId(), request.getHashCode(), true);
    PodDownloader.IDownloaderError downloaderErrorInterface = getDownloaderErrorInterface(progressHandler, uniqueId, url);
    File destinationFolder;
    if (cache && request.canUseCache()) {
        destinationFolder = FileUtils.getDownloadDirectory() != null ? FileUtils.getOrCreateDownloadDirectory(FileUtils.FILES) : FileUtils.getOrCreateDirectory(FileUtils.FILES);
    } else {
        destinationFolder = FileUtils.getDownloadDirectory() != null ? FileUtils.getOrCreateDownloadDirectory(FileUtils.FILES) : FileUtils.getPublicFilesDirectory();
    }
    String fileName = "file_" + request.getFileId() + "_" + request.getHashCode();
    if (destinationFolder == null) {
        progressHandler.onError(uniqueId, ChatConstant.ERROR_WRITING_FILE, url);
        return uniqueId;
    }
    File cachedFile = FileUtils.findFileInFolder(destinationFolder, fileName);
    if (cachedFile != null && cachedFile.isFile() && request.canUseCache()) {
        // file exists
        ChatResponse<ResultDownloadFile> response = PodDownloader.generateDownloadResult(request.getHashCode(), request.getFileId(), cachedFile);
        progressHandler.onFileReady(response);
        return uniqueId;
    }
    // only url should return in callback
    if (!hasFreeSpace) {
        progressHandler.onLowFreeSpace(uniqueId, url);
        return uniqueId;
    }
    if (chatReady) {
        Call call = PodDownloader.download(new ProgressHandler.IDownloadFile() {

            @Override
            public void onError(String mUniqueId, String error, String mUrl) {
                progressHandler.onError(uniqueId, error, url);
            }

            @Override
            public void onProgressUpdate(String mUniqueId, long bytesDownloaded, long totalBytesToDownload) {
                progressHandler.onProgressUpdate(uniqueId, bytesDownloaded, totalBytesToDownload);
                if (totalBytesToDownload > checkFreeSpace()) {
                    progressHandler.onLowFreeSpace(uniqueId, url);
                }
            }

            @Override
            public void onProgressUpdate(String mUniqueId, int progress) {
                progressHandler.onProgressUpdate(uniqueId, progress);
            }

            @Override
            public void onFileReady(ChatResponse<ResultDownloadFile> response) {
                progressHandler.onFileReady(response);
            }
        }, getFileServer(), url, fileName, destinationFolder, downloaderErrorInterface, request.getHashCode(), request.getFileId());
        downloadCallList.put(uniqueId, call);
    } else
        onChatNotReady(uniqueId);
    return uniqueId;
}
Also used : PodDownloader(com.fanap.podchat.chat.file_manager.download_file.PodDownloader) Call(retrofit2.Call) ProgressHandler(com.fanap.podchat.ProgressHandler) ResultDownloadFile(com.fanap.podchat.chat.file_manager.download_file.model.ResultDownloadFile) 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 2 with ResultDownloadFile

use of com.fanap.podchat.chat.file_manager.download_file.model.ResultDownloadFile in project pod-chat-android-sdk by FanapSoft.

the class ChatCore method getImage.

/**
 * @param request         imageId and hashCode of desired image
 * @param progressHandler callbacks for downloading progress.
 * @return uniqueId of request.
 */
public String getImage(RequestGetImage request, ProgressHandler.IDownloadFile progressHandler) {
    String uniqueId = generateUniqueId();
    String url = getImage(request.getImageId(), request.getHashCode(), true);
    PodDownloader.IDownloaderError downloaderErrorInterface = getDownloaderErrorInterface(progressHandler, uniqueId, url);
    File destinationFolder;
    if (cache && request.canUseCache()) {
        destinationFolder = FileUtils.getDownloadDirectory() != null ? FileUtils.getOrCreateDownloadDirectory(FileUtils.PICTURES) : FileUtils.getOrCreateDirectory(FileUtils.PICTURES);
    } else {
        destinationFolder = FileUtils.getDownloadDirectory() != null ? FileUtils.getOrCreateDownloadDirectory(FileUtils.PICTURES) : FileUtils.getPublicFilesDirectory();
    }
    String fileName = "image_" + request.getImageId() + "_" + request.getHashCode();
    if (destinationFolder == null) {
        progressHandler.onError(uniqueId, ChatConstant.ERROR_WRITING_FILE, url);
        return uniqueId;
    }
    File cachedFile = FileUtils.findFileInFolder(destinationFolder, fileName);
    if (cachedFile != null && cachedFile.isFile() && request.canUseCache()) {
        // file exists
        ChatResponse<ResultDownloadFile> response = PodDownloader.generateDownloadResult(request.getHashCode(), request.getImageId(), cachedFile);
        progressHandler.onFileReady(response);
        return uniqueId;
    }
    // only url should return in callback
    if (!hasFreeSpace) {
        progressHandler.onLowFreeSpace(uniqueId, url);
        return uniqueId;
    }
    if (chatReady) {
        Call call = PodDownloader.download(new ProgressHandler.IDownloadFile() {

            @Override
            public void onError(String mUniqueId, String error, String mUrl) {
                progressHandler.onError(uniqueId, error, url);
            }

            @Override
            public void onProgressUpdate(String mUniqueId, long bytesDownloaded, long totalBytesToDownload) {
                progressHandler.onProgressUpdate(uniqueId, bytesDownloaded, totalBytesToDownload);
                if (totalBytesToDownload > checkFreeSpace()) {
                    progressHandler.onLowFreeSpace(uniqueId, url);
                }
            }

            @Override
            public void onProgressUpdate(String mUniqueId, int progress) {
                progressHandler.onProgressUpdate(uniqueId, progress);
            }

            @Override
            public void onFileReady(ChatResponse<ResultDownloadFile> response) {
                progressHandler.onFileReady(response);
            }
        }, getFileServer(), url, fileName, destinationFolder, downloaderErrorInterface, request.getHashCode(), request.getImageId());
        downloadCallList.put(uniqueId, call);
    } else
        onChatNotReady(uniqueId);
    return uniqueId;
}
Also used : PodDownloader(com.fanap.podchat.chat.file_manager.download_file.PodDownloader) Call(retrofit2.Call) ProgressHandler(com.fanap.podchat.ProgressHandler) ResultDownloadFile(com.fanap.podchat.chat.file_manager.download_file.model.ResultDownloadFile) 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 3 with ResultDownloadFile

use of com.fanap.podchat.chat.file_manager.download_file.model.ResultDownloadFile in project pod-chat-android-sdk by FanapSoft.

the class ChatCore method getImage.

/**
 * @param request         contains desired image hashCode
 * @param progressHandler callbacks for downloading progress.
 * @return uniqueId of request.
 */
public String getImage(RequestGetPodSpaceImage request, ProgressHandler.IDownloadFile progressHandler) {
    String uniqueId = generateUniqueId();
    String url = getPodSpaceImageUrl(request.getHashCode());
    showLog("DOWNLOAD IMAGE: " + url);
    PodDownloader.IDownloaderError downloaderErrorInterface = getDownloaderErrorInterface(progressHandler, uniqueId, url);
    File destinationFolder;
    if (cache && request.canUseCache()) {
        destinationFolder = FileUtils.getDownloadDirectory() != null ? FileUtils.getOrCreateDownloadDirectory(FileUtils.PICTURES) : FileUtils.getOrCreateDirectory(FileUtils.PICTURES);
    } else {
        destinationFolder = FileUtils.getDownloadDirectory() != null ? FileUtils.getOrCreateDownloadDirectory(FileUtils.PICTURES) : FileUtils.getPublicFilesDirectory();
    }
    showLog("Save in folder: " + destinationFolder);
    String fileName = "image_" + request.getHashCode();
    if (destinationFolder == null) {
        showErrorLog("Error Creating destination folder");
        progressHandler.onError(uniqueId, ChatConstant.ERROR_WRITING_FILE, url);
        return uniqueId;
    }
    if (cache) {
        dataSource.checkInCache(request.getHashCode(), request.getQuality()).subscribe(cacheFile -> {
            if (cacheFile != null) {
                File cachedFileInLocal = FileUtils.findFileInFolder(destinationFolder, fileName);
                if (cachedFileInLocal != null && cachedFileInLocal.isFile() && request.canUseCache()) {
                    showLog("File Exist in cache: " + cachedFileInLocal);
                    // file exists
                    ChatResponse<ResultDownloadFile> response = PodDownloader.generatePodSpaceDownloadResult(request.getHashCode(), cachedFileInLocal);
                    response.getResult().setFromCache(true);
                    progressHandler.onFileReady(response);
                } else {
                    messageDatabaseHelper.deleteImageFromCache(cacheFile);
                    downloadFile(request, progressHandler, uniqueId, url, fileName, destinationFolder, downloaderErrorInterface);
                }
            } else {
                downloadFile(request, progressHandler, uniqueId, url, fileName, destinationFolder, downloaderErrorInterface);
            }
        });
    // messageDatabaseHelper.getImagesByHash(
    // request.getHashCode(), request.getQuality())
    // .subscribe(cacheFile -> {
    // if (cacheFile != null) {
    // File cachedFileInLocal = FileUtils.findFileInFolder(destinationFolder, fileName);
    // 
    // if (cachedFileInLocal != null && cachedFileInLocal.isFile() && request.canUseCache()) {
    // 
    // showLog("File Exist in cache: " + cachedFileInLocal);
    // 
    // //file exists
    // ChatResponse<ResultDownloadFile> response = PodDownloader.generatePodSpaceDownloadResult(request.getHashCode(), cachedFileInLocal);
    // response.getResult().setFromCache(true);
    // progressHandler.onFileReady(response);
    // 
    // } else {
    // 
    // messageDatabaseHelper.deleteImageFromCache(cacheFile);
    // 
    // downloadFile(request, progressHandler, uniqueId, url, fileName,
    // destinationFolder, downloaderErrorInterface);
    // 
    // 
    // }
    // } else {
    // downloadFile(request, progressHandler, uniqueId, url, fileName,
    // destinationFolder, downloaderErrorInterface);
    // }
    // 
    // });
    } else {
        downloadFile(request, progressHandler, uniqueId, url, fileName, destinationFolder, downloaderErrorInterface);
    }
    return uniqueId;
}
Also used : PodDownloader(com.fanap.podchat.chat.file_manager.download_file.PodDownloader) ResultDownloadFile(com.fanap.podchat.chat.file_manager.download_file.model.ResultDownloadFile) 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 4 with ResultDownloadFile

use of com.fanap.podchat.chat.file_manager.download_file.model.ResultDownloadFile 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 5 with ResultDownloadFile

use of com.fanap.podchat.chat.file_manager.download_file.model.ResultDownloadFile in project pod-chat-android-sdk by FanapSoft.

the class PodDownloader method generatePodSpaceDownloadResult.

public static ChatResponse<ResultDownloadFile> generatePodSpaceDownloadResult(String hashCode, File cacheFile) {
    ResultDownloadFile result = new ResultDownloadFile();
    result.setFile(cacheFile);
    result.setUri(Uri.fromFile(cacheFile));
    result.setHashCode(hashCode);
    ChatResponse<ResultDownloadFile> response = new ChatResponse<>();
    response.setResult(result);
    return response;
}
Also used : ChatResponse(com.fanap.podchat.model.ChatResponse) ResultDownloadFile(com.fanap.podchat.chat.file_manager.download_file.model.ResultDownloadFile)

Aggregations

ResultDownloadFile (com.fanap.podchat.chat.file_manager.download_file.model.ResultDownloadFile)10 File (java.io.File)8 CursorIndexOutOfBoundsException (android.database.CursorIndexOutOfBoundsException)4 PodDownloader (com.fanap.podchat.chat.file_manager.download_file.PodDownloader)4 MetaDataFile (com.fanap.podchat.model.MetaDataFile)4 ResultFile (com.fanap.podchat.model.ResultFile)4 ResultImageFile (com.fanap.podchat.model.ResultImageFile)4 RequestCreateThreadWithFile (com.fanap.podchat.requestobject.RequestCreateThreadWithFile)4 RequestGetFile (com.fanap.podchat.requestobject.RequestGetFile)4 RequestGetPodSpaceFile (com.fanap.podchat.requestobject.RequestGetPodSpaceFile)4 RequestUploadFile (com.fanap.podchat.requestobject.RequestUploadFile)4 IOException (java.io.IOException)4 ProgressHandler (com.fanap.podchat.ProgressHandler)3 ChatResponse (com.fanap.podchat.model.ChatResponse)3 ProgressResponseBody (com.fanap.podchat.networking.ProgressResponseBody)3 FileApi (com.fanap.podchat.networking.api.FileApi)3 BufferedOutputStream (java.io.BufferedOutputStream)3 FileOutputStream (java.io.FileOutputStream)3 InputStream (java.io.InputStream)3 OutputStream (java.io.OutputStream)3