use of net.iGap.structs.MessageObject in project iGap-Android by KianIranian-STDG.
the class FragmentChat method sendFromBot.
@Override
public void sendFromBot(Object message) {
if (message instanceof MessageObject) {
mAdapter.add(new TextItem(mAdapter, chatType, FragmentChat.this).setMessage((MessageObject) message).withIdentifier(SUID.id().get()));
scrollToEnd();
} else if (message instanceof String) {
openWebViewFragmentForSpecialUrlChat(message.toString());
}
}
use of net.iGap.structs.MessageObject in project iGap-Android by KianIranian-STDG.
the class FragmentChat method initComponent.
@SuppressLint("ClickableViewAccessibility")
private void initComponent() {
final RealmRoom realmRoom = getRoom();
ll_attach_text = rootView.findViewById(R.id.ac_ll_attach_text);
txtFileNameForSend = rootView.findViewById(R.id.ac_txt_file_neme_for_sending);
btnCancelSendingFile = rootView.findViewById(R.id.ac_btn_cancel_sending_file);
btnCancelSendingFile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ll_attach_text.setVisibility(View.GONE);
edtChat.setFilters(new InputFilter[] {});
edtChat.setText(EmojiManager.getInstance().replaceEmoji(edtChat.getText(), edtChat.getPaint().getFontMetricsInt(), LayoutCreator.dp(22), false));
edtChat.setSelection(edtChat.getText().length());
if (edtChat.getText().length() == 0) {
sendButtonVisibility(false);
}
}
});
// final int screenWidth = (int) (getResources().getDisplayMetrics().widthPixels / 1.2);
imvSmileButton = rootView.findViewById(R.id.tv_chatRoom_emoji);
edtChat.requestFocus();
edtChat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isEmojiSHow) {
imvSmileButton.performClick();
}
if (botInit != null)
botInit.close();
}
});
if (viewAttachFile != null) {
// LinearLayout linearLayout = (LinearLayout) viewAttachFile;
// voiceHintTextView = new HintView(G.context, 9);
}
imvAttachFileButton = rootView.findViewById(R.id.vtn_chatRoom_attach);
layoutAttachBottom = rootView.findViewById(R.id.ll_chatRoom_send);
imvMicButton = rootView.findViewById(R.id.btn_chatRoom_mic);
imvAddStoryButton = rootView.findViewById(R.id.btn_chatRoom_add_story);
actionButtonsRootView = rootView.findViewById(R.id.chat_action_buttons_root_view);
customStatusActionLayout = rootView.findViewById(R.id.custom_status_action_root);
floatActionLayout = rootView.findViewById(R.id.add_story_action_root);
customStatusActionLayout.setBackground(Theme.createSimpleSelectorCircleDrawable(LayoutCreator.dp(56), Theme.getInstance().getToolbarBackgroundColor(context), Theme.getInstance().getAccentColor(context)));
floatActionLayout.setBackground(Theme.createSimpleSelectorCircleDrawable(LayoutCreator.dp(56), Theme.getInstance().getToolbarBackgroundColor(context), Theme.getInstance().getAccentColor(context)));
hideFloatingButton(true);
if (isBot) {
botInit = new BotInit(rootView, false);
sendButtonVisibility(false);
RealmRoomMessage rm = null;
String lastMessage = "";
boolean backToMenu = true;
RealmResults<RealmRoomMessage> result = DbManager.getInstance().doRealmTask(realm -> {
return realm.where(RealmRoomMessage.class).equalTo("roomId", mRoomId).notEqualTo("authorHash", RealmUserInfo.getCurrentUserAuthorHash()).findAll();
});
if (result.size() > 0) {
rm = result.last();
if (rm.getMessage() != null) {
lastMessage = rm.getMessage();
}
}
try {
if (rm.getRealmAdditional() != null && rm.getRealmAdditional().getAdditionalType() == AdditionalType.UNDER_KEYBOARD_BUTTON) {
botInit.updateCommandList(false, lastMessage, getActivity(), backToMenu, rm, rm.getRoomId());
}
} catch (Exception e) {
}
}
mAdapter = new MessagesAdapter<>(managedRoom, this, this, this, avatarHandler, compositeDisposable, isCloudRoom);
mAdapter.getItemFilter().withFilterPredicate(new IItemAdapter.Predicate<AbstractMessage>() {
@Override
public boolean filter(AbstractMessage item, CharSequence constraint) {
return !item.messageObject.message.toLowerCase().contains(constraint.toString().toLowerCase());
}
});
// FragmentMain.PreCachingLayoutManager layoutManager = new FragmentMain.PreCachingLayoutManager(ActivityChat.this, 7500);
MyLinearLayoutManager layoutManager = new MyLinearLayoutManager(G.fragmentActivity);
layoutManager.setStackFromEnd(true);
if (recyclerView == null) {
recyclerView = rootView.findViewById(R.id.chl_recycler_view_chat);
}
recyclerView.setItemAnimator(null);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(mAdapter);
recyclerView.setItemViewCacheSize(20);
if (realmRoom != null && !realmRoom.getReadOnly()) {
ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return true;
}
@Override
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
super.clearView(recyclerView, viewHolder);
try {
// TODO: 12/28/20 MESSAGE_REFACTOR
MessageObject message_ = (mAdapter.getItem(viewHolder.getAdapterPosition())).messageObject;
if (message_ != null && message_.status != ProtoGlobal.RoomMessageStatus.SENDING_VALUE && message_.status != ProtoGlobal.RoomMessageStatus.FAILED_VALUE) {
if (isReply)
reply((mAdapter.getItem(viewHolder.getAdapterPosition())).messageObject, false);
}
} catch (Exception ignored) {
ignored.printStackTrace();
}
isReply = false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
}
@Override
public void onChildDraw(@NotNull Canvas c, @NotNull RecyclerView recyclerView, @NotNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
if (actionState == ACTION_STATE_SWIPE && isCurrentlyActive) {
setTouchListener(recyclerView, dX);
}
dX = dX + ViewMaker.dpToPixel(25);
if (dX > 0)
dX = 0;
if (dX < -ViewMaker.dpToPixel(150)) {
dX = -ViewMaker.dpToPixel(150);
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
@Override
public float getSwipeThreshold(@NonNull RecyclerView.ViewHolder viewHolder) {
return super.getSwipeThreshold(viewHolder);
}
@Override
public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
// TODO: 12/28/20 MESSAGE_REFACTOR
MessageObject message_ = null;
try {
message_ = (mAdapter.getItem(viewHolder.getAdapterPosition())).messageObject;
} catch (Exception e) {
e.printStackTrace();
}
if (message_ != null && (message_.status == ProtoGlobal.RoomMessageStatus.SENDING_VALUE || message_.status == ProtoGlobal.RoomMessageStatus.FAILED_VALUE)) {
return 0;
} else if (viewHolder instanceof VoiceItem.ViewHolder) {
return 0;
} else if (viewHolder instanceof AudioItem.ViewHolder) {
return 0;
} else if (viewHolder instanceof NewChatItemHolder) {
return super.getSwipeDirs(recyclerView, viewHolder);
}
// we disable swipe with returning Zero
return 0;
}
@Override
public int convertToAbsoluteDirection(int flags, int layoutDirection) {
if (swipeBack) {
swipeBack = false;
return 0;
}
return super.convertToAbsoluteDirection(flags, layoutDirection);
}
@Override
public boolean isItemViewSwipeEnabled() {
return !FragmentChat.isInSelectionMode;
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
}
/**
* load message , use handler for load async
*/
visibilityTextEmptyMessages();
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
visibilityTextEmptyMessages();
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
super.onItemRangeRemoved(positionStart, itemCount);
visibilityTextEmptyMessages();
}
});
// added run time -> counter of un read messages
llScrollNavigate = rootView.findViewById(R.id.ac_ll_scrool_navigate);
txtNewUnreadMessage = new BadgeView(getContext());
txtNewUnreadMessage.getTextView().setTypeface(ResourcesCompat.getFont(txtNewUnreadMessage.getContext(), R.font.main_font));
txtNewUnreadMessage.getTextView().setSingleLine();
// set max length
txtNewUnreadMessage.getTextView().setFilters(new InputFilter[] { new InputFilter.LengthFilter(5) });
txtNewUnreadMessage.setBadgeColor(new Theme().getPrimaryDarkColor(txtNewUnreadMessage.getContext()));
llScrollNavigate.addView(txtNewUnreadMessage, LayoutCreator.createFrame(LayoutCreator.WRAP_CONTENT, LayoutCreator.WRAP_CONTENT, Gravity.CENTER | Gravity.TOP));
G.handler.post(() -> {
AndroidUtils.globalQueue.postRunnable(this::getMessages);
manageForwardedMessage(false);
});
MaterialDesignTextView txtNavigationLayout = rootView.findViewById(R.id.ac_txt_down_navigation);
llScrollNavigate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cancelAllRequestFetchHistory();
// Todo : also needed: block future Request
latestButtonClickTime = System.currentTimeMillis();
/**
* have unread
*/
if (countNewMessage > 0 && getFirstUnreadMessage() != null) {
if (!getFirstUnreadMessage().isValid() || getFirstUnreadMessage().isDeleted()) {
resetAndGetFromEnd();
return;
}
int position = mAdapter.findPositionByMessageId(getFirstUnreadMessage().getMessageId());
String m = getFirstUnreadMessage().getMessage();
if (position > 0) {
mAdapter.add(position, new UnreadMessage(mAdapter, FragmentChat.this).setMessage(MessageObject.create(makeUnreadMessage(countNewMessage))).withIdentifier(SUID.id().get()));
isShowLayoutUnreadMessage = true;
LinearLayoutManager linearLayout = (LinearLayoutManager) recyclerView.getLayoutManager();
linearLayout.scrollToPositionWithOffset(position, 0);
} else {
resetMessagingValue();
unreadCount = countNewMessage;
getMessages();
if (getFirstUnreadMessage() == null) {
resetAndGetFromEnd();
return;
}
int position1 = mAdapter.findPositionByMessageId(getFirstUnreadMessage().getMessageId());
if (position1 > 0) {
LinearLayoutManager linearLayout = (LinearLayoutManager) recyclerView.getLayoutManager();
linearLayout.scrollToPositionWithOffset(position1 - 1, 0);
}
}
setCountNewMessageZero();
} else {
if (!addToView) {
resetMessagingValue();
getMessages();
} else {
scrollToEnd();
}
}
}
});
recyclerView.setOnFlingListener(new RecyclerView.OnFlingListener() {
@Override
public boolean onFling(int velocityX, int velocityY) {
return false;
}
});
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
G.imageLoader.resume();
} else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
G.imageLoader.pause();
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleItemCount = recyclerView.getLayoutManager().getChildCount();
int totalItemCount = recyclerView.getLayoutManager().getItemCount();
int pastVisibleItems = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
cardFloatingTime.setVisibility(View.VISIBLE);
long item = mAdapter.getItemByPosition(layoutManager.findFirstVisibleItemPosition());
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(item);
if (item != 0L) {
txtFloatingTime.setText(TimeUtils.getChatSettingsTimeAgo(G.fragmentActivity, calendar.getTime()));
}
gongingHandler.removeCallbacks(gongingRunnable);
gongingHandler.postDelayed(gongingRunnable, 1000);
if (totalItemCount - pastVisibleItems <= 2 && !isAnimateStart) {
isAnimateStart = true;
isAnimateStart = false;
setDownBtnGone();
// llScrollNavigate.animate()
// .alpha(0.0f)
// .translationY(llScrollNavigate.getHeight() / 2)
// .setDuration(200)
// .setListener(new AnimatorListenerAdapter() {
// @Override
// public void onAnimationEnd(Animator animation) {
// super.onAnimationEnd(animation);
// }
// });
} else if (!isScrollEnd && !isAnimateStart) {
isAnimateStart = true;
setDownBtnVisible();
isAnimateStart = false;
// llScrollNavigate.animate()
// .alpha(1.0f)
// .translationY(0)
// .setDuration(200)
// .setListener(new AnimatorListenerAdapter() {
// @Override
// public void onAnimationEnd(Animator animation) {
// super.onAnimationEnd(animation);
// }
// });
txtNewUnreadMessage.getTextView().setText(countNewMessage + "");
if (countNewMessage == 0) {
txtNewUnreadMessage.setVisibility(View.GONE);
} else {
txtNewUnreadMessage.setVisibility(View.VISIBLE);
}
}
}
});
/* if (event.getAction() == MotionEvent.ACTION_CANCEL) {
card.setCardBackgroundColor(Color.parseColor("#ffffff"));
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
// event.addBatch(0,0,0,0,0,0);
// card.setCardBackgroundColor(Color.parseColor("#ffffff"));
} else if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
card.setCardBackgroundColor(Color.parseColor("#20000000"));
} else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
*/
/* Reset Color */
/*
card.setCardBackgroundColor(Color.parseColor("#ffffff"));
// card.setOnClickListener(clickListener);
}
return false;
*/
recyclerView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
imvSendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
lastChar = null;
if (!addToView) {
resetAndGetFromEnd();
}
if (suggestedLayout != null) {
if (suggestedLayout.getVisibility() == View.VISIBLE)
suggestedLayout.setVisibility(View.GONE);
lastChar = null;
}
if (isShowLayoutUnreadMessage) {
removeLayoutUnreadMessage();
}
HelperSetAction.setCancel(mRoomId);
clearDraftRequest();
if (hasForward) {
manageForwardedMessage(false);
if (edtChat.getText().length() == 0) {
return;
}
}
if (ll_attach_text.getVisibility() == View.VISIBLE) {
if (listPathString.size() == 0) {
return;
}
sendMessage(latestRequestCode, listPathString.get(0));
listPathString.clear();
ll_attach_text.setVisibility(View.GONE);
edtChat.setFilters(new InputFilter[] {});
edtChat.setText("");
clearReplyView();
return;
}
if (edtChat.getTag() != null && edtChat.getTag() instanceof MessageObject) {
final MessageObject messageInfo = (MessageObject) edtChat.getTag();
final String message = getWrittenMessage();
if (!message.equals(messageInfo.message) && edtChat.getText().toString().trim().length() > 0) {
if (G.connectionState == ConnectionState.WAITING_FOR_NETWORK) {
Toast.makeText(getContext(), getResources().getString(R.string.please_check_your_connenction), Toast.LENGTH_SHORT).show();
return;
}
chatRoom_send_container.setVisibility(View.VISIBLE);
imvSendButton.setVisibility(View.GONE);
editTextProgress.setVisibility(View.VISIBLE);
getMessageController().editMessage(messageInfo.id, messageInfo.documentId, mRoomId, message, chatType.getNumber());
} else {
removeEditedMessage();
}
} else {
// new message has written
sendNewMessage(getWrittenMessage());
scrollToEnd();
}
oldMessageLentghCounter = 0;
messageLentghCounter = 0;
}
});
G.openBottomSheetItem = new OpenBottomSheetItem() {
@Override
public void openBottomSheet(boolean isNew) {
if (mAttachmentPopup != null)
mAttachmentPopup.setIsNewDialog(isNew);
imvAttachFileButton.performClick();
if (mAttachmentPopup != null)
mAttachmentPopup.notifyRecyclerView();
}
};
FragmentEditImage.completeEditImage = new FragmentEditImage.CompleteEditImage() {
@Override
public void result(String path, String message, HashMap<String, StructBottomSheet> textImageList) {
listPathString = null;
listPathString = new ArrayList<>();
if (textImageList.size() == 0) {
return;
}
ArrayList<StructBottomSheet> itemList = new ArrayList<StructBottomSheet>();
for (Map.Entry<String, StructBottomSheet> items : textImageList.entrySet()) {
itemList.add(items.getValue());
}
Collections.sort(itemList);
for (StructBottomSheet item : itemList) {
edtChat.setText(EmojiManager.getInstance().replaceEmoji(item.getText(), edtChat.getPaint().getFontMetricsInt(), LayoutCreator.dp(22), false));
listPathString.add(item.getPath());
latestRequestCode = AttachFile.requestOpenGalleryForImageMultipleSelect;
ll_attach_text.setVisibility(View.VISIBLE);
imvSendButton.performClick();
}
}
};
imvAttachFileButton.setOnClickListener(view -> {
if (getActivity() == null)
return;
if (mAttachmentPopup == null)
initPopupAttachment();
mAttachmentPopup.setMessagesLayoutHeight(recyclerView.getMeasuredHeight());
hideKeyboard();
mAttachmentPopup.show();
});
sendMoney.setOnClickListener(view -> {
if ((chatType == CHAT) && !isCloudRoom && !isBot) {
showSelectItem();
} else {
showCardToCard();
}
if (keyboardViewVisible) {
hideKeyboard();
}
});
customStatusActionLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (getActivity() != null) {
hideFloatingButton(true);
new HelperFragment(getActivity().getSupportFragmentManager(), new StatusTextFragment(true, mRoomId, 0, title)).setReplace(false).load();
}
}
});
floatActionLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (getActivity() != null) {
hideFloatingButton(true);
new HelperFragment(getActivity().getSupportFragmentManager(), new StoryPagerFragment(true, mRoomId, 0, title)).setReplace(false).load();
}
}
});
imvAddStoryButton.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (keyboardViewVisible) {
hideKeyboard();
}
if (!MessageController.isSendingRoomStory && !MessageController.isSendingStory) {
hideFloatingButton(false);
}
return true;
}
});
imvAddStoryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
hideFloatingButton(true);
micAndAddStoryAnimateVisible(false);
}
});
imvMicButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (chatType == CHANNEL) {
if (channelRole == ChannelChatRole.OWNER && !isRecording) {
micAndAddStoryAnimateVisible(true);
}
}
}
});
Runnable recordVoiceRunnable = new Runnable() {
@Override
public void run() {
isLongPress = true;
if (isLongPress) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(100);
if (mustCheckPermission()) {
if (currentRoomAccess != null && !currentRoomAccess.getRealmPostMessageRights().isCanSendMedia()) {
Toast.makeText(getContext(), getResources().getString(R.string.restrictions_on_sending_multimedia_messages), Toast.LENGTH_SHORT).show();
isLongPress = false;
}
}
if (keyboardViewVisible)
hideKeyboard();
if (ContextCompat.checkSelfPermission(G.fragmentActivity, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
try {
HelperPermission.getMicroPhonePermission(G.fragmentActivity, null);
} catch (IOException e) {
e.printStackTrace();
}
} else {
isRecording = true;
voiceRecord.setItemTag("ivVoice");
viewMicRecorder.setVisibility(View.VISIBLE);
AppUtils.setVibrator(50);
voiceRecord.startVoiceRecord();
}
}
}
};
imvMicButton.setOnTouchListener((v, event) -> {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
G.runOnUiThread(recordVoiceRunnable, longClickDuration);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
G.cancelRunOnUiThread(recordVoiceRunnable);
isLongPress = false;
}
return isLongPress;
});
imvSmileButton.setOnClickListener(v -> onEmojiButtonClick());
edtChat.addTextChangedListener(new TextWatcher() {
boolean processChange = false;
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence text, int start, int before, int count) {
if (text.length() > 0) {
HelperSetAction.setActionTyping(mRoomId, chatType);
}
// if in the seeting page send by enter is on message send by enter key
if (text.toString().endsWith(System.getProperty("line.separator"))) {
if (sendByEnter)
imvSendButton.performClick();
}
messageLentghCounter = ((int) Math.ceil((float) text.length() / (float) Config.MAX_TEXT_LENGTH));
if (messageLentghCounter > 1 && messageLentghCounter != oldMessageLentghCounter && getContext() != null) {
oldMessageLentghCounter = messageLentghCounter;
Toast.makeText(getContext(), getString(R.string.message_is_long) + " " + messageLentghCounter + " " + getString(R.string.message), Toast.LENGTH_SHORT).show();
}
if ((count - before) > 1) {
processChange = true;
}
}
@Override
public void afterTextChanged(Editable editable) {
if (ll_attach_text.getVisibility() == View.GONE && !hasForward) {
if (edtChat.getText() != null && edtChat.getText().length() > 0) {
sendButtonVisibility(true);
} else {
if (!isEditMessage) {
sendButtonVisibility(false);
}
}
if (processChange) {
ImageSpan[] spans = editable.getSpans(0, editable.length(), ImageSpan.class);
for (ImageSpan span : spans) {
editable.removeSpan(span);
}
EmojiManager.getInstance().replaceEmoji(editable, edtChat.getPaint().getFontMetricsInt(), LayoutCreator.dp(20), false);
processChange = false;
}
}
if (edtChat.getText() != null && !EmojiManager.getInstance().isValidEmoji(edtChat.getText()) && suggestedLayout != null && suggestedLayout.getVisibility() == View.VISIBLE) {
suggestedLayout.setVisibility(View.GONE);
lastChar = null;
} else if (lastChar != null) {
lastChar = null;
}
}
});
}
use of net.iGap.structs.MessageObject in project iGap-Android by KianIranian-STDG.
the class FragmentChat method onCreateView.
@Nullable
@Override
public View onCreateView(@NotNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
isNeedResume = true;
G.locationListener = this;
StickerRepository.getInstance().getUserStickersGroup();
notifyFrameLayout = new NotifyFrameLayout(context) {
@Override
public boolean dispatchKeyEventPreIme(KeyEvent event) {
if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
if (topFragmentIsChat() && keyboardViewVisible) {
showPopup(-1);
return true;
}
return false;
}
return super.dispatchKeyEventPreIme(event);
}
};
Bundle extras = getArguments();
if (extras != null) {
mRoomId = extras.getLong("RoomId");
if (mustCheckPermission())
currentRoomAccess = DbManager.getInstance().doRealmTask(realm -> {
return realm.where(RealmRoomAccess.class).equalTo("id", mRoomId + "_" + AccountManager.getInstance().getCurrentUser().getId()).findFirst();
});
}
notifyFrameLayout.setListener(this::onScreenSizeChanged);
rootView = (FrameLayout) inflater.inflate(R.layout.fragment_chat, container, false);
chatContainer = rootView.findViewById(R.id.chatMainContainer);
mediaContainer = new FragmentMediaContainer(getActivity(), this);
mediaContainer.setListener(i -> {
switch(i) {
case FragmentMediaContainer.CALL_TAG:
getActivity().startActivity(new Intent(getContext(), CallActivity.class));
break;
case FragmentMediaContainer.MEDIA_TAG:
if (!MusicPlayer.isVoice) {
Intent intent = new Intent(context, ActivityMain.class);
intent.putExtra(ActivityMain.openMediaPlayer, true);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().startActivity(intent);
}
break;
case FragmentMediaContainer.PLAY_TAG:
break;
}
});
// mediaContainer.setVisibility(View.GONE);
chatContainer.addView(mediaContainer, LayoutCreator.createLinear(LayoutCreator.MATCH_PARENT, 39, Gravity.TOP | Gravity.LEFT, 0, 59, 0, 0));
mToolbar = new Toolbar(context);
searchFieldItem = mToolbar.addItem(searchFieldTag, R.string.icon_search, Theme.getInstance().getTitleTextColor(getContext())).setIsSearchBox(true).setActionBarMenuItemSearchListener(new ToolbarItem.ActionBarMenuItemSearchListener() {
int textLength;
@Override
public void onSearchExpand() {
if (layoutMute != null) {
layoutMute.setVisibility(View.GONE);
}
if (viewAttachFile != null) {
viewAttachFile.setVisibility(View.GONE);
}
if (rootView.findViewById(R.id.ac_ll_join).getVisibility() == View.VISIBLE) {
rootView.findViewById(R.id.ac_ll_join).setVisibility(View.GONE);
}
if (pinedMessageLayout != null) {
changePinnedMessageVisibility(true, false, MusicPlayer.isMusicPlyerEnable, CallManager.getInstance().isCallAlive());
}
if (vgSpamUser != null) {
vgSpamUser.setVisibility(View.GONE);
}
isSearchVisible = true;
}
@Override
public void onTextChanged(EditText editText) {
String text = editText.getText().toString();
if (text.length() > 0 && !text.startsWith("#")) {
if (!initHash) {
initHash = true;
initHashView();
}
searchHash.setHashString(editText.getText().toString());
searchHash.setPosition("");
if (searchFragment != null) {
searchFragment.onSearchCollapsed();
}
if (ll_navigateHash != null) {
ll_navigateHash.setVisibility(View.VISIBLE);
}
if (viewAttachFile != null) {
viewAttachFile.setVisibility(View.GONE);
}
} else if (text.startsWith("#") && text.length() < 2) {
if (text.length() > textLength) {
searchFragment = SearchFragment.newInstance(mRoomId, text, true);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.chatContainer, searchFragment).commit();
}
if (keyboardContainer != null) {
keyboardContainer.setVisibility(View.GONE);
}
if (ll_navigateHash != null) {
ll_navigateHash.setVisibility(View.GONE);
}
if (txtFloatingTime != null) {
txtFloatingTime.setVisibility(View.GONE);
}
} else if (text.startsWith("#") && text.length() > 1) {
if (searchFragment != null && searchFragment.isAdded()) {
searchFragment.onTextChanged(editText.getText().toString());
}
} else {
hideKeyboardView();
if (ll_navigateHash != null) {
ll_navigateHash.setVisibility(View.GONE);
}
if (searchFragment != null && searchFragment.isAdded()) {
searchFragment.onSearchCollapsed();
}
}
textLength = editText.getText().length();
}
@Override
public void onSearchCollapse() {
if (muteIcon != null) {
muteIcon.setVisibility(getRoom().getMute() ? View.VISIBLE : View.GONE);
}
if (verifiedIcon != null) {
RealmChannelRoom channelRoom = getRoom().getChannelRoom();
boolean isVerified = false;
if (channelRoom != null) {
isVerified = channelRoom.isVerified();
}
verifiedIcon.setVisibility(isVerified ? View.VISIBLE : View.GONE);
}
if (avatarItem != null) {
avatarItem.setVisibility(View.VISIBLE);
}
if (pinedMessageLayout != null) {
if (isPinAvailable) {
changePinnedMessageVisibility(true, true, MusicPlayer.isMusicPlyerEnable, CallManager.getInstance().isCallAlive());
}
}
if (isNotJoin) {
rootView.findViewById(R.id.ac_ll_join).setVisibility(View.VISIBLE);
}
if (searchFragment != null) {
searchFragment.onSearchCollapsed();
}
if (vgSpamUser != null) {
showSpamBar();
}
goneSearchHashFooter();
hideKeyboardView();
searchFieldItem.setVisibility(View.GONE);
isSearchVisible = false;
}
});
searchFieldItem.setVisibility(View.GONE);
mToolbar.setOnClickListener(view -> {
hideKeyboard();
goToProfile();
});
mToolbar.setListener(i -> {
switch(i) {
case -1:
if (mToolbar.isActionModeShowed()) {
mAdapter.deselect();
return;
}
if (webViewChatPage != null) {
closeWebViewForSpecialUrlChat(false);
return;
}
hideKeyboard();
if (chatType == CHANNEL && !floatingHidden) {
if (channelRole == ChannelChatRole.OWNER && !isRecording) {
hideFloatingButton(true);
micAndAddStoryAnimateVisible(false);
}
return;
}
if (currentRoomAccess != null) {
if (currentRoomAccess != null) {
if (!currentRoomAccess.getRealmPostMessageRights().isCanSendText()) {
G.runOnUiThread(() -> {
viewAttachFile.setVisibility(View.GONE);
});
}
}
}
if (G.twoPaneMode) {
if (getActivity() instanceof ActivityMain) {
((ActivityMain) getActivity()).goToTabletEmptyPage();
}
} else {
if (!mToolbar.isSearchFieldVisible()) {
popBackStackFragment();
}
}
break;
case searchItem:
initLayoutSearchNavigation();
if (!initHash) {
initHash = true;
initHashView();
}
openSearchBox(null);
showPopup(KeyboardView.MODE_KEYBOARD);
G.handler.postDelayed(() -> editTextRequestFocus(searchEditText), 300);
break;
case voiceCallTag:
if (CallManager.getInstance().getCallPeerId() == chatPeerId) {
Intent activityIntent = new Intent(getActivity(), CallActivity.class);
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activityIntent);
} else if (!CallManager.getInstance().isCallAlive()) {
CallSelectFragment selectFragment = CallSelectFragment.getInstance(chatPeerId, false, null);
if (getFragmentManager() != null)
selectFragment.show(getFragmentManager(), null);
if (keyboardViewVisible) {
hideKeyboard();
}
} else {
Toast.makeText(getContext(), "NOT ALLOWED", Toast.LENGTH_SHORT).show();
}
break;
case moreTag:
createMoreItems();
break;
case clearHistoryItem:
new MaterialDialog.Builder(G.fragmentActivity).title(R.string.clear_history).content(R.string.clear_history_content).positiveText(R.string.yes).onPositive((dialog, which) -> clearHistory(mRoomId)).negativeText(R.string.no).show();
break;
case deleteItem:
new MaterialDialog.Builder(G.fragmentActivity).title(R.string.delete_chat).content(R.string.delete_chat_content).positiveText(R.string.yes).onPositive((dialog, which) -> deleteChat(mRoomId)).negativeText(R.string.no).show();
break;
case muteItem:
case unMuteItem:
muteNotification(mRoomId);
break;
case chatToGroupItem:
new MaterialDialog.Builder(G.fragmentActivity).title(R.string.convert_chat_to_group_title).content(R.string.convert_chat_to_group_content).positiveText(R.string.yes).negativeText(R.string.no).onPositive((dialog, which) -> {
// finish();
finishChat();
dialog.dismiss();
G.handler.post(() -> G.onConvertToGroup.openFragmentOnActivity("ConvertToGroup", mRoomId));
}).show();
break;
case cleanUpItem:
resetMessagingValue();
setDownBtnGone();
setCountNewMessageZero();
DbManager.getInstance().doRealmTask(realm -> {
RealmRoomMessage.ClearAllMessageRoomAsync(realm, mRoomId, () -> {
recyclerView.addOnScrollListener(scrollListener);
saveMessageIdPositionState(0, 0);
/**
* get history from server
*/
topMore = true;
getOnlineMessage(0, 0, UP);
});
});
break;
case reportItem:
dialogReport(false, 0, 0);
break;
case sendMoneyItem:
showPaymentDialog();
break;
case exportChatItem:
if (HelperPermission.grantedUseStorage()) {
exportChat();
} else {
try {
HelperPermission.getStoragePermission(G.fragmentActivity, new OnGetPermission() {
@Override
public void Allow() {
exportChat();
}
@Override
public void deny() {
Toast.makeText(G.currentActivity, R.string.export_message, Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
break;
case stopItem:
new MaterialDialog.Builder(G.fragmentActivity).title(R.string.stop).content(R.string.stop_message_bot).positiveText(R.string.yes).onPositive((dialog, which) -> {
// onSelectRoomMenu("txtClearHistory", mRoomId);
closeWebViewForSpecialUrlChat(true);
// popBackStackFragment();
}).negativeText(R.string.no).show();
break;
case copyMessageTag:
copySelectedItemTextToClipboard();
break;
case forwardMessageTag:
// forward selected messages to room list for selecting room
if (mAdapter != null && mAdapter.getSelectedItems().size() > 0) {
onForwardClick(null);
}
break;
case replyMessageTag:
if (mAdapter != null && !mAdapter.getSelectedItems().isEmpty() && mAdapter.getSelectedItems().size() == 1) {
reply(mAdapter.getSelectedItems().iterator().next().messageObject, false);
}
break;
case deleteMessageTag:
messageIds = new ArrayList<>();
documentIds = new ArrayList<>();
bothDeleteMessageId = new ArrayList<>();
G.handler.post(() -> {
for (final AbstractMessage item : mAdapter.getSelectedItems()) {
if (mAdapter.getSelectedItems().size() == 1) {
confirmAndDeleteMessage(item.messageObject, true);
return;
}
try {
if (item != null && item.messageObject != null) {
Long messageId = item.messageObject.id;
Long documentId = item.messageObject.documentId;
messageIds.add(messageId);
documentIds.add(documentId);
boolean bothDelete = RealmRoomMessage.isBothDelete(item.messageObject.getUpdateOrCreateTime());
if (bothDelete)
bothDeleteMessageId.add(messageId);
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
if (chatType == CHAT && !isCloudRoom && bothDeleteMessageId.size() > 0 && mAdapter.getSelectedItems().iterator().next().messageObject.userId == AccountManager.getInstance().getCurrentUser().getId()) {
String delete;
String textCheckBox = getContext().getResources().getString(R.string.st_checkbox_delete) + " " + title;
delete = getContext().getResources().getString(R.string.st_desc_deletes);
new MaterialDialog.Builder(getContext()).content(delete).title(R.string.message).positiveText(R.string.ok).negativeText(R.string.cancel).onPositive((dialog, which) -> {
if (!dialog.isPromptCheckBoxChecked()) {
bothDeleteMessageId = null;
}
getMessageController().deleteSelectedMessage(chatType.getNumber(), mRoomId, messageIds, documentIds, bothDeleteMessageId);
// deleteSelectedMessageFromAdapter(messageIds);
}).checkBoxPrompt(textCheckBox, false, null).show();
} else {
new MaterialDialog.Builder(getActivity()).title(R.string.message).content(getActivity().getResources().getString(R.string.st_desc_deletes)).positiveText(R.string.ok).negativeText(R.string.cancel).onPositive((dialog, which) -> {
bothDeleteMessageId = null;
getMessageController().deleteSelectedMessage(chatType.getNumber(), mRoomId, messageIds, documentIds, bothDeleteMessageId);
// deleteSelectedMessageFromAdapter(messageIds);
}).show();
}
});
break;
}
});
searchEditText = searchFieldItem.getSearchEditText();
mToolbar.setBackIcon(new BackDrawable(false));
verifiedIcon = mToolbar.addVerifiedChannelsIcon();
muteIcon = mToolbar.addMuteIcon();
ToolbarItems toolbarItems = mToolbar.createToolbarItems();
toolbarItems.setBackground(null);
moreItem = toolbarItems.addItemWithWidth(moreTag, R.string.icon_other_vertical_dots, 48);
callItem = toolbarItems.addItemWithWidth(voiceCallTag, R.string.icon_voice_call, 48);
createActionMode();
rootView.addView(mToolbar, LayoutCreator.createFrame(LayoutCreator.MATCH_PARENT, 60, Gravity.TOP));
notifyFrameLayout.addView(rootView, LayoutCreator.createFrame(LayoutCreator.MATCH_PARENT, LayoutCreator.MATCH_PARENT));
keyboardContainer = rootView.findViewById(R.id.fl_chat_keyboardContainer);
sendMoney = rootView.findViewById(R.id.btn_chatRoom_wallet);
/**
* init chat box edit text and send item because we need change this color in dark mode!
*/
edtChat = rootView.findViewById(R.id.et_chatRoom_writeMessage);
edtChat.setGravity(Gravity.CENTER_VERTICAL);
edtChat.setListener(this::chatMotionEvent);
imvSendButton = rootView.findViewById(R.id.btn_chatRoom_send);
editTextProgress = rootView.findViewById(R.id.editTextProgress);
chatRoom_send_container = rootView.findViewById(R.id.chatRoom_send_container);
getEventManager().addObserver(EventManager.CALL_STATE_CHANGED, this);
getEventManager().addObserver(EventManager.EMOJI_LOADED, this);
getEventManager().addObserver(EventManager.ON_MESSAGE_DELETE, this);
getEventManager().addObserver(EventManager.ON_EDIT_MESSAGE, this);
getEventManager().addObserver(EventManager.ON_PINNED_MESSAGE, this);
getEventManager().addObserver(EventManager.CHAT_CLEAR_MESSAGE, this);
getEventManager().addObserver(EventManager.CHANNEL_ADD_VOTE, this);
getEventManager().addObserver(EventManager.CHANNEL_GET_VOTE, this);
getEventManager().addObserver(EventManager.CHANNEL_UPDATE_VOTE, this);
getEventManager().addObserver(EventManager.CHANNEL_UPDATE_VOTE, this);
getEventManager().addObserver(EventManager.CHAT_UPDATE_STATUS, this);
getEventManager().addObserver(EventManager.MEDIA_PLAYER_STATE_CHANGED, this);
getEventManager().addObserver(EventManager.NEXT_VOICE, this);
getEventManager().addObserver(EventManager.ON_FILE_PICKED_FROM_INTENT, this);
if (twoPaneMode)
EventManager.getInstance(AccountManager.selectedAccount).addObserver(EventManager.CHAT_BACKGROUND_CHANGED, this);
return attachToSwipeBack(notifyFrameLayout);
}
use of net.iGap.structs.MessageObject in project iGap-Android by KianIranian-STDG.
the class FragmentChat method switchAddItem.
private void switchAddItem(ArrayList<StructMessageInfo> infos, boolean addTop) {
if (prgWaiting != null && infos.size() > 0) {
prgWaiting.setVisibility(View.GONE);
}
long identifier = SUID.id().get();
for (StructMessageInfo info : infos) {
MessageObject messageObject = MessageObject.create(info.realmRoomMessage);
int messageType;
if (messageObject.isForwarded()) {
messageType = messageObject.forwardedMessage.messageType;
} else {
messageType = messageObject.messageType;
}
if (!messageObject.isTimeOrLogMessage() || (messageType == LOG_VALUE)) {
int index = 0;
if (addTop) {
if (messageObject.needToShow) {
for (int i = 0; i < mAdapter.getAdapterItemCount(); i++) {
if (mAdapter.getAdapterItem(i) instanceof TimeItem) {
// TODO: 12/28/20 MESSAGE_REFACTOR
if (!RealmRoomMessage.isTimeDayDifferent(messageObject.getUpdateOrCreateTime(), mAdapter.getAdapterItem(i).messageObject.getUpdateOrCreateTime())) {
mAdapter.remove(i);
}
break;
}
}
mAdapter.add(0, new TimeItem(mAdapter, this).setMessage(makeLayoutTime(messageObject.getUpdateOrCreateTime())).withIdentifier(identifier++));
index = 1;
}
} else {
/**
* don't allow for add lower messageId to bottom of list
*/
if (messageObject.id > biggestMessageId) {
if (messageObject.status != MessageObject.STATUS_SENDING) {
biggestMessageId = messageObject.id;
}
} else {
continue;
}
if (lastMessageId == messageObject.id) {
continue;
} else {
lastMessageId = messageObject.id;
}
if (messageObject.needToShow) {
if (mAdapter.getItemCount() > 0) {
if (mAdapter.getAdapterItem(mAdapter.getItemCount() - 1).messageObject != null && RealmRoomMessage.isTimeDayDifferent(messageObject.getUpdateOrCreateTime(), mAdapter.getAdapterItem(mAdapter.getItemCount() - 1).messageObject.getUpdateOrCreateTime())) {
mAdapter.add(new TimeItem(mAdapter, this).setMessage(makeLayoutTime(messageObject.getUpdateOrCreateTime())).withIdentifier(identifier++));
}
} else {
mAdapter.add(new TimeItem(mAdapter, this).setMessage(makeLayoutTime(messageObject.getUpdateOrCreateTime())).withIdentifier(identifier++));
}
}
}
switch(messageType) {
case TEXT_VALUE:
case STORY_REPLY_VALUE:
if (messageObject.getAdditional() != null && messageObject.getAdditional().type == AdditionalType.CARD_TO_CARD_MESSAGE)
if (!addTop) {
mAdapter.add(new CardToCardItem(mAdapter, chatType, FragmentChat.this).setMessage(messageObject).withIdentifier(identifier));
} else {
mAdapter.add(index, new CardToCardItem(mAdapter, chatType, FragmentChat.this).setMessage(messageObject).withIdentifier(identifier));
}
else {
if (!addTop) {
mAdapter.add(new TextItem(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
} else {
mAdapter.add(index, new TextItem(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
}
}
break;
case WALLET_VALUE:
if (messageObject.wallet.cardToCard != null) {
if (!addTop) {
mAdapter.add(new LogWalletCardToCard(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
} else {
mAdapter.add(index, new LogWalletCardToCard(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
}
} else if (messageObject.wallet.topupObject != null) {
if (!addTop) {
mAdapter.add(new LogWalletTopup(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
} else {
mAdapter.add(index, new LogWalletTopup(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
}
;
} else if (messageObject.wallet.billObject != null) {
if (!addTop) {
mAdapter.add(new LogWalletBill(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
} else {
mAdapter.add(index, new LogWalletBill(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
}
} else {
if (!addTop) {
mAdapter.add(new LogWallet(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
} else {
mAdapter.add(index, new LogWallet(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
}
}
break;
case IMAGE_VALUE:
case IMAGE_TEXT_VALUE:
if (!addTop) {
mAdapter.add(new ImageWithTextItem(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
} else {
mAdapter.add(index, new ImageWithTextItem(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
}
break;
case VIDEO_VALUE:
case VIDEO_TEXT_VALUE:
if (!addTop) {
mAdapter.add(new VideoWithTextItem(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
} else {
mAdapter.add(index, new VideoWithTextItem(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
}
break;
case LOCATION_VALUE:
if (!addTop) {
mAdapter.add(new LocationItem(mAdapter, chatType, this, getActivity()).setMessage(messageObject).withIdentifier(identifier));
} else {
mAdapter.add(index, new LocationItem(mAdapter, chatType, this, getActivity()).setMessage(messageObject).withIdentifier(identifier));
}
break;
case FILE_VALUE:
case FILE_TEXT_VALUE:
if (!addTop) {
mAdapter.add(new FileItem(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
} else {
mAdapter.add(index, new FileItem(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
}
break;
case STICKER_VALUE:
if (messageObject.getAdditional() != null && messageObject.getAdditional().type == AdditionalType.GIFT_STICKER) {
} else if (messageObject.getAttachment() != null && messageObject.getAttachment().name != null && messageObject.getAttachment().isAnimatedSticker()) {
if (!addTop) {
mAdapter.add(new AnimatedStickerItem(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
} else {
mAdapter.add(index, new AnimatedStickerItem(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
}
} else {
if (messageObject.getAttachment() != null) {
if (!addTop) {
mAdapter.add(new StickerItem(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
} else {
mAdapter.add(index, new StickerItem(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
}
}
}
break;
case VOICE_VALUE:
if (!addTop) {
mAdapter.add(new VoiceItem(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
} else {
mAdapter.add(index, new VoiceItem(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
}
break;
case AUDIO_VALUE:
case AUDIO_TEXT_VALUE:
if (!addTop) {
mAdapter.add(new AudioItem(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
} else {
mAdapter.add(index, new AudioItem(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
}
break;
case CONTACT_VALUE:
if (!addTop) {
mAdapter.add(new ContactItem(getActivity(), mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
} else {
mAdapter.add(index, new ContactItem(getActivity(), mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
}
break;
case GIF_VALUE:
case GIF_TEXT_VALUE:
if (!addTop) {
mAdapter.add(new GifWithTextItem(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
} else {
mAdapter.add(index, new GifWithTextItem(mAdapter, chatType, this).setMessage(messageObject).withIdentifier(identifier));
}
break;
case LOG_VALUE:
if (messageObject.needToShow) {
if (!addTop) {
mAdapter.add(new LogItem(mAdapter, this).setMessage(messageObject).withIdentifier(identifier));
} else {
mAdapter.add(index, new LogItem(mAdapter, this).setMessage(messageObject).withIdentifier(identifier));
}
}
break;
}
}
identifier++;
}
}
use of net.iGap.structs.MessageObject in project iGap-Android by KianIranian-STDG.
the class FragmentChat method sendPosition.
public void sendPosition(final Double latitude, final Double longitude, final String imagePath) {
sendCancelAction();
if (isShowLayoutUnreadMessage) {
removeLayoutUnreadMessage();
}
final long messageId = AppUtils.makeRandomId();
RealmRoomMessage roomMessage = new RealmRoomMessage();
roomMessage.setMessageId(messageId);
RealmRoomMessageLocation realmRoomMessageLocation = new RealmRoomMessageLocation();
realmRoomMessageLocation.setId(AppUtils.makeRandomId());
realmRoomMessageLocation.setLocationLat(latitude);
realmRoomMessageLocation.setLocationLong(longitude);
realmRoomMessageLocation.setImagePath(imagePath);
roomMessage.setLocation(realmRoomMessageLocation);
roomMessage.setCreateTime(TimeUtils.currentLocalTime());
roomMessage.setMessageType(ProtoGlobal.RoomMessageType.LOCATION);
roomMessage.setRoomId(mRoomId);
roomMessage.setUserId(AccountManager.getInstance().getCurrentUser().getId());
roomMessage.setAuthorHash(RealmUserInfo.getCurrentUserAuthorHash());
roomMessage.setStatus(ProtoGlobal.RoomMessageStatus.SENDING.toString());
if (replyMessageId() > 0) {
RealmRoomMessage realmRoomMessageCopy = DbManager.getInstance().doRealmTask(realm -> {
RealmRoomMessage realmRoomMessage = realm.where(RealmRoomMessage.class).equalTo("messageId", replyMessageId()).findFirst();
if (realmRoomMessage != null) {
return realm.copyFromRealm(realmRoomMessage);
} else {
return null;
}
});
if (realmRoomMessageCopy != null) {
roomMessage.setReplyTo(realmRoomMessageCopy);
}
}
new Thread(new Runnable() {
@Override
public void run() {
DbManager.getInstance().doRealmTransaction(realm -> {
RealmRoomMessage managedMessage = realm.copyToRealmOrUpdate(roomMessage);
RealmRoom.setLastMessageWithRoomMessage(realm, mRoomId, managedMessage);
});
}
}).start();
G.handler.postDelayed(new Runnable() {
@Override
public void run() {
switchAddItem(new ArrayList<>(Collections.singletonList(new StructMessageInfo(roomMessage))), false);
MessageObject locationMessage = MessageObject.create(roomMessage);
getSendMessageUtil().build(chatType, mRoomId, locationMessage);
scrollToEnd();
}
}, 300);
clearReplyView();
}
Aggregations