Search in sources :

Example 1 with ChatMessageReceived

use of br.ufrj.caronae.models.ChatMessageReceived in project caronae-android by caronae.

the class MyFirebaseMessagingService method onMessageReceived.

@Override
public void onMessageReceived(final RemoteMessage remoteMessage) {
    Log.i("onMessageReceived", "onMessageReceived");
    if (App.isUserLoggedIn() && remoteMessage.getData() != null) {
        Map data = remoteMessage.getData();
        String msgType = (String) data.get("msgType");
        if (msgType != null && msgType.equals("alert")) {
            PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putString(MSG_TYPE_ALERT, (String) data.get(ALERT_KEY)).apply();
            PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putString(MSG_TYPE_ALERT_HEADER, (String) data.get(ALERT_HEADER_KEY)).commit();
        } else {
            String message = (String) data.get("message");
            String senderName = (String) data.get("senderName");
            final String rideId = (String) data.get("rideId");
            Log.i("onMessageReceived", message);
            if (msgType != null && msgType.equals("chat")) {
                String senderId = (String) data.get("senderId");
                // noinspection ConstantConditions
                if (senderId.equals(App.getUser().getDbId() + "")) {
                    return;
                }
                List<ChatMessageReceived> listOldMessages = ChatMessageReceived.find(ChatMessageReceived.class, "ride_id = ?", rideId);
                ChatMessageReceived lastMessage = null;
                if (listOldMessages.size() != 0) {
                    lastMessage = listOldMessages.get(listOldMessages.size() - 1);
                }
                String since;
                if (lastMessage == null) {
                    since = null;
                } else {
                    since = lastMessage.getTime();
                }
                if (!SharedPref.getChatActIsForeground()) {
                    startService(new Intent(this, FetchReceivedMessagesService.class).putExtra("rideId", rideId).putExtra("since", since));
                }
            }
            if (msgType != null && msgType.equals("joinRequest")) {
                new RideRequestReceived(Integer.valueOf(rideId)).save();
            }
            if (msgType != null && msgType.equals("finished")) {
                FirebaseTopicsHandler.unsubscribeFirebaseTopic(rideId);
                App.getBus().post(new RideEndedEvent(rideId));
                ActiveRide.deleteAll(ActiveRide.class, "db_id = ?", rideId);
            }
            // TODO: Carona cancelada Nao esta rebendo notificacao
            if (msgType != null && msgType.equals("cancelled")) {
                FirebaseTopicsHandler.unsubscribeFirebaseTopic(rideId);
                App.getBus().post(new RideEndedEvent(rideId));
                ActiveRide.deleteAll(ActiveRide.class, "db_id = ?", rideId);
            }
            if (msgType != null && msgType.equals("accepted")) {
                FirebaseTopicsHandler.CheckSubFirebaseTopic(rideId);
            // new DeleteConflictingRequests().execute(rideId);
            }
            if (SharedPref.getNotifPref().equals("true"))
                if (msgType != null && msgType.equals("chat")) {
                    if (!SharedPref.getChatActIsForeground()) {
                        createNotification(msgType, senderName, message, rideId);
                    } else {
                        App.getBus().post(rideId);
                    }
                } else
                    createNotification(msgType, senderName, message, rideId);
        }
    }
}
Also used : ChatMessageReceived(br.ufrj.caronae.models.ChatMessageReceived) RideEndedEvent(br.ufrj.caronae.models.RideEndedEvent) RideRequestReceived(br.ufrj.caronae.models.RideRequestReceived) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) Map(java.util.Map)

Example 2 with ChatMessageReceived

use of br.ufrj.caronae.models.ChatMessageReceived in project caronae-android by caronae.

the class ChatMsgsAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    ChatMessageReceived msg = chatMsgsList.get(position);
    if (holder.getItemViewType() == 0) {
        ViewHolderRight viewHolderRight = (ViewHolderRight) holder;
        viewHolderRight.msg_tv.setText(msg.getMessage());
        String time = "";
        try {
            time = msg.getTime().split(" ")[1].substring(0, 5);
        } catch (Exception e) {
            Log.e("ChatMsgsAdapter", e.getMessage());
        }
        viewHolderRight.time_tv.setText(time);
    } else {
        ViewHolderLeft viewHolderLeft = (ViewHolderLeft) holder;
        viewHolderLeft.msg_tv.setText(msg.getMessage());
        String time = "";
        try {
            time = msg.getTime().split(" ")[1].substring(0, 5);
        } catch (Exception e) {
            Log.e("ChatMsgsAdapter", e.getMessage());
        }
        viewHolderLeft.time_tv.setText(time);
        viewHolderLeft.sender_name_tv.setText(msg.getSenderName());
        viewHolderLeft.sender_name_tv.setTextColor(color);
    }
}
Also used : ChatMessageReceived(br.ufrj.caronae.models.ChatMessageReceived)

Example 3 with ChatMessageReceived

use of br.ufrj.caronae.models.ChatMessageReceived in project caronae-android by caronae.

the class ChatAct method sendBt.

@OnClick(R.id.send_bt)
public void sendBt() {
    final String message = msg_et.getText().toString();
    msg_et.setText("");
    if (message.isEmpty())
        return;
    String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(new Date());
    final ChatMessageReceived msg = new ChatMessageReceived(App.getUser().getName(), App.getUser().getDbId() + "", message, rideId, time);
    msg.setId((long) -1);
    chatMsgsList.add(msg);
    final ChatMsgsAdapter adapter = (ChatMsgsAdapter) chatMsgs_rv.getAdapter();
    adapter.notifyItemInserted(chatMsgsList.size() - 1);
    chatMsgs_rv.scrollToPosition(chatMsgsList.size() - 1);
    CaronaeAPI.service(getApplicationContext()).sendChatMsg(rideId, new ChatSendMessageForJson(message)).enqueue(new Callback<ChatMessageSendResponse>() {

        @Override
        public void onResponse(Call<ChatMessageSendResponse> call, Response<ChatMessageSendResponse> response) {
            if (response.isSuccessful()) {
                ChatMessageSendResponse chatMessageSendResponse = response.body();
                Log.i("Message Sent", "Sulcefully Send Chat Messages");
                msg.setId(Long.parseLong(chatMessageSendResponse.getMessageId()));
                chatMsgsList.get(getMessagePositionWithId(chatMsgsList, msg.getId())).setId(Long.parseLong(chatMessageSendResponse.getMessageId()));
                msg.save();
            } else {
                Util.treatResponseFromServer(response);
                Util.toast("Erro ao enviar mensagem de chat, verifique sua conexao");
                chatMsgsList.remove(chatMsgsList.size() - 1);
                chatMsgsAdapter.notifyItemRemoved(chatMsgsList.size());
                msg_et.setText(msg.getMessage());
                /**
                 *********** Esconde o teclado **********
                 */
                View view = ChatAct.this.getCurrentFocus();
                if (view != null) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
                /**
                 ******
                 */
                Log.e("SendMessages", response.message());
            }
        }

        @Override
        public void onFailure(Call<ChatMessageSendResponse> call, Throwable t) {
            Util.toast("Erro ao enviar mensagem de chat, verifique sua conexao");
            if (chatMsgsList.size() > 0) {
                chatMsgsList.remove(chatMsgsList.size() - 1);
                chatMsgsAdapter.notifyItemRemoved(chatMsgsList.size());
                msg_et.setText(msg.getMessage());
            }
            /**
             *********** Esconde o teclado **********
             */
            View view = ChatAct.this.getCurrentFocus();
            if (view != null) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
            /**
             ******
             */
            Log.e("SendMessages", t.getMessage());
        }
    });
}
Also used : ChatMsgsAdapter(br.ufrj.caronae.adapters.ChatMsgsAdapter) ChatSendMessageForJson(br.ufrj.caronae.models.modelsforjson.ChatSendMessageForJson) ChatMessageSendResponse(br.ufrj.caronae.models.ChatMessageSendResponse) ChatMessageReceived(br.ufrj.caronae.models.ChatMessageReceived) InputMethodManager(android.view.inputmethod.InputMethodManager) BindView(butterknife.BindView) View(android.view.View) CardView(android.support.v7.widget.CardView) TextView(android.widget.TextView) RecyclerView(android.support.v7.widget.RecyclerView) Date(java.util.Date) SimpleDateFormat(java.text.SimpleDateFormat) OnClick(butterknife.OnClick)

Example 4 with ChatMessageReceived

use of br.ufrj.caronae.models.ChatMessageReceived in project caronae-android by caronae.

the class FetchReceivedMessagesService method onHandleIntent.

@Override
protected void onHandleIntent(Intent intent) {
    rideId = intent.getStringExtra("rideId");
    String since = intent.getStringExtra("since");
    CaronaeAPI.service(getApplicationContext()).requestChatMsgs(rideId, since).enqueue(new Callback<ModelReceivedFromChat>() {

        @Override
        public void onResponse(Call<ModelReceivedFromChat> call, Response<ModelReceivedFromChat> response) {
            if (response.isSuccessful()) {
                ModelReceivedFromChat chatMessagesReceived = response.body();
                if (chatMessagesReceived != null && chatMessagesReceived.getMessages().size() != 0) {
                    final List<ChatMessageReceived> messagesFetched = new ArrayList<>();
                    List<ChatMessageReceivedFromJson> listMessages = chatMessagesReceived.getMessages();
                    for (int mensagesNum = 0; mensagesNum < listMessages.size(); mensagesNum++) {
                        ChatMessageReceived cmr = new ChatMessageReceived(listMessages.get(mensagesNum).getUser().getName(), String.valueOf(listMessages.get(mensagesNum).getUser().getId()), listMessages.get(mensagesNum).getMessage(), rideId, listMessages.get(mensagesNum).getTime());
                        cmr.setId(Long.parseLong(listMessages.get(mensagesNum).getMessageId()));
                        messagesFetched.add(cmr);
                    }
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            for (int messageIndex = 0; messageIndex < messagesFetched.size(); messageIndex++) {
                                if (!messageAlrealdyExist(messagesFetched.get(messageIndex).getId())) {
                                    messagesFetched.get(messageIndex).save();
                                }
                            }
                            if (SharedPref.getChatActIsForeground()) {
                                App.getBus().post(messagesFetched.get(0));
                            }
                        }
                    }).start();
                } else {
                    ChatMessageReceived cmr = new ChatMessageReceived();
                    if (SharedPref.getChatActIsForeground()) {
                        App.getBus().post(cmr);
                    }
                    getApplicationContext().sendBroadcast(new Intent("br.ufrj.caronae.acts.ChatAct.BROADCAST_NEW_MESSAGES_NULL"));
                }
            } else {
                Util.treatResponseFromServer(response);
                Util.toast("Erro ao Recuperar mensagem de chat");
                Log.e("GetMessages", response.message());
            }
        }

        @Override
        public void onFailure(Call<ModelReceivedFromChat> call, Throwable t) {
            Util.toast("Erro ao Recuperar mensagem de chat");
            Log.e("GetMessages", t.getMessage());
        }
    });
}
Also used : ChatMessageReceived(br.ufrj.caronae.models.ChatMessageReceived) Intent(android.content.Intent) ArrayList(java.util.ArrayList) List(java.util.List) ModelReceivedFromChat(br.ufrj.caronae.models.ModelReceivedFromChat)

Aggregations

ChatMessageReceived (br.ufrj.caronae.models.ChatMessageReceived)4 Intent (android.content.Intent)2 PendingIntent (android.app.PendingIntent)1 CardView (android.support.v7.widget.CardView)1 RecyclerView (android.support.v7.widget.RecyclerView)1 View (android.view.View)1 InputMethodManager (android.view.inputmethod.InputMethodManager)1 TextView (android.widget.TextView)1 ChatMsgsAdapter (br.ufrj.caronae.adapters.ChatMsgsAdapter)1 ChatMessageSendResponse (br.ufrj.caronae.models.ChatMessageSendResponse)1 ModelReceivedFromChat (br.ufrj.caronae.models.ModelReceivedFromChat)1 RideEndedEvent (br.ufrj.caronae.models.RideEndedEvent)1 RideRequestReceived (br.ufrj.caronae.models.RideRequestReceived)1 ChatSendMessageForJson (br.ufrj.caronae.models.modelsforjson.ChatSendMessageForJson)1 BindView (butterknife.BindView)1 OnClick (butterknife.OnClick)1 SimpleDateFormat (java.text.SimpleDateFormat)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 List (java.util.List)1