use of com.fanap.podchat.networking.api.FileApi 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;
}
use of com.fanap.podchat.networking.api.FileApi 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;
}
use of com.fanap.podchat.networking.api.FileApi in project pod-chat-android-sdk by FanapSoft.
the class PodUploader method uploadFileToChatServer.
public static Subscription uploadFileToChatServer(String uniqueId, @NonNull Uri fileUri, Context context, String fileServer, String token, int tokenIssuer, IPodUploadFile 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("file", file.getName(), requestFile);
Observable<Response<FileUpload>> uploadObservable = fileApi.sendFile(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));
}
}
});
}
use of com.fanap.podchat.networking.api.FileApi in project pod-chat-android-sdk by FanapSoft.
the class PodUploader method uploadFileToPodSpace.
private static Subscription uploadFileToPodSpace(String uniqueId, String threadHashCode, String fileServer, String token, int tokenIssuer, IPodUploadFileToPodSpace listener, String mimeType, File file, long fileSize) {
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);
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.uploadToPodSpace(filePart, token, tokenIssuer, namePart, hashGroupPart);
long finalFileSize = fileSize;
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) finalFileSize, 0);
listener.onSuccess(response.body().getUploadToPodSpaceResult(), file, mimeType, finalFileSize);
} 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));
}
use of com.fanap.podchat.networking.api.FileApi in project pod-chat-android-sdk by FanapSoft.
the class PodUploader method uploadPublicImageToPodSpace.
private static Subscription uploadPublicImageToPodSpace(String uniqueId, String fileServer, String token, int tokenIssuer, String xC, String yC, String hC, String wC, boolean isPublic, IPodUploadFileToPodSpace listener, String mimeType, File file, long fileSize) throws FileNotFoundException {
int width = 0;
int height = 0;
String nWidth = "";
String nHeight = "";
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) && Long.parseLong(wC) > 0 ? wC : String.valueOf(width);
nHeight = !Util.isNullOrEmpty(hC) && Long.parseLong(hC) > 0 ? 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 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.uploadPublicImageToPodSpace(filePart, token, tokenIssuer, namePart, xCPart, yCPart, wCPart, hCPart, isPublic);
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));
}
Aggregations