use of com.fanap.podchat.util.PodThreadManager in project pod-chat-android-sdk by FanapSoft.
the class ChatCore method retryUpload.
/**
* It retry upload that they didn't send
*/
// public void retryUpload(RetryUpload retry, ProgressHandler.sendFileMessage handler) {
//
// Runnable retryTask = () -> {
// String uniqueId = retry.getUniqueId();
// Activity activity = retry.getActivity();
//
// UploadingQueueCache uploadingQ;
// if (cache) {
// uploadingQ = messageDatabaseHelper.getUploadingQ(uniqueId);
// } else {
// uploadingQ = uploadingQList.get(uniqueId);
// }
//
// if (uploadingQ != null) {
// long messageId = uploadingQ.getId();
// int messageType = uploadingQ.getMessageType();
// long threadId = uploadingQ.getThreadId();
// String message = uploadingQ.getMessage();
// String systemMetadata = uploadingQ.getSystemMetadata();
// MetaDataFile metaDataFile = gson.fromJson(systemMetadata, MetaDataFile.class);
// String link = metaDataFile.getFile().getLink();
// String mimeType = metaDataFile.getFile().getMimeType();
//
// LFileUpload lFileUpload = new LFileUpload();
// lFileUpload.setActivity(activity);
// lFileUpload.setDescription(message);
// lFileUpload.setFileUri(Uri.parse(link));
// lFileUpload.setHandler(handler);
// lFileUpload.setMessageType(messageType);
// lFileUpload.setThreadId(threadId);
// lFileUpload.setUniqueId(uniqueId);
// lFileUpload.setSystemMetaData(systemMetadata);
// lFileUpload.setHandler(handler);
// lFileUpload.setMimeType(mimeType);
//
// if (!Util.isNullOrEmpty(messageId)) {
// String methodName = ChatConstant.METHOD_REPLY_MSG;
// lFileUpload.setMethodName(methodName);
// }
//
// removeFromUploadQueue(uniqueId);
//
// if (FileUtils.isImage(mimeType) && !FileUtils.isGif(mimeType)) {
// uploadImageFileMessage(lFileUpload);
// } else {
// uploadFileMessage(lFileUpload);
// }
//
// }
// };
//
// new PodThreadManager()
// .doThisAndGo(retryTask);
//
// }
public void retryUpload(RetryUpload retry, ProgressHandler.sendFileMessage handler) {
Runnable retryTask = () -> {
String uniqueId = retry.getUniqueId();
Activity activity = retry.getActivity();
UploadingQueueCache uploadingQ;
if (cache) {
uploadingQ = dataSource.getUploadingQ(uniqueId);
// uploadingQ = messageDatabaseHelper.getUploadingQ(uniqueId);
} else {
uploadingQ = uploadingQList.get(uniqueId);
}
if (uploadingQ != null) {
long messageId = uploadingQ.getId();
int messageType = uploadingQ.getMessageType();
long threadId = uploadingQ.getThreadId();
String userGroupHash = uploadingQ.getUserGroupHash();
String methodName = !Util.isNullOrEmpty(messageId) ? ChatConstant.METHOD_REPLY_MSG : null;
String message = uploadingQ.getMessage();
String systemMetadata = uploadingQ.getSystemMetadata();
String metadata = uploadingQ.getMetadata();
MetaDataFile metaDataFile = gson.fromJson(metadata, MetaDataFile.class);
String link = null;
try {
link = metaDataFile.getFile().getLink();
} catch (Exception e) {
Log.e(TAG, "Couldn't retrieve link");
}
if (needReadStoragePermission(activity)) {
String jsonError = captureError(ChatConstant.ERROR_READ_EXTERNAL_STORAGE_PERMISSION, ChatConstant.ERROR_CODE_READ_EXTERNAL_STORAGE_PERMISSION, uniqueId);
ErrorOutPut error = new ErrorOutPut(true, ChatConstant.ERROR_READ_EXTERNAL_STORAGE_PERMISSION, ChatConstant.ERROR_CODE_READ_EXTERNAL_STORAGE_PERMISSION, uniqueId);
if (handler != null) {
handler.onError(jsonError, error);
}
return;
}
if (!chatReady) {
onChatNotReady(uniqueId);
return;
}
if (getPodSpaceServer() == null) {
captureError("File server is null", 0, uniqueId);
return;
}
removeFromUploadQueue(uniqueId);
try {
String finalLink = link;
Subscription subscription = PodUploader.uploadToPodSpace(uniqueId, Util.isNullOrEmpty(link) ? null : Uri.parse(link), userGroupHash, context, getPodSpaceServer(), getToken(), TOKEN_ISSUER, new PodUploader.IPodUploadFileToPodSpace() {
@Override
public void onSuccess(UploadToPodSpaceResult response, File file, String mimeType, long length) {
removeFromUploadQueue(uniqueId);
ChatResponse<ResultFile> chatResponse = PodUploader.generateImageUploadResultForSendMessage(response, uniqueId);
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, response.getHashCode(), 0, mimeType, length, response.getParentHash());
if (isReplyMessage(methodName)) {
showLog("SEND_REPLY_FILE_MESSAGE", jsonMeta);
mainReplyMessage(message, threadId, messageId, systemMetadata, messageType, jsonMeta, uniqueId, null);
} else {
sendTextMessageWithFile(message, threadId, jsonMeta, systemMetadata, uniqueId, typeCode, messageType);
}
}
@Override
public void onSuccess(UploadToPodSpaceResult response, File file, String mimeType, long length, int actualWidth, int actualHeight, int width, int height) {
removeFromUploadQueue(uniqueId);
ChatResponse<ResultImageFile> chatResponse = PodUploader.generateImageUploadResultForSendMessage(response, uniqueId, actualWidth, actualHeight, width, height, getPodSpaceImageUrl(response.getHashCode()));
String imageJson = gson.toJson(chatResponse);
listenerManager.callOnUploadImageFile(imageJson, chatResponse);
if (handler != null) {
handler.onFinishImage(imageJson, chatResponse);
}
showLog("RECEIVE_UPLOAD_IMAGE", imageJson);
String jsonMeta = createImageMetadata(file, response.getHashCode(), 0, height, width, mimeType, length, response.getParentHash(), false, null);
if (isReplyMessage(methodName)) {
showLog("SEND_REPLY_FILE_MESSAGE", jsonMeta);
mainReplyMessage(message, threadId, messageId, systemMetadata, messageType, jsonMeta, uniqueId, null);
} else {
sendTextMessageWithFile(message, threadId, jsonMeta, systemMetadata, uniqueId, typeCode, messageType);
}
}
@Override
public void onFailure(String cause, Throwable t) {
String jsonError = captureError(cause, ChatConstant.ERROR_CODE_UPLOAD_FILE, uniqueId, t);
ErrorOutPut error = new ErrorOutPut(true, ChatConstant.ERROR_INVALID_FILE_URI, ChatConstant.ERROR_CODE_INVALID_FILE_URI, uniqueId);
if (handler != null) {
handler.onError(jsonError, error);
}
}
@Override
public void onUploadStarted(String mimeType, File file, long length) {
addToUploadQueue(message, Util.isNullOrEmpty(finalLink) ? null : Uri.parse(finalLink), messageType, threadId, userGroupHash, uniqueId, systemMetadata, messageId, mimeType, null, methodName, file, length);
showLog("UPLOAD_FILE_TO_SERVER");
}
@Override
public void onProgressUpdate(int progress, int totalBytesSent, int totalBytesToSend) {
if (handler != null)
handler.onProgressUpdate(uniqueId, progress, totalBytesSent, totalBytesToSend);
}
});
initCancelUpload(uniqueId, subscription);
} catch (Exception e) {
String jsonError = captureError(ChatConstant.ERROR_INVALID_FILE_URI, ChatConstant.ERROR_CODE_INVALID_FILE_URI, uniqueId, e);
ErrorOutPut error = new ErrorOutPut(true, ChatConstant.ERROR_INVALID_FILE_URI, ChatConstant.ERROR_CODE_INVALID_FILE_URI, uniqueId);
if (handler != null) {
handler.onError(jsonError, error);
}
}
}
};
new PodThreadManager().doThisAndGo(retryTask);
}
use of com.fanap.podchat.util.PodThreadManager in project pod-chat-android-sdk by FanapSoft.
the class ChatCore method addGroupContacts.
private PublishSubject<List<PhoneContact>> addGroupContacts(List<PhoneContact> phoneContacts, String uniqueId) {
PublishSubject<List<PhoneContact>> subject = PublishSubject.create();
ArrayList<String> firstNames = new ArrayList<>();
ArrayList<String> cellphoneNumbers = new ArrayList<>();
ArrayList<String> lastNames = new ArrayList<>();
ArrayList<String> typeCodes = new ArrayList<>();
ArrayList<String> uniqueIds = new ArrayList<>();
ArrayList<String> emails = new ArrayList<>();
for (PhoneContact contact : phoneContacts) {
firstNames.add(contact.getName());
lastNames.add(contact.getLastName());
uniqueIds.add(generateUniqueId());
String phoneNum = String.valueOf(contact.getPhoneNumber());
if (phoneNum.startsWith("9")) {
phoneNum = phoneNum.replaceFirst("9", "09");
}
cellphoneNumbers.add(phoneNum);
emails.add("");
typeCodes.add(getTypeCode());
}
Observable<Response<Contacts>> addContactsObservable;
if (getPlatformHost() != null) {
if (!Util.isNullOrEmpty(getTypeCode())) {
addContactsObservable = contactApi.addContacts(getToken(), TOKEN_ISSUER, firstNames, lastNames, emails, uniqueIds, cellphoneNumbers, typeCodes);
} else {
addContactsObservable = contactApi.addContacts(getToken(), TOKEN_ISSUER, firstNames, lastNames, emails, uniqueIds, cellphoneNumbers);
}
showLog("Call add contacts " + new Date());
addContactsObservable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(contactsResponse -> {
showLog(">>> Server Respond " + new Date());
boolean error = false;
if (contactsResponse.body() != null) {
error = contactsResponse.body().getHasError();
showLog(">>>Response: " + contactsResponse.code());
showLog(">>>ReferenceNumber: " + contactsResponse.body().getReferenceNumber());
showLog(">>>Ott: " + contactsResponse.body().getOtt());
}
if (contactsResponse.isSuccessful()) {
if (error) {
captureError(contactsResponse.body().getMessage(), contactsResponse.body().getErrorCode(), uniqueId);
showLog("Error add Contacts: " + contactsResponse.body().getMessage());
subject.onError(new Throwable(contactsResponse.body().getMessage()));
} else {
// successful response
Contacts contacts = contactsResponse.body();
ChatResponse<Contacts> chatResponse = new ChatResponse<>();
chatResponse.setResult(contacts);
chatResponse.setUniqueId(uniqueId);
Runnable updatePhoneContactsDBTask = () -> {
try {
boolean result = phoneContactDbHelper.addPhoneContacts(phoneContacts);
if (!result) {
disableCache(() -> phoneContactDbHelper.addPhoneContacts(phoneContacts));
}
} catch (Exception e) {
showErrorLog("Updating Contacts cache failed: " + e.getMessage());
onUnknownException(uniqueId, e);
}
};
Runnable updateCachedContactsTask = () -> {
if (cache) {
try {
// messageDatabaseHelper.saveContacts(chatResponse.getResult().getResult(), getExpireAmount());
dataSource.saveContactsResultFromServer(chatResponse.getResult().getResult());
} catch (Exception e) {
showErrorLog("Saving Contacts Failed: " + e.getMessage());
onUnknownException(uniqueId, e);
}
}
};
new PodThreadManager().addNewTask(updatePhoneContactsDBTask).addNewTask(updateCachedContactsTask).addNewTask(() -> subject.onNext(phoneContacts)).runTasksSynced();
}
} else {
captureError(contactsResponse.message(), contactsResponse.code(), uniqueId);
showLog("Error add Contacts: " + contactsResponse.raw());
subject.onError(new Throwable(contactsResponse.message()));
}
}, throwable -> {
captureError(throwable.getMessage(), ChatConstant.ERROR_CODE_UNKNOWN_EXCEPTION, uniqueId);
subject.onError(throwable);
});
}
return subject;
}
use of com.fanap.podchat.util.PodThreadManager in project pod-chat-android-sdk by FanapSoft.
the class ChatCore method getUserInfo.
/**
* It Gets the information of the current user
*/
public String getUserInfo(ChatHandler handler) {
String uniqueId = generateUniqueId();
Runnable cacheLoading = () -> {
if (permit && cache && handler != null) {
try {
UserInfo userInfo = messageDatabaseHelper.getUserInfo();
if (userInfo != null) {
ChatResponse<ResultUserInfo> chatResponse = new ChatResponse<>();
ResultUserInfo result = new ResultUserInfo();
setUserId(userInfo.getId());
result.setUser(userInfo);
chatResponse.setResult(result);
chatResponse.setCache(true);
chatResponse.setUniqueId(uniqueId);
String userInfoJson = gson.toJson(chatResponse);
listenerManager.callOnUserInfo(userInfoJson, chatResponse);
showLog("CACHE_USER_INFO", userInfoJson);
}
} catch (Exception e) {
showErrorLog(e.getMessage());
onUnknownException(uniqueId, e);
}
}
};
Runnable requestServer = () -> {
if (asyncReady) {
ChatMessage chatMessage = new ChatMessage();
chatMessage.setType(Constants.USER_INFO);
chatMessage.setUniqueId(uniqueId);
chatMessage.setToken(getToken());
chatMessage.setTokenIssuer("1");
setCallBacks(null, null, null, true, Constants.USER_INFO, null, uniqueId);
JsonObject jsonObject = (JsonObject) gson.toJsonTree(chatMessage);
if (Util.isNullOrEmpty(getTypeCode())) {
jsonObject.remove("typeCode");
} else {
jsonObject.remove("typeCode");
jsonObject.addProperty("typeCode", getTypeCode());
}
String asyncContent = jsonObject.toString();
showLog("SEND_USER_INFO", asyncContent);
async.sendMessage(asyncContent, AsyncAckType.Constants.WITHOUT_ACK);
if (handler != null) {
handler.onGetUserInfo(uniqueId);
}
}
};
new PodThreadManager().addNewTask(cacheLoading).addNewTask(requestServer).runTasksSynced();
return uniqueId;
}
use of com.fanap.podchat.util.PodThreadManager in project pod-chat-android-sdk by FanapSoft.
the class ChatCore method getBlockList.
/**
* It gets the list of the contacts that is on block list
*/
public String getBlockList(RequestBlockList request, ChatHandler handler) {
String uniqueId = generateUniqueId();
PodThreadManager threadManager = new PodThreadManager();
threadManager.addTask(() -> {
if (cache && request.useCacheData()) {
List<BlockedContact> cacheContacts = messageDatabaseHelper.getBlockedContacts(request.getCount(), request.getOffset());
if (!Util.isNullOrEmpty(cacheContacts)) {
ChatResponse<ResultBlockList> chatResponse = ContactManager.prepareGetBlockListFromCache(uniqueId, cacheContacts);
listenerManager.callOnGetBlockList(gson.toJson(chatResponse), chatResponse);
if (sentryResponseLog) {
showLog("RECEIVE_GET_BLOCK_LIST_FROM_CACHE", gson.toJson(chatResponse));
} else {
showLog("RECEIVE_GET_BLOCK_LIST_FROM_CACHE");
}
}
}
});
threadManager.addTask(() -> {
if (chatReady) {
String asyncContent = ContactManager.prepareGetBlockListRequest(request.getCount(), request.getOffset(), uniqueId, getTypeCode(), getToken());
setCallBacks(null, null, null, true, Constants.GET_BLOCKED, null, uniqueId);
sendAsyncMessage(asyncContent, AsyncAckType.Constants.WITHOUT_ACK, "SEND_GET_BLOCK_LIST");
if (handler != null) {
handler.onGetBlockList(uniqueId);
}
} else {
captureError(ChatConstant.ERROR_CHAT_READY, ChatConstant.ERROR_CODE_CHAT_READY, uniqueId);
}
});
threadManager.runTasksSynced();
return uniqueId;
}
use of com.fanap.podchat.util.PodThreadManager in project pod-chat-android-sdk by FanapSoft.
the class ExampleUnitTest method testOnComplete.
@Test
public void testOnComplete() {
// new PodThreadManager()
// .doWithUI(() -> {
// System.out.println("On UI Im on " + Thread.currentThread().getName());
//
// }, () -> {
// System.out.println("Error Im on " + Thread.currentThread().getName());
//
// }, () -> {
// System.out.println("Task Im on " + Thread.currentThread().getName());
//
// int a = 10;
// int b = 0;
//
// int c = a / b;
//
// });
new PodThreadManager().addNewTask(() -> {
System.out.println("aaa " + Thread.currentThread().getName());
//
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("aaa " + "aaa " + Thread.currentThread().getName());
}).addNewTask(() -> {
System.out.println("bbb " + Thread.currentThread().getName());
// try {
// Thread.sleep(2000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println("bbb " + "bbb " + Thread.currentThread().getName());
}).runTasksSynced();
new PodThreadManager().addNewTask(() -> {
System.out.println("aaa " + Thread.currentThread().getName());
//
// try {
// Thread.sleep(2000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println("aaa " + "aaa " + Thread.currentThread().getName());
}).addNewTask(() -> {
System.out.println("bbb " + Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("bbb " + "bbb " + Thread.currentThread().getName());
}).runTasksASync();
// new PodThreadManager()
// .doThisSafe(()->{
//
// System.out.println("aaa " + Thread.currentThread().getName());
//
// try {
// Thread.sleep(2000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// System.out.println("aaa " + "aaa " + Thread.currentThread().getName());
//
// }, new PodThreadManager.IComplete() {
// @Override
// public void onComplete() {
// System.out.println("v " + "aaa " + Thread.currentThread().getName());
//
// }
//
// @Override
// public void onError(String error) {
// System.out.println("a " + "aaa " + Thread.currentThread().getName());
//
// }
// });
}
Aggregations