Search in sources :

Example 1 with Conversation

use of com.applozic.mobicommons.people.channel.Conversation in project Applozic-Android-SDK by AppLozic.

the class MainActivity method takeOrder.

// public void takeOrder(View v) {
// Intent takeOrderIntent = new Intent(this, ConversationActivity.class);
// takeOrderIntent.putExtra(TAKE_ORDER, true);
// takeOrderIntent.putExtra(ConversationUIService.USER_ID, Utils.getMetaDataValue(this, TAKE_ORDER_USERID_METADATA));
// takeOrderIntent.putExtra(ConversationUIService.DEFAULT_TEXT, "Hello I am interested in your property, Can we chat?");
// takeOrderIntent.putExtra(ConversationUIService.PRODUCT_TOPIC_ID, "Ebco Strip Light Connection Cord 4");
// takeOrderIntent.putExtra(ConversationUIService.PRODUCT_IMAGE_URL, "https://www.applozic.com/resources/sidebox/images/applozic.png");
// // takeOrderIntent.putExtra(ConversationUIService.APPLICATION_ID,"applozic-sample-app");
// startActivity(takeOrderIntent);
// }
public void takeOrder(View v) {
    Conversation conversation = buildConversation();
    ApplozicConversationCreateTask applozicConversationCreateTask;
    ApplozicConversationCreateTask.ConversationCreateListener conversationCreateListener = new ApplozicConversationCreateTask.ConversationCreateListener() {

        @Override
        public void onSuccess(Integer conversationId, Context context) {
            Log.i(TAG, "ConversationID is:" + conversationId);
            Intent takeOrderIntent = new Intent(context, ConversationActivity.class);
            takeOrderIntent.putExtra(TAKE_ORDER, true);
            takeOrderIntent.putExtra(ConversationUIService.CONTEXT_BASED_CHAT, true);
            takeOrderIntent.putExtra(ConversationUIService.USER_ID, "usertest2");
            takeOrderIntent.putExtra(ConversationUIService.DEFAULT_TEXT, R.string.intrest_in_chat);
            takeOrderIntent.putExtra(ConversationUIService.CONVERSATION_ID, conversationId);
            startActivity(takeOrderIntent);
        }

        @Override
        public void onFailure(Exception e, Context context) {
        }
    };
    applozicConversationCreateTask = new ApplozicConversationCreateTask(MainActivity.this, conversationCreateListener, conversation);
    applozicConversationCreateTask.execute((Void) null);
}
Also used : Context(android.content.Context) ApplozicConversationCreateTask(com.applozic.mobicomkit.uiwidgets.async.ApplozicConversationCreateTask) Conversation(com.applozic.mobicommons.people.channel.Conversation) Intent(android.content.Intent)

Example 2 with Conversation

use of com.applozic.mobicommons.people.channel.Conversation in project Applozic-Android-SDK by AppLozic.

the class ConversationDatabaseService method getConversationList.

public List<Conversation> getConversationList(final Channel channel, final Contact contact) {
    List<Conversation> conversation = null;
    SQLiteDatabase database = dbHelper.getReadableDatabase();
    String conversationParameters = "";
    List<String> structuredNameParamsList = new ArrayList<>();
    if (channel != null) {
        conversationParameters += "channelKey = ? ";
        structuredNameParamsList.add(String.valueOf(channel.getKey()));
    } else {
        conversationParameters += "userId = ? ";
        structuredNameParamsList.add(contact.getContactIds());
    }
    Cursor cursor = database.query(MobiComDatabaseHelper.CONVERSATION, null, conversationParameters, structuredNameParamsList.toArray(new String[structuredNameParamsList.size()]), null, null, "key desc");
    if (cursor.moveToFirst()) {
        conversation = getConversationList(cursor);
    }
    if (cursor != null) {
        cursor.close();
    }
    return conversation;
}
Also used : SQLiteDatabase(android.database.sqlite.SQLiteDatabase) ArrayList(java.util.ArrayList) Conversation(com.applozic.mobicommons.people.channel.Conversation) Cursor(android.database.Cursor)

Example 3 with Conversation

use of com.applozic.mobicommons.people.channel.Conversation in project Applozic-Android-SDK by AppLozic.

the class MobiComConversationFragment method onCreateView.

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View list = inflater.inflate(R.layout.mobicom_message_list, container, false);
    recyclerView = (RecyclerView) list.findViewById(R.id.messageList);
    linearLayoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setHasFixedSize(true);
    recyclerViewPositionHelper = new RecyclerViewPositionHelper(recyclerView, linearLayoutManager);
    ((ConversationActivity) getActivity()).setChildFragmentLayoutBGToTransparent();
    // listView.setDivider(null);
    messageList = new ArrayList<Message>();
    multimediaPopupGrid = (GridView) list.findViewById(R.id.mobicom_multimedia_options1);
    getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    toolbar = (Toolbar) getActivity().findViewById(R.id.my_toolbar);
    toolbar.setClickable(true);
    mainEditTextLinearLayout = (LinearLayout) list.findViewById(R.id.main_edit_text_linear_layout);
    individualMessageSendLayout = (LinearLayout) list.findViewById(R.id.individual_message_send_layout);
    slideImageView = (ImageView) list.findViewById(R.id.slide_image_view);
    sendButton = (ImageButton) individualMessageSendLayout.findViewById(R.id.conversation_send);
    recordButton = (ImageButton) individualMessageSendLayout.findViewById(R.id.record_button);
    mainEditTextLinearLayout = (LinearLayout) list.findViewById(R.id.main_edit_text_linear_layout);
    audioRecordFrameLayout = (FrameLayout) list.findViewById(R.id.audio_record_frame_layout);
    messageTemplateView = (RecyclerView) list.findViewById(R.id.mobicomMessageTemplateView);
    Configuration config = getResources().getConfiguration();
    recordButtonWeakReference = new WeakReference<ImageButton>(recordButton);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        if (config.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
            sendButton.setScaleX(-1);
            mainEditTextLinearLayout.setBackgroundResource(R.drawable.applozic_chat_left_icon);
            audioRecordFrameLayout.setBackgroundResource(R.drawable.applozic_chat_left_icon);
            slideImageView.setImageResource(R.drawable.slide_arrow_right);
        }
    }
    extendedSendingOptionLayout = (LinearLayout) list.findViewById(R.id.extended_sending_option_layout);
    attachmentLayout = (RelativeLayout) list.findViewById(R.id.attachment_layout);
    isTyping = (TextView) list.findViewById(R.id.isTyping);
    contextFrameLayout = (FrameLayout) list.findViewById(R.id.contextFrameLayout);
    contextSpinner = (Spinner) list.findViewById(R.id.spinner_show);
    slideTextLinearlayout = (LinearLayout) list.findViewById(R.id.slide_LinearLayout);
    errorEditTextView = (EditText) list.findViewById(R.id.error_edit_text_view);
    audioRecordIconImageView = (ImageView) list.findViewById(R.id.audio_record_icon_image_view);
    recordTimeTextView = (TextView) list.findViewById(R.id.recording_time_text_view);
    mDetector = new GestureDetectorCompat(getContext(), this);
    adapterView = new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
            if (conversations != null && conversations.size() > 0) {
                Conversation conversation = conversations.get(pos);
                BroadcastService.currentConversationId = conversation.getId();
                if (onSelected) {
                    currentConversationId = conversation.getId();
                    if (messageList != null) {
                        messageList.clear();
                    }
                    downloadConversation = new DownloadConversation(recyclerView, true, 1, 0, 0, contact, channel, conversation.getId());
                    downloadConversation.execute();
                }
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    };
    mediaUploadProgressBar = (ProgressBar) attachmentLayout.findViewById(R.id.media_upload_progress_bar);
    emoticonsFrameLayout = (FrameLayout) list.findViewById(R.id.emojicons_frame_layout);
    emoticonsBtn = (ImageButton) list.findViewById(R.id.emoticons_btn);
    if (emojiIconHandler == null && emoticonsBtn != null) {
        emoticonsBtn.setVisibility(View.GONE);
    }
    replayRelativeLayout = (RelativeLayout) list.findViewById(R.id.reply_message_layout);
    messageTextView = (TextView) list.findViewById(R.id.messageTextView);
    galleryImageView = (ImageView) list.findViewById(R.id.imageViewForPhoto);
    nameTextView = (TextView) list.findViewById(R.id.replyNameTextView);
    attachReplyCancelLayout = (ImageButton) list.findViewById(R.id.imageCancel);
    imageViewRLayout = (RelativeLayout) list.findViewById(R.id.imageViewRLayout);
    imageViewForAttachmentType = (ImageView) list.findViewById(R.id.imageViewForAttachmentType);
    spinnerLayout = inflater.inflate(R.layout.mobicom_message_list_header_footer, null);
    infoBroadcast = (TextView) spinnerLayout.findViewById(R.id.info_broadcast);
    spinnerLayout.setVisibility(View.GONE);
    emptyTextView = (TextView) list.findViewById(R.id.noConversations);
    emptyTextView.setTextColor(Color.parseColor(alCustomizationSettings.getNoConversationLabelTextColor().trim()));
    emoticonsBtn.setOnClickListener(this);
    // listView.addHeaderView(spinnerLayout);
    sentIcon = getResources().getDrawable(R.drawable.applozic_ic_action_message_sent);
    deliveredIcon = getResources().getDrawable(R.drawable.applozic_ic_action_message_delivered);
    // listView.setLongClickable(true);
    recordButton.setVisibility(alCustomizationSettings.isRecordButton() && (contact != null || channel != null && !Channel.GroupType.OPEN.getValue().equals(channel.getType())) ? View.VISIBLE : View.GONE);
    sendButton.setVisibility(alCustomizationSettings.isRecordButton() && (contact != null || channel != null && !Channel.GroupType.OPEN.getValue().equals(channel.getType())) ? View.GONE : View.VISIBLE);
    GradientDrawable bgShape = (GradientDrawable) sendButton.getBackground();
    bgShape.setColor(Color.parseColor(alCustomizationSettings.getSendButtonBackgroundColor().trim()));
    GradientDrawable bgShapeRecordButton = (GradientDrawable) recordButton.getBackground();
    bgShapeRecordButton.setColor(Color.parseColor(alCustomizationSettings.getSendButtonBackgroundColor().trim()));
    attachButton = (ImageButton) individualMessageSendLayout.findViewById(R.id.attach_button);
    sendType = (Spinner) extendedSendingOptionLayout.findViewById(R.id.sendTypeSpinner);
    messageEditText = (EditText) individualMessageSendLayout.findViewById(R.id.conversation_message);
    messageEditText.setTextColor(Color.parseColor(alCustomizationSettings.getMessageEditTextTextColor()));
    messageEditText.setHintTextColor(Color.parseColor(alCustomizationSettings.getMessageEditTextHintTextColor()));
    userNotAbleToChatLayout = (LinearLayout) list.findViewById(R.id.user_not_able_to_chat_layout);
    userNotAbleToChatTextView = (TextView) userNotAbleToChatLayout.findViewById(R.id.user_not_able_to_chat_textView);
    userNotAbleToChatTextView.setTextColor(Color.parseColor(alCustomizationSettings.getUserNotAbleToChatTextColor()));
    if (channel != null && channel.isDeleted()) {
        userNotAbleToChatTextView.setText(R.string.group_has_been_deleted_text);
    }
    bottomlayoutTextView = (TextView) list.findViewById(R.id.user_not_able_to_chat_textView);
    if (!TextUtils.isEmpty(defaultText)) {
        messageEditText.setText(defaultText);
        defaultText = "";
    }
    scheduleOption = (Button) extendedSendingOptionLayout.findViewById(R.id.scheduleOption);
    mediaContainer = (ImageView) attachmentLayout.findViewById(R.id.media_container);
    attachedFile = (TextView) attachmentLayout.findViewById(R.id.attached_file);
    ImageView closeAttachmentLayout = (ImageView) attachmentLayout.findViewById(R.id.close_attachment_layout);
    swipeLayout = (SwipeRefreshLayout) list.findViewById(R.id.swipe_container);
    swipeLayout.setColorScheme(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);
    // listView.setMessageEditText(messageEditText);
    ArrayAdapter<CharSequence> sendTypeAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.send_type_options, R.layout.mobiframework_custom_spinner);
    sendTypeAdapter.setDropDownViewResource(R.layout.mobiframework_custom_spinner);
    sendType.setAdapter(sendTypeAdapter);
    t = new CountDownTimer(Long.MAX_VALUE, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            count++;
            seconds = count;
            if (seconds == 60) {
                minutes++;
                count = 0;
                seconds = 0;
            }
            if (minutes == 60) {
                minutes = 0;
                count = 0;
            }
            if (count % 2 == 0) {
                audioRecordIconImageView.setVisibility(VISIBLE);
                audioRecordIconImageView.setImageResource(R.drawable.applozic_audio_record);
            } else {
                audioRecordIconImageView.setVisibility(View.INVISIBLE);
            }
            recordTimeTextView.setText(String.format("%02d:%02d", minutes, seconds));
        }

        @Override
        public void onFinish() {
            count = 0;
        }
    };
    recordButton.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            mDetector.onTouchEvent(motionEvent);
            if (motionEvent.getAction() == MotionEvent.ACTION_UP && longPress) {
                isToastVisible = true;
                errorEditTextView.setVisibility(View.GONE);
                errorEditTextView.requestFocus();
                errorEditTextView.setError(null);
                startedDraggingX = -1;
                audioRecordFrameLayout.setVisibility(View.GONE);
                mainEditTextLinearLayout.setVisibility(View.VISIBLE);
                applozicAudioRecordManager.sendAudio();
                t.cancel();
                longPress = false;
                messageEditText.requestFocus();
                seconds = 0;
                minutes = 0;
                count = 0;
            } else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
                float x = motionEvent.getX();
                if (x < -distCanMove) {
                    count = 0;
                    t.cancel();
                    audioRecordIconImageView.setImageResource(R.drawable.applozic_audio_delete);
                    recordTimeTextView.setVisibility(View.GONE);
                    applozicAudioRecordManager.cancelAudio();
                    messageEditText.requestFocus();
                }
                x = x + ApplozicAudioRecordAnimation.getX(recordButton);
                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) slideTextLinearlayout.getLayoutParams();
                if (startedDraggingX != -1) {
                    float dist = (x - startedDraggingX);
                    params.leftMargin = dp(30) + (int) dist;
                    slideTextLinearlayout.setLayoutParams(params);
                    float alpha = 1.0f + dist / distCanMove;
                    if (alpha > 1) {
                        alpha = 1;
                    } else if (alpha < 0) {
                        alpha = 0;
                    }
                    ApplozicAudioRecordAnimation.setAlpha(slideTextLinearlayout, alpha);
                }
                if (x <= ApplozicAudioRecordAnimation.getX(slideTextLinearlayout) + slideTextLinearlayout.getWidth() + dp(30)) {
                    if (startedDraggingX == -1) {
                        startedDraggingX = x;
                        distCanMove = (audioRecordFrameLayout.getMeasuredWidth() - slideTextLinearlayout.getMeasuredWidth() - dp(48)) / 2.0f;
                        if (distCanMove <= 0) {
                            distCanMove = dp(80);
                        } else if (distCanMove > dp(80)) {
                            distCanMove = dp(80);
                        }
                    }
                }
                if (params.leftMargin > dp(30)) {
                    params.leftMargin = dp(30);
                    slideTextLinearlayout.setLayoutParams(params);
                    ApplozicAudioRecordAnimation.setAlpha(slideTextLinearlayout, 1);
                    startedDraggingX = -1;
                }
            }
            view.onTouchEvent(motionEvent);
            return true;
        }
    });
    scheduleOption.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            ConversationScheduler conversationScheduler = new ConversationScheduler();
            conversationScheduler.setScheduleOption(scheduleOption);
            conversationScheduler.setScheduledTimeHolder(scheduledTimeHolder);
            conversationScheduler.setCancelable(false);
            conversationScheduler.show(getActivity().getSupportFragmentManager(), "conversationScheduler");
        }
    });
    messageEditText.addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        // EmojiconHandler.addEmojis(getActivity(), messageEditText.getText(), Utils.dpToPx(30));
        // TODO: write code to emoticons .....
        }

        public void afterTextChanged(Editable s) {
            try {
                if (!TextUtils.isEmpty(s.toString()) && s.toString().trim().length() > 0 && !typingStarted) {
                    // Log.i(TAG, "typing started event...");
                    typingStarted = true;
                    handleSendAndRecordButtonView(true);
                    if (contact != null || channel != null && !Channel.GroupType.OPEN.getValue().equals(channel.getType()) || contact != null) {
                        Intent intent = new Intent(getActivity(), ApplozicMqttIntentService.class);
                        intent.putExtra(ApplozicMqttIntentService.CHANNEL, channel);
                        intent.putExtra(ApplozicMqttIntentService.CONTACT, contact);
                        intent.putExtra(ApplozicMqttIntentService.TYPING, typingStarted);
                        ApplozicMqttIntentService.enqueueWork(getActivity(), intent);
                    }
                } else if (s.toString().trim().length() == 0 && typingStarted) {
                    // Log.i(TAG, "typing stopped event...");
                    typingStarted = false;
                    handleSendAndRecordButtonView(false);
                    if (contact != null || channel != null && !Channel.GroupType.OPEN.getValue().equals(channel.getType()) || contact != null) {
                        Intent intent = new Intent(getActivity(), ApplozicMqttIntentService.class);
                        intent.putExtra(ApplozicMqttIntentService.CHANNEL, channel);
                        intent.putExtra(ApplozicMqttIntentService.CONTACT, contact);
                        intent.putExtra(ApplozicMqttIntentService.TYPING, typingStarted);
                        ApplozicMqttIntentService.enqueueWork(getActivity(), intent);
                    }
                }
            } catch (Exception e) {
            }
        // sendButton.setVisibility((s == null || s.toString().trim().length() == 0) && TextUtils.isEmpty(filePath) ? View.GONE : View.VISIBLE);
        // attachButton.setVisibility(s == null || s.toString().trim().length() == 0 ? View.VISIBLE : View.GONE);
        }
    });
    messageEditText.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            emoticonsFrameLayout.setVisibility(View.GONE);
        }
    });
    if (channel != null && Channel.GroupType.OPEN.getValue().equals(channel.getType())) {
        attachButton.setVisibility(View.GONE);
        messageEditText.setPadding(20, 0, 0, 0);
    }
    attachReplyCancelLayout.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            messageMetaData = null;
            replayRelativeLayout.setVisibility(View.GONE);
        }
    });
    messageEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                if (typingStarted) {
                    if (contact != null || channel != null && !Channel.GroupType.OPEN.getValue().equals(channel.getType()) || contact != null) {
                        Intent intent = new Intent(getActivity(), ApplozicMqttIntentService.class);
                        intent.putExtra(ApplozicMqttIntentService.CHANNEL, channel);
                        intent.putExtra(ApplozicMqttIntentService.CONTACT, contact);
                        intent.putExtra(ApplozicMqttIntentService.TYPING, typingStarted);
                        ApplozicMqttIntentService.enqueueWork(getActivity(), intent);
                    }
                }
                emoticonsFrameLayout.setVisibility(View.GONE);
                multimediaPopupGrid.setVisibility(View.GONE);
            }
        }
    });
    messageEditText.setOnKeyListener(new View.OnKeyListener() {

        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                Utils.toggleSoftKeyBoard(getActivity(), true);
                return true;
            }
            return false;
        }
    });
    recordButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            if (!isToastVisible && !typingStarted) {
                vibrate();
                errorEditTextView.requestFocus();
                errorEditTextView.setError(getResources().getString(R.string.hold_to_record_release_to_send));
                isToastVisible = true;
                new CountDownTimer(3000, 1000) {

                    @Override
                    public void onTick(long millisUntilFinished) {
                    }

                    @Override
                    public void onFinish() {
                        errorEditTextView.setError(null);
                        messageEditText.requestFocus();
                        isToastVisible = false;
                    }
                }.start();
            } else {
                errorEditTextView.setError(null);
                isToastVisible = false;
            }
            emoticonsFrameLayout.setVisibility(View.GONE);
            sendMessage();
            handleSendAndRecordButtonView(false);
            errorEditTextView.setVisibility(View.VISIBLE);
        }
    });
    sendButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            emoticonsFrameLayout.setVisibility(View.GONE);
            sendMessage();
            if (contact != null && !contact.isBlocked() || channel != null) {
                handleSendAndRecordButtonView(false);
            }
        }
    });
    closeAttachmentLayout.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            filePath = null;
            if (previewThumbnail != null) {
                previewThumbnail.recycle();
            }
            attachmentLayout.setVisibility(View.GONE);
        }
    });
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (recyclerDetailConversationAdapter != null) {
                recyclerDetailConversationAdapter.contactImageLoader.setPauseWork(newState == RecyclerView.SCROLL_STATE_DRAGGING);
            }
        }

        @Override
        public void onScrolled(final RecyclerView recyclerView, int dx, int dy) {
            // super.onScrolled(recyclerView, dx, dy);
            if (loadMore) {
                int topRowVerticalPosition = (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                swipeLayout.setEnabled(topRowVerticalPosition >= 0);
            }
        }
    });
    toolbar.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (channel != null) {
                if (channel.isDeleted()) {
                    return;
                }
                if (alCustomizationSettings.isGroupInfoScreenVisible() && !Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType()) && !Channel.GroupType.OPEN.getValue().equals(channel.getType())) {
                    Intent channelInfo = new Intent(getActivity(), ChannelInfoActivity.class);
                    channelInfo.putExtra(ChannelInfoActivity.CHANNEL_KEY, channel.getKey());
                    startActivity(channelInfo);
                } else if (Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType()) && alCustomizationSettings.isUserProfileFragment()) {
                    UserProfileFragment userProfileFragment = (UserProfileFragment) UIService.getFragmentByTag(getActivity(), ConversationUIService.USER_PROFILE_FRAMENT);
                    if (userProfileFragment == null) {
                        String userId = ChannelService.getInstance(getActivity()).getGroupOfTwoReceiverUserId(channel.getKey());
                        if (!TextUtils.isEmpty(userId)) {
                            Contact newcContact = appContactService.getContactById(userId);
                            userProfileFragment = new UserProfileFragment();
                            Bundle bundle = new Bundle();
                            bundle.putSerializable(ConversationUIService.CONTACT, newcContact);
                            userProfileFragment.setArguments(bundle);
                            ConversationActivity.addFragment(getActivity(), userProfileFragment, ConversationUIService.USER_PROFILE_FRAMENT);
                        }
                    }
                }
            } else {
                if (alCustomizationSettings.isUserProfileFragment()) {
                    UserProfileFragment userProfileFragment = (UserProfileFragment) UIService.getFragmentByTag(getActivity(), ConversationUIService.USER_PROFILE_FRAMENT);
                    if (userProfileFragment == null) {
                        userProfileFragment = new UserProfileFragment();
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(ConversationUIService.CONTACT, contact);
                        userProfileFragment.setArguments(bundle);
                        ConversationActivity.addFragment(getActivity(), userProfileFragment, ConversationUIService.USER_PROFILE_FRAMENT);
                    }
                }
            }
        }
    });
    recyclerView.setLongClickable(true);
    // Adding fragment for emoticons...
    // //Fragment emojiFragment = new EmojiconsFragment(this, this);
    // Fragment emojiFragment = new EmojiconsFragment();
    // FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
    // transaction.add(R.id.emojicons_frame_layout, emojiFragment).commit();
    messageTemplate = alCustomizationSettings.getMessageTemplate();
    if (messageTemplate != null && messageTemplate.isEnabled()) {
        templateAdapter = new MobicomMessageTemplateAdapter(messageTemplate);
        MobicomMessageTemplateAdapter.MessageTemplateDataListener listener = new MobicomMessageTemplateAdapter.MessageTemplateDataListener() {

            @Override
            public void onItemSelected(String message) {
                final Message lastMessage = !messageList.isEmpty() ? messageList.get(messageList.size() - 1) : null;
                if ((messageTemplate.getTextMessageList() != null && !messageTemplate.getTextMessageList().getMessageList().isEmpty() && messageTemplate.getTextMessageList().isSendMessageOnClick() && "text".equals(getMessageType(lastMessage))) || (messageTemplate.getImageMessageList() != null && !messageTemplate.getImageMessageList().getMessageList().isEmpty() && messageTemplate.getImageMessageList().isSendMessageOnClick() && "image".equals(getMessageType(lastMessage))) || (messageTemplate.getVideoMessageList() != null && !messageTemplate.getVideoMessageList().getMessageList().isEmpty() && messageTemplate.getVideoMessageList().isSendMessageOnClick() && "video".equals(getMessageType(lastMessage))) || (messageTemplate.getLocationMessageList() != null && !messageTemplate.getLocationMessageList().getMessageList().isEmpty() && messageTemplate.getLocationMessageList().isSendMessageOnClick() && "location".equals(getMessageType(lastMessage))) || (messageTemplate.getContactMessageList() != null && !messageTemplate.getContactMessageList().getMessageList().isEmpty() && messageTemplate.getContactMessageList().isSendMessageOnClick() && "contact".equals(getMessageType(lastMessage))) || (messageTemplate.getAudioMessageList() != null && !messageTemplate.getAudioMessageList().getMessageList().isEmpty() && messageTemplate.getAudioMessageList().isSendMessageOnClick() && "audio".equals(getMessageType(lastMessage))) || messageTemplate.getSendMessageOnClick()) {
                    sendMessage(message);
                }
                if (messageTemplate.getHideOnSend()) {
                    AlMessageMetadataUpdateTask.MessageMetadataListener listener1 = new AlMessageMetadataUpdateTask.MessageMetadataListener() {

                        @Override
                        public void onSuccess(Context context, String message) {
                            templateAdapter.setMessageList(new HashMap<String, String>());
                            templateAdapter.notifyDataSetChanged();
                        }

                        @Override
                        public void onFailure(Context context, String error) {
                        }
                    };
                    if (lastMessage != null) {
                        Map<String, String> metadata = lastMessage.getMetadata();
                        metadata.put("isDoneWithClicking", "true");
                        lastMessage.setMetadata(metadata);
                        new AlMessageMetadataUpdateTask(getContext(), lastMessage.getKeyString(), lastMessage.getMetadata(), listener1).execute();
                    }
                }
                final Intent intent = new Intent();
                intent.setAction("com.applozic.mobicomkit.TemplateMessage");
                intent.putExtra("templateMessage", message);
                intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
                getActivity().sendBroadcast(intent);
            }
        };
        templateAdapter.setOnItemSelected(listener);
        LinearLayoutManager horizontalLayoutManagaer = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        messageTemplateView.setLayoutManager(horizontalLayoutManagaer);
        messageTemplateView.setAdapter(templateAdapter);
    }
    createTemplateMessages();
    return list;
}
Also used : Configuration(android.content.res.Configuration) ViewConfiguration(android.view.ViewConfiguration) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) AlMessageMetadataUpdateTask(com.applozic.mobicomkit.uiwidgets.async.AlMessageMetadataUpdateTask) ChannelInfoActivity(com.applozic.mobicomkit.uiwidgets.conversation.activity.ChannelInfoActivity) ImageView(android.widget.ImageView) ConversationActivity(com.applozic.mobicomkit.uiwidgets.conversation.activity.ConversationActivity) ApplozicMqttIntentService(com.applozic.mobicomkit.api.conversation.ApplozicMqttIntentService) GradientDrawable(android.graphics.drawable.GradientDrawable) AdapterView(android.widget.AdapterView) Message(com.applozic.mobicomkit.api.conversation.Message) Conversation(com.applozic.mobicommons.people.channel.Conversation) KeyEvent(android.view.KeyEvent) ImageButton(android.widget.ImageButton) RecyclerViewPositionHelper(com.applozic.mobicomkit.uiwidgets.conversation.activity.RecyclerViewPositionHelper) ConversationScheduler(com.applozic.mobicomkit.uiwidgets.schedule.ConversationScheduler) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) Context(android.content.Context) Bundle(android.os.Bundle) CountDownTimer(android.os.CountDownTimer) UserProfileFragment(com.applozic.mobicomkit.uiwidgets.people.fragment.UserProfileFragment) Intent(android.content.Intent) ImageView(android.widget.ImageView) RecyclerView(android.support.v7.widget.RecyclerView) GridView(android.widget.GridView) View(android.view.View) ApplozicDocumentView(com.applozic.mobicomkit.uiwidgets.attachmentview.ApplozicDocumentView) AdapterView(android.widget.AdapterView) TextView(android.widget.TextView) AttachmentView(com.applozic.mobicomkit.api.attachment.AttachmentView) GestureDetectorCompat(android.support.v4.view.GestureDetectorCompat) Collections.disjoint(java.util.Collections.disjoint) MotionEvent(android.view.MotionEvent) Contact(com.applozic.mobicommons.people.contact.Contact) FrameLayout(android.widget.FrameLayout) RecyclerView(android.support.v7.widget.RecyclerView) MobicomMessageTemplateAdapter(com.applozic.mobicomkit.uiwidgets.conversation.adapter.MobicomMessageTemplateAdapter)

Example 4 with Conversation

use of com.applozic.mobicommons.people.channel.Conversation in project Applozic-Android-SDK by AppLozic.

the class MobiComConversationService method getMessages.

public synchronized List<Message> getMessages(Long startTime, Long endTime, Contact contact, Channel channel, Integer conversationId, boolean isSkipRead) {
    List<Message> messageList = new ArrayList<Message>();
    List<Message> cachedMessageList = messageDatabaseService.getMessages(startTime, endTime, contact, channel, conversationId);
    boolean isServerCallNotRequired = false;
    if (channel != null) {
        Channel newChannel = ChannelService.getInstance(context).getChannelByChannelKey(channel.getKey());
        isServerCallNotRequired = (newChannel != null && !Channel.GroupType.OPEN.getValue().equals(newChannel.getType()));
    } else if (contact != null) {
        isServerCallNotRequired = true;
    }
    if (isServerCallNotRequired && (!cachedMessageList.isEmpty() && (cachedMessageList.size() > 1 || wasServerCallDoneBefore(contact, channel, conversationId)) || (contact == null && channel == null && cachedMessageList.isEmpty() && wasServerCallDoneBefore(contact, channel, conversationId)))) {
        Utils.printLog(context, TAG, "cachedMessageList size is : " + cachedMessageList.size());
        return cachedMessageList;
    }
    String data;
    try {
        data = messageClientService.getMessages(contact, channel, startTime, endTime, conversationId, isSkipRead);
        Utils.printLog(context, TAG, "Received response from server for Messages: " + data);
    } catch (Exception ex) {
        ex.printStackTrace();
        return cachedMessageList;
    }
    if (data == null || TextUtils.isEmpty(data) || data.equals("UnAuthorized Access") || !data.contains("{")) {
        // Note: currently not supporting syncing old channel messages from server
        if (channel != null && channel.getKey() != null) {
            return cachedMessageList;
        }
        return cachedMessageList;
    }
    updateServerCallDoneStatus(contact, channel, conversationId);
    try {
        Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).setExclusionStrategies(new AnnotationExclusionStrategy()).create();
        JsonParser parser = new JsonParser();
        JSONObject jsonObject = new JSONObject(data);
        String channelFeedResponse = "";
        String conversationPxyResponse = "";
        String element = parser.parse(data).getAsJsonObject().get("message").toString();
        String userDetailsElement = parser.parse(data).getAsJsonObject().get("userDetails").toString();
        if (!TextUtils.isEmpty(userDetailsElement)) {
            UserDetail[] userDetails = (UserDetail[]) GsonUtils.getObjectFromJson(userDetailsElement, UserDetail[].class);
            processUserDetails(userDetails);
        }
        if (jsonObject.has("groupFeeds")) {
            channelFeedResponse = parser.parse(data).getAsJsonObject().get("groupFeeds").toString();
            ChannelFeed[] channelFeeds = (ChannelFeed[]) GsonUtils.getObjectFromJson(channelFeedResponse, ChannelFeed[].class);
            ChannelService.getInstance(context).processChannelFeedList(channelFeeds, false);
            if (channel != null && !isServerCallNotRequired) {
                BroadcastService.sendUpdate(context, BroadcastService.INTENT_ACTIONS.UPDATE_TITLE_SUBTITLE.toString());
            }
        }
        if (jsonObject.has("conversationPxys")) {
            conversationPxyResponse = parser.parse(data).getAsJsonObject().get("conversationPxys").toString();
            Conversation[] conversationPxy = (Conversation[]) GsonUtils.getObjectFromJson(conversationPxyResponse, Conversation[].class);
            ConversationService.getInstance(context).processConversationArray(conversationPxy, channel, contact);
        }
        Message[] messages = gson.fromJson(element, Message[].class);
        MobiComUserPreference userPreferences = MobiComUserPreference.getInstance(context);
        if (messages != null && messages.length > 0 && cachedMessageList.size() > 0 && cachedMessageList.get(0).isLocalMessage()) {
            if (cachedMessageList.get(0).equals(messages[0])) {
                Utils.printLog(context, TAG, "Both messages are same.");
                deleteMessage(cachedMessageList.get(0));
            }
        }
        for (Message message : messages) {
            if (!message.isCall() || userPreferences.isDisplayCallRecordEnable()) {
                // we have to figure out if it is a parsing problem or response from server.
                if (message.getTo() == null) {
                    continue;
                }
                if (message.hasAttachment() && !(message.getContentType() == Message.ContentType.TEXT_URL.getValue())) {
                    setFilePathifExist(message);
                }
                if (message.getContentType() == Message.ContentType.CONTACT_MSG.getValue()) {
                    FileClientService fileClientService = new FileClientService(context);
                    fileClientService.loadContactsvCard(message);
                }
                if (Message.MetaDataType.HIDDEN.getValue().equals(message.getMetaDataValueForKey(Message.MetaDataType.KEY.getValue())) || Message.MetaDataType.PUSHNOTIFICATION.getValue().equals(message.getMetaDataValueForKey(Message.MetaDataType.KEY.getValue()))) {
                    continue;
                }
                if (messageDatabaseService.isMessagePresent(message.getKeyString(), Message.ReplyMessage.HIDE_MESSAGE.getValue())) {
                    messageDatabaseService.updateMessageReplyType(message.getKeyString(), Message.ReplyMessage.NON_HIDDEN.getValue());
                } else {
                    if (isServerCallNotRequired || contact == null && channel == null) {
                        messageDatabaseService.createMessage(message);
                    }
                }
                if (contact == null && channel == null) {
                    if (message.isHidden()) {
                        if (message.getGroupId() != null) {
                            Channel newChannel = ChannelService.getInstance(context).getChannelByChannelKey(message.getGroupId());
                            if (newChannel != null) {
                                getMessages(null, null, null, newChannel, null, true);
                            }
                        } else {
                            getMessages(null, null, new Contact(message.getContactIds()), null, null, true);
                        }
                    }
                }
            }
            if (!isServerCallNotRequired) {
                messageList.add(message);
            }
        }
        if (contact == null && channel == null) {
            Intent intent = new Intent(MobiComKitConstants.APPLOZIC_UNREAD_COUNT);
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    /*   messageList.removeAll(cachedMessageList);
        messageList.addAll(cachedMessageList);

        Collections.sort(messageList, new Comparator<Message>() {
            @Override
            public int compare(Message lhs, Message rhs) {
                return lhs.getCreatedAtTime().compareTo(rhs.getCreatedAtTime());
            }
        });*/
    List<Message> finalMessageList = messageDatabaseService.getMessages(startTime, endTime, contact, channel, conversationId);
    List<String> messageKeys = new ArrayList<>();
    for (Message msg : finalMessageList) {
        if (msg.getTo() == null) {
            continue;
        }
        if (Message.MetaDataType.HIDDEN.getValue().equals(msg.getMetaDataValueForKey(Message.MetaDataType.KEY.getValue())) || Message.MetaDataType.PUSHNOTIFICATION.getValue().equals(msg.getMetaDataValueForKey(Message.MetaDataType.KEY.getValue()))) {
            continue;
        }
        if (msg.getMetadata() != null && msg.getMetaDataValueForKey(Message.MetaDataType.AL_REPLY.getValue()) != null && !messageDatabaseService.isMessagePresent(msg.getMetaDataValueForKey(Message.MetaDataType.AL_REPLY.getValue()))) {
            messageKeys.add(msg.getMetaDataValueForKey(Message.MetaDataType.AL_REPLY.getValue()));
        }
    }
    if (messageKeys != null && messageKeys.size() > 0) {
        Message[] replyMessageList = getMessageListByKeyList(messageKeys);
        if (replyMessageList != null) {
            for (Message replyMessage : replyMessageList) {
                if (replyMessage.getTo() == null) {
                    continue;
                }
                if (Message.MetaDataType.HIDDEN.getValue().equals(replyMessage.getMetaDataValueForKey(Message.MetaDataType.KEY.getValue())) || Message.MetaDataType.PUSHNOTIFICATION.getValue().equals(replyMessage.getMetaDataValueForKey(Message.MetaDataType.KEY.getValue()))) {
                    continue;
                }
                if (replyMessage.hasAttachment() && !(replyMessage.getContentType() == Message.ContentType.TEXT_URL.getValue())) {
                    setFilePathifExist(replyMessage);
                }
                if (replyMessage.getContentType() == Message.ContentType.CONTACT_MSG.getValue()) {
                    FileClientService fileClientService = new FileClientService(context);
                    fileClientService.loadContactsvCard(replyMessage);
                }
                replyMessage.setReplyMessage(Message.ReplyMessage.HIDE_MESSAGE.getValue());
                if (isServerCallNotRequired || contact == null && channel == null) {
                    messageDatabaseService.createMessage(replyMessage);
                }
            }
        }
    }
    if (messageList != null && !messageList.isEmpty()) {
        Collections.sort(messageList, new Comparator<Message>() {

            @Override
            public int compare(Message lhs, Message rhs) {
                return lhs.getCreatedAtTime().compareTo(rhs.getCreatedAtTime());
            }
        });
    }
    return channel != null && Channel.GroupType.OPEN.getValue().equals(channel.getType()) ? messageList : finalMessageList;
}
Also used : MobiComUserPreference(com.applozic.mobicomkit.api.account.user.MobiComUserPreference) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) Conversation(com.applozic.mobicommons.people.channel.Conversation) UserDetail(com.applozic.mobicomkit.api.account.user.UserDetail) AnnotationExclusionStrategy(com.applozic.mobicommons.json.AnnotationExclusionStrategy) ChannelFeed(com.applozic.mobicomkit.feed.ChannelFeed) JsonParser(com.google.gson.JsonParser) GsonBuilder(com.google.gson.GsonBuilder) Channel(com.applozic.mobicommons.people.channel.Channel) FileClientService(com.applozic.mobicomkit.api.attachment.FileClientService) Intent(android.content.Intent) JSONException(org.json.JSONException) ApplozicException(com.applozic.mobicomkit.exception.ApplozicException) Contact(com.applozic.mobicommons.people.contact.Contact) ArrayAdapterFactory(com.applozic.mobicommons.json.ArrayAdapterFactory) JSONObject(org.json.JSONObject)

Example 5 with Conversation

use of com.applozic.mobicommons.people.channel.Conversation in project Applozic-Android-SDK by AppLozic.

the class ConversationDatabaseService method getConversationByTopicId.

public Conversation getConversationByTopicId(final String topicId, Context context) {
    if (TextUtils.isEmpty(topicId)) {
        return null;
    }
    Conversation conversation = null;
    SQLiteDatabase database = MobiComDatabaseHelper.getInstance(context).getReadableDatabase();
    String conversationParameters = "";
    List<String> structuredNameParamsList = new ArrayList<>();
    conversationParameters += MobiComDatabaseHelper.TOPIC_ID + "= ? ";
    structuredNameParamsList.add(topicId);
    Cursor cursor = database.query(MobiComDatabaseHelper.CONVERSATION, null, conversationParameters, structuredNameParamsList.toArray(new String[structuredNameParamsList.size()]), null, null, null);
    if (cursor.moveToFirst()) {
        conversation = getConversation(cursor);
    }
    if (cursor != null) {
        cursor.close();
    }
    dbHelper.close();
    return conversation;
}
Also used : SQLiteDatabase(android.database.sqlite.SQLiteDatabase) ArrayList(java.util.ArrayList) Conversation(com.applozic.mobicommons.people.channel.Conversation) Cursor(android.database.Cursor)

Aggregations

Conversation (com.applozic.mobicommons.people.channel.Conversation)12 ArrayList (java.util.ArrayList)5 Intent (android.content.Intent)4 Cursor (android.database.Cursor)4 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)4 Context (android.content.Context)2 TopicDetail (com.applozic.mobicomkit.feed.TopicDetail)2 Contact (com.applozic.mobicommons.people.contact.Contact)2 Configuration (android.content.res.Configuration)1 GradientDrawable (android.graphics.drawable.GradientDrawable)1 Bundle (android.os.Bundle)1 CountDownTimer (android.os.CountDownTimer)1 GestureDetectorCompat (android.support.v4.view.GestureDetectorCompat)1 LinearLayoutManager (android.support.v7.widget.LinearLayoutManager)1 RecyclerView (android.support.v7.widget.RecyclerView)1 Editable (android.text.Editable)1 TextWatcher (android.text.TextWatcher)1 KeyEvent (android.view.KeyEvent)1 MotionEvent (android.view.MotionEvent)1 View (android.view.View)1