Search in sources :

Example 6 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 generateDownloadResult.

public static ChatResponse<ResultDownloadFile> generateDownloadResult(String hashCode, long id, File cacheFile) {
    ResultDownloadFile result = new ResultDownloadFile();
    result.setFile(cacheFile);
    result.setUri(Uri.fromFile(cacheFile));
    result.setHashCode(hashCode);
    result.setId(id);
    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)

Example 7 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         desired file hashCode
 * @param progressHandler callbacks for downloading progress.
 * @return uniqueId of request.
 */
public String getFile(RequestGetPodSpaceFile request, ProgressHandler.IDownloadFile progressHandler) {
    String uniqueId = generateUniqueId();
    String url = getPodSpaceFileUrl(request.getHashCode());
    showLog("DOWNLOAD FILE: " + url);
    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();
    }
    showLog("Save in folder: " + destinationFolder);
    String fileName = "file_" + request.getHashCode();
    if (destinationFolder == null) {
        showErrorLog("Error Creating destination folder");
        progressHandler.onError(uniqueId, ChatConstant.ERROR_WRITING_FILE, url);
        return uniqueId;
    }
    File cachedFile = FileUtils.findFileInFolder(destinationFolder, fileName);
    if (cachedFile != null && cachedFile.isFile() && request.canUseCache()) {
        showLog("File Exist in cache: " + cachedFile);
        // file exists
        ChatResponse<ResultDownloadFile> response = PodDownloader.generatePodSpaceDownloadResult(request.getHashCode(), cachedFile);
        progressHandler.onFileReady(response);
        return uniqueId;
    }
    // only url should return in callback
    if (!hasFreeSpace) {
        showErrorLog("Download couldn't start. cause: LOW FREE SPACE");
        progressHandler.onLowFreeSpace(uniqueId, url);
        return uniqueId;
    }
    if (chatReady) {
        showLog("Download Started", request.toString());
        Call call = PodDownloader.downloadFileFromPodSpace(new ProgressHandler.IDownloadFile() {

            @Override
            public void onError(String mUniqueId, String error, String mUrl) {
                progressHandler.onError(uniqueId, error, url);
                showErrorLog("Download Error. cause: " + error);
            }

            @Override
            public void onProgressUpdate(String mUniqueId, long bytesDownloaded, long totalBytesToDownload) {
                progressHandler.onProgressUpdate(uniqueId, bytesDownloaded, totalBytesToDownload);
                if (totalBytesToDownload > checkFreeSpace()) {
                    showErrorLog("Total file space is more than free space");
                    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);
                showLog("Download is complete!");
            }
        }, getToken(), TOKEN_ISSUER, request.getHashCode(), getPodSpaceServer(), fileName, destinationFolder, downloaderErrorInterface);
        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 8 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 downloadImageFromPodSpace.

public static Call downloadImageFromPodSpace(ProgressHandler.IDownloadFile progressHandler, String token, int tokenIssuer, String fileHash, String fileServer, String fileName, File destinationFolder, IDownloaderError downloaderErrorInterface, String size, Float quality, Boolean crop) {
    Retrofit retrofit = ProgressResponseBody.getDownloadRetrofit(fileServer, progressHandler);
    FileApi api = retrofit.create(FileApi.class);
    Call<ResponseBody> call = api.downloadPodSpaceImage(fileHash, size, quality, crop, 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 9 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 download.

public static Call download(ProgressHandler.IDownloadFile progressHandler, String fileServer, String url, String fileName, File destinationFolder, IDownloaderError downloaderErrorInterface, String hashCode, long fileId) {
    Retrofit retrofit = ProgressResponseBody.getDownloadRetrofit(fileServer, progressHandler);
    FileApi api = retrofit.create(FileApi.class);
    Call<ResponseBody> call = api.download(url);
    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 = generateDownloadResult(hashCode, fileId, 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 10 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 download.

public static long download(ProgressHandler.IDownloadFile progressHandler, String uniqueId, File destinationFolder, String url, String fileName, String hashCode, long id, Context context, IDownloaderError iDownloader, long bytesAvailable) {
    File downloadTempFile = new File(destinationFolder, fileName);
    DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    Uri uri = Uri.parse(url);
    DownloadManager.Request dlManagerRequest = new DownloadManager.Request(uri);
    dlManagerRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
    dlManagerRequest.setDestinationUri(Uri.fromFile(downloadTempFile));
    long downloadId = downloadManager.enqueue(dlManagerRequest);
    new Thread(() -> {
        int bytesDownloaded = 0;
        while (true) {
            try {
                DownloadManager.Query dlManagerQuery = new DownloadManager.Query();
                dlManagerQuery.setFilterById(downloadId);
                Cursor cursor = downloadManager.query(dlManagerQuery);
                cursor.moveToFirst();
                int newBytesDownloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                int totalBytes = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                if (totalBytes > bytesAvailable) {
                    progressHandler.onLowFreeSpace(uniqueId, url);
                    break;
                }
                final int dl_progress = (int) ((newBytesDownloaded * 100L) / totalBytes);
                if (totalBytes != -1 && bytesDownloaded != newBytesDownloaded) {
                    progressHandler.onProgressUpdate(uniqueId, newBytesDownloaded, totalBytes);
                    progressHandler.onProgressUpdate(uniqueId, dl_progress);
                    bytesDownloaded = newBytesDownloaded;
                }
                if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                    String mime = downloadManager.getMimeTypeForDownloadedFile(downloadId);
                    String extension = FileUtils.getExtensionFromMimType(mime);
                    File downloadedFile = new File(destinationFolder, fileName + "." + extension);
                    boolean savingSuccess = downloadTempFile.renameTo(downloadedFile);
                    if (savingSuccess) {
                        ChatResponse<ResultDownloadFile> response = generateDownloadResult(hashCode, id, downloadedFile);
                        progressHandler.onFileReady(response);
                    // if (!cache) {
                    // downloadedFile.delete();
                    // }
                    } else {
                        iDownloader.errorOnWritingToFile();
                    }
                    break;
                }
                if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_FAILED) {
                    int errorCode = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
                    Log.e(TAG, "Error in downloading file! DownloadManager error code: " + errorCode);
                    iDownloader.errorOnDownloadingFile(errorCode);
                    break;
                }
            } catch (CursorIndexOutOfBoundsException e) {
                Log.i(TAG, "Download Canceled by client");
                break;
            } catch (Exception exc) {
                exc.printStackTrace();
                iDownloader.errorUnknownException(exc.getMessage());
                break;
            }
        }
    }).start();
    return downloadId;
}
Also used : Cursor(android.database.Cursor) DownloadManager(android.app.DownloadManager) Uri(android.net.Uri) IOException(java.io.IOException) CursorIndexOutOfBoundsException(android.database.CursorIndexOutOfBoundsException) CursorIndexOutOfBoundsException(android.database.CursorIndexOutOfBoundsException) ChatResponse(com.fanap.podchat.model.ChatResponse) ResultDownloadFile(com.fanap.podchat.chat.file_manager.download_file.model.ResultDownloadFile) File(java.io.File)

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