Search in sources :

Example 91 with ChatResponse

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

the class ChatCore method handleEditMessage.

private void handleEditMessage(ChatMessage chatMessage, String messageUniqueId) {
    if (sentryResponseLog) {
        showLog("RECEIVE_EDIT_MESSAGE", gson.toJson(chatMessage));
    } else {
        showLog("RECEIVE_EDIT_MESSAGE");
    }
    ChatResponse<ResultNewMessage> chatResponse = new ChatResponse<>();
    ResultNewMessage newMessage = new ResultNewMessage();
    MessageVO messageVO = gson.fromJson(chatMessage.getContent(), MessageVO.class);
    if (messageVO.getMessage().startsWith("#")) {
        Log.e(TAG, "hashtag: " + "hello");
        String hashtag = messageVO.getMessage().substring(0, messageVO.getMessage().indexOf(' '));
        Log.e(TAG, "hashtag: " + hashtag);
    }
    if (cache) {
        dataSource.updateMessageResultFromServer(messageVO, chatMessage.getSubjectId());
    }
    newMessage.setMessageVO(messageVO);
    newMessage.setThreadId(chatMessage.getSubjectId());
    chatResponse.setResult(newMessage);
    chatResponse.setUniqueId(chatMessage.getUniqueId());
    chatResponse.setSubjectId(chatMessage.getSubjectId());
    String content = gson.toJson(chatResponse);
    messageCallbacks.remove(messageUniqueId);
    listenerManager.callOnEditedMessage(content, chatResponse);
}
Also used : ResultNewMessage(com.fanap.podchat.model.ResultNewMessage) ChatResponse(com.fanap.podchat.model.ChatResponse) GapMessageVO(com.fanap.podchat.cachemodel.GapMessageVO) CacheMessageVO(com.fanap.podchat.cachemodel.CacheMessageVO) MessageVO(com.fanap.podchat.mainmodel.MessageVO)

Example 92 with ChatResponse

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

the class ChatCore method mainMapStaticImage.

private String mainMapStaticImage(RequestLocationMessage request, Activity activity, String uniqueId, boolean isMessage, ProgressHandler.sendFileMessage handler) {
    try {
        if (Util.isNullOrEmpty(uniqueId)) {
            uniqueId = generateUniqueId();
        }
        if (needReadStoragePermission(activity))
            return uniqueId;
        if (chatReady) {
            JsonObject jsonLog = new JsonObject();
            String type = request.getType();
            int zoom = request.getZoom();
            int width = request.getWidth();
            int height = request.getHeight();
            String center = request.getCenter();
            long threadId = request.getThreadId();
            int messageType = request.getMessageType() > 0 ? request.getMessageType() : TextMessageType.Constants.POD_SPACE_PICTURE;
            String systemMetadata = request.getSystemMetadata();
            if (Util.isNullOrEmpty(type)) {
                type = "standard-night";
            }
            if (Util.isNullOrEmpty(zoom)) {
                zoom = 15;
            }
            if (Util.isNullOrEmpty(width)) {
                width = 800;
            }
            if (Util.isNullOrEmpty(height)) {
                height = 500;
            }
            RetrofitHelperMap retrofitHelperMap = new RetrofitHelperMap("https://api.neshan.org/");
            MapApi mapApi = retrofitHelperMap.getService(MapApi.class);
            Call<ResponseBody> call = mapApi.mapStaticCall(API_KEY_MAP, type, zoom, center, width, height);
            String finalUniqueId = uniqueId;
            jsonLog.addProperty("type", type);
            jsonLog.addProperty("zoom", zoom);
            jsonLog.addProperty("width", width);
            jsonLog.addProperty("height", height);
            jsonLog.addProperty("center", center);
            jsonLog.addProperty("threadId", threadId);
            jsonLog.addProperty("messageType", messageType);
            jsonLog.addProperty("systemMetadata", systemMetadata);
            jsonLog.addProperty("uniqueId", uniqueId);
            showLog("SEND_LOCATION_MESSAGE", getJsonForLog(jsonLog));
            call.enqueue(new retrofit2.Callback<ResponseBody>() {

                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response.isSuccessful()) {
                        if (response.body() != null) {
                            Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream());
                            ChatResponse<ResultStaticMapImage> chatResponse = new ChatResponse<>();
                            ResultStaticMapImage result = new ResultStaticMapImage();
                            result.setBitmap(bitmap);
                            chatResponse.setUniqueId(finalUniqueId);
                            chatResponse.setResult(result);
                            listenerManager.callOnStaticMap(chatResponse);
                            showLog("RECEIVE_MAP_STATIC");
                            if (!call.isCanceled()) {
                                call.cancel();
                            }
                            if (isMessage) {
                                File file = null;
                                try {
                                    file = FileUtils.saveBitmap(bitmap, "map");
                                } catch (Exception e) {
                                    captureError(ChatConstant.ERROR_WRITING_FILE, ChatConstant.ERROR_CODE_WRITING_FILE, finalUniqueId, e);
                                }
                                if (file == null) {
                                    captureError(ChatConstant.ERROR_WRITING_FILE, ChatConstant.ERROR_CODE_WRITING_FILE, finalUniqueId);
                                    return;
                                }
                                Uri fileUri = Uri.fromFile(file);
                                if (!chatReady) {
                                    onChatNotReady(finalUniqueId);
                                    return;
                                }
                                if (getPodSpaceServer() == null) {
                                    captureError("PodSpace server is null", 0, finalUniqueId);
                                    return;
                                }
                                removeFromUploadQueue(finalUniqueId);
                                try {
                                    Subscription subscription = PodUploader.uploadToPodSpace(finalUniqueId, fileUri, request.getUserGroupHash(), context, getPodSpaceServer(), getToken(), TOKEN_ISSUER, new PodUploader.IPodUploadFileToPodSpace() {

                                        @Override
                                        public void onSuccess(UploadToPodSpaceResult response, File file, String mimeType, long length, int actualWidth, int actualHeight, int width, int height) {
                                            removeFromUploadQueue(finalUniqueId);
                                            ChatResponse<ResultImageFile> chatResponse = PodUploader.generateImageUploadResultForSendMessage(response, finalUniqueId, 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);
                                            sendTextMessageWithFile(request.getMessage(), threadId, jsonMeta, systemMetadata, finalUniqueId, typeCode, messageType);
                                        }

                                        @Override
                                        public void onFailure(String cause, Throwable t) {
                                            String jsonError = captureError(cause, ChatConstant.ERROR_CODE_UPLOAD_FILE, finalUniqueId, t);
                                            ErrorOutPut error = new ErrorOutPut(true, ChatConstant.ERROR_INVALID_FILE_URI, ChatConstant.ERROR_CODE_INVALID_FILE_URI, finalUniqueId);
                                            if (handler != null) {
                                                handler.onError(jsonError, error);
                                            }
                                        }

                                        @Override
                                        public void onUploadStarted(String mimeType, File file, long length) {
                                            addToUploadQueue(request.getMessage(), fileUri, messageType, threadId, request.getUserGroupHash(), finalUniqueId, systemMetadata, request.getMessageId(), mimeType, request.getCenter(), ChatConstant.METHOD_LOCATION_MSG, file, length);
                                            showLog("UPLOAD_FILE_TO_SERVER");
                                        }

                                        @Override
                                        public void onProgressUpdate(int progress, int totalBytesSent, int totalBytesToSend) {
                                            if (handler != null)
                                                handler.onProgressUpdate(finalUniqueId, progress, totalBytesSent, totalBytesToSend);
                                        }
                                    });
                                    initCancelUpload(finalUniqueId, subscription);
                                } catch (Exception e) {
                                    String jsonError = captureError(ChatConstant.ERROR_INVALID_FILE_URI, ChatConstant.ERROR_CODE_INVALID_FILE_URI, finalUniqueId, e);
                                    ErrorOutPut error = new ErrorOutPut(true, ChatConstant.ERROR_INVALID_FILE_URI, ChatConstant.ERROR_CODE_INVALID_FILE_URI, finalUniqueId);
                                    if (handler != null) {
                                        handler.onError(jsonError, error);
                                    }
                                }
                            }
                        }
                    } else {
                        captureError(ChatConstant.ERROR_CALL_NESHAN_API, ChatConstant.ERROR_CODE_CALL_NESHAN_API, finalUniqueId);
                        showErrorLog(response.message());
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    captureError(t.getMessage(), ChatConstant.ERROR_CODE_UNKNOWN_EXCEPTION, finalUniqueId, t);
                }
            });
        } else {
            captureError(ChatConstant.ERROR_CHAT_READY, ChatConstant.ERROR_CODE_CHAT_READY, uniqueId);
        }
    } catch (Throwable throwable) {
        showErrorLog(throwable.getMessage());
        onUnknownException(uniqueId, throwable);
    }
    return uniqueId;
}
Also used : ResultStaticMapImage(com.fanap.podchat.model.ResultStaticMapImage) JsonObject(com.google.gson.JsonObject) Uri(android.net.Uri) RetrofitHelperMap(com.fanap.podchat.networking.retrofithelper.RetrofitHelperMap) MapApi(com.fanap.podchat.networking.api.MapApi) ResultImageFile(com.fanap.podchat.model.ResultImageFile) Bitmap(android.graphics.Bitmap) ChatResponse(com.fanap.podchat.model.ChatResponse) ErrorOutPut(com.fanap.podchat.model.ErrorOutPut) Subscription(rx.Subscription) 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) ProgressResponseBody(com.fanap.podchat.networking.ProgressResponseBody) ResponseBody(okhttp3.ResponseBody) UploadToPodSpaceResult(com.fanap.podchat.chat.file_manager.upload_file.UploadToPodSpaceResult) 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 93 with ChatResponse

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

the class ChatCore method publishContactResult.

private void publishContactResult(String uniqueId, long offset, ArrayList<Contact> cacheContactsList, int contentCount) {
    ChatResponse<ResultContact> chatResponse = new ChatResponse<>();
    ResultContact resultContact = new ResultContact();
    resultContact.setContacts(cacheContactsList);
    chatResponse.setResult(resultContact);
    chatResponse.setCache(true);
    chatResponse.setUniqueId(uniqueId);
    long nextOffset = cacheContactsList.size() + offset;
    boolean hasNext = nextOffset < contentCount;
    resultContact.setContentCount(contentCount);
    resultContact.setNextOffset(nextOffset);
    resultContact.setHasNext(hasNext);
    String contactJson = gson.toJson(chatResponse);
    listenerManager.callOnGetContacts(contactJson, chatResponse);
    if (sentryResponseLog) {
        showLog("CACHE_GET_CONTACT", contactJson);
    } else {
        showLog("CACHE_GET_CONTACT");
    }
}
Also used : ResultContact(com.fanap.podchat.model.ResultContact) ChatResponse(com.fanap.podchat.model.ChatResponse)

Example 94 with ChatResponse

use of com.fanap.podchat.model.ChatResponse 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 95 with ChatResponse

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

the class ChatCore method searchContact.

// public String searchContact(RequestSearchContact requestSearchContact) {
// 
// String uniqueId = generateUniqueId();
// 
// Runnable cacheLoading = () -> {
// 
// if (cache && requestSearchContact.canUseCache()) {
// List<Contact> contacts = new ArrayList<>();
// if (requestSearchContact.getId() != null) {
// Contact contact = messageDatabaseHelper.getContactById(Long.parseLong(requestSearchContact.getId()));
// contacts.add(contact);
// } else if (requestSearchContact.getFirstName() != null) {
// contacts = messageDatabaseHelper.getContactsByFirst(requestSearchContact.getFirstName());
// } else if (requestSearchContact.getFirstName() != null && requestSearchContact.getLastName() != null && !requestSearchContact.getFirstName().isEmpty() && !requestSearchContact.getLastName().isEmpty()) {
// contacts = messageDatabaseHelper.getContactsByFirstAndLast(requestSearchContact.getFirstName(), requestSearchContact.getLastName());
// } else if (requestSearchContact.getEmail() != null && !requestSearchContact.getEmail().isEmpty()) {
// contacts = messageDatabaseHelper.getContactsByEmail(requestSearchContact.getEmail());
// } else if (requestSearchContact.getCellphoneNumber() != null && !requestSearchContact.getCellphoneNumber().isEmpty()) {
// contacts = messageDatabaseHelper.getContactByCell(requestSearchContact.getCellphoneNumber());
// }
// 
// ChatResponse<ResultContact> chatResponse = new ChatResponse<>();
// chatResponse.setCache(true);
// 
// ResultContact resultContact = new ResultContact();
// ArrayList<Contact> listContact = new ArrayList<>(contacts);
// resultContact.setContacts(listContact);
// chatResponse.setUniqueId(uniqueId);
// chatResponse.setHasError(false);
// chatResponse.setErrorCode(0);
// chatResponse.setErrorMessage("");
// chatResponse.setResult(resultContact);
// 
// String jsonContact = gson.toJson(chatResponse);
// listenerManager.callOnSearchContact(jsonContact, chatResponse);
// showLog("CACHE_SEARCH_CONTACT", jsonContact);
// 
// 
// }
// };
// 
// Runnable requestServer = () -> {
// if (chatReady) {
// 
// JsonObject jsonObject = (JsonObject) gson.toJsonTree(requestSearchContact);
// 
// jsonObject.addProperty("uniqueId", uniqueId);
// 
// jsonObject.addProperty("tokenIssuer", 1);
// 
// showLog("SEND_SEARCH_CONTACT", getJsonForLog(jsonObject));
// 
// 
// Observable<Response<SearchContactVO>> observable = contactApi.searchContact(
// getToken(),
// TOKEN_ISSUER,
// requestSearchContact.getId()
// , requestSearchContact.getFirstName()
// , requestSearchContact.getLastName()
// , requestSearchContact.getEmail()
// , null
// , requestSearchContact.getOffset()
// , requestSearchContact.getSize()
// , null
// , requestSearchContact.getQuery()
// , requestSearchContact.getCellphoneNumber());
// 
// observable
// .subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread())
// .subscribe(contactResponse -> {
// 
// 
// if (contactResponse.isSuccessful()) {
// 
// if (contactResponse.body() != null && contactResponse.body().getResult() != null) {
// 
// ArrayList<Contact> contacts = new ArrayList<>(contactResponse.body().getResult());
// 
// ResultContact resultContacts = new ResultContact();
// resultContacts.setContacts(contacts);
// 
// ChatResponse<ResultContact> chatResponse = new ChatResponse<>();
// chatResponse.setUniqueId(uniqueId);
// chatResponse.setResult(resultContacts);
// 
// String content = gson.toJson(chatResponse);
// 
// 
// showLog("RECEIVE_SEARCH_CONTACT", content);
// 
// listenerManager.callOnSearchContact(content, chatResponse);
// 
// }
// 
// } else {
// 
// if (contactResponse.body() != null) {
// String errorMessage = contactResponse.body().getMessage() != null ? contactResponse.body().getMessage() : "";
// int errorCode = contactResponse.body().getErrorCode() != null ? contactResponse.body().getErrorCode() : 0;
// getErrorOutPut(errorMessage, errorCode, uniqueId);
// }
// }
// 
// }, (Throwable throwable) -> Log.e(TAG, throwable.getMessage()));
// } else {
// getErrorOutPut(ChatConstant.ERROR_CHAT_READY, ChatConstant.ERROR_CODE_CHAT_READY, uniqueId);
// }
// };
// 
// 
// new PodThreadManager()
// .addNewTask(cacheLoading)
// .addNewTask(requestServer)
// .runTasksSynced();
// 
// return uniqueId;
// }
public String searchContact(RequestSearchContact requestSearchContact) {
    String uniqueId = generateUniqueId();
    String size = !Util.isNullOrEmpty(requestSearchContact.getSize()) && !requestSearchContact.getSize().equals("0") ? requestSearchContact.getSize() : "50";
    String offset = !Util.isNullOrEmpty(requestSearchContact.getOffset()) ? requestSearchContact.getOffset() : "0";
    String order = !Util.isNullOrEmpty(requestSearchContact.getOrder()) ? requestSearchContact.getOrder() : "asc";
    Runnable cacheLoading = () -> {
        if (cache && requestSearchContact.canUseCache()) {
            ChatResponse<ResultContact> chatResponse = messageDatabaseHelper.searchContacts(requestSearchContact, size, offset);
            chatResponse.setUniqueId(uniqueId);
            String jsonContact = gson.toJson(chatResponse);
            listenerManager.callOnSearchContact(jsonContact, chatResponse);
            showLog("CACHE_SEARCH_CONTACT", jsonContact);
        }
    };
    Runnable requestServer = () -> {
        if (chatReady) {
            JsonObject jObj = new JsonObject();
            String query = requestSearchContact.getQuery();
            if (Util.isNullOrEmpty(query)) {
                query = "";
                if (!Util.isNullOrEmpty(requestSearchContact.getFirstName())) {
                    query += requestSearchContact.getFirstName() + " ";
                }
                if (!Util.isNullOrEmpty(requestSearchContact.getLastName())) {
                    query += requestSearchContact.getLastName();
                }
            }
            if (!Util.isNullOrEmpty(query)) {
                jObj.addProperty("query", query);
            }
            if (!Util.isNullOrEmpty(requestSearchContact.getEmail())) {
                jObj.addProperty("email", requestSearchContact.getEmail());
            }
            if (!Util.isNullOrEmpty(requestSearchContact.getCellphoneNumber())) {
                jObj.addProperty("cellphoneNumber", requestSearchContact.getCellphoneNumber());
            }
            if (!Util.isNullOrEmpty(requestSearchContact.getId())) {
                jObj.addProperty("id", requestSearchContact.getId());
            }
            jObj.addProperty("size", size);
            jObj.addProperty("offset", offset);
            jObj.addProperty("order", order);
            AsyncMessage chatMessage = new AsyncMessage();
            chatMessage.setContent(jObj.toString());
            chatMessage.setType(Constants.GET_CONTACTS);
            chatMessage.setToken(getToken());
            chatMessage.setUniqueId(uniqueId);
            chatMessage.setTypeCode(!Util.isNullOrEmpty(typeCode) ? typeCode : getTypeCode());
            chatMessage.setTokenIssuer(String.valueOf(TOKEN_ISSUER));
            JsonObject jsonObject = (JsonObject) gson.toJsonTree(chatMessage);
            String asyncContent = jsonObject.toString();
            setCallBacks(null, null, null, true, Constants.GET_CONTACTS, Long.valueOf(offset), uniqueId);
            handlerSend.put(uniqueId, new ChatHandler() {

                @Override
                public void onGetContact(String contactJson, ChatResponse<ResultContact> chatResponse) {
                    super.onGetContact(contactJson, chatResponse);
                    showLog("RECEIVE_SEARCH_CONTACT", contactJson);
                    listenerManager.callOnSearchContact(contactJson, chatResponse);
                    handlerSend.remove(uniqueId);
                }
            });
            sendAsyncMessage(asyncContent, AsyncAckType.Constants.WITHOUT_ACK, "SEND_SEARCH_CONTACT");
        } else {
            captureError(ChatConstant.ERROR_CHAT_READY, ChatConstant.ERROR_CODE_CHAT_READY, uniqueId);
        }
    };
    new PodThreadManager().addNewTask(cacheLoading).addNewTask(requestServer).runTasksSynced();
    return uniqueId;
}
Also used : PodThreadManager(com.fanap.podchat.util.PodThreadManager) AsyncMessage(com.fanap.podchat.mainmodel.AsyncMessage) ChatResponse(com.fanap.podchat.model.ChatResponse) JsonObject(com.google.gson.JsonObject)

Aggregations

ChatResponse (com.fanap.podchat.model.ChatResponse)162 ChatListener (com.fanap.podchat.chat.ChatListener)38 Test (org.junit.Test)38 ArrayList (java.util.ArrayList)35 Thread (com.fanap.podchat.mainmodel.Thread)29 JsonSyntaxException (com.google.gson.JsonSyntaxException)29 ResultHistory (com.fanap.podchat.model.ResultHistory)28 LargeTest (android.support.test.filters.LargeTest)27 RequestThread (com.fanap.podchat.requestobject.RequestThread)27 PodChatException (com.fanap.podchat.util.PodChatException)26 MessageVO (com.fanap.podchat.mainmodel.MessageVO)25 RoomIntegrityException (com.fanap.podchat.persistance.RoomIntegrityException)23 IOException (java.io.IOException)23 JSONException (org.json.JSONException)22 ResultThreads (com.fanap.podchat.model.ResultThreads)21 RequestGetHistory (com.fanap.podchat.requestobject.RequestGetHistory)21 SentryException (io.sentry.core.protocol.SentryException)21 FlakyTest (android.support.test.filters.FlakyTest)19 MediumTest (android.support.test.filters.MediumTest)19 Activity (android.app.Activity)17